Java College Notes

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 631

BASICS OF JAVA

Java is an object-oriented programming language


developed by Sun Micro-Systems in USA in 1971 .
It was called originally Oak by James Goslin the
developer of java . JAVA is a purely object oriented
programming language. The code written by us in
the machine is first converted into the byte code
by the java compiler(javac) and then it is
interpreted into the machine code.

SOURCE --------> BYTECODE -----------> MACHINE


CODE
CODE

INSTALLATION IN JAVA

JDK : - To run our java code we need to install a


Java Development Kit which is a collection of tools
used for developing and running java programs .

CODE EDITOR : - To write our java code we need


a place to write a code where it can be viewed and
then sent later on for execution .

JRE : - Java Runtime Environment helps us to


execute our programs developed in Java.

HELLO WORLD PROGRAM

public class HELLOWORLD {


public static void main(String[] args) {
System.out.println("Hello World");
}
}
EXPLANATION OF ABOVE CODE

package com.company;
public class Main{
public static void main(String args[]){
System.out.println(“Hello World”);
}
}

Here com.company package means that the java


program is stored in the folder com which has a file
named company in it .

The main function is here as existent which


basically means that it is the entry point to every
program in a java program .

The System.out.println is used to give the output in


the java as in any format .

CLASSES : - A class in java is a set of objects


which shares common characteristics/behaviour
and common properties/attributes . It is a user
defined blueprint/prototype from which objects are
created . For - Example: Student is a class while
a particular student named Ravi is an object .

PROPERTIES OF CLASSES : -

1. Class is not a real world entity. It is just a


template or blueprint using which the objects
are created .

2. Classes do not occupy memory.


3. Class is a group of variables of different data
types and a group of methods.

4. A class in a java can contain:


 Data Member
 Methods
 Constructor
 Nested class
 Interface

NAMING CONVENCTIONS IN JAVA

 For classes we do use Pascal Convention


i.e. the first letter of every word is capital
letter .
 For functions we do use Camel Case
Convention i.e. first letter of every word is
capital letter apart from the first letter and
no spaces allowed in both of them .

COMMENTS IN JAVA

Comments in java is a way of writing the notes in


java and is used to hide the text from the compiler
in java. The code written in the comments is
ignored by the compiler and is never executed .

Comments can be classified into two types. They


are :

1. SINGLE - LINE COMMENTS : - These


comments are used to comment down a single
line in java and cannot be used to comment
multiple lines in java . It is written as // .
2. MULTI-LINE COMMENTS : - These comments
are used to comment multiple lines in java at
the same time . This is denoted by /* */ .

VARIABLES AND DATATYPES IN JAVA

Variables are like a container of some specific data


type which can hold some value in it .

A Data type is defined for a variable and defines


the type of the data one can store in a particular
variable . Datatypes can be of many types such
as : -

I. PRIMITIVE DATATYPES : -

 Int(stores integral values in range of -


2147483648 to 2147483647)(4 bytes)
 Long(stores integral values in the range of -
9223372036854775808 to
9223372036854775807)(8 bytes)
 Double(stores decimal values in range of 15
decimal digits)(8 bytes)
 Short(stores integral values in range of -32768
to 32767)(2 bytes)
 Bool(stores the values as true or false)(1 bit)
 Char(stores a single character or an ASCII value)
(2 bytes)
 Float(stores fractional values from in range of 6
to 7 digits)(4 bytes)
 Byte(stores integral values in rane of -128 to
127)(1 byte)
II. NON PRIMITIVE DATATYPES : - It consists of
objects classes and many other datatypes like
strings arrays etc .
RULES FOR DECLARING VARIABLES

1. Must not begin with an integer or digit .


2. Name is case sensitive.
3. Should not be a keyword(like void).
4. White space is not allowed .
5. Can contain alphabets and characters like $ and
_ if only all the other conditions are met .

WRITE A JAVA PROGRAM TO ADD THREE


NUMBERS

public class HELLOWORLD {


public static void main(String[] args) {
int a = 411;
int b = 343;
int c = 422;
int sum = a+b+c;
System.out.println(sum);
}
}

LITERALS

Literals are the constant values that we can assign


to the variables are called as Literals .

For a float literal we do place a ‘f’ after it to specify


it as float else it is taken as a double .

For a long literal we do place a ‘l’ after it to specify


it as long .
For a char literal we do place a ‘ ’ surrounding our
literal to specify it as a character .
For a String literal we do place a “ “ surrounding
our literal to specify it as a String of characters.

KEYWORDS

Keywords are reserved words in java that is used


to by the java compiler and cannot be used as a
identifier.

There are many keyword in java . They are : -

abstract continue for new switch

assert*** default goto* package synchronized

boolean do if private this

break double implements protected throw

byte else import public throws

case enum**** instanceof return transient

catch extends int short try

char final interface static void

class finally long strictfp** volatile

const* float native super while


INPUTS FROM THE USER

In order to take the data as an input from the


keyboard we do use a Scanner class in java to do
so . Scanner class has a lot number of methods to
take the inputs from the users throug the keyboard
.

Scanner class in Java is found in the java.util


package. Java provides various ways to read input
from the keyboard, the java.util.Scanner class is
one of them.

The Java Scanner class breaks the input into tokens


using a delimiter which is whitespace by default. It
provides many methods to read and parse various
primitive values.

The Java Scanner class is widely used to parse text


for strings and primitive types using a regular
expression. It is the simplest way to get input in
Java. By the help of Scanner in Java, we can get
input from the user in primitive types such as int,
long, double, byte, float, short, etc.

The Java Scanner class extends Object class and


implements Iterator and Closeable interfaces.

The Java Scanner class provides nextXXX()


methods to return the type of value such as
nextInt(), nextByte(), nextShort(), next(),
nextLine(), nextDouble(), nextFloat(),
nextBoolean(), etc. To get a single character from
the scanner, you can call next().charAt(0) method
which returns a single character.
Java Scanner Class Declaration

1. public final class Scanner


2. extends Object
3. implements Iterator<String>

How to get Java Scanner

To get the instance of Java Scanner which reads


input from the user, we need to pass the input
stream (System.in) in the constructor of Scanner
class. For Example:

1. Scanner in = new Scanner(System.in);

To get the instance of Java Scanner which parses


the strings, we need to pass the strings in the
constructor of Scanner class. For Example:

1. Scanner in = new Scanner("Hello Javatpoint");

Java Scanner Class Constructors

S Constructor Description
N
1) Scanner(File It constructs a new Scanner that
source) produces values scanned from the
specified file.
2) Scanner(File It constructs a new Scanner that
source, String produces values scanned from the
charsetName) specified file.
3) Scanner(InputStrea It constructs a new Scanner that
m source) produces values scanned from the
specified input stream.
4) Scanner(InputStrea It constructs a new Scanner that
m source, String produces values scanned from the
charsetName) specified input stream.
5) Scanner(Readable It constructs a new Scanner that
source) produces values scanned from the
specified source.
6) Scanner(String It constructs a new Scanner that
source) produces values scanned from the
specified string.
7) Scanner(Readable It constructs a new Scanner that
ByteChannel produces values scanned from the
source) specified channel.
8) Scanner(Readable It constructs a new Scanner that
ByteChannel produces values scanned from the
source, String specified channel.
charsetName)
9) Scanner(Path It constructs a new Scanner that
source) produces values scanned from the
specified file.
10 Scanner(Path It constructs a new Scanner that
) source, String produces values scanned from the
charsetName) specified file.

Java Scanner Class Methods

The following are the list of Scanner methods:

S Modifier & Method Description


N Type
1) void close() It is used to close this scanner.
2) pattern delimiter() It is used to get the Pattern
which the Scanner class is
currently using to match
delimiters.
3) Stream<M findAll() It is used to find a stream of
atchResult match results that match the
> provided pattern string.
4) String findInLine() It is used to find the next
occurrence of a pattern
constructed from the specified
string, ignoring delimiters.
5) string findWithinH It is used to find the next
orizon() occurrence of a pattern
constructed from the specified
string, ignoring delimiters.
6) boolean hasNext() It returns true if this scanner
has another token in its input.
7) boolean hasNextBig It is used to check if the next
Decimal() token in this scanner's input
can be interpreted as a
BigDecimal using the
nextBigDecimal() method or
not.
8) boolean hasNextBigI It is used to check if the next
nteger() token in this scanner's input
can be interpreted as a
BigDecimal using the
nextBigDecimal() method or
not.
9) boolean hasNextBoo It is used to check if the next
lean() token in this scanner's input
can be interpreted as a
Boolean using the
nextBoolean() method or not.
10) boolean hasNextByt It is used to check if the next
e() token in this scanner's input
can be interpreted as a Byte
using the nextBigDecimal()
method or not.
11) boolean hasNextDo It is used to check if the next
uble() token in this scanner's input
can be interpreted as a
BigDecimal using the
nextByte() method or not.
12) boolean hasNextFlo It is used to check if the next
at() token in this scanner's input
can be interpreted as a Float
using the nextFloat() method
or not.
13) boolean hasNextInt( It is used to check if the next
) token in this scanner's input
can be interpreted as an int
using the nextInt() method or
not.
14) boolean hasNextLin It is used to check if there is
e() another line in the input of this
scanner or not.
15) boolean hasNextLon It is used to check if the next
g() token in this scanner's input
can be interpreted as a Long
using the nextLong() method
or not.
16) boolean hasNextSho It is used to check if the next
rt() token in this scanner's input
can be interpreted as a Short
using the nextShort() method
or not.
17) IOExceptio ioException It is used to get the
n () IOException last thrown by this
Scanner's readable.
18) Locale locale() It is used to get a Locale of the
Scanner class.
19) MatchResu match() It is used to get the match
lt result of the last scanning
operation performed by this
scanner.
20) String next() It is used to get the next
complete token from the
scanner which is in use.
21) BigDecimal nextBigDeci It scans the next token of the
mal() input as a BigDecimal.
22) BigInteger nextBigInte It scans the next token of the
ger() input as a BigInteger.
23) boolean nextBoolea It scans the next token of the
n() input into a boolean value and
returns that value.
24) byte nextByte() It scans the next token of the
input as a byte.
25) double nextDouble It scans the next token of the
() input as a double.
26) float nextFloat() It scans the next token of the
input as a float.
27) int nextInt() It scans the next token of the
input as an Int.
28) String nextLine() It is used to get the input string
that was skipped of the
Scanner object.
29) long nextLong() It scans the next token of the
input as a long.
30) short nextShort() It scans the next token of the
input as a short.
31) int radix() It is used to get the default
radix of the Scanner use.
32) void remove() It is used when remove
operation is not supported by
this implementation of Iterator.
33) Scanner reset() It is used to reset the Scanner
which is in use.
34) Scanner skip() It skips input that matches the
specified pattern, ignoring
delimiters
35) Stream<St tokens() It is used to get a stream of
ring> delimiter-separated tokens
from the Scanner object which
is in use.
36) String toString() It is used to get the string
representation of Scanner
using.
37) Scanner useDelimite It is used to set the delimiting
r() pattern of the Scanner which is
in use to the specified pattern.
38) Scanner useLocale() It is used to sets this scanner's
locale object to the specified
locale.
39) Scanner useRadix() It is used to set the default
radix of the Scanner which is in
use to the specified radix.

Example 1

Let's see a simple example of Java Scanner where


we are getting a single input from the user. Here,
we are asking for a string through in.nextLine()
method.

1. import java.util.*;
2. public class ScannerExample {
3. public static void main(String args[]){
4. Scanner in = new Scanner(System.in);
5. System.out.print("Enter your name: ");
6. String name = in.nextLine();
7. System.out.println("Name is: " + name);

8. in.close();
9. }
10. }

Output:

Enter your name: sonoo jaiswal


Name is: sonoo jaiswal
Example 2

1. import java.util.*;
2. public class ScannerClassExample1 {
3. public static void main(String args[]){

4. String s = "Hello, This is JavaTpoint.";


5. //Create scanner Object and pass string in it
6. Scanner scan = new Scanner(s);
7. //Check if the scanner has a token
8. System.out.println("Boolean Result: " + scan
.hasNext());
9. //Print the string
10. System.out.println("String: " +scan.next
Line());
11. scan.close();
12. System.out.println("--------Enter Your Det
ails-------- ");
13. Scanner in = new Scanner(System.in);
14. System.out.print("Enter your name: ");
15. String name = in.next();
16. System.out.println("Name: " + name);

17. System.out.print("Enter your age: ");


18. int i = in.nextInt();
19. System.out.println("Age: " + i);
20. System.out.print("Enter your salary: ");
21. double d = in.nextDouble();
22. System.out.println("Salary: " + d);
23. in.close();
24. }
25. }

Output:

Boolean Result: true


String: Hello, This is JavaTpoint.
-------Enter Your Details---------
Enter your name: Abhishek
Name: Abhishek
Enter your age: 23
Age: 23
Enter your salary: 25000
Salary: 25000.0

Example 3

1. import java.util.*;
2. public class ScannerClassExample2 {
3. public static void main(String args[]){

4. String str = "Hello/This is JavaTpoint/My nam


e is Abhishek.";
5. //Create scanner with the specified String Ob
ject
6. Scanner scanner = new Scanner(str);
7. System.out.println("Boolean Result: "+scann
er.hasNextBoolean());
8. //Change the delimiter of this scanner
9. scanner.useDelimiter("/");
10. //Printing the tokenized Strings
11. System.out.println("---Tokenizes String--
-");
12. while(scanner.hasNext()){
13. System.out.println(scanner.next());
14. }
15. //Display the new delimiter
16. System.out.println("Delimiter used: " +s
canner.delimiter());
17. scanner.close();
18. }
19. }

Output:

Boolean Result: false


---Tokenizes String---
Hello
This is JavaTpoint
My name is Abhishek.
Delimiter used: /

JAVA CBSE PERCENTAGE CALCULATOR

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int div = (a+b+c+d+e)/500;
int percentage = div * 100 ;
System.out.println(percentage);
}
}

PRACTICE SET 1

WRITE A PROGRAM TO ADD THREE NUMBERS


IN JAVA

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int d = sc.nextInt();
int e = sc.nextInt();
int sum = (a+b+c+d+e);
System.out.println(sum);
}
}

WRITE A PROGRAM TO PRINT THE CGPA OF A


STUDENT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int cgpa = (a+b+c)/300;
System.out.println(cgpa);
}
}

WRITE A PROGRAM TO TAKE INPUT OF A


USER AND PRINT IT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println("Hello " + a + " , have a
good day");
}
}

WRITE A PROGRAM TO CONVERT KILOMETERS


TO MILES

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
float kilometers = sc.nextFloat();
float miles = kilometers * (0.62f) ;
System.out.println(miles);
}
}

WRITE A PROGRAM TO CHECK WHETHER THE


ENTERED NUMBER IS INTEGER OR NOT

import java.util.Scanner;
public class HELLOWORLD {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Boolean a = sc.hasNextInt();
if(a == true){
System.out.println("Integer");
}
else{
System.out.println("Decimal");
}

}
}

************END OF PRACTICE SET


1***********

OPERATORS AND EXPRESSIONS IN


JAVA
Operators are used to perform operations on
variables and values . There are a wide variety of
operators used in java . They are :

a. Arithmetic Operators
b. Assignment Operators
c. Comparison Operators
d. Logical Operators
e. Bit wise Operators

ARITHMETIC OPERATORS

It consists of operators like +,-,*,/ and %,++,--,etc


These are used to perform arithmetic operations in
java in between two operands(binary operators) or
for one operators(unary operators) .

BINARY OPERATORS
UNARY OPERATORS

Java unary operators are the types that need only


one operand to perform any operation like
increment, decrement, negation, etc. It consists of
various arithmetic, logical and other operators that
operate on a single operand. Let’s look at the
various unary operators in detail and see how they
operate.

Operator 1: Unary minus(-)


This operator can be used to convert a positive
value to a negative one.

Syntax:

-(operand)
Illustration:

a = -10
Example:

// Java Program to Illustrate Unary - Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring a custom variable
int n1 = 20;

// Printing the above variable


System.out.println("Number = " + n1);

// Performing unary operation


n1 = -n1;

// Printing the above result number


// after unary operation
System.out.println("Result = " + n1);
}
}

Output
Number = 20
Result = -20
Operator 2: ‘NOT’ Operator(!)
This is used to convert true to false or vice versa.
Basically, it reverses the logical state of an
operand.

Syntax:

!(operand)
Illustration:

cond = !true;
// cond < false
Example:

// Java Program to Illustrate Unary NOT Operator

// Importing required classes


import java.io.*;
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
boolean cond = true;
int a = 10, b = 1;

// Displaying values stored in above variables


System.out.println("Cond is: " + cond);
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);

// Displaying values stored in above variables


// after applying unary NOT operator
System.out.println("Now cond is: " + !cond);
System.out.println("!(a < b) = " + !(a < b));
System.out.println("!(a > b) = " + !(a > b));
}
}

Output
Cond is: true
Var1 = 10
Var2 = 1
Now cond is: false
!(a < b) = true
!(a > b) = false
Operator 3: Increment(++)
It is used to increment the value of an integer. It
can be used in two separate ways:

3.1: Post-increment operator


When placed after the variable name, the value of
the operand is incremented but the previous value
is retained temporarily until the execution of this
statement and it gets updated before the
execution of the next statement.

Syntax:

num++
Illustration:

num = 5
num++ = 6
3.2: Pre-increment operator

When placed before the variable name, the


operand’s value is incremented instantly.

Syntax:

++num
Illustration:

num = 5
++num = 6
Operator 4: Decrement ( — )
It is used to decrement the value of an integer. It
can be used in two separate ways:

4.1: Post-decrement operator

When placed after the variable name, the value of


the operand is decremented but the previous
values is retained temporarily until the execution
of this statement and it gets updated before the
execution of the next statement.
Syntax:

num--
Illustration:

num = 5
num-- = 4 // Value will be decremented before
execution of next statement.
4.2: Pre-decrement operator

When placed before the variable name, the


operand’s value is decremented instantly.

Syntax:

--num
Illustration:

num = 5
--num = 4 //output is 5, value is decremented
before execution of next statement
Operator 5: Bitwise Complement(~)
This unary operator returns the one’s complement
representation of the input value or operand, i.e,
with all bits inverted, which means it makes every
0 to 1, and every 1 to 0.

Syntax:

~(operand)
Illustration:

a = 5 [0101 in Binary]
result = ~5
This performs a bitwise complement of 5
~0101 = 1010 = 10 (in decimal)
Then the compiler will give 2’s complement
of that number.
2’s complement of 10 will be -6.
result = -6
Example:

// Java program to Illustrate Unary


// Bitwise Complement Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Declaring a variable
int n1 = 6, n2 = -2;

// Printing numbers on console


System.out.println("First Number = " + n1);
System.out.println("Second Number = " +
n2);

// Printing numbers on console after


// performing bitwise complement
System.out.println(
n1 + "'s bitwise complement = " + ~n1);
System.out.println(
n2 + "'s bitwise complement = " + ~n2);
}
}

Output
First Number = 6
Second Number = -2
6's bitwise complement = -7
-2's bitwise complement = 1
Example program in Java that implements all basic
unary operators for user input:

import java.util.Scanner;

public class UnaryOperators {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Uncomment this block for user input


// System.out.print("Enter a number: ");
// int num = sc.nextInt();

// Initialize num
int num = 10;

// Unary plus
int result = +num;
System.out.println("The value of result after
unary plus is: " + result);

// Unary minus
result = -num;
System.out.println("The value of result after
unary minus is: " + result);

// Pre-increment
result = ++num;
System.out.println("The value of result after
pre-increment is: " + result);

// Post-increment
result = num++;
System.out.println("The value of result after
post-increment is: " + result);

// Pre-decrement
result = --num;
System.out.println("The value of result after
pre-decrement is: " + result);

// Post-decrement
result = num--;
System.out.println("The value of result after
post-decrement is: " + result);

// Close the scanner


sc.close();
}
}

Output
The value of result after unary plus is: 10
The value of result after unary minus is: -10
The value of result after pre-increment is: 11
The value of result after post-increment is: 11
The value of re...
Explanation:
The above program implements all basic unary
operators in Java using user input. The program
uses the Scanner class from the java.util package
to read user input from the console. The following
steps describe how the program works in detail:

Import the java.util.Scanner class: The program


starts by importing the Scanner class, which is
used to read input from the console.
Create a Scanner object: Next, a Scanner object sc
is created and associated with the standard input
stream System.in.
Read the number from the user: The program
prompts the user to enter a number and uses the
nextInt() method of the Scanner class to read the
input. The input is stored in the num variable of
type int.
Use unary plus operator: The program uses the
unary plus operator + to perform a positive
operation on num. The result of the operation is
stored in the result variable of type int.
Use unary minus operator: The program uses the
unary minus operator – to perform a negative
operation on num. The result of the operation is
stored in the result variable.
Use pre-increment operator: The program uses the
pre-increment operator ++ to increment the value
of num before using it in an expression. The result
of the operation is stored in the result variable.
Use post-increment operator: The program uses
the post-increment operator ++ to increment the
value of num after using it in an expression. The
result of the operation is stored in the result
variable.
Use pre-decrement operator: The program uses
the pre-decrement operator — to decrement the
value of num before using it in an expression. The
result of the operation is stored in the result
variable.
Use post-decrement operator: The program uses
the post-decrement operator — to decrement the
value of num after using it in an expression. The
result of the operation is stored in the result
variable.
Print the results: The program prints out the final
values of result using the println method of the
System.out object after each operation.
This program demonstrates how to use basic unary
operators in Java. The Scanner class makes it easy
to read user input from the console, and various
unary operators are used to modify the value of
the num variable in the program.
Advantages
The main advantage of using unary operators in
Java is that they provide a simple and efficient way
to modify the value of a variable. Some specific
advantages of using unary operators are:

Concise and Easy to Use: Unary operators are


simple to use and require only one operand. They
are easy to understand and make code more
readable and concise.
Faster than Other Operators: Unary operators are
faster than other operators as they only require
one operand. This makes them ideal for operations
that need to be performed quickly, such as
incrementing a counter.
Pre- and Post-Increment/Decrement: Unary
operators provide both pre- and post-increment
and decrement options, which makes them useful
for a variety of use cases. For example, the pre-
increment operator can be used to increment the
value of a variable before using it in an expression,
while the post-increment operator can be used to
increment the value of a variable after using it in
an expression.
Modifying Primitive Types: Unary operators can be
used to modify the value of primitive types such as
int, long, float, double, etc.
Overall, unary operators provide a simple and
efficient way to perform operations on variables in
Java, and they can be used in a variety of scenarios
to make code more readable and concise.

ASSIGNMENT OPERATORS
These operators are used to assign values to a
variable. The left side operand of the assignment
operator is a variable, and the right side operand
of the assignment operator is a value. The value on
the right side must be of the same data type of the
operand on the left side. Otherwise, the compiler
will raise an error. This means that the assignment
operators have right to left associativity, i.e., the
value given on the right-hand side of the operator
is assigned to the variable on the left. Therefore,
the right-hand side value must be declared before
using it or should be a constant. The general
format of the assignment operator is,

variable operator value;


Types of Assignment Operators in Java
The Assignment Operator is generally of two types.
They are:

1. Simple Assignment Operator: The Simple


Assignment Operator is used with the “=” sign
where the left side consists of the operand and the
right side consists of a value. The value of the right
side must be of the same data type that has been
defined on the left side.

2. Compound Assignment Operator: The


Compound Operator is used where +,-,*, and / is
used along with the = operator.

Let’s look at each of the assignment operators and


how they operate:

1. (=) operator:
This is the most straightforward assignment
operator, which is used to assign the value on the
right to the variable on the left. This is the basic
definition of an assignment operator and how it
functions.

Syntax:

num1 = num2;
Example:

a = 10;
ch = 'y';
// Java code to illustrate "=" operator

import java.io.*;

class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num;
String name;

// Assigning values
num = 10;
name = "GeeksforGeeks";

// Displaying the assigned values


System.out.println("num is assigned: " +
num);
System.out.println("name is assigned: " +
name);
}
}
Output
num is assigned: 10
name is assigned: GeeksforGeeks
2. (+=) operator:
This operator is a compound of ‘+’ and ‘=’
operators. It operates by adding the current value
of the variable on the left to the value on the right
and then assigning the result to the operand on the
left.

Syntax:

num1 += num2;
Example:

a += 10

This means,
a = a + 10
// Java code to illustrate "+="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Adding & Assigning values


num1 += num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = 30
Note: The compound assignment operator in Java
performs implicit type casting. Let’s consider a
scenario where x is an int variable with a value of
5.

int x = 5;

If you want to add the double value 4.5 to the


integer variable x and print its value, there are two
methods to achieve this:

Method 1: x = x + 4.5

Method 2: x += 4.5

As per the previous example, you might think both


of them are equal. But in reality, Method 1 will
throw a runtime error stating the “incompatible
types: possible lossy conversion from double to
int“, Method 2 will run without any error and prints
9 as output.

Reason for the Above Calculation


Method 1 will result in a runtime error stating
“incompatible types: possible lossy conversion
from double to int.” The reason is that the addition
of an int and a double results in a double value.
Assigning this double value back to the int variable
x requires an explicit type casting because it may
result in a loss of precision. Without the explicit
cast, the compiler throws an error.

Method 2 will run without any error and print the


value 9 as output. The compound assignment
operator += performs an implicit type conversion,
also known as an automatic narrowing primitive
conversion from double to int. It is equivalent to x
= (int) (x + 4.5), where the result of the addition is
explicitly cast to an int. The fractional part of the
double value is truncated, and the resulting int
value is assigned back to x.

It is advisable to use Method 2 (x += 4.5) to avoid


runtime errors and to obtain the desired output.

Same automatic narrowing primitive conversion is


applicable for other compound assignment
operators as well, including -=, *=, /=, and %=.

3. (-=) operator:
This operator is a compound of ‘-‘ and ‘=’
operators. It operates by subtracting the variable’s
value on the right from the current value of the
variable on the left and then assigning the result to
the operand on the left.

Syntax:

num1 -= num2;
Example:

a -= 10

This means,
a = a - 10
// Java code to illustrate "-="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 10, num2 = 20;
System.out.println("num1 = " + num1);
System.out.println("num2 = " + num2);

// Subtracting & Assigning values


num1 -= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = -10
4. (*=) operator:
This operator is a compound of ‘*’ and ‘=’
operators. It operates by multiplying the current
value of the variable on the left to the value on the
right and then assigning the result to the operand
on the left.

Syntax:

num1 *= num2;
Example:

a *= 10
This means,
a = a * 10
// Java code to illustrate "*="

import java.io.*;

class Assignment {
public static void main(String[] args)
{
// Declaring variables
int num1 = 10, num2 = 20;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Multiplying & Assigning values


num1 *= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 10
num2 = 20
num1 = 200
5. (/=) operator:
This operator is a compound of ‘/’ and ‘=’
operators. It operates by dividing the current value
of the variable on the left by the value on the right
and then assigning the quotient to the operand on
the left.

Syntax:

num1 /= num2;
Example:

a /= 10
This means,
a = a / 10
// Java code to illustrate "/="

import java.io.*;

class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 20, num2 = 10;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Dividing & Assigning values


num1 /= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 20
num2 = 10
num1 = 2
6. (%=) operator:
This operator is a compound of ‘%’ and ‘=’
operators. It operates by dividing the current value
of the variable on the left by the value on the right
and then assigning the remainder to the operand
on the left.

Syntax:

num1 %= num2;
Example:

a %= 3

This means,
a=a%3
// Java code to illustrate "%="

import java.io.*;
class Assignment {
public static void main(String[] args)
{

// Declaring variables
int num1 = 5, num2 = 3;

System.out.println("num1 = " + num1);


System.out.println("num2 = " + num2);

// Moduling & Assigning values


num1 %= num2;

// Displaying the assigned values


System.out.println("num1 = " + num1);
}
}
Output
num1 = 5
num2 = 3
num1 = 2

COMPARISON OPERATORS

Comparison operators can be classified into many


types. They are as follows : -

1. Relational Operators
2. Logical operators
3. Ternary Operators

RELATIONAL OPERATORS

Java Relational Operators are a bunch of binary


operators used to check for relations between two
operands, including equality, greater than, less
than, etc. They return a boolean result after the
comparison and are extensively used in looping
statements as well as conditional if-else
statements and so on. The general format of
representing relational operator is:

Syntax:

variable1 relation_operator variable2


Let us look at each one of the relational operators
in Java:

Operator 1: ‘Equal to’ operator (==)

This operator is used to check whether the two


given operands are equal or not. The operator
returns true if the operand at the left-hand side is
equal to the right-hand side, else false.

Syntax:

var1 == var2
Illustration:

var1 = "GeeksforGeeks"
var2 = 20
var1 == var2 results in false
Example:

// Java Program to Illustrate equal to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 == var2: "
+ (var1 == var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 == var3: "
+ (var1 == var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 == var2: false
var1 == var3: true
Operator 2: ‘Not equal to’ Operator(!=)

This operator is used to check whether the two


given operands are equal or not. It functions
opposite to that of the equal-to-operator. It returns
true if the operand at the left-hand side is not
equal to the right-hand side, else false.

Syntax:

var1 != var2
Illustration:

var1 = "GeeksforGeeks"
var2 = 20

var1 != var2 results in true


Example:

// Java Program to Illustrate No- equal-to Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 5, var2 = 10, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 != var2: "
+ (var1 != var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var1 != var3: "
+ (var1 != var3));
}
}
Output
Var1 = 5
Var2 = 10
Var3 = 5
var1 != var2: true
var1 != var3: false
Operator 3: ‘Greater than’ operator(>)

This checks whether the first operand is greater


than the second operand or not. The operator
returns true when the operand at the left-hand side
is greater than the right-hand side.

Syntax:

var1 > var2


Illustration:

var1 = 30
var2 = 20

var1 > var2 results in true


Example:

// Java code to Illustrate Greater than operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 30, var2 = 20, var3 = 5;
// Displaying var1, var2, var3
System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 > var2: " + (var1 >
var2));

// Comparing var1 and var3 and


// printing corresponding boolean value
System.out.println("var3 > var1: "
+ (var3 >= var1));
}
}
Output
Var1 = 30
Var2 = 20
Var3 = 5
var1 > var2: true
var3 > var1: false
Operator 4: ‘Less than’ Operator(<)

This checks whether the first operand is less than


the second operand or not. The operator returns
true when the operand at the left-hand side is less
than the right-hand side. It functions opposite to
that of the greater-than operator.

Syntax:

var1 < var2


Illustration:

var1 = 10
var2 = 20
var1 < var2 results in true
Example:

// Java code to Illustrate Less than Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 20, var3 = 5;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 < var2: " + (var1 <
var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 < var3: " + (var2 <
var3));
}
}
Output
Var1 = 10
Var2 = 20
Var3 = 5
var1 < var2: true
var2 < var3: false
Operator 5: Greater than or equal to (>=)

This checks whether the first operand is greater


than or equal to the second operand or not. The
operator returns true when the operand at the left-
hand side is greater than or equal to the right-hand
side.

Syntax:

var1 >= var2


Illustration:

var1 = 20
var2 = 20
var3 = 10

var1 >= var2 results in true


var2 >= var3 results in true
Example:

// Java Program to Illustrate Greater than or equal


to
// Operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 20, var2 = 20, var3 = 10;
// Displaying var1, var2, var3
System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 >= var2: "
+ (var1 >= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 >= var3: "
+ (var2 >= var3));
}
}
Output
Var1 = 20
Var2 = 20
Var3 = 10
var1 >= var2: true
var2 >= var3: true
Operator 6: Less than or equal to (<=)

This checks whether the first operand is less than


or equal to the second operand or not. The
operator returns true when the operand at the left-
hand side is less than or equal to the right-hand
side.

Syntax:

var1 <= var2


Illustration:

var1 = 10
var2 = 10
var3 = 9

var1 <= var2 results in true


var2 <= var3 results in false
Example:

// Java Program to Illustrate Less


// than or equal to operator

// Importing I/O classes


import java.io.*;

// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Initializing variables
int var1 = 10, var2 = 10, var3 = 9;

// Displaying var1, var2, var3


System.out.println("Var1 = " + var1);
System.out.println("Var2 = " + var2);
System.out.println("Var3 = " + var3);

// Comparing var1 and var2 and


// printing corresponding boolean value
System.out.println("var1 <= var2: "
+ (var1 <= var2));

// Comparing var2 and var3 and


// printing corresponding boolean value
System.out.println("var2 <= var3: "
+ (var2 <= var3));
}
}
Output
Var1 = 10
Var2 = 10
Var3 = 9
var1 <= var2: true
var2 <= var3: false
program that implements all relational operators in
Java for user input:
import java.util.Scanner;

public class RelationalOperators {


public static void main(String[] args) {
Scanner scan = new Scanner(System.in);

//System.out.println("Enter first number: ");


// int num1 = scan.nextInt();

// System.out.println("Enter second number: ");


// int num2 = scan.nextInt();

int num1 =1;


int num2 = 2;

System.out.println("num1 > num2 is " + (num1


> num2));
System.out.println("num1 < num2 is " + (num1
< num2));
System.out.println("num1 >= num2 is " +
(num1 >= num2));
System.out.println("num1 <= num2 is " +
(num1 <= num2));
System.out.println("num1 == num2 is " +
(num1 == num2));
System.out.println("num1 != num2 is " + (num1
!= num2));
}
}
Output
num1 > num2 is false
num1 < num2 is true
num1 >= num2 is false
num1 <= num2 is true
num1 == num2 is false
num1 != num2 is true
Explanation
The code above implements all relational
operators in Java for user input. The following is an
explanation of the code in detail:
Importing the Scanner class: The code starts by
importing the Scanner class, which is used to read
input from the user. The Scanner class is part of
the java.util package, so it needs to be imported in
order to be used.
Defining the main method: The program then
defines the main method, which is the starting
point of the program. This is where the program
logic is executed.
Reading user input: The code uses the Scanner
object to read two integers from the user. The first
number is stored in the num1 variable, and the
second number is stored in the num2 variable.
Using relational operators: The code then uses the
relational operators >, <, >=, <=, ==, and != to
compare the values of num1 and num2. The
results of these comparisons are stored in boolean
variables, which are then displayed to the user.
Displaying results: The results of the comparisons
are displayed to the user using the
System.out.println method. This method is used to
print a message to the console.
Closing the Scanner object: Finally, the code closes
the Scanner object to prevent memory leaks and to
ensure that the program terminates cleanly.
The relational operators in Java return a boolean
value of true or false, depending on the result of
the comparison. For example, num1 > num2
returns true if num1 is greater than num2, and
false otherwise. Similarly, num1 == num2 returns
true if num1 is equal to num2, and false otherwise.

Advantages
There are several advantages of using relational
operators in Java, including:
Easy to understand: Relational operators are
simple and easy to understand, making it easy to
write code that performs comparisons.
Versatile: Relational operators can be used to
compare values of different data types, such as
integers, floating-point numbers, and strings.
Essential for making decisions: Relational
operators are essential for making decisions in a
program, as they allow you to control the flow of a
program based on the results of comparisons.
Efficient: Relational operators are efficient, as they
perform comparisons quickly and accurately.
Reusable code: The code that uses relational
operators can be reused in different parts of a
program, making it easier to maintain and update
the code.
Improved code readability: By using relational
operators, you can make your code more readable
and understandable, as the comparisons are
clearly stated in the code.
Debugging made easier: Relational operators make
debugging easier, as you can use them to check
the values of variables and to find out where a
problem is occurring in your code.

LOGICAL OPERATORS

Logical operators are used to perform logical


“AND”, “OR” and “NOT” operations, i.e. the
function similar to AND gate and OR gate in digital
electronics. They are used to combine two or more
conditions/constraints or to complement the
evaluation of the original condition under particular
consideration. One thing to keep in mind is, while
using AND operator, the second condition is not
evaluated if the first one is false. Whereas while
using OR operator, the second condition is not
evaluated if the first one is true, i.e. the AND and
OR operators have a short-circuiting effect. Used
extensively to test for several conditions for
making a decision.

AND Operator ( && ) – if( a && b ) [if true execute


else don’t]
OR Operator ( || ) – if( a || b) [if one of them is true
to execute else don’t]
NOT Operator ( ! ) – !(a<b) [returns false if a is
smaller than b]
Example For Logical Operator in Java
Here is an example depicting all the operators
where the values of variables a, b, and c are kept
the same for all the situations.

a = 10, b = 20, c = 30

For AND operator:

Condition 1: c > a

Condition 2: c > b

Output:

True [Both Conditions are true]


For OR Operator:

Condition 1: c > a

Condition 2: c > b

Output:

True [One of the Condition if true]

For NOT Operator:

Condition 1: c > a

Condition 2: c > b

Output:

False [Because the result was true and NOT


operator did it’s opposite]

Logical ‘AND’ Operator (&&)


This operator returns true when both the
conditions under consideration are satisfied or are
true. If even one of the two yields false, the
operator results false. In Simple terms, cond1 &&
cond2 returns true when both cond1 and cond2 are
true (i.e. non-zero).

Syntax:

condition1 && condition2


Illustration:
a = 10, b = 20, c = 20

condition1: a < b
condition2: b == c

if(condition1 && condition2)


d=a+b+c

// Since both the conditions are true


d = 50.
Example:

// Java code to illustrate


// logical AND operator

import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 20, c = 20, d = 0;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);

// using logical AND to verify


// two constraints
if ((a < b) && (b == c)) {
d = a + b + c;
System.out.println("The sum is: " + d);
}
else
System.out.println("False conditions");
}
}

Output
Var1 = 10
Var2 = 20
Var3 = 20
The sum is: 50

Now in the below example, we can see the short-


circuiting effect. Here when the execution reaches
to if statement, the first condition inside the if
statement is false and so the second condition is
never checked. Thus the ++b(pre-increment of b)
never happens, and b remains unchanged.

Example:

import java.io.*;

class shortCircuiting {
public static void main(String[] args)
{

// initializing variables
int a = 10, b = 20, c = 15;

// displaying b
System.out.println("Value of b : " + b);

// Using logical AND


// Short-Circuiting effect as the first condition
is
// false so the second condition is never
reached
// and so ++b(pre increment) doesn't take
place and
// value of b remains unchanged
if ((a > c) && (++b > c)) {
System.out.println("Inside if block");
}

// displaying b
System.out.println("Value of b : " + b);
}
}
Output:

AND Operator Output


Logical ‘OR’ Operator (||)
This operator returns true when one of the two
conditions under consideration is satisfied or is
true. If even one of the two yields true, the
operator results true. To make the result false,
both the constraints need to return false.

Syntax:

condition1 || condition2
Example:

a = 10, b = 20, c = 20

condition1: a < b

condition2: b > c

if(condition1 || condition2)

d=a+b+c

// Since one of the condition is true


d = 50.

Illustration:

// Java code to illustrate


// logical OR operator

import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1, c = 10, d = 30;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);
System.out.println("Var3 = " + c);
System.out.println("Var4 = " + d);

// using logical OR to verify


// two constraints
if (a > b || c == d)
System.out.println(
"One or both + the conditions are true");
else
System.out.println(
"Both the + conditions are false");
}
}

Output
Var1 = 10
Var2 = 1
Var3 = 10
Var4 = 30
One or both + the conditions are true

Now in the below example, we can see the short-


circuiting effect for OR operator. Here when the
execution reaches to if statement, the first
condition inside the if statement is true and so the
second condition is never checked. Thus the ++b
(pre-increment of b) never happens, and b remains
unchanged.

Example:

import java.io.*;

class ShortCircuitingInOR {
public static void main (String[] args) {

// initializing variables
int a = 10, b = 20, c = 15;

// displaying b
System.out.println("Value of b: " +b);

// Using logical OR
// Short-circuiting effect as the first condition
is true
// so the second condition is never reached
// and so ++b (pre-increment) doesn't take
place and
// value of b remains unchanged
if((a < c) || (++b < c))
System.out.println("Inside if");

// displaying b
System.out.println("Value of b: " +b);
}
}

Output
Value of b: 20
Inside if
Value of b: 20

Logical ‘NOT’ Operator (!)


Unlike the previous two, this is a unary operator
and returns true when the condition under
consideration is not satisfied or is a false condition.
Basically, if the condition is false, the operation
returns true and when the condition is true, the
operation returns false.

Syntax:

!(condition)
Example:

a = 10, b = 20

!(a<b) // returns false

!(a>b) // returns true

Illustartion:

// Java code to illustrate


// logical NOT operator
import java.io.*;

class Logical {
public static void main(String[] args)
{
// initializing variables
int a = 10, b = 1;

// Displaying a, b, c
System.out.println("Var1 = " + a);
System.out.println("Var2 = " + b);

// Using logical NOT operator


System.out.println("!(a < b) = " + !(a < b));
System.out.println("!(a > b) = " + !(a > b));
}
}

Output
Var1 = 10
Var2 = 1
!(a < b) = true
!(a > b) = false

Implementing all logical operators on Boolean


values (By default values – TRUE or FALSE)
Syntax:
boolean a = true;
boolean b = false;
Example:

public class LogicalOperators {


public static void main(String[] args) {
boolean a = true;
boolean b = false;

System.out.println("a: " + a);


System.out.println("b: " + b);
System.out.println("a && b: " + (a && b));
System.out.println("a || b: " + (a || b));
System.out.println("!a: " + !a);
System.out.println("!b: " + !b);
}
}

Output
a: true
b: false
a && b: false
a || b: true
!a: false
!b: true

Explanation:
The code above is a Java program that implements
all logical operators with default values. The
program defines a class LogicalOperators with a
main method.
In the main method, two boolean variables a and b
are defined and assigned default values true and
false, respectively.
The program then prints the values of a and b to
the console using the System.out.println method.
This allows us to verify the values assigned to a
and b.
Next, the program calculates the result of the
logical operators && (and), || (or), and ! (not)
applied to a and b. The results of these operations
are also printed to the console using the
System.out.println method.
The && operator returns true if both operands are
true; otherwise, it returns false. In this case, the
result of a && b is false.
The || operator returns true if either operand is
true; otherwise, it returns false. In this case, the
result of a || b is true.
The ! operator negates the value of its operand. If
the operand is true, the result is false, and if the
operand is false, the result is true. In this case, the
results of !a and !b are false and true, respectively.
The output of the program shows the truth table
for all logical operators. This table provides a visual
representation of how these operators behave for
all possible combinations of true and false inputs.
Advantages of logical operators:
Short-circuit evaluation: One of the main
advantages of logical operators is that they
support short-circuit evaluation. This means that if
the value of an expression can be determined
based on the left operand alone, the right operand
is not evaluated at all. While this can be useful for
optimizing code and preventing unnecessary
computations, it can also lead to subtle bugs if the
right operand has side effects that are expected to
be executed.
Readability: Logical operators make code more
readable by providing a clear and concise way to
express complex conditions. They are easily
recognizable and make it easier for others to
understand the code.
Flexibility: Logical operators can be combined in
various ways to form complex conditions, making
the code more flexible. This allows developers to
write code that can handle different scenarios and
respond dynamically to changes in the program’s
inputs.
Reusability: By using logical operators, developers
can write code that can be reused in different parts
of the program. This reduces the amount of code
that needs to be written and maintained, making
the development process more efficient.
Debugging: Logical operators can help to simplify
the debugging process. If a condition does not
behave as expected, it is easier to trace the
problem by examining the results of each logical
operator rather than having to navigate through a
complex code structure.
Disadvantages of logical operators:
Limited expressiveness: Logical operators have a
limited expressive power compared to more
complex logical constructs like if-else statements
and switch-case statements. This can make it
difficult to write complex conditionals that require
more advanced logic, such as evaluating multiple
conditions in a specific order.
Potential for confusion: In some cases, the use of
logical operators can lead to confusion or
ambiguity in the code. For example, consider the
expression a or b and c. Depending on the
intended order of operations, this expression can
have different interpretations. To avoid this kind of
confusion, it is often recommended to use
parentheses to explicitly specify the order of
evaluation.
Boolean coercion: Logical operators can sometimes
lead to unexpected behavior when used with non-
Boolean values. For example, when using the or
operator, the expression a or b will evaluate to a if
a is truthy, and b otherwise. This can lead to
unexpected results if a or b are not actually
Boolean values, but instead have a truthy or false
interpretation that does not align with the
programmer’s intentions.
Overall, logical operators are an important tool for
developers and play a crucial role in the
implementation of complex conditions in a
program. They help to improve the readability,
flexibility, reusability, and debuggability of the
code.
TERNARY OPERATORS

Java ternary operator is the only conditional


operator that takes three operands. It’s a one-liner
replacement for the if-then-else statement and is
used a lot in Java programming. We can use the
ternary operator in place of if-else conditions or
even switch conditions using nested ternary
operators. Although it follows the same algorithm
as of if-else statement, the conditional operator
takes less space and helps to write the if-else
statements in the shortest way possible.

Ternary Operator in Java

Syntax:

variable = Expression1 ? Expression2: Expression3

If operates similarly to that of the if-else statement


as in Exression2 is executed if Expression1 is true
else Expression3 is executed.

if(Expression1)
{
variable = Expression2;
}
else
{
variable = Expression3;
}

Example:

num1 = 10;
num2 = 20;

res=(num1>num2) ? (num1+num2):(num1-num2)

Since num1<num2,
the second operation is performed
res = num1-num2 = -10

Flowchart of Ternary Operation


Flowchart for Ternary Operator

Examples of Ternary Operators in Java


Example 1:
Below is the implementation of the Ternary
Operator:

// Java program to find largest among two


// numbers using ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, max;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);

// Largest among n1 and n2


max = (n1 > n2) ? n1 : n2;

// Print the largest number


System.out.println("Maximum is = " + max);
}
}

Output
First num: 5
Second num: 10
Maximum is = 10

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)

Example 2:
Below is the implementation of the above method:

// Java code to illustrate ternary operator

import java.io.*;

class Ternary {
public static void main(String[] args)
{

// variable declaration
int n1 = 5, n2 = 10, res;

System.out.println("First num: " + n1);


System.out.println("Second num: " + n2);

// Performing ternary operation


res = (n1 > n2) ? (n1 + n2) : (n1 - n2);

// Print the largest number


System.out.println("Result = " + res);
}
}
Output
First num: 5
Second num: 10
Result = -5

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space: O(1)

Example 3:
Implementing ternary operator on Boolean values:

// Java Program for Implementing


// Ternary operator on Boolean values

// Driver Class
public class TernaryOperatorExample {
// main function
public static void main(String[] args)
{
boolean condition = true;
String result = (condition) ? "True" : "False";

System.out.println(result);
}
}

Output
True

Explanation of the above method:


In this program, a Boolean variable condition is
declared and assigned the value true. Then, the
ternary operator is used to determine the value of
the result string. If the condition is true, the value
of result will be “True”, otherwise it will be “False”.
Finally, the value of result is printed to the console.

Advantages of Java Ternary Operator


Compactness: The ternary operator allows you to
write simple if-else statements in a much more
concise way, making the code easier to read and
maintain.
Improved readability: When used correctly, the
ternary operator can make the code more readable
by making it easier to understand the intent behind
the code.
Increased performance: Since the ternary operator
evaluates a single expression instead of executing
an entire block of code, it can be faster than an
equivalent if-else statement.
Simplification of nested if-else statements: The
ternary operator can simplify complex logic by
providing a clean and concise way to perform
conditional assignments.
Easy to debug: If a problem occurs with the code,
the ternary operator can make it easier to identify
the cause of the problem because it reduces the
amount of code that needs to be examined.
It’s worth noting that the ternary operator is not a
replacement for all if-else statements. For complex
conditions or logic, it’s usually better to use an if-
else statement to avoid making the code more
difficult to understand.

BITWISE OPERATORS

Bitwise operators are used to performing the


manipulation of individual bits of a number. They
can be used with any integral type (char, short, int,
etc.). They are used when performing update and
query operations of the Binary indexed trees.
Now let’s look at each one of the bitwise operators
in Java:

1. Bitwise OR (|)

This operator is a binary operator, denoted by ‘|’. It


returns bit by bit OR of input values, i.e., if either of
the bits is 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise OR Operation of 5 and 7


0101
| 0111
________
0111 = 7 (In decimal)
2. Bitwise AND (&)

This operator is a binary operator, denoted by ‘&.’


It returns bit by bit AND of input values, i.e., if both
bits are 1, it gives 1, else it shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise AND Operation of 5 and 7


0101
& 0111
________
0101 = 5 (In decimal)
3. Bitwise XOR (^)
This operator is a binary operator, denoted by ‘^.’
It returns bit by bit XOR of input values, i.e., if
corresponding bits are different, it gives 1, else it
shows 0.

Example:

a = 5 = 0101 (In Binary)


b = 7 = 0111 (In Binary)

Bitwise XOR Operation of 5 and 7


0101
^ 0111
________
0010 = 2 (In decimal)
4. Bitwise Complement (~)

This operator is a unary operator, denoted by ‘~.’


It returns the one’s complement representation of
the input value, i.e., with all bits inverted, which
means it makes every 0 to 1, and every 1 to 0.

Example:

a = 5 = 0101 (In Binary)

Bitwise Complement Operation of 5

~ 0101
________
1010 = 10 (In decimal)
Note: Compiler will give 2’s complement of that
number, i.e., 2’s complement of 10 will be -6.

// Java program to illustrate


// bitwise operators

public class operators {


public static void main(String[] args)
{
// Initial values
int a = 5;
int b = 7;

// bitwise and
// 0101 & 0111=0101 = 5
System.out.println("a&b = " + (a & b));

// bitwise or
// 0101 | 0111=0111 = 7
System.out.println("a|b = " + (a | b));

// bitwise xor
// 0101 ^ 0111=0010 = 2
System.out.println("a^b = " + (a ^ b));

// bitwise not
// ~00000000 00000000 00000000
00000101=11111111 11111111 11111111
11111010
// will give 2's complement (32 bit) of 5 = -6
System.out.println("~a = " + ~a);

// can also be combined with


// assignment operator to provide shorthand
// assignment
// a=a&b
a &= b;
System.out.println("a= " + a);
}
}
Output
a&b = 5
a|b = 7
a^b = 2
~a = -6
a= 5
Auxiliary space:O(1)

Time complexity:O(1)

// Demonstrating the bitwise logical operators

class GFG {
public static void main (String[] args) {

String binary[]={
"0000","0001","0010","0011","0100","0101",
"0110","0111","1000","1001","1010",
"1011","1100","1101","1110","1111"
};

// initializing the values of a and b


int a=3; // 0+2+1 or 0011 in binary
int b=6; // 4+2+0 or 0110 in binary

// bitwise or
int c= a | b;

// bitwise and
int d= a & b;

// bitwise xor
int e= a ^ b;

// bitwise not
int f= (~a & b)|(a &~b);
int g= ~a & 0x0f;

System.out.println(" a= "+binary[a]);
System.out.println(" b= "+binary[b]);
System.out.println(" a|b= "+binary[c]);
System.out.println(" a&b= "+binary[d]);
System.out.println(" a^b= "+binary[e]);
System.out.println("~a & b|a&~b=
"+binary[f]);
System.out.println("~a= "+binary[g]);
}
}

Output
a= 0011
b= 0110
a|b= 0111
a&b= 0010
a^b= 0101
~a & b|a&~b= 0101
~a= 1100
Bit-Shift Operators (Shift Operators)

Shift operators are used to shift the bits of a


number left or right, thereby multiplying or dividing
the number by two, respectively. They can be used
when we have to multiply or divide a number by
two.

Syntax:

number shift_op number_of_places_to_shift;


Types of Shift Operators:

Shift Operators are further divided into 3 types.


These are:
Signed Right shift operator (>>)
Unsigned Right shift operator (>>>)
Left shift operator(<<)
Note: For more detail about the Shift Operators in
Java, refer Shift Operator in Java.

program to implement all Bitwise operators in java


for user input

import java.util.Scanner;

public class BitwiseOperators {


public static void main(String[] args) {
Scanner input = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = input.nextInt();

System.out.print("Enter second number: ");


int num2 = input.nextInt();

System.out.println("Bitwise AND: " + (num1 &


num2));
System.out.println("Bitwise OR: " + (num1 |
num2));
System.out.println("Bitwise XOR: " + (num1 ^
num2));
System.out.println("Bitwise NOT: " +
(~num1));
System.out.println("Bitwise Left Shift: " +
(num1 << 2));
System.out.println("Bitwise Right Shift: " +
(num1 >> 2));
System.out.println("Bitwise Unsigned Right
Shift: " + (num1 >>> 2));
input.close();
}
}
Input

Enter first number: 4


Enter second number: 8
Output

Bitwise AND: 0
Bitwise OR: 12
Bitwise XOR: 12
Bitwise NOT: -5
Bitwise Left Shift: 16
Bitwise Right Shift: 1
Bitwise Unsigned Right Shift: 1
Explanation
This program prompts the user to enter two
numbers, num1 and num2. It then performs the
following bitwise operations using the &, |, ^, ~,
<<, >>, and >>> operators:

Bitwise AND
Bitwise OR
Bitwise XOR
Bitwise NOT
Bitwise Left Shift
Bitwise Right Shift
Bitwise Zero Fill Right Shift

Advantages
The advantages of using Bitwise Operators in Java
are:

Speed: Bitwise operations are much faster than


arithmetic operations as they operate directly on
binary representations of numbers.
Space Optimization: Bitwise operations can be
used to store multiple values in a single variable,
which can be useful when working with limited
memory.
Bit Manipulation: Bitwise operators allow for
precise control over individual bits of a number,
which can be useful in various applications such as
cryptography, error detection, and compression.
Code Simplification: Bitwise operations can simplify
the code by reducing the number of conditional
statements and loops required to perform certain
tasks.
In summary, Bitwise Operators are an important
tool for optimizing performance, improving code
readability, and reducing code complexity in Java
applications.

SHIFT OPERATORS

By shifting the bits of its first operand right or left,


a shift operator performs bit manipulation on data.
The shift operators available in the Java
programming language are listed below. The shift
operator is a java operator that is used to shift bit
patterns right or left.

Types of Shift Operators in Java:


Name of operator

Sign Description
Signed Left Shift << The left shift operator moves
all bits by a given number of bits to the left.
Signed Right Shift>> The right shift operator
moves all bits by a given number of bits to the
right.
Unsigned Right Shift >>> It is the same as
the signed right shift, but the vacant leftmost
position is filled with 0 instead of the sign bit.
1. Signed Left Shift Operator in Java
This operator is represented by a symbol <<, read
as double less than.

Syntax:

left_operand << number


Illustration:

// Left Shifting a byte value

class GFG {
public static void main(String[] args)
{
byte a = 64, b;
int i;

i = a << 2;
b = (byte)(a << 2);
System.out.println("Original value of a: " + a);
System.out.println("i and b: " + i + " " + b);
}
}
Calculating the value of number<<2 if number=2.
When the value of a number is shifted to the left
two places, the leftmost two bits are lost. The
number has a value of two. 0010 is the binary
representation of the number 2. In the following
example, the method for doing a left shift is
explained:
Example:

In the below example below, the binary number


0010 (in decimal 2) becomes 1000 after shifting
the bits to the left (in decimal 8).

// Java Program to demonstrate


// Signed Left-Shift Operator

// Importing required classes


import java.io.*;

// Main class
class GFG {

// main driver method


public static void main(String[] args)
{
int number = 2;

// 2 bit left shift operation


int Ans = number << 2;

System.out.println(Ans);
}
}
Output
8
2. Signed Right Shift Operator in Java
The Right Shift Operator moves the bits of a
number in a given number of places to the right.
The >> sign represents the right shift operator,
which is understood as double greater than. When
you type x>>n, you tell the computer to move the
bits x to the right n places.
When we shift a number to the right, the least
significant bits (rightmost) are deleted, and the
sign bit is filled in the most considerable place
(leftmost).

Syntax:

left_operand >> number


Illustration:

Calculate the value of number>>2 if number=8.

When the value of a number is shifted to the right


two places, the rightmost two bits are lost. The
number has a value of eight. 1000 is the binary
representation of the number 8. The following is an
example of how to perform the right shift:

In the example above, the binary number 1000 (in


decimal 8) becomes 0010 after shifting the bits to
the right (in decimal 2).

Example:

// Java program to demonstrate


// the Signed right shift operator
import java.io.*;

class GFG
{
public static void main (String[] args) {
{
int number = 8;

// 2 bit signed right shift


int Ans = number >> 2;
System.out.println(Ans);
}
}
}

// Masking sign extension

class GFG {
public static void main (String[] args) {
char hex[]={
'0','1','2','3','4','5',
'6','7','8','9','a','b','c',
'd','e','f'
};

byte b=(byte) 0xf1;

System.out.println("b = 0x" + hex [(b>>4) &


0x0f] + hex[b & 0x0f]);
}
}
3. Unsigned Right Shift Operator in Java
Unsigned Right Shift Operator moves the bits of
the integer a given number of places to the right.
The sign bit was filled with 0s. The Bitwise Zero Fill
Right Shift Operator is represented by the symbol
>>>.

Syntax:

left_operand >>> number

// Java program to demonstrate


// the Unsigned right shift operator
import java.io.*;

class GFG
{
public static void main (String[] args)
{
byte num1 = 8;
byte num2 = -8;

System.out.println(num1 >>> 2);


System.out.println(num2 >>> 2);
}
}
Output
2
1073741822
Note: For negative bits, the signed and unsigned
right shift operators provide different results.

4. Unsigned Left Shift Operator in Java


Unlike unsigned Right Shift, there is no “<<<”
operator in Java because the logical (<<) and
arithmetic left-shift (<<<) operations are identical.
PRECEDENCE OF OPERATORS

Precedence Operator Type Associativity


() Parentheses
15 [] Array subscript Left to Right
· Member selection
++ Unary post-increment
14 Left to Right
-- Unary post-decrement
++ Unary pre-increment
-- Unary pre-decrement
+ Unary plus
13 - Unary minus Right to left
! Unary logical negation
~ Unary bitwise complement
( type ) Unary type cast
* Multiplication
12 / Division Left to right
% Modulus
+ Addition
11 Left to right
- Subtraction
<< Bitwise left shift
10 >> Bitwise right shift with sign extension Left to right
>>> Bitwise right shift with zero extension
< Relational less than
<= Relational less than or equal
9 > Relational greater than Left to right
>= Relational greater than or equal
instanceof Type comparison (objects only)
== Relational is equal to
8 Left to right
!= Relational is not equal to
7 & Bitwise AND Left to right
6 ^ Bitwise exclusive OR Left to right
5 | Bitwise inclusive OR Left to right
4 && Logical AND Left to right
3 || Logical OR Left to right
2 ?: Ternary conditional Right to left
= Assignment
+= Addition assignment
-= Subtraction assignment
1 Right to left
*= Multiplication assignment
/= Division assignment
%= Modulus assignment

ASSOCIATIVITY OF OPERATORS

Java Operator Precedence and Associativity

Operators Precedence Associativity

postfix increment and decrement ++ -- left to right

prefix increment and decrement, and


++ -- + - ~ ! right to left
unary

multiplicative * / % left to right

additive + - left to right

shift << >> >>> left to right

< > <= >=


relational instanceof
left to right

equality == != left to right

bitwise AND & left to right


bitwise exclusive OR ^ left to right

bitwise inclusive OR | left to right

logical AND && left to right

logical OR || left to right

ternary ? : right to left

= += -= *= /= %=
assignment &= ^= |= <<= >>= right to left
>>>=

CHAPER 2 PRACTICE SET

DETERMINE THE OUTPUT OF


Float a = 7/4*9/2

public class HELLOWORLD{


public static void main(String[] args) {
float a = 7/4*9/2;
System.out.println(a);
}
}

OUTPUT :
4.0

ENCRYPT A GRADE BY ADDING 8 TO IT

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int grade = sc.nextInt();
int newgrade = grade + 8;
System.out.println(grade);
}
}
COMPARE A GIVEN NUMBER TO ENTERED
NUMBER

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 10;
int b = sc.nextInt();
if(a>b){
System.out.println("Smaller");
}
else{
System.out.println("Bigger");
}
}
}

WRITE THE GIVEN EXPRESSION

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int v,u,a,s ;
v = sc.nextInt();
u = sc.nextInt();
a = sc.nextInt();
s = sc.nextInt();
int x = (v*v - u*u)/(2*a*s);
System.out.println(x);
}
}

FIND THE VALUE OF EXPRESSION


import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = 7*49/7+35/7 ;
System.out.println(a);
}
}
****************END OF PRACTICE SET
2******************

STRINGS IN JAVA

Strings are the type of objects that can store the


character of values and in Java, every character is
stored in 16 bits i,e using UTF 16-bit encoding. A
string acts the same as an array of characters in
Java.

Example:

String name = "Geeks";


String Example in Java
String Example in Java

Below is an example of a String in Java:

// Java Program to demonstrate


// String
public class StringExample {

// Main Function
public static void main(String args[])
{
String str = new String("example");
// creating Java string by new keyword
// this statement create two object i.e
// first the object is created in heap
// memory area and second the object is
// created in String constant pool.

System.out.println(str);
}
}

Output
example
Ways of Creating a String
There are two ways to create a string in Java:

String Literal
Using new Keyword
Syntax:

<String_Type> <string_variable> =
"<sequence_of_string>";
1. String literal
To make Java more memory efficient (because no
new objects are created if it exists already in the
string constant pool).

Example:

String demoString = “GeeksforGeeks”;


2. Using new keyword
String s = new String(“Welcome”);
In such a case, JVM will create a new string object
in normal (non-pool) heap memory and the literal
“Welcome” will be placed in the string constant
pool. The variable s will refer to the object in the
heap (non-pool)
Example:
String demoString = new String
(“GeeksforGeeks”);
Interfaces and Classes in Strings in Java
CharBuffer: This class implements the
CharSequence interface. This class is used to allow
character buffers to be used in place of
CharSequences. An example of such usage is the
regular-expression package java.util.regex.

String: It is a sequence of characters. In Java,


objects of String are immutable which means a
constant and cannot be changed once created.

CharSequence Interface
CharSequence Interface is used for representing
the sequence of Characters in Java.
Classes that are implemented using the
CharSequence interface are mentioned below and
these provides much of functionality like substring,
lastoccurence, first occurence, concatenate ,
toupper, tolower etc.

String
StringBuffer
StringBuilder
1. String
String is an immutable class which means a
constant and cannot be changed once created and
if wish to change , we need to create an new object
and even the functionality it provides like toupper,
tolower, etc all these return a new object , its not
modify the original object. It is automatically
thread safe.

Syntax

String str= "geeks";


or
String str= new String("geeks")
2. StringBuffer
StringBuffer is a peer class of String, it is mutable
in nature and it is thread safe class , we can use it
when we have multi threaded environment and
shared object of string buffer i.e, used by mutiple
thread. As it is thread safe so there is extra
overhead, so it is mainly used for multithreaded
program.

Syntax:

StringBuffer demoString = new


StringBuffer("GeeksforGeeks");
3. StringBuilder
StringBuilder in Java represents an alternative to
String and StringBuffer Class, as it creates a
mutable sequence of characters and it is not
thread safe. It is used only within the thread , so
there is no extra overhead , so it is mainly used for
single threaded program.

Syntax:

StringBuilder demoString = new StringBuilder();


demoString.append("GFG");
StringTokenizer
StringTokenizer class in Java is used to break a
string into tokens.

Example:

String Tokenizer in Java


A StringTokenizer object internally maintains a
current position within the string to be tokenized.
Some operations advance this current position past
the characters processed. A token is returned by
taking a substring of the string that was used to
create the StringTokenizer object.

StringJoiner is a class in java.util package which is


used to construct a sequence of characters(strings)
separated by a delimiter and optionally starting
with a supplied prefix and ending with a supplied
suffix. Though this can also be done with the help
of the StringBuilder class to append a delimiter
after each string, StringJoiner provides an easy way
to do that without much code to write.

Syntax:

public StringJoiner(CharSequence delimiter)


Above we saw we can create a string by String
Literal.

String demoString =”Welcome”;

Here the JVM checks the String Constant Pool. If


the string does not exist, then a new string
instance is created and placed in a pool. If the
string exists, then it will not create a new object.
Rather, it will return the reference to the same
instance. The cache that stores these string
instances is known as the String Constant pool or
String Pool. In earlier versions of Java up to JDK 6
String pool was located inside PermGen(Permanent
Generation) space. But in JDK 7 it is moved to the
main heap area.

Immutable String in Java


In Java, string objects are immutable. Immutable
simply means unmodifiable or unchangeable. Once
a string object is created its data or state can’t be
changed but a new string object is created.

Below is the implementation of the topic:

// Java Program to demonstrate Immutable String


in Java
import java.io.*;

class GFG {
public static void main(String[] args)
{
String s = "Sachin";

// concat() method appends


// the string at the end
s.concat(" Tendulkar");

// This will print Sachin


// because strings are
// immutable objects
System.out.println(s);
}
}

Output
Sachin
Here Sachin is not changed but a new object is
created with “Sachin Tendulkar”. That is why a
string is known as immutable.

As you can see in the given figure that two objects


are created but s reference variable still refers to
“Sachin” and not to “Sachin Tendulkar”. But if we
explicitly assign it to the reference variable, it will
refer to the “Sachin Tendulkar” object.
For Example:

// Java Program to demonstrate Explicitly assigned


strings
import java.io.*;

class GFG {
public static void main(String[] args)
{
String name = "Sachin";
name = name.concat(" Tendulkar");
System.out.println(name);
}
}

Output
Sachin Tendulkar
Memory Allotment of String
Whenever a String Object is created as a literal,
the object will be created in the String constant
pool. This allows JVM to optimize the initialization
of String literal.

Example:

String demoString = "Geeks";


The string can also be declared using a new
operator i.e. dynamically allocated. In case of
String are dynamically allocated they are assigned
a new memory location in the heap. This string will
not be added to the String constant pool.

Example:

String demoString = new String("Geeks");


If you want to store this string in the constant pool
then you will need to “intern” it.

Example:

String internedString = demoString.intern();


// this will add the string to string constant pool.
It is preferred to use String literals as it allows JVM
to optimize memory allocation.

An example that shows how to declare a String

// Java code to illustrate String


import java.io.*;
import java.lang.*;

class Test {
public static void main(String[] args)
{
// Declare String without using new operator
String name = "GeeksforGeeks";

// Prints the String.


System.out.println("String name = " + name);

// Declare String using new operator


String newString = new
String("GeeksforGeeks");

// Prints the String.


System.out.println("String newString = " +
newString);
}
}

Output
String name = GeeksforGeeks
String newString = GeeksforGeeks

Note: String Object is created in Heap area and


Literals are stored in special memory area known
as string constant pool.

Why did the String pool move from PermGen to the


normal heap area?
PermGen space is limited, the default size is just
64 MB. it was a problem with creating and storing
too many string objects in PermGen space. That’s
why the String pool was moved to a larger heap
area. To make Java more memory efficient, the
concept of string literal is used. By the use of the
‘new’ keyword, The JVM will create a new string
object in the normal heap area even if the same
string object is present in the string pool.

For example:

String demoString = new String("Bhubaneswar");


Let us have a look at the concept with a Java
program and visualize the actual JVM memory
structure:

Below is the implementation of the above


approach:

// Java program and visualize the


// actual JVM memory structure
// mentioned in image
class StringStorage {
public static void main(String args[])
{
// Declaring Strings
String s1 = "TAT";
String s2 = "TAT";
String s3 = new String("TAT");
String s4 = new String("TAT");

// Printing all the Strings


System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
System.out.println(s4);
}
}

Output
TAT
TAT
TAT
TAT
String Pool in Java
String Pool in Java

Note: All objects in Java are stored in a heap. The


reference variable is to the object stored in the
stack area or they can be contained in other
objects which puts them in the heap area also.

Example 1:

// Construct String from subset of char array

// Driver Class
class GFG {
// main function
public static void main(String args[])
{
byte ascii[] = { 71, 70, 71 };

String firstString = new String(ascii);


System.out.println(firstString);

String secondString = new String(ascii, 1, 2);


System.out.println(secondString);
}
}

Output
GFG
FG
Example 2:

// Construct one string from another

class GFG {
public static void main(String args[])
{

char characters[] = { 'G', 'f', 'g' };

String firstString = new String(characters);


String secondString = new String(firstString);

System.out.println(firstString);
System.out.println(secondString);
}
}

Output
Gfg
Gfg

STRING METHODS
Method Description Return Type

charAt() Returns the character at the specified index char


(position)

codePointAt() Returns the Unicode of the character at the int


specified index

codePointBefore() Returns the Unicode of the character before int


the specified index

codePointCount() Returns the number of Unicode values found int


in a string.

compareTo() Compares two strings lexicographically int

compareToIgnoreCase() Compares two strings lexicographically, int


ignoring case differences

concat() Appends a string to the end of another String


string

contains() Checks whether a string contains a boolean


sequence of characters

contentEquals() Checks whether a string contains the exact boolean


same sequence of characters of the
specified CharSequence or StringBuffer

copyValueOf() Returns a String that represents the String


characters of the character array

endsWith() Checks whether a string ends with the boolean


specified character(s)

equals() Compares two strings. Returns true if the boolean


strings are equal, and false if not

equalsIgnoreCase() Compares two strings, ignoring case boolean


considerations

format() Returns a formatted string using the String


specified locale, format string, and
arguments

getBytes() Converts a string into an array of bytes byte[]

getChars() Copies characters from a string to an array void


of chars

hashCode() Returns the hash code of a string int

indexOf() Returns the position of the first found int


occurrence of specified characters in a
string

intern() Returns the canonical representation for the String


string object

isEmpty() Checks whether a string is empty or not boolean

join() Joins one or more strings with a specified String


separator
lastIndexOf() Returns the position of the last found int
occurrence of specified characters in a
string

length() Returns the length of a specified string int

matches() Searches a string for a match against a boolean


regular expression, and returns the matches

offsetByCodePoints() Returns the index within this String that is int


offset from the given index by
codePointOffset code points

regionMatches() Tests if two string regions are equal boolean

replace() Searches a string for a specified value, and String


returns a new string where the specified
values are replaced

replaceAll() Replaces each substring of this string that String


matches the given regular expression with
the given replacement

replaceFirst() Replaces the first occurrence of a substring String


that matches the given regular expression
with the given replacement

split() Splits a string into an array of substrings String[]

startsWith() Checks whether a string starts with boolean


specified characters

subSequence() Returns a new character sequence that is a CharSequenc


subsequence of this sequence e

substring() Returns a new string which is the substring String


of a specified string

toCharArray() Converts this string to a new character array char[]

toLowerCase() Converts a string to lower case letters String

toString() Returns the value of a String object String

toUpperCase() Converts a string to upper case letters String

trim() Removes whitespace from both ends of a String


string

valueOf() Returns the string representation of the String


specified value

ESCAPE SEQUENCES IN JAVA


Control Sequence:

A control sequence is nothing however the


backslash(\) glued with a character (the character
which has to be escaped) is called a control
sequence.

Example:

\\ is a control sequence used for displaying a


backslash as output. so let’s use this concept in the
previous java code to avoid the compile-time error:

Java
public class Test {
public static void main(String[] args)
{
System.out.println("Hi geek, welcome
to \"GeeksforGeeks\".");
}
}
Output: Hi geek, welcome to "GeeksforGeeks".
Some Coding Examples of Java Escape Characters
Java code for the escape sequence \t:
Java
// \t -> It gives a tab between two words.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning\t Geeks! ");
}
}

Output:
Good Morning Geeks!
Java code for the escape sequence \b :
Java
// The escape sequence \b is a backspace character
// It moves the cursor one character back with
// or without deleting the character(depending
upon compiler)

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning\bg Geeks!
");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!

Java code for the escape sequence \n :


Java
// This \n escape sequence is for a new line.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \n
How are you all? ");
}
}

Output:
Good Morning Geeks!
How are you all?

Java code for the escape sequence \r:


Java
// This \r escape sequence is a carriage return
character
// It moves the output point back to the beginning
of the line without moving down a line (usually).

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \r
How are you all? ");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!
How are you all?

Java code for the escape sequence \f:


Java
// This \f escape sequence is a form feed character
// It is an old technique and used to indicate a page
break.

public class Test {


public static void main(String[] args)
{
System.out.println("Good Morning Geeks! \f
How are you all? ");
}
}

Output:(The output depends upon compiler)


Good Morning Geeks!
How are you all?

Java code for the escape sequence \’


Java
// This \' escape sequence is for printing a single
quotation mark on the text string

public class Gfg {


public static void main(String[] args)
{
System.out.println("Good Morning \'Geeks!\'
How are you all? ");
}
}

Output:
Good Morning 'Geeks!' How are you all?
Java code for the escape sequence \”
Java
// This \" escape sequence is for printing a double
quotation mark on the text string

public class Gfg {


public static void main(String[] args)
{
System.out.println("Good Morning \"Geeks!\"
How are you all? ");
}
}
Output:
Good Morning "Geeks!" How are you all?
Java code for the escape sequence \\
Java
// This \\ escape sequence is for printing a
backslash on the text string

public class Gfg {


public static void main(String[] args)
{
System.out.println("\\- this is a backslash. ");
}
}

Output:
\- this is a backslash.
Explanation:It contains two backslashes, this
means after reading the first \ the compiler read
the next \ as a new character

STRINGS PRACTICE SET

CONVERT A STRING TO LOWER CASE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.toLowerCase());
}
}
CONVERTING SPACES TO UNDERSCORES IN
STRING

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
System.out.println(a.replace(" ", "_"));
}
}

REPLACING A NAME WITH ANOTHER ONE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Yash Thanks a Lot";
System.out.println(letter.replace("Yash", a));
}
}

DETECTING THE PRESENCE OF DOUBLE AND


TRIPLE SPACES

mport java.util.Scanner;
i

public class HELLOWORLD{


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String b = a.replace(" ", "--");
String c = a.replace(" ", "---");
System.out.println(b);
System.out.println(c);
}
}

USE ESCAPE SEQUENCE TO MAKE A TITLE

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String a = sc.nextLine();
String letter = "Dear Harry , This java course
is nice . Thanks ! ";
}
}

************END OF PRACTICE SET ON


STRINGS***********

CONDITIONALS

Conditional statements are used to take decisions


based on some specific conditions. There are two
types of conditionals . They are : -

1) If - Else Statements.

2) Switch Case Statements .


IF - ELSE STATEMENTS

Decision-making in Java helps to write decision-


driven statements and execute a particular set of
code based on certain conditions. The if statement
alone tells us that if a condition is true it will
execute a block of statements and if the condition
is false it won’t. In this article, we will learn about
Java if-else.

If-Else in Java
If- else together represents the set of Conditional
statements in Java that are executed according to
the condition which is true.

Syntax of if-else Statement


if (condition)
{
// Executes this block if
// condition is true
}
else
{
// Executes this block if
// condition is false
}
Java if-else Flowchart
Java if-else flowchart

if-else Program in Java


Dry-Run of if-else statements
1. Program starts.
2. i is initialized to 20.
3. if-condition is checked. 20<15, yields false.
4. flow enters the else block.
4.a) "i is greater than 15" is printed
5. "Outside if-else block" is printed.
Below is the implementation of the above
statements:

// Java program to illustrate if-else statement

class IfElseDemo {
public static void main(String args[])
{
int i = 20;

if (i < 15)
System.out.println("i is smaller than 15");
else
System.out.println("i is greater than 15");

System.out.println("Outside if-else block");


}
}

Output
i is greater than 15
Outside if-else block
Nested if statement in Java
In Java, we can use nested if statements to create
more complex conditional logic. Nested if
statements are if statements inside other if
statements.

Syntax:
if (condition1) {
// code block 1
if (condition2) {
// code block 2
}
}
Below is the implementation of Nested if
statements:
// Java Program to implementation
// of Nested if statements

// Driver Class
public class AgeWeightExample {
// main function
public static void main(String[] args) {
int age = 25;
double weight = 65.5;

if (age >= 18) {


if (weight >= 50.0) {
System.out.println("You are eligible to
donate blood.");
} else {
System.out.println("You must weigh at
least 50 kilograms to donate blood.");
}
} else {
System.out.println("You must be at least 18
years old to donate blood.");
}
}
}

Output
You are eligible to donate blood.
Note: The first print statement is in a block of “if”
so the second statement is not in the block of “if”.
The third print statement is in else but that else
doesn’t have any corresponding “if”. That means
an “else” statement cannot exist without an “if”
statement.
SWITCH - CASE STATEMENTS

Unlike if-then and if-then-else statements,


the switch statement can have a number of
possible execution paths. A switch works with
the byte, short, char, and int primitive data types.
It also works with enumerated types (discussed
in Enum Types), the String class, and a few special
classes that wrap certain primitive
types: Character, Byte, Short,
and Integer (discussed in Numbers and Strings).

The following code example, SwitchDemo, declares


an int named month whose value represents a
month. The code displays the name of the month,
based on the value of month, using
the switch statement.

public class SwitchDemo {


public static void main(String[] args) {

int month = 8;
String monthString;
switch (month) {
case 1: monthString = "January";
break;
case 2: monthString = "February";
break;
case 3: monthString = "March";
break;
case 4: monthString = "April";
break;
case 5: monthString = "May";
break;
case 6: monthString = "June";
break;
case 7: monthString = "July";
break;
case 8: monthString = "August";
break;
case 9: monthString = "September";
break;
case 10: monthString = "October";
break;
case 11: monthString = "November";
break;
case 12: monthString = "December";
break;
default: monthString = "Invalid
month";
break;
}
System.out.println(monthString);
}
}

In this case, August is printed to standard output.

The body of a switch statement is known as


a switch block. A statement in the switch block can
be labeled with one or more case or default labels.
The switch statement evaluates its expression,
then executes all statements that follow the
matching case label.

You could also display the name of the month


with if-then-else statements:

int month = 8;
if (month == 1) {
System.out.println("January");
} else if (month == 2) {
System.out.println("February");
}
... // and so on

Deciding whether to use if-then-else statements or


a switch statement is based on readability and the
expression that the statement is testing. An if-
then-else statement can test expressions based on
ranges of values or conditions, whereas
a switch statement tests expressions based only on
a single integer, enumerated value,
or String object.

Another point of interest is the break statement.


Each break statement terminates the
enclosing switch statement. Control flow continues
with the first statement following the switch block.
The break statements are necessary because
without them, statements in switch blocks fall
through: All statements after the
matching case label are executed in sequence,
regardless of the expression of
subsequent case labels, until a break statement is
encountered. The
program SwitchDemoFallThrough shows
statements in a switch block that fall through. The
program displays the month corresponding to the
integer month and the months that follow in the
year:

public class SwitchDemoFallThrough {

public static void main(String[] args) {


java.util.ArrayList<String> futureMonths
=
new java.util.ArrayList<String>();

int month = 8;
switch (month) {
case 1: futureMonths.add("January");
case 2: futureMonths.add("February");
case 3: futureMonths.add("March");
case 4: futureMonths.add("April");
case 5: futureMonths.add("May");
case 6: futureMonths.add("June");
case 7: futureMonths.add("July");
case 8: futureMonths.add("August");
case 9:
futureMonths.add("September");
case 10: futureMonths.add("October");
case 11:
futureMonths.add("November");
case 12:
futureMonths.add("December");
break;
default: break;
}

if (futureMonths.isEmpty()) {
System.out.println("Invalid month
number");
} else {
for (String monthName : futureMonths)
{
System.out.println(monthName);
}
}
}
}

This is the output from the code:

August
September
October
November
December

Technically, the final break is not required because


flow falls out of the switch statement. Using
a break is recommended so that modifying the
code is easier and less error prone.
The default section handles all values that are not
explicitly handled by one of the case sections.

The following code example, SwitchDemo2, shows


how a statement can have multiple case labels.
The code example calculates the number of days
in a particular month:

class SwitchDemo2 {
public static void main(String[] args) {

int month = 2;
int year = 2000;
int numDays = 0;

switch (month) {
case 1: case 3: case 5:
case 7: case 8: case 10:
case 12:
numDays = 31;
break;
case 4: case 6:
case 9: case 11:
numDays = 30;
break;
case 2:
if (((year % 4 == 0) &&
!(year % 100 == 0))
|| (year % 400 == 0))
numDays = 29;
else
numDays = 28;
break;
default:
System.out.println("Invalid month.");
break;
}
System.out.println("Number of Days = "
+ numDays);
}
}

This is the output from the code:

Number of Days = 29

Using Strings in switch Statements

In Java SE 7 and later, you can use a String object


in the switch statement's expression. The following
code example, StringSwitchDemo, displays the
number of the month based on the value of
the String named month:

public class StringSwitchDemo {

public static int getMonthNumber(String


month) {

int monthNumber = 0;

if (month == null) {
return monthNumber;
}

switch (month.toLowerCase()) {
case "january":
monthNumber = 1;
break;
case "february":
monthNumber = 2;
break;
case "march":
monthNumber = 3;
break;
case "april":
monthNumber = 4;
break;
case "may":
monthNumber = 5;
break;
case "june":
monthNumber = 6;
break;
case "july":
monthNumber = 7;
break;
case "august":
monthNumber = 8;
break;
case "september":
monthNumber = 9;
break;
case "october":
monthNumber = 10;
break;
case "november":
monthNumber = 11;
break;
case "december":
monthNumber = 12;
break;
default:
monthNumber = 0;
break;
}

return monthNumber;
}

public static void main(String[] args) {

String month = "August";

int returnedMonthNumber =

StringSwitchDemo.getMonthNumber(month);

if (returnedMonthNumber == 0) {
System.out.println("Invalid month");
} else {

System.out.println(returnedMonthNumber);
}
}
}

The output from this code is 8.

The String in the switch expression is compared


with the expressions associated with
each case label as if the String.equals method
were being used. In order for
the StringSwitchDemo example to accept any
month regardless of case, month is converted to
lowercase (with the toLowerCase method), and all
the strings associated with the case labels are in
lowercase.

Note: This example checks if the expression in


the switch statement is null. Ensure that the
expression in any switch statement is not null to
prevent a NullPointerException from being thrown.

PRACTICE SET CHAPTER 4

DETERMINE THE OUTPUT

public class HELLOWORLD{


public static void main(String[] args) {
int a =10;
if(a=11){
System.out.println("i am 11");
}
else{
System.out.println("i am not 11");
}
}
}

OUTPUT :
I am 11
DETERMINE IF A STUDENT IS PASS OR FAIL

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();
int c = sc.nextInt();
int percentage = ((a+b+c)/300) * 100;
if(a>33 && b>33 && c>33 && percentage >
40){
System.out.println("Pass");
}
else{
System.out.println("Fail");
}
}
}

INCOME TAX CALCULATION

import java.util.Scanner;
class Income
{
public static void main(String args[])
{
double tax=0,it;
Scanner sc=new Scanner(System.in);
System.out.println("Enter income ");
it=sc.nextDouble();
if(it<=200000)
tax=0;
else if(it<=300000)
tax=0.1*(it-200000);
else if(it<=500000)
tax=(0.2*(it-300000))+(0.1*100000);
else if(it<=1000000)
tax=(0.3*(it-500000))
+(0.2*200000)+(0.1*100000);
else
tax=(0.4*(it-1000000))
+(0.3*500000)+(0.2*200000)+(0.1*100000);
System.out.println("Income tax amount is
"+tax);
}
}

WEEKDAYS OF THE WEEK


import java.util.Scanner;
public class Exercise5 {

public static void main(String[] args)


{
Scanner in = new Scanner(System.in);
System.out.print("Input number: ");
int day = in.nextInt();
System.out.println(getDayName(day));
}
// Get the name for the Week
public static String getDayName(int day) {
String dayName = "";
switch (day) {
case 1: dayName = "Monday"; break;
case 2: dayName = "Tuesday"; break;
case 3: dayName = "Wednesday"; break;
case 4: dayName = "Thursday"; break;
case 5: dayName = "Friday"; break;
case 6: dayName = "Saturday"; break;
case 7: dayName = "Sunday"; break;
default:dayName = "Invalid day range";
}
return dayName;
}
}

*******END OF PRACICE SET ON IF - ELSE *******

ROCK - PAPER - SCISSORS GAMES IN JAVA

import java.util.*;
public class RockPaperScissor {

public static void main(String[] args) {


Scanner scn = new
Scanner(System.in);

while(true) {

//1. RANDOMIZED COMPUTER MOVE

// array of string containing


available moves.
String [] availableMoves =
{"Rock", "Paper", "Scissors"};

// using Random() function on


indices of array so that it chooses a random move.
String computerMove =
availableMoves[new
Random().nextInt(availableMoves.length)];

System.out.println("Computer has
chosen it's move.");
System.out.println();
System.out.println("Now it's your
turn to choose. Good Luck!");
System.out.println();

//2. PLAYER MOVE

//input
String userMove;

// loop until the user chooses the


correct move
while(true) {
System.out.println("Please
choose your move from these available moves :
'Rock' 'Paper' 'Scissors' ");
System.out.println("Enter
the move you chose : ");
userMove = scn.nextLine();
// checking if user's move is
one of the available moves or not
if(userMove.equals("Rock")
|| userMove.equals("Paper") ||
userMove.equals("Scissors")){
System.out.println();
break;
}

// if user didn't enter a valid


input
System.out.println();
System.out.println("Invalid
Move!!");
System.out.println("Please
enter the move from the available moves only!");
System.out.println();
}

//printing what computer chose


System.out.println("Computer
chose : " + computerMove);

//3. COMPARING THE MOVES &


DECIDING THE WINNER

// checking for a tie

if(userMove.equals(computerMove)) {
System.out.println("Its a
tie!");
}

//checking for all other moves


possible
else if(userMove.equals("Rock"))
{

if(computerMove.equals("Paper")) {

System.out.println("Computer won!");

System.out.println("Better luck next time!");


}
else
if(computerMove.equals("Scissors")) {

System.out.println("You won!");

System.out.println("Congratulations!");
}
}

else if(userMove.equals("Paper"))
{

if(computerMove.equals("Rock")) {

System.out.println("You won!");

System.out.println("Congratulations!");
}
else
if(computerMove.equals("Scissors")) {

System.out.println("Computer won!");

System.out.println("Better luck next time!");


}
}

else
if(userMove.equals("Scissors")) {
if(computerMove.equals("Paper")) {

System.out.println("You won!");

System.out.println("Congratulations!");
}
else
if(computerMove.equals("Rock")) {

System.out.println("Computer won!");

System.out.println("Better luck next time!");


}
}

System.out.println();
String playAgain;
System.out.println("Do you want
to play again? ");

// loop until the user chooses the


correct option
while(true) {

System.out.println("Type
'yes' or 'no' ");
playAgain = scn.nextLine();

if(playAgain.equals("yes") ||
playAgain.equals("Yes") || playAgain.equals("no") ||
playAgain.equals("No")) {
System.out.println();

System.out.println("*******************************
**********************************************");
System.out.println();
break;
}
System.out.println();
System.out.println("Invalid
Input");
System.out.println();
}

if(playAgain.equals("no") ||
playAgain.equals("No")) {
break;
}
}
}}

Output 1 (Computer Won):

Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available


moves : 'Rock' 'Paper' 'Scissors'
Enter the move you chose :
Paper

Computer chose : Scissors


Computer won!
Better luck next time!

Do you want to play again?


Type 'yes' or 'no'
Yes
***************************************************
*********
Output 2 (Player wins):

Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available


moves : 'Rock' 'Paper' 'Scissors'
Enter the move you chose :
Rock

Computer chose : Scissors


You won!
Congratulations!

Do you want to play again?


Type 'yes' or 'no'
yes
***************************************************
*********

Output 3 (It's a Tie):

Computer has chosen it's move.

Now it's your turn to choose. Good Luck!

Please choose your move from these available


moves : 'Rock' 'Paper' 'Scissors'
Enter the move you chose :
Rock

Computer chose : Rock


Its a tie!

Do you want to play again?


Type 'yes' or 'no'
No
***************************************************
********

LOOPS IN JAVA

Looping in programming languages is a feature


which facilitates the execution of a set of
instructions/functions repeatedly while some
condition evaluates to true. Java provides three
ways for executing the loops. While all the ways
provide similar basic functionality, they differ in
their syntax and condition checking time.

There are three types of loops in java . They are : -

1. For Loops
2. While Loops
3. Do - While Loops

FOR LOOPS

Loops in Java come into use when we need to


repeatedly execute a block of statements. Java for
loop provides a concise way of writing the loop
structure. The for statement consumes the
initialization, condition, and increment/decrement
in one line thereby providing a shorter, easy-to-
debug structure of looping. Let us understand Java
for loop with Examples.

For Loop in Java


Syntax:

for (initialization expr; test expr; update exp)


{
// body of the loop
// statements we want to execute
}

Parts of Java For Loop


Java for loop is divided into various parts as
mentioned below:

Initialization Expression
Test Expression
Update Expression
1. Initialization Expression
In this expression, we have to initialize the loop
counter to some value.

Example:

int i=1;

2. Test Expression
In this expression, we have to test the condition. If
the condition evaluates to true then, we will
execute the body of the loop and go to the update
expression. Otherwise, we will exit from the for a
loop.

Example:

i <= 10

3. Update Expression:
After executing the loop body, this expression
increments/decrements the loop variable by some
value.

Example:

i++;

How does a For loop work?


Control falls into the for loop. Initialization is done
The flow jumps to Condition
Condition is tested.
If the Condition yields true, the flow goes into the
Body
If the Condition yields false, the flow goes outside
the loop
The statements inside the body of the loop get
executed.
The flow goes to the Updation
Updation takes place and the flow goes to Step 3
again
The for loop has ended and the flow has gone
outside.
Flow Chart For “for loop in Java”
Flow chart for loop in Java
Flow chart for loop in Java

Examples of Java For loop


Example 1: (This program will print 1 to 10)
Java

/*package whatever //do not write package name


here */
// Java program to write a code in for loop from 1 to
10

class GFG {
public static void main(String[] args)
{
for (int i = 1; i <= 10; i++) {
System.out.println(i);
}
}
}
Output
1
2
3
4
5
6
7
8
9
10

Example 2: This program will try to print “Hello


World” 5 times.
Java

// Java program to illustrate for loop


class forLoopDemo {
public static void main(String args[])
{
// Writing a for loop
// to print Hello World 5 times
for (int i = 1; i <= 5; i++)
System.out.println("Hello World");
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World

The complexity of the method:


Time Complexity: O(1)
Auxiliary Space : O(1)

Dry-Running Example 1
The program will execute in the following manner.

Program starts.
i is initialized with value 1.
Condition is checked. 1 <= 5 yields true.
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 <= 5 yields true.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 <= 5 yields true.
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 <= 5 yields true.
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 <= 5 yields true.
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 <= 5 yields false.
Flow goes outside the loop. Program terminates.
Example 3: (The Program prints the sum of x
ranging from 1 to 20)
Java

// Java program to illustrate for loop.


class forLoopDemo {
public static void main(String args[])
{
int sum = 0;

// for loop begins


// and runs till x <= 20
for (int x = 1; x <= 20; x++) {
sum = sum + x;
}
System.out.println("Sum: " + sum);
}
}
Output
Sum: 210

Nested For Loop in Java


Java Nested For Loop is a concept of using a for
loop inside another for loop(Similar to that of using
nested if-else). Let us understand this with an
example mentioned below:

Java

// Java Program to implement


// Nested for loop
import java.io.*;

// Driver Class
class GFG {
// main function
public static void main(String[] args)
{
// Printing a 1 to 5 (5 times)
// first loop
for (int i = 1; i <= 5; i++) {
// second loop
for (int j = 1; j <= 5; j++) {
System.out.print(j + " ");
}
System.out.println();
}
}
}
Output
1234 5
1234 5
1234 5
1234 5
1234 5

To know more about Nested loops refer Nested


loops in Java.

Java For-Each Loop


Enhanced For Loop or Java For-Each loop in Java is
another version of for loop introduced in Java 5.
Enhanced for loop provides a simpler way to
iterate through the elements of a collection or
array. It is inflexible and should be used only when
there is a need to iterate through the elements in a
sequential manner without knowing the index of
the currently processed element.

Note: The object/variable is immutable when


enhanced for loop is used i.e it ensures that the
values in the array can not be modified, so it can
be said as a read-only loop where you can’t update
the values as opposed to other loops where values
can be modified.

Syntax:
for (T element:Collection obj/array)
{
// loop body
// statement(s)
}

Let’s take an example to demonstrate how


enhanced for loop can be used to simplify the
work. Suppose there is an array of names and we
want to print all the names in that array. Let’s see
the difference between these two examples by this
simple implementation:

Java

// Java program to illustrate enhanced for loop


public class enhancedforloop {

// Main Function
public static void main(String args[])
{
// String array
String array[] = { "Ron", "Harry",
"Hermoine" };

// enhanced for loop


for (String x : array) {
System.out.println(x);
}

/* for loop for same function


for (int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
*/
}
}
Output
Ron
Harry
Hermoine

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space : O(1)

Recommendation: Use this form of statement


instead of the general form whenever possible. (as
per JAVA doc.)

Java Infinite for Loop


This is an infinite loop as the condition would never
return false. The initialization step is setting up the
value of variable i to 1, since we are incrementing
the value of i, it would always be greater than 1 so
it would never return false. This would eventually
lead to the infinite loop condition.

Example:

Java
// Java infinite loop
class GFG {
public static void main(String args[])
{
for (int i = 1; i >= 1; i++) {
System.out.println("Infinite Loop " + i);
}
}
}
Output
Infinite Loop 1
Infinite Loop 2
...

There is another method for calling the Infinite loop

If you use two semicolons ;; in the for loop, it will


be infinitive for a loop.

Syntax:

for(;;){
//code to be executed
}

Example:

Java
public class GFG {
public static void main(String[] args)
{
for (;;) {
System.out.println("infinitive loop");
}
}
}
Output
infinite loop
infinite loop
....

WHILE LOOP

Java while loop is a control flow statement that


allows code to be executed repeatedly based on a
given Boolean condition. The while loop can be
thought of as a repeating if statement. While loop
in Java comes into use when we need to repeatedly
execute a block of statements. The while loop is
considered as a repeating if statement. If the
number of iterations is not fixed, it is
recommended to use the while loop.

while loop in Java

Syntax:

while (test_expression)
{
// statements

update_expression;
}
Note: If we do not provide the curly braces ‘{‘ and
‘}’ after while( condition ) then by default while
statement will consider the immediate one
statement to be inside its block.

while (test_expression)
// single statement in while only

Parts of Java While Loop


The various parts of the While loop are:

1. Test Expression: In this expression, we have to


test the condition. If the condition evaluates to true
then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the
while loop.

Example:

i <= 10
2. Update Expression: After executing the loop
body, this expression increments/decrements the
loop variable by some value.
Example:

i++;
How Does a While loop execute?
Control falls into the while loop.
The flow jumps to Condition
Condition is tested.
If Condition yields true, the flow goes into the
Body.
If Condition yields false, the flow goes outside the
loop
The statements inside the body of the loop get
executed.
Updation takes place.
Control flows back to Step 2.
The while loop has ended and the flow has gone
outside.
Flowchart For while loop (Control Flow):
Flow chart while loop (for Control Flow

Examples of Java while loop


Example 1: This program will try to print “Hello
World” 5 times.

// Java program to illustrate while loop.

class whileLoopDemo {
public static void main(String args[])
{
// initialization expression
int i = 1;

// test expression
while (i < 6) {
System.out.println("Hello World");
// update expression
i++;
}
}
}
Output
Hello World
Hello World
Hello World
Hello World
Hello World

Complexity of the above method:


Time Complexity: O(1)
Auxiliary Space : O(1)

Dry-Running Example 1: The program will execute


in the following manner.

1. Program starts.
2. i is initialized with value 1.
3. Condition is checked. 1 < 6 yields true.
3.a) "Hello World" gets printed 1st time.
3.b) Updation is done. Now i = 2.
4. Condition is checked. 2 < 6 yields true.
4.a) "Hello World" gets printed 2nd time.
4.b) Updation is done. Now i = 3.
5. Condition is checked. 3 < 6 yields true.
5.a) "Hello World" gets printed 3rd time
5.b) Updation is done. Now i = 4.
6. Condition is checked. 4 < 6 yields true.
6.a) "Hello World" gets printed 4th time
6.b) Updation is done. Now i = 5.
7. Condition is checked. 5 < 6 yields true.
7.a) "Hello World" gets printed 5th time
7.b) Updation is done. Now i = 6.
8. Condition is checked. 6 < 6 yields false.
9. Flow goes outside the loop. Program terminates.

Example 2: This program will find the summation


of numbers from 1 to 10.

// Java program to illustrate while loop

class whileLoopDemo {
public static void main(String args[])
{
int x = 1, sum = 0;

// Exit when x becomes greater than 4


while (x <= 10) {
// summing up x
sum = sum + x;

// Increment the value of x for


// next iteration
x++;
}
System.out.println("Summation: " + sum);
}
}
Output
Summation: 55

Complexity of the above method


Time Complexity: O(1)
Auxiliary Space : O(1)

DO - WHILE LOOPS

Loops in Java come into use when we need to


repeatedly execute a block of statements. Java do-
while loop is an Exit control loop. Therefore, unlike
for or while loop, a do-while check for the condition
after executing the statements of the loop body.

Syntax:

do
{
// Loop Body
Update_expression
}

// Condition check
while (test_expression);
Note: The test_expression for the do-while loop
must return a boolean value , else we would get
compile-time error.

Application of do-while : Its example application is


showing some kind of menu to the users.

For example:

You are implementing a game where you show


some options to the user, press 1 to do this ..,
press 2 to do this .. etc and press ‘Q’ to quit the
game. So here you want to show the game menu
to the user at least once, so you write the code for
the game menu inside the do-while loop.

Illustration:

// Java Program to Illustrate One Time Iteration


// Inside do-while Loop
// When Condition IS Not Satisfied
// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// initial counter variable
int i = 0;

do {

// Body of loop that will execute minimum


// 1 time for sure no matter what
System.out.println("Print statement");
i++;
}

// Checking condition
// Note: It is being checked after
// minimum 1 iteration
while (i < 0);
}
}
Output
Print statement
Output explanation:

In the above code, we figured out that the


condition is checked later as the body inside do will
get executed one time without fail as the condition
is checked later onwards. Hence whenever we
want to display the menu and later on proceed
command on the terminal, we always use do-while
loop.

Components of do-while Loop


A. Test Expression: In this expression, we have to
test the condition. If the condition evaluates to true
then we will execute the body of the loop and go to
update expression. Otherwise, we will exit from the
while loop. For example:

i <= 10
B. Update Expression: After executing the loop
body, this expression increments/decrements the
loop variable by some value. For example:

i++;
Execution of do-While loop
Control falls into the do-while loop.
The statements inside the body of the loop get
executed.
Updation takes place.
The flow jumps to Condition
Condition is tested.
If Condition yields true, go to Step 6.
If Condition yields false, the flow goes outside the
loop
The flow goes back to Step 2.
Flowchart do-while loop:

Implementation:

Example 1: This program will try to print “Hello


World” 5 times.

// Java Program to Illustrate Do-while Loop

// Class
class GFG {
// Main driver method
public static void main(String args[])
{

// Declaring and initialization expression


int i = 1;

// Do-while loop
do {

// Body of do-while loop


// Print statement
System.out.println("Hello World");

// Update expression
i++;
}

// Test expression
while (i < 6);
}
}
Output:
Hello World
Hello World
Hello World
Hello World
Hello World

Auxiliary Space: O(1)

Output explanation:

The program will execute in the following manner


as follows:

Program starts.
i is initialized with value 1.
Execution enters the loop
“Hello World” gets printed 1st time.
Updation is done. Now i = 2.
Condition is checked. 2 < 6 yields true.
Execution enters the loop.
“Hello World” gets printed 2nd time.
Updation is done. Now i = 3.
Condition is checked. 3 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 3rd time
Updation is done. Now i = 4.
Condition is checked. 4 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 4th time
Updation is done. Now i = 5.
Condition is checked. 5 < 6 yields true.
Execution enters the loop
“Hello World” gets printed 5th time
Updation is done. Now i = 6.
Condition is checked. 6 < 6 yields false.
The flow goes outside the loop.
Example 2

// Java Program to Illustrate Do-while Loop

// Class
class GFG {

// Main driver method


public static void main(String args[])
{
// Declaring and initializing integer values
int x = 21, sum = 0;

// Do-while loop
do {
// Execution statements(Body of loop)

// Here, the line will be printed even


// if the condition is false
sum += x;
x--;
}

// Now checking condition


while (x > 10);

// Summing up
System.out.println("Summation: " + sum);
}
}
Output:
Summation: 176

Example 3: do-while loop without curly braces {}

/*package whatever //do not write package name


here */

import java.io.*;

class GFG {
public static void main (String[] args) {
int i=1;
do
// only single statement in do block
System.out.println("Hello GFG!");
// this condition is false so only do block will
execute
while(i>=3);
}
}
Output
Hello GFG!

BREAK AND CONTINUE STATEMENTS

The break and continue statements are the jump


statements that are used to skip some statements
inside the loop or terminate the loop immediately
without checking the test expression. These
statements can be used inside any loops such as
for, while, do-while loop.

Break: The break statement in java is used to


terminate from the loop immediately. When a
break statement is encountered inside a loop, the
loop iteration stops there, and control returns from
the loop immediately to the first statement after
the loop. Basically, break statements are used in
situations when we are not sure about the actual
number of iteration for the loop, or we want to
terminate the loop based on some condition.

Syntax :

break;
In Java, a break statement is majorly used for:

To exit a loop.
Used as a “civilized” form of goto.
Terminate a sequence in a switch statement.
Using break to exit a loop

Using break, we can force immediate termination


of a loop, bypassing the conditional expression and
any remaining code in the body of the loop. When
we use break inside the nested loops, it will only
break out of the innermost loop.

Example:

Java
// Java program to demonstrate using
// break to exit a loop
class GFG {
public static void main(String[] args)
{
// Initially loop is set to run from 0-9
for (int i = 0; i < 10; i++) {
// Terminate the loop when i is 5
if (i == 5)
break;
System.out.println("i: " + i);
}
System.out.println("Out of Loop");
}
}
Output
i: 0
i: 1
i: 2
i: 3
i: 4
Out of Loop
Using break as a Form of Goto

Java does not have a goto statement because it


provides a way to branch in an arbitrary and
unstructured manner. Java uses a label. A Label is
used to identify a block of code.

Syntax:
label:
{
statement1;
statement2;
statement3;
.
.
}
Now, the break statements can be used to jump
out of the target block. We cannot break to any
label which is not defined for an enclosing block.

Syntax:

break label;
Example:

Java
// Java program to demonstrates using break with
goto
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using break statement with label


break first;
}
System.out.println(i + " " + j);
}
}
}
}
Output
00
01
02
10
Using break to terminate a sequence in a switch
statement.

The switch statement is a multi-way branch


statement. It provides an easy way to dispatch
execution to different parts of code based on the
value of the expression. The break statement is
used inside the switch to terminate a statement
sequence. The break statement is optional. If
omitted, execution will continue on into the next
case.

Syntax:

switch (expression)
{
case value1:
statement1;
break;
case value2:
statement2;
break;
.
.
case valueN:
statementN;
break;
default:
statementDefault;
}
Example:

Java
// Java program to demonstrate using break to
terminate a
// sequence in a switch statement.
class GFG {
public static void main(String args[])
{
int i = 2;
switch (i) {
case 0:
System.out.println("i is zero.");
break;
case 1:
System.out.println("i is one.");
break;
case 2:
System.out.println("i is two.");
break;
default:
System.out.println("Invalid number");
}
}
}
Output
i is two.
Continue:

The continue statement in Java is used to skip the


current iteration of a loop. We can use continue
statement inside any types of loops such as for,
while, and do-while loop. Basically continue
statements are used in the situations when we
want to continue the loop but do not want the
remaining statement after the continue statement.
Syntax:

continue;
Using continue to continue a loop

Using continue, we can skip the current iteration of


a loop and jumps to the next iteration of the loop
immediately.

Example:

Java
// Java program to demonstrates the continue
// statement to continue a loop
class GFG {
public static void main(String args[])
{
for (int i = 0; i < 10; i++) {
// If the number is 2
// skip and continue
if (i == 2)
continue;

System.out.print(i + " ");


}
}
}
Output
013456789
Using continue as a labelled continue statement

The unlabeled continue statement is used to


continue the innermost loop. However, since JDK
1.5 java introduces another feature known as
labelled continue statement. We can use a labelled
continue statement to continue the outermost
loop.

Example:

Java
// Java program to demonstrates labeled continue
statement
class GFG {
public static void main(String args[])
{
// First label
first:
for (int i = 0; i < 3; i++) {
// Second label
second:
for (int j = 0; j < 3; j++) {
if (i == 1 && j == 1) {

// Using continue statement with label


continue first;
}
System.out.println(i + " " + j);
}
}
}
}
Output
00
01
02
10
20
21
22
Break Continue

The break statement is used to The continue statement is used to skip


terminate the loop immediately. the current iteration of the loop.

break keyword is used to indicate


continue keyword is used to indicate
break statements in java
continue statement in java programming.
programming.

We can use a break with the switch We can not use a continue with the
statement. switch statement.

The break statement terminates the The continue statement brings the next
whole loop early. iteration early.

It does not stop the execution of the


It stops the execution of the loop.
loop.

PRACTICE SET ON LOOPS

PATTERN PRINTING

public class HELLOWORLD {

public static void main(String[] args)


{
for(int i=4;i>=0;i--){
for(int j=0;j<i;j++){
System.out.print("*");
}
System.out.println();
}
}
}
SUM OF FIRST N EVEN NUMBERS

import java.util.*;
import java.lang.*;

public class GfG{

// function to find sum of


// first n even numbers
static int evenSum(int n)
{
int curr = 2, sum = 0;

// sum of first n even numbers


for (int i = 1; i <= n; i++) {
sum += curr;

// next even number


curr += 2;
}

// required sum
return sum;
}

// driver function
public static void main(String argc[])
{
int n = 20;
System.out.println("Sum of first " + n +
" Even numbers is: " +
evenSum(n));
}

}
PRINTING MULLTIPLICATION TABLE OF A
GIVEN NO.

import java.util.Scanner;

public class Exercise7 {

public static void main(String[] args) {


// Create a Scanner object to read input from the
user
Scanner in = new Scanner(System.in);

// Prompt the user to input a number


System.out.print("Input a number: ");

// Read and store the input number


int num1 = in.nextInt();

// Use a loop to calculate and print the


multiplication table for the input number
for (int i = 0; i < 10; i++) {
// Calculate and print the result of num1
multiplied by (i+1)
System.out.println(num1 + " x " + (i + 1) + " =
" + (num1 * (i + 1)));
}
}
}

Whatever we can do using one type of loop can be


done using another type of loops as well .

*************END OF PRACTICE SET ON


LOOPS************
FOR EACH LOOPS

For-each is another array traversing technique like


for loop, while loop, do-while loop introduced in
Java5.

It starts with the keyword for like a normal for-loop.


Instead of declaring and initializing a loop counter
variable, you declare a variable that is the same
type as the base type of the array, followed by a
colon, which is then followed by the array name.
In the loop body, you can use the loop variable you
created rather than using an indexed array
element.

It’s commonly used to iterate over an array or a


Collections class (eg, ArrayList)
Syntax:

for (type var : array)


{
statements using var;
}
Simple program with for each loop:

/*package whatever //do not write package name


here */

import java.io.*;

class Easy

public static void main(String[] args)


{

// array declaration

int ar[] = { 10, 50, 60, 80, 90 };

for (int element : ar)

System.out.print(element + " ");


}
}

Output

10 50 60 80 90
The above syntax is equivalent to:

for (int i=0; i<arr.length; i++)


{
type var = arr[i];
statements using var;
}
// Java program to illustrate
// for-each loop
class For_Each
{
public static void main(String[] arg)
{
{
int[] marks = { 125, 132, 95, 116, 110 };

int highest_marks = maximum(marks);


System.out.println("The highest score is " +
highest_marks);
}
}
public static int maximum(int[] numbers)
{
int maxSoFar = numbers[0];

// for each loop


for (int num : numbers)
{
if (num > maxSoFar)
{
maxSoFar = num;
}
}
return maxSoFar;
}
}

Output

The highest score is 132


Limitations of for-each loop
decision-making

For-each loops are not appropriate when you want


to modify the array:

for (int num : marks)


{
// only changes num, not the array element
num = num*2;
}
2. For-each loops do not keep track of index.
So we can not obtain array index using For-Each
loop

for (int num : numbers)


{
if (num == target)
{
return ???; // do not know the index of num
}
}
3. For-each only iterates forward over the
array in single steps

// cannot be converted to a for-each loop


for (int i=numbers.length-1; i>0; i--)
{
System.out.println(numbers[i]);
}
4. For-each cannot process two decision
making statements at once

// cannot be easily converted to a for-each loop


for (int i=0; i<numbers.length; i++)
{
if (numbers[i] == arr[i])
{ ...
}
}
5. For-each also has some performance
overhead over simple iteration:

/*package whatever //do not write package name


here */

import java.io.*;
import java.util.*;

class GFG {
public static void main (String[] args) {
List<Integer> list = new ArrayList<>();
long startTime;
long endTime;
for (int i = 0; i < 1000000; i++) {
list.add(i);
}
// Type 1
startTime =
Calendar.getInstance().getTimeInMillis();
for (int i : list) {
int a = i;
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("For each loop :: " +
(endTime - startTime) + " ms");

// Type 2
startTime =
Calendar.getInstance().getTimeInMillis();
for (int j = 0; j < list.size(); j++) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("Using collection.size() :: "
+ (endTime - startTime) + " ms");

// Type 3
startTime =
Calendar.getInstance().getTimeInMillis();
int size = list.size();
for (int j = 0; j < size; j++) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("By calculating
collection.size() first :: " + (endTime - startTime) +
" ms");

// Type 4
startTime =
Calendar.getInstance().getTimeInMillis();
for(int j = list.size()-1; j >= 0; j--) {
int a = list.get(j);
}
endTime =
Calendar.getInstance().getTimeInMillis();
System.out.println("Using [int j = list.size(); j
> size ; j--] :: " + (endTime - startTime) + " ms");
}
}

// This code is contributed by Ayush Choudhary


@gfg(code_ayush)

Output

For each loop :: 45 ms


Using collection.size() :: 11 ms
By calculating collection.size() first :: 13 ms
Using [int j = list.size(); j > size ; j--] :: 15 ms

ARRAYS IN JAVA

In Java, Array is a group of like-typed variables


referred to by a common name. Arrays in Java work
differently than they do in C/C++. Following are
some important points about Java arrays.

Arrays in Java

In Java, all arrays are dynamically allocated.


(discussed below)
Arrays may be stored in contiguous memory
[consecutive memory locations].
Since arrays are objects in Java, we can find their
length using the object property length. This is
different from C/C++, where we find length using
size of.
A Java array variable can also be declared like
other variables with [] after the data type.
The variables in the array are ordered, and each
has an index beginning with 0.
Java array can also be used as a static field, a local
variable, or a method parameter.
An array can contain primitives (int, char, etc.) and
object (or non-primitive) references of a class,
depending on the definition of the array. In the
case of primitive data types, the actual values
might be stored in contiguous memory locations
(JVM does not guarantee this behavior). In the case
of class objects, the actual objects are stored in a
heap segment. To learn more about Java Array, go
through Java programming course here.

Java Arrays

Note: This storage of arrays helps us randomly


access the elements of an array [Support Random
Access].

Creating, Initializing, and Accessing an Arrays


One-Dimensional Arrays
The general form of a one-dimensional array
declaration is

-- type var-name[];
-- type[] var-name;
An array declaration has two components: the type
and the name. type declares the element type of
the array. The element type determines the data
type of each element that comprises the array.
Like an array of integers, we can also create an
array of other primitive data types like char, float,
double, etc., or user-defined data types (objects of
a class). Thus, the element type for the array
determines what type of data the array will hold.

Example:

// both are valid declarations


int intArray[];
int[] intArray;
// similar to int we can declare
// byte , short, boolean, long, float
// double, char
// an array of references to objects of
// the class MyClass (a class created by user)
MyClass myClassArray[];
// array of Object
Object[] ao,
// array of Collection
// of unknown type
Collection[] ca;
Although the first declaration establishes that int
Array is an array variable, no actual array exists. It
merely tells the compiler that this variable (int
Array) will hold an array of the integer type. To link
int Array with an actual, physical array of integers,
you must allocate one using new and assign it to
int Array.

Instantiating an Array in Java


When an array is declared, only a reference of an
array is created. To create or give memory to the
array, you create an array like this: The general
form of new as it applies to one-dimensional arrays
appears as follows:
var-name = new type [size];
Here, type specifies the type of data being
allocated, size determines the number of elements
in the array, and var-name is the name of the array
variable that is linked to the array. To use new to
allocate an array, you must specify the type and
number of elements to allocate.

Example:

//declaring array
int intArray[];
// allocating memory to array
intArray = new int[20];
// combining both statements in one
int[] intArray = new int[20];
Note: The elements in the array allocated by new
will automatically be initialized to zero (for numeric
types), false (for boolean), or null (for reference
types). Do refer to default array values in Java.

Obtaining an array is a two-step process. First, you


must declare a variable of the desired array type.
Second, you must allocate the memory to hold the
array, using new, and assign it to the array
variable. Thus, in Java, all arrays are dynamically
allocated.

Array Literal in Java


In a situation where the size of the array and
variables of the array are already known, array
literals can be used.

// Declaring array literal


int[] intArray = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
The length of this array determines the length of
the created array.
There is no need to write the new int[] part in the
latest versions of Java.
Accessing Java Array Elements using for Loop
Each element in the array is accessed via its index.
The index begins with 0 and ends at (total array
size)-1. All the elements of array can be accessed
using Java for Loop.

// accessing the elements of the specified array


for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : "+ arr[i]);
Implementation:

// Java program to illustrate creating an array


// of integers, puts some values in the array,
// and prints each value to standard output.

class GFG {
public static void main(String[] args)
{
// declares an Array of integers.
int[] arr;

// allocating memory for 5 integers.


arr = new int[5];

// initialize the first elements of the array


arr[0] = 10;

// initialize the second elements of the array


arr[1] = 20;

// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;

// accessing the elements of the specified


array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at index " + i
+ " : " + arr[i]);
}
}

Output
Element at index 0 : 10
Element at index 1 : 20
Element at index 2 : 30
Element at index 3 : 40
Element at index 4 : 50
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space: O(1)

You can also access java arrays using for each


loops.

Arrays-in-Java

Arrays of Objects in Java


An array of objects is created like an array of
primitive-type data items in the following way.

Student[] arr = new Student[5]; //Student is a user-


defined class
Syntax:

-- data type[] arrName;


-- datatype arrName[];
-- datatype [] arrName;
Example of Arrays of Objects
Example 1:
Below is the implementation of the above
mentioned topic:

import java.io.*;

class GFG {
public static void main (String[] args) {

int [] arr=new int [4];


// 4 is the size of arr

System.out.println("Array Size:"+arr.length);
}
}

Output
Array Size:4
The Student Array contains five memory spaces
each of the size of Student class in which the
address of five Student objects can be stored. The
Student objects have to be instantiated using the
constructor of the Student class, and their
references should be assigned to the array
elements in the following way.

Example 2:
Below is the implementation of the above
mentioned topic:

// Java program to illustrate creating


// an array of objects

class Student {
public int roll_no;
public String name;
Student(int roll_no, String name)
{
this.roll_no = roll_no;
this.name = name;
}
}

// Elements of the array are objects of a class


Student.
public class GFG {
public static void main(String[] args)
{
// declares an Array of Student
Student[] arr;

// allocating memory for 5 objects of type


Student.
arr = new Student[5];

// initialize the first elements of the array


arr[0] = new Student(1, "aman");

// initialize the second elements of the array


arr[1] = new Student(2, "vaibhav");

// so on...
arr[2] = new Student(3, "shikar");
arr[3] = new Student(4, "dharmesh");
arr[4] = new Student(5, "mohit");

// accessing the elements of the specified


array
for (int i = 0; i < arr.length; i++)
System.out.println("Element at " + i + " : "
+ arr[i].roll_no + " "
+ arr[i].name);
}
}

Output
Element at 0 : 1 aman
Element at 1 : 2 vaibhav
Element at 2 : 3 shikar
Element at 3 : 4 dharmesh
Element at 4 : 5 mohit
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Example 3
An array of objects is also created like :

// Java program to illustrate creating


// an array of objects

class Student
{

public String name;


Student(String name)
{
this.name = name;
}
@Override
public String toString(){
return name;
}
}

// Elements of the array are objects of a class


Student.
public class GFG
{
public static void main (String[] args)
{
// declares an Array and initializing the
elements of the array
Student[] myStudents = new Student[]{new
Student("Dharma"),new Student("sanvi"),new
Student("Rupa"),new Student("Ajay")};

// accessing the elements of the specified


array
for(Student m:myStudents){
System.out.println(m);
}
}
}

Output
Dharma
sanvi
Rupa
Ajay
What happens if we try to access elements outside
the array size?
JVM throws ArrayIndexOutOfBoundsException to
indicate that the array has been accessed with an
illegal index. The index is either negative or
greater than or equal to the size of an array.

Below code shows what happens if we try to


access elements outside the array size:

// Code for showing error


"ArrayIndexOutOfBoundsException"

public class GFG {


public static void main(String[] args)
{
int[] arr = new int[4];
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
arr[3] = 40;

System.out.println(
"Trying to access element outside the size
of array");
System.out.println(arr[5]);
}
}
Output

Trying to access element outside the size of array


Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: Index
5 out of bounds for length 4
at GFG.main(GFG.java:13)
Example (Iterating the array):

public class GFG {


public static void main(String[] args)
{
int[] arr = new int[2];
arr[0] = 10;
arr[1] = 20;

for (int i = 0; i < arr.length; i++)


System.out.println(arr[i]);
}
}

Output
10
20
Complexity of the above method:
Time Complexity: O(n),here n is size of array.
Auxiliary Space: O(1), since no extra space
required.

Multidimensional Arrays in Java


Multidimensional arrays are arrays of arrays with
each element of the array holding the reference of
other arrays. These are also known as Jagged
Arrays. A multidimensional array is created by
appending one set of square brackets ([]) per
dimension.

Syntax of Java Multidimensional Array


There are 2 methods to declare Java
Multidimensional Arrays as mentioned below:

-- datatype [][] arrayrefvariable;


-- datatype arrayrefvariable[][];
Example:

// Java Program to demonstrate


// Java Multidimensional Array
import java.io.*;

// Driver class
class GFG {
public static void main(String[] args)
{
// Syntax
int[][] arr = new int[3][3];
// 3 row and 3 column

// Number of Rows
System.out.println("Number of Rows:"+
arr.length);
// Number of Columns
System.out.println("Number of Columns:"+
arr[0].length);
}
}

Output
Number of Rows:3
Number of Columns:3

MultiDimensional-Array

Multidimensional Array Declaration


int[][] intArray = new int[10][20]; //a 2D array or
matrix
int[][][] intArray = new int[10][20][10]; //a 3D array
Example of Muilti Dimensional Array in Java
Example 1:
Below is the implementation of the above method:

// Java Program to Multidimensional Array

// Driver Class
public class multiDimensional {
// main function
public static void main(String args[])
{
// declaring and initializing 2D array
int arr[][]
= { { 2, 7, 9 }, { 3, 6, 1 }, { 7, 4, 2 } };

// printing 2D array
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++)
System.out.print(arr[i][j] + " ");

System.out.println();
}
}
}

Output
279
361
742
Passing Arrays to Methods
Like variables, we can also pass arrays to methods.
For example, the below program passes the array
to method sum to calculate the sum of the array’s
values.

// Java program to demonstrate


// passing of array to method

public class Test {


// Driver method
public static void main(String args[])
{
int arr[] = { 3, 1, 2, 5, 4 };

// passing array to method m1


sum(arr);
}

public static void sum(int[] arr)


{
// getting sum of array values
int sum = 0;

for (int i = 0; i < arr.length; i++)


sum += arr[i];

System.out.println("sum of array values : " +


sum);
}
}

Output
sum of array values : 15
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Returning Arrays from Methods


As usual, a method can also return an array. For
example, the below program returns an array from
method m1.

// Java program to demonstrate


// return of array from method

class Test {
// Driver method
public static void main(String args[])
{
int arr[] = m1();

for (int i = 0; i < arr.length; i++)


System.out.print(arr[i] + " ");
}

public static int[] m1()


{
// returning array
return new int[] { 1, 2, 3 };
}
}

Output
123
Complexity of the above method:
Time Complexity: O(n)
Auxiliary Space : O(1)

Class Objects for Arrays


Every array has an associated Class object, shared
with all other arrays with the same component
type.

// Java program to demonstrate


// Class Objects for Arrays

class Test {
public static void main(String args[])
{
int intArray[] = new int[3];
byte byteArray[] = new byte[3];
short shortsArray[] = new short[3];

// array of Strings
String[] strArray = new String[3];

System.out.println(intArray.getClass());
System.out.println(
intArray.getClass().getSuperclass());
System.out.println(byteArray.getClass());
System.out.println(shortsArray.getClass());
System.out.println(strArray.getClass());
}
}

Output
class [I
class java.lang.Object
class [B
class [S
class [Ljava.lang.String;
Explanation of the above method:
The string “[I” is the run-time type signature for
the class object “array with component type int.”
The only direct superclass of an array type is
java.lang.Object.
The string “[B” is the run-time type signature for
the class object “array with component type byte.”
The string “[S” is the run-time type signature for
the class object “array with component type
short.”
The string “[L” is the run-time type signature for
the class object “array with component type of a
Class.” The Class name is then followed.
Java Array Members
Now, as you know that arrays are objects of a
class, and a direct superclass of arrays is a class
Object. The members of an array type are all of the
following:

The public final field length contains the number of


components of the array. Length may be positive
or zero.
All the members are inherited from class Object;
the only method of Object that is not inherited is
its clone method.
The public method clone() overrides the clone
method in class Object and throws no checked
exceptions.
Arrays Types and Their Allowed Element Types
Array Types Allowed Element Types
Primitive Type Arrays Any type which can be
implicitly promoted to declared type.
Object Type Arrays Either declared type objects
or it’s child class objects.
Abstract Class Type ArraysIts child-class objects
are allowed.
Interface Type Arrays Its implementation class
objects are allowed.
Cloning of Single-Dimensional Array in Java
When you clone a single-dimensional array, such
as Object[], a shallow copy is performed. This
means that the new array contains references to
the original array’s elements rather than copies of
the objects themselves. A deep copy occurs only
with arrays containing primitive data types, where
the actual values are copied.

Below is the implementation of the above method:

// Java program to demonstrate


// cloning of one-dimensional arrays

class Test {
public static void main(String args[])
{
int intArray[] = { 1, 2, 3 };

int cloneArray[] = intArray.clone();

// will print false as shallow copy is created


System.out.println(intArray == cloneArray);

for (int i = 0; i < cloneArray.length; i++) {


System.out.print(cloneArray[i] + " ");
}
}
}

Output
false
123
Explanation of the above Program:
In this example, intArray and cloneArray are not
the same object (intArray == cloneArray is false),
but they share the same contents because
primitive values are deeply copied.
For arrays containing objects, the references are
copied, so the objects themselves are not
duplicated.
Clone-of-Array

Cloning Multidimensional Array in Java


A clone of a multi-dimensional array (like Object[]
[]) is a “shallow copy,” however, which is to say
that it creates only a single new array with each
element array a reference to an original element
array, but subarrays are shared.

// Java program to demonstrate


// cloning of multi-dimensional arrays

class Test {
public static void main(String args[])
{
int intArray[][] = { { 1, 2, 3 }, { 4, 5 } };

int cloneArray[][] = intArray.clone();

// will print false


System.out.println(intArray == cloneArray);

// will print true as shallow copy is created


// i.e. sub-arrays are shared
System.out.println(intArray[0] ==
cloneArray[0]);
System.out.println(intArray[1] ==
cloneArray[1]);
}
}

Output
false
true
True
PRACTICE SET ON ARRAYS

CREATING AN ARRAY OF 5 FLOATS AND


SUMMING THEM

public class HELLOWORLD{


public static void main(String[] args) {
float []arr = {2.5f,23.25f,45.23f,21.32f,52.36f};
float sum = 0;
for(int i=0;i<arr.length;i++){
sum = sum + arr[i] ;
}
System.out.println(sum);
}
}

FINDING AN ELEMENT IN AN ARRAY

public class HELLOWORLD{


public static void main(String[] args) {
int arr[] = {2,3,4,5,6,7,8};
int element = 8;
for (int i : arr) {
if(arr[i] == element){
System.out.println("Present");
}
else{
System.out.println("Absent");
}
}
}
}
CALCULATING AVERAGE OF ARRAY

public class HELLOWORLD{


public static void main(String[] args) {
int arr[] = {2,3,4,5,6,7,8};
int sum = 0;
for (int i : arr) {
sum = sum + arr[i] ;
}
int avg = sum / arr.length;
System.out.println(avg);
}
}

ADDING TWO MATRICES OF SIZE 2 x 3

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[][] = new int[3][3] ;
int arr1[][] = new int[3][3] ;
int sum[][] = new int [3][3];
//INPUT OF ARRAY 1
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr[i][j] = sc.nextInt();
}
}
//INPUT OF ARRAY 2
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
arr1[i][j] = sc.nextInt();
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
sum[i][j] = arr[i][j] + arr1[i][j] ;
}
}
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}

REVERSE AN ARRAY

import java.util.Scanner;
public class HELLOWORLD{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int arr[] = {3,4,5};
for (int i =0;i<arr.length/2 ; i++) {
int temp = arr[i] ;
arr[i] = arr[arr.length - i - 1];
arr[arr.length - i - 1] = temp;
}
for(int i=0;i<arr.length;i++){
System.out.println(arr[i]);
}
}
}

FINDING MAXIMUM ELEMENT IN AN ARRAY

// Java Program to find maximum in arr[]

// Driver Class
class Test
{
// array declared
static int arr[] = {10, 324, 45, 90, 9808};

// Method to find maximum in arr[]


static int largest()
{
int i;

// Initialize maximum element


int max = arr[0];

// Traverse array elements from second and


// compare every element with current max
for (i = 1; i < arr.length; i++)
if (arr[i] > max)
max = arr[i];

return max;
}

// Driver method
public static void main(String[] args)
{
System.out.println("Largest in given array is "
+ largest());
}
}

FINDING MINIMUM ELEMENT IN AN ARRAY

import java.util.*;
class Array {
public static void main(String[] args) {
int a[]={1,423,6,46,34,23,13,53,4};

//Implemented inbuilt function to sort array


Arrays.sort(a);

// after sorting the value at 0th position will


minimum and
//nth position will be maximum
System.out.println("min-"+a[0]+"
max-"+a[a.length-1]);
}
}

SORTING AN ARRAY

import java.util.Arrays;

class GFG {
public static void main(String args[])
{
int[] arr = { 5, -2, 23, 7, 87, -42, 509 };
System.out.println("The original array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
Arrays.sort(arr);
System.out.println("\nThe sorted array is: ");
for (int num : arr) {
System.out.print(num + " ");
}
}
}

**********END OF PRACTICE SET ON


ARRAYS*************

METHODS IN JAVA

In general, a method is a way to perform some


task. Similarly, the method in Java is a collection of
instructions that performs a specific task. It
provides the reusability of code.

We can also easily modify code using methods. In


this section, we will learn what is a method in Java,
types of methods, method declaration, and how to
call a method in Java.

A method is a block of code or collection of


statements or a set of code grouped together to
perform a certain task or operation. It is used to
achieve the reusability of code. We write a
method once and use it many times. We do not
require to write code again and again. It also
provides the easy
modification and readability of code, just by
adding or removing a chunk of code. The method is
executed only when we call or invoke it.

The main() is the starting point for JVM to start


execution of a Java program. Without the main()
method, JVM will not execute the program. The
syntax of the main() method is:

public: It is an access specifier. We should use a


public keyword before the main() method so that
JVM can identify the execution point of the
program. If we use private, protected, and default
before the main() method, it will not be visible to
JVM.

static: You can make a method static by using the


keyword static. We should call the main() method
without creating an object. Static methods are the
method which invokes without creating the
objects, so we do not need any object to call the
main() method.

void: In Java, every method has the return type.


Void keyword acknowledges the compiler that
main() method does not return any value.

main(): It is a default signature which is


predefined in the JVM. It is called by JVM to execute
a program line by line and end the execution after
completion of this method. We can also overload
the main() method.

String args[]: The main() method also accepts


some data from the user. It accepts a group of
strings, which is called a string array. It is used to
hold the command line arguments in the form of
string values.

1. main(String args[])

Here, agrs[] is the array name, and it is of String


type. It means that it can store a group of string.
Remember, this array can also store a group of
numbers but in the form of string only. Values
passed to the main() method is called arguments.
These arguments are stored into args[] array, so
the name args[] is generally used for it.

What happens if the main() method is written


without String args[]?

The program will compile, but not run, because JVM


will not recognize the main() method. Remember
JVM always looks for the main() method with a
string type array as a parameter.

Execution Process

First, JVM executes the static block, then it


executes static methods, and then it creates the
object needed by the program. Finally, it executes
the instance methods. JVM executes a static block
on the highest priority basis. It means JVM first
goes to static block even before it looks for the
main() method in the program.

Example

1. class Demo
2. {
3. static //static block
4. {
5. System.out.println("Static block");
6. }
7. public static void main(String args[]) //static met
hod
8. {
9. System.out.println("Static method");
10. }
11. }

Output:

Static block
Static method

We observe that JVM first executes the static block,


if it is present in the program. After that it searches
for the main() method. If the main() method is not
found, it gives error.

Example

A program that does not have the main() method


gives an error at run time.

1. class DemoStaticBlock
2. {
3. Static //static block
4. {
5. System.out.println("Static block");
6. }
7. }

Output:
Error: Main method not found in the class Demo,
please define the main method as:
public static void main(String[] args)
or a JavaFX application class must extend
javafx.application.Application

So the main() method should always be written as:

1. public static void main(String args[])

We can interchange public and static and write it


as follows:

1. static public void main(String args[])

We can also use the different name for the String


type array and write it as:

1. static public void main(String[] x)

Different ways of writing main() method are:

1. static public void main(String []x)


2. static public void main(String...args)

String...args: It allows the method to accept zero


or multiple arguments. There should be exactly
three dots between String and array; otherwise, it
gives an error.

Example

A program that has no main() method, but compile


and runs successfully.
1. abstract class DemoNoMain extends javafx.appli
cation.Application
2. {
3. static //static block
4. {
5. System.out.println("Java");
6. System.exit(0);
7. }
8. }

Output:

Java

Overloading of main() method

We can also overload the main() method. We can


define any number of main() method in the class,
but the method signature must be different.

Example

1. class OverloadMain
2. {
3. public static void main(int a) //overloaded main
method
4. {
5. System.out.println(a);
6. }
7. public static void main(String args[])
8. {
9. System.out.println("main method incoked");
10. main(6);
11. }
12. }

Output:

main method invoked


6
The method declaration provides information about
method attributes, such as visibility, return-type,
name, and arguments. It has six components that
are known as method header, as we have shown
in the following figure.

Method Signature: Every method has a method


signature. It is a part of the method declaration. It
includes the method name and parameter list.

Access Specifier: Access specifier or modifier is


the access type of the method. It specifies the
visibility of the method. Java provides four types of
access specifier:
 Public: The method is accessible by all classes
when we use public specifier in our application.
 Private: When we use a private access
specifier, the method is accessible only in the
classes in which it is defined.
 Protected: When we use protected access
specifier, the method is accessible within the
same package or subclasses in a different
package.
 Default: When we do not use any access
specifier in the method declaration, Java uses
default access specifier by default. It is visible
only from the same package only.

Return Type: Return type is a data type that the


method returns. It may have a primitive data type,
object, collection, void, etc. If the method does not
return anything, we use void keyword.

Method Name: It is a unique name that is used to


define the name of a method. It must be
corresponding to the functionality of the method.
Suppose, if we are creating a method for
subtraction of two numbers, the method name
must be subtraction(). A method is invoked by its
name.

Parameter List: It is the list of parameters


separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable
name. If the method has no parameter, left the
parentheses blank.

Method Body: It is a part of the method


declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly
braces.
While defining a method, remember that the
method name must be a verb and start with
a lowercase letter. If the method name has more
than two words, the first name must be a verb
followed by adjective or noun. In the multi-word
method name, the first letter of each word must be
in uppercase except the first word. For example:

Single-word method name: sum(), area()

Multi-word method name: areaOfCircle(),


stringComparision()

It is also possible that a method has the same


name as another method name in the same class,
it is known as method overloading.

There are two types of methods in Java:

 Predefined Method
 User-defined Method

Predefined Method

In Java, predefined methods are the method that is


already defined in the Java class libraries is known
as predefined methods. It is also known as
the standard library method or built-in
method. We can directly use these methods just
by calling them in the program at any point. Some
pre-defined methods are length(), equals(),
compareTo(), sqrt(), etc. When we call any of
the predefined methods in our program, a series of
codes related to the corresponding method runs in
the background that is already stored in the
library.

Each and every predefined method is defined


inside a class. Such as print() method is defined in
the java.io.PrintStream class. It prints the
statement that we write inside the method. For
example, print("Java"), it prints Java on the
console.

Let's see an example of the predefined method.

Demo.java

1. public class Demo


2. {
3. public static void main(String[] args)
4. {
5. // using the max() method of Math class
6. System.out.print("The maximum number is: " + Ma
th.max(9,7));
7. }
8. }

Output:

The maximum number is: 9

In the above example, we have used three


predefined methods main(), print(), and max().
We have used these methods directly without
declaration because they are predefined. The
print() method is a method of PrintStream class
that prints the result on the console. The max()
method is a method of the Math class that returns
the greater of two numbers.
We can also see the method signature of any
predefined method by using the
link https://docs.oracle.com/. When we go through
the link and see the max() method signature, we
find the following:

In the above method signature, we see that the


method signature has access specifier public, non-
access modifier static, return type int, method
name max(), parameter list (int a, int b). In the
above example, instead of defining the method, we
have just invoked the method. This is the
advantage of a predefined method. It makes
programming less complicated.

Similarly, we can also see the method signature of


the print() method.

User-defined Method

The method written by the user or programmer is


known as a user-defined method. These methods
are modified according to the requirement.

How to Create a User-defined Method


Let's create a user defined method that checks the
number is even or odd. First, we will define the
method.

1. //user defined method


2. public static void findEvenOdd(int num)
3. {
4. //method body
5. if(num%2==0)
6. System.out.println(num+" is even");
7. else
8. System.out.println(num+" is odd");
9. }

We have defined the above method named


findevenodd(). It has a parameter num of type int.
The method does not return any value that's why
we have used void. The method body contains the
steps to check the number is even or odd. If the
number is even, it prints the number is even, else
prints the number is odd.

How to Call or Invoke a User-defined Method

Once we have defined a method, it should be


called. The calling of a method in a program is
simple. When we call or invoke a user-defined
method, the program control transfer to the called
method.

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from the user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }

In the above code snippet, as soon as the compiler


reaches at line findEvenOdd(num), the control
transfer to the method and gives the output
accordingly.

Let's combine both snippets of codes in a single


program and execute it.

EvenOdd.java

1. import java.util.Scanner;
2. public class EvenOdd
3. {
4. public static void main (String args[])
5. {
6. //creating Scanner class object
7. Scanner scan=new Scanner(System.in);
8. System.out.print("Enter the number: ");
9. //reading value from user
10. int num=scan.nextInt();
11. //method calling
12. findEvenOdd(num);
13. }
14. //user defined method
15. public static void findEvenOdd(int num)
16. {
17. //method body
18. if(num%2==0)
19. System.out.println(num+" is even");
20. else
21. System.out.println(num+" is odd");
22. }
23. }

Output 1:

Enter the number: 12


12 is even

Output 2:

Enter the number: 99


99 is odd

Let's see another program that return a value to


the calling method.

In the following program, we have defined a


method named add() that sum up the two
numbers. It has two parameters n1 and n2 of
integer type. The values of n1 and n2 correspond
to the value of a and b, respectively. Therefore, the
method adds the value of a and b and store it in
the variable s and returns the sum.

Addition.java

1. public class Addition


2. {
3. public static void main(String[] args)
4. {
5. int a = 19;
6. int b = 5;
7. //method calling
8. int c = add(a, b); //a and b are actual parameters
9. System.out.println("The sum of a and b is= " + c);
10. }
11. //user defined method
12. public static int add(int n1, int n2) //n1 an
d n2 are formal parameters
13. {
14. int s;
15. s=n1+n2;
16. return s; //returning the sum
17. }
18. }

Output:

The sum of a and b is= 24

Static Method

A method that has static keyword is known as


static method. In other words, a method that
belongs to a class rather than an instance of a
class is known as a static method. We can also
create a static method by using the
keyword static before the method name.

The main advantage of a static method is that we


can call it without creating an object. It can access
static data members and also change the value of
it. It is used to create an instance method. It is
invoked by using the class name. The best
example of a static method is the main() method.

Example of static method

Display.java

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static meth
od.");
10. }
11. }

Output:

It is an example of a static method.

Instance Method

The method of the class is known as an instance


method. It is a non-static method defined in the
class. Before calling or invoking the instance
method, it is necessary to create an object of its
class. Let's see an example of an instance method.

InstanceMethodExample.java

1. public class InstanceMethodExample


2. {
3. public static void main(String [] args)
4. {
5. //Creating an object of the class
6. InstanceMethodExample obj = new InstanceMetho
dExample();
7. //invoking instance method
8. System.out.println("The sum is: "+obj.add(12, 13));

9. }
10. int s;
11. //user-defined method because we have not us
ed static keyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }

Output:

The sum is: 25

There are two types of instance method:

o Accessor Method
o Mutator Method

Accessor Method: The method(s) that reads the


instance variable(s) is known as the accessor
method. We can easily identify it because the
method is prefixed with the word get. It is also
known as getters. It returns the value of the
private field. It is used to get the value of the
private field.

Example

1. public int getId()


2. {
3. return Id;
4. }

Mutator Method: The method(s) read the


instance variable(s) and also modify the values.
We can easily identify it because the method is
prefixed with the word set. It is also known
as setters or modifiers. It does not return
anything. It accepts a parameter of the same data
type that depends on the field. It is used to set the
value of the private field.

Example

1. public void setRoll(int roll)


2. {
3. this.roll = roll;
4. }

Example of accessor and mutator method

Student.java

1. public class Student


2. {
3. private int roll;
4. private String name;
5. public int getRoll() //accessor method
6. {
7. return roll;
8. }
9. public void setRoll(int roll) //mutator method
10. {
11. this.roll = roll;
12. }
13. public String getName()
14. {
15. return name;
16. }
17. public void setName(String name)
18. {
19. this.name = name;
20. }
21. public void display()
22. {
23. System.out.println("Roll no.: "+roll);
24. System.out.println("Student name: "+name);
25. }
26. }

Abstract Method

The method that does not has method body is


known as abstract method. In other words, without
an implementation is known as abstract method. It
always declares in the abstract class. It means
the class itself must be abstract if it has abstract
method. To create an abstract method, we use the
keyword abstract.

Syntax

1. abstract void method_name();

Example of abstract method

Demo.java

1. abstract class Demo //abstract class


2. {
3. //abstract method declaration
4. abstract void display();
5. }
6. public class MyClass extends Demo
7. {
8. //method impelmentation
9. void display()
10. {
11. System.out.println("Abstract method?");
12. }
13. public static void main(String args[])
14. {
15. //creating object of abstract class
16. Demo obj = new MyClass();
17. //invoking abstract method
18. obj.display();
19. }
20. }

Output:

Abstract method…

Factory method

It is a method that returns an object to the class to


which it belongs. All static methods are factory
methods. For example, NumberFormat obj =
NumberFormat.getNumberInstance();

Different ways of Method Overloading in Java

 If a class has multiple methods having same


name but parameters of the method should be
different is known as Method Overloading.

 If we have to perform only one operation, having


same name of the methods increases the
readability of the program.
 Suppose you have to perform addition of the
given numbers but there can be any number of
arguments, if you write the method such as
a(int,int) for two parameters, and b(int,int,int)
for three parameters then it may be difficult for
you to understand the behavior of the method
because its name differs.

Method overloading in java is based on the number


and type of the parameters passed as an argument
to the methods. We can not define more than one
method with the same name, Order, and type of
the arguments. It would be a compiler error. The
compiler does not consider the return type while
differentiating the overloaded method. But you
cannot declare two methods with the same
signature and different return types. It will throw a
compile-time error. If both methods have the same
parameter types, but different return types, then it
is not possible.

Java can distinguish the methods with different


method signatures. i.e. the methods can have the
same name but with different parameters list (i.e.
the number of the parameters, the order of the
parameters, and data types of the parameters)
within the same class.

Parameters should be different means

1. Type of parameter should be different


Eg:

Java

/*package whatever //do not write package name


here */

import java.io.*;

void add(int, int);

void add(double,double);

class Adder{

void add(int a, int b){

System.out.println(“sum =”+(a+b));

void add(double a, double b){

System.out.println(“sum=”+(a+b));

public static void main(String[] args){

Adder ad=new Adder();


ad.add(5,6);

ad.add(5.4,7.2);

}}

2. Number of parameter should be different

Eg:

Java

class Adder{

void add(int a, int b){

System.out.println(“sum =”+(a+b));

void add(int a, int b,int c){

System.out.println(“sum=”+(a+b+c));

public static void main(String[] args){

Adder ad=new Adder();

ad.add(5,6);

ad.add(5.4,7.2);

}}
Geeks, now you would be up to why do we need
method overloading?

If we need to do some kind of operation in different


ways i.e. for different inputs. In the example
described below, we are doing the addition
operation for different inputs. It is hard to find
many meaningful names for a single action.

Ways of Overloading Methods

Method overloading can be done by changing:

The number of parameters in two methods.

The data types of the parameters of methods.

The Order of the parameters of methods.

Let us propose examples in order to illustrate each


way while overloading methods. They are as
follows:

Method 1: By changing the number of parameters.


Java

Yash Malani, [21-08-2024 21:35]

// Java Program to Illustrate Method Overloading

// By Changing the Number of Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Addition {

// Method 1

// Adding two integer values

public int add(int a, int b)

int sum = a + b;

return sum;

}
// Method 2

// Adding three integer values

public int add(int a, int b, int c)

int sum = a + b + c;

return sum;

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating object of above class inside main()

// method

Addition ob = new Addition();


// Calling method to add 3 numbers

int sum1 = ob.add(1, 2);

// Printing sum of 2 numbers

System.out.println("sum of the two integer


value :"

+ sum1);

// Calling method to add 3 numbers

int sum2 = ob.add(1, 2, 3);

// Printing sum of 3 numbers

System.out.println(

"sum of the three integer value :" + sum2);

Output

sum of the two integer value :3

sum of the three integer value :6

Method 2: By changing the Data types of the


parameters

Java
// Java Program to Illustrate Method Overloading

// By Changing Data Types of the Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Addition {

// Adding three integer values

public int add(int a, int b, int c)

int sum = a + b + c;

return sum;

// adding three double values.

public double add(double a, double b, double c)

{
double sum = a + b + c;

return sum;

class GFG {

public static void main(String[] args)

Addition ob = new Addition();

int sum2 = ob.add(1, 2, 3);

System.out.println(

"sum of the three integer value :" + sum2);

double sum3 = ob.add(1.0, 2.0, 3.0);

System.out.println("sum of the three double


value :"

+ sum3);

Output
sum of the three integer value :6

sum of the three double value :6.0

Method 3: By changing the Order of the


parameters

Java

// Java Program to Illustrate Method Overloading

// By changing the Order of the Parameters

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Geek {

// Method 1

public void geekIdentity(String name, int id)

// Printing name and id of person


System.out.println("geekName :" + name + "
"

+ "Id :" + id);

// Method 2

public void geekIdentity(int id, String name)

// Again printing name and id of person

System.out.println("Id :" + id + " "

+ "geekName :" + name);

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

{
// Creating object of above class

Geek geek = new Geek();

// Passing name and id

// Note: Reversing order

geek.geekIdentity("Mohit", 1);

geek.geekIdentity(2, "shubham");

Output

geekName :Mohit Id :1

geekName :shubham Id :2

Note: Now geeks you must be wondering what will


happen when the method signature is the same
and the return type is different?
Here the compiler will give an error as the return
value alone is not sufficient for the compiler to
figure out which function it has to call. Only if both
methods have different parameter types (so, they
have a different signature), then Method
overloading is possible.

Example 4

Java

// Java Program to Illustrate Error Thrown in

// Method Overloading When Method Signature is


Same and

// ReturnType is Different

// Importing required classes

import java.io.*;

// Class 1

// Helper class

class Addition {

// Method 1

// Adding two integer value


public int add(int a, int b)

// Summing up

int sum = a + b;

// Returning the sum

return sum;

// Method 2

// Adding three integer value

public double add(int a, int b)

double sum = a + b + 0.0;

return sum;

// Class 2

// Main class

class GFG {
// Main driver method

public static void main(String[] args)

// Try block to check for exceptions

try {

// Creating an object of above class

Addition ob = new Addition();

// Calling method 1 to sum 2 numbers

int sum1 = ob.add(1, 2);

// Printing sum of two numbers

System.out.println(

"sum of the two integer value :" +


sum1);

// Calling method 2 to sum 3 numbers

int sum2 = ob.add(1, 2);

// Printing sum of three numbers

System.out.println(
"sum of the three integer value :" +
sum2);

// Catch block to handle exceptions

catch (Exception e) {

// Display the exceptions on console

System.out.println(e);

OUTPUT

VARIABLE ARGUMENTS IN JAVA


Variable Arguments (Varargs) in Java is a method
that takes a variable number of arguments.
Variable Arguments in Java simplifies the creation
of methods that need to take a variable number of
arguments.

Need of Java Varargs

Until JDK 4, we cant declare a method with variable


no. of arguments. If there is any change in the
number of arguments, we have to declare a new
method. This approach increases the length of the
code and reduces readability.

Before JDK 5, variable-length arguments could be


handled in two ways. One uses an overloaded
method(one for each), and another puts the
arguments into an array and then passes this array
to the method. Both of them are potentially error-
prone and require more code.

To resolve these problems, Variable Arguments


(Varargs) were introduced in JDK 5. From JDK 5
onwards, we can declare a method with a variable
number of arguments. Such types of methods are
called Varargs methods. The varargs feature offers
a simpler, better option.

Syntax of Varargs

Internally, the Varargs method is implemented by


using the single dimensions arrays concept. Hence,
in the Varargs method, we can differentiate
arguments by using Index. A variable-length
argument is specified by three periods or dots(…).
For Example,

public static void fun(int ... a)

// method body

This syntax tells the compiler that fun( ) can be


called with zero or more arguments. As a result,
here, a is implicitly declared as an array of type
int[].

Below is a code snippet for illustrating the above


concept :

// Java program to demonstrate varargs

class Test1 {

// A method that takes variable

// number of integer arguments.

static void fun(int... a)

System.out.println("Number of arguments: "


+ a.length);

// using for each loop to display contents of a

for (int i : a)

System.out.print(i + " ");

System.out.println();

// Driver code

public static void main(String args[])

// Calling the varargs method with

// different number of parameters

// one parameter

fun(100);

// four parameters

fun(1, 2, 3, 4);

// no parameter

fun();
}

Output

Number of arguments: 1

100

Number of arguments: 4

1234

Number of arguments: 0

Explanation of the above program

The … syntax tells the compiler that varargs have


been used, and these arguments should be stored
in the array referred to by a.

The variable a is operated on as an array. In this


case, we have defined the data type of an array ‘a’
as int. So it can take only integer values. The
number of arguments can be found out using
a.length, the way we find the length of an array in
Java.

Note: A method can have variable length


parameters with other parameters too, but one
should ensure that there exists only one varargs
parameter that should be written last in the
parameter list of the method declaration. For
example:
int nums(int a, float b, double … c)

In this case, the first two arguments are matched


with the first two parameters, and the remaining
arguments belong to c.

// Java program to demonstrate

// varargs with normal arguments

class Test2 {

// Takes string as a argument followed by


varargs

static void fun2(String str, int... a)

System.out.println("String: " + str);

System.out.println("Number of arguments is: "

+ a.length);

// using for each loop to display contents of a

for (int i : a)

System.out.print(i + " ");

System.out.println();
}

public static void main(String args[])

// Calling fun2() with different parameter

fun2("GeeksforGeeks", 100, 200);

fun2("CSPortal", 1, 2, 3, 4, 5);

fun2("forGeeks");

Output

String: GeeksforGeeks

Number of arguments is: 2

100 200

String: CSPortal

Number of arguments is: 5

12345

String: forGeeks

Number of arguments is: 0

Erroneous Varargs Examples

Case 1: Specifying two Varargs in a single method:


void method(String... gfg, int... q)

// Compile time error as there

// are two varargs

Case 2: Specifying Varargs as the first parameter


of the method instead of the last one:

void method(int... gfg, String q)

// Compile time error as vararg

// appear before normal argument

Important Points regarding Varargs :

a. Vararg Methods can also be overloaded, but


overloading may lead to ambiguity.

b. Before JDK 5, variable length arguments could


be handled in two ways: One was using
overloading, other was using array argument.

c. There can be only one variable argument in a


method.

d. Variable argument (Varargs) must be the last


argument.
RECURSION

In Java, Recursion is a process in which a function


calls itself directly or indirectly is called recursion
and the corresponding function is called a
recursive function. Using a recursive algorithm,
certain problems can be solved quite easily. A few
Java recursion examples are Towers of Hanoi
(TOH), Inorder/Preorder/Postorder Tree Traversals,
DFS of Graph, etc.

Base Condition in Recursion

In the recursive program, the solution to the base


case is provided and the solution to the bigger
problem is expressed in terms of smaller problems.

int fact(int n)

if (n < = 1) // base case

return 1;

else

return n*fact(n-1);

In the above example, the base case for n < = 1 is


defined and the larger value of a number can be
solved by converting it to a smaller one till the
base case is reached.

Working of Recursion

The idea is to represent a problem in terms of one


or more smaller sub-problems and add base
conditions that stop the recursion. For example, we
compute factorial n if we know the factorial of (n-
1). The base case for factorial would be n = 0. We
return 1 when n = 0.

Java Recursion Programs

1. Factorial Using Recursion


The classic example of recursion is the
computation of the factorial of a number. The
factorial of a number N is the product of all the
numbers between 1 and N. The below-given code
computes the factorial of the numbers: 3, 4, and
5.

3= 3 *2*1 (6)
4= 4*3*2*1 (24)
5= 5*4*3*2*1 (120)
Below is the implementation of the factorial:

// Java Program to implement


// Factorial using recursion
class GFG {

// recursive method
int fact(int n)
{
int result;

if (n == 1)
return 1;
result = fact(n - 1) * n;
return result;
}
}

// Driver Class
class Recursion {

// Main function
public static void main(String[] args)
{
GFG f = new GFG();

System.out.println("Factorial of 3 is "
+ f.fact(3));
System.out.println("Factorial of 4 is "
+ f.fact(4));
System.out.println("Factorial of 5 is "
+ f.fact(5));
}
}
Output
Factorial of 3 is 6
Factorial of 4 is 24
Factorial of 5 is 120
2. Fibonacci Series
Fibonacci Numbers are the numbers is the integer
sequence where Fib(N) = Fib(N-2) + Fib(N-1).
Below is the example to find 3,4,5.

Fib(3) = Fib(2) + Fib(1) = Fib(1) + 0 + 1 = 1+1 = 2


Fib(4) = Fib(3) + Fib(2) = 2+1 = 3
Fib(5) = Fib(4) + Fib(3) = 3 + 2 = 5
fibonacci Series recursion tree
Recursion Tree Diagram for Fibonacci Series

Below is the implementation of the Fibonacci


Series:

// Java Program to implement


// Fibonacci Series
import java.io.*;

// Driver Function
class GFG {

// Function to return Fibonacci value


static int Fib(int N)
{
if (N == 0 || N == 1)
return N;

return Fib(N - 1) + Fib(N - 2);


}

// Main function
public static void main(String[] args)
{
// Fibonacci of 3
System.out.println("Fibonacci of " + 3 + " "
+ Fib(3));

// Fibonacci of 4
System.out.println("Fibonacci of " + 4 + " "
+ Fib(4));

// Fibonacci of 5
System.out.println("Fibonacci of " + 5 + " "
+ Fib(5));
}
}

Output
Fibonacci of 3 2
Fibonacci of 4 3
Fibonacci of 5 5
Stack Overflow error
If the base case is not reached or not defined, then
the stack overflow problem may arise. Let us take
an example to understand this.

int fact(int n)
{
// wrong base case (it may cause
// stack overflow).
if (n == 100)
return 1;
else
return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8),
fact(7) and so on but the number will never reach
100. So, the base case is not reached. If the
memory is exhausted by these functions on the
stack, it will cause a stack overflow error.

How is memory allocated to different function calls


in recursion?
When any function is called from main(), the
memory is allocated to it on the stack. A recursive
function calls itself, the memory for the called
function is allocated on top of memory allocated to
the calling function and a different copy of local
variables is created for each function call. When
the base case is reached, the function returns its
value to the function by whom it is called and
memory is de-allocated and the process continues.

Let us take the example of recursion by taking a


simple function.

// A Java program to demonstrate


// working of recursion

class GFG {
static void printFun(int test)
{
if (test < 1)
return;

else {
System.out.printf("%d ", test);

// Statement 2
printFun(test - 1);

System.out.printf("%d ", test);


return;
}
}

public static void main(String[] args)


{
int test = 3;
printFun(test);
}
}

Output
321123

Explanation of the above Program:

When printFun(3) is called from main(), memory is


allocated to printFun(3), a local variable test is
initialized to 3, and statements 1 to 4 are pushed
on the stack as shown below diagram. It first prints
‘3’.

In statement 2, printFun(2) is called and memory is


allocated to printFun(2), a local variable test is
initialized to 2, and statements 1 to 4 are pushed
in the stack. Similarly, printFun(2) calls printFun(1)
and printFun(1) calls printFun(0). printFun(0) goes
to if statement and it return to printFun(1).

The remaining statements of printFun(1) are


executed and it returns to printFun(2) and so on. In
the output, values from 3 to 1 are printed and then
1 to 3 are printed.

The memory stack is shown in the below diagram:

Advantages of Recursive Programming


The advantages of recursive programs are as
follows:

 Recursion provides a clean and simple way to


write code.
 Some problems are inherently recursive like
tree traversals, Tower of Hanoi, etc. For such
problems, it is preferred to write recursive
code.

Disadvantages of Recursive Programming

The disadvantages of recursive programs is as


follows:

 The recursive program has greater space


requirements than the iterative program as all
functions will remain in the stack until the base
case is reached.
 It also has greater time requirements because
of function calls and returns overhead.

Note: Both recursive and iterative programs have


the same problem-solving powers, i.e., every
recursive program can be written iteratively and
vice versa is also true.

PRACTICE SET ON METHODS

PRINTING THE TABLE OF A NUMBER

// Java Program to print the multiplication table of


number N using function

import java.io.*;
import java.util.Scanner;
class Program
{
/*function to find table of number*/
static void table(int no)
{
for (int i = 1; i<=10; i++)
{
System.out.print(i*no+" ");
}
}
public static void main(String[] args)
{
System.out.println("Table of 6=");
table(6);//calling function
System.out.println("\nTable of 5=");
table(5);//calling function
}
}

PATTERN PRINTING METHOD IN JAVA

// Java Program to print


// Pyramid pattern
import java.util.*;

public class GeeksForGeeks {


// Function to demonstrate pattern
public static void printPattern(int n)
{
int i, j;
// outer loop to handle rows
for (i = 1; i <= n; i++) {
// inner loop to handle columns
for (j = 1; j <= i; j++) {
System.out.print("*");
}
// printing new line for each row
System.out.println();
}
}
// Driver Function
public static void main(String args[])
{
int n = 6;
printPattern(n);
}
}

PRINTING SUM OF FIRST N NUMBERS

// Java program to find the


// sum of natural numbers up
// to n using recursion
import java.util.*;
import java.lang.*;

class GFG
{
// Returns sum of first
// n natural numbers
public static int recurSum(int n)
{
if (n <= 1)
return n;
return n + recurSum(n - 1);
}

// Driver code
public static void main(String args[])
{
int n = 5;
System.out.println(recurSum(n));
}
}

PRINTING FINABOCCI SEQUENCE

// Fibonacci series program in java

import java.io.*;
class GFG {
// Function to print N Fibonacci Number
static void Fibonacci(int N)
{
int num1 = 0, num2 = 1;
for (int i = 0; i < N; i++) {
// Print the number
System.out.print(num1 + " ");
// Swap
int num3 = num2 + num1;
num1 = num2;
num2 = num3;
}
}
// Driver Code
public static void main(String args[])
{
// Given Number N
int N = 10;
// Function Call
Fibonacci(N);
}
}

***********END OF PRACTICE SET ON


METHODS**********
OBJECT ORIENTED PROGRAMMING IN JAVA

Object-Oriented Programming or OOPs refers to


languages that use objects in programming.
Object-oriented programming aims to implement
real-world entities like inheritance, hiding,
polymorphism, etc in programming.

The main aim of OOP is to bind together the data


and the functions that operate on them so that no
other part of the code can access this data except
that function.

OOPs Concepts:

 Class
 Objects
 Data Abstraction
 Encapsulation
 Inheritance
 Polymorphism
 Dynamic Binding
 Message Passing

1. Class:

A class is a user-defined data type. It consists of


data members and member functions, which can
be accessed and used by creating an instance of
that class. It represents the set of properties or
methods that are common to all objects of one
type. A class is like a blueprint for an object.

For Example: Consider the Class of Cars. There


may be many cars with different names and brands
but all of them will share some common properties
like all of them will have 4 wheels, Speed Limit,
Mileage range, etc. So here, Car is the class, and
wheels, speed limits, mileage are their properties.

2. Object:

It is a basic unit of Object-Oriented Programming


and represents the real-life entities. An Object is an
instance of a Class. When a class is defined, no
memory is allocated but when it is instantiated (i.e.
an object is created) memory is allocated.

An object has an identity, state, and behavior.


Each object contains data and code to manipulate
the data. Objects can interact without having to
know details of each other’s data or code, it is
sufficient to know the type of message accepted
and type of response returned by the objects.

For example “Dog” is a real-life Object, which has


some characteristics like color, Breed, Bark, Sleep,
and Eats.

3. Data Abstraction:

Data abstraction is one of the most essential and


important features of object-oriented
programming. Data abstraction refers to providing
only essential information about the data to the
outside world, hiding the background details or
implementation.

Consider a real-life example of a man driving a car.


The man only knows that pressing the accelerators
will increase the speed of the car or applying
brakes will stop the car, but he does not know
about how on pressing the accelerator the speed is
increasing, he does not know about the inner
mechanism of the car or the implementation of the
accelerator, brakes, etc in the car. This is what
abstraction is.

4. Encapsulation:

Encapsulation is defined as the wrapping up of


data under a single unit. It is the mechanism that
binds together code and the data it manipulates.

In Encapsulation, the variables or data of a class


are hidden from any other class and can be
accessed only through any member function of
their class in which they are declared. As in
encapsulation, the data in a class is hidden from
other classes, so it is also known as data-hiding.
Consider a real-life example of encapsulation, in a
company, there are different sections like the
accounts section, finance section, sales section,
etc. The finance section handles all the financial
transactions and keeps records of all the data
related to finance.

Similarly, the sales section handles all the sales-


related activities and keeps records of all the sales.
Now there may arise a situation when for some
reason an official from the finance section needs all
the data about sales in a particular month. In this
case, he is not allowed to directly access the data
of the sales section. He will first have to contact
some other officer in the sales section and then
request him to give the particular data.

This is what encapsulation is. Here the data of the


sales section and the employees that can
manipulate them are wrapped under a single name
“sales section”.
5. Inheritance:

Inheritance is an important pillar of OOP(Object-


Oriented Programming). The capability of a class to
derive properties and characteristics from another
class is called Inheritance. When we write a class,
we inherit properties from other classes. So when
we create a class, we do not need to write all the
properties and functions again and again, as these
can be inherited from another class that possesses
it. Inheritance allows the user to reuse the code
whenever possible and reduce its redundancy.
6. Polymorphism:

The word polymorphism means having many


forms. In simple words, we can define
polymorphism as the ability of a message to be
displayed in more than one form.

For example, A person at the same time can have


different characteristics. Like a man at the same
time is a father, a husband, an employee. So the
same person posses different behavior in different
situations. This is called polymorphism.
7. Dynamic Binding:

In dynamic binding, the code to be executed in


response to the function call is decided at runtime.
Dynamic binding means that the code associated
with a given procedure call is not known until the
time of the call at run time.
Dynamic Method Binding One of the main
advantages of inheritance is that some derived
class D has all the members of its base class B.
Once D is not hiding any of the public members of
B, then an object of D can represent B in any
context where a B could be used.

This feature is known as subtype polymorphism.

8. Message Passing:

It is a form of communication used in object-


oriented programming as well as parallel
programming. Objects communicate with one
another by sending and receiving information to
each other.

A message for an object is a request for execution


of a procedure and therefore will invoke a function
in the receiving object that generates the desired
results.

Message passing involves specifying the name of


the object, the name of the function, and the
information to be sent.

Why do we need object-oriented programming

 To make the development and maintenance of


projects more effortless.
 To provide the feature of data hiding that is
good for security concerns.

 We can solve real-world problems if we are


using object-oriented programming.

 It ensures code reusability.

 It lets us write generic code: which will work with


a range of data, so we don’t have to write basic
stuff over and over again.

CREATING A CUSTOM CLASS

// Java Program to Creating our Own Custom Class

// Importing input output classes


import java.io.*;

// Class 1
// Helper class
class Employee {

// Member variables of this class

// first attribute
int id;
// second attribute
int salary;
// third attribute
String name;

// Member function of this class

// Method 1
public void printDetails()
{
// Print and display commands
System.out.println("My id is " + id);
System.out.println("This is my name " +
name);
}

// Method 2
public int getSalary()
{

// Simply returning the salary


return salary;
}
}

// Class 2
// Main class
class Custom {

// Main driver method


public static void main(String[] args)
{

// Display message only


System.out.println("This is the custom class");

// Creating object of custom class in the


main()
// method Instantiating a new Employee
object
Employee harry = new Employee();

// Again creating object of custom class and


// instantiating a new Employee object
Employee robin = new Employee();

// Initializing values for first object created


// above
harry.id = 23;
harry.salary = 100000;
harry.name = "Ritu bhatiya";

// Initializing values for second object created


// above
robin.id = 25;
robin.salary = 150000;
robin.name = "Amit thripathi";

// Printing object attributes by


// calling the method as defined in our class
harry.printDetails();
robin.printDetails();

// Calling the method again of our class and


// storing it in a variable
int salary = robin.getSalary();

// Print and display the above salary


System.out.println("Salary of robin : " + salary
+ "$");

System.out.println("ID : " + harry.id);


}
}

Output
This is the custom class
My id is 23
This is my name Ritu bhatiya
My id is 25
This is my name Amit thripathi
Salary of robin : 150000$
ID : 23
ACCESS MODIFIERS

There are two types of modifiers in Java:

1. access modifiers
2. non-access modifiers

The access modifiers in Java specifies the


accessibility or scope of a field, method,
constructor, or class.

We can change the access level of fields,


constructors, methods, and class by applying the
access modifier on it.

There are four types of Java access modifiers:

 Private: The access level of a private modifier is


only within the class. It cannot be accessed from
outside the class.

 Default: The access level of a default modifier is


only within the package. It cannot be accessed
from outside the package. If you do not specify
any access level, it will be the default.

 Protected: The access level of a protected


modifier is within the package and outside the
package through child class. If you do not make
the child class, it cannot be accessed from
outside the package.

 Public: The access level of a public modifier is


everywhere. It can be accessed from within the
class, outside the class, within the package and
outside the package.

There are many non-access modifiers, such as


static, abstract, synchronized, native, volatile,
transient, etc.

Here, we are going to learn the access modifiers


only.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a


simple table.

Access within within outside outside


Modifier class package package by package
subclass only

Private Y N N N
Default Y Y N N
Protecte Y Y Y N
d
Public Y Y Y Y

1) Private

The private access modifier is accessible only


within the class.
Simple example of private access modifier :

In this example, we have created two classes A


and Simple. A class contains private data member
and private method. We are accessing these
private members from outside the class, so there is
a compile-time error.

class A{
private int data=40;
private void msg(){System.out.println("Hello
java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}

Role of Private Constructor

If you make any class constructor private, you


cannot create the instance of that class from
outside the class. For example:

class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
Note: A class cannot be private or protected except
nested class.

2) Default
If you don't use any modifier, it is treated as
default by default. The default modifier is
accessible only within package.

It cannot be accessed from outside the package. It


provides more accessibility than private. But, it is
more restrictive than protected, and public.

Example of default access modifier :

In this example, we have created two packages


pack and mypack. We are accessing the A class
from outside its package, since A class is not
public, so it cannot be accessed from outside the
package.

//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
In the above example, the scope of class A and its
method msg() is default so it cannot be accessed
from outside the package.

2) Protected

The protected access modifier is accessible within


package and outside the package but through
inheritance only.

The protected access modifier can be applied on


the data member, method and constructor. It can't
be applied on the class.

It provides more accessibility than the default


modifer.

Example of protected access modifier

In this example, we have created the two packages


pack and mypack. The A class of pack package is
public, so can be accessed from outside the
package. But msg method of this package is
declared as protected, so it can be accessed from
outside the class only through inheritance.

//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Output:Hello
4) Public
The public access modifier is accessible
everywhere. It has the widest scope among all
other modifiers.

Example of public access modifier

//save by A.java

package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java

package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}

Output:Hello

Java Access Modifiers with Method Overriding :


If you are overriding any method, overridden
method (i.e. declared in subclass) must not be
more restrictive.

class A{
protected void msg(){System.out.println("Hello
java");}
}

public class Simple extends A{


void msg(){System.out.println("Hello
java");}//C.T.Error
public static void main(String args[]){
Simple obj=new Simple();
obj.msg();
}
}

The default modifier is more restrictive than


protected. That is why, there is a compile-time
error.

GETTER AND SETTER IN JAVA

In Java, Getter and Setter are methods used to


protect your data and make your code more
secure. Getter and Setter make the programmer
convenient in setting and getting the value for a
particular data type.

Getter in Java: Getter returns the value


(accessors), it returns the value of data type int,
String, double, float, etc. For the program’s
convenience, the getter starts with the word “get”
followed by the variable name.
Setter in Java: While Setter sets or updates the
value (mutators). It sets the value for any variable
used in a class’s programs. and starts with the
word “set” followed by the variable name.

Syntax
class ABC{
private variable;

public void setVariable(int x){


this.variable=x;
}

public int getVariable{


return variable;
}
}
Note: In both getter and setter, the first letter of
the variable should be capital.

Examples of Getter and Setter in Java


Example 1:
Java
// Java Program to Illustrate Getter and Setter

// Importing input output classes


import java.io.*;

// Class 1
// Helper class
class GetSet {

// Member variable of this class


private String name;

// Method 1 - Getter
public String getName() { return name; }
// Method 2 - Setter
public void setName(String N)
{

// This keyword refers to current instance


itself
this.name = N;
}
}

// Class 2
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Creating an object of class 1 in main()
method
GetSet obj = new GetSet();

// Setting the name by calling setter method


obj.setName("Geeks for Geeks");
// Getting the name by calling getter method
System.out.println(obj.getName());
}
}
Output
Geeks for Geeks
Getter and Setter give you the convenience of
entering the value of the variables of any data type
by the requirement of the code. Getters and
setters let you manage how crucial variables in
your code are accessed and altered. It can be seen
in the program discussed below as follows:

Example 2
Java
// Java Program to Illustrate Getter and Setter

// Importing input output classes


import java.io.*;

class GetSet {
// Member variable of this class
private int num;

// Method 1 - Setter
public void setNumber(int number)
{
// Checking if number is between 1 to 10
exclusive
if (number < 1 || number > 10) {

throw new IllegalArgumentException();


}
num = number;
}

// Method 2 - Getter
public int getNumber() { return num; }
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();

// Calling method 1 inside main() method


obj.setNumber(5);

// Printing the number as setter above


System.out.println(obj.getNumber());
}
}
Output
5
Explanation of the above program:
Here we can see that if we take a value greater
than 10 then it shows an error, By using the
setNumber() method, one can be sure the value of
a number is always between 1 and 10. This is
much better than updating the number variable
directly.

Note: This could be avoided by making the number


a private variable and utilizing the setNumber
method. Using a getter method, on the other hand,
is the sole way to read a number’s value.

CODE SYNTAX : -

class ABC{
private variable;

public void setVariable(int x){


this.variable=x;
}

public int getVariable{


return variable;
}
}
CODE : -

// Java Program to Illustrate Getter and Setter

// Importing input output classes


import java.io.*;

class GetSet {
// Member variable of this class
private int num;

// Method 1 - Setter
public void setNumber(int number)
{
// Checking if number is between 1 to 10
exclusive
if (number < 1 || number > 10) {

throw new IllegalArgumentException();


}
num = number;
}

// Method 2 - Getter
public int getNumber() { return num; }
}

// Class 2
// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{
GetSet obj = new GetSet();
// Calling method 1 inside main() method
obj.setNumber(5);

// Printing the number as setter above


System.out.println(obj.getNumber());
}
}

OUTPUT : -

Explanation of the above program:

Here we can see that if we take a value greater


than 10 then it shows an error, By using the
setNumber() method, one can be sure the value of
a number is always between 1 and 10. This is
much better than updating the number variable
directly.

Note: This could be avoided by making the number


a private variable and utilizing the setNumber
method. Using a getter method, on the other hand,
is the sole way to read a number’s value.

CONSTRUCTORS IN JAVA

In Java, a constructor is a block of codes similar to


the method. It is called when an instance of
the class is created. At the time of calling
constructor, memory for the object is allocated in
the memory.
It is a special type of method which is used to
initialize the object.

Every time an object is created using the new()


keyword, at least one constructor is called.

It calls a default constructor if there is no


constructor available in the class. In such case,
Java compiler provides a default constructor by
default.

There are two types of constructors in Java: no-


argument constructor, and parameterized
constructor.

Note: It is called constructor because it constructs


the values at the time of object creation. It is not
necessary to write a constructor for a class. It is
because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its


class name
2. A Constructor must have no explicit return
type
3. A Java constructor cannot be abstract, static,
final, and synchronized.

Note: We can use access modifiers while


declaring a constructor. It controls the object
creation. In other words, we can have
private, protected, public or default
constructor in Java.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-argument constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when
it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor

In this example, we are creating the no-arg constructor


in the Bike class. It will be invoked at the time of object
creation.

CODE : -

1. //Java Program to create and call a default construc


tor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Output:

Bike is created

Rule: If there is no constructor in a class,


compiler automatically creates a default
constructor.

Q) What is the purpose of a default


constructor?

The default constructor is used to provide the


default values to the object like 0, null, etc.,
depending on the type.

Example of default constructor that displays


the default values

1. //Let us see another example of default constructor

2. //which displays the default values


3. class Student3{
4. int id;
5. String name;
6. //method to display the value of id and name
7. void display(){System.out.println(id+" "+name);}
8.
9. public static void main(String args[]){
10. //creating objects
11. Student3 s1=new Student3();
12. Student3 s2=new Student3();
13. //displaying values of the object
14. s1.display();
15. s2.display();
16. }
17. }

Output:

0 null
0 null

Explanation:In the above class,you are not


creating any constructor so compiler provides you
a default constructor. Here 0 and null values are
provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of


parameters is called a parameterized constructor.
Why use the parameterized constructor?

The parameterized constructor is used to provide


different values to distinct objects. However, you
can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor


of Student class that have two parameters. We can
have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the para


meterized constructor.
2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+"
"+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of obj
ect
18. s1.display();
19. s2.display();
20. }
21. }

Output:

111 Karan
222 Aryan

Constructor Overloading in Java

In Java, a constructor is just like a method but


without return type. It can also be overloaded like
Java methods.

Constructor overloading in Java is a technique of


having more than one constructor with different
parameter lists. They are arranged in a way that
each constructor performs a different task. They
are differentiated by the compiler by the number of
parameters in the list and their types.

Example of Constructor Overloading

1. //Java program to overload constructors


2. class Student5{
3. int id;
4. String name;
5. int age;
6. //creating two arg constructor
7. Student5(int i,String n){
8. id = i;
9. name = n;
10. }
11. //creating three arg constructor
12. Student5(int i,String n,int a){
13. id = i;
14. name = n;
15. age=a;
16. }
17. void display(){System.out.println(id+"
"+name+" "+age);}
18.
19. public static void main(String args[]){
20. Student5 s1 = new Student5(111,"Karan");
21. Student5 s2 = new Student5(222,"Aryan",2
5);
22. s1.display();
23. s2.display();
24. }
25. }

Output:

111 Karan 0
222 Aryan 25

Difference between constructor and method


in Java

There are many differences between constructors


and methods. They are given below.
Java Constructor Java Method

A constructor is used to A method is used to


initialize the state of an expose the behavior of
object. an object.

A constructor must not A method must have a


have a return type. return type.

The constructor is invoked The method is invoked


implicitly. explicitly.

The Java compiler provides The method is not


a default constructor if you provided by the
don't have any constructor compiler in any case.
in a class.

The constructor name The method name may


must be same as the class or may not be same as
name. the class name.
Java Copy Constructor

There is no copy constructor in Java. However, we


can copy the values from one object to another like
copy constructor in C++.

There are many ways to copy the values of one


object into another in Java. They are:

o By constructor
o By assigning the values of one object into
another
o By clone() method of Object class

In this example, we are going to copy the values of


one object into another using Java constructor.

1. //Java program to initialize the values from one obj


ect to another object.
2. class Student6{
3. int id;
4. String name;
5. //constructor to initialize integer and string
6. Student6(int i,String n){
7. id = i;
8. name = n;
9. }
10. //constructor to initialize another object
11. Student6(Student6 s){
12. id = s.id;
13. name =s.name;
14. }
15. void display(){System.out.println(id+"
"+name);}
16.
17. public static void main(String args[]){
18. Student6 s1 = new Student6(111,"Karan");
19. Student6 s2 = new Student6(s1);
20. s1.display();
21. s2.display();
22. }
23. }

Output:

111 Karan
111 Karan

Copying values without constructor

We can copy the values of one object into another


by assigning the objects values to another object.
In this case, there is no need to create the
constructor.

1. class Student7{
2. int id;
3. String name;
4. Student7(int i,String n){
5. id = i;
6. name = n;
7. }
8. Student7(){}
9. void display(){System.out.println(id+"
"+name);}
10.
11. public static void main(String args[]){
12. Student7 s1 = new Student7(111,"Karan");
13. Student7 s2 = new Student7();
14. s2.id=s1.id;
15. s2.name=s1.name;
16. s1.display();
17. s2.display();
18. }
19. }

Output:

111 Karan
111 Karan

Q) Does constructor return any value?

Yes, it is the current class instance (You cannot use


return type yet it returns a value).

Can constructor perform other tasks instead


of initialization?

Yes, like object creation, starting a thread, calling a


method, etc. You can perform any operation in the
constructor as you perform in the method.

Is there Constructor class in Java?


Yes.

What is the purpose of Constructor class?

Java provides a Constructor class which can be


used to get the internal information of a
constructor in the class. It is found in the
java.lang.reflect package.

GUESS THE NUMBER GAME IN JAVA

The task is to write a Java program in which a user


will get K trials to guess a randomly generated
number. Below are the rules of the game:

a. If the guessed number is bigger than the


actual number, the program will respond with
the message that the guessed number is higher
than the actual number.

b. If the guessed number is smaller than the


actual number, the program will respond with
the message that the guessed number is lower
than the actual number.
c. If the guessed number is equal to the actual
number or if the K trials are exhausted, the
program will end with a suitable message.

Approach: Below are the steps:

 The approach is to generate a random number


using Math.random() method in Java.

 Now using a loop, take K input from the user and


for each input print whether the number is
smaller or larger than the actual number.

 If within K trials the user guessed the number


correctly, print that the user won.

 Else print that he was not able to guess and


then print the actual number.

Below is the implementation of the above


approach:

// Java program for the above approach


import java.util.Scanner;

public class GFG {

// Function that implements the


// number guessing game
public static void
guessingNumberGame()
{
// Scanner Class
Scanner sc = new Scanner(System.in);

// Generate the numbers


int number = 1 + (int)(100
* Math.random());

// Given K trials
int K = 5;

int i, guess;

System.out.println(
"A number is chosen"
+ " between 1 to 100."
+ "Guess the number"
+ " within 5 trials.");

// Iterate over K Trials


for (i = 0; i < K; i++) {

System.out.println(
"Guess the number:");

// Take input for guessing


guess = sc.nextInt();

// If the number is guessed


if (number == guess) {
System.out.println(
"Congratulations!"
+ " You guessed the number.");
break;
}
else if (number > guess
&& i != K - 1) {
System.out.println(
"The number is "
+ "greater than " + guess);
}
else if (number < guess
&& i != K - 1) {
System.out.println(
"The number is"
+ " less than " + guess);
}
}

if (i == K) {
System.out.println(
"You have exhausted"
+ " K trials.");

System.out.println(
"The number was " + number);
}
}

// Driver Code
public static void
main(String arg[])
{

// Function Call
guessingNumberGame();
}
}
OUTPUT : -

THIS AND SUPER KEYWORDS IN JAVA

In java, super keyword is used to access methods


of the parent class while this is used to access
methods of the current class.
this keyword is a reserved keyword in java i.e, we
can’t use it as an identifier. It is used to refer
current class’s instance as well as static members.
It can be used in various contexts as given below:

to refer instance variable of current class


to invoke or initiate current class constructor
can be passed as an argument in the method call
can be passed as argument in the constructor call
can be used to return the current class instance
Example

// Program to illustrate this keyword


// is used to refer current class
class RR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)


// static variable(i.e, b)
this.b = 600;

System.out.println(b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}

Output
100
600
super keyword
super is a reserved keyword in java i.e, we can’t
use it as an identifier.
super is used to refer super-class’s instance as well
as static members.
super is also used to invoke super-class’s method
or constructor.
super keyword in java programming language
refers to the superclass of the class where the
super keyword is currently being used.
The most common use of super keyword is that it
eliminates the confusion between the superclasses
and subclasses that have methods with same
name.
super can be used in various contexts as given
below:

it can be used to refer immediate parent class


instance variable
it can be used to refer immediate parent class
method
it can be used to refer immediate parent class
constructor.
Example

// Program to illustrate super keyword


// refers super-class instance

class Parent {
// instance variable
int a = 10;

// static variable
static int b = 20;
}

class Base extends Parent {


void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
System.out.println(super.a);

// referring parent class(i.e, class Parent)


// static variable(i.e, b)
System.out.println(super.b);
}

public static void main(String[] args)


{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}

Output
10
20
Similarities in this and super
We can use this as well as super anywhere except
static area. Example of this is already shown above
where we use this as well as super inside public
static void main(String[]args) hence we get
Compile Time Error since cannot use them inside
static area.
We can use this as well as super any number of
times in a program.
Both are non-static keyword.
Example

// Java Program to illustrate using this


// many number of times

class RRR {
// instance variable
int a = 10;

// static variable
static int b = 20;

void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;

System.out.println(a);

// referring current class(i.e, class RR)


// static variable(i.e, b)
this.b = 600;
System.out.println(b);

// referring current class(i.e, class RR)


// instance variable(i.e, a) again
this.a = 9000;

System.out.println(a);
}

public static void main(String[] args)


{
new RRR().GFG();
}
}

Output

100
600
9000

See above we have used this 3 times. So this can


be used any number of times.

// Java Program to illustrate using super


// many number of times

class Parent {
// instance variable
int a = 36;

// static variable
static float x = 12.2f;
}

class Base extends Parent {


void GFG()
{
// referring super class(i.e, class Parent)
// instance variable(i.e, a)
super.a = 1;
System.out.println(a);

// referring super class(i.e, class Parent)


// static variable(i.e, x)
super.x = 60.3f;

System.out.println(x);
}
public static void main(String[] args)
{
new Base().GFG();
}
}

Output

1
60.3

See above we have used super 2 times. So super


can be used any number of times.

Note: We can use ‘this’ as well as ‘super’ any


number of times but main thing is that we cannot
use them inside static context.

Let us consider a tricky example of this keyword:

// Java program to illustrate


// the usage of this keyword

class RR {
int first = 22;
int second = 33;

void garcia(int a, int b)


{
a = this.first;
b = this.second;
System.out.println(first);
System.out.println(second);
System.out.println(a);
System.out.println(b);
}

void louis(int m, int n)


{
this.first = m;
this.second = n;
System.out.println(first);
System.out.println(second);
System.out.println(m);
System.out.println(n);
}

public static void main(String[] args)


{
new RR().garcia(100, 200);
new RR().louis(1, 2);
}
}

Output
22
33
22
33
1
2
1
2

Understanding the Output:

//it is of S.O.P(first) of garcia method


22
//it is of S.O.P(second) of garcia method
33
//it is of S.O.P(a) of garcia method
22
//it is of S.O.P(b) of garcia method
33
//it is of S.O.P(first) of louis method
1
//it is of S.O.P(second) of louis method
2
//it is of S.O.P(m) of louis method
1
//it is of S.O.P(n) of louis method
2
Flow of program : First, it start from main and then
we have new RR().garcia(100, 200) then flow goes
to garcia method of RR class and then in that we
have:

a = this.first
b = this.second
Here, what is happening is that the value of
instance variable(i.e, first) and the value of static
variable(i.e, second) are assigned to the garcia
method’s local variables a and b respectively.
Hence value of a and b comes out to be 22 and 33
respectively. Next we have new RR().louis(1, 2)
hence here flow goes to the louis method of RR
class and in that we have:

this.first = m
this.second = n
Here, above what happens is that the value of the
louis method’s local variables i.e, m and n are
assigned to the instance as well as static variables
i.e, first and second respectively.
Hence, the value of first and second variables are
same which we have passed into the louis method
i.e, 1 and 2 respectively.

Can we use both this() and super() in the same


constructor?
An interesting thing to note here is that according
to Java guidelines, this() or super() must be the
first statement in the constructor block for it to be
executed. So we cannot have them together in the
same constructor as both need to be the first
statement in the block for proper execution, which
is not possible. Trying to do so would raise a
compiler error.

class Vehicle {
Vehicle() { System.out.println("Vehicle is
created."); }
}

class Bike extends Vehicle {


Bike() { System.out.println("Bike is created."); }

Bike(String brand)
{
super(); // it calls Vehicle(), the parent class
// constructor of class Bike
this();
System.out.println("Bike brand is " + brand);
}
}

public class GFG {


public static void main(String args[])
{
Bike bike = new Bike("Honda");
}
}
On running the above program, we get an error on
line number 12 saying that “call to this must be
first statement in constructor”. This is because we
tried using both super() and this() together. While
super() was the first line of the constructor, this()
statement violated the condition that it should be
the first line, hence raising an error.
Compile Errors:
prog.java:12: error: call to this must be first
statement in constructor
this();
^
1 error

DYNAMIC METHOD DISPATCH OR RUNTIME


POLYMORPHISM

Method overriding is one of the ways in which Java


supports Runtime Polymorphism. Dynamic method
dispatch is the mechanism by which a call to an
overridden method is resolved at run time, rather
than compile time.
When an overridden method is called through a
superclass reference, Java determines which
version(superclass/subclasses) of that method is to
be executed based upon the type of the object
being referred to at the time the call occurs. Thus,
this determination is made at run time.
At run-time, it depends on the type of the object
being referred to (not the type of the reference
variable) that determines which version of an
overridden method will be executed
A superclass reference variable can refer to a
subclass object. This is also known as upcasting.
Java uses this fact to resolve calls to overridden
methods at run time.

Therefore, if a superclass contains a method that is


overridden by a subclass, then when different
types of objects are referred to through a
superclass reference variable, different versions of
the method are executed. Here is an example that
illustrates dynamic method dispatch:

// A Java program to illustrate Dynamic Method


// Dispatch using hierarchical inheritance
class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
// object of type A
A a = new A();

// object of type B
B b = new B();

// object of type C
C c = new C();
// obtain a reference of type A
A ref;

// ref refers to an A object


ref = a;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = b;

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = c;

// calling C's version of m1()


ref.m1();
}
}
Output:

Inside A's m1 method


Inside B's m1 method
Inside C's m1 method
Explanation :

The above program creates one superclass called


A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.

Inside the main() method in Dispatch class, initially


objects of type A, B, and C are declared.
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C

Now a reference of type A, called ref, is also


declared, initially it will point to null.

A ref; // obtain a reference of type A

Now we are assigning a reference to each type of


object (either A’s or B’s or C’s) to ref, one-by-one,
and uses that reference to invoke m1( ). As the
output shows, the version of m1( ) executed is
determined by the type of object being referred to
at the time of the call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()

ref = b; // now r refers to a B object


ref.m1(); // calling B's version of m1()
ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()
Runtime Polymorphism with Data Members

In Java, we can override methods only, not the


variables(data members), so runtime
polymorphism cannot be achieved by data
members.

For example :

// Java program to illustrate the fact that


// runtime polymorphism cannot be achieved
// by data members

// class A
class A
{
int x = 10;
}

// class B
class B extends A
{
int x = 20;
}

// Driver class
public class Test
{
public static void main(String args[])
{
A a = new B(); // object of type B

// Data member of class A will be accessed


System.out.println(a.x);
}
}

Output:
10

Explanation :

In above program, both the class A(super class)


and B(sub class) have a common variable ‘x’. Now
we make object of class B, referred by ‘a’ which is
of type of class A. Since variables are not
overridden, so the statement “a.x” will always refer
to data member of super class.

Advantages of Dynamic Method Dispatch

Dynamic method dispatch allow Java to support


overriding of methods which is central for run-time
polymorphism.

It allows a class to specify methods that will be


common to all of its derivatives, while allowing
subclasses to define the specific implementation of
some or all of those methods
.
It also allow subclasses to add its specific methods
subclasses to define the specific implementation of
some.

Static vs Dynamic binding

 Static binding is done during compile-time while


dynamic binding is done during run-time.
 private, final and static methods and variables
uses static binding and bonded by compiler
while overridden methods are bonded during
runtime based upon type of runtime object
ABSTRACTION AND ABSTRACT CLASSES IN
JAVA

A class which is declared with the abstract keyword


is known as an abstract class in Java. It can have
abstract and non-abstract methods (method with
the body).

Before learning the Java abstract class, let's


understand the abstraction in Java first.

ABSTRACTION : -

Abstraction is a process of hiding the


implementation details and showing only
functionality to the user.

Another way, it shows only essential things to the


user and hides the internal details, for example,
sending SMS where you type the text and send the
message. You don't know the internal processing
about the message delivery.

Abstraction lets you focus on what the object does


instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

ABSTRACT CLASS : -

A class which is declared as abstract is known as


an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its
method implemented.
It cannot be instantiated.

Points to Remember

o An abstract class must be declared with an


abstract keyword.
o It can have abstract and non-abstract
methods.
o It cannot be instantiated.
o It can have constructors and static methods
also.
o It can have final methods which will force the
subclass not to change the body of the
method.
Example of abstract class

1. abstract class A{}

ABSTRACTION METHODS IN JAVA : -

A method which is declared as abstract and does


not have implementation is known as an abstract
method.

Example of abstract method

1. abstract void printStatus();//no method body and


abstract

Example of Abstract class that has an


abstract method

In this example, Bike is an abstract class that


contains only one abstract method run. Its
implementation is provided by the Honda class.

1. abstract class Bike{


2. abstract void run();
3. }
4. class Honda4 extends Bike{
5. void run(){System.out.println("running safely");}
6. public static void main(String args[]){
7. Bike obj = new Honda4();
8. obj.run();
9. }
10. }

running safely
Understanding the real scenario of Abstract
class

In this example, Shape is the abstract class, and its


implementation is provided by the Rectangle and
Circle classes.

Mostly, we don't know about the implementation


class (which is hidden to the end user), and an
object of the implementation class is provided by
the factory method.

A factory method is a method that returns the


instance of the class. We will learn about the
factory method later.

In this example, if you create the instance of


Rectangle class, draw() method of Rectangle class
will be invoked.

File: TestAbstraction1.java

1. abstract class Shape{


2. abstract void draw();
3. }
4. //In real scenario, implementation is provided by ot
hers i.e. unknown by end user
5. class Rectangle extends Shape{
6. void draw(){System.out.println("drawing rectangle
");}
7. }
8. class Circle1 extends Shape{
9. void draw(){System.out.println("drawing circle");}
10. }
11. //In real scenario, method is called by program
mer or user
12. class TestAbstraction1{
13. public static void main(String args[]){
14. Shape s=new Circle1();//In a real scenario, obj
ect is provided through method, e.g., getShape() m
ethod
15. s.draw();
16. }
17. }

drawing circle

Another example of Abstract class in java

File: TestBank.java

1. abstract class Bank{


2. abstract int getRateOfInterest();
3. }
4. class SBI extends Bank{
5. int getRateOfInterest(){return 7;}
6. }
7. class PNB extends Bank{
8. int getRateOfInterest(){return 8;}
9. }
10.
11. class TestBank{
12. public static void main(String args[]){
13. Bank b;
14. b=new SBI();
15. System.out.println("Rate of Interest is: "+b.get
RateOfInterest()+" %");
16. b=new PNB();
17. System.out.println("Rate of Interest is: "+b.get
RateOfInterest()+" %");
18. }}
Rate of Interest is: 7 %
Rate of Interest is: 8 %

Abstract class having constructor, data


member and methods

An abstract class can have a data member,


abstract method, method body (non-abstract
method), constructor, and even main() method.

File: TestAbstraction2.java

1. //Example of an abstract class that has abstract an


d non-abstract methods
2. abstract class Bike{
3. Bike(){System.out.println("bike is created");}
4. abstract void run();
5. void changeGear(){System.out.println("gear cha
nged");}
6. }
7. //Creating a Child class which inherits Abstract clas
s
8. class Honda extends Bike{
9. void run(){System.out.println("running safely..");}

10. }
11. //Creating a Test class which calls abstract and
non-abstract methods
12. class TestAbstraction2{
13. public static void main(String args[]){
14. Bike obj = new Honda();
15. obj.run();
16. obj.changeGear();
17. }
18. }
bike is created
running safely..
gear changed

Rule: If there is an abstract method in a


class, that class must be abstract.

1. class Bike12{
2. abstract void run();
3. }

compile time error

Rule: If you are extending an abstract class


that has an abstract method, you must
either provide the implementation of the
method or make this class abstract.

Another real scenario of abstract class

The abstract class can also be used to provide


some implementation of the interface. In such
case, the end user may not be forced to override
all the methods of the interface.

Note: If you are beginner to java, learn


interface first and skip this example.
1. interface A{
2. void a();
3. void b();
4. void c();
5. void d();
6. }
7.
8. abstract class B implements A{
9. public void c(){System.out.println("I am c");}
10. }
11.
12. class M extends B{
13. public void a(){System.out.println("I am a");}

14. public void b(){System.out.println("I am b");}

15. public void d(){System.out.println("I am d");}

16. }
17.
18. class Test5{
19. public static void main(String args[]){
20. A a=new M();
21. a.a();
22. a.b();
23. a.c();
24. a.d();
25. }}

Output:I am a
I am b
I am c
I am d
INTERFACES IN JAVA

An Interface in Java programming language is


defined as an abstract type used to specify the
behavior of a class. An interface in Java is a
blueprint of a behavior. A Java interface contains
static constants and abstract methods.

What are Interfaces in Java?

The interface in Java is a mechanism to achieve


abstraction. Traditionally, an interface could only
have abstract methods (methods without a body)
and public, static, and final variables by default. It
is used to achieve abstraction and multiple
inheritances in Java. In other words, interfaces
primarily define methods that other classes must
implement. Java Interface also represents the IS-A
relationship.

In Java, the abstract keyword applies only to


classes and methods, indicating that they cannot
be instantiated directly and must be implemented.

When we decide on a type of entity by its behavior


and not via attribute we should define it as an
interface.
Syntax for Java Interfaces
interface {
// declare constant fields
// declare methods that abstract
// by default.
}
To declare an interface, use the interface keyword.
It is used to provide total abstraction. That means
all the methods in an interface are declared with
an empty body and are public and all fields are
public, static, and final by default. A class that
implements an interface must implement all the
methods declared in the interface. To implement
the interface, use the implements keyword.

Uses of Interfaces in Java


Uses of Interfaces in Java are mentioned below:

It is used to achieve total abstraction.


Since java does not support multiple inheritances
in the case of class, by using an interface it can
achieve multiple inheritances.
Any class can extend only 1 class, but can any
class implement an infinite number of interfaces.
It is also used to achieve loose coupling.
Interfaces are used to implement abstraction.
So, the question arises why use interfaces when we
have abstract classes?

The reason is, abstract classes may contain non-


final variables, whereas variables in the interface
are final, public, and static.

// A simple interface
interface Player
{
final int id = 10;
int move();
}
Relationship Between Class and Interface
A class can extend another class similar to this an
interface can extend another interface. But only a
class can extend to another interface, and vice-
versa is not allowed.
Difference Between Class and Interface

Although Class and Interface seem the same there


have certain differences between Classes and
Interface. The major differences between a class
and an interface are mentioned below:

Class Interface

In an interface, you must


In class, you can instantiate initialize variables as they are
variables and create an object. final but you can’t create an
object.

The interface cannot contain


A class can contain concrete
concrete (with implementation)
(with implementation) methods
methods.

The access specifiers used with


In Interface only one specifier is
classes are private, protected,
used- Public.
and public.

Implementation:

To implement an interface, we use the keyword


implements .
WORKING OF INTERFACE : -

// Java program to demonstrate working of


// interface
import java.io.*;

// A simple interface
interface In1 {

// public, static and final


final int a = 10;

// public and abstract


void display();
}

// A class that implements the interface.


class TestClass implements In1 {

// Implementing the capabilities of


// interface.
public void display(){
System.out.println("Geek");
}

// Driver Code
public static void main(String[] args)
{
TestClass t = new TestClass();
t.display();
System.out.println(t.a);
}
}

DIFFERENCE BETWEEN ABSTRACTION AND


INTERFACES

Abstract Class Interface


Does not have access
modifiers, and
Access Can have access
everything defined
Modifiers modifier
inside is assumed to
be a public modifier

Can declare Cannot declare


Constructors constructors and constructors or
destructors destructors

Can have data Cannot have data


Data Fields
fields fields

Can have any type


Data
of class member Can only have public
Member
(e.g., public, members, by default
Accessibility
private, protected)

Users can define


Defining
both fields and Cannot define fields
Fields
constants

Extends just one


class or one Can extend any
Extension abstract class at a number of interfaces.
Limits time. Can extend However, it can only
another regular (or extend interfaces.
concrete) class.

Implementat Faster than the Interface is slower


and requires extra
ion Speed interface indirection or
dereferencing

Cannot be
Cannot be
instantiated, but it
Instantiation instantiated, as it is
can be invoked if
absolutely abstract
main () exist

Abstract keyword
Interface keyword
used to declare the
used to declare
abstract class.
interface. Also,
Keywords Also, the abstract
interface can be
Used class can be
implemented by
extended by using
using the keyword
the keyword
“implements”
“extends”

Can only have


abstract methods,
though, since Java 8,
Can have abstract
it can also have
and non-abstract
static and default
Methods methods. Can have
methods. Cannot
default method
have implementation
implementation
due to interfaces
providing pure
abstraction

Multiple Can have only one Can implement


Inheritances abstract class several interfaces
Abstract methods Abstract and
Structure
only concrete methods

Can have final,


Variable non-final, static, Can only have final
Types and non-static and static variables
variables

Best used when


Use when several various
implementations of implementations
the same type share only method
When It
share common signature. Also, a
Should Be
behavior, good choice when
Used
Additionally, use it your classes need
if you require a additional behavior
base class. or dependency
injection.

MULTIPLE INHERITANCE IN JAVA

Multiple Inheritance is a feature of an object-


oriented concept, where a class can inherit
properties of more than one parent class. The
problem occurs when there exist methods with the
same signature in both the superclasses and
subclass. On calling the method, the compiler
cannot determine which class method to be called
and even on calling which class method gets the
priority.
Note: Java doesn’t support Multiple
Inheritance

Example 1:

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance

// Importing input output classes


import java.io.*;

// Class 1
// First Parent class
class Parent1 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent1");
}
}

// Class 2
// Second Parent Class
class Parent2 {

// Method inside first parent class


void fun() {

// Print statement if this method is called


System.out.println("Parent2");
}
}

// Class 3
// Trying to be child of both the classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {

// Creating object of class in main() method


Test t = new Test();

// Trying to call above functions of class where


// Error is thrown as this class is inheriting
// multiple classes
t.fun();
}
}
Output: Compilation error is thrown

Conclusion: As depicted from code above, on


calling the method fun() using Test object will
cause complications such as whether to call
Parent1’s fun() or Parent2’s fun() method.

Example 2:

GrandParent
/ \
/ \
Parent1 Parent2
\ /
\ /
Test
The code is as follows

// Java Program to Illustrate Unsupportance of


// Multiple Inheritance
// Diamond Problem Similar Scenario

// Importing input output classes


import java.io.*;
// Class 1
// A Grand parent class in diamond
class GrandParent {

void fun() {

// Print statement to be executed when this


method is called
System.out.println("Grandparent");
}
}

// Class 2
// First Parent class
class Parent1 extends GrandParent {
void fun() {

// Print statement to be executed when this


method is called
System.out.println("Parent1");
}
}

// Class 3
// Second Parent Class
class Parent2 extends GrandParent {
void fun() {

// Print statement to be executed when this


method is called
System.out.println("Parent2");
}
}

// Class 4
// Inheriting from multiple classes
class Test extends Parent1, Parent2 {
// Main driver method
public static void main(String args[]) {

// Creating object of this class i main() method


Test t = new Test();

// Now calling fun() method from its parent


classes
// which will throw compilation error
t.fun();
}
}
Output:

Again it throws compiler error when run fun()


method as multiple inheritances cause a diamond
problem when allowed in other languages like C+
+. From the code, we see that: On calling the
method fun() using Test object will cause
complications such as whether to call Parent1’s
fun() or Parent2’s fun() method. Therefore, in order
to avoid such complications, Java does not support
multiple inheritances of classes.

Multiple inheritance is not supported by Java using


classes, handling the complexity that causes due
to multiple inheritances is very complex. It creates
problems during various operations like casting,
constructor chaining, etc, and the above all reason
is that there are very few scenarios on which we
actually need multiple inheritances, so better to
omit it for keeping things simple and
straightforward.

How are the above problems handled for Default


Methods and Interfaces?
Java 8 supports default methods where interfaces
can provide a default implementation of methods.
And a class can implement two or more interfaces.
In case both the implemented interfaces contain
default methods with the same method signature,
the implementing class should explicitly specify
which default method is to be used in some
method excluding the main() of implementing class
using super keyword, or it should override the
default method in the implementing class, or it
should specify which default method is to be used
in the default overridden method of the
implementing class.

Example 3:

// Java program to demonstrate Multiple


Inheritance
// through default methods

// Interface 1
interface PI1 {

// Default method
default void show()
{

// Print statement if method is called


// from interface 1
System.out.println("Default PI1");
}
}

// Interface 2
interface PI2 {

// Default method
default void show()
{

// Print statement if method is called


// from interface 2
System.out.println("Default PI2");
}
}

// Main class
// Implementation class code
class TestClass implements PI1, PI2 {

// Overriding default show method


@Override
public void show()
{

// Using super keyword to call the show


// method of PI1 interface
PI1.super.show();//Should not be used directly
in the main method;

// Using super keyword to call the show


// method of PI2 interface
PI2.super.show();//Should not be used directly
in the main method;
}

//Method for only executing the show() of PI1


public void showOfPI1() {
PI1.super.show();//Should not be used directly
in the main method;
}

//Method for only executing the show() of PI2


public void showOfPI2() {
PI2.super.show(); //Should not be used
directly in the main method;
}

// Mai driver method


public static void main(String args[])
{

// Creating object of this class in main()


method
TestClass d = new TestClass();
d.show();
System.out.println("Now Executing
showOfPI1() showOfPI2()");
d.showOfPI1();
d.showOfPI2();
}
}

Output
Default PI1
Default PI2
Now Executing showOfPI1() showOfPI2()
Default PI1
Default PI2

Note: If we remove the implementation of default


method from “TestClass”, we get a compiler error.
If there is a diamond through interfaces, then there
is no issue if none of the middle interfaces provide
implementation of root interface. If they provide
implementation, then implementation can be
accessed as above using super keyword.

Example 4:

// Java program to demonstrate How Diamond


Problem
// Is Handled in case of Default Methods
// Interface 1
interface GPI {

// Default method
default void show()
{

// Print statement
System.out.println("Default GPI");
}
}

// Interface 2
// Extending the above interface
interface PI1 extends GPI {
}

// Interface 3
// Extending the above interface
interface PI2 extends GPI {
}

// Main class
// Implementation class code
class TestClass implements PI1, PI2 {

// Main driver method


public static void main(String args[])
{

// Creating object of this class


// in main() method
TestClass d = new TestClass();

// Now calling the function defined in interface


1
// from whom Interface 2and 3 are deriving
d.show();
}
}

Output
Default GPI

INHERITANCE AND INTERFACES IN JAVA

Note: This Hierarchy will be followed in the same


way, we cannot reverse the hierarchy while
inheritance in Java. This means that we cannot
implement a class from the interface because
Interface-to-Class inheritance is not allowed, and it
goes against the fundamental principles of class-
based inheritance. This will also breach the
relationship known as the Is-A relationship, where
a subclass is a more specialized version of its
superclass.

// Java program to demonstrate that a class can


// implement multiple interfaces
import java.io.*;

interface intfA {
void m1();
}

interface intfB {
void m2();
}

// class implements both interfaces


// and provides implementation to the method.
class sample implements intfA, intfB {
@Override public void m1()
{
System.out.println("Welcome: inside the
method m1");
}

@Override public void m2()


{
System.out.println("Welcome: inside the
method m2");
}
}

class GFG {
public static void main(String[] args)
{
sample ob1 = new sample();

// calling the method implemented


// within the class.
ob1.m1();
ob1.m2();
}
}
Output:

Welcome: inside the method m1


Welcome: inside the method m2

Interface inheritance: An Interface can extend


another interface.

Inheritance is inheriting the properties of the


parent class into the child class.

a. Inheritance in Java is a mechanism in which


one object acquires all the properties and
behaviors of a parent object.
b. The idea behind inheritance in Java is that you
can create new classes that are built upon
existing classes. When you inherit from an
existing class, you can reuse methods and fields
of the parent class.
c. You can also add new methods and fields in
your current class.
d. Inheritance represents the IS-A relationship
which is also known as the parent-child
relationship.

Example
Dog IS_A Animal
Car IS_A Vehicle
Employee IS_A Person
Surgeon IS_A Doctor etc.
Below is the implementation of the above method:

// Animal is a Parent class


class Animal {
public void eat()
{
System.out.println("Animal is eating");
}
}

// Here Dog is derived from Animal class


class Dog extends Animal {
public static void main(String args[])
{
// creating object of Dog class
Dog d = new Dog();

// Now, Dog can access eat() method of


Animal class
d.eat();
}
}
Output
Animal is eating

Syntax of Java Inheritance


class <Subclass-name> extends <Superclass-
name>
{
//methods and fields
}
Note: The extends keyword indicates that you are
making a new class that derives from an existing
class. The meaning of “extends” is to increase the
functionality.

Example of Java Inheritance


Below is the implementation of Java Inheritance:

// Java Program to demonstrate


// Java Inheritance

// Parent Class
class Person1 {
// Variables
int id;
String name;

// Java Methods
void set_Person(int id, String name)
{
try {
this.id = id;
this.name = name;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
void disp_Person()
{
System.out.print(id + "\t" + name + "\t");
}
}

// Child Class
class Employee1 extends Person1 {
int sal;
String desgn;
void set_Emp(int id, String name, String desgn,
int sal)
{
try {
set_Person(id, name);
this.desgn = desgn;
this.sal = sal;
}
catch (Exception ex) {
ex.printStackTrace();
}
}
void disp_Emp()
{
disp_Person();
System.out.print(desgn + "\t" + sal);
}

// Main function
public static void main(String args[])
{

Employee1 e1 = new Employee1();


e1.set_Emp(1001, "Manjeet", "AP", 20000);
e1.disp_Emp();
}
}
Output
1001 Manjeet AP 20000
Types of inheritance in Java
Java supports three types of inheritance in Java:
single-level, multilevel, and hierarchical inheritance
in the case of classes to avoid ambiguity.
In Java programming, multiple and hybrid
inheritance is supported through the interface only.
1. Single Inheritance Example
When a class inherits another class, it is known as
a single inheritance.

// Single-Level inheritance
// Class B ---> Class A, which means that class B is
derived from Class A

class A {
int a;
void set_A(int x) {
a = x;
}
}

// Class B have access to all public and protected


methods and data members of Class A
class B extends A {
int b, product;
void set_B(int x) {
b = x;
}
void cal_Product()
{
product = a * b;
System.out.println("Product = " + product);
}
public static void main(String[] args)
{
B b = new B();
b.set_A(5);
b.set_B(5);
b.cal_Product();
}
}
Output
Product = 25

2. Multilevel Inheritance Example


When there is a chain of inheritance, it is known as
multilevel inheritance.

Below is the implementation of the above method:

// Multilevel inheritance
// Class C ---> Class B ---> Class A
// Class C is derived from Class B which in
correspondence derived from Class A

class A {
int a;
void set_A(int x) {
a = x;
}
}

// Child of Class A
class B extends A {
int b;
void set_B(int x) {
b = x;
}
}

// Child of Class B but have access to methods of


both classes, i.e., Class A and B
class C extends B {
int c, product;
void cal_Product()
{
product = a * b;
System.out.println("Product = " + product);
}
public static void main(String[] args)
{
C c = new C();
// Class C accesses methods of both class A
and B
c.set_A(5);
c.set_B(5);
c.cal_Product();
}
}
Output
Product = 25

3. Hierarchical Inheritance Example


When two or more classes inherit a single class, it
is known as hierarchical inheritance.

Below is the implementation of the mentioned


topic:

// Hierarchical inheritance
// Class C ---> Class A <--- Class B
// Both Class B and C inherits Class A

class A {
int a;
void set_A(int x) {
a = x;
System.out.println("Setting A's value to = "
+ x);
}
}

// Class B derived from Class A


class B extends A {
int b;
void set_B(int x) {
b = x;
System.out.println("Setting B's value to = " +
b);
}
}

// Class C also derived from Class A


class C extends A {
int c;
void set_C(int x) {
c = x;
System.out.println("Setting C's value to = " +
c);
}
}

public class GFG {


public static void main(String[] args) {
C c = new C();
c.set_C(5);
c.set_A(50);

B b = new B();
b.set_B(10);
b.set_A(15);
}
}
Output
Setting C's value to = 5
Setting A's value to = 50
Setting B's value to = 10
Setting A's value to = 15

4. Inheritance in Interfaces
// Java program to demonstrate inheritance in
// interfaces.
import java.io.*;
interface intfA {
void geekName();
}

interface intfB extends intfA {


void geekInstitute();
}

// class implements both interfaces and provides


// implementation to the method.
class sample implements intfB {
@Override public void geekName()
{
System.out.println("Rohit");
}

@Override public void geekInstitute()


{
System.out.println("JIIT");
}

public static void main(String[] args)


{
sample ob1 = new sample();

// calling the method implemented


// within the class.
ob1.geekName();
ob1.geekInstitute();
}
}
Output:

Rohit
JIIT
An interface can also extend multiple interfaces.
// Java program to demonstrate multiple
inheritance
// in interfaces

import java.io.*;

interface intfA {
void geekName();
}

interface intfB {
void geekInstitute();
}

// always remember that interfaces always extends


interface
// but a class always implements a interface
interface intfC extends intfA, intfB {
void geekBranch();
}

// class implements both interfaces and provides


// implementation to the method.
class sample implements intfC {
public void geekName()
{ System.out.println("Rohit"); }

public void geekInstitute()


{
System.out.println("JIIT");
}

public void geekBranch()


{ System.out.println("CSE"); }

public static void main(String[] args)


{
sample ob1 = new sample();
// calling the method implemented
// within the class.
ob1.geekName();
ob1.geekInstitute();
ob1.geekBranch();
}
}

Output
Rohit
JIIT
CSE

Q. Why Multiple Inheritance is not supported


through a class in Java, but it can be possible
through the interface?

Ans) Multiple Inheritance is not supported by class


because of ambiguity. In the case of interface,
there is no ambiguity because the implementation
of the method(s) is provided by the implementing
class up to Java 7.

From Java 8, interfaces also have implementations


of methods. So if a class implements two or more
interfaces having the same method signature with
implementation, it is mandated to implement the
method in class also.

POLYMORPHISM AND INTERFACES IN JAVA

Polymorphism is that it has many forms that mean


one specific defined form is used in many different
ways. The simplest real-life example is let’s
suppose we have to store the name of the person
and the phone number of the person, but there are
many situations when a person has two different
phone numbers. We have to save the same phone
number under the same name.

Let us interpret it with help . So, in java, the


problem can be solved using an object-oriented
concept, void insertPhone(String name, int phone).
So, this method is used to save the phone number
of the particular person. Similarly, we can use the
same form but a different signature means
different parameters to store the alternative phone
number of the person’s void insertPhone(String
name, int phone1, int phone2). One method has
two different forms and performs different
operations. This is an example of polymorphism,
which is method overloading.

Types of polymorphism in Java:

Run time polymorphism


Compile-time polymorphism
Type 1: Run time polymorphism

This type of polymorphism is resolved by the java


virtual machine, not by the java compiler. That’s
why this type of polymorphism is called run-time
polymorphism. Run time polymorphism occurs
during method overriding in java.

Example

// Java Program to Illustrate Run-time


polymorphism

// Importing I/O classes


import java.io.*;

// Class 1 (Parent class)


class GFG1 {
//name method
void name() {
System.out.println("This is the GFG1 class");
}
}

// Class 2 (Child class)


// Main class extending parent class
public class GFG extends GFG1 {

// Method 1
void name() {
// Print statement
System.out.println("This is the GFG class");
}

// Method 2
// Main drive method
public static void main(String[] args) {

// Now creating 2 objects with different


references and
// calling the Method 1 over the objects

// Case 1: GFG1 reference and GFG1 is the


object
GFG1 ob = new GFG1();
ob.name();

// Case 2: GFG1 reference and GFG is the object


GFG1 ob1 = new GFG();
ob1.name();
}
}
Output
This is the GFG1 class
This is the GFG class
Output explanation:

In the above example, the same function i.e name


is called two times, but in both cases, the output is
different. The signatures of these methods are also
the same. That’s why compilers cannot be able to
identify which should be executed. This is
determined only after the object creation and
reference of the class, which is performed during
run time (Memory management ). That’s why this
is run-time polymorphism.

Type 2: Compile-time polymorphism

Method overloading is an example of the compile-


time polymorphism method. Overloading means a
function having the same name but a different
signature. This is compile-time polymorphism
because this type of polymorphism is determined
during the compilation time because during writing
the code we already mention the different types of
parameters for the same function name.

Example:

// Java Program to Illustrate Run-time


polymorphism

// Importing required classes


import java.io.*;
import java.util.*;

// Class 1
// Helper class
class First {

// Method of this class


// Without any parameter
void check()
{

// Print statement if this method is called


System.out.println("This is the class First");
}
}

// Class 2
// Main class
class Second extends First {

// Method overloading
void check(String name)
{
// Printing the name of the class method
having the
// parameter
System.out.println("This is the class " +
name);
}

// Method 2
// Main driver method
public static void main(String args[])
{
// Creating object of class 2
Second ob = new Second();
// Calling method over class 2 object
ob.check("Second");

// Creating object of class 1


First ob1 = new First();
ob.check();
// Upcasting
First ob2 = new Second();
ob.check();
}
}

Output
This is the class Second
This is the class First
This is the class First

Interfaces are very similar to classes. They have


variables and methods but the interfaces allow
only abstract methods(that don’t contain the body
of the methods), but what is the difference
between the classes and the interfaces? The first
advantage is to allow interfaces to implement the
multiple inheritances in a particular class. The JAVA
language doesn’t support multiple inheritances if
we extend multiple classes in the class, but with
the help of the interfaces, multiple inheritances are
allowed in Java.

Real-life Example

The real-world example of interfaces is that we


have multiple classes for different levels of
employees working in a particular company and
the necessary property of the class is the salary of
the employees and this. We must be implemented
in every class and. Also, it is different for every
employee here. The concept of the interface is
used. We simply create an interface containing an
abstract salary method and implement it in all the
classes and we can easily define different salaries
of the employees.
Example:

// Java Program to Demonstrate Concept of


interfaces

// Interface
interface salary {
void insertsalary(int salary);
}

// Class 1
// Implementing the salary in the class
class SDE1 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary()
{ System.out.println(this.salary); }
}

// Class 2
// Implementing the salary inside the SDE2 class
class SDE2 implements salary {
int salary;
@Override public void insertsalary(int salary)
{
this.salary = salary;
}
void printSalary()
{ System.out.println(this.salary); }
}

public class GFG {

public static void main(String[] args)


{
SDE1 ob = new SDE1();
// Insert different salaries
ob.insertsalary(100000);
ob.printSalary();
SDE2 ob1 = new SDE2();

ob1.insertsalary(200000);
ob1.printSalary();
}
}

Output
100000
200000

COMPILED LANGUAGE vs INTERPRETED


LANGUAGES

COMPILED LANGUAGES : -

A compiled language is a programming language


that is converted into machine code so that the
processor can execute it. The compiled languages
are usually compiled, not interpreted. For better
understanding you can go through the types of
compiled language – CLEO, COBOL, C, C++, C#,
etc.

INTERPRETED LANGUAGES : -

An interpreted language is also a programming


language that is commonly interpreted. In this, the
implementations perform instructions directly and
easily, without compiling a program into machine-
language instructions. For better understanding,
you can go through the types of the interpreted
languages: Python, BASIC, JavaScript, Perl, etc.

S.N Compiled Interpreted Language


O. Language

1 Compiled Interpreted language


language follows follows one step to get
at least two levels from source code to
to get from source execution.
code to execution.

2 A compiled An interpreted language is


language is a language in which the
converted into implementations execute
machine code so instructions directly
that the processor without earlier compiling a
can execute it. program into machine
language.

4 The compiled The interpreted programs


programs run run slower than the
faster than compiled program.
interpreted
programs.

5 In a compiled In Interpreted languages,


language, the the program cannot be
code can be compiled, it is interpreted.
executed by the
CPU.
6 This language This language delivers
delivers better slower performance.
performance.
IS JAVA INTERPRETED OR COMPILED

Java is considered both an interpreted and a


compiled language. Here’s a breakdown of its
characteristics:

Compilation: Java code is first compiled into an


intermediate form called bytecode (.class files).
This compilation step is done by the Java compiler
(javac). Bytecode is not native machine code, but
rather a platform-independent, portable format.
Interpretation: The Java Virtual Machine (JVM)
interprets the bytecode at runtime, converting it
into native machine code for the specific platform.
This process is called “just-in-time” (JIT)
compilation or dynamic compilation. The JVM does
not execute the bytecode directly; instead, it reads
and interprets it, generating native code on the fly.
This hybrid approach allows Java to achieve
platform independence, as the bytecode can run
on any system that has a JVM implementation,
without the need for recompilation. The JVM’s
ability to dynamically compile and execute
bytecode makes Java a unique blend of compiled
and interpreted languages.

To illustrate this, consider the analogy of a game


console emulator mentioned in one of the search
results. The emulator creates a simulated gaming
console environment, runs files containing
compiled game images (ROM files), and converts
that code to run on its host. Similarly, the JVM
creates an emulated environment and executes
Java bytecode, converting it to native code for the
host machine.

In contrast, languages like Python and JavaScript


are typically considered interpreted, as they do not
undergo a compilation step before execution.
Instead, they are executed directly by an
interpreter at runtime. Java, however, combines
compilation and interpretation, making it a distinct
case in the programming language landscape.

JAVA PACKAGES

A package in Java is used to group related classes.


Think of it as a folder in a file directory. We use
packages to avoid name conflicts, and to write a
better maintainable code. Packages are divided
into two categories:

 Built-in Packages (packages from the Java API)


 User-defined Packages (create your own
packages)

Built-in Packages

The Java API is a library of prewritten classes, that


are free to use, included in the Java Development
Environment.
The library contains components for managing
input, database programming, and much much
more. The complete list can be found at Oracles
website:
https://docs.oracle.com/javase/8/docs/api/.

The library is divided into packages and classes.


Meaning you can either import a single class (along
with its methods and attributes), or a whole
package that contain all the classes that belong to
the specified package.

To use a class or a package from the library, you


need to use the import keyword:

Syntax :

import package.name.Class; // Import a single


classimport package.name.*; // Import the whole
package

Import a Class
If you find a class you want to use, for example,
the Scanner class, which is used to get user
input, write the following code:

Example
import java.util.Scanner;

In the example above, java.util is a package,


while Scanner is a class of the java.util package.
To use the Scanner class, create an object of the
class and use any of the available methods found
in the Scanner class documentation. In our
example, we will use the nextLine() method, which
is used to read a complete line:

Example

Using the Scanner class to get user input:

import java.util.Scanner;

class MyClass {

public static void main(String[] args) {

Scanner myObj = new Scanner(System.in);

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

String userName = myObj.nextLine();

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

}}
Import a Package
There are many packages to choose from. In the
previous example, we used the Scanner class from
the java.util package. This package also contains
date and time facilities, random-number generator
and other utility classes.
To import a whole package, end the sentence with
an asterisk sign (*). The following example will
import ALL the classes in the java.util package:

Example

import java.util.*;

User-defined Packages
To create your own package, you need to
understand that Java uses a file system directory to
store them. Just like folders on your computer:

Example

└── root

└── mypack

└── MyPackageClass.java
To create a package, use the package keyword:

MyPackageClass.java

package mypack;class MyPackageClass {

public static void main(String[] args) {

System.out.println("This is my package!");

}}

Save the file as MyPackageClass.java, and


compile it:
C:\Users\Your Name>javac MyPackageClass.java
Then compile the package:
C:\Users\Your Name>javac -d . MyPackageClass.java

This forces the compiler to create the "mypack"


package.

The -d keyword specifies the destination for where to


save the class file. You can use any directory name, like
c:/user (windows), or, if you want to keep the package
within the same directory, you can use the dot sign ".",
like in the example above.

Note: The package name should be written in lower


case to avoid conflict with class names.
When we compiled the package in the example
above, a new folder was created, called "mypack".
To run the MyPackageClass.java file, write the
following:
C:\Users\Your Name>java mypack.MyPackageClass
The output will be:

This is my package!

HOW TO CREATE PACKAGES IN JAVA

Package in Java is a mechanism to encapsulate a


group of classes, sub-packages, and interfaces. All
we need to do is put related classes into packages.
After that, we can simply write an import class
from existing packages and use it in our program.
A package is a container of a group of related
classes where some classes are accessible or
exposed and others are kept for internal purposes.
We can reuse existing classes from the packages
as many times as we need them in our program.
Package names and directory structure are closely
related

Types of Packages in Java


There are two types of packages in java:

User-defined Package (Create Your Own Package’s)


Built-in packages are packages from the java
application programming interface that are the
packages from Java API for example such as swing,
util, net, io, AWT, lang, javax, etc.
In this article, we will see How To Create A Package
In Java. A package is a group of similar types of
Classes, Interfaces, and sub-packages. We use
Packages to avoid name conflicts.
Syntax: To import a package

import package.name.*;
Example: Importing java.util package

// Java Program to Import a package

// Importing java utility package


import java.util.*;

// Main Class
class GFG {

// Main driver method


public static void main(String[] args)
{

// Scanner to take input from the user object


Scanner myObj = new Scanner(System.in);
String userName;

// Display message
// Enter Your Name And Press Enter
System.out.println("Enter Your Name:");

// Reading the integer age entered using


// nextInt() method
userName = myObj.nextLine();

// Print and display


System.out.println("Your Name is : " +
userName);
}
}
Input
Enter Your Name:
geeksforgeeks
Output:

Your Name is : geeksforgeeks


Here In The Above Program, ‘java.util’ package is
imported Scanner class is used to take input from
the user. These are called as Inbuilt Packages.

Creating a Package in Java


Now in order to create a package in java follow the
certain steps as described below:

First We Should Choose A Name For The Package


We Are Going To Create And Include. The package
command In The first line in the java program
source code.
Further inclusion of classes, interfaces, annotation
types, etc that is required in the package can be
made in the package. For example, the below
single statement creates a package name called
“FirstPackage”.
Syntax: To declare the name of the package to be
created. The package statement simply defines in
which package the classes defined belong.

package FirstPackage ;
Implementation: To Create a Class Inside A
Package

First Declare The Package Name As The First


Statement Of Our Program.
Then We Can Include A Class As A Part Of The
Package.
Example 1: Creating a Class Inside a Package
// Name of package to be created
package FirstPackage;

// Class in which the above created package belong


to
class Welcome {
// main driver method
public static void main(String[] args)
{
// Print statement for the successful
// compilation and execution of the program
System.out.println(
"This Is The First Program Geeks For
Geeks..");
}
}
So Inorder to generate the above-desired output
first do use the commands as specified use the
following specified commands

Procedure to Generate Output:

1. Compile the Welcome.java file:

Command: javac Welcome.java


2. This command creates a Welcome.class file. To
place the class file in the appropriate package
directory, use:

Command: javac -d . Welcome.java


3. This command will create a new folder called
FirstPackage. To run the class, use:

Command: java FirstPackage.Welcome


Output: The Above Will Give The Final Output Of
The Example Program.
Output
Example 2: Another Package Example

// Name of package to be created


package data;

// Class to which the above package belongs


public class Demo {

// Member functions of the class- 'Demo'


// Method 1 - To show()
public void show()
{

// Print message
System.out.println("Hi Everyone");
}

// Method 2 - To show()
public void view()
{
// Print message
System.out.println("Hello");
}
}
Again, in order to generate the above-desired
output first do use the commands as specified use
the following specified commands

Procedure:

1. Compile the Demo.java file:

Command: javac Demo.java


2. This command will generate a Demo.class file:
Command: javac -d . Demo.java
3. This command will create a new folder called
data containing the Demo.class file.

Note: In data Demo.java & Demo.class File should


be present

Example 3: Accessing Data from Another Program

// Name of the package


import data.*;

// Class to which the package belongs


class ncj {

// main driver method


public static void main(String arg[])
{

// Creating an object of Demo class


Demo d = new Demo();

// Calling the functions show() and view()


// using the object of Demo class
d.show();
d.view();
}
}

Procedure to Generate the Output:

1. Compile the ncj.java file:

Command: javac ncj.java


2. The above command compiles ncj.java and
requires the Demo.class file to be present in the
data package.

Command: java ncj


// To Run This File
Output: Generated on the terminal after the above
command Is executed

Hi Everyone
Hello

ACCESS MODIFIERS IN JAVA

Refer to the previous pages of the manual for


access modifiers .

MULTI - THREADING IN JAVA

Multithreading is a Java feature that allows


concurrent execution of two or more parts of a
program for maximum utilization of CPU. Each part
of such program is called a thread. So, threads are
light-weight processes within a process.

Threads can be created by using two mechanisms :

1. Extending the Thread class


2. Implementing the Runnable Interface

Thread creation by extending the Thread class


We create a class that extends the
java.lang.Thread class. This class overrides the
run() method available in the Thread class. A
thread begins its life inside run() method.

We create an object of our new class and call


start() method to start the execution of a thread.
Start() invokes the run() method on the Thread
object.

// Java code for thread creation by extending


// the Thread class
class MultithreadingDemo extends Thread {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " +
Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
public class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object
= new MultithreadingDemo();
object.start();
}
}
}

Output

Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running

Thread creation by implementing the Runnable


Interface

We create a new class which implements


java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and
call start() method on this object.

// Java code for thread creation by implementing


// the Runnable Interface
class MultithreadingDemo implements Runnable {
public void run()
{
try {
// Displaying the thread that is running
System.out.println(
"Thread " +
Thread.currentThread().getId()
+ " is running");
}
catch (Exception e) {
// Throwing an exception
System.out.println("Exception is caught");
}
}
}

// Main Class
class Multithread {
public static void main(String[] args)
{
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
Thread object
= new Thread(new
MultithreadingDemo());
object.start();
}
}
}

Output

Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running

Thread Class vs Runnable Interface

 If we extend the Thread class, our class cannot


extend any other class because Java doesn’t
support multiple inheritance. But, if we
implement the Runnable interface, our class can
still extend other base classes.

 We can achieve basic functionality of a thread


by extending Thread class because it provides
some inbuilt methods like yield(), interrupt() etc.
that are not available in Runnable interface.

 Using runnable will give you an object that can


be shared amongst multiple threads.

LIFE CYCLE OF A THREAD IN JAVA

. Life Cycle of a Thread in Java


The java.lang.Thread class contains a static State
enum – which defines its potential states. During
any given point of time, the thread can only be in
one of these states:

NEW – a newly created thread that has not yet


started the execution
RUNNABLE – either running or ready for execution
but it’s waiting for resource allocation
BLOCKED – waiting to acquire a monitor lock to
enter or re-enter a synchronized block/method
WAITING – waiting for some other thread to
perform a particular action without any time limit
TIMED_WAITING – waiting for some other thread to
perform a specific action for a specified period
TERMINATED – has completed its execution
All these states are covered in the diagram above;
let’s now discuss each of these in detail.

3.1. New
A NEW Thread (or a Born Thread) is a thread that’s
been created but not yet started. It remains in this
state until we start it using the start() method.

The following code snippet shows a newly created


thread that’s in the NEW state:

Runnable runnable = new NewState();


Thread t = new Thread(runnable);
System.out.println(t.getState());
Copy
Since we’ve not started the mentioned thread, the
method t.getState() prints:

NEW
Copy
3.2. Runnable
When we’ve created a new thread and called the
start() method on that, it’s moved from NEW to
RUNNABLE state. Threads in this state are either
running or ready to run, but they’re waiting for
resource allocation from the system.

In a multi-threaded environment, the Thread-


Scheduler (which is part of JVM) allocates a fixed
amount of time to each thread. So it runs for a
particular amount of time, then relinquishes the
control to other RUNNABLE threads.

For example, let’s add t.start() method to our


previous code and try to access its current state:
Runnable runnable = new NewState();
Thread t = new Thread(runnable);
t.start();
System.out.println(t.getState());
Copy
This code is most likely to return the output as:

RUNNABLE
Copy
Note that in this example, it’s not always
guaranteed that by the time our control reaches
t.getState(), it will be still in the RUNNABLE state.

It may happen that it was immediately scheduled


by the Thread-Scheduler and may finish execution.
In such cases, we may get a different output.

3.3. Blocked
A thread is in the BLOCKED state when it’s
currently not eligible to run. It enters this state
when it is waiting for a monitor lock and is trying to
access a section of code that is locked by some
other thread.

Let’s try to reproduce this state:

public class BlockedState {


public static void main(String[] args) throws
InterruptedException {
Thread t1 = new Thread(new
DemoBlockedRunnable());
Thread t2 = new Thread(new
DemoBlockedRunnable());

t1.start();
t2.start();
Thread.sleep(1000);

System.out.println(t2.getState());
System.exit(0);
}
}

class DemoBlockedRunnable implements Runnable


{
@Override
public void run() {
commonResource();
}

public static synchronized void


commonResource() {
while(true) {
// Infinite loop to mimic heavy processing
// 't1' won't leave this method
// when 't2' try to enter this
}
}
}
Copy
In this code:

We’ve created two different threads – t1 and t2


t1 starts and enters the synchronized
commonResource() method; this means that only
one thread can access it; all other subsequent
threads that try to access this method will be
blocked from the further execution until the
current one will finish the processing
When t1 enters this method, it is kept in an infinite
while loop; this is just to imitate heavy processing
so that all other threads cannot enter this method
Now when we start t2, it tries to enter the
commonResource() method, which is already being
accessed by t1, thus, t2 will be kept in the
BLOCKED state
Being in this state, we call t2.getState() and get
the output as:

BLOCKED
Copy
3.4. Waiting
A thread is in WAITING state when it’s waiting for
some other thread to perform a particular action.
According to JavaDocs, any thread can enter this
state by calling any one of the following three
methods:

object.wait()
thread.join() or
LockSupport.park()
Note that in wait() and join() – we do not define any
timeout period as that scenario is covered in the
next section.

We have a separate tutorial that discusses in detail


the use of wait(), notify() and notifyAll().

For now, let’s try to reproduce this state:

public class WaitingState implements Runnable {


public static Thread t1;

public static void main(String[] args) {


t1 = new Thread(new WaitingState());
t1.start();
}

public void run() {


Thread t2 = new Thread(new
DemoWaitingStateRunnable());
t2.start();

try {
t2.join();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}

class DemoWaitingStateRunnable implements


Runnable {
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}

System.out.println(WaitingState.t1.getState())
;
}
}
Copy
Let’s discuss what we’re doing here:

We’ve created and started the t1


t1 creates a t2 and starts it
While the processing of t2 continues, we call
t2.join(), this puts t1 in WAITING state until t2 has
finished execution
Since t1 is waiting for t2 to complete, we’re calling
t1.getState() from t2
The output here is, as you’d expect:

WAITING
Copy
3.5. Timed Waiting
A thread is in TIMED_WAITING state when it’s
waiting for another thread to perform a particular
action within a stipulated amount of time.

According to JavaDocs, there are five ways to put a


thread on TIMED_WAITING state:

thread.sleep(long millis)
wait(int timeout) or wait(int timeout, int nanos)
thread.join(long millis)
LockSupport.parkNanos
LockSupport.parkUntil
To read more about the differences between wait()
and sleep() in Java, have a look at this dedicated
article here.

For now, let’s try to quickly reproduce this state:

public class TimedWaitingState {


public static void main(String[] args) throws
InterruptedException {
DemoTimeWaitingRunnable runnable= new
DemoTimeWaitingRunnable();
Thread t1 = new Thread(runnable);
t1.start();

// The following sleep will give enough time for


ThreadScheduler
// to start processing of thread t1
Thread.sleep(1000);
System.out.println(t1.getState());
}
}

class DemoTimeWaitingRunnable implements


Runnable {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
e.printStackTrace();
}
}
}
Copy
Here, we’ve created and started a thread t1 which
is entered into the sleep state with a timeout
period of 5 seconds; the output will be:

TIMED_WAITING
Copy
3.6. Terminated
This is the state of a dead thread. It’s in the
TERMINATED state when it has either finished
execution or was terminated abnormally.

We have a dedicated article that discusses


different ways of stopping the thread.

Let’s try to achieve this state in the following


example:

public class TerminatedState implements Runnable


{
public static void main(String[] args) throws
InterruptedException {
Thread t1 = new Thread(new
TerminatedState());
t1.start();
// The following sleep method will give enough
time for
// thread t1 to complete
Thread.sleep(1000);
System.out.println(t1.getState());
}

@Override
public void run() {
// No processing in this block
}
}
Copy
Here, while we’ve started thread t1, the very next
statement Thread.sleep(1000) gives enough time
for t1 to complete and so this program gives us the
output as:

TERMINATED
Copy
In addition to the thread state, we can check the
isAlive() method to determine if the thread is alive
or not. For instance, if we call the isAlive() method
on this thread:

Assert.assertFalse(t1.isAlive());
Copy
It returns false. Put simply, a thread is alive if and
only if it has been started and has not yet died.

CONSTRUCTORS OF THE THREAD CLASS


Constructor Action Performed

Allocates a new Thread


Thread()
object.

Thread(Runnable Allocates a new Thread


target) object.

Thread(Runnable Allocates a new Thread


target, String name) object.

Allocates a new Thread


Thread(String name)
object.

Thread(ThreadGroup
Allocates a new Thread
group, Runnable
object.
target)

Allocates a new Thread


object so that it has
Thread(ThreadGroup targeted as its run object,
group, Runnable has the specified name as
target, String name) its name, and belongs to
the thread group referred
to by a group.

Allocates a new Thread


object so that it has
Thread(ThreadGroup targeted as its run object,
group, Runnable has the specified name as
target, String name, its name, and belongs to
long stackSize) the thread group referred
to by group, and has the
specified stack size.

Thread(ThreadGroup Allocates a new Thread


group, String name) object.
Methods of Thread class:

Now let us do discuss all the methods of this class


are illustrated as follows:

Methods Action
Performed

Returns an
estimate of
the number
of active
threads in the
activeCount()
current
thread’s
thread group
and its
subgroups

Determines if
the currently
running
checkAccess() thread has
permission to
modify this
thread

Throws
CloneNotSup
portedExcepti
on as a
clone()
Thread can
not be
meaningfully
cloned
Methods Action
Performed

Returns a
reference to
currentThread() the currently
executing
thread object

Prints a stack
trace of the
current
dumpStack()
thread to the
standard
error stream

Copies into
the specified
array every
active thread
enumerate(Thread[] tarray) in the current
thread’s
thread group
and its
subgroups

Returns a
map of stack
getAllStackTraces()
traces for all
live threads

Returns the
context
getContextClassLoader() ClassLoader
for this
Thread
Methods Action
Performed

Returns the
default
handler
invoked when
getDefaultUncaughtExceptionHand a thread
ler() abruptly
terminates
due to an
uncaught
exception

Returns the
getId() identifier of
this Thread

Returns this
getName() thread’s
name

Returns this
getPriority() thread’s
priority

Returns an
array of stack
trace
elements
getStackTrace()
representing
the stack
dump of this
thread

getState() Returns the


state of this
Methods Action
Performed

thread

Returns the
thread group
getThreadGroup() to which this
thread
belongs

Returns the
handler
invoked when
this thread
getUncaughtExceptionHandler() abruptly
terminates
due to an
uncaught
exception

Returns true
if and only if
the current
thread holds
holdsLock(Object obj)
the monitor
lock on the
specified
object

Interrupts this
interrupt()
thread

interrupted() Tests whether


the current
thread has
been
Methods Action
Performed

interrupted

Tests if this
isAlive() thread is
alive

Tests if this
thread is a
isDaemon()
daemon
thread

Tests whether
this thread
isInterrupted()
has been
interrupted

Waits for this


join()
thread to die

Waits at most
millis
join(long millis) milliseconds
for this
thread to die

run() If this thread


was
constructed
using a
separate
Runnable run
object, then
that Runnable
object’s run
Methods Action
Performed

method is
called;
otherwise,
this method
does nothing
and returns

Sets the
context
setContextClassLoader(ClassLoade
ClassLoader
r cl)
for this
Thread

Marks this
thread as
either a
setDaemon(boolean on)
daemon
thread or a
user thread

setDefaultUncaughtExceptionHand Set the


ler( Thread.UncaughtExceptionHan default
dler eh) handler
invoked when
a thread
abruptly
terminates
due to an
uncaught
exception,
and no other
handler has
been defined
for that
Methods Action
Performed

thread

Changes the
name of this
thread to be
setName(String name)
equal to the
argument
name.

Set the
handler
invoked when
setUncaughtExceptionHandler( Thr this thread
ead.UncaughtExceptionHandler abruptly
eh) terminates
due to an
uncaught
exception

Changes the
setPriority(int newPriority) priority of this
thread

sleep(long millis) Causes the


currently
executing
thread to
sleep
(temporarily
cease
execution) for
the specified
number of
milliseconds,
Methods Action
Performed

subject to the
precision and
accuracy of
system
timers and
schedulers

Causes this
thread to
begin
execution;
the Java
start()
Virtual
Machine calls
the run
method of
this thread

Returns a
string
representatio
n of this
thread,
toString()
including the
thread’s
name,
priority, and
thread group

yield() A hint to the


scheduler
that the
current
thread is
Methods Action
Performed

willing to
yield its
current use of
a processor

Also do remember there are certain methods


inherited from class java. lang.Object that are as
follows:

equals() Method
finalize() Method
getClass() Method
hashCode() Method
notify() Method
notifyAll() Method
toString() Method
wait() Method
Example: Java program to demonstrate usage of
Thread class

// Java program Demonstrating Methods of Thread


class

// Importing package
package generic;

// Class 1
// Helper class implementing Runnable interface
class Helper implements Runnable {

//
public void run() {

// Try block to check for exceptions


try {

// Print statement
System.out.println(&quot;thread2 going to
sleep for 5000&quot;);

// Making thread sleep for 0.5 seconds


Thread.sleep(5000);

// Catch block to handle exception


catch (InterruptedException e) {

// Print statement
System.out.println(&quot;Thread2
interrupted&quot;);
}
}
}

// Class 2
// Helper class extending Runnable interface
public class Test implements Runnable {

// Method 1
// run() method of this class
public void run() {

// Thread run() method


}

// Method 2
// Main driver method
public static void main(String[] args) {

// Making objects of class 1 and 2 in main()


method
Test obj = new Test();
Helper obj2 = new Helper();

// Creating 2 threads in main() method


Thread thread1 = new Thread(obj);
Thread thread2 = new Thread(obj2);

// Moving thread to runnable states


thread1.start();
thread2.start();

// Loading thread 1 in class 1


ClassLoader loader =
thread1.getContextClassLoader();

// Creating 3rd thread in main() method


Thread thread3 = new Thread(new Helper());

// Getting number of active threads


System.out.println(Thread.activeCount());
thread1.checkAccess();

// Fetching an instance of this thread


Thread t = Thread.currentThread();

// Print and display commands


System.out.println(t.getName());

System.out.println(&quot;Thread1 name:
&quot; + thread1.getName());
System.out.println(&quot;Thread1 ID: &quot;
+ thread1.getId());
// Fetching the priority and state of thread1
System.out.println(&quot;Priority of thread1 =
&quot; + thread1.getPriority());

// Getting the state of thread 1 using


getState() method
// and printing the same
System.out.println(thread1.getState());

thread2 = new Thread(obj2);


thread2.start();
thread2.interrupt();
System.out.println(&quot;Is thread2
interrupted? &quot; + thread2.interrupted() );
System.out.println(&quot;Is thread2 alive?
&quot; + thread2.isAlive());

thread1 = new Thread(obj);


thread1.setDaemon(true);
System.out.println(&quot;Is thread1 a
daemon thread? &quot; + thread1.isDaemon());
System.out.println(&quot;Is thread1
interrupted? &quot; + thread1.isInterrupted());

// Waiting for thread2 to complete its


execution
System.out.println(&quot;thread1 waiting for
thread2 to join&quot;);

try {
thread2.join();
}

catch (InterruptedException e) {

// Display the exception along with line


number
// using printStackTrace() method
e.printStackTrace();
}

// Now setting the name of thread1


thread1.setName(&quot;child thread
xyz&quot;);

// Print and display command


System.out.println(&quot;New name set for
thread 1&quot; + thread1.getName());

// Setting the priority of thread1


thread1.setPriority(5);

thread2.yield();

// Fetching the string representation of


thread1
System.out.println(thread1.toString());

// Getting list of active thread in current


thread's group
Thread[] tarray = new Thread[3];

Thread.enumerate(tarray);

// Display commands
System.out.println(&quot;List of active
threads:&quot;);
System.out.printf(&quot;[&quot;);

// Looking out using for each loop


for (Thread thread : tarray) {

System.out.println(thread);
}
// Display commands
System.out.printf(&quot;]\n&quot;);

System.out.println(Thread.getAllStackTraces()
);

ClassLoader classLoader =
thread1.getContextClassLoader();
System.out.println(classLoader.toString());
System.out.println(thread1.getDefaultUncaug
htExceptionHandler());

thread2.setUncaughtExceptionHandler(thread
1.getDefaultUncaughtExceptionHandler());
thread1.setContextClassLoader(thread2.getCo
ntextClassLoader());
thread1.setDefaultUncaughtExceptionHandler
(thread2.getUncaughtExceptionHandler());

thread1 = new Thread(obj);


StackTraceElement[] trace =
thread1.getStackTrace();

System.out.println(&quot;Printing stack trace


elements for thread1:&quot;);

for (StackTraceElement e : trace) {


System.out.println(e);
}

ThreadGroup grp =
thread1.getThreadGroup();
System.out.println(&quot;ThreadGroup to
which thread1 belongs &quot; + grp.toString());
System.out.println(thread1.getUncaughtExcep
tionHandler());
System.out.println(&quot;Does thread1 holds
Lock? &quot; + thread1.holdsLock(obj2));

Thread.dumpStack();

}
}

Output:

3
main
Thread1 name: Thread-0
Thread1 ID: 10
Priority of thread1 = 5
RUNNABLE
Is thread2 interrupted? false
Is thread2 alive? true
Is thread1 a daemon thread? true
Is thread1 interrupted? false
thread1 waiting for thread2 to join
thread2 going to sleep for 5000 ms
thread2 going to sleep for 5000 ms
Thread2 interrupted
New name set for thread 1child thread xyz
Thread[child thread xyz, 5, main]
List of active threads:
[Thread[main, 5, main]
Thread[Thread-1, 5, main]
null
]
{Thread[Signal Dispatcher, 9,
system]=[Ljava.lang.StackTraceElement;@339097
52,
Thread[Thread-1, 5,
main]=[Ljava.lang.StackTraceElement;@55f96302,
Thread[main, 5,
main]=[Ljava.lang.StackTraceElement;@3d4eac69,
Thread[Attach Listener, 5,
system]=[Ljava.lang.StackTraceElement;@42a579
93,
Thread[Finalizer, 8,
system]=[Ljava.lang.StackTraceElement;@75b84c
92,
Thread[Reference Handler, 10,
system]=[Ljava.lang.StackTraceElement;@6bc7c0
54}
sun.misc.Launcher$AppClassLoader@73d16e93
null
Printing stack trace elements for thread1:
ThreadGroup to which thread1 belongs
java.lang.ThreadGroup[name=main, maxpri=10]
java.lang.ThreadGroup[name=main, maxpri=10]
Does thread1 holds Lock? false
java.lang.Exception: Stack trace
at java.lang.Thread.dumpStack(Unknown
Source)
at generic.Test.main(Test.java:111)

JAVA PRIORITY IN MULTI - THREADING

As we already know java being completely


object-oriented works within a multithreading
environment in which thread scheduler assigns the
processor to a thread based on the priority of
thread. Whenever we create a thread in Java, it
always has some priority assigned to it. Priority can
either be given by JVM while creating the thread or
it can be given by the programmer explicitly.

Priorities in threads is a concept where each


thread is having a priority which in layman’s
language one can say every object is having
priority here which is represented by numbers
ranging from 1 to 10.

The default priority is set to 5 as excepted.


Minimum priority is set to 1.
Maximum priority is set to 10.
Here 3 constants are defined in it namely as
follows:

public static int NORM_PRIORITY


public static int MIN_PRIORITY
public static int MAX_PRIORITY
Let us discuss it with an example to get how
internally the work is getting executed. Here we
will be using the knowledge gathered above as
follows:

We will use currentThread() method to get the


name of the current thread. User can also use
setName() method if he/she wants to make names
of thread as per choice for understanding
purposes.
getName() method will be used to get the name
of the thread.
The accepted value of priority for a thread is in
the range of 1 to 10.

Let us do discuss how to get and set priority of a


thread in java.

public final int getPriority():


java.lang.Thread.getPriority() method returns
priority of given thread.
public final void setPriority(int newPriority):
java.lang.Thread.setPriority() method changes the
priority of thread to the value newPriority. This
method throws IllegalArgumentException if value
of parameter newPriority goes beyond minimum(1)
and maximum(10) limit.
Example

// Java Program to Illustrate Priorities in


Multithreading
// via help of getPriority() and setPriority()
method

// Importing required classes


import java.lang.*;

// Main class
class ThreadDemo extends Thread {

// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in
main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}

// Main driver method


public static void main(String[] args)
{
// Creating random threads
// with the help of above class
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();

// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "
+ t1.getPriority());

// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "
+ t2.getPriority());

// Thread 3
System.out.println("t3 thread priority : "
+ t3.getPriority());

// Setting priorities of above threads by


// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw


// IllegalArgumentException

// 2
System.out.println("t1 thread priority : "
+ t1.getPriority());

// 5
System.out.println("t2 thread priority : "
+ t2.getPriority());

// 8
System.out.println("t3 thread priority : "
+ t3.getPriority());

// Main thread

// Displays the name of


// currently executing Thread
System.out.println(
"Currently Executing Thread : "
+ Thread.currentThread().getName());
System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);

System.out.println(
"Main thread priority : "
+ Thread.currentThread().getPriority());
}
}
Output
t1 thread priority : 5
t2 thread priority : 5
t3 thread priority : 5
t1 thread priority : 2
t2 thread priority : 5
t3 thread priority : 8
Currently Executing Thread : main
Main thread priority : 5
Main thread priority : 10
Output explanation:

Thread with the highest priority will get an


execution chance prior to other threads. Suppose
there are 3 threads t1, t2, and t3 with priorities 4,
6, and 1. So, thread t2 will execute first based on
maximum priority 6 after that t1 will execute and
then t3.
The default priority for the main thread is always
5, it can be changed later. The default priority for
all other threads depends on the priority of the
parent thread.
Now geeks you must be wondering out what if
we do assign the same priorities to threads then
what will happen. All the processing in order to
look after threads is carried with help of the thread
scheduler. One can refer to the below example of
what will happen if the priorities are set to the
same and later onwards we will discuss it as an
output explanation to have a better understanding
conceptually and practically.

Example

// Java program to demonstrate that a Child


thread
// Getting Same Priority as Parent thread

// Importing all classes from java.lang package


import java.lang.*;

// Main class
// ThreadDemo
// Extending Thread class
class GFG extends Thread {

// Method 1
// run() method for the thread that is
// invoked as threads are started
public void run()
{
// Print statement
System.out.println("Inside run method");
}

// Method 2
// Main driver method
public static void main(String[] args)
{
// main thread priority is set to 6 now
Thread.currentThread().setPriority(6);

// Current thread is accessed


// using currentThread() method

// Print and display main thread priority


// using getPriority() method of Thread class
System.out.println(
"main thread priority : "
+ Thread.currentThread().getPriority());

// Creating a thread by creating object


inside
// main()
GFG t1 = new GFG();

// t1 thread is child of main thread


// so t1 thread will also have priority 6

// Print and display priority of current thread


System.out.println("t1 thread priority : "
+ t1.getPriority());
}
}
Output
main thread priority : 6
t1 thread priority : 6
Output explanation:

If two threads have the same priority then we


can’t expect which thread will execute first. It
depends on the thread scheduler’s
algorithm(Round-Robin, First Come First Serve, etc)
If we are using thread priority for thread
scheduling then we should always keep in mind
that the underlying platform should provide
support for scheduling based on thread priority.

METHODS RELATED TO THREAD CLASS IN


JAVA
See the method table above for the same

ERRORS AND EXCEPTIONS IN JAVA

In Java, errors and exceptions are both types of


throwable objects, but they represent different
types of problems that can occur during the
execution of a program.

Errors are usually caused by serious problems that


are outside the control of the program, such as
running out of memory or a system crash. Errors
are represented by the Error class and its
subclasses. Some common examples of errors in
Java include:

 OutOfMemoryError: Thrown when the Java


Virtual Machine (JVM) runs out of memory.
 StackOverflowError: Thrown when the call stack
overflows due to too many method invocations.

 NoClassDefFoundError: Thrown when a required


class cannot be found.

Since errors are generally caused by problems that


cannot be recovered from, it’s usually not
appropriate for a program to catch errors. Instead,
the best course of action is usually to log the error
and exit the program.

Exceptions, on the other hand, are used to handle


errors that can be recovered from within the
program. Exceptions are represented by the
Exception class and its subclasses. Some common
examples of exceptions in Java include:
 NullPointerException: Thrown when a null
reference is accessed.

 IllegalArgumentException: Thrown when an


illegal argument is passed to a method.

 IOException: Thrown when an I/O operation fails.

Since exceptions can be caught and handled within


a program, it’s common to include code to catch
and handle exceptions in Java programs.

By handling exceptions, you can provide more


informative error messages to users and prevent
the program from crashing.

In summary, errors and exceptions represent


different types of problems that can occur during
program execution. Errors are usually caused by
serious problems that cannot be recovered from,
while exceptions are used to handle recoverable
errors within a program.

In java, both Errors and Exceptions are the


subclasses of java.lang.Throwable class. Error
refers to an illegal operation performed by the user
which results in the abnormal working of the
program. Programming errors often remain
undetected until the program is compiled or
executed. Some of the errors inhibit the program
from getting compiled or executed. Thus errors
should be removed before compiling and
executing. It is of three types:

 Compile-time
 Run-time
 Logical

Whereas exceptions in java refer to an unwanted


or unexpected event, which occurs during the
execution of a program i.e at run time, that
disrupts the normal flow of the program’s
instructions.

Now let us discuss various types of errors in order


to get a better understanding over arrays. As
discussed in the header an error indicates serious
problems that a reasonable application should not
try to catch. Errors are conditions that cannot get
recovered by any handling techniques. It surely
causes termination of the program abnormally.
Errors belong to unchecked type and mostly occur
at runtime. Some of the examples of errors are Out
of memory errors or System crash errors.

Example 1 Run-time Error

// Java Program to Illustrate Error


// Stack overflow error via infinite recursion

// Class 1
class StackOverflow {

// method of this class


public static void test(int i)
{
// No correct as base condition leads to
// non-stop recursion.
if (i == 0)
return;
else {
test(i++);
}
}
}

// Class 2
// Main class
public class GFG {

// Main driver method


public static void main(String[] args)
{
// Testing for error by passing
// custom integer as an argument
StackOverflow.test(5);
}
}

Example 2

// Java Program to Illustrate Run-time Errors

// Main class
class GFG {
// Main driver method
public static void main(String args[])
{

// Declaring and initializing numbers


int a = 2, b = 8, c = 6;

if (a > b && a > c)


System.out.println(a
+ " is the largest Number");
else if (b > a && b > c)
System.out.println(b
+ " is the smallest Number");

// The correct message should have been


// System.out.println
// (b+" is the largest Number"); to make logic
else
System.out.println(c
+ " is the largest Number");
}
}

Output
8 is the smallest Number

Now let us dwell onto Exceptions which indicates


conditions that a reasonable application might
want to catch. Exceptions are the conditions that
occur at runtime and may cause the termination of
the program. But they are recoverable using try,
catch and throw keywords. Exceptions are divided
into two categories:

 Checked exceptions
 Unchecked exceptions
CHECKED EXCEPTIONS : -

Checked Exceptions in Java


These are the exceptions that are checked at
compile time. If some code within a method throws
a checked exception, then the method must either
handle the exception or it must specify the
exception using the throws keyword. Checked
exceptions can be fully checked or partially
checked.

Fully Checked Exception: A checked exception


where all its child classes are also checked (e.g.,
IOException, InterruptedException).
Partially Checked Exception: A checked exception
where some of its child classes are unchecked
(e.g., Exception).
Checked exceptions represent invalid conditions in
areas outside the immediate control of the
program (like memory, network, file system, etc.).
Any checked exception is a subclass of Exception.
Unlike unchecked exceptions, checked exceptions
must be either caught by the caller or listed as part
of the method signature using the throws keyword.

Example:

// Java Program to Illustrate Checked Exceptions


// Where FileNotFoundException occurred

// Importing I/O classes


import java.io.*;

// Main class
class GFG {
// Main driver method
public static void main(String[] args)
{

// Reading file from path in local directory


FileReader file = new FileReader("C:\\test\\
a.txt");

// Creating object as one of ways of taking


input
BufferedReader fileInput = new
BufferedReader(file);

// Printing first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

// Closing file connections


// using close() method
fileInput.close();
}
}

Output:
To fix the above program, we either need to
specify a list of exceptions using throws, or we
need to use a try-catch block. We have used
throws in the below program. Since
FileNotFoundException is a subclass of
IOException, we can just specify IOException in the
throws list and make the above program compiler-
error-free.

Example:

// Java Program to Illustrate Checked Exceptions


// Where FileNotFoundException does not occur

// Importing I/O classes


import java.io.*;
// Main class
class GFG {

// Main driver method


public static void main(String[] args)
throws IOException
{

// Creating a file and reading from local


repository
FileReader file = new FileReader("C:\\test\\
a.txt");

// Reading content inside a file


BufferedReader fileInput = new
BufferedReader(file);

// Printing first 3 lines of file "C:\test\a.txt"


for (int counter = 0; counter < 3; counter++)
System.out.println(fileInput.readLine());

// Closing all file connections


// using close() method
// Good practice to avoid any memory leakage
fileInput.close();
}
}
Output:

First three lines of file "C:\test\a.txt"

UNCHECKED EXCEPTIONS : -

These are the exceptions that are not checked at


compile time. In C++, all exceptions are
unchecked, so it is not forced by the compiler’s to
either handle or specify the exception. It is up to
the programmers to be civilized and specify or
catch the exceptions. In Java, exceptions under
Error and RuntimeException classes are unchecked
exceptions, everything else under throwable is
checked.

Consider the following Java program. It compiles


fine, but it throws ArithmeticException when run.
The compiler allows it to compile because
ArithmeticException is an unchecked exception.

Example:

// Java Program to Illustrate Un-checked Exceptions

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Here we are dividing by 0
// which will not be caught at compile time
// as there is no mistake but caught at runtime
// because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}
Output

Exception in thread "main"


java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
In short unchecked exceptions are runtime
exceptions that are not required to be caught or
declared in a throws clause. These exceptions are
usually caused by programming errors, such as
attempting to access an index out of bounds in an
array or attempting to divide by zero.

Unchecked exceptions include all subclasses of the


RuntimeException class, as well as the Error class
and its subclasses.

The separation into checked and unchecked


exceptions sounded like a good idea at the time.
However, over the years, it has introduced more
boilerplate and less aesthetically pleasing code
patterns than it solved real problems. The typical
(and unfortunately quite cumbersome) pattern
within the Java ecosystem is to hide (or wrap) the
checked exception within an unchecked one.

Example:

try {
// Some I/O operation here
} catch( final IOException ex ) {
throw new RuntimeException( "I/O operation
failed", ex );
}

Here are some examples of unchecked exceptions


in Java:

1. ArrayIndexOutOfBoundsException: This
exception is thrown when you attempt to access an
array index that is out of bounds.
2. NullPointerException: This exception is thrown
when you attempt to access a null object
reference.
3. ArithmeticException: This exception is thrown
when you attempt to divide by zero or perform an
invalid arithmetic operation.

Conclusion : -

Checked exceptions in Java must be either caught


or declared in the method signature, representing
conditions outside the program’s control.
Unchecked exceptions, typically caused by
programming errors, are not required to be caught
or declared. Understanding the difference between
these exceptions helps write more robust and
error-free code.

Checked exceptions like IOException known to the


compiler at compile time while unchecked
exceptions like ArrayIndexOutOfBoundException
known to the compiler at runtime. It is mostly
caused by the program written by the
programmer.

Example Exception

// Java program illustrating exception thrown


// by Arithmetic Exception class

// Main class
class GFG {

// main driver method


public static void main(String[] args)
{
int a = 5, b = 0;

// Try-catch block to check and handle


exceptions
try {

// Attempting to divide by zero


int c = a / b;
}
catch (ArithmeticException e) {

// Displaying line number where exception


occurred
// using printStackTrace() method
e.printStackTrace();
}
}
}
Output:
Finally now wrapping-off the article by plotting the
differences out between them in a tabular format
as provided below as follows :

Errors Exceptions

We can recover from


exceptions by either
Recovering from Error
using try-catch block or
is not possible.
throwing exceptions back
to the caller.

Exceptions include both


All errors in java are
checked as well as
unchecked type.
unchecked type.

Errors are mostly


Program itself is
caused by the
responsible for causing
environment in which
exceptions.
program is running.

Unchecked exceptions
Errors can occur at occur at runtime whereas
compile time. checked exceptions occur
at compile time

They are defined in They are defined in


java.lang.Error java.lang.Exception
package. package

Examples : Examples : Checked


java.lang.StackOverflo Exceptions :
wError, SQLException,
Errors Exceptions

IOException Unchecked
Exceptions :
java.lang.OutOfMemor ArrayIndexOutOfBoundEx
yError ception,
NullPointerException,
ArithmeticException.

ERRORS IN JAVA

Java Error

An error defines a reasonable issue that is topping


the execution of the program. In different
programming languages, there occur different
types of errors as per the concepts.

This section will discuss errors in Java and different


types of errors, and when such errors occur.

What is an Error in Java

In Java, an error is a subclass of Throwable that


tells that something serious problem is existing
and a reasonable Java application should not try to
catch that error. Generally, it has been noticed that
most of the occurring errors are abnormal
conditions and cannot be resolved by normal
conditions. As these errors are abnormal conditions
and should not occur, thus, error and its subclass
are referred to as Unchecked Exceptions. In
Java, we have the concept of errors as well as
exceptions. Thus there exist several differences
between an exception and an error. Errors cannot
be solved by any handling techniques, whereas we
can solve exceptions using some logic
implementations. So, when an error occurs, it
causes termination of the program as errors cannot
try to catch.

Certain Errors in Java

The Java.lang.Errors provide varieties of errors


that are thrown under the lang package of Java.
Some of the errors are:

Error Name Descri


ption
AbstractMethod When a
Error Java
applicati
on tries
to
invoke
an
abstract
method.
Error Indicatin
g a
serious
but
uncatch
able
error is
thrown.
This
type of
error is a
subclass
of
Throwab
le.
AssertionError To
indicate
that an
assertio
n has
failed.
ClassCircularityE While
rror initializin
g a
class, a
circularit
y is
detected
.
IllegalAccessErro A Java
r applicati
on
attempts
either to
access
or
modify a
field or
maybe
invoking
a
method
to which
it does
not have
access.
ClassFormatErro When
r JVM
attempts
to read a
class file
and find
that the
file is
malform
ed or
cannot
be
interpret
ed as a
class
file.
InstantiationErro In case
r an
applicati
on is
trying to
use the
Java new
construc
t for
instantia
ting an
abstract
class or
an
interface
.
ExceptionInInitia Signals
lizerError that tell
an
unexpec
ted
exceptio
n have
occurred
in a
static
initialize
r.
InternalError Indicatin
g the
occurren
ce of an
unexpec
ted
internal
error in
the JVM.
IncompatibleClas When an
sChangeError incompa
tible
class
change
has
occurred
to some
class of
definitio
n.
LinkageError Its
subclass
indicates
that a
class
has
some
depende
ncy on
another
data.
NoSuchFieldErro In case
r an
applicati
on tries
to
access
or
modify a
specified
field of
an
object,
and
after it,
that
object
no
longer
has this
field.
OutOfMemoryErr In case
or JVM
cannot
allocate
an
object as
it is out
of
memory,
such
error is
thrown
that
says no
more
memory
could be
made
available
by the
GC.
NoClassDefFoun If a class
dError loader
instance
or JVM,
try to
load in
the class
definitio
n and
not
found
any
class
definitio
n of the
class.
ThreadDeath Its
instance
is
thrown
in the
victim
thread
when in
thread
class,
the stop
method
with
zero
argumen
ts is
invoked.
NoSuchMethodEr In case
ror an
applicati
on tries
to call a
specified
method
of a
class
that can
be either
static or
instance
, and
that
class no
longer
holds
that
method
definitio
n.
StackOverflowEr When a
ror stack
overflow
occurs in
an
applicati
on
because
it has
recursed
too
deeply.
UnsatisfiedLinkE In case
rror JVM is
unable
to find
an
appropri
ate
native
languag
e for a
native
method
definitio
n.
VirtualMachineEr Indicate
ror that the
JVM is
broken
or has
run out
of
resource
s,
essential
for
continui
ng
operatin
g.
UnsupportedClas When
sVersionError the JVM
attempts
to read a
class file
and get
to know
that the
major &
minor
version
numbers
in the
file are
unsuppo
rtable.
UnknownError In case a
serious
exceptio
n that is
unknow
n has
occurred
in the
JVM.
VerifyError When it
is found
that a
class file
that is
well-
formed
although
contains
some
sort of
internal
inconsist
ency or
security
problem
by the
verifier.

Let's see an example implementation to know how


an error is thrown.

Java Error Example

Below is the error example implementation


code of the occurrence of the System crash:

1. class StackExample {
2. public static void check(int i)
3. {
4. if (i == 0)
5. return;
6. else {
7. check(i++);
8. }
9. }
10. }
11. public class Main {
12.
13. public static void main(String[] args)
14. {
15. StackExample.check(5);
16. }
17. }

Code Explanation

o In the above code, we have performed a


program of Stack overflow.
o In it, we have created a class, namely
StackOverflow, within which designed a
function that performs an infinite recursion.
o Next, in the main class, we have invoked the
function, and it results in infinite recursion.

On executing the code, we got the below-


shown output:

In order to stop the infinite execution, we may


require to terminate the program because it will
not be tackled by any normal condition.

Error Vs. Exception


There are the below points that differentiate
between both terms:

Exception Error

Can be handled Cannot be handled.

Can be either checked Errors are of unchecked


type or unchecked type type

Thrown at runtime only, Occurs at the runtime of


but the checked the code and is not
exceptions known by known to the compiler.
the compiler and the
unchecked are not.

They are defined in They are defined in


Java.lang.Exception Java.lang.Error package
package.
Program Errors are mainly caused
implementation because of the
mistakes cause environment of the
exceptions. program where it is
executing.

TYPES OF ERRORS IN JAVA

Error is an illegal operation performed by the user


which results in the abnormal working of the
program. Programming errors often remain
undetected until the program is compiled or
executed. Some of the errors inhibit the program
from getting compiled or executed. Thus errors
should be removed before compiling and
executing.

The most common errors can be broadly classified


as follows:

1. Run Time Error:

Run Time errors occur or we can say, are detected


during the execution of the program. Sometimes
these are discovered when the user enters an
invalid data or data which is not relevant. Runtime
errors occur when a program does not contain any
syntax errors but asks the computer to do
something that the computer is unable to reliably
do. During compilation, the compiler has no
technique to detect these kinds of errors. It is the
JVM (Java Virtual Machine) that detects it while the
program is running. To handle the error during the
run time we can put our error code inside the try
block and catch the error inside the catch block.

For example: if the user inputs a data of string


format when the computer is expecting an integer,
there will be a runtime error. Example 1: Runtime
Error caused by dividing by zero

// Java program to demonstrate Runtime Error

class DivByZero {

public static void main(String args[])

int var1 = 15;

int var2 = 5;

int var3 = 0;

int ans1 = var1 / var2;

// This statement causes a runtime error,

// as 15 is getting divided by 0 here

int ans2 = var1 / var3;


System.out.println(

"Division of va1"

+ " by var2 is: "

+ ans1);

System.out.println(

"Division of va1"

+ " by var3 is: "

+ ans2);

Runtime Error in java code:

Exception in thread "main"


java.lang.ArithmeticException: / by zero

at DivByZero.main(File.java:14)

Example 2: Runtime Error caused by


Assigning/Retrieving Value from an array using an
index which is greater than the size of the array

class RTErrorDemo {

public static void main(String args[])

{
int arr[] = new int[5];

// Array size is 5

// whereas this statement assigns

// value 250 at the 10th position.

arr[9] = 250;

System.out.println("Value assigned! ");

RunTime Error in java code:

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 9

at RTErrorDemo.main(File.java:10)

2. Compile Time Error:

Compile Time Errors are those errors which


prevent the code from running because of an
incorrect syntax such as a missing semicolon at
the end of a statement or a missing bracket, class
not found, etc. These errors are detected by the
java compiler and an error message is displayed on
the screen while compiling. Compile Time Errors
are sometimes also referred to as Syntax errors.
These kind of errors are easy to spot and rectify
because the java compiler finds them for you. The
compiler will tell you which piece of code in the
program got in trouble and its best guess as to
what you did wrong. Usually, the compiler
indicates the exact line where the error is, or
sometimes the line just before it, however, if the
problem is with incorrectly nested braces, the
actual error may be at the beginning of the block.
In effect, syntax errors represent grammatical
errors in the use of the programming language.

Example 1: Misspelled variable name or method


names

class MisspelledVar {

public static void main(String args[])

int a = 40, b = 60;

// Declared variable Sum with Capital S

int Sum = a + b;

// Trying to call variable Sum

// with a small s ie. sum

System.out.println(

"Sum of variables is "


+ sum);

Compilation Error in java code:

prog.java:14: error: cannot find symbol

+ sum);

symbol: variable sum

location: class MisspelledVar

1 error

Example 2: Missing semicolons

class PrintingSentence {

public static void main(String args[])

String s = "GeeksforGeeks";

// Missing ';' at the end

System.out.println("Welcome to " + s)

}
}

Compilation Error in java code:

prog.java:8: error: ';' expected

System.out.println("Welcome to " + s)

1 error

Example: Missing parenthesis, square brackets, or


curly braces

class MissingParenthesis {

public static void main(String args[])

System.out.println("Printing 1 to 5 \n");

int i;

// missing parenthesis, should have

// been for(i=1; i<=5; i++)

for (i = 1; i <= 5; i++ {

System.out.println(i + "\n");

} // for loop ends


} // main ends

} // class ends

Compilation Error in java code:

prog.java:10: error: ')' expected

for (i = 1; i <= 5; i++ {

1 error

Example: Incorrect format of selection statements


or loops

class IncorrectLoop {

public static void main(String args[])

System.out.println("Multiplication Table of 7");

int a = 7, ans;

int i;

// Should have been

// for(i=1; i<=10; i++)


for (i = 1, i <= 10; i++) {

ans = a * i;

System.out.println(ans + "\n");

Compilation Error in java code:

prog.java:12: error: not a statement

for (i = 1, i <= 10; i++) {

prog.java:12: error: ';' expected

for (i = 1, i <= 10; i++) {

2 errors

Logical Error: A logic error is when your program


compiles and executes, but does the wrong thing
or returns an incorrect result or no output when it
should be returning an output. These errors are
detected neither by the compiler nor by JVM. The
Java system has no idea what your program is
supposed to do, so it provides no additional
information to help you find the error. Logical
errors are also called Semantic Errors.
These errors are caused due to an incorrect idea or
concept used by a programmer while coding.
Syntax errors are grammatical errors whereas,
logical errors are errors arising out of an incorrect
meaning. For example, if a programmer
accidentally adds two variables when he or she
meant to divide them, the program will give no
error and will execute successfully but with an
incorrect result.

Example: Accidentally using an incorrect operator


on the variables to perform an operation (Using ‘/’
operator to get the modulus instead using ‘%’)

public class LErrorDemo {

public static void main(String[] args)

int num = 789;

int reversednum = 0;

int remainder;

while (num != 0) {

// to obtain modulus % sign should

// have been used instead of /

remainder = num / 10;


reversednum

= reversednum * 10

+ remainder;

num /= 10;

System.out.println("Reversed number is "

+ reversednum);

Output:

Reversed number is 7870

Example: Displaying the wrong message

class IncorrectMessage {

public static void main(String args[])

int a = 2, b = 8, c = 6;

System.out.println(

"Finding the largest number \n");

if (a > b && a > c)


System.out.println(

a + " is the largest Number");

else if (b > a && b > c)

System.out.println(

b + " is the smallest Number");

// The correct message should have

// been System.out.println

//(b+" is the largest Number");

// to make logic

else

System.out.println(

c + " is the largest Number");

Output:

Finding the largest number


8 is the smallest Number

Syntax Error:

Syntax and Logical errors are faced by


Programmers.

Spelling or grammatical mistakes are syntax


errors, for example, using an uninitialized variable,
using an undefined variable, etc., missing a
semicolon, etc.

int x, y;

x = 10 // missing semicolon (;)

z = x + y; // z is undefined, y in uninitialized.

Syntax errors can be removed with the help of the


compiler.

TRY - CATCH BLOCK IN JAVA

Java Exceptions
When executing Java code, different errors can
occur: coding errors made by the programmer,
errors due to wrong input, or other unforeseeable
things.
When an error occurs, Java will normally stop and
generate an error message. The technical term for
this is: Java will throw an exception (throw an
error).

Java try and catch


The try statement allows you to define a block of
code to be tested for errors while it is being
executed.
The catch statement allows you to define a block of
code to be executed, if an error occurs in the try
block.
The try and catch keywords come in pairs:

SyntaxGet your own Java Server

try {

// Block of code to try}catch(Exception e) {

// Block of code to handle errors}

Consider the following example:

This will generate an error,


because myNumbers[10] does not exist.

public class Main {


public static void main(String[ ] args) {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]); // error!

}}

The output will be something like this:

Exception in thread "main"


java.lang.ArrayIndexOutOfBoundsException: 10
at Main.main(Main.java:4)

Note: ArrayIndexOutOfBoundsException occurs when


you try to access an index number that does not exist.

If an error occurs, we can use try...catch to catch


the error and execute some code to handle it:

Example

public class Main {

public static void main(String[ ] args) {

try {
int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

}}

The output will be:

Something went wrong.

Finally
The finally statement lets you execute code,
after try...catch, regardless of the result:

Example

public class Main {

public static void main(String[] args) {

try {

int[] myNumbers = {1, 2, 3};

System.out.println(myNumbers[10]);

} catch (Exception e) {

System.out.println("Something went wrong.");

} finally {

System.out.println("The 'try catch' is finished.");

}
}}

The output will be:

Something went wrong.


The 'try catch' is finished.

The throw keyword


The throw statement allows you to create a custom
error.
The throw statement is used together with
an exception type. There are many exception
types available in
Java: ArithmeticException, FileNotFoundException,
ArrayIndexOutOfBoundsException, SecurityExcepti
on, etc:

Example

Throw an exception if age is below 18 (print "Access


denied"). If age is 18 or older, print "Access granted":

public class Main {

static void checkAge(int age) {


if (age < 18) {

throw new ArithmeticException("Access denied - You


must be at least 18 years old.");

else {

System.out.println("Access granted - You are old


enough!");

public static void main(String[] args) {

checkAge(15); // Set age to 15 (which is below 18...)

}}
The output will be:

Exception in thread "main"


java.lang.ArithmeticException: Access denied - You
must be at least 18 years old.
at Main.checkAge(Main.java:4)
at Main.main(Main.java:12)

If age was 20, you would not get an exception:

Example

checkAge(20);

The output will be:

Access granted - You are old enough!

HANDALING MAJOR EXCEPTIONS IN JAVA

Exception Handling in Java is one of the effective


means to handle runtime errors so that the regular
flow of the application can be preserved. Java
Exception Handling is a mechanism to handle
runtime errors such as ClassNotFoundException,
IOException, SQLException, RemoteException, etc.

What are Java Exceptions?


In Java, Exception is an unwanted or unexpected
event, which occurs during the execution of a
program, i.e. at run time, that disrupts the normal
flow of the program’s instructions. Exceptions can
be caught and handled by the program. When an
exception occurs within a method, it creates an
object. This object is called the exception object. It
contains information about the exception, such as
the name and description of the exception and the
state of the program when the exception occurred.

Major reasons why an exception Occurs


 Invalid user input
 Device failure
 Loss of network connection
 Physical limitations (out-of-disk memory)
 Code errors
 Out of bound
 Null reference
 Type mismatch
 Opening an unavailable file
 Database errors
 Arithmetic errors
Errors represent irrecoverable conditions such as
Java virtual machine (JVM) running out of memory,
memory leaks, stack overflow errors, library
incompatibility, infinite recursion, etc. Errors are
usually beyond the control of the programmer, and
we should not try to handle errors.

Difference between Error and Exception

Let us discuss the most important part which is the


differences between Error and Exception that is as
follows:

 Error: An Error indicates a serious problem that


a reasonable application should not try to catch.
 Exception: Exception indicates conditions that a
reasonable application might try to catch.
Exception Hierarchy

All exception and error types are subclasses of the


class Throwable, which is the base class of the
hierarchy. One branch is headed by Exception. This
class is used for exceptional conditions that user
programs should catch. NullPointerException is an
example of such an exception. Another branch,
Error is used by the Java run-time system(JVM) to
indicate errors having to do with the run-time
environment itself(JRE). StackOverflowError is an
example of such an error.

Types of Exceptions
Java defines several types of exceptions that relate
to its various class libraries. Java also allows users
to define their own exceptions.

Exceptions can be categorized in two ways:

Built-in Exceptions
Checked Exception
Unchecked Exception
User-Defined Exceptions
Let us discuss the above-defined listed exception
that is as follows:

1. Built-in Exceptions
Built-in exceptions are the exceptions that are
available in Java libraries. These exceptions are
suitable to explain certain error situations.

Checked Exceptions: Checked exceptions are


called compile-time exceptions because these
exceptions are checked at compile-time by the
compiler.

Unchecked Exceptions: The unchecked exceptions


are just opposite to the checked exceptions. The
compiler will not check these exceptions at
compile time. In simple words, if a program throws
an unchecked exception, and even if we didn’t
handle or declare it, the program would not give a
compilation error.
Note: For checked vs unchecked exception, see
Checked vs Unchecked Exceptions

2. User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not
able to describe a certain situation. In such cases,
users can also create exceptions, which are called
‘user-defined Exceptions’.

The advantages of Exception Handling in Java are


as follows:

Provision to Complete Program Execution


Easy Identification of Program Code and Error-
Handling Code
Propagation of Errors
Meaningful Error Reporting
Identifying Error Types
Methods to print the Exception information:

1. printStackTrace()
This method prints exception information in the
format of the Name of the exception: description of
the exception, stack trace.

Example:
//program to print the exception information using
printStackTrace() method

import java.io.*;

class GFG {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
e.printStackTrace();
}
}
}

Output

java.lang.ArithmeticException: / by zero
at GFG.main(File.java:10)
2. toString()
The toString() method prints exception information
in the format of the Name of the exception:
description of the exception.

Example:

//program to print the exception information using


toString() method

import java.io.*;

class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.toString());
}
}
}

Output

java.lang.ArithmeticException: / by zero
3. getMessage()
The getMessage() method prints only the
description of the exception.

Example:

//program to print the exception information using


getMessage() method

import java.io.*;

class GFG1 {
public static void main (String[] args) {
int a=5;
int b=0;
try{
System.out.println(a/b);
}
catch(ArithmeticException e){
System.out.println(e.getMessage());
}
}
}

Output

/ by zero
How Does JVM Handle an Exception?
Default Exception Handling: Whenever inside a
method, if an exception has occurred, the method
creates an Object known as an Exception Object
and hands it off to the run-time system(JVM). The
exception object contains the name and
description of the exception and the current state
of the program where the exception has occurred.
Creating the Exception Object and handling it in
the run-time system is called throwing an
Exception. There might be a list of the methods
that had been called to get to the method where
an exception occurred. This ordered list of methods
is called Call Stack. Now the following procedure
will happen.

 The run-time system searches the call stack to


find the method that contains a block of code
that can handle the occurred exception. The
block of the code is called an Exception handler.
 The run-time system starts searching from the
method in which the exception occurred and
proceeds through the call stack in the reverse
order in which methods were called.
 If it finds an appropriate handler, then it passes
the occurred exception to it. An appropriate
handler means the type of exception object
thrown matches the type of exception object it
can handle.
 If the run-time system searches all the methods
on the call stack and couldn’t have found the
appropriate handler, then the run-time system
handover the Exception Object to the default
exception handler, which is part of the run-time
system. This handler prints the exception
information in the following format and
terminates the program abnormally.

Exception in thread "xxx" Name of Exception :


Description
... ...... .. // Call Stack
Look at the below diagram to understand the flow
of the call stack

// Java Program to Demonstrate How Exception Is


Thrown

// Class
// ThrowsExecp
class GFG {

// Main driver method


public static void main(String args[])
{
// Taking an empty string
String str = null;
// Getting length of a string
System.out.println(str.length());
}
}

Output : -

Let us see an example that illustrates how a run-


time system searches for appropriate exception
handling code on the call stack.

Example:

// Java Program to Demonstrate Exception is


Thrown
// How the runTime System Searches Call-Stack
// to Find Appropriate Exception Handler
// Class
// ExceptionThrown
class GFG {

// Method 1
// It throws the Exception(ArithmeticException).
// Appropriate Exception handler is not found
// within this method.
static int divideByZero(int a, int b)
{

// this statement will cause


ArithmeticException
// (/by zero)
int i = a / b;

return i;
}

// The runTime System searches the appropriate


// Exception handler in method also but couldn't
have
// found. So looking forward on the call stack
static int computeDivision(int a, int b)
{

int res = 0;

// Try block to check for exceptions


try {

res = divideByZero(a, b);


}

// Catch block to handle


NumberFormatException
// exception Doesn't matches with
// ArithmeticException
catch (NumberFormatException ex) {
// Display message when exception occurs
System.out.println(
"NumberFormatException is occurred");
}
return res;
}

// Method 2
// Found appropriate Exception handler.
// i.e. matching catch block.
public static void main(String args[])
{

int a = 1;
int b = 0;

// Try block to check for exceptions


try {
int i = computeDivision(a, b);
}

// Catch block to handle ArithmeticException


// exceptions
catch (ArithmeticException ex) {

// getMessage() will print description


// of exception(here / by zero)
System.out.println(ex.getMessage());
}
}
}

Output
/ by zero
How Programmer Handle an Exception?
Customized Exception Handling: Java exception
handling is managed via five keywords: try, catch,
throw, throws, and finally. Briefly, here is how they
work. Program statements that you think can raise
exceptions are contained within a try block. If an
exception occurs within the try block, it is thrown.
Your code can catch this exception (using catch
block) and handle it in some rational manner.
System-generated exceptions are automatically
thrown by the Java run-time system. To manually
throw an exception, use the keyword throw. Any
exception that is thrown out of a method must be
specified as such by a throws clause. Any code that
absolutely must be executed after a try block
completes is put in a finally block.

Tip: One must go through control flow in try catch


finally block for better understanding.

Need for try-catch clause(Customized Exception


Handling)
Consider the below program in order to get a
better understanding of the try-catch clause.

Example:

// Java Program to Demonstrate


// Need of try-catch Clause

// Class
class GFG {

// Main driver method


public static void main(String[] args)
{
// Taking an array of size 4
int[] arr = new int[4];

// Now this statement will cause an exception


int i = arr[4];

// This statement will never execute


// as above we caught with an exception
System.out.println("Hi, I want to execute");
}
}

Output

program output
Unchecked exception

Output explanation: In the above example, an


array is defined with size i.e. you can access
elements only from index 0 to 3. But you trying to
access the elements at index 4(by mistake) that’s
why it is throwing an exception. In this case, JVM
terminates the program abnormally. The statement
System.out.println(“Hi, I want to execute”); will
never execute. To execute it, we must handle the
exception using try-catch. Hence to continue the
normal flow of the program, we need a try-catch
clause.

How to Use the Try-catch Clause?


try {
// block of code to monitor for errors
// the code you think can raise an exception
} catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
} catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// optional
finally { // block of code to be executed after try
block ends
}
Certain key points need to be remembered that
are as follows:

In a method, there can be more than one


statement that might throw an exception, So put
all these statements within their own try block and
provide a separate exception handler within their
own catch block for each of them.
If an exception occurs within the try block, that
exception is handled by the exception handler
associated with it. To associate the exception
handler, we must put a catch block after it. There
can be more than one exception handler. Each
catch block is an exception handler that handles
the exception to the type indicated by its
argument. The argument, ExceptionType declares
the type of exception that it can handle and must
be the name of the class that inherits from the
Throwable class.
For each try block, there can be zero or more catch
blocks, but only one final block.
The finally block is optional. It always gets
executed whether an exception occurred in try
block or not. If an exception occurs, then it will be
executed after try and catch blocks. And if an
exception does not occur, then it will be executed
after the try block. The finally block in Java is used
to put important codes such as clean-up code e.g.,
closing the file or closing the connection.
If we write System.exit in the try block, then finally
block will not be executed.
The summary is depicted via visual aid below as
follows:
NESTED TRY CATCH BLOCKS

In Java , we can use a try block within a try block.


Each time a try statement is entered, the context
of that exception is pushed onto a stack. Given
below is an example of a nested try. In this
example, the inner try block (or try-block2) is used
to handle ArithmeticException, i.e., division by
zero. After that, the outer try block (or try-block)
handles the ArrayIndexOutOfBoundsException.

Example to Demonstrate Nested Try Blocks in


Exception Handling in Java
Below is the implementation of Nested Try Blocks
in Exception Handling in Java:

class NestedTry {

// main method
public static void main(String args[])
{
// Main try block
try {

// initializing array
int a[] = { 1, 2, 3, 4, 5 };

// trying to print element at index 5


System.out.println(a[5]);

// try-block2 inside another try block


try {

// performing division by zero


int x = a[2] / 0;
}
catch (ArithmeticException e2) {
System.out.println("division by zero is
not possible");
}
}
catch (ArrayIndexOutOfBoundsException e1)
{
System.out.println("ArrayIndexOutOfBound
sException");
System.out.println("Element at such index
does not exists");
}
}
}

Output
ArrayIndexOutOfBoundsException
Element at such index does not exists

Whenever a try block does not have a catch block


for a particular exception, then the catch blocks of
parent try block are inspected for that exception,
and if a match is found then that catch block is
executed. If none of the catch blocks handles the
exception then the Java run-time system will
handle the exception and a system generated
message would be shown for the exception.

Why “division by zero is not possible” not printed


on the Screen?
Here is the “division by zero is not possible”
statement is executed, but it is done within the
inner catch block, not in the outer catch block for
ArrayIndexOutOfBoundsException. If you want to
see both messages, you can modify the code to
print the “division by zero is not possible” message
outside the inner try block.

Example 2:

class Nesting {
// main method
public static void main(String args[])
{
// main try-block
try {
// try-block2
try {
// try-block3
try {
int arr[] = { 1, 2, 3, 4 };
System.out.println(arr[10]);
}

// handles ArithmeticException if any


catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println(" try-block1");
}
}
// handles ArithmeticException if any
catch (ArithmeticException e) {
System.out.println("Arithmetic
exception");
System.out.println(" try-block2");
}
}

// handles ArrayIndexOutOfBoundsException if
any
catch (ArrayIndexOutOfBoundsException e4)
{
System.out.print("ArrayIndexOutOfBoundsE
xception");
System.out.println(" main try-block");
}
catch (Exception e5) {
System.out.print("Exception");
System.out.println(" handled in main try-
block");
}
}
}

Output
ArrayIndexOutOfBoundsException main try-block

Exception Class in Java

An error is a problem, bug, or human-created


mistake that arises at the time of execution of a
program. An exception interrupts the flow of the
program and terminates it abnormally. The
termination of the program abnormally is not
recommended, and for that, we need to handle
these exceptions.
Java provides Java.lang.Exception class for
handling the exceptions which inherit the
properties and methods
of Object and Throwable class.

Methods of java.lang.Throwable class

addSuppressed(), fillInStackTrace(), getCause(), ge


tLocalizedMessage(), getMessage(), getStackTrace(
), getSuppressed(), initCause(), printStackTrace(),
printStackTrace(), printStackTrace(), setStackTrace
(), and toString().

Methods of java.lang.Object class

clone(), equals(), finalize(), getClass(), hashCode(),


notify(), notifyAll(), and wait().

The Exception class has a set of sub-classes for


handling different types of exceptions such
as IOException, NotBoundException,
and NotOwnerException etc.

All the subclasses of the Exception class are in the


form of Throwable that indicates the conditions
that an application wants to catch.

The Exception class provides the following 5


constructors:

1. public Exception()

The public Exception () construct an exception


with a null detail message. The cause can be
subsequently initialized by
calling Throwable.initCause(Java.lang.Throwa
ble). It is a default constructor and takes no
parameters for message and Throwable cause.
2. public Exception(String message)

The public Exception( String


message) construct a new exception with the
given detailed message. Just like the default
constructor, the cause can be subsequently
initialized by
calling Throwable.initCause(Java.lang.Throwa
ble). It is a parameterized constructor which takes
a parameter of type String for detail message. The
detail message is saved so that
the Throwable.getMessage() method can
retrieve it.

Parameters

a. message
It is of type string for the error message or
detail message.

3. public Exception(String message,


Throwable cause)

It is another variation of the Exception ()


constructor, which takes two parameters,
i.e., message and cause. It constructs a new
exception with the given detailed message
and cause. The message associated with
the cause will not be automatically included in
the exception detail message.

Parameters

1. message
It is of type string for the error message or
detail message.
2. cause
The cause is saved so that
the Throwable.getCause() method can
retrieve it. The null value defines that the
cause is nonexistent or unknown.

4. public Exception(Throwable cause)

It is another variation of the Exception ()


constructor, which takes only a single
parameter, i.e., cause. The constructor
creates an Exception with the given cause and
the detailed message of the cause.

1. detail message = (cause == null ? null : caus


e.toString())

It is mainly used for the exceptions, which are


more than wrappers for other throwables.

Parameters

1. cause

The cause is saved so that


the Throwable.getCause() method can
retrieve it. The null value defines that the
cause is nonexistent or unknown.

5. protected Exception(String message,


Throwable cause, Boolean
enableSuppression, Boolean
writableStackTrace)

It is a little different from the other


constructors. It is also a parameterized
constructor and takes 4 parameters,
i.e., message, cause, enableSuppression,
and writableStackTrace.
It creates an exception with the specified
parameters.

Parameters

1. message
It is a detailed message.
2. cause
The cause is saved so that
the Throwable.getCause() method can
retrieve it. The null value defines that the
cause is nonexistent or unknown.
3. enableSuppression
It is a Boolean value that defines whether
the suppression is enabled or not.
4. writableStackTrace
It is a Boolean value that defines whether
the stack trace is writable or not.

Create custom exceptions using the


Exception class

We have a series of predefined exceptions in


Java. Many times, we need to create our own
Exception for handling errors. We used the
custom exception for customizing the
exceptions as per the user need.

Let's take some examples of the Exception


class and understand how we can create our
own Exception in Java.

CustomExceptionExample1.java

1. // import required classes and packages


2. package javaTpoint.MicrosoftJava;
3.
4. import java.util.Scanner;
5.
6. // create class InvalidAgeException by extendi
ng Exception class for create invalid age excep
tion
7. @SuppressWarnings("serial")
8. class InvalidAgeException extends Exceptio
n
9. {
10. // parameterized constructor that accep
ts only detail message
11. public InvalidAgeException (String mes
sage)
12. {
13. // calling parent Exception class cons
tructor
14. super(message);
15. }
16. }
17.
18. // create CustomExceptionExample1 class
that uses custom exception InvalidAgeExcepti
on
19. public class CustomExceptionExample1

20. {
21.
22. // create method checkEligibility() to ch
eck whether the given is valid for exam or not
23. static void checkEligibility (int age) th
rows InvalidAgeException
24. {
25. // use conditional statement to check
age
26. if(age < 18){
27. // we throw InvalidAgeException w
hen the age is less than 18
28. throw new InvalidAgeException("
You are not eligible for the exam.");
29. }else {
30. System.out.println("You are eligibl
e for the exam.");
31. }
32. }
33.
34. // main() method start
35. public static void main(String args[])

36. {
37. // create scanner class object to take
input from user
38. Scanner scan = new Scanner(Syste
m.in);
39.
40. // declare variable age to store the us
er input
41. int age;
42.
43. // take input from the user
44. System.out.println("Please enter you
r age:");
45. age = scan.nextInt();
46.
47. scan.close();
48.
49. try
50. {
51. // call method checkEligibility() to
check whether the user is eligible for exam or
not
52. checkEligibility(age);
53. }
54. catch (InvalidAgeException exceptio
n)
55. {
56. System.out.println("We found an e
xcaption:");
57.
58. // printing the message from Invali
dAgeException object
59. System.out.println(exception);
60.
61. }
62. }
63. }

Output:

Description:

In the above code, we create a custom


exception, InvalidAgeException. We take input
from the user for checking whether the user is
eligible for the exam or not. We call the
checkEligibility() method by passing the user
input to it. The checkEligibility() method
checks whether the given age is greater than
18 or not because a user having age 18+ is
eligible for the exam. The method throws
InvalidAgeException when it finds an age less
than 18. The catch block in the main() method
will handle this Exception and print the
detailed message of the Exception.

CustomExceptionExample2.java

1. // import required classes and packages


2. package javaTpoint.MicrosoftJava;
3.
4. import java.util.Scanner;
5. import java.util.ArrayList;
6. import java.util.Arrays;
7.
8. // create class AlreadyExistException by exten
ding Exception class for checking whether the
language exists in the array list or not
9. @SuppressWarnings("serial")
10. class AlreadyExistException extends Ex
ception
11. {
12. // parameterized constructor that accep
ts only detail message
13. public AlreadyExistException (String m
essage)
14. {
15. // calling parent Exception class cons
tructor
16. super(message);
17. }
18. }
19.
20. // create CustomExceptionExample2 class
that uses custom exception AlreadyExistExcep
tion
21. public class CustomExceptionExample2

22. {
23. // create method checkExistence() to ch
eck whether the given language already exists
in the list or not
24. static void checkExistence (ArrayList<
String> languages, String language) throws A
lreadyExistException
25. {
26. // use conditional statement to check
the existence of the language
27. if(languages.contains(language)){
28. // we throw AlreadyExistException
when the language is already exist in the list
29. throw new AlreadyExistException
(language +" is already exist in the list.");
30. }else {
31. languages.add(language);
32. System.out.println(language + " is
added to the ArrayList successfully.");
33. for(int i = 0; i < languages.size();
i++) {
34. System.out.println(languages.g
et(i));
35. }
36. }
37. }
38.
39. // main() method start
40. public static void main(String args[])

41. {
42. // declare ArrayList with some langua
ges
43. ArrayList<String> languages = new
ArrayList<>(Arrays.asList("Java", "Python", "Ja
vaScript"));
44.
45. // create scanner class object to take
input from user
46. Scanner scan = new Scanner(Syste
m.in);
47.
48. // declare variable lang to store the u
ser input
49. String lang;
50.
51. // take input from the user
52. System.out.println("Enter language t
o enter in the ArrayList:");
53. lang = scan.nextLine();
54.
55. scan.close();
56.
57. try
58. {
59. // call method checkExistence() to
check whether the language is already exist in
the list or not
60. checkExistence(languages, lang);

61. }
62. catch (AlreadyExistException except
ion)
63. {
64. System.out.println("We found an e
xcaption:");
65.
66. // printing the message from Alrea
dyExistException object
67. System.out.println(exception);
68.
69. }
70. }
71. }

Output:

Description:

In the above code, we create the custom


exception AlreadyExistException. We take
input from the user to add it in the languages
ArrayList. We call the checkExistence()
method by passing the user input and the
languages ArrayList to it.
The checkExistence() method checks whether
the given language is available in the
languages ArrayList or not. The method throws
AlreadyExistException when it finds the user
input language in the languages ArrayList. The
catch block in the main() method will handle
this Exception and print the detailed message
of the Exception. If the checkExistence()
method doesn't find the given language in the
languages ArrayList, it will add the user input
language in the languages ArrayList.

DIFFERENCE BETWEEN THROW AND THROWS


IN JAVA

The throw and throws are the concepts of


exception handling in Java where the throw
keyword throws the exception explicitly from a
method or a block of code, whereas the throws
keyword is used in the signature of the method.

The differences between throw and throws in Java


are:
S. Key throw throws
N Differenc
o. e

The throw key The throws key


word is used word is used in
inside a the function
function. It is signature. It is
Point of
1. used when it is used when the
Usage
required to function has
throw an some statements
Exception that can lead to
logically. exceptions.

The throws key


word can be
used to declare
multiple
The throw key
exceptions,
word is used to
separated by a
throw an
comma.
Exception exception
2. Whichever
s Thrown explicitly. It can
exception
throw only one
occurs, if
exception at a
matched with
time.
the declared
ones, is thrown
automatically
then.

3. Syntax Syntax Syntax


of throw keywo of throws keywo
rd includes the rd includes the
instance of the class names of
Exception to be the Exceptions to
thrown. Syntax be thrown.
S. Key throw throws
N Differenc
o. e

wise throw Syntax wise


keyword is throws keyword
followed by the is followed by
instance exception class
variable. names.

throw keyword
cannot
propagate
checked
throws keyword
Propagati exceptions. It is
is used to
on of only used to
4. propagate the
Exception propagate the
checked
s unchecked
Exceptions only.
Exceptions that
are not checked
using the
throws keyword.
Examples
1. Java throw

// Java program to demonstrate the working


// of throw keyword in exception handling

public class GFG {


public static void main(String[] args)
{
// Use of unchecked Exception
try {
// double x=3/0;
throw new ArithmeticException();
}
catch (ArithmeticException e) {
e.printStackTrace();
}
}
}
Output:

java.lang.ArithmeticException
at GFG.main(GFG.java:10)
2. Java throws

// Java program to demonstrate the working


// of throws keyword in exception handling
import java.io.*;
import java.util.*;

public class GFG {

public static void writeToFile() throws Exception


{
BufferedWriter bw = new BufferedWriter(
new FileWriter("myFile.txt"));
bw.write("Test");
bw.close();
}

public static void main(String[] args) throws


Exception
{
try {
writeToFile();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Output:
java.security.AccessControlException: access
denied ("java.io.FilePermission" "myFile.txt"
"write")
at GFG.writeToFile(GFG.java:10)

FINALLY BLOCK IN JAVA

The finally Block


The finally block always executes when the try
block exits. This ensures that the finally block is
executed even if an unexpected exception occurs.
But finally is useful for more than just exception
handling — it allows the programmer to avoid
having cleanup code accidentally bypassed by a
return, continue, or break. Putting cleanup code in
a finally block is always a good practice, even
when no exceptions are anticipated.

Note: The finally block may not execute if the JVM


exits while the try or catch code is being executed.
The try block of the writeList method that you've
been working with here opens a PrintWriter. The
program should close that stream before exiting
the writeList method. This poses a somewhat
complicated problem because writeList's try block
can exit in one of three ways.

The new FileWriter statement fails and throws an


IOException.
The list.get(i) statement fails and throws an
IndexOutOfBoundsException.

Everything succeeds and the try block exits


normally.
The runtime system always executes the
statements within the finally block regardless of
what happens within the try block. So it's the
perfect place to perform cleanup.

The following finally block for the writeList method


cleans up and then closes the PrintWriter and
FileWriter.

finally {
if (out != null) {
System.out.println("Closing PrintWriter");
out.close();
} else {
System.out.println("PrintWriter not open");
}
if (f != null) {
System.out.println("Closing FileWriter");
f.close();
}
}

Important: Use a try-with-resources statement


instead of a finally block when closing a file or
otherwise recovering resources. The following
example uses a try-with-resources statement to
clean up and close the PrintWriter and FileWriter
for the writeList method:
public void writeList() throws IOException {
try (FileWriter f = new FileWriter("OutFile.txt");
PrintWriter out = new PrintWriter(f)) {
for (int i = 0; i < SIZE; i++) {
out.println("Value at: " + i + " = " +
list.get(i));
}
}
}
The try-with-resources statement automatically
releases system resources when no longer needed.

JAVA COLLECTIONS FRAMEWORK

Introduction
The Java platform includes a collections framework.
A collection is an object that represents a group of
objects (such as the classic Vector class). A
collections framework is a unified architecture for
representing and manipulating collections,
enabling collections to be manipulated
independently of implementation details.
The primary advantages of a collections framework
are that it:

 Reduces programming effort by providing


data structures and algorithms so you don't have
to write them yourself.
 Increases performance by providing high-
performance implementations of data structures
and algorithms. Because the various
implementations of each interface are
interchangeable, programs can be tuned by
switching implementations.
 Provides interoperability between
unrelated APIs by establishing a common
language to pass collections back and forth.
 Reduces the effort required to learn APIs by
requiring you to learn multiple ad hoc collection
APIs.
 Reduces the effort required to design and
implement APIs by not requiring you to
produce ad hoc collections APIs.
 Fosters software reuse by providing a
standard interface for collections and algorithms
with which to manipulate them.

The collections framework consists of:

 Collection interfaces. Represent different


types of collections, such as sets, lists, and
maps. These interfaces form the basis of the
framework.
 General-purpose implementations. Primary
implementations of the collection interfaces.
 Legacy implementations. The collection
classes from earlier
releases, Vector and Hashtable, were retrofitted
to implement the collection interfaces.
 Special-purpose implementations.
Implementations designed for use in special
situations. These implementations display
nonstandard performance characteristics, usage
restrictions, or behavior.
 Concurrent implementations.
Implementations designed for highly concurrent
use.
 Wrapper implementations. Add functionality,
such as synchronization, to other
implementations.
 Convenience implementations. High-
performance "mini-implementations" of the
collection interfaces.
 Abstract implementations. Partial
implementations of the collection interfaces to
facilitate custom implementations.
 Algorithms. Static methods that perform useful
functions on collections, such as sorting a list.
 Infrastructure. Interfaces that provide essential
support for the collection interfaces.
 Array Utilities. Utility functions for arrays of
primitive types and reference objects. Not,
strictly speaking, a part of the collections
framework, this feature was added to the Java
platform at the same time as the collections
framework and relies on some of the same
infrastructure.

Collection Interfaces
The collection interfaces are divided into two
groups. The most basic
interface, java.util.Collection, has the following
descendants:

 java.util.Set
 java.util.SortedSet
 java.util.NavigableSet
 java.util.Queue
 java.util.concurrent.BlockingQueue
 java.util.concurrent.TransferQueue
 java.util.Deque
 java.util.concurrent.BlockingDeque

The other collection interfaces are based


on java.util.Map and are not true collections.
However, these interfaces contain collection-
view operations, which enable them to be
manipulated as collections. Map has the following
offspring:

 java.util.SortedMap
 java.util.NavigableMap
 java.util.concurrent.ConcurrentMap
 java.util.concurrent.ConcurrentNavigableMap

Many of the modification methods in the collection


interfaces are labeled optional. Implementations
are permitted to not perform one or more of these
operations, throwing a runtime exception
(UnsupportedOperationException) if they are
attempted. The documentation for each
implementation must specify which optional
operations are supported. Several terms are
introduced to aid in this specification:

 Collections that do not support modification


operations (such as add, remove and clear) are
referred to as unmodifiable. Collections that are
not unmodifiable are modifiable.
 Collections that additionally guarantee that no
change in the Collection object will be visible are
referred to as immutable. Collections that are not
immutable are mutable.
 Lists that guarantee that their size remains
constant even though the elements can change
are referred to as fixed-size. Lists that are not
fixed-size are referred to as variable-size.
 Lists that support fast (generally constant time)
indexed element access are known as random
access lists. Lists that do not support fast
indexed element access are known as sequential
access lists. The RandomAccess marker interface
enables lists to advertise the fact that they
support random access. This enables generic
algorithms to change their behavior to provide
good performance when applied to either
random or sequential access lists.

Some implementations restrict what elements (or


in the case of Maps, keys and values) can be
stored. Possible restrictions include requiring
elements to:

 Be of a particular type.
 Be not null.
 Obey some arbitrary predicate.

Attempting to add an element that violates an


implementation's restrictions results in a runtime
exception, typically a ClassCastException,
an IllegalArgumentException, or
a NullPointerException. Attempting to remove or
test for the presence of an element that violates an
implementation's restrictions can result in an
exception. Some restricted collections permit this
usage.

Collection Implementations
Classes that implement the collection interfaces
typically have names in the form of
<Implementation-style><Interface>. The general
purpose implementations are summarized in the
following table:

Hash
Balan
Interf Hash Resizab Linked Table +
ced
ace Table le Array List Linked
Tree
List
HashS TreeSe LinkedHash
Set
et t Set
LinkedL
List ArrayList
ist
ArrayDe LinkedL
Deque
que ist
HashM TreeM LinkedHash
Map
ap ap Map
The general-purpose implementations support all
of the optional operations in the collection
interfaces and have no restrictions on the elements
they may contain. They are unsynchronized, but
the Collections class contains static factories
called synchronization wrappers that can be used
to add synchronization to many unsynchronized
collections. All of the new implementations
have fail-fast iterators, which detect invalid
concurrent modification, and fail quickly and
cleanly (rather than behaving erratically).
The AbstractCollection, AbstractSet, AbstractList, A
bstractSequentialList and AbstractMap classes
provide basic implementations of the core
collection interfaces, to minimize the effort
required to implement them. The API
documentation for these classes describes
precisely how each method is implemented so the
implementer knows which methods must be
overridden, given the performance of the basic
operations of a specific implementation.

Concurrent Collections
Applications that use collections from more than
one thread must be carefully programmed. In
general, this is known as concurrent programming.
The Java platform includes extensive support for
concurrent programming. See Java Concurrency
Utilities for details.
Collections are so frequently used that various
concurrent friendly interfaces and implementations
of collections are included in the APIs. These types
go beyond the synchronization wrappers discussed
previously to provide features that are frequently
needed in concurrent programming.
These concurrent-aware interfaces are available:

 BlockingQueue
 TransferQueue
 BlockingDeque
 ConcurrentMap
 ConcurrentNavigableMap

The following concurrent-aware implementation


classes are available. See the API documentation
for the correct usage of these implementations.

 LinkedBlockingQueue
 ArrayBlockingQueue
 PriorityBlockingQueue
 DelayQueue
 SynchronousQueue
 LinkedBlockingDeque
 LinkedTransferQueue
 CopyOnWriteArrayList
 CopyOnWriteArraySet
 ConcurrentSkipListSet
 ConcurrentHashMap
 ConcurrentSkipListMap

Design Goals
The main design goal was to produce an API that
was small in size and, more importantly, in
"conceptual weight." It was critical that the new
functionality not seem too different to current Java
programmers; it had to augment current facilities,
rather than replace them. At the same time, the
new API had to be powerful enough to provide all
the advantages described previously.
To keep the number of core interfaces small, the
interfaces do not attempt to capture such subtle
distinctions as mutability, modifiability, and
resizability. Instead, certain calls in the core
interfaces are optional, enabling implementations
to throw an UnsupportedOperationException to
indicate that they do not support a specified
optional operation. Collection implementers must
clearly document which optional operations are
supported by an implementation.
To keep the number of methods in each core
interface small, an interface contains a method
only if either:

 It is a truly fundamental operation: a basic


operations in terms of which others could be
reasonably defined,
 There is a compelling performance reason why
an important implementation would want to
override it.

It was critical that all reasonable representations of


collections interoperate well. This included arrays,
which cannot be made to implement
the Collection interface directly without changing
the language. Thus, the framework includes
methods to enable collections to be moved into
arrays, arrays to be viewed as collections, and
maps to be viewed as collections.

Hierarchy of Collection Framework

Let us see the hierarchy of Collection framework.


The java.util package contains all
the classes and interfaces for the Collection
framework.
Methods of Collection interface

There are many methods declared in the Collection


interface. They are as follows:

N Method Descri
o ption
.
1 public boolean It is
add(E e) used to
insert
an
element
in this
collecti
on.
2 public boolean It is
addAll(Collectio used to
n<? extends E> insert
c) the
specifie
d
collecti
on
element
s in the
invokin
g
collecti
on.
3 public boolean It is
remove(Object used to
element) delete
an
element
from
the
collecti
on.
4 public boolean It is
removeAll(Colle used to
ction<?> c) delete
all the
element
s of the
specifie
d
collecti
on from
the
invokin
g
collecti
on.
5 default boolean It is
removeIf(Predic used to
ate<? super E> delete
filter) all the
element
s of the
collecti
on that
satisfy
the
specifie
d
predicat
e.
6 public boolean It is
retainAll(Collect used to
ion<?> c) delete
all the
element
s of
invokin
g
collecti
on
except
the
specifie
d
collecti
on.
7 public int size() It
returns
the
total
number
of
element
s in the
collecti
on.
8 public void It
clear() remove
s the
total
number
of
element
s from
the
collecti
on.
9 public boolean It is
contains(Object used to
element) search
an
element
.
1 public boolean It is
0 containsAll(Coll used to
ection<?> c) search
the
specifie
d
collecti
on in
the
collecti
on.
1 public Iterator It
1 iterator() returns
an
iterator.
1 public Object[] It
2 toArray() convert
s
collecti
on into
array.
1 public <T> T[] It
3 toArray(T[] a) convert
s
collecti
on into
array.
Here,
the
runtime
type of
the
returne
d array
is that
of the
specifie
d array.
1 public boolean It
4 isEmpty() checks
if
collecti
on is
empty.
1 default It
5 Stream<E> returns
parallelStream() a
possibly
parallel
Stream
with the
collecti
on as
its
source.
1 default It
6 Stream<E> returns
stream() a
sequent
ial
Stream
with the
collecti
on as
its
source.
1 default It
7 Spliterator<E> generat
spliterator() es a
Splitera
tor over
the
specifie
d
element
s in the
collecti
on.
1 public boolean It
8 equals(Object matche
element) s two
collecti
ons.
1 public int It
9 hashCode() returns
the
hash
code
number
of the
collecti
on.

Iterator interface

Iterator interface provides the facility of iterating


the elements in a forward direction only.

Methods of Iterator interface

There are only three methods in the Iterator


interface. They are:

N Method Description
o.
1 public It returns true
boolean if the iterator
hasNext( has more
) elements
otherwise it
returns false.
2 public It returns the
Object element and
next() moves the
cursor pointer
to the next
element.
3 public It removes
void the last
remove() elements
returned by
the iterator. It
is less used.

Iterable Interface

The Iterable interface is the root interface for all


the collection classes. The Collection interface
extends the Iterable interface and therefore all the
subclasses of Collection interface also implement
the Iterable interface.

It contains only one abstract method. i.e.,

1. Iterator<T> iterator()

It returns the iterator over the elements of type T.

Collection Interface
The Collection interface is the interface which is
implemented by all the classes in the collection
framework. It declares the methods that every
collection will have. In other words, we can say
that the Collection interface builds the foundation
on which the collection framework depends.

Some of the methods of Collection interface are


Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are
implemented by all the subclasses of Collection
interface.

List Interface

List interface is the child interface of Collection


interface. It inhibits a list type data structure in
which we can store the ordered collection of
objects. It can have duplicate values.

List interface is implemented by the classes


ArrayList, LinkedList, Vector, and Stack.

To instantiate the List interface, we must use :

1. List <data-type> list1= new ArrayList();


2. List <data-type> list2 = new LinkedList();
3. List <data-type> list3 = new Vector();
4. List <data-type> list4 = new Stack();

There are various methods in List interface that


can be used to insert, delete, and access the
elements from the list.

The classes that implement the List interface are


given below.
ArrayList

The ArrayList class implements the List interface. It


uses a dynamic array to store the duplicate
element of different data types. The ArrayList class
maintains the insertion order and is non-
synchronized. The elements stored in the ArrayList
class can be randomly accessed. Consider the
following example.

1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//
Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }

Output:

Ravi
Vijay
Ravi
Ajay

LinkedList
LinkedList implements the Collection interface. It
uses a doubly linked list internally to store the
elements. It can store the duplicate elements. It
maintains the insertion order and is not
synchronized. In LinkedList, the manipulation is
fast because no shifting is required.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ravi
Ajay

Vector

Vector uses a dynamic array to store the data


elements. It is similar to ArrayList. However, It is
synchronized and contains many methods that are
not the part of Collection framework.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ayush
Amit
Ashish
Garima

Stack

The stack is the subclass of Vector. It implements


the last-in-first-out data structure, i.e., Stack. The
stack contains all of the methods of Vector class
and also provides its methods like boolean push(),
boolean peek(), boolean push(object o), which
defines its properties.

Consider the following example.


1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ayush
Garvit
Amit
Ashish

Queue Interface

Queue interface maintains the first-in-first-out


order. It can be defined as an ordered list that is
used to hold the elements which are about to be
processed. There are various classes like
PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.

Queue interface can be instantiated as:


1. Queue<String> q1 = new PriorityQueue();
2. Queue<String> q2 = new ArrayDeque();

There are various classes that implement the


Queue interface, some of them are given below.

PriorityQueue

The PriorityQueue class implements the Queue


interface. It holds the elements or objects which
are to be processed by their priorities.
PriorityQueue doesn't allow null values to be stored
in the queue.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection5{
3. public static void main(String args[]){
4. PriorityQueue<String> queue=new PriorityQueue
<String>();
5. queue.add("Amit Sharma");
6. queue.add("Vijay Raj");
7. queue.add("JaiShankar");
8. queue.add("Raj");
9. System.out.println("head:"+queue.element());
10. System.out.println("head:"+queue.peek());
11. System.out.println("iterating the queue eleme
nts:");
12. Iterator itr=queue.iterator();
13. while(itr.hasNext()){
14. System.out.println(itr.next());
15. }
16. queue.remove();
17. queue.poll();
18. System.out.println("after removing two eleme
nts:");
19. Iterator<String> itr2=queue.iterator();
20. while(itr2.hasNext()){
21. System.out.println(itr2.next());
22. }
23. }
24. }

Output:

head:Amit Sharma
head:Amit Sharma
iterating the queue elements:
Amit Sharma
Raj
JaiShankar
Vijay Raj
after removing two elements:
Raj
Vijay Raj

Deque Interface

Deque interface extends the Queue interface. In


Deque, we can remove and add the elements from
both the side. Deque stands for a double-ended
queue which enables us to perform the operations
at both the ends.

Deque can be instantiated as:

1. Deque d = new ArrayDeque();

ArrayDeque
ArrayDeque class implements the Deque interface.
It facilitates us to use the Deque. Unlike queue, we
can add or delete the elements from both the
ends.

ArrayDeque is faster than ArrayList and Stack and


has no capacity restrictions.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection6{
3. public static void main(String[] args) {
4. //Creating Deque and adding elements
5. Deque<String> deque = new ArrayDeque<String
>();
6. deque.add("Gautam");
7. deque.add("Karan");
8. deque.add("Ajay");
9. //Traversing elements
10. for (String str : deque) {
11. System.out.println(str);
12. }
13. }
14. }

Output:

Gautam
Karan
Ajay

Set Interface

Set Interface in Java is present in java.util package.


It extends the Collection interface. It represents
the unordered set of elements which doesn't allow
us to store the duplicate items. We can store at
most one null value in Set. Set is implemented by
HashSet, LinkedHashSet, and TreeSet.

Set can be instantiated as:

1. Set<data-type> s1 = new HashSet<data-type>();


2. Set<data-type> s2 = new LinkedHashSet<data-
type>();
3. Set<data-type> s3 = new TreeSet<data-type>();

HashSet

HashSet class implements Set Interface. It


represents the collection that uses a hash table for
storage. Hashing is used to store the elements in
the HashSet. It contains unique items.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:

Vijay
Ravi
Ajay

LinkedHashSet

LinkedHashSet class represents the LinkedList


implementation of Set Interface. It extends the
HashSet class and implements Set interface. Like
HashSet, It also contains unique elements. It
maintains the insertion order and permits null
elements.

Consider the following example.

1. import java.util.*;
2. public class TestJavaCollection8{
3. public static void main(String args[]){
4. LinkedHashSet<String> set=new LinkedHashSet<
String>();
5. set.add("Ravi");
6. set.add("Vijay");
7. set.add("Ravi");
8. set.add("Ajay");
9. Iterator<String> itr=set.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }

Output:

Ravi
Vijay
Ajay

SortedSet Interface

SortedSet is the alternate of Set interface that


provides a total ordering on its elements. The
elements of the SortedSet are arranged in the
increasing (ascending) order. The SortedSet
provides the additional methods that inhibit the
natural ordering of the elements.

The SortedSet can be instantiated as:

1. SortedSet<data-type> set = new TreeSet();

TreeSet

Java TreeSet class implements the Set interface


that uses a tree for storage. Like HashSet, TreeSet
also contains unique elements. However, the
access and retrieval time of TreeSet is quite fast.
The elements in TreeSet stored in ascending order.

Consider the following example:

1. import java.util.*;
2. public class TestJavaCollection9{
3. public static void main(String args[]){
4. //Creating and adding elements
5. TreeSet<String> set=new TreeSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }

Output:

Ajay
Ravi
Vijay

ARRAY LIST IN JAVA

Let’s create an ArrayList object named elements


which stores string elements:

import java.util.ArrayList; // Importing the


ArrayList class from the java.util package

// Creating an ArrayList to store String elements


ArrayList<String> elements = new
ArrayList<String>();
Java ArrayList is a part of the Java collections
framework and it is a class of java.util package. It
provides us with dynamic arrays in Java.

Though, it may be slower than standard arrays but


can be helpful in programs where lots of
manipulation in the array is needed. This class is
found in java.util package.
The main advantage of ArrayList in Java is, that if
we declare an array then we need to mention the
size, but in ArrayList, it is not needed to mention
the size of ArrayList.

If you want to mention the size then you can do it.

What is ArrayList in Java?

ArrayList is a Java class implemented using the List


interface. Java ArrayList, as the name suggests,
provides the functionality of a dynamic array
where the size is not fixed as an array. Also, as a
part of the Collections framework, it has many
features not available with arrays.

Illustration:

Let us check on the ArrayList with the Integer


Object type Stored in it with a image.
Java ArrayList Example
Example 1: The following implementation
demonstrates how to create and use an ArrayList
with a mention of its size.

// Java program to demonstrate the


// working of ArrayList
import java.io.*;
import java.util.*;

class ArrayListExample {
public static void main(String[] args)
{
// Size of the
// ArrayList
int n = 5;

// Declaring the ArrayList with


// initial size n
ArrayList<Integer> arr1 = new
ArrayList<Integer>(n);
// Declaring the ArrayList
ArrayList<Integer> arr2 = new
ArrayList<Integer>();

// Printing the ArrayList


System.out.println("Array 1:" + arr1);
System.out.println("Array 2:" + arr2);

// Appending new elements at


// the end of the list
for (int i = 1; i <= n; i++) {
arr1.add(i);
arr2.add(i);
}

// Printing the ArrayList


System.out.println("Array 1:" + arr1);
System.out.println("Array 2:" + arr2);
}
}

Output
Array 1:[]
Array 2:[]
Array 1:[1, 2, 3, 4, 5]
Array 2:[1, 2, 3, 4, 5]
Explanation of the above Program:
ArrayList is a dynamic array and we do not have to
specify the size while creating it, the size of the
array automatically increases when we
dynamically add and remove items. Though the
actual library implementation may be more
complex, the following is a very basic idea
explaining the working of the array when the array
becomes full and if we try to add an item:
 Creates a bigger-sized memory on heap memory
(for example memory of double size).
 Copies the current memory elements to the new
memory.
 The new item is added now as there is bigger
memory available now.
 Delete the old memory.

Important Features of ArrayList in Java

 ArrayList inherits AbstractList class and


implements the List interface.
 ArrayList is initialized by size. However, the size
is increased automatically if the collection grows
or shrinks if the objects are removed from the
collection.
 Java ArrayList allows us to randomly access the
list.
 ArrayList can not be used for primitive types,
like int, char, etc. We need a wrapper class for
such cases.
 ArrayList in Java can be seen as a vector in C++.
 ArrayList is not Synchronized. Its equivalent
synchronized class in Java is Vector.

Let’s understand the Java ArrayList in depth. Look


at the below image:
In the above illustration, AbstractList,
CopyOnWriteArrayList, and AbstractSequentialList
are the classes that implement the list interface. A
separate functionality is implemented in each of
the mentioned classes. They are:

 AbstractList: This class is used to implement an


unmodifiable list, for which one needs to only
extend this AbstractList Class and implement
only the get() and the size() methods.
 CopyOnWriteArrayList: This class implements
the list interface. It is an enhanced version of
ArrayList in which all the modifications(add, set,
remove, etc.) are implemented by making a
fresh copy of the list.
 AbstractSequentialList: This class implements
the Collection interface and the
AbstractCollection class. This class is used to
implement an unmodifiable list, for which one
needs to only extend this AbstractList Class and
implement only the get() and the size()
methods.
Constructors in ArrayList in Java

In order to Create an ArrayList, we need to create


an object of the ArrayList class. The ArrayList class
consists of various constructors which allow the
possible creation of the array list. The following are
the constructors available in this class:

1. ArrayList()
This constructor is used to build an empty array
list. If we wish to create an empty ArrayList with
the name arr, then, it can be created as:

ArrayList arr = new ArrayList();


2. ArrayList(Collection c)
This constructor is used to build an array list
initialized with the elements from the collection c.
Suppose, we wish to create an ArrayList arr which
contains the elements present in the collection c,
then, it can be created as:

ArrayList arr = new ArrayList(c);

3. ArrayList(int capacity)
This constructor is used to build an array list with
the initial capacity being specified. Suppose we
wish to create an ArrayList with the initial size
being N, then, it can be created as:

ArrayList arr = new ArrayList(N);


Java ArrayList Methods
Method Description

This method is used to insert


add(int index, a specific element at a
Object element) specific position index in a
list.

This method is used to


add(Object o) append a specific element to
the end of a list.

This method is used to


append all the elements from
a specific collection to the
addAll(Collectio
end of the mentioned list, in
n C)
such an order that the values
are returned by the specified
collection’s iterator.

Used to insert all of the


elements starting at the
addAll(int index,
specified position from a
Collection C)
specific collection into the
mentioned list.

This method is used to


clear() remove all the elements from
any list.

This method is used to return


clone() a shallow copy of an ArrayList
in Java.

Returns true if this list


contains?
contains the specified
(Object o)
element.
Method Description

Increases the capacity of this


ArrayList instance, if
ensureCapacity
necessary, to ensure that it
?(int
can hold at least the number
minCapacity)
of elements specified by the
minimum capacity argument.

Performs the given action for


forEach?
each element of the Iterable
(Consumer<?
until all elements have been
super E>
processed or the action
action)
throws an exception.

Returns the element at the


get?(int index)
specified position in this list.

The index the first


occurrence of a specific
indexOf(Object
element is either returned or
O)
-1 in case the element is not
in the list.

Returns true if this list


isEmpty?()
contains no elements.

The index of the last


occurrence of a specific
lastIndexOf(Obj
element is either returned or
ect O)
-1 in case the element is not
in the list.

Returns a list iterator over


listIterator?() the elements in this list (in
proper sequence).
Method Description

Returns a list iterator over


the elements in this list (in
listIterator?(int
proper sequence), starting at
index)
the specified position in the
list.

remove?(int Removes the element at the


index) specified position in this list.

Removes the first occurrence


remove?
of the specified element from
(Object o)
this list, if it is present.

Removes from this list all of


removeAll? its elements that are
(Collection c) contained in the specified
collection.

Removes all of the elements


removeIf?
of this collection that satisfy
(Predicate filter)
the given predicate.

Removes from this list all of


removeRange? the elements whose index is
(int fromIndex, between fromIndex,
int toIndex) inclusive, and toIndex,
exclusive.

retainAll? Retains only the elements in


(Collection<?> this list that are contained in
c) the specified collection.

Replaces the element at the


set?(int index, E
specified position in this list
element)
with the specified element.
Method Description

Returns the number of


size?()
elements in this list.

Creates a late-binding and


spliterator?() fail-fast Spliterator over the
elements in this list.

Returns a view of the portion


subList?(int of this list between the
fromIndex, int specified fromIndex,
toIndex) inclusive, and toIndex,
exclusive.

This method is used to return


an array containing all of the
toArray()
elements in the list in the
correct order.

It is also used to return an


array containing all of the
toArray(Object[]
elements in this list in the
O)
correct order same as the
previous method.

This method is used to trim


the capacity of the instance
trimToSize()
of the ArrayList to the list’s
current size.

Note: You can also create a generic ArrayList:

// Creating generic integer ArrayList


ArrayList<Integer> arrli = new
ArrayList<Integer>();
Some Key Points of ArrayList in Java
ArrayList is Underlined data Structure Resizable
Array or Growable Array.
ArrayList Duplicates Are Allowed.
Insertion Order is Preserved.
Heterogeneous objects are allowed.
Null insertion is possible.
Let’s see how to perform some basic operations on
the ArrayList as listed which we are going to
discuss further alongside implementing every
operation.

Adding element to List/ Add element


Changing elements/ Set element
Removing elements/Delete element
Iterating elements
get elements
add elements in between two number
Sorting elements
ArrayList size
Operations performed in ArrayList
1. Adding Elements
In order to add an element to an ArrayList, we can
use the add() method. This method is overloaded
to perform multiple operations based on different
parameters. They are as follows:

add(Object): This method is used to add an


element at the end of the ArrayList.
add(int index, Object): This method is used to add
an element at a specific index in the ArrayList.
Below is the implementation of the above
approach:

// Java Program to Add elements to An ArrayList


// Importing all utility classes
import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Array of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to ArrayList


// Custom inputs
al.add("Geeks");
al.add("Geeks");

// Here we are mentioning the index


// at which it is to be added
al.add(1, "For");

// Printing all the elements in an ArrayList


System.out.println(al);
}
}

Output
[Geeks, For, Geeks]
2. Changing Elements
After adding the elements, if we wish to change
the element, it can be done using the set()
method. Since an ArrayList is indexed, the element
which we wish to change is referenced by the
index of the element. Therefore, this method takes
an index and the updated element which needs to
be inserted at that index.
Below is the implementation of the above
approach:

// Java Program to Change elements in ArrayList

// Importing all utility classes


import java.util.*;

// main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Arraylist object of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to Arraylist


// Custom input elements
al.add("Geeks");
al.add("Geeks");

// Adding specifying the index to be added


al.add(1, "Geeks");

// Printing the Arraylist elements


System.out.println("Initial ArrayList " + al);

// Setting element at 1st index


al.set(1, "For");

// Printing the updated Arraylist


System.out.println("Updated ArrayList " + al);
}
}
Output
Initial ArrayList [Geeks, Geeks, Geeks]
Updated ArrayList [Geeks, For, Geeks]
3. Removing Elements
In order to remove an element from an ArrayList,
we can use the remove() method. This method is
overloaded to perform multiple operations based
on different parameters. They are as follows:

remove(Object): This method is used to simply


remove an object from the ArrayList. If there are
multiple such objects, then the first occurrence of
the object is removed.
remove(int index): Since an ArrayList is indexed,
this method takes an integer value which simply
removes the element present at that specific index
in the ArrayList. After removing the element, all
the elements are moved to the left to fill the space
and the indices of the objects are updated.
Example:

// Java program to Remove Elements in ArrayList

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an object of arraylist class
ArrayList<String> al = new ArrayList<>();
// Adding elements to ArrayList
// Custom addition
al.add("Geeks");
al.add("Geeks");
// Adding element at specific index
al.add(1, "For");

// Printing all elements of ArrayList


System.out.println("Initial ArrayList " + al);

// Removing element from above ArrayList


al.remove(1);

// Printing the updated Arraylist elements


System.out.println("After the Index Removal "
+ al);

// Removing this word element in ArrayList


al.remove("Geeks");

// Now printing updated ArrayList


System.out.println("After the Object Removal
"
+ al);
}
}

Output
Initial ArrayList [Geeks, For, Geeks]
After the Index Removal [Geeks, Geeks]
After the Object Removal [Geeks]
4. Iterating the ArrayList
There are multiple ways to iterate through the
ArrayList. The most famous ways are by using the
basic for loop in combination with a get() method
to get the element at a specific index and the
advanced for a loop.
Example

// Java program to Iterate the elements


// in an ArrayList

// Importing all utility classes


import java.util.*;

// Main class
class GFG {

// Main driver method


public static void main(String args[])
{
// Creating an Arraylist of string type
ArrayList<String> al = new ArrayList<>();

// Adding elements to ArrayList


// using standard add() method
al.add("Geeks");
al.add("Geeks");
al.add(1, "For");

// Using the Get method and the


// for loop
for (int i = 0; i < al.size(); i++) {

System.out.print(al.get(i) + " ");


}

System.out.println();

// Using the for each loop


for (String str : al)
System.out.print(str + " ");
}
}

Output
Geeks For Geeks
Geeks For Geeks
5. Get Elements

// Java program to get the elemens in ArrayList


import java.io.*;
import java.util.*;

class GFG {
public static void main (String[] args) {
ArrayList<Integer> list = new ArrayList();
// add the number
list.add(9);
list.add(5);
list.add(6);
System.out.println(list);
// get method
Integer n= list.get(1);
System.out.println("at indext 1 number is:"+n);
}
}

Output
[9, 5, 6]
at indext 1 number is:5
6. Add Elements Between Two Numbers

// Java program to add the elements


// between two numbers in ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
list.add(4);
System.out.println(list);
// insert missing element 3
list.add(2, 3);
System.out.println(list);
}
}

Output
[1, 2, 4]
[1, 2, 3, 4]
7. ArrayList Sort

// Java Program for ArrayList Sorting


import java.io.*;
import java.util.*;

class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();
list.add(2);
list.add(4);
list.add(3);
list.add(1);
System.out.println("Before sorting list:");
System.out.println(list);
Collections.sort(list);
System.out.println("after sorting list:");
System.out.println(list);
}
}
Output
Before sorting list:
[2, 4, 3, 1]
after sorting list:
[1, 2, 3, 4]
8. Size of Elements

// Java program to find the size


// of elements of an ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<Integer> list = new ArrayList();

list.add(1);
list.add(2);
list.add(3);
list.add(4);
int b = list.size();
System.out.println("The size is :" + b);
}
}

Output
The size is :4
Complexity of Java ArrayList

Operation Time Space


Complexit Complexit
y y

Inserting
Element in O(1) O(N)
ArrayList
Operation Time Space
Complexit Complexit
y y

Removing
Element from O(N) O(1)
ArrayList

Traversing
Elements in O(N) O(N)
ArrayList

Replacing
Elements in O(1) O(1)
ArrayList

ArrayList in Java is a class in the Java Collections


framework that implements the List interface. Here
are the advantages and disadvantages of using
ArrayList in Java.

Advantages of Java ArrayList

1. Dynamic size: ArrayList can dynamically grow


and shrink in size, making it easy to add or
remove elements as needed.
2. Easy to use: ArrayList is simple to use, making it
a popular choice for many Java developers.
3. Fast access: ArrayList provides fast access to
elements, as it is implemented as an array
under the hood.
4. Ordered collection: ArrayList preserves the order
of elements, allowing you to access elements in
the order they were added.
5. Supports null values: ArrayList can store null
values, making it useful in cases where the
absence of a value needs to be represented.

Disadvantages of Java ArrayList

1. Slower than arrays: ArrayList is slower than


arrays for certain operations, such as inserting
elements in the middle of the list.
2. Increased memory usage: ArrayList requires
more memory than arrays, as it needs to
maintain its dynamic size and handle resizing.
3. Not thread-safe: ArrayList is not thread-safe,
meaning that multiple threads may access and
modify the list concurrently, leading to potential
race conditions and data corruption.
4. Performance degradation: ArrayList’s
performance may degrade as the number of
elements in the list increases, especially for
operations such as searching for elements or
inserting elements in the middle of the list.

Conclusion

Points to be remembered from this article are


mentioned below:

 ArrayList is the part of Collections framework. It


inherits the AbstractList class and implements
the List interface.
 ArrayList is the implementation of a dynamic
array.
 ArrayList can be initialized used using different
constructor types like without parameters,
passing collection as a parameter, and passing
integer as a parameter.
 Operations can be performed in ArrayList as
follows Adding, removing, iterating, and sorting.

Q) What is an ArrayList in Java?

A) ArrayList in Java is a part of the Collections


framework. It is used to store elements and the
size is resizable.

Q) How is data stored in ArrayList?

A) ArrayList can stores data till the ArrayList size is


full, after that the size of ArrayList is doubled if we
want to store any more elements.

Q) Does ArrayList allow duplicates?

A) Yes, ArrayList allows duplicate values to be


stored.

DATE AND TIME IN JAVA

Java is a most powerful programming language, by


which we can do many things and Java is an
industry preferable language. So it has a huge field
of features. Here we discuss one of the best
features of Java, that is how to represent the
current date and time using Java.

There are many ways to do this, there are many


classes by which it can be possible to display the
current Date and Time.

Method 1: Using Date class


There is a class called Date class which can
represent the current date and time in GMT form.
We can get the IST form by adding 5 hours and 30
minutes to the GMT form. This class comes under
the util package of Java.

Implementation:

// Java Program to Display Current Date and Time


import java.util.*;

public class GFG {


public static void main(String args[])
{
Date current_Date = new Date();
//"Date" class
//"current_Date" is Date object

System.out.println(current_Date);
// print the time and date
}
}
Output
Fri Nov 20 07:12:42 UTC 2020
Conversion of GMT form to IST using two classes
called TimeZone, it also comes under util package
of Java, and SimpleDateFormat, which comes
under Text package of Java.

Implementation:

// Java Program to Display Current Date and Time


import java.text.*;
import java.util.*;
public class GFG {
public static void main(String args[])
{
SimpleDateFormat formatDate = new
SimpleDateFormat(
"dd/MM/yyyy HH:mm:ss z");
//"SimpleDateFormat" class initialize with
object
//"formatDate" this class acceptes the format
of
// date and time as ""dd/MM/yyyy" and
"HH:mm:ss z""
//"z" use for print the time zone

Date date = new Date();


// initialize "Date" class

formatDate.setTimeZone(TimeZone.getTimeZ
one("IST"));
// converting to IST or format the Date as IST

System.out.println(formatDate.format(date));
// print formatted date and time
}
}
Output
20/11/2020 12:42:41 IST
Method 2: Using LocalDateTime class

There is a class called LocalDateTime class which


can also represent the current date and time in
GMT form. We can get the IST form by adding 5
hours and 30 minutes to the GMT form. This class
comes under the Time package of Java.

Implementation:

// Java Program to Display Current Date and Time


import java.time.*;
public class MyClass {
public static void main(String args[])
{
System.out.println(LocalDateTime.now());
//"LocalDateTime" is the class
//"now()" is a method, represent the
// current date and time
}
}
Output
2020-11-20T07:12:43.158549
We can convert this GMT form to IST using a class
called ZonedDateTime, it also comes under Time
package of Java. This class accepts a time by
specifying a time zone and convert it to a specific
time zone. Here we convert the time to
Asia/Kolkata form.

Implementation:

// Java Program to Display Current Date and Time


import java.util.*;
import java.time.*;
public class GFG {
public static void main(String[] args)
{
Date date = new Date();

LocalDateTime d = LocalDateTime.now();

ZonedDateTime UTCtime =
d.atZone(ZoneId.of("UTC"));
//"d" is the current date and
//"ZonedDateTime" accepts "d" as UTC
//"atZone" specifies the time zone

// converting to IST
ZonedDateTime ISTtime =
UTCtime.withZoneSameInstant(
ZoneId.of("Asia/Kolkata"));
//"withZoneSameInstant" convert the time
// to given time zone

System.out.println(ISTtime);
// print the time and date
}
}
Output
2020-11-20T12:42:42.723246+05:30[Asia/Kolkata]
Method 3: Using Clock class

There is a class called Clock class which can also


represent the current date and time in UTC form.
This class comes under the Time package of Java.

Implementation:

/*package whatever //do not write package name


here */

import java.time.*;

class GFG {
public static void main (String[] args)
{
System.out.println(Clock.systemUTC().instant(
));
//"Clock" is the class
//"systemUTC()" is the method which
represent the time in UTC form
}
}
Output
2020-11-20T07:12:37.598048Z

DATE CLASS IN JAVA


The class Date represents a specific instant in
time, with millisecond precision. The Date class of
java.util package implements Serializable,
Cloneable and Comparable interface. It provides
constructors and methods to deal with date and
time with java.

Constructors

Date() : Creates date object representing current


date and time.
Date(long milliseconds) : Creates a date object for
the given milliseconds since January 1, 1970,
00:00:00 GMT.
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Date(int year, int month, int date, int hrs, int min,
int sec)
Date(String s)
Note : The last 4 constructors of the Date class are
Deprecated.

// Java program to demonstrate constuctors of Date


import java.util.*;

public class Main


{
public static void main(String[] args)
{
Date d1 = new Date();
System.out.println("Current date is " + d1);
Date d2 = new Date(2323223232L);
System.out.println("Date represented is "+ d2
);
}
}
Output:
Current date is Tue Jul 12 18:35:37 IST 2016
Date represented is Wed Jan 28 02:50:23 IST 1970
Important Methods

boolean after(Date date) : Tests if current date is


after the given date.
boolean before(Date date) : Tests if current date is
before the given date.
int compareTo(Date date) : Compares current date
with given date. Returns 0 if the argument Date is
equal to the Date; a value less than 0 if the Date is
before the Date argument; and a value greater
than 0 if the Date is after the Date argument.
long getTime() : Returns the number of
milliseconds since January 1, 1970, 00:00:00 GMT
represented by this Date object.
void setTime(long time) : Changes the current date
and time to given time.
// Program to demonstrate methods of Date class
import java.util.*;

public class Main


{
public static void main(String[] args)
{
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);

boolean a = d3.after(d1);
System.out.println("Date d3 comes after " +
"date d2: " + a);

boolean b = d3.before(d2);
System.out.println("Date d3 comes before "+
"date d2: " + b);
int c = d1.compareTo(d2);
System.out.println(c);

System.out.println("Miliseconds from Jan 1 "+


"1970 to date d1 is " + d1.getTime());

System.out.println("Before setting "+d2);


d2.setTime(204587433443L);
System.out.println("After setting "+d2);
}
}
Output:

Date d3 comes after date d2: true


Date d3 comes before date d2: false
1
Miliseconds from Jan 1 1970 to date d1 is
60935500800000
Before setting Tue Jul 12 13:13:16 UTC 2016
After setting Fri Jun 25 21:50:33 UTC 1976

CALENDAR CLASS IN JAVA

Calendar class in Java is an abstract class that


provides methods for converting date between a
specific instant in time and a set of calendar fields
such as MONTH, YEAR, HOUR, etc. It inherits Object
class and implements the Comparable,
Serializable, Cloneable interfaces.

As it is an Abstract class, so we cannot use a


constructor to create an instance. Instead, we will
have to use the static method
Calendar.getInstance() to instantiate and
implement a sub-class.
Calendar.getInstance(): return a Calendar instance
based on the current time in the default time zone
with the default locale.
Calendar.getInstance(TimeZone zone)
Calendar.getInstance(Locale aLocale)
Calendar.getInstance(TimeZone zone, Locale
aLocale)
Java program to demonstrate getInstance()
method:

Output:

The Current Date is:Tue Aug 28 11:10:40 UTC 2018


Important Methods and their usage

METHOD DESCRIPTION

It is used to add or subtract


abstract void
the specified amount of time
add(int field, int
to the given calendar field,
amount)
based on the calendar’s rules.

It is used to return the value


int get(int field)
of the given calendar field.

It is used to return the


abstract int
maximum value for the given
getMaximum(int
calendar field of this Calendar
field)
instance.

It is used to return the


abstract int
minimum value for the given
getMinimum(int
calendar field of this Calendar
field)
instance.

Date getTime() It is used to return a Date


METHOD DESCRIPTION

object representing this


Calendar’s time value.</td

Below programs illustrate the above methods:

Program 1: Java program to demonstrate get()


method.

Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
Program 2: Java program to demonstrate
getMaximum() method.

Output:
Maximum number of days in a week: 7
Maximum number of weeks in a year: 53
Program 3: Java program to demonstrate the
getMinimum() method.

Output:
Minimum number of days in week: 1
Minimum number of weeks in year: 1
Program 4: Java program to demonstrate add()
method.

Output:

15 days ago: Mon Aug 13 11:10:57 UTC 2018


4 months later: Thu Dec 13 11:10:57 UTC 2018
2 years later: Sun Dec 13 11:10:57 UTC 2020
GREGORIAN CLASS IN JAVA

compact1, compact2, compact3


java.util
Class GregorianCalendar

 java.lang.Object

 java.util.Calendar

 java.util.GregorianCalendar

All Implemented Interfaces:

Serializable, Cloneable, Comparable<Calendar>

public class GregorianCalendar


extends Calendar

GregorianCalendar is a concrete subclass


of Calendar and provides the standard calendar
system used by most of the world.

GregorianCalendar is a hybrid calendar that


supports both the Julian and Gregorian calendar
systems with the support of a single discontinuity,
which corresponds by default to the Gregorian
date when the Gregorian calendar was instituted
(October 15, 1582 in some countries, later in
others). The cutover date may be changed by the
caller by calling setGregorianChange().

Historically, in those countries which adopted the


Gregorian calendar first, October 4, 1582 (Julian)
was thus followed by October 15, 1582
(Gregorian). This calendar models this correctly.
Before the Gregorian
cutover, GregorianCalendar implements the Julian
calendar. The only difference between the
Gregorian and the Julian calendar is the leap year
rule. The Julian calendar specifies leap years every
four years, whereas the Gregorian calendar omits
century years which are not divisible by 400.

GregorianCalendar implements proleptic Gregoria


n and Julian calendars. That is, dates are
computed by extrapolating the current rules
indefinitely far backward and forward in time. As a
result, GregorianCalendar may be used for all
years to generate meaningful and consistent
results. However, dates obtained
using GregorianCalendar are historically accurate
only from March 1, 4 AD onward, when modern
Julian calendar rules were adopted. Before this
date, leap year rules were applied irregularly, and
before 45 BC the Julian calendar did not even
exist.


Prior to the institution of the Gregorian calendar,
New Year's Day was March 25. To avoid confusion,
this calendar always uses January 1. A manual
adjustment may be made if desired for dates that
are prior to the Gregorian changeover and which
fall between January 1 and March 24.

Week Of Year and Week Year

Values calculated for the WEEK_OF_YEAR field


range from 1 to 53. The first week of a calendar
year is the earliest seven day period starting
on getFirstDayOfWeek() that contains at
least getMinimalDaysInFirstWeek() days from that
year. It thus depends on the values
of getMinimalDaysInFirstWeek(), getFirstDayOfWe
ek(), and the day of the week of January 1. Weeks
between week 1 of one year and week 1 of the
following year (exclusive) are numbered
sequentially from 2 to 52 or 53 (except for year(s)
involved in the Julian-Gregorian transition).

The getFirstDayOfWeek() and getMinimalDaysInFir


stWeek() values are initialized using locale-
dependent resources when constructing
a GregorianCalendar. The week determination is
compatible with the ISO 8601 standard
when getFirstDayOfWeek() is MONDAY and getMin
imalDaysInFirstWeek() is 4, which values are used
in locales where the standard is preferred. These
values can explicitly be set by
calling setFirstDayOfWeek() and setMinimalDaysIn
FirstWeek().

A week year is in sync with


a WEEK_OF_YEAR cycle. All weeks between the
first and last weeks (inclusive) have the
same week year value. Therefore, the first and
last days of a week year may have different
calendar year values.

For example, January 1, 1998 is a Thursday.


If getFirstDayOfWeek() is MONDAY and getMinimal
DaysInFirstWeek() is 4 (ISO 8601 standard
compatible setting), then week 1 of 1998 starts on
December 29, 1997, and ends on January 4, 1998.
The week year is 1998 for the last three days of
calendar year 1997. If,
however, getFirstDayOfWeek() is SUNDAY, then
week 1 of 1998 starts on January 4, 1998, and
ends on January 10, 1998; the first three days of
1998 then are part of week 53 of 1997 and their
week year is 1997.

Week Of Month

Values calculated for the WEEK_OF_MONTH field


range from 0 to 6. Week 1 of a month (the days
with WEEK_OF_MONTH = 1) is the earliest set of at
least getMinimalDaysInFirstWeek() contiguous
days in that month, ending on the day
before getFirstDayOfWeek(). Unlike week 1 of a
year, week 1 of a month may be shorter than 7
days, need not start on getFirstDayOfWeek(), and
will not include days of the previous month. Days
of a month before week 1 have
a WEEK_OF_MONTH of 0.

For example,
if getFirstDayOfWeek() is SUNDAY and getMinimal
DaysInFirstWeek() is 4, then the first week of
January 1998 is Sunday, January 4 through
Saturday, January 10. These days have
a WEEK_OF_MONTH of 1. Thursday, January 1
through Saturday, January 3 have
a WEEK_OF_MONTH of 0.
If getMinimalDaysInFirstWeek() is changed to 3,
then January 1 through January 3 have
a WEEK_OF_MONTH of 1.

Default Fields Values

The clear method sets calendar field(s)


undefined. GregorianCalendar uses the following
default value for each calendar field if its value is
undefined.

Field Default
Value
ERA AD
YEAR 1970
MONTH JANUARY
DAY_OF_MONTH 1
the first
DAY_OF_WEEK day of
week
WEEK_OF_MONTH 0
DAY_OF_WEEK_IN_MONT 1
H
AM_PM AM
HOUR, HOUR_OF_DAY,
MINUTE, SECOND, 0
MILLISECOND

Default values are not applicable for the fields not


listed above.

Example:

// get the supported ids for GMT-08:00


(Pacific Standard Time)
String[] ids =
TimeZone.getAvailableIDs(-8 * 60 * 60 *
1000);
// if no ids were returned, something is
wrong. get out.
if (ids.length == 0)
System.exit(0);

// begin output
System.out.println("Current Time");

// create a Pacific Standard Time time


zone
SimpleTimeZone pdt = new
SimpleTimeZone(-8 * 60 * 60 * 1000,
ids[0]);
// set up rules for Daylight Saving Time
pdt.setStartRule(Calendar.APRIL, 1,
Calendar.SUNDAY, 2 * 60 * 60 * 1000);
pdt.setEndRule(Calendar.OCTOBER, -1,
Calendar.SUNDAY, 2 * 60 * 60 * 1000);

// create a GregorianCalendar with the


Pacific Daylight time zone
// and the current date and time
Calendar calendar = new
GregorianCalendar(pdt);
Date trialTime = new Date();
calendar.setTime(trialTime);

// print out a bunch of interesting things


System.out.println("ERA: " +
calendar.get(Calendar.ERA));
System.out.println("YEAR: " +
calendar.get(Calendar.YEAR));
System.out.println("MONTH: " +
calendar.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " +
calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH: "
+
calendar.get(Calendar.WEEK_OF_MONTH)
);
System.out.println("DATE: " +
calendar.get(Calendar.DATE));
System.out.println("DAY_OF_MONTH: " +
calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " +
calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " +
calendar.get(Calendar.DAY_OF_WEEK));
System.out.println("DAY_OF_WEEK_IN_M
ONTH: "
+
calendar.get(Calendar.DAY_OF_WEEK_IN_
MONTH));
System.out.println("AM_PM: " +
calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " +
calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " +
calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " +
calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " +
calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " +
calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+
(calendar.get(Calendar.ZONE_OFFSET)/(6
0*60*1000)));
System.out.println("DST_OFFSET: "
+
(calendar.get(Calendar.DST_OFFSET)/(60
*60*1000)));

System.out.println("Current Time, with


hour reset to 3");
calendar.clear(Calendar.HOUR_OF_DAY);
// so doesn't override
calendar.set(Calendar.HOUR, 3);
System.out.println("ERA: " +
calendar.get(Calendar.ERA));
System.out.println("YEAR: " +
calendar.get(Calendar.YEAR));
System.out.println("MONTH: " +
calendar.get(Calendar.MONTH));
System.out.println("WEEK_OF_YEAR: " +
calendar.get(Calendar.WEEK_OF_YEAR));
System.out.println("WEEK_OF_MONTH: "
+
calendar.get(Calendar.WEEK_OF_MONTH)
);
System.out.println("DATE: " +
calendar.get(Calendar.DATE));
System.out.println("DAY_OF_MONTH: " +
calendar.get(Calendar.DAY_OF_MONTH));
System.out.println("DAY_OF_YEAR: " +
calendar.get(Calendar.DAY_OF_YEAR));
System.out.println("DAY_OF_WEEK: " +
calendar.get(Calendar.DAY_OF_WEEK));

System.out.println("DAY_OF_WEEK_IN_M
ONTH: "
+
calendar.get(Calendar.DAY_OF_WEEK_IN_
MONTH));
System.out.println("AM_PM: " +
calendar.get(Calendar.AM_PM));
System.out.println("HOUR: " +
calendar.get(Calendar.HOUR));
System.out.println("HOUR_OF_DAY: " +
calendar.get(Calendar.HOUR_OF_DAY));
System.out.println("MINUTE: " +
calendar.get(Calendar.MINUTE));
System.out.println("SECOND: " +
calendar.get(Calendar.SECOND));
System.out.println("MILLISECOND: " +
calendar.get(Calendar.MILLISECOND));
System.out.println("ZONE_OFFSET: "
+
(calendar.get(Calendar.ZONE_OFFSET)/(6
0*60*1000))); // in hours
System.out.println("DST_OFFSET: "
+
(calendar.get(Calendar.DST_OFFSET)/(60
*60*1000))); // in hours

Since:

JDK1.1

See Also:

TimeZone, Serialized Form

Nested Class Summary

Nested classes/interfaces inherited from


class java.util.Calendar

 Calendar.Builder
Field Summary


Fields
Modifier Field and Description
and Type
static int AD
Value of the ERA field indicating the
common era (Anno Domini), also
known as CE.
static int BC
Value of the ERA field indicating the
period before the common era
(before Christ), also known as BCE.

Fields inherited from class java.util.Calendar

 ALL_STYLES, AM, AM_PM, APRIL, areFieldsSet, AUG


UST, DATE, DAY_OF_MONTH, DAY_OF_WEEK, DAY_
OF_WEEK_IN_MONTH, DAY_OF_YEAR, DECEMBER, D
ST_OFFSET, ERA, FEBRUARY, FIELD_COUNT, fields,
FRIDAY, HOUR, HOUR_OF_DAY, isSet, isTimeSet, JA
NUARY, JULY, JUNE, LONG, LONG_FORMAT, LONG_S
TANDALONE, MARCH, MAY, MILLISECOND, MINUTE,
MONDAY, MONTH, NARROW_FORMAT, NARROW_ST
ANDALONE, NOVEMBER, OCTOBER, PM, SATURDAY
, SECOND, SEPTEMBER, SHORT, SHORT_FORMAT, S
HORT_STANDALONE, SUNDAY, THURSDAY, time, T
UESDAY, UNDECIMBER, WEDNESDAY, WEEK_OF_M
ONTH, WEEK_OF_YEAR, YEAR, ZONE_OFFSET
Constructor Summary

Constructors
Constructor and Description
GregorianCalendar()
Constructs a default GregorianCalendar using
the current time in the default time zone with
the default FORMAT locale.
GregorianCalendar(int year, int month,
int dayOfMonth)
Constructs a GregorianCalendar with the given
date set in the default time zone with the default
locale.
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute)
Constructs a GregorianCalendar with the given
date and time set for the default time zone with
the default locale.
GregorianCalendar(int year, int month,
int dayOfMonth, int hourOfDay, int minute,
int second)
Constructs a GregorianCalendar with the given
date and time set for the default time zone with
the default locale.
GregorianCalendar(Locale aLocale)
Constructs a GregorianCalendar based on the
current time in the default time zone with the
given locale.
GregorianCalendar(TimeZone zone)
Constructs a GregorianCalendar based on the
current time in the given time zone with the
default FORMAT locale.
GregorianCalendar(TimeZone zone, Locale aL
ocale)
Constructs a GregorianCalendar based on the
current time in the given time zone with the
given locale.

Method Summary

All MethodsStatic MethodsInstance


MethodsConcrete Methods
Modifier and Method and Description
Type
void add(int field, int amount)
Adds the specified (signed)
amount of time to the given
calendar field, based on the
calendar's rules.
Object clone()
Creates and returns a copy of
this object.
protected void computeFields()
Converts the time value
(millisecond offset from
the Epoch) to calendar field
values.
protected void computeTime()
Converts calendar field values
to the time value (millisecond
offset from the Epoch).
boolean equals(Object obj)
Compares
this GregorianCalendar to the
specified Object.
static Gregoria from(ZonedDateTime zdt)
nCalendar Obtains an instance
of GregorianCalendar with the
default locale from
a ZonedDateTime object.
int getActualMaximum(int field)
Returns the maximum value
that this calendar field could
have, taking into consideration
the given time value and the
current values of
the getFirstDayOfWeek, get
MinimalDaysInFirstWeek, g
etGregorianChange and get
TimeZone methods.
int getActualMinimum(int field)
Returns the minimum value
that this calendar field could
have, taking into consideration
the given time value and the
current values of
the getFirstDayOfWeek, get
MinimalDaysInFirstWeek, g
etGregorianChange and get
TimeZone methods.
String getCalendarType()
Returns "gregory" as the
calendar type.
int getGreatestMinimum(int field
)
Returns the highest minimum
value for the given calendar
field of
this GregorianCalendar instanc
e.
Date getGregorianChange()
Gets the Gregorian Calendar
change date.
int getLeastMaximum(int field)
Returns the lowest maximum
value for the given calendar
field of
this GregorianCalendar instanc
e.
int getMaximum(int field)
Returns the maximum value
for the given calendar field of
this GregorianCalendar instanc
e.
int getMinimum(int field)
Returns the minimum value for
the given calendar field of
this GregorianCalendar instanc
e.
TimeZone getTimeZone()
Gets the time zone.
int getWeeksInWeekYear()
Returns the number of weeks
in the week year represented
by this GregorianCalendar.
int getWeekYear()
Returns the week
year represented by
this GregorianCalendar.
int hashCode()
Generates the hash code for
this GregorianCalendar object.
boolean isLeapYear(int year)
Determines if the given year is
a leap year.
boolean isWeekDateSupported()
Returns true indicating
this GregorianCalendar support
s week dates.
void roll(int field, boolean up)
Adds or subtracts (up/down) a
single unit of time on the given
time field without changing
larger fields.
void roll(int field, int amount)
Adds a signed amount to the
specified calendar field without
changing larger fields.
void setGregorianChange(Date d
ate)
Sets
the GregorianCalendar change
date.
void setTimeZone(TimeZone zone
)
Sets the time zone with the
given time zone value.
void setWeekDate(int weekYear,
int weekOfYear, int dayOfWeek)
Sets this GregorianCalendar to
the date given by the date
specifiers
- weekYear, weekOfYear,
and dayOfWeek.
ZonedDateTim toZonedDateTime()
e Converts this object to
a ZonedDateTime that
represents the same point on
the time-line as
this GregorianCalendar.

Methods inherited from


class java.util.Calendar

 after, before, clear, clear, compareTo, complete, ge


t, getAvailableCalendarTypes, getAvailableLocales,
getDisplayName, getDisplayNames, getFirstDayOf
Week, getInstance, getInstance, getInstance, getIn
stance, getMinimalDaysInFirstWeek, getTime, getTi
meInMillis, internalGet, isLenient, isSet, set, set, se
t, set, setFirstDayOfWeek, setLenient, setMinimalD
aysInFirstWeek, setTime, setTimeInMillis, toInstant,
toString

Methods inherited from class java.lang.Object

 finalize, getClass, notify, notifyAll, wait, wait, wait

Field Detail

BC

public static final int BC

Value of the ERA field indicating the period before


the common era (before Christ), also known as
BCE. The sequence of years at the transition
from BC to AD is ..., 2 BC, 1 BC, 1 AD, 2 AD,...

See Also:

Calendar.ERA, Constant Field Values

AD

public static final int AD

Value of the ERA field indicating the common era


(Anno Domini), also known as CE. The sequence of
years at the transition from BC to AD is ..., 2 BC, 1
BC, 1 AD, 2 AD,...

See Also:

Calendar.ERA, Constant Field Values

Constructor Detail

GregorianCalendar

public GregorianCalendar()

Constructs a default GregorianCalendar using the


current time in the default time zone with the
default FORMAT locale.

GregorianCalendar

public GregorianCalendar(TimeZone zone)

Constructs a GregorianCalendar based on the


current time in the given time zone with the
default FORMAT locale.

Parameters:

zone - the given time zone.

GregorianCalendar

public GregorianCalendar(Locale aLocale)


Constructs a GregorianCalendar based on the


current time in the default time zone with the
given locale.

Parameters:

aLocale - the given locale.

GregorianCalendar

public GregorianCalendar(TimeZone zone,


Locale aLocale)

Constructs a GregorianCalendar based on the


current time in the given time zone with the given
locale.

Parameters:

zone - the given time zone.

aLocale - the given locale.


GregorianCalendar

public GregorianCalendar(int year,


int month,
int dayOfMonth)

Constructs a GregorianCalendar with the given


date set in the default time zone with the default
locale.

Parameters:

year - the value used to set the YEAR calendar field


in the calendar.

month - the value used to set the MONTH calendar


field in the calendar. Month value is 0-based. e.g.,
0 for January.

dayOfMonth - the value used to set


the DAY_OF_MONTH calendar field in the calendar.

GregorianCalendar

public GregorianCalendar(int year,


int month,
int dayOfMonth,
int hourOfDay,
int minute)

Constructs a GregorianCalendar with the given


date and time set for the default time zone with
the default locale.

Parameters:

year - the value used to set the YEAR calendar field


in the calendar.

month - the value used to set the MONTH calendar


field in the calendar. Month value is 0-based. e.g.,
0 for January.

dayOfMonth - the value used to set


the DAY_OF_MONTH calendar field in the calendar.

hourOfDay - the value used to set


the HOUR_OF_DAY calendar field in the calendar.

minute - the value used to set the MINUTE calendar


field in the calendar.

GregorianCalendar

public GregorianCalendar(int year,


int month,
int dayOfMonth,
int hourOfDay,
int minute,
int second)

Constructs a GregorianCalendar with the given


date and time set for the default time zone with
the default locale.

Parameters:

year - the value used to set the YEAR calendar field


in the calendar.

month - the value used to set the MONTH calendar


field in the calendar. Month value is 0-based. e.g.,
0 for January.

dayOfMonth - the value used to set


the DAY_OF_MONTH calendar field in the calendar.


hourOfDay - the value used to set
the HOUR_OF_DAY calendar field in the calendar.

minute - the value used to set the MINUTE calendar


field in the calendar.

second - the value used to set


the SECOND calendar field in the calendar.

Method Detail

setGregorianChange

public void setGregorianChange(Date date)

Sets the GregorianCalendar change date. This is


the point when the switch from Julian dates to
Gregorian dates occurred. Default is October 15,
1582 (Gregorian). Previous to this, dates will be in
the Julian calendar.

To obtain a pure Julian calendar, set the change


date to Date(Long.MAX_VALUE). To obtain a pure
Gregorian calendar, set the change date
to Date(Long.MIN_VALUE).

Parameters:

date - the given Gregorian cutover date.

getGregorianChange

public final Date getGregorianChange()

Gets the Gregorian Calendar change date. This is


the point when the switch from Julian dates to
Gregorian dates occurred. Default is October 15,
1582 (Gregorian). Previous to this, dates will be in
the Julian calendar.

Returns:

the Gregorian cutover date for


this GregorianCalendar object.

isLeapYear

public boolean isLeapYear(int year)


Determines if the given year is a leap year.
Returns true if the given year is a leap year. To
specify BC year numbers, 1 - year number must
be given. For example, year BC 4 is specified as -
3.

Parameters:

year - the given year.

Returns:

true if the given year is a leap


year; false otherwise.

getCalendarType

public String getCalendarType()

Returns "gregory" as the calendar type.

Overrides:

getCalendarType in class Calendar


Returns:

"gregory"

Since:

1.8

See Also:

Locale
extensions, Locale.Builder.setLocale(Locale), Local
e.Builder.setUnicodeLocaleKeyword(String, String)

equals

public boolean equals(Object obj)

Compares this GregorianCalendar to the


specified Object. The result is true if and only if
the argument is a GregorianCalendar object that
represents the same time value (millisecond offset
from the Epoch) under the
same Calendar parameters and Gregorian change
date as this object.

Overrides:

equals in class Calendar

Parameters:

obj - the object to compare with.

Returns:

true if this object is equal to obj; false otherwise.

See Also:

Calendar.compareTo(Calendar)

hashCode

public int hashCode()


Generates the hash code for


this GregorianCalendar object.

Overrides:

hashCode in class Calendar

Returns:

a hash code value for this object.

See Also:

Object.equals(java.lang.Object), System.identityHa
shCode(java.lang.Object)

add

public void add(int field,


int amount)


Adds the specified (signed) amount of time to the
given calendar field, based on the calendar's
rules.

Add rule 1. The value of field after the call minus


the value of field before the call is amount,
modulo any overflow that has occurred in field.
Overflow occurs when a field value exceeds its
range and, as a result, the next larger field is
incremented or decremented and the field value is
adjusted back into its range.

Add rule 2. If a smaller field is expected to be


invariant, but it is impossible for it to be equal to
its prior value because of changes in its minimum
or maximum after field is changed, then its value
is adjusted to be as close as possible to its
expected value. A smaller field represents a
smaller unit of time. HOUR is a smaller field
than DAY_OF_MONTH. No adjustment is made to
smaller fields that are not expected to be
invariant. The calendar system determines what
fields are expected to be invariant.

Specified by:

add in class Calendar

Parameters:


field - the calendar field.

amount - the amount of date or time to be added


to the field.

Throws:

IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.

See Also:

Calendar.roll(int,int), Calendar.set(int,int)

roll

public void roll(int field,


boolean up)

Adds or subtracts (up/down) a single unit of time


on the given time field without changing larger
fields.

Example: Consider a GregorianCalendar originally


set to December 31, 1999.
Calling roll(Calendar.MONTH, true) sets the
calendar to January 31, 1999. The YEAR field is
unchanged because it is a larger field
than MONTH.

Specified by:

roll in class Calendar

Parameters:

up - indicates if the value of the specified calendar


field is to be rolled up or rolled down. Use true if
rolling up, false otherwise.

field - the time field.

Throws:

IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.


See Also:

add(int,int), Calendar.set(int,int)

roll

public void roll(int field,


int amount)

Adds a signed amount to the specified calendar


field without changing larger fields. A negative roll
amount means to subtract from field without
changing larger fields. If the specified amount is 0,
this method performs nothing.

This method calls Calendar.complete() before


adding the amount so that all the calendar fields
are normalized. If there is any calendar field
having an out-of-range value in non-lenient mode,
then an IllegalArgumentException is thrown.

Example: Consider a GregorianCalendar originally


set to August 31, 1999.
Calling roll(Calendar.MONTH, 8) sets the calendar
to April 30, 1999. Using a GregorianCalendar,
the DAY_OF_MONTH field cannot be 31 in the
month April. DAY_OF_MONTH is set to the closest
possible value, 30. The YEAR field maintains the
value of 1999 because it is a larger field
than MONTH.

Example: Consider a GregorianCalendar originally


set to Sunday June 6, 1999.
Calling roll(Calendar.WEEK_OF_MONTH, -1) sets
the calendar to Tuesday June 1, 1999, whereas
calling add(Calendar.WEEK_OF_MONTH, -1) sets
the calendar to Sunday May 30, 1999. This is
because the roll rule imposes an additional
constraint: The MONTH must not change when
the WEEK_OF_MONTH is rolled. Taken together
with add rule 1, the resultant date must be
between Tuesday June 1 and Saturday June 5.
According to add rule 2, the DAY_OF_WEEK, an
invariant when changing the WEEK_OF_MONTH, is
set to Tuesday, the closest possible value to
Sunday (where Sunday is the first day of the
week).

Overrides:

roll in class Calendar

Parameters:

field - the calendar field.

amount - the signed amount to add to field.


Throws:

IllegalArgumentException -
if field is ZONE_OFFSET, DST_OFFSET, or unknown,
or if any calendar fields have out-of-range values in
non-lenient mode.

Since:

1.2

See Also:

roll(int,boolean), add(int,int), Calendar.set(int,int)

getMinimum

public int getMinimum(int field)

Returns the minimum value for the given calendar


field of this GregorianCalendar instance. The
minimum value is defined as the smallest value
returned by the get method for any possible time
value, taking into consideration the current values
of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds.

Specified by:

getMinimum in class Calendar

Parameters:

field - the calendar field.

Returns:

the minimum value for the given calendar field.

See Also:

getMaximum(int), getGreatestMinimum(int), getLe


astMaximum(int), getActualMinimum(int), getActua
lMaximum(int)


getMaximum

public int getMaximum(int field)

Returns the maximum value for the given


calendar field of this GregorianCalendar instance.
The maximum value is defined as the largest
value returned by the get method for any possible
time value, taking into consideration the current
values of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds.

Specified by:

getMaximum in class Calendar

Parameters:

field - the calendar field.

Returns:

the maximum value for the given calendar field.


See Also:

getMinimum(int), getGreatestMinimum(int), getLea


stMaximum(int), getActualMinimum(int), getActual
Maximum(int)

getGreatestMinimum

public int getGreatestMinimum(int field)

Returns the highest minimum value for the given


calendar field of this GregorianCalendar instance.
The highest minimum value is defined as the
largest value returned
by getActualMinimum(int) for any possible time
value, taking into consideration the current values
of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds.

Specified by:

getGreatestMinimum in class Calendar

Parameters:

field - the calendar field.

Returns:

the highest minimum value for the given calendar


field.

See Also:

getMinimum(int), getMaximum(int), getLeastMaxim


um(int), getActualMinimum(int), getActualMaximu
m(int)

getLeastMaximum

public int getLeastMaximum(int field)

Returns the lowest maximum value for the given


calendar field of this GregorianCalendar instance.
The lowest maximum value is defined as the
smallest value returned
by getActualMaximum(int) for any possible time
value, taking into consideration the current values
of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds.

Specified by:

getLeastMaximum in class Calendar

Parameters:

field - the calendar field

Returns:

the lowest maximum value for the given calendar


field.

See Also:

getMinimum(int), getMaximum(int), getGreatestMi


nimum(int), getActualMinimum(int), getActualMaxi
mum(int)

getActualMinimum

public int getActualMinimum(int field)

Returns the minimum value that this calendar


field could have, taking into consideration the
given time value and the current values of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds.

For example, if the Gregorian change date is


January 10, 1970 and the date of
this GregorianCalendar is January 20, 1970, the
actual minimum value of the DAY_OF_MONTH field
is 10 because the previous date of January 10,
1970 is December 27, 1996 (in the Julian
calendar). Therefore, December 28, 1969 to
January 9, 1970 don't exist.

Overrides:

getActualMinimum in class Calendar

Parameters:

field - the calendar field

Returns:

the minimum of the given field for the time value


of this GregorianCalendar

Since:

1.2

See Also:

getMinimum(int), getMaximum(int), getGreatestMi


nimum(int), getLeastMaximum(int), getActualMaxi
mum(int)

getActualMaximum

public int getActualMaximum(int field)

Returns the maximum value that this calendar


field could have, taking into consideration the
given time value and the current values of
the getFirstDayOfWeek, getMinimalDaysInFirstWe
ek, getGregorianChange and getTimeZone metho
ds. For example, if the date of this instance is
February 1, 2004, the actual maximum value of
the DAY_OF_MONTH field is 29 because 2004 is a
leap year, and if the date of this instance is
February 1, 2005, it's 28.

This method calculates the maximum value


of WEEK_OF_YEAR based on the YEAR (calendar
year) value, not the week year.
Call getWeeksInWeekYear() to get the maximum
value of WEEK_OF_YEAR in the week year of
this GregorianCalendar.

Overrides:

getActualMaximum in class Calendar

Parameters:

field - the calendar field

Returns:

the maximum of the given field for the time value


of this GregorianCalendar

Since:

1.2

See Also:

getMinimum(int), getMaximum(int), getGreatestMi


nimum(int), getLeastMaximum(int), getActualMini
mum(int)

clone

public Object clone()

Description copied from class: Calendar

Creates and returns a copy of this object.

Overrides:

clone in class Calendar

Returns:

a copy of this object.


See Also:

Cloneable

getTimeZone

public TimeZone getTimeZone()

Description copied from class: Calendar

Gets the time zone.

Overrides:

getTimeZone in class Calendar

Returns:

the time zone object associated with this calendar.


setTimeZone

public void setTimeZone(TimeZone zone)

Description copied from class: Calendar

Sets the time zone with the given time zone value.

Overrides:

setTimeZone in class Calendar

Parameters:

zone - the given time zone.

isWeekDateSupported

public final boolean isWeekDateSupported()

Returns true indicating


this GregorianCalendar supports week dates.

Overrides:

isWeekDateSupported in class Calendar

Returns:

true (always)

Since:

1.7

See Also:

getWeekYear(), setWeekDate(int,int,int), getWeeks


InWeekYear()

getWeekYear

public int getWeekYear()


Returns the week year represented by
this GregorianCalendar. The dates in the weeks
between 1 and the maximum week number of the
week year have the same week year value that
may be one year before or after
the YEAR (calendar year) value.

This method calls Calendar.complete() before


calculating the week year.

Overrides:

getWeekYear in class Calendar

Returns:

the week year represented by


this GregorianCalendar. If the ERA value is BC, the
year is represented by 0 or a negative number: BC
1 is 0, BC 2 is -1, BC 3 is -2, and so on.

Throws:

IllegalArgumentException - if any of the calendar


fields is invalid in non-lenient mode.

Since:

1.7

See Also:

isWeekDateSupported(), getWeeksInWeekYear(), C
alendar.getFirstDayOfWeek(), Calendar.getMinimal
DaysInFirstWeek()

setWeekDate

public void setWeekDate(int weekYear,


int weekOfYear,
int dayOfWeek)

Sets this GregorianCalendar to the date given by


the date specifiers - weekYear, weekOfYear,
and dayOfWeek. weekOfYear follows
the WEEK_OF_YEAR numbering.
The dayOfWeek value must be one of
the DAY_OF_WEEK values: SUNDAY to SATURDAY.

Note that the numeric day-of-week representation


differs from the ISO 8601 standard, and that
the weekOfYear numbering is compatible with the
standard
when getFirstDayOfWeek() is MONDAY and getMin
imalDaysInFirstWeek() is 4.

Unlike the set method, all of the calendar fields


and the instant of time value are calculated upon
return.

If weekOfYear is out of the valid week-of-year


range in weekYear,
the weekYear and weekOfYear values are adjusted
in lenient mode, or an IllegalArgumentException is
thrown in non-lenient mode.

Overrides:

setWeekDate in class Calendar

Parameters:

weekYear - the week year

weekOfYear - the week number based on weekYear

dayOfWeek - the day of week value: one of the


constants for
the DAY_OF_WEEK field: SUNDAY, ..., SATURDAY.

Throws:

IllegalArgumentException - if any of the given date


specifiers is invalid, or if any of the calendar fields
are inconsistent with the given date specifiers in
non-lenient mode

Since:

1.7

See Also:

isWeekDateSupported(), Calendar.getFirstDayOfW
eek(), Calendar.getMinimalDaysInFirstWeek()

getWeeksInWeekYear

public int getWeeksInWeekYear()

Returns the number of weeks in the week


year represented by this GregorianCalendar.


For example, if this GregorianCalendar's date is
December 31, 2008 with the ISO 8601 compatible
setting, this method will return 53 for the period:
December 29, 2008 to January 3, 2010
while getActualMaximum(WEEK_OF_YEAR) will
return 52 for the period: December 31, 2007 to
December 28, 2008.

Overrides:

getWeeksInWeekYear in class Calendar

Returns:

the number of weeks in the week year.

Since:

1.7

See Also:

Calendar.WEEK_OF_YEAR, getWeekYear(), getActu


alMaximum(int)


computeFields

protected void computeFields()

Converts the time value (millisecond offset from


the Epoch) to calendar field values. The time
is not recomputed first; to recompute the time,
then the fields, call the complete method.

Specified by:

computeFields in class Calendar

See Also:

Calendar.complete()

computeTime

protected void computeTime()

Converts calendar field values to the time value


(millisecond offset from the Epoch).

Specified by:

computeTime in class Calendar

Throws:

IllegalArgumentException - if any calendar fields


are invalid.

See Also:

Calendar.complete(), Calendar.computeFields()

toZonedDateTime

public ZonedDateTime toZonedDateTime()

Converts this object to a ZonedDateTime that


represents the same point on the time-line as
this GregorianCalendar.


Since this object supports a Julian-Gregorian
cutover date and ZonedDateTime does not, it is
possible that the resulting year, month and day
will have different values. The result will represent
the correct date in the ISO calendar system, which
will also be the same value for Modified Julian
Days.

Returns:

a zoned date-time representing the same point on


the time-line as this gregorian calendar

Since:

1.8

from

public
static GregorianCalendar from(ZonedDateTime zdt)

Obtains an instance of GregorianCalendar with the


default locale from a ZonedDateTime object.


Since ZonedDateTime does not support a Julian-
Gregorian cutover date and uses ISO calendar
system, the return GregorianCalendar is a pure
Gregorian calendar and uses ISO 8601 standard
for week definitions, which has MONDAY as
the FirstDayOfWeek and 4 as the value of
the MinimalDaysInFirstWeek.

ZoneDateTime can store points on the time-line


further in the future and further in the past
than GregorianCalendar. In this scenario, this
method will throw
an IllegalArgumentException exception.

Parameters:

zdt - the zoned date-time object to convert

Returns:

the gregorian calendar representing the same


point on the time-line as the zoned date-time
provided

Throws:

NullPointerException - if zdt is null


IllegalArgumentException - if the zoned date-time
is too large to represent as a GregorianCalendar

Since:

1.8

JAVA DATE AND TIME API

The Date-Time APIs, introduced in JDK 8, are a set


of packages that model the most important
aspects of date and time. The core classes in
the java.time package use the calendar system
defined in ISO-8601 (based on the Gregorian
calendar system) as the default calendar. Other
non-ISO calendar systems can be represented
using the java.time.chrono package and several
predefined chronologies, such as Hijrah and Thai
Buddhist are provided.

API Specification

 java.time - Classes for date, time, date and time


combined, time zones, instants, duration, and
clocks.
 java.time.chrono - API for representing calendar
systems other than ISO-8601. Several predefined
chronologies are provided and you can also
define your own chronology.
 java.time.format - Classes for formatting and
parsing dates and time.
 java.time.temporal - Extended API, primarily for
framework and library writers, allowing
interoperations between the date and time
classes, querying, and adjustment. Fields and
units are defined in this package.
 java.time.zone - Classes that support time zones,
offsets from time zones, and time zone rules.
 JSR 310: Date and Time API

JAVA DOCS TOOLS AND HOW TO USE IT

JavaDoc tool is a document generator tool in Java


programming language for generating standard
documentation in HTML format. It generates API
documentation. It parses the declarations ad
documentation in a set of source file describing
classes, methods, constructors, and fields.

Before using JavaDoc tool, you must include


JavaDoc comments /………………..*/ providing
information about classes, methods, and
constructors, etc. For creating a good and
understandable document API for any java file you
must write better comments for every class,
method, constructor.
The JavaDoc comments is different from the
normal comments because of the extra asterisk at
the beginning of the comment. It may contain the
HTML tags as well.

// Single-Line Comment

/*
* Multiple-Line comment
*/

/**
* JavaDoc comment
*/
By writing a number of comments, it does not
affect the performance of the Java program as all
the comments are removed at compile time.

JavaDoc Format: –
It has two parts: – a description which is followed
by block tags.
Some Integrated Development Environments (IDE)
automatically generate the JavaDoc file like
NetBeans, IntelliJ IDEA, Eclipse, etc.
Generation of JavaDoc: –
To create a JavaDoc you do not need to compile
the java file. To create the Java documentation API,
you need to write Javadoc followed by file name.

javadoc file_name or javadoc package_name

After successful execution of the above command,


a number of HTML files will be created, open the
file named index to see all the information about
classes.

JavaDoc Tags

Tag Parameter Description

@autho author_nam
Describes an author
r e

provide information about


@para
description method parameter or the
m
input it takes

generate a link to other


@see reference
element of the document

@versio version- provide version of the


n name class, interface or enum.

@return description provide the return value

To generate JavaDoc in Eclipse: –

 Select “Generate JavaDoc” option from Project


menu and a wizard will appear.
 Specify the location for the JavaDoc file on your
computer, by default it will be in the C drive.
 Select the project and then the packages for
which you want to create the JavaDoc file.
 After this on the right side, select the classes for
which you want to generate the JavaDoc, by
default all the classes will be selected.
 Then you can also specify for which classes the
JavaDoc will be generated by selecting the
visibility.
 Select the destination location where the
generated JavaDoc will be placed.
 Then click Next or Finish.
 If you select Next in the next window you can
select the Document title and other basic
options.

Example 1 : –

package exa;

import java.util.Scanner;

/**
*
* @author Yash
*/
public class Example {
/**
* This is a program for adding two numbers in java.
* @param args
*/
public static void main(String[] args)
{
/**
* This is the main method
* which is very important for
* execution for a java program.
*/

int x, y;
Scanner sc = new Scanner(System.in);
/**
* Declared two variables x and y.
* And taking input from the user
* by using Scanner class.
*
*/

x = sc.nextInt();
y = sc.nextInt();
/**
* Storing the result in variable sum
* which is of the integer type.
*/
int sum = x + y;

/**
* Using standard output stream
* for giving the output.
* @return null
*/
System.out.println("Sum is: " + sum);
}
}

Generating document for the above class

javadoc exa

Screenshot of javadoc: –
ANNONATIONS IN JAVA

Many APIs require a fair amount of boilerplate


code. For example, in order to write a JAX-RPC web
service, you must provide a paired interface and
implementation. This boilerplate could be
generated automatically by a tool if the program
were “decorated” with annotations indicating
which methods were remotely accessible.
Other APIs require “side files” to be maintained in
parallel with programs. For example JavaBeans
requires a BeanInfo class to be maintained in
parallel with a bean, and Enterprise JavaBeans
(EJB) requires a deployment descriptor. It would be
more convenient and less error-prone if the
information in these side files were maintained as
annotations in the program itself.
The Java platform has always had various ad hoc
annotation mechanisms. For example
the transient modifier is an ad hoc annotation
indicating that a field should be ignored by the
serialization subsystem, and
the @deprecated javadoc tag is an ad hoc
annotation indicating that the method should no
longer be used. The platform has a general
purpose annotation (also known as metadata)
facility that permits you to define and use your
own annotation types. The facility consists of a
syntax for declaring annotation types, a syntax for
annotating declarations, APIs for reading
annotations, a class file representation for
annotations, and annotation processing support
provided by the javac tool.
Annotations do not directly affect program
semantics, but they do affect the way programs
are treated by tools and libraries, which can in turn
affect the semantics of the running program.
Annotations can be read from source files, class
files, or reflectively at run time.
Annotations complement javadoc tags. In general,
if the markup is intended to affect or produce
documentation, it should probably be a javadoc
tag; otherwise, it should be an annotation.
Typical application programmers will never have to
define an annotation type, but it is not hard to do
so. Annotation type declarations are similar to
normal interface declarations. An at-sign (@)
precedes the interface keyword. Each method
declaration defines an element of the annotation
type. Method declarations must not have any
parameters or a throws clause. Return types are
restricted to primitives, String, Class, enums,
annotations, and arrays of the preceding types.
Methods can have default values. Here is an
example annotation type declaration:
/**
* Describes the Request-For-Enhancement(RFE)
that led
* to the presence of the annotated API element.
*/
public @interface RequestForEnhancement {
int id();
String synopsis();
String engineer() default "[unassigned]";
String date() default "[unimplemented]";
}
Once an annotation type is defined, you can use it
to annotate declarations. An annotation is a special
kind of modifier, and can be used anywhere that
other modifiers (such as public, static, or final) can
be used. By convention, annotations precede other
modifiers. Annotations consist of an at-sign (@)
followed by an annotation type and a
parenthesized list of element-value pairs. The
values must be compile-time constants. Here is a
method declaration with an annotation
corresponding to the annotation type declared
above:
@RequestForEnhancement(
id = 2868724,
synopsis = "Enable time-travel",
engineer = "Mr. Peabody",
date = "4/1/3007"
)
public static void travelThroughTime(Date
destination) { ... }
An annotation type with no elements is termed
a marker annotation type, for example:
/**
* Indicates that the specification of the
annotated API element
* is preliminary and subject to change.
*/
public @interface Preliminary { }
It is permissible to omit the parentheses in marker
annotations, as shown below:
@Preliminary public class TimeTravel { ... }
In annotations with a single element, the element
should be named value, as shown below:
/**
* Associates a copyright notice with the
annotated API element.
*/
public @interface Copyright {
String value();
}
It is permissible to omit the element name and
equals sign (=) in a single-element annotation
whose element name is value, as shown below:
@Copyright("2002 Yoyodyne Propulsion
Systems")
public class OscillationOverthruster { ... }
To tie it all together, we'll build a simple
annotation-based test framework. First we need a
marker annotation type to indicate that a method
is a test method, and should be run by the testing
tool:
import java.lang.annotation.*;

/**
* Indicates that the annotated method is a test
method.
* This annotation should be used only on
parameterless static methods.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test { }
Note that the annotation type declaration is itself
annotated. Such annotations are called meta-
annotations. The first
(@Retention(RetentionPolicy.RUNTIME)) indicates
that annotations with this type are to be retained
by the VM so they can be read reflectively at run-
time. The second
(@Target(ElementType.METHOD)) indicates that
this annotation type can be used to annotate only
method declarations.
Here is a sample program, some of whose methods
are annotated with the above interface:
public class Foo {
@Test public static void m1() { }
public static void m2() { }
@Test public static void m3() {
throw new RuntimeException("Boom");
}
public static void m4() { }
@Test public static void m5() { }
public static void m6() { }
@Test public static void m7() {
throw new RuntimeException("Crash");
}
public static void m8() { }
}
Here is the testing tool:
import java.lang.reflect.*;

public class RunTests {


public static void main(String[] args) throws
Exception {
int passed = 0, failed = 0;
for (Method m :
Class.forName(args[0]).getMethods()) {
if (m.isAnnotationPresent(Test.class))
{
try {
m.invoke(null);
passed++;
} catch (Throwable ex) {
System.out.printf("Test %s failed: %s
%n", m, ex.getCause());
failed++;
}
}
}
System.out.printf("Passed: %d, Failed %d
%n", passed, failed);
}
}
The tool takes a class name as a command line
argument and iterates over all the methods of the
named class attempting to invoke each method
that is annotated with the Test annotation type
(defined above). The reflective query to find out if
a method has a Test annotation is highlighted in
green. If a test method invocation throws an
exception, the test is deemed to have failed, and a
failure report is printed. Finally, a summary is
printed showing the number of tests that passed
and failed. Here is how it looks when you run the
testing tool on the Foo program (above):
$ java RunTests Foo
Test public static void Foo.m3() failed:
java.lang.RuntimeException: Boom
Test public static void Foo.m7() failed:
java.lang.RuntimeException: Crash
Passed: 2, Failed 2
While this testing tool is clearly a toy, it
demonstrates the power of annotations and could
easily be extended to overcome its limitations.

Tag Description Syntax


Adds the author of
@author @author name-text
a class.
Displays text in
code font without
interpreting the
{@code} {@code text}
text as HTML
markup or nested
javadoc tags.
Represents the
relative path to
{@docRoot the generated
{@docRoot}
} document's root
directory from any
generated page.
Adds a comment
@deprecat indicating that this @deprecated
ed API should no deprecatedtext
longer be used.
Adds
a Throws subhea
ding to the
@exceptio generated @exception class-
n documentation, name description
with the
classname and
description text.
{@inheritD Inherits a Inherits a comment
comment from
the nearest inheri from the
oc} table class or immediate
implementable surperclass.
interface.
Inserts an in-line
link with the
visible text label
that points to the {@link
{@link} documentation for package.class#me
the specified mber label}
package, class, or
member name of
a referenced class.
Identical to
{@link}, except
{@linkplain
{@linkplai the link's label is
package.class#me
n} displayed in plain
mber label}
text than code
font.
Adds a parameter
with the specified
parameter-name
@param
followed by the
@param parameter-name
specified
description
description to the
"Parameters"
section.
Adds a "Returns"
@return
@return section with the
description
description text.
@see Adds a "See Also" @see reference
heading with a link
or text entry that
points to
reference.
Used in the doc
@serial field-
comment for a
@serial description |
default serializable
include | exclude
field.
Documents the
data written by
@serialDat @serialData data-
the writeObject( )
a description
or writeExternal( )
methods.
Documents an @serialField field-
@serialFiel
ObjectStreamField name field-type
d
component. field-description
Adds a "Since"
heading with the
specified since-
@since @since release
text to the
generated
documentation.
The @throws and
@throws class-
@throws @exception tags
name description
are synonyms.
When {@value} is
used in the doc
{@value
comment of a
{@value} package.class#fiel
static field, it
d}
displays the value
of that constant.
@version Adds a "Version" @version version-
subheading with text
the specified
version-text to the
generated docs
when the -version
option is used.

JAVA ANONYMOUS CLASSES vs LAMBDA


EXPRESSIONS

Anonymous Inner Class:


It is an inner class without a name and for which
only a single object is created. An anonymous
inner class can be useful when making an instance
of an object with certain “extras” such as
overloading methods of a class or interface,
without having to actually subclass a class.
Anonymous inner classes are useful in writing
implementation classes for listener interfaces in
graphics programming.
Anonymous inner class are mainly created in two
ways:

Class (may be abstract or concrete)


Interface

Syntax: The syntax of an anonymous class


expression is like the invocation of a constructor,
except that there is a class definition contained in
a block of code.

// Test can be interface, abstract/concrete class


Test t = new Test()
{
// data members and methods
public void test_method()
{
........
........
}
};

To understand the anonymous inner class, let us


take a simple program

// Java Program to Demonstrate Anonymous inner


class

// Interface
interface Age {
int x = 21;
void getAge();
}

// Main class
class AnonymousDemo {

// Main driver method


public static void main(String[] args)
{

// A hidden inner class of Age interface is


created
// whose name is not written but an object to
it
// is created.
Age oj1 = new Age() {

@Override public void getAge()


{
// printing age
System.out.print("Age is " + x);
}
};

oj1.getAge();
}
}

Output
Age is 21
Lambda Expressions:
Lambda expressions basically express instances of
functional interfaces (An interface with single
abstract method is called functional interface. An
example is java.lang.Runnable). lambda
expressions implement the only abstract function
and therefore implement functional interfaces
lambda expressions are added in Java 8 and
provide below functionalities.

Enable to treat functionality as a method


argument, or code as data.
A function that can be created without belonging to
any class.
A lambda expression can be passed around as if it
was an object and executed on demand.

// Java program to demonstrate lambda


expressions
// to implement a user defined functional interface.

// A sample functional interface (An interface with


// single abstract method
interface FuncInterface {
// An abstract function
void abstractFun(int x);

// A non-abstract (or default) function


default void
normalFun()
{
System.out.println("Hello");
}
}

class Test {
public static void main(String args[])
{
// lambda expression to implement above
// functional interface. This interface
// by default implements abstractFun()
FuncInterface fobj = (int x) ->
System.out.println(2 * x);

// This calls above lambda expression and


prints 10.
fobj.abstractFun(5);
}
}

Output
10
Table of difference:

Anonymous Inner Lambda Expression


Class

It is a method without
It is a class without
name.(anonymous
name.
function)

It can extend abstract It can’t extend abstract


and concrete class. and concrete class.

It can implement It can implement an


Anonymous Inner Lambda Expression
Class

an interface that
interface which contains
contains any number
a single abstract method.
of abstract methods.

It does not allow


Inside this we can declaration of instance
declare instance variables, whether the
variables. variables declared simply
act as local variables.

Anonymous inner class Lambda Expression can’t


can be instantiated. be instantiated.

Inside Anonymous
Inside Lambda
inner class, “this”
Expression, “this” always
always refers to
refers to current outer
current anonymous
class object that is,
inner class object but
enclosing class object.
not to outer object.

It is the best choice if


It is the best choice if we
we want to handle
want to handle interface.
multiple methods.

At the time of
At the time of compilation, no
compilation, a separate .class file will be
separate .class file will generated. It simply
be generated. convert it into private
method outer class.

Memory allocation is It resides in a permanent


on demand, whenever memory of JVM.
we are creating an
Anonymous Inner Lambda Expression
Class

object.

GENERICS IN JAVA

Generics means parameterized types. The idea is


to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods,
classes, and interfaces. Using Generics, it is
possible to create classes that work with different
data types. An entity such as class, interface, or
method that operates on a parameterized type is a
generic entity.

Why Generics?
The Object is the superclass of all other classes,
and Object reference can refer to any object. These
features lack type safety. Generics add that type of
safety feature. We will discuss that type of safety
feature in later examples.

Generics in Java are similar to templates in C++.


For example, classes like HashSet, ArrayList,
HashMap, etc., use generics very well. There are
some fundamental differences between the two
approaches to generic types.

Types of Java Generics


Generic Method: Generic Java method takes a
parameter and returns some value after
performing a task. It is exactly like a normal
function, however, a generic method has type
parameters that are cited by actual type. This
allows the generic method to be used in a more
general way. The compiler takes care of the type of
safety which enables programmers to code easily
since they do not have to perform long, individual
type castings.

Generic Classes: A generic class is implemented


exactly like a non-generic class. The only
difference is that it contains a type parameter
section. There can be more than one type of
parameter, separated by a comma. The classes,
which accept one or more parameters, ?are known
as parameterized classes or parameterized types.

Generic Class
Like C++, we use <> to specify parameter types in
generic class creation. To create objects of a
generic class, we use the following syntax.

// To create an instance of generic class


BaseType <Type> obj = new BaseType <Type>()
Note: In Parameter type we can not use primitives
like ‘int’,’char’ or ‘double’.

Java
// Java program to show working of user defined
// Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}
Output
15
GeeksForGeeks
We can also pass multiple Type parameters in
Generic classes.

Java
// Java program to show multiple
// type parameters in Java Generics

// We use < > to specify Parameter type


class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U

// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

// To print objects of T and U


public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}

// Driver class to test above


class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);

obj.print();
}
}
Output
GfG
15
Generic Functions:
We can also write generic functions that can be
called with different types of arguments based on
the type of arguments passed to the generic
method. The compiler handles each method.

Java
// Java program to show working of user defined
// Generic functions

class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getNa
me()
+ " = " + element);
}
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer
argument
genericDisplay(11);

// Calling generic method with String


argument
genericDisplay("GeeksForGeeks");

// Calling generic method with double


argument
genericDisplay(1.0);
}
}
Output
java.lang.Integer = 11
java.lang.String = GeeksForGeeks
java.lang.Double = 1.0
Generics Work Only with Reference Types:
When we declare an instance of a generic type, the
type argument passed to the type parameter must
be a reference type. We cannot use primitive data
types like int, char.

Test<int> obj = new Test<int>(20);


The above line results in a compile-time error that
can be resolved using type wrappers to
encapsulate a primitive type.

But primitive type arrays can be passed to the type


parameter because arrays are reference types.

ArrayList<int[]> a = new ArrayList<>();


Generic Types Differ Based on Their Type
Arguments:
Consider the following Java code.

Java
// Java program to show working
// of user-defined Generic classes

// We use < > to specify Parameter type


class Test<T> {
// An object of type T is declared
T obj;
Test(T obj) { this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}

// Driver class to test above


class Main {
public static void main(String[] args)
{
// instance of Integer type
Test<Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());

// instance of String type


Test<String> sObj
= new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
iObj = sObj; // This results an error
}
}
Output:

error:
incompatible types:
Test cannot be converted to Test
Even though iObj and sObj are of type Test, they
are the references to different types because their
type parameters differ. Generics add type safety
through this and prevent errors.
Type Parameters in Java Generics
The type parameters naming conventions are
important to learn generics thoroughly. The
common type parameters are as follows:

T – Type
E – Element
K – Key
N – Number
V – Value
Advantages of Generics:
Programs that use Generics has got many benefits
over non-generic code.

1. Code Reuse: We can write a


method/class/interface once and use it for any type
we want.

2. Type Safety: Generics make errors to appear


compile time than at run time (It’s always better to
know problems in your code at compile time rather
than making your code fail at run time). Suppose
you want to create an ArrayList that store name of
students, and if by mistake the programmer adds
an integer object instead of a string, the compiler
allows it. But, when we retrieve this data from
ArrayList, it causes problems at runtime.

Java
// Java program to demonstrate that NOT using
// generics can cause run time exceptions

import java.util.*;

class Test
{
public static void main(String[] args)
{
// Creatinga an ArrayList without any type
specified
ArrayList al = new ArrayList();

al.add("Sachin");
al.add("Rahul");
al.add(10); // Compiler allows this

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);

// Causes Runtime Exception


String s3 = (String)al.get(2);
}
}
Output :

Exception in thread "main"


java.lang.ClassCastException:
java.lang.Integer cannot be cast to
java.lang.String
at Test.main(Test.java:19)
How do Generics Solve this Problem?
When defining ArrayList, we can specify that this
list can take only String objects.

Java
// Using Java Generics converts run time exceptions
into
// compile time exception.
import java.util.*;

class Test
{
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new
ArrayList<String> ();

al.add("Sachin");
al.add("Rahul");

// Now Compiler doesn't allow this


al.add(10);

String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}
Output:

15: error: no suitable method found for add(int)


al.add(10);
^
3. Individual Type Casting is not needed: If we do
not use generics, then, in the above example,
every time we retrieve data from ArrayList, we
have to typecast it. Typecasting at every retrieval
operation is a big headache. If we already know
that our list only holds string data, we need not
typecast it every time.

Java
// We don't need to typecast individual members of
ArrayList

import java.util.*;

class Test {
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList<String> al = new
ArrayList<String>();

al.add("Sachin");
al.add("Rahul");

// Typecasting is not needed


String s1 = al.get(0);
String s2 = al.get(1);
}
}
4. Generics Promotes Code Reusability: With the
help of generics in Java, we can write code that will
work with different types of data. For example,

Let’s say we want to Sort the array elements of


various data types like int, char, String etc.

Basically we will be needing different functions for


different data types.

For simplicity, we will be using Bubble sort.

But by using Generics, we can achieve the code


reusability feature.

Java
public class GFG {

public static void main(String[] args)


{

Integer[] a = { 100, 22, 58, 41, 6, 50 };

Character[] c = { 'v', 'g', 'a', 'c', 'x', 'd', 't' };

String[] s = { "Virat", "Rohit", "Abhinay",


"Chandu","Sam", "Bharat", "Kalam" };
System.out.print("Sorted Integer array : ");
sort_generics(a);

System.out.print("Sorted Character array : ");


sort_generics(c);

System.out.print("Sorted String array : ");


sort_generics(s);

public static <T extends Comparable<T> > void


sort_generics(T[] a)
{

//As we are comparing the Non-primitive data


types
//we need to use Comparable class

//Bubble Sort logic


for (int i = 0; i < a.length - 1; i++) {

for (int j = 0; j < a.length - i - 1; j++) {

if (a[j].compareTo(a[j + 1]) > 0) {

swap(j, j + 1, a);
}
}
}

// Printing the elements after sorted

for (T i : a)
{
System.out.print(i + ", ");
}
System.out.println();
}

public static <T> void swap(int i, int j, T[] a)


{
T t = a[i];
a[i] = a[j];
a[j] = t;
}

}
Output
Sorted Integer array : 6, 22, 41, 50, 58, 100,
Sorted Character array : a, c, d, g, t, v, x,
Sorted String array : Abhinay, Bharat, Chandu,
Kalam, Rohit, Sam, Virat,
Here, we have created a generics method. This
same method can be used to perform operations
on integer data, string data, and so on.

5. Implementing Generic Algorithms: By using


generics, we can implement algorithms that
work on different types of objects, and at the
same, they are type-safe too.
FILE HANDALING IN JAVA

In Java, with the help of File Class, we can work


with files. This File Class is inside the java.io
package. The File class can be used by creating an
object of the class and then specifying the name of
the file.

Why File Handling is Required?

File Handling is an integral part of any


programming language as file handling enables us
to store the output of any particular program in a
file and allows us to perform certain operations on
it.
In simple words, file handling means reading and
writing data to a file.
// Importing File Class
import java.io.File;

class GFG {
public static void main(String[] args)
{

// File name specified


File obj = new File("myfile.txt");
System.out.println("File Created!");
}
}
Output

File Created!
In Java, the concept Stream is used in order to
perform I/O operations on a file. So at first, let us
get acquainted with a concept known as Stream in
Java.

Streams in Java
In Java, a sequence of data is known as a stream.
This concept is used to perform I/O operations on a
file.
There are two types of streams :
1. Input Stream:
The Java InputStream class is the superclass of all
input streams. The input stream is used to read
data from numerous input devices like the
keyboard, network, etc. InputStream is an abstract
class, and because of this, it is not useful by itself.
However, its subclasses are used to read data.
There are several subclasses of the InputStream
class, which are as follows:

AudioInputStream
ByteArrayInputStream
FileInputStream
FilterInputStream
StringBufferInputStream
ObjectInputStream
Creating an InputStream
// Creating an InputStream
InputStream obj = new FileInputStream();
Here, an input stream is created using
FileInputStream.

Note: We can create an input stream from other


subclasses as well as InputStream.

Methods of InputStream

S Method Description
No
.

Reads one byte of data from


1 read()
the input stream.

Reads byte from the stream


read(byte[]
2 and stores that byte in the
array)()
specified array.

It marks the position in the


3 mark() input stream until the data
has been read.

Returns the number of bytes


4 available()
available in the input stream.
S Method Description
No
.

It checks if the mark()


markSupported method and the reset()
5
() method is supported in the
stream.

Returns the control to the


6 reset() point where the mark was
set inside the stream.

Skips and removes a


7 skips() particular number of bytes
from the input stream.

8 close() Closes the input stream.

2. Output Stream:
The output stream is used to write data to
numerous output devices like the monitor, file, etc.
OutputStream is an abstract superclass that
represents an output stream. OutputStream is an
abstract class and because of this, it is not useful
by itself. However, its subclasses are used to write
data.

There are several subclasses of the OutputStream


class which are as follows:

ByteArrayOutputStream
FileOutputStream
StringBufferOutputStream
ObjectOutputStream
DataOutputStream
PrintStream
Creating an OutputStream
// Creating an OutputStream
OutputStream obj = new FileOutputStream();
Here, an output stream is created using
FileOutputStream.

Note: We can create an output stream from other


subclasses as well as OutputStream.

Methods of OutputStream

S. Method Description
No.

Writes the specified byte to the


1. write()
output stream.

Writes the bytes which are


write(byte[]
2. inside a specific array to the
array)
output stream.

3. close() Closes the output stream.

Forces to write all the data


4. flush() present in an output stream to
the destination.

Based on the data type, there are two types of


streams :

1. Byte Stream:
This stream is used to read or write byte data. The
byte stream is again subdivided into two types
which are as follows:
Byte Input Stream: Used to read byte data from
different devices.
Byte Output Stream: Used to write byte data to
different devices.
2. Character Stream:
This stream is used to read or write character data.
Character stream is again subdivided into 2 types
which are as follows:

Character Input Stream: Used to read character


data from different devices.
Character Output Stream: Used to write character
data to different devices.
Owing to the fact that you know what a stream is,
let’s polish up File Handling in Java by further
understanding the various methods that are useful
for performing operations on the files like creating,
reading, and writing files.

Java File Class Methods


The following table depicts several File Class
methods:

Method Name Description Return


Type

It tests whether the


canRead() Boolean
file is readable or not.

It tests whether the


canWrite() Boolean
file is writable or not.

createNewFile It creates an empty


Boolean
() file.

delete() It deletes a file. Boolean


Method Name Description Return
Type

It tests whether the


exists() Boolean
file exists or not.

Returns the size of the


length() Long
file in bytes.

Returns the name of


getName() String
the file.

Returns an array of
list() the files in the String[]
directory.

Creates a new
mkdir() Boolean
directory.

getAbsoluteP Returns the absolute


String
ath() pathname of the file.

Let us now get acquainted with the various file


operations in Java.

File operations in Java


The following are the several operations that can
be performed on a file in Java :

Create a File
Read from a File
Write to a File
Delete a File
Now let us study each of the above operations in
detail.
1. Create a File

In order to create a file in Java, you can use the


createNewFile() method.
If the file is successfully created, it will return a
Boolean value true and false if the file already
exists.
Following is a demonstration of how to create a file
in Java :

// Import the File class


import java.io.File;

// Import the IOException class to handle errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{

try {
File Obj = new File("myfile.txt");
if (Obj.createNewFile()) {
System.out.println("File created: "
+ Obj.getName());
}
else {
System.out.println("File already exists.");
}
}
catch (IOException e) {
System.out.println("An error has
occurred.");
e.printStackTrace();
}
}
}
Output
An error has occurred.
2. Read from a File: We will use the Scanner class
in order to read contents from a file. Following is a
demonstration of how to read contents from a file
in Java :

// Import the File class


import java.io.File;

// Import this class for handling errors


import java.io.FileNotFoundException;

// Import the Scanner class to read content from


text files
import java.util.Scanner;

public class GFG {


public static void main(String[] args)
{
try {
File Obj = new File("myfile.txt");
Scanner Reader = new Scanner(Obj);
while (Reader.hasNextLine()) {
String data = Reader.nextLine();
System.out.println(data);
}
Reader.close();
}
catch (FileNotFoundException e) {
System.out.println("An error has
occurred.");
e.printStackTrace();
}
}
}
Output
An error has occurred.
3. Write to a File: We use the FileWriter class along
with its write() method in order to write some text
to the file. Following is a demonstration of how to
write text to a file in Java :

// Import the FileWriter class


import java.io.FileWriter;

// Import the IOException class for handling errors


import java.io.IOException;

public class GFG {


public static void main(String[] args)
{
try {
FileWriter Writer
= new FileWriter("myfile.txt");
Writer.write(
"Files in Java are seriously good!!");
Writer.close();
System.out.println("Successfully written.");
}
catch (IOException e) {
System.out.println("An error has
occurred.");
e.printStackTrace();
}
}
}
Output

An error has occurred.


4. Delete a File: We use the delete() method in
order to delete a file. Following is a demonstration
of how to delete a file in Java :
// Import the File class
import java.io.File;

public class GFG {


public static void main(String[] args)
{
File Obj = new File("myfile.txt");
if (Obj.delete()) {
System.out.println("The deleted file is : "
+ Obj.getName());
}
else {
System.out.println(
"Failed in deleting the file.");
}
}
}
Output

Failed in deleting the file.

END OF JAVA UNIT 1

You might also like