Java Syntax
we created a Java file called [Link], and we used the following code to print
"Hello World" to the screen:
[Link]
public class Main {
public static void main(String[] args) {
[Link]("Hello World");
Example explained
Every line of code that runs in Java must be inside a class. In our example, we
named the class Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
The name of the java file must match the class name. When saving the file,
save it using the class name and add ".java" to the end of the filename. To run
the example above on your computer, make sure that Java is properly installed.
The output should be:
Hello World
The main Method
The main() method is required and you will see it in every Java program:
public static void main(String[] args)
Any code inside the main() method will be executed. Don't worry about the
keywords before and after main.
For now, just remember that every Java program has a class name which must
match the filename, and that every program must contain the main() method.
[Link]()
Inside the main() method, we can use the println() method to print a line of text to
the screen:
public static void main(String[] args) {
[Link]("Hello World");
Internal Details of Hello Java Program
we have created Java Hello World program and learn how to compile and run
a Java program. we are going to learn, what happens while we compile and
run the Java program. Moreover, we will see some questions based on the
first program.
What happens at compile time?
At compile time, the Java file is compiled by Java Compiler (It does not
interact with OS) and converts the Java code into bytecode.
What happens at runtime?
At runtime, the following steps are performed:
Classloader: It is the subsystem of JVM that is used to load class files.
Bytecode Verifier: Checks the code fragments for illegal code that can
violate access rights to objects.
Interpreter: Read bytecode stream then execute the instructions.
Q) Can you save a Java source file by another name than
the class name?
Yes, if the class is not public. It is explained in the figure given below:
To compile: javac [Link]
To execute: java Simple
Observe that, we have compiled the code with file name but running the
program with class name. Therefore, we can save a Java program other than
class name.
Q) Can you have multiple classes in a java source file?
Yes, like the figure given below illustrates:
Java Data Types
Example
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String
Data types are divided into two groups:
Primitive data types -
includes byte, short, int, long, float, double, boolean and char
Non-primitive data types - such as String, Arrays and Classes
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no
additional methods.
There are eight primitive data types in Java:
Data Size Description
Type
byte 1 byte Stores whole numbers from -128 to 127
short 2 bytes Stores whole numbers from -32,768 to 32,767
int 4 bytes Stores whole numbers from -2,147,483,648 to
2,147,483,647
long 8 bytes Stores whole numbers from -
9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
float 4 bytes Stores fractional numbers. Sufficient for storing 6 to 7
decimal digits
double 8 bytes Stores fractional numbers. Sufficient for storing 15
decimal digits
boolean 1 bit Stores true or false values
char 2 bytes Stores a single character/letter or ASCII values
Java 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.
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.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
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 and the other methods in
the class aren't even aware that the variable exists.
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.
It is called an instance variable because its value is instance-specific and is
not shared among instances.
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.
Example to understand the types of variables in java
public class A {
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
public static void main(String args[])
{
int data=50;//instance variable
}
}//end of class
Java Variable Example: Add Two Numbers
public class Simple{
public static void main(String[] args){
int a=10;
int b=10;
int c=a+b;
[Link](c);
}
}
Output:
20
Java Variable Example: Widening
public class Simple{
public static void main(String[ ] args){
int a=10;
float f=a;
[Link](a);
[Link](f);
}
}
Output:
10
10.0
Java Variable Example: Narrowing (Typecasting)
public class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f;//Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}
}
Output:
10.5
10
Java Variable Example: Overflow
class Simple{
public static void main(String[ ] args){
//Overflow
int a=130;
byte b=(byte)a;
[Link](a);
[Link](b);
}
}
Output:
130
-126
Java Variable Example: Adding Lower Type
class Simple{
public static void main(String[] args){
byte a=10;
byte b=10;
byte c=a+b;//Compile Time Error: because a+b=20 will be int
byte c=(byte)(a+b);
[Link](c);
}
}
Output:
20
Operators in Java
Operator in Java is a symbol that is used to perform operations. For
example: +, -, *, / etc.
There are many types of operators in Java which are given below:
o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.
Java Operator Precedence
Operator Type Category Precedence
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 ?:
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>=
>>>=
Java Unary Operator
The Java unary operators require only one operand. Unary operators are
used to perform various operations i.e.:
o incrementing/decrementing a value by one
o negating an expression
o inverting the value of a boolean
Java Unary Operator Example: ++ and --
public class OperatorExample{
public static void main(String args[]){
int x=10;
[Link](x++);//10 (11)
[Link](++x);//12
[Link](x--);//12 (11)
[Link](--x);//10
}
}
Output:
10
12
12
10
Java Unary Operator Example 2: ++ and --
public class OperatorExample{
public static void main(String args[ ]){
int a=10;
int b=10;
[Link](a++ + ++a);//10+12=22
[Link](b++ + b++);//10+11=21
}
}
Output:
22
21
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;
[Link](~a);//-11 (minus of total positive value which starts
from 0)
[Link](~b);//9 (positive of total minus, positive starts from
0)
[Link](!c);//false (opposite of boolean value)
[Link](!d);//true
}
}
Output:
-11
9
false
true
Java Arithmetic Operators
Java arithmetic operators are used to perform addition, subtraction,
multiplication, and division. They act as basic mathematical operations.
Java Arithmetic Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
[Link](a+b);//15
[Link](a-b);//5
[Link](a*b);//50
[Link](a/b);//2
[Link](a%b);//0
}
}
Output:
15
5
50
2
0
Java Arithmetic Operator Example: Expression
public class OperatorExample{
public static void main(String args[ ]){
[Link](10*10/5+3-1*4/2);
}
}
Output:
21
Java Left Shift Operator
The Java left shift operator << is used to shift all of the bits in a value to the
left side of a specified number of times.
Java Left Shift Operator Example
public class OperatorExample{
public static void main(String args[ ]){
[Link](10<<2);//10*2^2=10*4=40
[Link](10<<3);//10*2^3=10*8=80
[Link](20<<2);//20*2^2=20*4=80
[Link](15<<4);//15*2^4=15*16=240
}
}
Output:
40
80
80
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[ ]){
[Link](10>>2);//10/2^2=10/4=2
[Link](20>>2);//20/2^2=20/4=5
[Link](20>>3);//20/2^3=20/8=2
}
}
Output:
2
5
2
Java Shift Operator Example: >> vs >>>
public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
[Link](20>>2);
[Link](20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
[Link](-20>>2);
[Link](-20>>>2);
}
}
Output:
5
5
-5
1073741819
Java 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;
[Link](a<b&&a<c);//false && true = false
[Link](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;
[Link](a<b&&a++<c);//false && true = false
[Link](a);//10 because second condition is not checked
[Link](a<b&a++<c);//false && true = false
[Link](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;
[Link](a>b||a<c);//true || true = true
[Link](a>b|a<c);//true | true = true
//|| vs |
[Link](a>b||a++<c);//true || true = true
[Link](a);//10 because second condition is not checked
[Link](a>b|a++<c);//true | true = true
[Link](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;
[Link](min);
}}
Output:
Another Example:
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
[Link](min);
}}
Output:
Java 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.
Java Assignment Operator Example
public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
[Link](a);
[Link](b);
}}
Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
[Link](a);
a-=4;//13-4
[Link](a);
a*=2;//9*2
[Link](a);
a/=2;//18/2
[Link](a);
}}
Output:
13
9
18
9
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
[Link](a);
}}
Output:
Compile time error
After type cast:
public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
[Link](a);
}}
Output:
20