0% found this document useful (0 votes)
10 views

Java 1 Intro, Variable Datetype Oper

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Java 1 Intro, Variable Datetype Oper

Uploaded by

amaleshmsc
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 22

Java

Class – reserved keyword. We cannot use this word in the { }.


Object oriented – class object {} every class will overwrite the main object class.

Variable declaration, method definition.

Stack, heap, class (static values). Background storage.

1.What is java? (history)


Java is a programming language and a platform. Java is a high level, robust,
object-oriented and secure programming language.

Java was developed by Sun Microsystems in the year 1995. James Gosling is
known as the father of Java. Before Java, its name was Oak. Since Oak was already
a registered company, so James Gosling and his team changed the name from Oak
to Java.

Platform: Any hardware or software environment in which a program runs, is known


as a platform. Since Java has a runtime environment (JRE) and API, it is called a
platform.

Types of Java Applications


There are mainly 4 types of applications that can be created using Java
programming:

Standalone Application

Web Application.

Enterprise Application (banking applications, etc.)

Mobile Application (Currently, Android and Java ME are used for creating
mobile applications.

C++ vs java:
Java doesn't support default arguments like C++.
Java does not support header files like C++. Java uses the
import keyword to include different classes and methods.

Comparison C++ Java


Index

Platform- C++ is platform- Java is platform-


independent dependent. independent.

Mainly used C++ is mainly used Java is mainly used for


for for system application
programming. programming. It is
widely used in
Windows-based, web-
based, enterprise, and
mobile applications.

Design Goal C++ was designed for Java was designed and
systems and created as an
applications interpreter for printing
programming. It was systems but later
an extension of the C extended as a support
programming network computing. It
language. was designed to be
easy to use and
accessible to a broader
audience.

Goto C++ supports Java doesn't support


the goto statement. the goto statement.

Multiple C++ supports multiple Java doesn't support


inheritance inheritance. multiple inheritance
through class. It can be
achieved by
using interfaces in java.
Operator C++ Java doesn't support
Overloading supports operator operator overloading.
overloading.

Pointers C++ Java supports pointer


supports pointers. You internally. However,
can write a pointer you can't write the
program in C++. pointer program in java.
It means java has
restricted pointer
support in java.

Hardware C++ is nearer to Java is not so


hardware. interactive with
hardware.

Documentati C++ doesn't support Java supports


on comment documentation documentation
comments. comment (/** ... */) to
create documentation
for java source code.

2. Features of Java
Simple - Java is very easy to learn, and its syntax is simple, clean and easy to
understand.

Java syntax is based on C++ (so easier for programmers to learn it after C+
+).

Java has removed many complicated and rarely-used features, for example,
explicit pointers, operator overloading, etc.

Object-Oriented - Everything in Java is an object. Object-oriented means we


organize our software as a combination of different types of objects that incorporate
both data and behavior.
Portable - Java is portable because it facilitates you to carry the Java bytecode to
any platform.

Platform independent -
If any language code written on 1 operating system and run it on that same OS, After that
same code copy and execute on another Operating System, If that copied code not execute
on another OS then that language code is called as PLATFORM DEPENDENT code. Java
compiler javac converts the program code into byte code. This byte code
is platform-independent and can run on any JVM operating system. JVM
interprets the byte code to machine code, and the program is executed.

Secured – because there no pointers, we have used sand box alternatively to store
the data.

Robust - strong

Architecture neutral - In C programming, int data type occupies 2 bytes of memory


for 32-bit architecture and 4 bytes of memory for 64-bit architecture. However, it
occupies 4 bytes of memory for both 32 and 64-bit architectures in Java.

Interpreted(clearly explained)

High Performance

Multithreaded - The main advantage of multi-threading is that it doesn't occupy


memory for each thread. It shares a common memory area.

Distributed - Java is distributed because it facilitates users to create distributed


applications in Java. RMI and EJB are used for creating distributed applications.

Dynamic - Java is a dynamic language. It supports the dynamic loading of classes. It


means classes are loaded on demand. It also supports functions from its native
languages, i.e., C and C++.

Download
Install the JDK if you don't have installed it, download the JDK and install it.

Set path of the jdk/bin directory. http://www.javatpoint.com/how-to-set-path-in-java


Create the Java program

Compile and run the Java program

How to set the Temporary Path of JDK in


Windows
To set the temporary path of JDK, you need to follow the following steps:

Open the command prompt

Copy the path of the JDK/bin directory

Write in command prompt: set path=copied_path

For Example:
set path=C:\Program Files\Java\jdk1.6.0_23\bin

2) How to set Permanent Path of JDK in Windows


For setting the permanent path of JDK, you need to follow these steps:

Go to MyComputer properties -> advanced tab -> environment variables -> new tab
of user variable -> write path in variable name -> write path of bin folder in variable
value -> ok -> ok -> ok

To javac
compile: Simple.java
To
java Simple
execute:
class Simple
{
public static void main(String args[])
{
System.out.println("Hello Java");
}
}
class keyword is used to declare a class in Java.

public keyword is an access modifier that represents visibility. It means it is visible


to all.

static is a keyword. If we declare any method as static, it is known as the static


method. The core advantage of the static method is that there is no need to create
an object to invoke the static method. The main() method is executed by the JVM, so
it doesn't require creating an object to invoke the main() method. So, it saves
memory.

void is the return type of the method. It means it doesn't return any value.

main represents the starting point of the program.

String[] args or String args[] is used for command line argument. We will discuss it
in coming section.

System.out.println() is used to print statement. Here, System is a class, out is an


object of the PrintStream class, println() is a method of the PrintStream class.

3. JVM, JRE, JDK:


JVM (Java Virtual Machine) is an abstract machine. It is called a
virtual machine because it doesn't physically exist. It is a specification
that provides a runtime environment in which Java bytecode can be
executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.

JRE is an acronym for Java Runtime Environment. It is also written


as Java RTE. The Java Runtime Environment is a set of software
tools which are used for developing Java applications. It is used to
provide the runtime environment. It is the implementation of JVM. It
physically exists. It contains a set of libraries + other files that JVM
uses at runtime.

The Java Development Kit (JDK) is a software development


environment which is used to develop Java applications and applets.
It physically exists. It contains JRE + development tools.
The JVM performs following operation:

Loads code

Verifies code

Executes code

Provides runtime environment

4.Java Variables
A variable is a container which holds the value while the Java program is executed.

A variable is assigned with a data type. Variable is a name of memory location.

There are three types of variables in java: local, instance and static.

1.Local Variable

A variable declared inside the body of the method is called local variable. You can
use this variable only within that method. A local variable cannot be defined with
"static" keyword.
2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an
instance variable. It is not declared as static.

A variable which is created inside the class but outside the method is
known as an instance variable. Instance variable doesn't get memory at
compile time. It gets memory at runtime when an object or instance is
created. That is why it is known as an instance variable.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You
can create a single copy of the static variable and share it among all the instances of
the class. Memory allocation for static variables happens only once when the class
is loaded in the memory.

public class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
}
}//end of class

5. Data type:
Data types specify the different sizes and values that can be stored in the variable.
There are two types of data types in Java:

Primitive data types: The primitive data types include Boolean(true or


false), char(Default value for char=\uooo)), byte (Its minimum value is -128
and maximum value is 127. Its default value is 0.), short (Its minimum
value is -32,768 and maximum value is 32,767. Its default value is 0.),
int(. Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.), long Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0., float (The float data
type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited.)and double The double data type is a double-precision 64-bit
IEEE 754 floating point. Its value range is unlimited.

Non-primitive data types: Non-primitive data types are called reference


types because they refer to objects. The main difference
between primitive and non-primitive data types are:

Primitive types are predefined (already defined) in Java. Non-primitive types are
created by the programmer and is not defined by Java (except for String).

Non-primitive types can be used to call methods to perform certain operations, while
primitive types cannot.

A primitive type has always a value, while non-primitive types can be null.

A primitive type starts with a lowercase letter, while non-primitive types starts with an
uppercase letter.

Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc. You will
learn more about these in a later chapter.

Java Type Casting


Type casting is when you assign a value of one primitive data type to another type.

In Java, there are two types of casting:

Widening Casting
Widening Casting (automatically) - converting a smaller type to a larger type
sizebyte -> short -> char -> int -> long -> float -> double

Widening casting is done automatically when passing a smaller size type to a larger
size type:

public class Main {


public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);

System.out.println(myDouble);

Narrowing Casting
Narrowing Casting (manually) - converting a larger type to a smaller size type
double -> float -> long -> int -> char -> short -> byte

Narrowing casting must be done manually by placing the type in parentheses in front
of the value:

public class Main {

public static void main(String[] args) {

double myDouble = 9.78d;

int myInt = (int) myDouble; // Explicit casting: double to int

System.out.println(myDouble);

System.out.println(myInt);

6.Operators in Java
Operator Category Precedence
Type

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative */%

additive +-

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise ^
exclusive
OR

bitwise |
inclusive OR

Logical logical AND &&

logical OR ||

Ternary ternary ?:

Assignmen assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=


t

Unary operator: increment and decrement operator.


public class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
} } Output:
10
12
12
10

Java Unary Operator Example: ~ and !


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}

Arithmetic Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Shift
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right
by the number of bits specified by the right operand.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is
false. It checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true
or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b&a++<c);//false && true = false
System.out.println(a);//11 because second condition is checked
}}

Output

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |


The logical || operator doesn't check the second condition if the
first condition is true. It checks the second condition only if the
first one is false.

The bitwise | operator always checks both conditions whether


first condition is true or false.

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}

Output:
true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-
then-else statement and used a lot in Java programming. It is
the only conditional operator which takes three operands.

Java Ternary Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:
2

condition true, It will do the 1st and if it false, do second.

Assignment Operator
Java assignment operator is one of the most common operators. It is used to assign
the value on its right to the operand on its left.
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}

Java Assignment Operator Example: Adding short


public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}

Output:
Compile time error

7.List of Java Keywords


A list of Java keywords or reserved words are given below:

abstract: Java abstract keyword is used to declare an abstract class. An abstract


class can provide the implementation of the interface. It can have abstract and non-
abstract methods.
boolean: Java boolean keyword is used to declare a variable as a boolean type. It
can hold True and False values only.

break: Java break keyword is used to break the loop or switch statement. It breaks
the current flow of the program at specified conditions.

byte: Java byte keyword is used to declare a variable that can hold 8-bit data
values.

case: Java case keyword is used with the switch statements to mark blocks of text.

catch: Java catch keyword is used to catch the exceptions generated by try
statements. It must be used after the try block only.

char: Java char keyword is used to declare a variable that can hold unsigned 16-bit
Unicode characters

class: Java class keyword is used to declare a class.

continue: Java continue keyword is used to continue the loop. It continues the
current flow of the program and skips the remaining code at the specified condition.

default: Java default keyword is used to specify the default block of code in a switch
statement.

do: Java do keyword is used in the control statement to declare a loop. It can iterate
a part of the program several times.

double: Java double keyword is used to declare a variable that can hold 64-bit
floating-point number.

else: Java else keyword is used to indicate the alternative branches in an if


statement.

enum: Java enum keyword is used to define a fixed set of constants. Enum
constructors are always private or default.
extends: Java extends keyword is used to indicate that a class is derived from
another class or interface.

final: Java final keyword is used to indicate that a variable holds a constant value. It
is used with a variable. It is used to restrict the user from updating the value of the
variable.

finally: Java finally keyword indicates a block of code in a try-catch structure. This
block is always executed whether an exception is handled or not.

float: Java float keyword is used to declare a variable that can hold a 32-bit floating-
point number.

for: Java for keyword is used to start a for loop. It is used to execute a set of
instructions/functions repeatedly when some condition becomes true. If the number
of iteration is fixed, it is recommended to use for loop.

if: Java if keyword tests the condition. It executes the if block if the condition is true.

implements: Java implements keyword is used to implement an interface.

import: Java import keyword makes classes and interfaces available and accessible
to the current source code.

instanceof: Java instanceof keyword is used to test whether the object is an


instance of the specified class or implements an interface.

int: Java int keyword is used to declare a variable that can hold a 32-bit signed
integer.

interface: Java interface keyword is used to declare an interface. It can have only
abstract methods.

long: Java long keyword is used to declare a variable that can hold a 64-bit integer.

native: Java native keyword is used to specify that a method is implemented in


native code using JNI (Java Native Interface).
new: Java new keyword is used to create new objects.

null: Java null keyword is used to indicate that a reference does not refer to
anything. It removes the garbage value.

package: Java package keyword is used to declare a Java package that includes
the classes.

private: Java private keyword is an access modifier. It is used to indicate that a


method or variable may be accessed only in the class in which it is declared.

protected: Java protected keyword is an access modifier. It can be accessible


within the package and outside the package but through inheritance only. It can't be
applied with the class.

public: Java public keyword is an access modifier. It is used to indicate that an item
is accessible anywhere. It has the widest scope among all other modifiers.

return: Java return keyword is used to return from a method when its execution is
complete.

short: Java short keyword is used to declare a variable that can hold a 16-bit
integer.

static: Java static keyword is used to indicate that a variable or method is a class
method. The static keyword in Java is mainly used for memory management.

strictfp: Java strictfp is used to restrict the floating-point calculations to ensure


portability.

super: Java super keyword is a reference variable that is used to refer to parent
class objects. It can be used to invoke the immediate parent class method.

switch: The Java switch keyword contains a switch statement that executes code
based on test value. The switch statement tests the equality of a variable against
multiple values.
synchronized: Java synchronized keyword is used to specify the critical sections or
methods in multithreaded code.

this: Java this keyword can be used to refer the current object in a method or
constructor.

throw: The Java throw keyword is used to explicitly throw an exception. The throw
keyword is mainly used to throw custom exceptions. It is followed by an instance.

throws: The Java throws keyword is used to declare an exception. Checked


exceptions can be propagated with throws.

transient: Java transient keyword is used in serialization. If you define any data
member as transient, it will not be serialized.

try: Java try keyword is used to start a block of code that will be tested for
exceptions. The try block must be followed by either catch or finally block.

void: Java void keyword is used to specify that a method does not have a return
value.

volatile: Java volatile keyword is used to indicate that a variable may change
asynchronously.

while: Java while keyword is used to start a while loop. This loop iterates a part of
the program several times. If the number of iteration is not fixed, it is recommended
to use the while loop.

Input Types
In the example above, we used the nextLine() method, which is used to
read Strings. To read other types, look at the table below:

Method Description
nextBoolean( Reads a boolean value from the user
)

nextByte() Reads a byte value from the user

nextDouble() Reads a double value from the user

nextFloat() Reads a float value from the user

nextInt() Reads a int value from the user

nextLine() Reads a String value from the user

nextLong() Reads a long value from the user

nextShort() Reads a short value from the user

import java.util.Scanner; // Import the Scanner class

class Main {

public static void main(String[] args) {


Scanner myObj = new Scanner(System.in); // Create a Scanner
object

System.out.println("Enter username");

String userName = myObj.nextLine(); // Read user input

System.out.println("Username is: " + userName); // Output


user input

You might also like