Java Notes Compact
Java Notes Compact
Java is a :-Java is a :-
Programming Language :Programming Language :
Java is a high-level, object-oriented programming language that enables developers to write
instructions for execution.Java is a high-level, object-oriented programming language that
enables developers to write instructions for execution.
For example "teacher" who gives the instructions to students to perform specific tasks,
developers use Java to instruct the system to execute desired operations like addition,
subtraction, division, login, register, add items into cart, online payment etc.For example
"teacher" who gives the instructions to students to perform specific tasks, developers use Java to
instruct the system to execute desired operations like addition, subtraction, division, login,
register, add items into cart, online payment etc.
Developers can use Java to perform various tasks such as addition, subtraction, user
authentication (login and registration), adding items to a cart, or processing online
payments.Developers can use Java to perform various tasks such as addition, subtraction, user
authentication (login and registration), adding items to a cart, or processing online payments.
It is designed to be simple, object-oriented, and user-friendly, similar to languages like C and C+
+.It is designed to be simple, object-oriented, and user-friendly, similar to languages like C and
C++.
Below is the diagram showing JDK architecture in Java.Below is the diagram showing JDK
architecture in Java.
This structure if explained below :- When writing a program in any programming language, it's
important to follow a basic structure recommended by experts. Typically, a Java program is
made up of the following parts, as shown in the figure below.
Deep Explanation of How Java Works Step by StepDeep Explanation of How Java Works Step by
Step
Below diagram visually explains the steps involved when writing, compiling, and executing a
Java program using Notepad and CMD.
Below is detailed explanation: Below diagram visually explains the steps involved when writing,
compiling, and executing a Java program using Notepad and CMD.
Diagram :
Diagram :
Introduction Introduction
A variable is the name of memory location that can store data.A variable is the name of memory
location that can store data.
In simple words we can say, variables are the containers used to store the data values.In simple
words we can say, variables are the containers used to store the data values.
Java Example :
int rollno = 101;
Here data i.e. 101 is stored in memory, variable name i.e. rollno points to that memory and
variable has its data type i.e. int.Java Example :
int rollno = 101;
Here data i.e. 101 is stored in memory, variable name i.e. rollno points to that memory and
variable has its data type i.e. int.
So we can say that every variable has its :-So we can say that every variable has its :-
Data Type : The type of data that it stores; for example int, char, long, float etc.Data Type : The
type of data that it stores; for example int, char, long, float etc.
Variable Name : The unique name within the scope which points to the memory
location.Variable Name : The unique name within the scope which points to the memory
location.
Value : The data assigned to the variable.
Value : The data assigned to the variable.
More Points about Varibales in Java :More Points about Varibales in Java :
Java is a statically typed language, so we must declare the type of data a variable will store.
For example if we create variable rollno having data as 101, then we have to specify its data-type
i.e. int.
Java is a statically typed language, so we must declare the type of data a variable will store.
For example if we create variable rollno having data as 101, then we have to specify its data-type
i.e. int.
The value stored in a variable can change during program execution, which is why it is called a
"variable“.
For example we have one variable no having 10 value, we can change its data as below :The
value stored in a variable can change during program execution, which is why it is called a
"variable“.
For example we have one variable no having 10 value, we can change its data as below :
int no = 10;int no = 10;
System.out.println("no : "+no); //output is no : 10System.out.println("no : "+no); //output
is no : 10
no = no + 20;no = no + 20;
System.out.println("no : "+no); //output is no : 30System.out.println("no : "+no); //output
is no : 30
public static void main(String[] args) public static void main(String[] args)
{ {
MainApp obj = new MainApp(); MainApp obj = new MainApp();
obj.m1(); obj.m1();
obj.m2(); obj.m2();
Introduction Introduction
Literals are constants used in Java programs to represent fixed values.Literals are constants
used in Java programs to represent fixed values.
They represent fixed values such as numeric values, characters, strings etc which are directly
assigned to the variables.They represent fixed values such as numeric values, characters, strings
etc which are directly assigned to the variables.
For example :
int rollno = 101;
For example :
int rollno = 101;
// Binary Literal (Base 2): Starts with 0b or 0B // Binary Literal (Base 2): Starts with 0b
or 0B
int binary = 0b1010; // Binary for decimal 10 int binary = 0b1010; // Binary for decimal
10
System.out.println("Binary Literal: " + binary); // Output: 10 System.out.println("Binary
Literal: " + binary); // Output: 10
// Octal Literal (Base 8): Starts with 0 // Octal Literal (Base 8): Starts with 0
int octal = 010; // Octal for decimal 8 int octal = 010; // Octal for decimal 8
System.out.println("Octal Literal: " + octal); // Output: 8 System.out.println("Octal
Literal: " + octal); // Output: 8
// Hexadecimal Literal (Base 16): Starts with 0x or 0X // Hexadecimal Literal (Base 16):
Starts with 0x or 0X
int hexadecimal = 0x1F; // Hexadecimal for decimal 31 int hexadecimal = 0x1F; //
Hexadecimal for decimal 31
System.out.println("Hexadecimal Literal: " + hexadecimal); // Output: 31
System.out.println("Hexadecimal Literal: " + hexadecimal); // Output: 31
// Long Literal: Specified with L or l at the end // Long Literal: Specified with L or l at
the end
long bigNum = 123456789L; long bigNum = 123456789L;
System.out.println("Long Literal: " + bigNum); // Output: 123456789
System.out.println("Long Literal: " + bigNum); // Output: 123456789
// Example of usage of all types together in calculations // Example of usage of all types
together in calculations
int sum = decimal + binary + octal + hexadecimal; int sum = decimal + binary + octal +
hexadecimal;
System.out.println("Sum of all literals: " + sum); // Output: 91 System.out.println("Sum
of all literals: " + sum); // Output: 91
} }
}}
Output:Output:
Decimal Literal: 42Decimal Literal: 42
Binary Literal: 10Binary Literal: 10
Octal Literal: 8Octal Literal: 8
Hexadecimal Literal: 31Hexadecimal Literal: 31
Long Literal: 123456789Long Literal: 123456789
Sum of all literals: 91Sum of all literals: 91
2. Floating-Point Literals2. Floating-Point Literals
Floating-Point Literals represents the numbers with decimal points.Floating-Point Literals
represents the numbers with decimal points.
Difference types of Floating-Point Literals are :-Difference types of Floating-Point Literals are :-
Float: These ends with F or f suffix (e.g., float pi = 3.14F;).Float: These ends with F or f suffix
(e.g., float pi = 3.14F;).
Double: These are the default type for decimal literals (e.g., double e = 2.718;).Double: These
are the default type for decimal literals (e.g., double e = 2.718;).
Rules for Floating-Point Literals are:Rules for Floating-Point Literals are:
Use scientific notation for very large or small numbers (e.g., double largeNum = 1.23e4;).Use
scientific notation for very large or small numbers (e.g., double largeNum = 1.23e4;).
Program for Floating-Point Literal :Program for Floating-Point Literal :
public class FloatingPointLiteralsExamplepublic class FloatingPointLiteralsExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Float Literal: Ends with F or f // Float Literal: Ends with F or f
float pi = 3.14F; // The 'F' indicates it's a float literal float pi = 3.14F; // The 'F' indicates
it's a float literal
System.out.println("Float Literal (pi): " + pi); // Output: 3.14 System.out.println("Float
Literal (pi): " + pi); // Output: 3.14
// Double Literal: Default type for decimal numbers // Double Literal: Default type for
decimal numbers
double e = 2.718; // By default, this is considered a double double e = 2.718; // By
default, this is considered a double
System.out.println("Double Literal (e): " + e); // Output: 2.718
System.out.println("Double Literal (e): " + e); // Output: 2.718
// Using Escape Sequences for special characters // Using Escape Sequences for special
characters
char newlineChar = '\n'; // Represents a newline char newlineChar = '\n'; // Represents
a newline
char tabChar = '\t'; // Represents a tab char tabChar = '\t'; // Represents a tab
char singleQuoteChar = '\''; // Represents a single quote char singleQuoteChar = '\''; //
Represents a single quote
char backslashChar = '\\'; // Represents a backslash char backslashChar = '\\'; //
Represents a backslash
String quotedString = "He said, \"Hello!\""; // Using escape sequence \" for double quote
String quotedString = "He said, \"Hello!\""; // Using escape sequence \" for double quote
System.out.println("String with Escape Sequences (quotedString): " + quotedString);
System.out.println("String with Escape Sequences (quotedString): " + quotedString);
// Output: He said, "Hello!" // Output: He said, "Hello!"
// Using Boolean literals for control flow (example with boolean flags) // Using Boolean
literals for control flow (example with boolean flags)
if (!isHot) { if (!isHot) {
System.out.println("It is not hot today!"); // This will print as isHot is false
System.out.println("It is not hot today!"); // This will print as isHot is false
} else { } else {
System.out.println("It is hot today!"); System.out.println("It is hot today!");
} }
} }
}}
Output:Output:
Is Java Fun? trueIs Java Fun? true
Is it Hot? falseIs it Hot? false
Java is fun!Java is fun!
It is not hot today!It is not hot today!
6. Null Literal6. Null Literal
Null Literal represents the absence of a value for an object reference.Null Literal represents the
absence of a value for an object reference.
Examples of Null Literal is :-Examples of Null Literal is :-
String str = null;String str = null;
Rules for Null Literals are:Rules for Null Literals are:
null can only be assigned to reference types, not primitive data types.null can only be assigned
to reference types, not primitive data types.
Program for Null Literal :Program for Null Literal :
public class NullLiteralExamplepublic class NullLiteralExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Null Literal: Represents the absence of a value for an object reference // Null Literal:
Represents the absence of a value for an object reference
String str = null; // Null literal assigned to a reference type String str = null; // Null
literal assigned to a reference type
// Checking if the object reference is null // Checking if the object reference is null
if (str == null) if (str == null)
{ {
System.out.println("The string is null, no value assigned."); System.out.println("The
string is null, no value assigned.");
} }
else else
{ {
System.out.println("The string has a value: " + str); System.out.println("The string
has a value: " + str);
} }
} }
}}
Output:Output:
The string is null, no value assigned.The string is null, no value assigned.
Underscores in Numeric Literals (Java 7+) Underscores in Numeric Literals (Java 7+)
We can use underscores in numeric literals to improve readability.We can use underscores in
numeric literals to improve readability.
For example :-For example :-
int million = 1_000_000;int million = 1_000_000;
double pi = 3.141_592_653;double pi = 3.141_592_653;
Rules to use Underscores in Numeric Literals :Rules to use Underscores in Numeric Literals :
Underscores cannot be used at the start or end of the literal, or next to a decimal
point.Underscores cannot be used at the start or end of the literal, or next to a decimal point.
Program for Underscores in Numeric Literals :Program for Underscores in Numeric Literals :
public class NumericLiteralsWithUnderscorepublic class NumericLiteralsWithUnderscore
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Using underscores to improve readability in numeric literals // Using underscores to
improve readability in numeric literals
int million = 1_000_000; // Underscores to separate thousands int million =
1_000_000; // Underscores to separate thousands
double pi = 3.141_592_653; // Underscores in a floating-point number double pi =
3.141_592_653; // Underscores in a floating-point number
// Addition // Addition
System.out.println("Addition (int): " + (a + b)); // Output: 15
System.out.println("Addition (int): " + (a + b)); // Output: 15
System.out.println("Addition (double): " + (x + y)); // Output: 14.7
System.out.println("Addition (double): " + (x + y)); // Output: 14.7
// Subtraction // Subtraction
System.out.println("Subtraction (int): " + (a - b)); // Output: 5
System.out.println("Subtraction (int): " + (a - b)); // Output: 5
System.out.println("Subtraction (double): " + (x - y)); // Output: 6.3
System.out.println("Subtraction (double): " + (x - y)); // Output: 6.3
// Multiplication // Multiplication
System.out.println("Multiplication (int): " + (a * b)); // Output: 50
System.out.println("Multiplication (int): " + (a * b)); // Output: 50
System.out.println("Multiplication (double): " + (x * y)); // Output: 44.1
System.out.println("Multiplication (double): " + (x * y)); // Output: 44.1
// Division // Division
System.out.println("Division (int): " + (a / b)); // Output: 2 (integer division)
System.out.println("Division (int): " + (a / b)); // Output: 2 (integer division)
System.out.println("Division (double): " + (x / y)); // Output: 2.5
System.out.println("Division (double): " + (x / y)); // Output: 2.5
// Modulus // Modulus
System.out.println("Modulus (int): " + (a % b)); // Output: 0
System.out.println("Modulus (int): " + (a % b)); // Output: 0
System.out.println("Modulus (double): " + (x % y)); // Output: 2.1
System.out.println("Modulus (double): " + (x % y)); // Output: 2.1
} }
}}
Output:Output:
Addition (int): 15Addition (int): 15
Addition (double): 14.7Addition (double): 14.7
Subtraction (int): 5Subtraction (int): 5
Subtraction (double): 6.3Subtraction (double): 6.3
Multiplication (int): 50Multiplication (int): 50
Multiplication (double): 44.1Multiplication (double): 44.1
Division (int): 2Division (int): 2
Division (double): 2.5Division (double): 2.5
Modulus (int): 0Modulus (int): 0
Modulus (double): 2.0999999999999996Modulus (double): 2.0999999999999996
Some Advance Important Points :- Some Advance Important Points :-
Integer Division: When both operands are integers, the division operator (/) performs integer
division, which truncates the decimal part. For example, 10 / 3 results in 3, not 3.333....Integer
Division: When both operands are integers, the division operator (/) performs integer division,
which truncates the decimal part. For example, 10 / 3 results in 3, not 3.333....
Floating-Point Division: When at least one operand is a floating-point number (float or double),
division results in a floating-point value.Floating-Point Division: When at least one operand is
a floating-point number (float or double), division results in a floating-point value.
Modulus: The modulus operator returns the remainder of the division. For example, 10 % 3
results in 1 (because 10 divided by 3 gives a remainder of 1).Modulus: The modulus operator
returns the remainder of the division. For example, 10 % 3 results in 1 (because 10 divided by 3
gives a remainder of 1).
IntroductionIntroduction
Assignment operators are used to perform an operation (like addition, subtraction,
multiplication, etc.) and assign the result to a variable in a single step.Assignment operators are
used to perform an operation (like addition, subtraction, multiplication, etc.) and assign the
result to a variable in a single step.
Assignment operators are explained as below :-Assignment operators are explained as below :-
= (Assignment Operator):= (Assignment Operator):
Purpose: Assigns the right-hand operand value to the left-hand operand
(variable).Purpose: Assigns the right-hand operand value to the left-hand operand (variable).
Example: a = b assigns the value of b to a.Example: a = b assigns the value of b to a.
+= (Addition Assignment Operator):+= (Addition Assignment Operator):
Purpose: Adds the right-hand operand value to the left-hand operand and assigns the result to
the left operand.Purpose: Adds the right-hand operand value to the left-hand operand and
assigns the result to the left operand.
Example: a += b is equivalent to a = a + b.Example: a += b is equivalent to a = a + b.
-= (Subtraction Assignment Operator):-= (Subtraction Assignment Operator):
Purpose: Subtracts the right-hand operand value from the left-hand operand and assigns the
result to the left operand.Purpose: Subtracts the right-hand operand value from the left-hand
operand and assigns the result to the left operand.
Example: a -= b is equivalent to a = a - b.Example: a -= b is equivalent to a = a - b.
*= (Multiplication Assignment Operator):*= (Multiplication Assignment Operator):
Purpose: Multiplies the right-hand operand value by the left-hand operand and assigns the
result to the left operand.Purpose: Multiplies the right-hand operand value by the left-hand
operand and assigns the result to the left operand.
Example: a *= b is equivalent to a = a * b.Example: a *= b is equivalent to a = a * b.
/= (Division Assignment Operator):/= (Division Assignment Operator):
Purpose: Divides the left-hand operand by the right-hand operand and assigns the result to the
left operand.Purpose: Divides the left-hand operand by the right-hand operand and assigns the
result to the left operand.
Example: a /= b is equivalent to a = a / b.Example: a /= b is equivalent to a = a / b.
%= (Modulus Assignment Operator):%= (Modulus Assignment Operator):
Purpose: Calculates the remainder of the division of the left operand by the right operand and
assigns the result to the left operand.Purpose: Calculates the remainder of the division of the left
operand by the right operand and assigns the result to the left operand.
Example: a %= b is equivalent to a = a % b.Example: a %= b is equivalent to a = a % b.
Program :Program :
public class AssignmentOperatorspublic class AssignmentOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize variables // Initialize variables
int a = 10, b = 5; int a = 10, b = 5;
double x = 10.5, y = 4.2; double x = 10.5, y = 4.2;
// Using compound operators with double // Using compound operators with double
x += y; // x = x + y (10.5 + 4.2) x += y; // x = x + y (10.5 + 4.2)
System.out.println("Addition Assignment (double): x = " + x); // Output: x = 14.7
System.out.println("Addition Assignment (double): x = " + x); // Output: x = 14.7
} }
}}
Output:Output:
Simple Assignment: a = 5Simple Assignment: a = 5
Addition Assignment: a = 10Addition Assignment: a = 10
Subtraction Assignment: a = 5Subtraction Assignment: a = 5
Multiplication Assignment: a = 25Multiplication Assignment: a = 25
Division Assignment: a = 5Division Assignment: a = 5
Modulus Assignment: a = 0Modulus Assignment: a = 0
Addition Assignment (double): x = 14.7Addition Assignment (double): x = 14.7
Some Advance Important Points :- Some Advance Important Points :-
Chained Assignment:Chained Assignment:
We can assign the same value to multiple variables in a single statement.We can assign the same
value to multiple variables in a single statement.
Example: a = b = c = 10; assigns 10 to a, b and c.Example: a = b = c = 10; assigns 10 to a, b and c.
Implicit Casting with Compound Operators:Implicit Casting with Compound Operators:
Compound operators (e.g., +=, *=) perform implicit type casting if needed.Compound operators
(e.g., +=, *=) perform implicit type casting if needed.
Example: int a = 5; a += 2.5; results in a = 7 (2.5 is cast to an int).Example: int a = 5; a +=
2.5; results in a = 7 (2.5 is cast to an int).
String Concatenation:String Concatenation:
The += operator concatenates strings instead of performing numeric addition.The += operator
concatenates strings instead of performing numeric addition.
Example: String s = "Java"; s += " Rocks"; results in "Java Rocks".Example: String s = "Java"; s += "
Rocks"; results in "Java Rocks".
Final Variables:Final Variables:
Assignment operators cannot modify final variables.Assignment operators cannot modify final
variables.
Example: final int a = 10; a += 5; will cause a compilation error.Example: final int a = 10; a +=
5; will cause a compilation error.
Overflow and Underflow:Overflow and Underflow:
For integer types, compound assignments can cause overflow or underflow.For integer types,
compound assignments can cause overflow or underflow.
Example: int a = Integer.MAX_VALUE; a += 1; wraps around to Integer.MIN_VALUE.Example: int
a = Integer.MAX_VALUE; a += 1; wraps around to Integer.MIN_VALUE.
Precedence and Associativity:Precedence and Associativity:
Assignment operators have low precedence and are evaluated right-to-left.Assignment
operators have low precedence and are evaluated right-to-left.
Example: a = b = c = 10; evaluates as c = 10, then b = c, then a = b.Example: a = b = c =
10; evaluates as c = 10, then b = c, then a = b.
Side Effects:Side Effects:
Assignment operators modify the variable as part of the expression.Assignment operators
modify the variable as part of the expression.
Example: int a = 5; int b = (a += 10) * 2; results in a = 15 and b = 30.Example: int a = 5; int b = (a
+= 10) * 2; results in a = 15 and b = 30.
Not for Literals:Not for Literals:
The left-hand operand of an assignment must be a variable, not a literal or constant.The left-
hand operand of an assignment must be a variable, not a literal or constant.
Example: 5 += 3; is invalid.Example: 5 += 3; is invalid.
Usage in Loops:Usage in Loops:
Compound assignment operators (+=, -=) are frequently used in loops to modify counters
efficiently.Compound assignment operators (+=, -=) are frequently used in loops to modify
counters efficiently.
Example: for (int i = 0; i < 10; i += 2) iterates by steps of 2.Example: for (int i = 0; i < 10; i +=
2) iterates by steps of 2.
Cannot Chain Compound Operators:Cannot Chain Compound Operators:
Compound assignments like += cannot be directly chained.Compound assignments
like += cannot be directly chained.
Example: a += b += c; is invalid.Example: a += b += c; is invalid.
Works with All Primitives:Works with All Primitives:
Assignment operators can be used with numeric types (int, float, etc.), char, and boolean where
applicable.Assignment operators can be used with numeric types (int, float, etc.), char,
and boolean where applicable.
Efficiency:Efficiency:
Compound operators are generally more efficient as they reduce the number of operations
compared to their explicit counterparts.Compound operators are generally more efficient as
they reduce the number of operations compared to their explicit counterparts.
IntroductionIntroduction
Relational operators are used to compare two values or expressions and return a boolean value
(true or false).Relational operators are used to compare two values or expressions and return a
boolean value (true or false).
Relational operators are explained as below :-Relational operators are explained as below :-
== (Equal to Operator):== (Equal to Operator):
Purpose: Checks if two values are equal.Purpose: Checks if two values are equal.
Example:Example:
int a = 5, b = 5; int a = 5, b = 5;
System.out.println(a == b); // Output: trueSystem.out.println(a == b); // Output: true
!= (Not equal to operator):!= (Not equal to operator):
Purpose: Checks if two values are not equal.Purpose: Checks if two values are not equal.
Example:Example:
int a = 5, b = 10; int a = 5, b = 10;
System.out.println(a != b); // Output: trueSystem.out.println(a != b); // Output: true
< (Less Than Operator):< (Less Than Operator):
Purpose: Checks if the left operand is less than the right operand.Purpose: Checks if the left
operand is less than the right operand.
Example:Example:
int a = 5, b = 10; int a = 5, b = 10;
System.out.println(a < b); // Output: trueSystem.out.println(a < b); // Output: true
> (Greater Than Operator):> (Greater Than Operator):
Purpose: Checks if the left operand is greater than the right operand.Purpose: Checks if the left
operand is greater than the right operand.
Example:Example:
int a = 10, b = 5; int a = 10, b = 5;
System.out.println(a > b); // Output: trueSystem.out.println(a > b); // Output: true
<= (Less than or equal to operator):<= (Less than or equal to operator):
Purpose: Checks if the left operand is less than or equal to the right operand.Purpose: Checks if
the left operand is less than or equal to the right operand.
Example:Example:
int a = 5, b = 10; int a = 5, b = 10;
System.out.println(a <= b); // Output: trueSystem.out.println(a <= b); // Output: true
>= (Greater than or equal to operator):>= (Greater than or equal to operator):
Purpose: Checks if the left operand is greater than or equal to the right operand.Purpose: Checks
if the left operand is greater than or equal to the right operand.
Example:Example:
int a = 10, b = 10; int a = 10, b = 10;
System.out.println(a >= b); // Output: trueSystem.out.println(a >= b); // Output: true
Program :Program :
public class RelationalOperatorspublic class RelationalOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize variables // Initialize variables
int a = 10, b = 20; int a = 10, b = 20;
double x = 15.5, y = 15.5; double x = 15.5, y = 15.5;
IntroductionIntroduction
Logical Operators are used to perform logical operations between two or more boolean
expressions and return a boolean value (true or false).Logical Operators are used to perform
logical operations between two or more boolean expressions and return a boolean value (true
or false).
Logical operators are explained as below :-Logical operators are explained as below :-
&& (Logical AND Operator):&& (Logical AND Operator):
Purpose: Returns true if both operands (expressions) are true, otherwise returns
false.Purpose: Returns true if both operands (expressions) are true, otherwise returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a && b); // Output: falseSystem.out.println(a && b); // Output: false
|| (Logical OR Operator):|| (Logical OR Operator):
Purpose: Returns true if at least one of the operands (expressions) is true, otherwise returns
false.Purpose: Returns true if at least one of the operands (expressions) is true, otherwise
returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a || b); // Output: trueSystem.out.println(a || b); // Output: true
! (Logical NOT Operator):! (Logical NOT Operator):
Purpose: Inverts the value of the boolean expression. If the expression is true, it becomes false,
and vice versa.Purpose: Inverts the value of the boolean expression. If the expression is true, it
becomes false, and vice versa.
Example:Example:
boolean a = true; boolean a = true;
System.out.println(!a); // Output: falseSystem.out.println(!a); // Output: false
Program :Program :
public class LogicalOperatorspublic class LogicalOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize boolean variables // Initialize boolean variables
boolean a = true, b = false, c = true; boolean a = true, b = false, c = true;
IntroductionIntroduction
Logical Operators are used to perform logical operations between two or more boolean
expressions and return a boolean value (true or false).Logical Operators are used to perform
logical operations between two or more boolean expressions and return a boolean value (true
or false).
Logical operators are explained as below :-Logical operators are explained as below :-
&& (Logical AND Operator):&& (Logical AND Operator):
Purpose: Returns true if both operands (expressions) are true, otherwise returns
false.Purpose: Returns true if both operands (expressions) are true, otherwise returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a && b); // Output: falseSystem.out.println(a && b); // Output: false
|| (Logical OR Operator):|| (Logical OR Operator):
Purpose: Returns true if at least one of the operands (expressions) is true, otherwise returns
false.Purpose: Returns true if at least one of the operands (expressions) is true, otherwise
returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a || b); // Output: trueSystem.out.println(a || b); // Output: true
! (Logical NOT Operator):! (Logical NOT Operator):
Purpose: Inverts the value of the boolean expression. If the expression is true, it becomes false,
and vice versa.Purpose: Inverts the value of the boolean expression. If the expression is true, it
becomes false, and vice versa.
Example:Example:
boolean a = true; boolean a = true;
System.out.println(!a); // Output: falseSystem.out.println(!a); // Output: false
Program :Program :
public class LogicalOperatorspublic class LogicalOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize boolean variables // Initialize boolean variables
boolean a = true, b = false, c = true; boolean a = true, b = false, c = true;
IntroductionIntroduction
Logical Operators are used to perform logical operations between two or more boolean
expressions and return a boolean value (true or false).Logical Operators are used to perform
logical operations between two or more boolean expressions and return a boolean value (true
or false).
Logical operators are explained as below :-Logical operators are explained as below :-
&& (Logical AND Operator):&& (Logical AND Operator):
Purpose: Returns true if both operands (expressions) are true, otherwise returns
false.Purpose: Returns true if both operands (expressions) are true, otherwise returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a && b); // Output: falseSystem.out.println(a && b); // Output: false
|| (Logical OR Operator):|| (Logical OR Operator):
Purpose: Returns true if at least one of the operands (expressions) is true, otherwise returns
false.Purpose: Returns true if at least one of the operands (expressions) is true, otherwise
returns false.
Example:Example:
boolean a = true, b = false; boolean a = true, b = false;
System.out.println(a || b); // Output: trueSystem.out.println(a || b); // Output: true
! (Logical NOT Operator):! (Logical NOT Operator):
Purpose: Inverts the value of the boolean expression. If the expression is true, it becomes false,
and vice versa.Purpose: Inverts the value of the boolean expression. If the expression is true, it
becomes false, and vice versa.
Example:Example:
boolean a = true; boolean a = true;
System.out.println(!a); // Output: falseSystem.out.println(!a); // Output: false
Program :Program :
public class LogicalOperatorspublic class LogicalOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize boolean variables // Initialize boolean variables
boolean a = true, b = false, c = true; boolean a = true, b = false, c = true;
Introduction Introduction
The ternary operator in Java is a shortcut for the if-else statement.The ternary operator in Java
is a shortcut for the if-else statement.
It evaluates a boolean expression and returns one of two values based on the result of the
evaluation.It evaluates a boolean expression and returns one of two values based on the result
of the evaluation.
The syntax of ternary operator is as below:
condition ? value1 : value2;The syntax of ternary operator is as below:
condition ? value1 : value2;
condition: The boolean expression that is evaluated.condition: The boolean expression that is
evaluated.
value1: The value returned if the condition evaluates to true.value1: The value returned if the
condition evaluates to true.
value2: The value returned if the condition evaluates to false.value2: The value returned if the
condition evaluates to false.
Usage:Usage:
Simplified if-else: Instead of writing an entire if-else block, the ternary operator allows you to
decide between two values in one line.Simplified if-else: Instead of writing an entire if-else
block, the ternary operator allows you to decide between two values in one line.
Program:Program:
public class TernaryOperatorpublic class TernaryOperator
{{
public static void main(String[] args) public static void main(String[] args)
{ {
int a = 10, b = 20; int a = 10, b = 20;
// Using ternary operator to find the maximum of two numbers // Using ternary
operator to find the maximum of two numbers
int max = (a > b) ? a : b; int max = (a > b) ? a : b;
System.out.println("The maximum value is: " + max); // Output: The maximum value is: 20
System.out.println("The maximum value is: " + max); // Output: The maximum value is: 20
// Using ternary operator to check if a number is even or odd // Using ternary operator
to check if a number is even or odd
String result = (a % 2 == 0) ? "Even" : "Odd"; String result = (a % 2 == 0) ? "Even" : "Odd";
System.out.println("The number is: " + result); // Output: The number is: Even
System.out.println("The number is: " + result); // Output: The number is: Even
IntroductionIntroduction
Bitwise operators perform operations at the binary (bit) level on integer types such
as int, long, short, byte and char.Bitwise operators perform operations at the binary (bit) level
on integer types such as int, long, short, byte and char.
Usage:
Useful for tasks such as:Usage:
Useful for tasks such as:
Low-level programming: Directly manipulating bits for hardware interaction.Low-level
programming: Directly manipulating bits for hardware interaction.
Flags: Managing multiple boolean conditions compactly using a single integer.Flags: Managing
multiple boolean conditions compactly using a single integer.
Efficient calculations: Performing tasks like checking even/odd numbers or swapping values
without additional memory.Efficient calculations: Performing tasks like checking even/odd
numbers or swapping values without additional memory.
Operation:Operation:
They operate on the binary representation of numbers, modifying individual bits based on the
operator.They operate on the binary representation of numbers, modifying individual bits based
on the operator.
Operand Types:Operand Types:
Works only with integer data types (int, long, short, byte and char) but not with floating-point or
boolean values.Works only with integer data types (int, long, short, byte and char) but not with
floating-point or boolean values.
Efficiency:Efficiency:
Bitwise operations are computationally faster than arithmetic or logical operations, making
them ideal for performance-critical code.Bitwise operations are computationally faster than
arithmetic or logical operations, making them ideal for performance-critical code.
Common Applications:Common Applications:
Masks: Using bit masks to extract, modify, or toggle specific bits.Masks: Using bit masks to
extract, modify, or toggle specific bits.
Encryption: XOR (^) is often used in simple encryption schemes.Encryption: XOR (^) is often
used in simple encryption schemes.
Shift Operations: Combine with shift operators (<<, >>, >>>) for tasks like scaling numbers or
accessing specific bits.Shift Operations: Combine with shift operators (<<, >>, >>>) for tasks like
scaling numbers or accessing specific bits.
Bitwise operators are explained as below :-Bitwise operators are explained as below :-
& (Bitwise AND Operator):& (Bitwise AND Operator):
Purpose: Performs a bit-by-bit AND operation between two integer values. Each bit in the result
is 1 if the corresponding bits in both operands are 1; otherwise, it is 0.Purpose: Performs a bit-
by-bit AND operation between two integer values. Each bit in the result is 1 if the corresponding
bits in both operands are 1; otherwise, it is 0.
Example:Example:
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
int b = 3; // Binary: 0011 int b = 3; // Binary: 0011
System.out.println(a & b); // Output: 1 (Binary: 0001)System.out.println(a & b); // Output: 1
(Binary: 0001)
| (Bitwise OR Operator):| (Bitwise OR Operator):
Purpose: Performs a bit-by-bit OR operation between two integer values. Each bit in the result is
1 if at least one of the corresponding bits in the operands is 1; otherwise, it is
0.Purpose: Performs a bit-by-bit OR operation between two integer values. Each bit in the result
is 1 if at least one of the corresponding bits in the operands is 1; otherwise, it is 0.
Example:Example:
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
int b = 3; // Binary: 0011 int b = 3; // Binary: 0011
System.out.println(a | b); // Output: 7 (Binary: 0111)System.out.println(a | b); // Output: 7
(Binary: 0111)
^ (Bitwise XOR Operator):^ (Bitwise XOR Operator):
Purpose: Performs a bit-by-bit XOR (exclusive OR) operation between two integer values. Each
bit in the result is 1 if the corresponding bits in the operands are different; otherwise, it is
0.Purpose: Performs a bit-by-bit XOR (exclusive OR) operation between two integer values. Each
bit in the result is 1 if the corresponding bits in the operands are different; otherwise, it is 0.
Example:Example:
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
int b = 3; // Binary: 0011 int b = 3; // Binary: 0011
System.out.println(a ^ b); // Output: 6 (Binary: 0110)System.out.println(a ^ b); // Output: 6
(Binary: 0110)
~ (Bitwise NOT Operator)~ (Bitwise NOT Operator)
Purpose: Inverts each bit of its operand (also called one's complement). Each 1 becomes 0 and
each 0 becomes 1. The result is equivalent to -(operand + 1).Purpose: Inverts each bit of its
operand (also called one's complement). Each 1 becomes 0 and each 0 becomes 1. The result is
equivalent to -(operand + 1).
Example:Example:
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
System.out.println(~a); // Output: -6 (Binary: 1010 in two's complement
form)System.out.println(~a); // Output: -6 (Binary: 1010 in two's complement form)
Program:Program:
public class BitwiseOperatorspublic class BitwiseOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize variables // Initialize variables
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
int b = 3; // Binary: 0011 int b = 3; // Binary: 0011
Introduction Introduction
Shift operators in Java are used to shift the bits of integer types (int, long, short, byte, char)
either to the left or right, allowing efficient manipulation of binary data.Shift operators in Java
are used to shift the bits of integer types (int, long, short, byte, char) either to the left or right,
allowing efficient manipulation of binary data.
Usage:
Useful for tasks such as:Usage:
Useful for tasks such as:
Low-level programming: Used for manipulating binary data and hardware interaction.Low-level
programming: Used for manipulating binary data and hardware interaction.
Efficient calculations: Scale numbers by powers of two, faster than
multiplication/division.Efficient calculations: Scale numbers by powers of two, faster than
multiplication/division.
Optimizing performance: Faster than arithmetic/logical operations in performance-critical
tasks.Optimizing performance: Faster than arithmetic/logical operations in performance-critical
tasks.
Data encoding/decoding: Important in bit-packing and handling bits in data.Data
encoding/decoding: Important in bit-packing and handling bits in data.
Operation:Operation:
Binary Manipulation: Shift bits left or right to perform efficient binary tasks.Binary
Manipulation: Shift bits left or right to perform efficient binary tasks.
Operand Types:Operand Types:
Works only with integer data types (int, long, short, byte and char) but not with floating-point or
boolean values.Works only with integer data types (int, long, short, byte and char) but not with
floating-point or boolean values.
Efficiency:Efficiency:
Shift operations are faster than multiplication/division, ideal for performance-critical code.Shift
operations are faster than multiplication/division, ideal for performance-critical code.
Common Applications:Common Applications:
Scaling numbers: Left shift (<<) for multiplication by 2, right shift (>>) for division by 2.Scaling
numbers: Left shift (<<) for multiplication by 2, right shift (>>) for division by 2.
Flag manipulation: Combined with bitwise operators for flag management.Flag
manipulation: Combined with bitwise operators for flag management.
Memory optimization: Efficiently uses memory, especially with bitmasks.Memory
optimization: Efficiently uses memory, especially with bitmasks.
Efficient arithmetic operations: Fast for low-level calculations and cryptography.Efficient
arithmetic operations: Fast for low-level calculations and cryptography.
Shift operators are explained as below :-Shift operators are explained as below :-
<< (Left shift operator):<< (Left shift operator):
Purpose: Shifts the bits of a number to the left by the specified number of positions, filling the
empty positions with zeros.Purpose: Shifts the bits of a number to the left by the specified
number of positions, filling the empty positions with zeros.
Effect: Multiplies the number by 2 for each position the bits are shifted.Effect: Multiplies the
number by 2 for each position the bits are shifted.
Example:Example:
int a = 5; int a = 5;
System.out.println(a << 1); // Output: 10 (binary 101 << 1 becomes 1010)System.out.println(a
<< 1); // Output: 10 (binary 101 << 1 becomes 1010)
>> (Right shift operator):>> (Right shift operator):
Purpose: Shifts the bits of a number to the right by the specified number of positions. The empty
positions on the left are filled based on the sign of the number (for signed types).Purpose: Shifts
the bits of a number to the right by the specified number of positions. The empty positions on
the left are filled based on the sign of the number (for signed types).
Effect: Divides the number by 2 for each position the bits are shifted, maintaining the sign of the
number.Effect: Divides the number by 2 for each position the bits are shifted, maintaining the
sign of the number.
Example:Example:
int a = 20;int a = 20;
System.out.println(a >> 2); // Output: 5 (binary 10100 >> 2 becomes 101)System.out.println(a
>> 2); // Output: 5 (binary 10100 >> 2 becomes 101)
>>> (Unsigned right shift operator):>>> (Unsigned right shift operator):
Purpose: Shifts the bits of a number to the right by the specified number of positions, filling the
empty positions with zeros, regardless of the sign.Purpose: Shifts the bits of a number to the
right by the specified number of positions, filling the empty positions with zeros, regardless of
the sign.
Effect: Divides the number by 2 for each position the bits are shifted but does not preserve the
sign.Effect: Divides the number by 2 for each position the bits are shifted but does not preserve
the sign.
Example:Example:
int a = -20;int a = -20;
System.out.println(a >>> 2); // Output: 1073741815 (binary of -20 shifted right with zero-
fill)System.out.println(a >>> 2); // Output: 1073741815 (binary of -20 shifted right with zero-
fill)
Program:Program:
public class ShiftOperatorspublic class ShiftOperators
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Initialize variables // Initialize variables
int a = 5; // Binary: 0101 int a = 5; // Binary: 0101
int b = -10; // Binary: 11111111111111111111111111110110 (in 32-bit two's
complement) int b = -10; // Binary: 11111111111111111111111111110110 (in 32-bit
two's complement)
// Left shift with negative number // Left shift with negative number
System.out.println("Left Shift (b << 1): " + (b << 1)); // Output: -20 (Binary:
11111111111111111111111111101100) System.out.println("Left Shift (b << 1): " + (b <<
1)); // Output: -20 (Binary: 11111111111111111111111111101100)
// Right shift with negative number // Right shift with negative number
System.out.println("Right Shift (b >> 1): " + (b >> 1)); // Output: -5 (Binary:
11111111111111111111111111111011) System.out.println("Right Shift (b >> 1): " + (b >>
1)); // Output: -5 (Binary: 11111111111111111111111111111011)
// Unsigned right shift with negative number // Unsigned right shift with negative
number
System.out.println("Unsigned Right Shift (b >>> 1): " + (b >>> 1)); // Output: 2147483643
(Binary: 01111111111111111111111111111011) System.out.println("Unsigned Right Shift
(b >>> 1): " + (b >>> 1)); // Output: 2147483643 (Binary:
01111111111111111111111111111011)
} }
}}
Output:Output:
Left Shift (a << 1): 10Left Shift (a << 1): 10
Right Shift (a >> 1): 2Right Shift (a >> 1): 2
Unsigned Right Shift (a >>> 1): 2Unsigned Right Shift (a >>> 1): 2
Left Shift (b << 1): -20Left Shift (b << 1): -20
Right Shift (b >> 1): -5Right Shift (b >> 1): -5
Unsigned Right Shift (b >>> 1): 2147483643Unsigned Right Shift (b >>> 1): 2147483643
Some Advance Important Points :- Some Advance Important Points :-
Shift Operators with Literals:Shift Operators with Literals:
Shift operators can be directly applied to literals or variables.Shift operators can be directly
applied to literals or variables.
Example:Example:
System.out.println(4 << 2); // Output: 16 (Binary: 0100 << 2 positions results in
10000)System.out.println(4 << 2); // Output: 16 (Binary: 0100 << 2 positions results in 10000)
System.out.println(8 >> 1); // Output: 4 (Binary: 1000 >> 1 position results in
0100)System.out.println(8 >> 1); // Output: 4 (Binary: 1000 >> 1 position results in 0100)
Supported Data Types:Supported Data Types:
Shift operators work only with integer types such as byte, short, int, long and char.Shift
operators work only with integer types such as byte, short, int, long and char.
Applying shift operators to floating-point types (float, double) will result in a compilation error.
System.out.println(5.5 << 1); // Compilation error: incompatible types: possible lossy
conversion from double to intApplying shift operators to floating-point types (float, double) will
result in a compilation error.
System.out.println(5.5 << 1); // Compilation error: incompatible types: possible lossy
conversion from double to int
Left Shift (<<) for Multiplication:Left Shift (<<) for Multiplication:
The left shift operator (<<) is used for efficient multiplication by powers of two.The left shift
operator (<<) is used for efficient multiplication by powers of two.
Example :Example :
int x = 3;int x = 3;
System.out.println(x << 2); // Output: 12 (Equivalent to 3 * 2^2)System.out.println(x << 2); //
Output: 12 (Equivalent to 3 * 2^2)
This is computationally faster than using multiplication (x * 4).This is computationally faster
than using multiplication (x * 4).
Right Shift (>>) for Division:Right Shift (>>) for Division:
The right shift operator (>>) is used for efficient division by powers of two.The right shift
operator (>>) is used for efficient division by powers of two.
Example :Example :
int x = 16;int x = 16;
System.out.println(x >> 2); // Output: 4 (Equivalent to 16 / 2^2)System.out.println(x >> 2); //
Output: 4 (Equivalent to 16 / 2^2)
This is faster than using division (x / 4).This is faster than using division (x / 4).
Unsigned Right Shift (>>>) and Negative Numbers:Unsigned Right Shift (>>>) and Negative
Numbers:
The unsigned right shift operator (>>>) behaves differently for negative numbers by filling with
zeros instead of extending the sign bit.The unsigned right shift operator (>>>) behaves
differently for negative numbers by filling with zeros instead of extending the sign bit.
Example :Example :
int x = -8; int x = -8;
System.out.println(x >>> 1); // Output: 2147483640 (In binary:
11111111111111111111111111111000 >> 1 results in
01111111111111111111111111111100)System.out.println(x >>> 1); // Output: 2147483640
(In binary: 11111111111111111111111111111000 >> 1 results in
01111111111111111111111111111100)
Shift Operators with Negative Numbers:Shift Operators with Negative Numbers:
The behavior of shift operators is distinct when applied to negative numbers, especially the sign
extension in the right shift (>>).The behavior of shift operators is distinct when applied to
negative numbers, especially the sign extension in the right shift (>>).
The left shift (<<) of a negative number behaves the same as for positive numbers but can result
in sign changes if the leftmost bit is shifted into the sign bit.The left shift (<<) of a negative
number behaves the same as for positive numbers but can result in sign changes if the leftmost
bit is shifted into the sign bit.
Example :Example :
int x = -5;int x = -5;
System.out.println(x << 1); // Output: -10 (Binary: 11111111111111111111111111111011 <<
1 results in 11111111111111111111111111110110)System.out.println(x << 1); // Output: -10
(Binary: 11111111111111111111111111111011 << 1 results in
11111111111111111111111111110110)
Zero-Fill Right Shift (>>>) with Negative Numbers:Zero-Fill Right Shift (>>>) with Negative
Numbers:
The unsigned right shift (>>>) on negative numbers replaces the sign bit with 0, making it useful
for operations like bit masks or extracting specific parts of a number.The unsigned right shift
(>>>) on negative numbers replaces the sign bit with 0, making it useful for operations like bit
masks or extracting specific parts of a number.
Example:Example:
int x = -4;int x = -4;
System.out.println(x >>> 1); // Output: 2147483643 (Binary:
11111111111111111111111111111100 >>> 1 results in
01111111111111111111111111111110)System.out.println(x >>> 1); // Output: 2147483643
(Binary: 11111111111111111111111111111100 >>> 1 results in
01111111111111111111111111111110)
Shifting on Larger Numbers (long):Shifting on Larger Numbers (long):
The shift operators can be used on larger integer types like long. However, the right operand
should be masked with & 0x3F (for long shift) to avoid shifting more than 63 positions (for 64-
bit long).The shift operators can be used on larger integer types like long. However, the right
operand should be masked with & 0x3F (for long shift) to avoid shifting more than 63 positions
(for 64-bit long).
Example:Example:
long x = 100L;long x = 100L;
System.out.println(x << 3); // Output: 800 (Equivalent to 100 * 2^3)System.out.println(x <<
3); // Output: 800 (Equivalent to 100 * 2^3)
Shift Operations with Negative Powers:Shift Operations with Negative Powers:
Negative values in the right shift operator (>> and >>>) will throw a compile-time
error.Negative values in the right shift operator (>> and >>>) will throw a compile-time error.
Example:Example:
int x = 8;int x = 8;
System.out.println(x >> -2); // Compile-time error: shift count must be non-
negativeSystem.out.println(x >> -2); // Compile-time error: shift count must be non-negative
Overflow and Underflow in Shift Operations:Overflow and Underflow in Shift Operations:
While shifting, if the value overflows or underflows beyond the range of the data type, the result
can be unpredictable. Java’s shift operators do not raise errors for overflows but wrap the result
around based on the data type size.While shifting, if the value overflows or underflows beyond
the range of the data type, the result can be unpredictable. Java’s shift operators do not raise
errors for overflows but wrap the result around based on the data type size.
Example:Example:
int x = Integer.MAX_VALUE;int x = Integer.MAX_VALUE;
System.out.println(x << 1); // Output: -2 (Overflow: 2147483647 << 1 results in a negative
value)System.out.println(x << 1); // Output: -2 (Overflow: 2147483647 << 1 results in a
negative value)
Introduction Introduction
The instanceof operator is used to check if an object is an instance of a specific class or
implements a given interface.The instanceof operator is used to check if an object is an instance
of a specific class or implements a given interface.
It returns a boolean value: true if the object is an instance of the specified class or interface, and
false otherwise.It returns a boolean value: true if the object is an instance of the specified class
or interface, and false otherwise.
It is commonly used for type checking in Java.It is commonly used for type checking in Java.
Syntax:
object instanceof ClassNameSyntax:
object instanceof ClassName
object: The reference variable pointing to the object being tested.object: The reference variable
pointing to the object being tested.
ClassName: The class or interface that you want to check the type of the object
against.ClassName: The class or interface that you want to check the type of the object against.
Program:Program:
class Animal class Animal
{{
// some methods // some methods
}}
// Using instanceof to check the type // Using instanceof to check the type
if (animal instanceof Dog) if (animal instanceof Dog)
{ {
System.out.println("The animal is a Dog"); System.out.println("The animal is a
Dog");
} }
else else
{ {
System.out.println("The animal is not a Dog"); System.out.println("The animal is not
a Dog");
} }
} }
}}
Output:Output:
The animal is a DogThe animal is a Dog
Some Advance Important Points :- Some Advance Important Points :-
Usage of instanceof Operator:Usage of instanceof Operator:
Type Checking: It checks if an object is an instance of a particular class or interface.
For example :-Type Checking: It checks if an object is an instance of a particular class or
interface.
For example :-
String str = "Hello";String str = "Hello";
System.out.println(str instanceof String); // Output: trueSystem.out.println(str instanceof
String); // Output: true
Interface Type Checking: Checks if an object implements a particular interface.
For example :-Interface Type Checking: Checks if an object implements a particular interface.
For example :-
List<String> list = new ArrayList<>();List<String> list = new ArrayList<>();
System.out.println(list instanceof List); // Output: trueSystem.out.println(list instanceof
List); // Output: true
Null Check:Null Check:
The instanceof operator will always return false when the object being checked
is null.The instanceof operator will always return false when the object being checked is null.
String str = null;String str = null;
System.out.println(str instanceof String); // Output: falseSystem.out.println(str instanceof
String); // Output: false
Inheritance with instanceof:Inheritance with instanceof:
Inheritance Hierarchy: The operator works well with inheritance, checking if an object is an
instance of a superclass or subclass.Inheritance Hierarchy: The operator works well with
inheritance, checking if an object is an instance of a superclass or subclass.
class Animal {}class Animal {}
class Dog extends Animal {}class Dog extends Animal {}
Introduction Introduction
Keywords are the predefined, reserved words used by the Java compiler for specific
operations.Keywords are the predefined, reserved words used by the Java compiler for specific
operations.
There are total 50 keywords in Java, in which 48 keywords are actively used in programming
and 2 reserved words (goto and const) that are not currently used in java.There are total 50
keywords in Java, in which 48 keywords are actively used in programming and 2 reserved
words (goto and const) that are not currently used in java.
Below is the list of all reserved words in java :- Below is the list of all reserved words in java :-
NOTE :NOTE :
true, false and null are not keywords, they are literals (reserved words).true, false and null are
not keywords, they are literals (reserved words).
There are 5 Contextual keywords in Java, that act like keywords only in specific situations. These
keywords are var, yield, record, sealed and non-sealed. So total there are 57 reserved words
including 5 contextual keywords in Java.There are 5 Contextual keywords in Java, that act like
keywords only in specific situations. These keywords are var, yield, record, sealed and non-
sealed. So total there are 57 reserved words including 5 contextual keywords in Java.
Just as "Priya" is a name used to identify the girl; in programming, identifiers are names used to
identify variables, classes, methods, interfaces or other elements in the code.Just as "Priya" is a
name used to identify the girl; in programming, identifiers are names used to identify variables,
classes, methods, interfaces or other elements in the code.
In simple words we can say, Ientifiers is any name, it can be variable, methods or class name in
our program.In simple words we can say, Ientifiers is any name, it can be variable, methods or
class name in our program.
They are unique names that help us recognize elements like variables, methods, and classes in
our program.They are unique names that help us recognize elements like variables, methods,
and classes in our program.
For example :For example :
String name = "Deepak"; // here name is identifierString name = "Deepak"; // here name is
identifier
int rollno = 101; // here rollno is identifierint rollno = 101; // here rollno is identifier
class Test {-} // here Test is identifierclass Test {-} // here Test is identifier
Rules for Identifiers: Rules for Identifiers:
Spaces cannot be used in an identifier.Spaces cannot be used in an identifier.
Identifiers must not contain any whitespace.Identifiers must not contain any whitespace.
Valid Examples:Valid Examples:
int myVariable;int myVariable;
String userName;String userName;
Invalid Examples:Invalid Examples:
int my Variable; // Error: Spaces are not allowedint my Variable; // Error: Spaces are not
allowed
String user Name; // Error: Spaces are not allowedString user Name; // Error: Spaces are not
allowed
Only two symbols (_ and $) can be used in an identifier.Only two symbols (_ and $) can be
used in an identifier.
Identifiers can include underscores (_) or dollar signs ($), but other special symbols
like @, # or ! are not allowed.Identifiers can include underscores (_) or dollar signs ($), but other
special symbols like @, # or ! are not allowed.
Valid Examples:Valid Examples:
int _counter;int _counter;
double $price;double $price;
String first_name;String first_name;
Invalid Examples:Invalid Examples:
int user#name; // Error: '#' is not allowedint user#name; // Error: '#' is not allowed
double total@; // Error: '@' is not alloweddouble total@; // Error: '@' is not allowed
Integer values cannot be used at the first position.Integer values cannot be used at the first
position.
Identifiers cannot begin with a digit (0-9) but may include digits after the first
character.Identifiers cannot begin with a digit (0-9) but may include digits after the first
character.
Valid Examples:Valid Examples:
int variable1;int variable1;
double _123value;double _123value;
Invalid Examples:Invalid Examples:
int 1variable; // Error: Cannot start with a digitint 1variable; // Error: Cannot start with a
digit
double 3value; // Error: Cannot start with a digitdouble 3value; // Error: Cannot start with a
digit
Reserved words cannot be used as an identifier.Reserved words cannot be used as an
identifier.
Reserved keywords in Java (like class, public, if, etc.) cannot be used as identifiers.Reserved
keywords in Java (like class, public, if, etc.) cannot be used as identifiers.
Valid Examples:Valid Examples:
int myClass;int myClass;
String _if;String _if;
Invalid Examples:Invalid Examples:
int class; // Error: 'class' is a reserved keywordint class; // Error: 'class' is a reserved
keyword
String public; // Error: 'public' is a reserved keywordString public; // Error: 'public' is a
reserved keyword
Case Sensitivity.Case Sensitivity.
Java identifiers are case-sensitive. For example, MyVariable and myVariable are treated as
distinct identifiers.Java identifiers are case-sensitive. For
example, MyVariable and myVariable are treated as distinct identifiers.
Valid Examples:Valid Examples:
int MyVariable = 10;int MyVariable = 10;
int myVariable = 20; // Different from 'MyVariable'int myVariable = 20; // Different from
'MyVariable'
No Length Limit.No Length Limit.
There is no specific limit on the length of an identifier, but it is recommended to keep names
concise and meaningful.There is no specific limit on the length of an identifier, but it is
recommended to keep names concise and meaningful.
Valid Examples:Valid Examples:
int thisIsAnExtremelyLongVariableName = 100; // Valid but not recommendedint
thisIsAnExtremelyLongVariableName = 100; // Valid but not recommended
Must Not Conflict with Built-in Methods.Must Not Conflict with Built-in Methods.
Avoid using names that conflict with commonly used built-in methods or library functions to
prevent confusion.Avoid using names that conflict with commonly used built-in methods or
library functions to prevent confusion.
Valid Examples:Valid Examples:
int println = 5; // Valid but confusing, as 'println' is used in System.out.println()int println =
5; // Valid but confusing, as 'println' is used in System.out.println()
Use Meaningful Names.Use Meaningful Names.
Choose names that describe the purpose of the variable or method to improve code
readability.Choose names that describe the purpose of the variable or method to improve code
readability.
Valid Examples:Valid Examples:
int x = 10; // Valid but not descriptiveint x = 10; // Valid but not descriptive
int age = 10; // Better: Descriptive and meaningfulint age = 10; // Better: Descriptive and
meaningful
Introduction Introduction
Control statements in Java are the instructions that controls or manages the flow of execution of
a program based on specific conditions or loops.Control statements in Java are the instructions
that controls or manages the flow of execution of a program based on specific conditions or
loops.
Control Statements are used to:Control Statements are used to:
Make decisions: Control program flow based on conditions (e.g., if, switch).Make
decisions: Control program flow based on conditions (e.g., if, switch).
Loop through blocks of code: Repeat code execution multiple times (e.g., for, while).Loop
through blocks of code: Repeat code execution multiple times (e.g., for, while).
Jump to a different part of the code: Change the natural flow of execution
(e.g., break, continue).Jump to a different part of the code: Change the natural flow of
execution (e.g., break, continue).
Types of Control Statements: Types of Control Statements:
Control Statements in Java are divided in 3 main categories:Control Statements in Java are
divided in 3 main categories:
Decision-Making Statements or Conditional StatementsDecision-Making Statements or
Conditional Statements
These statements allow the program to make decisions and execute a block of code based on a
condition.These statements allow the program to make decisions and execute a block of code
based on a condition.
Examples are: if, if-else, if-else if ladder, switch.Examples are: if, if-else, if-else if ladder, switch.
to read Conditional Statements more deeply. to read Conditional Statements more deeply.
Iteration or Looping StatementsIteration or Looping Statements
These statements allow the execution of a block of code multiple times until a condition is
satisfied.These statements allow the execution of a block of code multiple times until a condition
is satisfied.
Examples are: for, while, do-while.Examples are: for, while, do-while.
to read Looping Statements more deeply. to read Looping Statements more deeply.
Jump StatementsJump Statements
These statements are used to alter the flow of control by jumping to a specific part of the
program.These statements are used to alter the flow of control by jumping to a specific part of
the program.
Examples are: break, continue, return.Examples are: break, continue, return.
to read Jump Statements more deeply. to read Jump Statements more deeply.
Java Conditional Statements with Examples Java Conditional Statements with Examples
Introduction Introduction
"Is it raining ?""Is it raining ?"
"No" - Then lets play cricket."No" - Then lets play cricket.
"Yes" - Ohh, we cant play cricket."Yes" - Ohh, we cant play cricket.
Just like in real life, in programming also, we face situations where we need to make decisions
based on certain conditions.Just like in real life, in programming also, we face situations where
we need to make decisions based on certain conditions.
In Java, we use conditional statements to decide which part of the code should run depending on
the condition.In Java, we use conditional statements to decide which part of the code
should run depending on the condition.
Conditional Statments helps us to:Conditional Statments helps us to:
Control the flow of the program.Control the flow of the program.
Decide which block of code should be executed when certain conditions are met.Decide which
block of code should be executed when certain conditions are met.
Examples of Conditional Statements in Java:Examples of Conditional Statements in Java:
if: Runs code if a condition is true.if: Runs code if a condition is true.
if-else: Runs one block of code if true, and another block if false.if-else: Runs one block of code if
true, and another block if false.
if-else if ladder: Checks multiple conditions one by one and runs the block of code for the first
true condition.if-else if ladder: Checks multiple conditions one by one and runs the block of
code for the first true condition.
switch: Chooses a block of code to run based on specific cases.switch: Chooses a block of code to
run based on specific cases.
These are explained deeply as below:These are explained deeply as below:
"if-else if" Ladder Statement in Java "if-else if" Ladder Statement in Java
The if-else if ladder in Java evaluates multiple boolean conditions in sequence.The if-else
if ladder in Java evaluates multiple boolean conditions in sequence.
If any of the condition is true, the block of code associated with that condition is executed; if
none of the conditions are true, the optional else block runs.If any of the condition is true, the
block of code associated with that condition is executed; if none of the conditions are true, the
optional else block runs.
Syntax:Syntax:
if (condition1) if (condition1)
{{
// Code to execute if condition1 is true // Code to execute if condition1 is true
}}
else if (condition2)else if (condition2)
{{
// Code to execute if condition2 is true // Code to execute if condition2 is true
}}
// ---- more else-if blocks as needed ----// ---- more else-if blocks as needed ----
elseelse
{{
// Code to execute if none of the above conditions are true // Code to execute if none of the
above conditions are true
}}
Program:Program:
public class IfElseIfLadderExamplepublic class IfElseIfLadderExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
int marks = 75; int marks = 75;
// Determine the grade based on marks // Determine the grade based on marks
if (marks >= 90) if (marks >= 90)
{ {
System.out.println("Grade: A"); System.out.println("Grade: A");
} }
else if (marks >= 75) else if (marks >= 75)
{ {
System.out.println("Grade: B"); System.out.println("Grade: B");
} }
else if (marks >= 50) else if (marks >= 50)
{ {
System.out.println("Grade: C"); System.out.println("Grade: C");
} }
else else
{ {
System.out.println("Grade: F"); System.out.println("Grade: F");
} }
} }
}}
Output:Output:
Grade: BGrade: B
Introduction Introduction
Looping Statements are also know as "Iteration Statements".Looping Statements are also know
as "Iteration Statements".
Looping Statements allow us to repeat a block of code multiple times, making our programs
more efficient and reducing redundancy.Looping Statements allow us to repeat a block of
code multiple times, making our programs more efficient and reducing redundancy.
Loops are essential for handling repetitive tasks like:Loops are essential for handling
repetitive tasks like:
printing data multiple timesprinting data multiple times
executing tasks until a specific condition is metexecuting tasks until a specific condition is met
iterating through arraysiterating through arrays
and many more....and many more....
Examples of Looping Statements in Java:Examples of Looping Statements in Java:
for: Repeats a block of code a specific number of times.for: Repeats a block of code a specific
number of times.
while: Executes a block of code as long as a specified condition is true.while: Executes a block of
code as long as a specified condition is true.
do-while: Executes a block of code once, then repeats it as long as the condition is true.do-
while: Executes a block of code once, then repeats it as long as the condition is true.
for-each (Enhanced For Loop): Iterates over elements in an array or collection.for-
each (Enhanced For Loop): Iterates over elements in an array or collection.
These are explained deeply as below:These are explained deeply as below:
NOTE :NOTE :
If there is only one statement in for loop, then curly braces {} are optional.If there is only one
statement in for loop, then curly braces {} are optional.
Syntax :Syntax :
for(initialization; condition; increment/decrement)for(initialization; condition;
increment/decrement)
statement; statement;
Example :Example :
public class ForLoopExamplepublic class ForLoopExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
for (int i = 1; i <= 5; i++) for (int i = 1; i <= 5; i++)
System.out.println("Number: " + i); System.out.println("Number: " + i);
} }
}}
// Prompting user for a positive number // Prompting user for a positive number
do do
{ {
System.out.print("Enter a positive number: "); System.out.print("Enter a positive
number: ");
number = scanner.nextInt(); number = scanner.nextInt();
} while (number <= 0); } while (number <= 0);
"for-each" Loop (Enhanced For Loop) in Java "for-each" Loop (Enhanced For Loop) in Java
The for-each loop (also called Enhanced For Loop) in Java is used to iterate over elements in an
array or collection without needing an index variable.The for-each loop (also called Enhanced
For Loop) in Java is used to iterate over elements in an array or collection without needing
an index variable.
It's commonly used when we don’t need to know the index of the element and simply want to
process each element in the collection.It's commonly used when we don’t need to know the
index of the element and simply want to process each element in the collection.
Syntax:Syntax:
for (dataType variable : collection)for (dataType variable : collection)
{{
// statements (code to execute) // statements (code to execute)
}}
Below is syntax explanation:Below is syntax explanation:
dataType: Specifies the type of the elements in the collection
(e.g. int, String).dataType: Specifies the type of the elements in the collection (e.g. int, String).
variable: Represents each element in the collection during each iteration.variable: Represents
each element in the collection during each iteration.
collection: The array or collection (i.e. List, Set etc.) we want to iterate over.collection: The
array or collection (i.e. List, Set etc.) we want to iterate over.
NOTE : The for-each loop (enhanced for loop) in Java is primarily used with arrays and
collections, but it can also be used with any other Iterable objects also.NOTE : The for-each loop
(enhanced for loop) in Java is primarily used with arrays and collections, but it can also be used
with any other Iterable objects also.
Program:Program:
public class EnhancedForLoopExamplepublic class EnhancedForLoopExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
String[] fruits = {"Apple", "Banana", "Cherry"}; String[] fruits = {"Apple", "Banana",
"Cherry"};
// Using Enhanced For Loop (For-each loop) // Using Enhanced For Loop (For-each
loop)
for (String fruit : fruits) for (String fruit : fruits)
{ {
System.out.println(fruit); System.out.println(fruit);
} }
} }
}}
Output:Output:
AppleApple
BananaBanana
CherryCherry
Advantages:Advantages:
Simplifies code by removing the need to manually manage the loop index.Simplifies code by
removing the need to manually manage the loop index.
Suitable for iterating over arrays and collections.Suitable for iterating over arrays and
collections.
Helps avoid ArrayIndexOutOfBoundsException by iterating directly over elements.Helps
avoid ArrayIndexOutOfBoundsException by iterating directly over elements.
Introduction Introduction
Jump statements transfer the program's control from one part of the code to another, skipping
the lines in between.Jump statements transfer the program's control from one part of the
code to another, skipping the lines in between.
By default, Java programs execute statements line by line from top to bottom, but jump
statements allows us to:By default, Java programs execute statements line by line from top to
bottom, but jump statements allows us to:
Break the usual execution order (e.g., exit a loop early using break).Break the usual execution
order (e.g., exit a loop early using break).
Skip parts of the code (e.g., skip an iteration using continue).Skip parts of the code (e.g., skip an
iteration using continue).
Return control to the method caller (e.g., exit a method and optionally return a value
using return).Return control to the method caller (e.g., exit a method and optionally return a
value using return).
Examples of Jump Statements in Java:Examples of Jump Statements in Java:
break: Stops the loop completely when a condition is true.break: Stops the loop completely
when a condition is true.
continue: Skips the current loop step and moves to the next onecontinue: Skips the current loop
step and moves to the next one
return: Ends the method and sends a result back, if needed.return: Ends the method and sends
a result back, if needed.
These are explained deeply as below:These are explained deeply as below:
Syntax:Syntax:
return value; // For methods with return types, to send a value back.return value; // For
methods with return types, to send a value back.
return; // For void methods, to exit the method.return; // For void methods, to exit the method.
Program 1 (Using return in a method):Program 1 (Using return in a method):
public class ReturnExamplepublic class ReturnExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
System.out.println("Result: " + addNumbers(5, 3)); // Calling method
System.out.println("Result: " + addNumbers(5, 3)); // Calling method
} }
public static int addNumbers(int a, int b) public static int addNumbers(int a, int b)
{ {
int sum = a + b; int sum = a + b;
return sum; // Return the sum to the caller return sum; // Return the sum to the caller
} }
}}
Output:Output:
Result: 8Result: 8
Program 2 (Using return in a void method):Program 2 (Using return in a void method):
public class ReturnVoidExamplepublic class ReturnVoidExample
{{
public static void main(String[] args) public static void main(String[] args)
{ {
checkAge(16); // Testing with an age less than 18 checkAge(16); // Testing with an age
less than 18
// checkAge(20); // Testing with an age greater than or equal to 18 // checkAge(20); //
Testing with an age greater than or equal to 18
System.out.println("Voting Ended."); System.out.println("Voting Ended.");
} }
public static void checkAge(int age) public static void checkAge(int age)
{ {
if (age < 18) if (age < 18)
{ {
return; // Exits the method early if age is less than 18 return; // Exits the method
early if age is less than 18
} }
System.out.println("You can vote"); System.out.println("You can vote");
} }
}}
Output:Output:
Voting Ended.Voting Ended.
NOTE : After the return statement, no other statements can be written in that method because
the control has already been returned to the caller.NOTE : After the return statement, no other
statements can be written in that method because the control has already been returned to the
caller.
Real World Example of Class, Methods & Objects Real World Example of Class, Methods &
Objects
First lefts understand what is Class, Methods & Objects in real world, below are some
classesFirst lefts understand what is Class, Methods & Objects in real world, below are some
classes
A class is a template or blueprint used to categorize objects. For example, we can have classes
like Animal, Birds, Vehicles and Furniture. Each class can have multiple objects, which represent
real-world entities.A class is a template or blueprint used to categorize objects. For example, we
can have classes like Animal, Birds, Vehicles and Furniture. Each class can have
multiple objects, which represent real-world entities.
The Animal class can have objects such as elephant, tiger, dog etc.The Animal class can have
objects such as elephant, tiger, dog etc.
The Birds class can have objects like sparrow, peacock etc.The Birds class can have objects
like sparrow, peacock etc.
Similarly, other classes will have their respective objects.Similarly, other classes will have their
respective objects.
Every class has its own methods, which define the actions that objects can perform:Every class
has its own methods, which define the actions that objects can perform:
The Animal class may have methods like eat(), run(), sleep() etc.The Animal class may have
methods like eat(), run(), sleep() etc.
The Birds class may have methods like fly(), eat() etc.The Birds class may have methods
like fly(), eat() etc.
Since objects represent real-world entities, they are used to call methods and perform
actions.Since objects represent real-world entities, they are used to call methods and
perform actions.
//method //method
void run() void run()
{ {
//body //body
} }
}}
Advance Concept
If you want to read "Different types of classes in Java", then Advance Concept
If you want to read "Different types of classes in Java", then
Types of Java Classes Types of Java Classes
Program 1: Program 1:
Below is the simple program in which we have created one Animal1 class, one run() method and
called the run() method using jambo object.Below is the simple program in which we have
created one Animal1 class, one run() method and called the run() method using jambo object.
// Define a class named Animal1// Define a class named Animal1
public class Animal1 public class Animal1
{{
// Method to display a running message // Method to display a running message
public void run() public void run()
{ {
System.out.println("I'm running"); // Print a message to the console
System.out.println("I'm running"); // Print a message to the console
} }
// Main method - entry point of the program // Main method - entry point of the program
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an instance (object) of the Animal1 class // Create an instance (object) of the
Animal1 class
Animal1 jumbo = new Animal1(); Animal1 jumbo = new Animal1();
// Call the run method using the object 'jumbo' // Call the run method using the object
'jumbo'
jumbo.run(); jumbo.run();
} }
}}
Output:Output:
I'm runningI'm running
Program 2: Program 2:
Below is the simple program having one Animal2 class, two methods i.e. run() and eat() method
and jambo object is accessing both the methods.Below is the simple program having
one Animal2 class, two methods i.e. run() and eat() method and jambo object is accessing both
the methods.
// Define a class named Animal2// Define a class named Animal2
public class Animal2 public class Animal2
{{
// Method to display a running message // Method to display a running message
public void run() public void run()
{ {
System.out.println("I'm running"); // Print a message to the console
System.out.println("I'm running"); // Print a message to the console
} }
// Main method - entry point of the program // Main method - entry point of the program
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an instance (object) of the Animal2 class // Create an instance (object) of the
Animal2 class
Animal2 jumbo = new Animal2(); Animal2 jumbo = new Animal2();
// Call the run method using the object 'jumbo' // Call the run method using the object
'jumbo'
jumbo.run(); jumbo.run();
// Call the eat method using the object 'jumbo' // Call the eat method using the object
'jumbo'
jumbo.eat(); jumbo.eat();
} }
Program 3: Program 3:
Below is the simple program having one Animal3 class, two methods
i.e. run() and eat() methods. Then two objects i.e. jambo and buzo objects are accessing both the
methods.Below is the simple program having one Animal3 class, two methods
i.e. run() and eat() methods. Then two objects i.e. jambo and buzo objects are accessing both the
methods.
// Define a class named Animal3// Define a class named Animal3
public class Animal3 public class Animal3
{{
// Method to display a running message // Method to display a running message
public void run() public void run()
{ {
System.out.println("I'm running"); // Print a message indicating the animal is running
System.out.println("I'm running"); // Print a message indicating the animal is running
} }
// Main method - entry point of the program // Main method - entry point of the program
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an instance (object) of Animal3 named 'jumbo' // Create an instance (object)
of Animal3 named 'jumbo'
Animal3 jumbo = new Animal3(); Animal3 jumbo = new Animal3();
// Call the run method using the 'jumbo' object // Call the run method using the 'jumbo'
object
jumbo.run(); jumbo.run();
// Call the eat method using the 'jumbo' object // Call the eat method using the 'jumbo'
object
jumbo.eat(); jumbo.eat();
// Create another instance (object) of Animal3 named 'buzo' // Create another instance
(object) of Animal3 named 'buzo'
Animal3 buzo = new Animal3(); Animal3 buzo = new Animal3();
// Call the eat method using the 'buzo' object // Call the eat method using the 'buzo'
object
buzo.eat(); buzo.eat();
// Call the run method using the 'buzo' object // Call the run method using the 'buzo'
object
buzo.run(); buzo.run();
} }
Program 4: Program 4:
Below is the another program with parameters in methods.Below is the another program with
parameters in methods.
// Define a class named Animal4// Define a class named Animal4
public class Animal4 public class Animal4
{{
// Method to display that an animal is running // Method to display that an animal is
running
public void run(String name) public void run(String name)
{ {
System.out.println(name + " is running"); System.out.println(name + " is running");
} }
// Main method - program entry point // Main method - program entry point
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an object 'jumbo' of Animal4 // Create an object 'jumbo' of Animal4
Animal4 jumbo = new Animal4(); Animal4 jumbo = new Animal4();
jumbo.run("Jumbo"); // Call run method with "Jumbo" jumbo.run("Jumbo"); // Call run
method with "Jumbo"
jumbo.eat("Jumbo"); // Call eat method with "Jumbo" jumbo.eat("Jumbo"); // Call eat
method with "Jumbo"
// Create another object 'buzo' of Animal4 // Create another object 'buzo' of Animal4
Animal4 buzo = new Animal4(); Animal4 buzo = new Animal4();
buzo.eat("Buzo"); // Call eat method with "Buzo" buzo.eat("Buzo"); // Call eat method
with "Buzo"
buzo.run("Buzo"); // Call run method with "Buzo" buzo.run("Buzo"); // Call run method
with "Buzo"
} }
// Method to display that an animal is eating // Method to display that an animal is eating
public void eat(String name) public void eat(String name)
{ {
System.out.println(name + " is eating...!!"); System.out.println(name + " is eating...!!");
} }
}}
Output:Output:
Jumbo is runningJumbo is running
Jumbo is eating...!!Jumbo is eating...!!
Buzo is eating...!!Buzo is eating...!!
Buzo is runningBuzo is running
Program 5: Program 5:
Below is the another program with multiple parameters in methods.Below is the another
program with multiple parameters in methods.
// Define a class named Animal5// Define a class named Animal5
public class Animal5 public class Animal5
{{
// Method to display that an animal has run a certain distance // Method to display that an
animal has run a certain distance
public void run(String name, int distance_km) public void run(String name, int distance_km)
{ {
System.out.println(name + " has run " + distance_km + " km"); System.out.println(name
+ " has run " + distance_km + " km");
} }
// Main method - program entry point // Main method - program entry point
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an object 'jumbo' of Animal5 // Create an object 'jumbo' of Animal5
Animal5 jumbo = new Animal5(); Animal5 jumbo = new Animal5();
jumbo.run("Jumbo", 5); // Call run method with name "Jumbo" and distance 5 km
jumbo.run("Jumbo", 5); // Call run method with name "Jumbo" and distance 5 km
jumbo.eat("Jumbo", "grass"); // Call eat method with name "Jumbo" and food "grass"
jumbo.eat("Jumbo", "grass"); // Call eat method with name "Jumbo" and food "grass"
// Create another object 'buzo' of Animal5 // Create another object 'buzo' of Animal5
Animal5 buzo = new Animal5(); Animal5 buzo = new Animal5();
buzo.eat("Buzo", "meat"); // Call eat method with name "Buzo" and food "meat"
buzo.eat("Buzo", "meat"); // Call eat method with name "Buzo" and food "meat"
buzo.run("Buzo", 12); // Call run method with name "Buzo" and distance 12 km
buzo.run("Buzo", 12); // Call run method with name "Buzo" and distance 12 km
} }
// Method to display that an animal is eating a specific dish // Method to display that an
animal is eating a specific dish
public void eat(String name, String dish) public void eat(String name, String dish)
{ {
System.out.println(name + " is eating " + dish); System.out.println(name + " is eating " +
dish);
} }
}}
Output:Output:
Jumbo has run 5 km Jumbo has run 5 km
Jumbo is eating grass Jumbo is eating grass
Buzo is eating meat Buzo is eating meat
Buzo has run 12 kmBuzo has run 12 km
Program 6: Program 6:
Below is the another program with instance variables and method parameter.Below is the
another program with instance variables and method parameter.
// Define a class named Animal6// Define a class named Animal6
public class Animal6 public class Animal6
{{
// Declare instance variables // Declare instance variables
int no_of_eyes; // Variable to store the number of eyes int no_of_eyes; // Variable to store
the number of eyes
String color; // Variable to store the color of the animal String color; // Variable to store the
color of the animal
// Method to display the details of an animal // Method to display the details of an animal
public void details(String name) public void details(String name)
{ {
System.out.println("-------Details of " + name + "-------"); System.out.println("-------
Details of " + name + "-------");
System.out.println("Eyes : " + no_of_eyes); System.out.println("Eyes : " + no_of_eyes);
System.out.println("Color : " + color); System.out.println("Color : " + color);
} }
// Main method - program entry point // Main method - program entry point
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an object 'jumbo' of Animal6 and assign values // Create an object 'jumbo' of
Animal6 and assign values
Animal6 jumbo = new Animal6(); Animal6 jumbo = new Animal6();
jumbo.no_of_eyes = 2; jumbo.no_of_eyes = 2;
jumbo.color = "Brown"; jumbo.color = "Brown";
jumbo.details("Jumbo"); // Call details method for 'jumbo' jumbo.details("Jumbo"); //
Call details method for 'jumbo'
// Create another object 'buzo' of Animal6 and assign values // Create another object
'buzo' of Animal6 and assign values
Animal6 buzo = new Animal6(); Animal6 buzo = new Animal6();
buzo.no_of_eyes = 2; buzo.no_of_eyes = 2;
buzo.color = "Black"; buzo.color = "Black";
buzo.details("Buzo"); // Call details method for 'buzo' buzo.details("Buzo"); // Call
details method for 'buzo'
} }
}}
Output:Output:
-------Details of Jumbo--------------Details of Jumbo-------
Eyes : 2Eyes : 2
Color : BrownColor : Brown
-------Details of Buzo--------------Details of Buzo-------
Eyes : 2Eyes : 2
Color : BlackColor : Black
// Define the main class MainApp7// Define the main class MainApp7
public class MainApp7 public class MainApp7
{{
// Main method - program entry point // Main method - program entry point
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an object 'buzo' of Animal7 // Create an object 'buzo' of Animal7
Animal7 buzo = new Animal7(); Animal7 buzo = new Animal7();
buzo.run(); // Call the run method buzo.run(); // Call the run method
} }
}}
Output:Output:
I'm runningI'm running
// Define the main class MainApp8// Define the main class MainApp8
public class MainApp8 public class MainApp8
{{
// Main method - program entry point // Main method - program entry point
public static void main(String[] args) public static void main(String[] args)
{ {
// Create an object 'buzo' of Animal8 and call the run method // Create an object 'buzo'
of Animal8 and call the run method
Animal8 buzo = new Animal8(); Animal8 buzo = new Animal8();
buzo.run(); buzo.run();
// Create an object 'sparrow' of Birds8 and call the fly method // Create an object
'sparrow' of Birds8 and call the fly method
Birds8 sparrow = new Birds8(); Birds8 sparrow = new Birds8();
sparrow.fly(); sparrow.fly();
} }
}}
Output:Output:
I'm runningI'm running
I'm flyingI'm flying
public static void main(String[] args) public static void main(String[] args)
{ {
Test t = new Test(); //default constructor called automatically when we create object
Test t = new Test(); //default constructor called automatically when we create object
} }
} }
Some important points for Default Constructor:Some important points for Default Constructor:
The access modifier of Default Constructor is as that of class. If a class is public, the default
constructor is public and so on.The access modifier of Default Constructor is as that of class. If a
class is public, the default constructor is public and so on.
Default Constructor has no parameters.Default Constructor has no parameters.
Default Constructor calls the superclass constructor (super()).Default Constructor calls the
superclass constructor (super()).
public Test()public Test()
{{
super(); super();
} }
public static void main(String[] args) public static void main(String[] args)
{ {
Student s1 = new Student(); // Calls no-argument constructor Student s1 = new
Student(); // Calls no-argument constructor
s1.display(); // Output: Student Name: Deepak s1.display(); // Output: Student Name:
Deepak
} }
} }
3. Parameterized Constructor:3. Parameterized Constructor:
If a programmer creates the constructor with parameters, then it is known as Parameterized
Constructor.If a programmer creates the constructor with parameters, then it is known as
Parameterized Constructor.
It is used to:It is used to:
Initialize objects with specific values instead of default values.Initialize objects with specific
values instead of default values.
Avoid the need for setter methods after object creation.Avoid the need for setter methods after
object creation.
Improve code readability by directly assigning values through the constructor.Improve code
readability by directly assigning values through the constructor.
Syntax :Syntax :
class ClassNameclass ClassName
{{
ClassName(dataType parameter1, dataType parameter2) ClassName(dataType parameter1,
dataType parameter2)
{ {
// Initialization code // Initialization code
} }
}}
Example :Example :
class Studentclass Student
{{
String name; String name;
int rollno; int rollno;
public static void main(String[] args) public static void main(String[] args)
{ {
Student s1 = new Student("Deepak", 101); // Passing values Student s1 = new
Student("Deepak", 101); // Passing values
s1.display(); // Output: Name: Deepak, Roll No.: 101 s1.display(); // Output: Name:
Deepak, Roll No.: 101
} }
}}
Introduction Introduction
Relationship between classes describes that how multiple classes interact with or depend on
each other.Relationship between classes describes that how multiple classes interact with or
depend on each other.
These relationships help structure and organize code in a logical and maintainable way.These
relationships help structure and organize code in a logical and maintainable way.
Types of relationships between classes in Java:Types of relationships between classes in Java:
Association (HAS-A relationship)Association (HAS-A relationship)
Dependency (USES-A relationship)Dependency (USES-A relationship)
Inheritance (IS-A relationship)Inheritance (IS-A relationship)
// Setter Injection: Injecting dependency through setter method // Setter Injection: Injecting
dependency through setter method
public void setProcessor(Processor processor) public void setProcessor(Processor
processor)
{ {
this.processor = processor; this.processor = processor;
} }
// Inject the dependency using setter // Inject the dependency using setter
myLaptop.setProcessor(processor); myLaptop.setProcessor(processor);
// Main class that uses Whiteboard// Main class that uses Whiteboard
class Teacherclass Teacher
{{
void teachLesson() void teachLesson()
{ {
// Local variable: Dependency created inside the method // Local variable: Dependency
created inside the method
Whiteboard board = new Whiteboard(); Whiteboard board = new Whiteboard();
board.writeOnBoard(); // Temporary usage board.writeOnBoard(); // Temporary
usage
System.out.println("Teacher is explaining the topic."); System.out.println("Teacher is
explaining the topic.");
} }
}}
// Main class that depends on Printer// Main class that depends on Printer
class OfficeWorkerclass OfficeWorker
{{
// Dependency injected via method parameter // Dependency injected via method
parameter
void performTask(Printer printer) void performTask(Printer printer)
{ {
printer.printDocument(); // Temporary usage printer.printDocument(); // Temporary
usage
System.out.println("OfficeWorker has completed printing task.");
System.out.println("OfficeWorker has completed printing task.");
} }
}}
// Inject dependency via method parameter // Inject dependency via method parameter
worker.performTask(printer); worker.performTask(printer);
} }
}}
Output:Output:
Printing document...Printing document...
OfficeWorker has completed printing task.OfficeWorker has completed printing task.
Introduction Introduction
Inheritance means acquiring the properties and behaviors of a parent class in a child
class.Inheritance means acquiring the properties and behaviors of a parent class in a child class.
It allows a subclass (child class) to inherit fields and methods from a superclass (parent class),
promoting code reuse and method overriding.It allows a subclass (child class) to inherit fields
and methods from a superclass (parent class), promoting code reuse and method overriding.
Inheritance represents an IS-A relationship, also known as a parent-child relationship. It
signifies that a subclass is a type of its superclass.Inheritance represents an IS-A relationship,
also known as a parent-child relationship. It signifies that a subclass is a type of its superclass.
For example:For example:
A Car IS-A Vehicle.A Car IS-A Vehicle.
A Dog IS-A Animal.A Dog IS-A Animal.
A Surgeon IS-A Doctor.A Surgeon IS-A Doctor.
How to achieve inheritance in Java?How to achieve inheritance in Java?
By using the extends keyword for class inheritance.By using the extends keyword for class
inheritance.
By using the implements keyword for interface inheritance.By using the implements keyword
for interface inheritance.
Program 1 (using extends keyword): :Program 1 (using extends keyword): :
class Vehicleclass Vehicle
{{
void start() void start()
{ {
System.out.println("Vehicle starts."); System.out.println("Vehicle starts.");
} }
}}
Introduction Introduction
in Java means one class can use the properties (like variables and methods) of another class. in
Java means one class can use the properties (like variables and methods) of another class.
It is the fundamental concept of OOP's which helps to reuse code.It is the fundamental concept
of OOP's which helps to reuse code.
It creates a parent-child relationship, where the parent is called the superclass and the child is
called the subclass.It creates a parent-child relationship, where the parent is called
the superclass and the child is called the subclass.
to read more about . to read more about .
There are 5 types of Inheritance in Java:There are 5 types of Inheritance in Java:
Single InheritanceSingle Inheritance
Multilevel InheritanceMultilevel Inheritance
Hierarchical InheritanceHierarchical Inheritance
Multiple Inheritance (not supported directly)Multiple Inheritance (not supported directly)
Hybrid Inheritance (not supported directly)Hybrid Inheritance (not supported directly)
interface Binterface B
{{
void methodB(); void methodB();
}}
class Cclass C
{{
void methodC() void methodC()
{ {
System.out.println("Method from class C"); System.out.println("Method from class C");
} }
}}
// Class D inherits class C and implements A and B// Class D inherits class C and implements A
and B
class D extends C implements A, Bclass D extends C implements A, B
{{
public void methodA() public void methodA()
{ {
System.out.println("Method from interface A"); System.out.println("Method from
interface A");
} }
Program example (using interfaces and class):Program example (using interfaces and class):
// Interface A// Interface A
interface Ainterface A
{{
void showA(); void showA();
}}
// Interface B// Interface B
interface Binterface B
{{
void showB(); void showB();
}}
// Class D: extends C and implements A and B// Class D: extends C and implements A and B
class D extends C implements A, Bclass D extends C implements A, B
{{
public void showA() public void showA()
{ {
System.out.println("Show from interface A"); System.out.println("Show from interface
A");
} }
Introduction Introduction
Polymorphism is one of the main concepts of Object-Oriented Programming (OOP) in
Java.Polymorphism is one of the main concepts of Object-Oriented Programming (OOP) in Java.
Poly → many, Morph → forms; so Polymorphism means "many forms".Poly → many, Morph →
forms; so Polymorphism means "many forms".
It means the ability of a single entity (method, object, or operator) to behave in multiple ways.It
means the ability of a single entity (method, object, or operator) to behave in multiple ways.
Java uses polymorphism to let us write flexible and reusable code.Java uses polymorphism to let
us write flexible and reusable code.
Real-world Examples :-Real-world Examples :-
A person: acts as a teacher, father, son — different roles.A person: acts as a teacher, father, son
— different roles.
Water: takes shape of the container it’s in.Water: takes shape of the container it’s in.
Sound: same sound word used in different tones.Sound: same sound word used in different
tones.
Advantage of Polymorphism :-Advantage of Polymorphism :-
Increases flexibility and reusability.Increases flexibility and reusability.
Allows code extensibility without modifying existing code.Allows code extensibility without
modifying existing code.
Supports single task, multiple implementations.Supports single task, multiple
implementations.
Enhances maintainability and scalability.Enhances maintainability and scalability.
Types of Polymorphism in Java :- Types of Polymorphism in Java :-
Compile-Time PolymorphismCompile-Time Polymorphism
It is also known as Static Binding or Early Binding.It is also known as Static Binding or Early
Binding.
It is achieved by Method Overloading or Operator Overloading.It is achieved by Method
Overloading or Operator Overloading.
In compile-time polymorphism, the Java compiler decides at compile time which overloaded
method or operator to invoke based on the method signature and reference type.In compile-
time polymorphism, the Java compiler decides at compile time which overloaded
method or operator to invoke based on the method signature and reference type.
Program ():Program ():
class Calculatorclass Calculator
{{
void add(int a, int b) void add(int a, int b)
{ {
System.out.println(a+b); System.out.println(a+b);
} }
Introduction Introduction
Method Overloading is a way (or mechanism or form) to achieve compile-time
polymorphismMethod Overloading is a way (or mechanism or form) to achieve compile-time
polymorphism
It is a feature in Java that allows a class to have more than one method with the same name, but
different parameters (number, type, or order of parameters).It is a feature in Java that allows a
class to have more than one method with the same name, but different
parameters (number, type, or order of parameters).
The compiler determines which method to execute at compile time, based on the method
signature.The compiler determines which method to execute at compile time, based on the
method signature.
Rules of Method Overloading :-Rules of Method Overloading :-
All overloaded methods must have the same name.All overloaded methods must have the same
name.
All the methods should be in same class or in subclass.All the methods should be in same class or
in subclass.
All the method parameters list must be different:All the method parameters list must be different:
Number of parametersNumber of parameters
Type of parametersType of parameters
Order of parametersOrder of parameters
Example :-Example :-
class Calculatorclass Calculator
{{
int add(int a, int b) int add(int a, int b)
{ {
return a + b; return a + b;
} }
Introduction Introduction
Method Overriding is a way (or mechanism or form) to achieve runtime polymorphismMethod
Overriding is a way (or mechanism or form) to achieve runtime polymorphism
It is a feature in Java that allows the child class to write its own implementation of a method that
is already present in the parent class.It is a feature in Java that allows the child class to write its
own implementation of a method that is already present in the parent class.
The JVM determines which method to execute at runtime, based on the object type (not the
reference type).The JVM determines which method to execute at runtime, based on the object
type (not the reference type).
Rules of Method Overriding :-Rules of Method Overriding :-
The methods must have the same name.The methods must have the same name.
The method must be in different class or in subclass.The method must be in different class or in
subclass.
All the method parameters list must be same:All the method parameters list must be same:
Number of parametersNumber of parameters
Type of parametersType of parameters
Order of parametersOrder of parameters
Should follow IS-A relationship (Inheritance).Should follow IS-A relationship (Inheritance).
Example :-Example :-
class Bankclass Bank
{{
double getInterestRate() double getInterestRate()
{ {
return 0.0; return 0.0;
} }
}}
Static methods, constructors, and the main method cannot be overridden.Static methods,
constructors, and the main method cannot be overridden.
Methods marked as final, static, or private cannot be overridden.Methods marked as final,
static, or private cannot be overridden.
The overriding method can throw only the same or narrower checked exceptions than the
overridden method.The overriding method can throw only the same or narrower checked
exceptions than the overridden method.
The @Override annotation is recommended to avoid mistakes and improve code
readability.The @Override annotation is recommended to avoid mistakes and improve code
readability.
@Override@Override
void methodName() {void methodName() {
// implementation // implementation
}}
Introduction Introduction
Abstraction is a concept of :Abstraction is a concept of :
hiding internal implementation details and showing only the essential features to the
user.hiding internal implementation details and showing only the essential features to the
user.
Real World ExampleReal World Example
When you drive a car, you only need to know how to operate the steering wheel, pedals and gear
shift. You don't need to understand how the engine works or how the brakes are designed.When
you drive a car, you only need to know how to operate the steering wheel, pedals and gear shift.
You don't need to understand how the engine works or how the brakes are designed.
// Main class to run the program// Main class to run the program
public class MainApppublic class MainApp
{{
public static void main(String[] args) public static void main(String[] args)
{ {
Car myCar = new Car(); Car myCar = new Car();
myCar.displayTyres(); myCar.displayTyres();
myCar.start(); myCar.start();
System.out.println(); System.out.println();
// Car class extends abstract class and provides its own implementation// Car class extends
abstract class and provides its own implementation
class Car extends Vehicleclass Car extends Vehicle
{{
Car() Car()
{ {
no_of_tyres = 4; no_of_tyres = 4;
} }
// Scooter class also extends abstract class// Scooter class also extends abstract class
class Scooter extends Vehicleclass Scooter extends Vehicle
{{
Scooter() Scooter()
{ {
no_of_tyres = 2; no_of_tyres = 2;
} }
@Override @Override
void start() void start()
{ {
System.out.println("Scooter starts with kick or self-start."); System.out.println("Scooter
starts with kick or self-start.");
} }
}}
// Main class to test polymorphism and abstraction// Main class to test polymorphism and
abstraction
public class Mainpublic class Main
{{
public static void main(String[] args) public static void main(String[] args)
{ {
// Using polymorphism (removes disadvantage #1) // Using polymorphism (removes
disadvantage #1)
Vehicle myVehicle1 = new Car(); Vehicle myVehicle1 = new Car();
myVehicle1.displayTyres(); myVehicle1.displayTyres();
myVehicle1.start(); myVehicle1.start();
System.out.println(); System.out.println();
// Easier to scale and add new vehicle types consistently (removes disadvantage #4) //
Easier to scale and add new vehicle types consistently (removes disadvantage #4)
} }
}}
Output:Output:
This vehicle has 4 tyres.This vehicle has 4 tyres.
Car starts with key ignition.Car starts with key ignition.
Introduction Introduction
An interface in Java is a blueprint of a class, containing only method signatures (no
implementations) and constants.An interface in Java is a blueprint of a class, containing only
method signatures (no implementations) and constants.
Interfaces are similar to abstract class but having all the methods of abstract type.Interfaces are
similar to abstract class but having all the methods of abstract type.
Note :Note :
Till Java 7, interfaces can contain only abstract methods and constants.Till Java 7, interfaces can
contain only abstract methods and constants.
In Java 8, we can provide the implementation of methods using default methods and static
methods.In Java 8, we can provide the implementation of methods using default
methods and static methods.
In Java 9, we can provide the implementation of methods using private methods.In Java 9, we
can provide the implementation of methods using private methods.
Syntax :-Syntax :-
interface InterfaceNameinterface InterfaceName
{{
// public static final variables (constants) // public static final variables
(constants)
// public abstract methods // public abstract methods
}}
// Car class implements the interface// Car class implements the interface
class Car implements Vehicleclass Car implements Vehicle
{{
public void start() public void start()
{ {
System.out.println("Car is starting..."); System.out.println("Car is starting...");
} }
p1.print(); p1.print();
p2.print(); p2.print();
} }
}}
Output:Output:
Printing document...Printing document...
Printing image...Printing image...
3. Used to achieve multiple inheritance in Java.3. Used to achieve multiple inheritance in
Java.
Example:Example:
interface I1interface I1
{{
void m1(); void m1();
}}
interface I2interface I2
{{
void m2(); void m2();
}}
// Checkout class using interface (not tightly bound to any one payment method)// Checkout
class using interface (not tightly bound to any one payment method)
class PaymentCheckoutclass PaymentCheckout
{{
void payment(Payment payment) void payment(Payment payment)
{ {
payment.pay(); // Loose coupling: works with any class that implements Payment
payment.pay(); // Loose coupling: works with any class that implements Payment
} }
}}
Introduction Introduction
Encapsulation is the mechanism of binding data (variables) and actions (methods) into a single
unit, called a class.Encapsulation is the mechanism of binding data (variables) and actions
(methods) into a single unit, called a class.
Technically, every class is an example of encapsulation.Technically, every class is an example of
encapsulation.
Real World Example:Real World Example:
A car is in which engine, wheels, and other parts are encapsulated.A car is in which engine,
wheels, and other parts are encapsulated.
Java Program Example:Java Program Example:
class Carclass Car
{{
// Data members (variables) // Data members (variables)
String brand; String brand;
int speed; int speed;
// ✅ Public getter (controlled access to private data) // ✅ Public getter (controlled access to
private data)
public String getAccountHolder() public String getAccountHolder()
{ {
return accountHolder; return accountHolder;
} }
// ✅ Public setter (controlled access with flexibility for future validation) // ✅ Public setter
(controlled access with flexibility for future validation)
public void setAccountHolder(String accountHolder) public void setAccountHolder(String
accountHolder)
{ {
this.accountHolder = accountHolder; this.accountHolder = accountHolder;
} }
// 🚫 Cannot access private fields directly // 🚫 Cannot access private fields directly
// account.balance = 10000; // ❌ Not allowed (Encapsulation) // account.balance =
10000; // ❌ Not allowed (Encapsulation)
// ✅ Uses public setters and methods // ✅ Uses public setters and methods
account.setAccountHolder("Deepak"); account.setAccountHolder("Deepak");
// ✅ Proper access via methods ensures validation // ✅ Proper access via methods
ensures validation
account.deposit(10000); // Valid deposit account.deposit(10000); // Valid deposit
account.withdraw(3000); // Valid withdrawal account.withdraw(3000); // Valid
withdrawal