0% found this document useful (0 votes)
4 views60 pages

Oops With Java Notes Unit 2

Uploaded by

luvyakapoor22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views60 pages

Oops With Java Notes Unit 2

Uploaded by

luvyakapoor22
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 60

NoJava Fundamentals

What is Java?
Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun Microsystems,
Inc. in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed
the name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation.

Editions of Java
Each edition of Java has different capabilities. There are three editions of
Java:

o Java Standard Editions (JSE): It is used to create programs for a


desktop computer.
o Java Enterprise Edition (JEE): It is used to create large programs
that run on the server and manages heavy traffic and complex
transactions.
o Java Micro Edition (JME): It is used to develop applications for small
devices such as set-top boxes, phone, and appliances.

Types of Java Applications


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

o Standalone Applications: Java standalone applications uses GUI


components such as AWT, Swing, and JavaFX. These components
contain buttons, list, menu, scroll panel, etc. It is also known as
desktop alienations.
o Enterprise Applications: An application which is distributed in nature
is called enterprise applications.
o Web Applications: An applications that run on the server is called
web applications. We use JSP, Servlet, Spring, and Hibernate
technologies for creating web applications.
o Mobile Applications: Java ME is a cross-platform to develop mobile
applications which run across smartphones. Java is a platform for App
Development in Android.

Java Platform
Java Platform is a collection of programs. It helps to develop and run a
program written in the Java programming language. Java Platform includes
an execution engine, a compiler and set of libraries. Java is a platform-
independent language.

Features of Java
o Simple: Java is a simple language because its syntax is simple, clean,
and easy to understand. Complex and ambiguous concepts of C++ are
either eliminated or re-implemented in Java. For example, pointer and
operator overloading are not used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It
means it has some data and behavior. A program must have at least
one class and object.
o Robust: Java makes an effort to check error at run time and compile
time. It uses a strong memory management system called garbage
collector. Exception handling and garbage collection features make it
strong.
o Secure: Java is a secure programming language because it has no
explicit pointer and programs runs in the virtual machine. Java contains
a security manager that defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes
once and run anywhere. This byte code is platform-independent and
can be run on any machine.

o Portable: Java Byte code can be carried to any platform. No


implementation-dependent features. Everything related to storage is
predefined, for example, the size of primitive data types.
o High Performance: Java is an interpreted language. Java enables
high performance with the use of the Just-In-Time compiler.
o Distributed: Java also has networking facilities. It is designed for the
distributed environment of the internet because it supports TCP/IP
protocol. It can run over the internet. EJB and RMI are used to create a
distributed system.
o Multi-threaded: Java also supports multi-threading. It means to
handle more than one job a time.
Data Types in Java
Data types specify the different sizes and values that can be stored in the
variable. There are two types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.

Java Primitive Data Types


In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type
Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type


The Boolean data type is used to store only two possible values: true and
false. This data type is used for simple flags that track true/false conditions.
The Boolean data type specifies one bit of information, but its "size" can't be
defined precisely.
Example:
1. Boolean one = false

Byte Data Type


The byte data type is an example of primitive data type. It isan 8-bit signed
two's complement integer. Its value-range lies between -128 to 127
(inclusive). Its minimum value is -128 and maximum value is 127. Its default
value is 0.
The byte data type is used to save memory in large arrays where the
memory savings is most required. It saves space because a byte is 4 times
smaller than an integer. It can also be used in place of "int" data type.
Example:
1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-
range lies between -32,768 to 32,767 (inclusive). Its minimum value is -
32,768 and maximum value is 32,767. Its default value is 0.
The short data type can also be used to save memory just like byte data
type. A short data type is 2 times smaller than an integer.
Example:
1. short s = 10000, short r = -5000

Int Data Type


The int data type is a 32-bit signed two's complement integer. Its value-
range lies between - 2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1)
(inclusive). Its minimum value is - 2,147,483,648and maximum value is
2,147,483,647. Its default value is 0.
The int data type is generally used as a default data type for integral values
unless if there is no problem about memory.
Example:
1. int a = 100000, int b = -200000
Long Data Type
The long data type is a 64-bit two's complement integer. Its value-range lies
between -9,223,372,036,854,775,808(-2^63) to
9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value is -
9,223,372,036,854,775,808and maximum value is
9,223,372,036,854,775,807. Its default value is 0. The long data type is used
when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is
unlimited. It is recommended to use a float (instead of double) if you need to save memory in
large arrays of floating point numbers. The float data type should never be used for precise
values, such as currency. Its default value is 0.0F.
Example:
1. float f1 = 234.5f

Double Data Type


The double data type is a double-precision 64-bit IEEE 754 floating point. Its
value range is unlimited. The double data type is generally used for decimal
values just like float. The double data type also should never be used for
precise values, such as currency. Its default value is 0.0d.
Example:
1. double d1 = 12.3

Char Data Type


The char data type is a single 16-bit Unicode character. Its value-range lies
between '\u0000' (or 0) to '\uffff' (or 65,535 inclusive).The char data type is
used to store characters.
Example:
1. char letterA = 'A'

Why char uses 2 byte in java and what is \u0000


?
It is because java uses Unicode system not ASCII code system. The \u0000 is
the lowest range of Unicode system. To get detail explanation about Unicode
visit next page.

Literals in Java
In Java

, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals
of a given type are generally known as tokens
. In this section, we will discuss the term literals in Java.

Literals
In Java, literals are the constant values that appear directly in the program.
It can be assigned directly to a variable. Java has various types of literals.
The following figure represents a literal.

Types of Literals in Java


There are the majorly four types of literals in Java:

1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals

Integer literals are sequences of digits. There are three types of integer literals:

Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-) Note that between numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.

● Octal Integer: It is a combination of number have digits from 0 to 7 with a leading 0.


For example, 045, 026,
● Hexa-Decimal: The sequence of digits preceded by 0x or 0X is considered as
hexadecimal integers. It may also include a character from a to f or A to F that represents
numbers from 10 to 15, respectively. For example, 0xd, 0xf,

Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in
Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.

Real Literals

The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.

Backslash Literals

Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:

\n: It is used for a new line

\t: It is used for horizontal tab


\b: It is used for blank space

\v: It is used for vertical tab

\a: It is used for a small beep

\r: It is used for carriage return

Character Literals

A character literal is expressed as a character or an escape sequence, enclosed in a single quote


('') mark. It is always a type of char. For example, 'a', '%', '\u000d', etc.

String Literals

String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.

Floating Point Literals

The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.

Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.

Variable is a name of memory location. There are three types of variables in


java: local, instance and static.

There are two types of data types in Java: primitive and non-primitive.

Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
1. int data=50;//Here data is variable

Types of Variables
There are three types of variables in Java:

o local variable
o instance variable
o static variable
Local Variable

A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

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

It is called an instance variable because its value is instance-specific and is


not shared among instances.
3) Static variable

A variable that is declared as static is called a static variable. It cannot be


local. You can create a single copy of the static variable and share it among
all the instances of the class. Memory allocation for static variables happens
only once when the class is loaded in the memory.

Example to understand the types of variables in java


1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12. }//end of class

Wrapper classes in Java


The wrapper class in Java provides the mechanism to convert primitive into object and object
into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.

Use of Wrapper classes in Java


Java is an object-oriented programming language, so we need to deal with objects many times
like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where
we need to use the wrapper classes.

● Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
● Serialization: We need to convert the objects into streams to perform the serialization. If
we have a primitive value, we can convert it in objects through the wrapper classes.
● Synchronization: Java synchronization works with objects in Multithreading.
● java.util package: The java.util package provides the utility classes to deal with objects.
● Collection Framework: Java collection framework works with objects only. All classes
of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.

The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:

Primitive Wrapper
Type class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.

Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages

● Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
● Random access: We can get any data located at an index position.

Disadvantages

● Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.

Types of Array in java

There are two types of array.

● Single Dimensional Array


● Multidimensional Array

Single Dimensional Array in Java

Syntax to Declare an Array in Java

1. dataType[] arr; (or)


2. dataType []arr; (or)
3. dataType arr[];

Instantiation of an Array in Java

1. arrayRefVar=new datatype[size];

Example of Java Array

Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40; llo
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}

Output
10
20
70
40
50

OPERATORS
Programming in Computer Science requires some arithmetical or logical operations. In such
circumstances, we need operators to perform these tasks. Thus, an Operator is basically a symbol
or token, which performs arithmetical or logical operations and gives us meaningful result. The
values involved in the operation are called Operands.

Here is a basic Pictorial representation of Operators.


TYPES OF OPERATORS
There are three types of Operators in Java which are −

● Arithmetical Operators
● Relational Operators
● Logical Operators
● ARITHMETICAL OPERATORS
● The operators which are applied to perform arithmetical calculations in a program, are
known as Arithmetical operators. Some basic calculations like addition, subtraction,
multiplication, division, modulus are often used during programming. One can apply
arithmetic operators like +, -, *, / and % respectively to carry out these calculations. For
example, A + B, A – B, A % B are all examples of arithmetical operator usage.
● Do you know what Arithmetical Expressions are? A + B is considered an Arithmetical
Expression. Basically, an Arithmetical expression may contain variables, constants and
arithmetical operators together to produce a meaningful result. A + B, A – B, A % B are
all examples of arithmetical expressions.
● Now what happens if we assign an arithmetical expression to a variable? For example,
what do we call X = A + B? Is it an arithmetical expression or is it something else? Well
this is called an Arithmetical Statement. If an arithmetical expression is assigned to a
variable then it is known as Arithmetical Statement. Syntax of Arithmetical Statement is
− X = A + B, Y = A % B etc.
● Now we need to know who to write expression in Java Program.

EXPRESSIONS IN JAVA
When you write a program in Java, it is necessary to represent the arithmetical expressions into
Java expressions. Given below are few examples of how to illustrate a mathematical expression
in JAVA.
● Mathematical Expression: abc
Java Expression: a * b * c
● Mathematical Expression: ab + bc + ca
Java Expression: a * b + b * c + c * a
● Mathematical Expression: a2 + b2
Java Expression: a * a + b * b
● Mathematical Expression: (1/3)ab + (2/5)ba
Java Expression: 1.0/3.0 * a * b + 2.0/5.0 * b * a

Now there exist three different types of Arithmetical Operators. They are −

● Unary Operator
● Binary Operator
● Ternary Operator

Let us understand each of them individually.

UNARY OPERATOR

An Arithmetical operator, which is applied with a single operand is known as Unary Operator.
Example: +, -, ++, --, etc. Details of each types of operators are given below.

Unary (+) Operator

This operator is applied before the operand. It is just applied as a pointer to a variable which
results in the same value of a variable. Example: If a = 10, then +a will result in 10. If a = -10,
then +a will result in -10.

import java.io.*; // importing java.io package


public class UnaryTest { // class declaration
public static void main(String[] args) { // main function declaration

int number = 10; // initializing variable


System.out.println("Original Number = "+number); // displaying
original number
number = +number; // applying unary (+) operator
System.out.println("Updated Number = "+number); // displaying number
after applying unary (+) operator
}
}
Unary (-) Operator
This operator is applied before the operand, same as that of Unary (+) operator. Unary (-) reverts
the sign of an operand. Example: If a = 10, then –a will result in -10. If a = 0, then –a will result
in 0. If a = -10, then –a will result in 10.
Unary (++) Operator
This operator increases the value of an operand by one. Example: a = a + 1, by applying
increment operator it can be written as a++ or ++a.
Unary (--) Operator
This operator decreases the value of an operand by one. Example: a = a - 1, by applying
decrement operator it can be written as a-- or --a.
Prefix Operator (++a)
When increment or decrement operators are applied before the operant, it is known as prefix
operators. This operator works on the principle “CHANGE BEFORE ACTION”. It means the
value of the variable changes before the operation takes place.

Example − Increment Prefix Operator

a = 10;
a = ++a * 2;

Before the operation, value of a was 10. Then in the next arithmetical statement, ++a increases
a’s value by 1. So the new value of a is 11. Then the arithmetical operation a * 2 takes place,
after which value of a becomes 22.

Example: Decrement Prefix Operator

a = 10;
a = --a * 2;

Before the operation, value of a was 10. Then in the next arithmetical statement, --a decreases a’s
value by 1. So the new value of a is 9. Then the arithmetical operation a * 2 takes place, after
which value of a becomes 18.

Code − Prefix increment and decrement operator

import java.io.*; // importing java.io package


public class PrefixTest { // class declaration
public static void main(String[] args) { // main function declaration
int number = 10; // initializing variable
System.out.println("Original Number = "+number); // displaying original
number
++number; // applying increment perfix operator
System.out.println("Updated Number after increment = "+number); //
displaying number after increment
--number; // applying decrement prefix operator
System.out.println("Updated Number after decrement = "+number); //
displaying number after decrement
}
}

Postfix Operator (a++)

When increment or decrement operators are applied after the operant, it is known as postfix
operators. This operator works on the principle “CHANGE AFTER THE ACTION”. It means
the value of the variable changes after the operation takes place.

Example − Increment Postfix Operator

a = 10;
a = a++ * 2;

Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.

Example − Decrement Postfix Operator

a = 10;
a = a-- * 2;

Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.

BINARY OPERATOR

An arithmetic operator which deals with two operands, is known as Binary Arithmetic Operator.

Example

Addition (+): a = 10, b = 7, a + b = 17


Subtraction (-): a = 10, b = 7, a – b = 3
Multiplication (*): a = 10, b = 7, a * b = 70
Division (/): a = 10, b = 7, a / b = 1
Modulus (&): a = 10, b = 7, a & b = 3
TERNARY OPERATOR

Ternary Operators deal with three operands. It is also called conditional assignment statement
because the value assigned to a variable depends upon a logical expression.

Syntax: variable = (test expression)? Expression 1: Expression 2

Example: a = 10, b = 7;

Max = (a>b)? a:b;

Here, the value 10 is stored in Max as a>b is true.

Min = (b>a)? a:b;

Here, the value 7 is stored in Min as b>a is false.

Code: Ternary Operator Example

import java.io.*; // importing java.io package


public class TernaryTest { // class declaration
public static void main(String[] args) { // main function declaration
int a = 10, b = 7; // variable initialization
System.out.println("Value of a = "+a); // displaying value of a and b
System.out.println("Value of b = "+b);
int max = (a>b)? a:b; // here value of a will be stored in max as a>b is
true in this example
int min = (b>a)? a:b; // here value of b will be stored in min as b>a is
false in this example
System.out.println("Maximum of a and b = "+max);
System.out.println("Minimum of a and b = "+min);
}
}

Logical OPERATORS
Java uses logical operators AND (&&), OR (||) or NOT (!). These operators yield 1 or 0
depending upon the outcome of different expressions. The different types of logical operators
along with their format are as shown below −

Logical Symb
Syntax
Operators ol
(a > b) && (a >
AND &&
c)
(a == b) || (a ==
OR ||
c)
NOT ! !(a == b)
Precedence of logical operators is NOT (!), AND (&&) and OR (||) i.e., if a statement contains
all the three logical operators then NOT operator will perform first. Here are the details of each
logical operator.

Logical NOT (!)

Logical NOT operator is applied when you want to revert the outcome of an expression. It is a
unary operator because it uses a single operand.

Example

!(8 > 3) − False, because 8>3 is True, !(3 > 8) − True, because 3>8 is False.

public class LogicalNOT { // public class declaration


public static void main(String[] args) { // main function declaration
int a = 10, b = 5; // variable initialization
if (!(a == b)){ // if checking whether a is not equal to b
System.out.println("a is not equal to b"); // Printing output if a
and b aren't equal
} else {
}
}
}

Output

a is not equal to b

Logical OR (||)

This operator is used to combine two conditional expressions. It will result in true if either of two
conditions (expressions) is true otherwise false.

Example

(5 > 4) || (8 > 12) : True, because 5>4 is True, (5 < 4) || (8 > 12) : False, because both the
expressions are false.

public class LogicalOR { // public class declaration


public static void main(String[] args){ // main function declaration
int a = 10, b = 5, c = 13; // variable initialization
if ((a > b) || (a > c)){ // if checking whether a is maximum element or
not
System.out.println("Max Element is "+ a); // Printing output
}
else if ((b > a) || (b > c)) { // if checking whether b is maximum
element or not
System.out.println("Max Element is "+ b); // Printing output
}
else if ((c > a) || (c > b)) { // if checking whether c is maximum
element or not
System.out.println("Max Element is "+ c); // Printing output
}
}
}

Output

Max Element is 10

Logical AND (&&)

The AND operator results in true if both the expressions (comprising its operands) are true.

Example

(5 > 3) && (4 > 3) : True, because both the expressions are True, ( 5 > 3) && ( 3 > 5) : False,
because 3 > 5 is False.

public class LogicalAND { // public class declaration


public static void main(String[] args){ // main function declaration
int a = 10, b = 5, c = 13; // variable initialization
if ((a > b) && (a > c)){ // if checking whether a is maximum element or
not
System.out.println("Max Element is "+ a); // Printing output
}
else if ((b > a) && (b > c)) { // if checking whether b is maximum
element or not
System.out.println("Max Element is "+ b); // Printing output
}
else if ((c > a) && (c > b)){ // if checking whether c is maximum
element or not
System.out.println("Max Element is "+ c); // Printing output
}
}
}

Output

Max Element is 13

Java Control Statements | Control Flow in


Java
Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java provides statements that can be used
to control the flow of Java code. Such statements are called control flow statements. It is one of
the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:

As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.

1) If Statement:

In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

Let's understand the if-statements one by one.

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

1. if(condition) {
2. statement 1; //executes when condition is true
3. }

Consider the following example in which we have used the if statement in the java code.

Student.java

Student.java

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
10.
11.
12. Output:
13. x + y is greater than 20

2) if-else statement

The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.

Syntax:

1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }

Student.java

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }

x + y is greater than 20

3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax of if-else-if statement is given below.

1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }

Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
Syntax of Nested if-statement is given below.

Switch Statement:

In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.

● The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
● Cases cannot be duplicate
● Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
● Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
● While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.

Student.java

1. public class Student implements Cloneable {


2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }

Loop Statements

In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Let's understand the loop statements one by one.

Java for loop

In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }
4. public class Calculattion {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. int sum = 0;
8. for(int j = 1; j<=10; j++) {
9. sum = sum + j;
10. }
11. System.out.println("The sum of first 10 natural numbers is " + sum);
12. }
13. }

Output:

The sum of first 10 natural numbers is 55

Java for-each loop

Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }
4. public class Calculation {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. String[] names = {"Java","C","C++","Python","JavaScript"};
8. System.out.println("Printing the content of the array names:\n");
9. for(String name:names) {
10. System.out.println(name);
11. }
12. }
13. }

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However, if
we don't know the number of iterations in advance, it is recommended to use a while loop.
Unlike for loop, the initialization and increment/decrement doesn't take place inside the loop
statement in while loop.
It is also known as the entry-controlled loop since the condition is checked at the start of the
loop. If the condition is true, then the loop body will be executed; otherwise, the statements after
the loop will be executed.
The syntax of the while loop is given below

Java do-while loop

The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.

It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.

Jump Statements

Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.

Java break statement

As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

BreakExample.java

1. public class BreakExample {


2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5. for(int i = 0; i<= 10; i++) {
6. System.out.println(i);
7. if(i==6) {
8. break;
9. }
10. }
11. }
12. }
Output:

0
1
2
3
4
5
6

Java continue statement

Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.

Objects and Classes in Java


An object in Java is the physical as well as a logical entity, whereas, a class in Java is a logical entity only.

An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.

An object has three characteristics:

● State: represents the data (value) of an object.


● Behavior: represents the behavior (functionality) of an object such as deposit, withdraw,
etc.
● Identity: An object identity is typically implemented via a unique ID. The value of the
ID is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

● An object is a real-world entity.


● An object is a runtime entity.
● The object is an entity which has state and behavior.
● The object is an instance of a class.

What is a class in Java

A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:

● Fields
● Methods
● Constructors
● Blocks
● Nested class and interface

Syntax to declare a class:

1. class <class_name>{
2. field;
3. method;
4. }

Instance variable in Java

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

Method in Java

In Java, a method is like a function which is used to expose the behavior of an object.

Advantage of Method

● Code Reusability
● Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.

Here, we are creating a main() method inside the class.

File: Student.java

1. //Java Program to illustrate how to define a class and fields


2. //Defining a Student class.
3. class Student{
4. //defining fields
5. int id;//field or data member or instance variable
6. String name;
7. //creating main method inside the Student class
8. public static void main(String args[]){
9. //Creating an object or instance
10. Student s1=new Student();//creating an object of Student
11. //Printing values of the object
12. System.out.println(s1.id);//accessing member through reference variable
13. System.out.println(s1.name);
14. }
15. }

Output:

0
null

3 Ways to initialize object


There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor
4. 1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.

5. class Student{
6. int id;
7. String name;
8. }
9. class TestStudent2{
10. public static void main(String args[]){
11. Student s1=new Student();
12. s1.id=101;
13. s1.name="Sonoo";
14. System.out.println(s1.id+" "+s1.name);//printing members with a white space
15. }
16. }

Output:

101 Sonoo
Class Modifiers in java
There are two types of modifiers in Java: access modifiers and 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:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. 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.
3. 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.
4. 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.

1) Private

The private access modifier is accessible only within the class.

Simple example of private access modifier


1. 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 theclass A{
2. private int data=40;
3. private void msg(){System.out.println("Hello java");}
4. }
5.
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }

re is a 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:

1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }

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.

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.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }

1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }

Java Anonymous inner class


Java anonymous inner class 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.
In simple words, a class that has no name is known as an anonymous inner class in Java. It
should be used if you have to override a method of class or interface. Java Anonymous inner
class can be created in two ways:

1. Class (may be abstract or concrete).


2. Interface

Java anonymous inner class example using class


TestAnonymousInner.java

1. abstract class Person{


2. abstract void eat();
3. }
4. class TestAnonymousInner{
5. public static void main(String args[]){
6. Person p=new Person(){
7. void eat(){System.out.println("nice fruits");}
8. };
9. p.eat();
10. }
11. }

Output:
nice fruits

1. A class is created, but its name is decided by the compiler, which extends the Person
class and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable
of Person type.

Internal class generated by the compiler

1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }

Java anonymous inner class example using interface


1. interface Eatable{
2. void eat();
3. }
4. class TestAnnonymousInner1{
5. public static void main(String args[]){
6. Eatable e=new Eatable(){
7. public void eat(){System.out.println("nice fruits");}
8. };
9. e.eat();
10. }
11. }

12. Abstract class 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).

Abstraction in Java

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 in Java

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

● An abstract class must be declared with an abstract keyword.


● It can have abstract and non-abstract methods.
● It cannot be instantiated.
● It can have constructors and static methods also.
● It can have final methods which will force the subclass not to change the body of the method.
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

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. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java

● For Method Overriding (so runtime polymorphism can be achieved).


● For Code Reusability.
● Class: A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created.
● Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called
a derived class, extended class, or child class.
● Super Class/Parent Class: Superclass is the class from where a subclass inherits the
features. It is also called a base class or a parent class.
● Reusability: As the name specifies, reusability is a mechanism which facilitates you to
reuse the fields and methods of the existing class when you create a new class. You can
use the same fields and methods already defined in the previous class.

The syntax of Java Inheritance

1. class Subclass-name extends Superclass-name


2. {
3. //methods and fields
4. }

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.

1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }

output

Programmer salary is:40000.0


Bonus of programmer is:10000

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}

Output:

barking...
eating.

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal
class, so there is a multilevel inheritance.

File: TestInheritance2.java

1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}

Output:

weeping...
barking...
eating..

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the
example given below, Dog and Cat classes inherits the Animal class, so there is hierarchical
inheritance.

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to
handle the runtime errors so that the normal flow of the application can be
maintained.
In this tutorial, we will learn about Java exceptions, it's types, and the
difference between checked and unchecked exceptions.

What is Exception in Java?


Dictionary Meaning: Exception is an abnormal condition.
In Java, an exception is an event that disrupts the normal flow of the
program. It is an object which is thrown at runtime.

What is Exception Handling?


Exception Handling is a mechanism to handle runtime errors such as
ClassNotFoundException, IOException, SQLException, RemoteException, etc.

Advantage of Exception Handling

The core advantage of exception handling is to maintain the normal flow


of the application. An exception normally disrupts the normal flow of the
application; that is why we need to handle exceptions. Let's consider a
scenario:

1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;

Suppose there are 10 statements in a Java program and an exception occurs at


statement 5; the rest of the code will not be executed, i.e., statements 6 to 10 will
not be executed. However, when we perform exception handling, the rest of the
statements will be executed. That is why we use exception handling in Java.

Difference between throw and throws in Java


The throw and throws is the concept of exception handling where the throw keyword throw the
exception explicitly from a method or a block of code whereas the throws keyword is used in
signature of the method.

There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:

S
r.
Basis of Differences throw throws
n
o.
Java throws keyword is used
Java throw keyword is
in the method signature to
used throw an exception
declare an exception which
1. Definition explicitly in the code,
might be thrown by the
inside the function or the
function while the execution
block of code.
of the code.
Using throws keyword,
Type of exception Using
we can declare both
throw keyword, we can only
checked and unchecked
propagate unchecked
2. exceptions. However, the
exception i.e., the checked
throws keyword can be
exception cannot be
used to propagate checked
propagated using throw only.
exceptions only.
The throw keyword is The throws keyword is
3. Syntax followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.
throw is used within the throws is used with the
4. Declaration
method. method signature.
We can declare multiple
We are allowed to throw exceptions using throws
only one exception at a keyword that can be thrown
5. Internal implementation
time i.e. we cannot throw by the method. For example,
multiple exceptions. main() throws IOException,
SQLException.

Java throw Example


TestThrow.java
1. public class TestThrow {
2. //defining a method
3. public static void checkNum(int num) {
4. if (num < 1) {
5. throw new ArithmeticException("\nNumber is negative, cannot calculate square")
;
6. }
7. else {
8. System.out.println("Square of " + num + " is " + (num*num));
9. }
10. }
11. //main method
12. public static void main(String[] args) {
13. TestThrow obj = new TestThrow();
14. obj.checkNum(-3);
15. System.out.println("Rest of the code..");
16. }
17. }

Output

Java Custom Exception


In Java, we can create our own exceptions that are derived classes of the Exception class.
Creating our own Exception is known as custom exception or user-defined exception. Basically,
Java custom exceptions are used to customize the exception according to user need.

Consider the example 1 in which InvalidAgeException class extends the Exception class.

Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.

In this section, we will learn how custom exceptions are implemented and used in Java
programs.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.

Following are few of the reasons to use custom exceptions:

● To catch and provide specific treatment to a subset of existing Java exceptions.


● Business logic exceptions: These are the exceptions related to business logic and
workflow. It is useful for the application users or the developers to understand the exact
problem.

In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.

Consider the following example, where we create a custom exception named


WrongFileNameException:

1. public class WrongFileNameException extends Exception {


2. public WrongFileNameException(String errorMessage) {
3. super(errorMessage);
4. }
5. }

Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface

The Collection in Java is a framework that provides an architecture to store


and manipulate the group of objects.

Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.

Java Collection means a single unit of objects. Java Collection framework


provides many interfaces (Set, List, Queue, Deque) and classes (ArrayList,
Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).

What is Collection in Java


A Collection represents a single unit of objects, i.e., a group.

What is a framework in Java


o It provides readymade architecture.
o It represents a set of classes and interfaces.
o It is optional.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:

1. Interfaces and its implementations, i.e., classes


2. Algorithm

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:

No Method Description
.

1 public boolean add(E e) It is used to insert an element in this collection.


2 public boolean It is used to insert the specified collectio
addAll(Collection<? extends E> elements in the invoking collection.
c)

3 public boolean remove(Object It is used to delete an element from th


element) collection.

4 public boolean It is used to delete all the elements of th


removeAll(Collection<?> c) specified collection from the invoking collection

5 default boolean It is used to delete all the elements of th


removeIf(Predicate<? super E> collection that satisfy the specified predicate.
filter)

6 public boolean It is used to delete all the elements of invokin


retainAll(Collection<?> c) collection except the specified collection.

7 public int size() It returns the total number of elements in th


collection.

8 public void clear() It removes the total number of elements from


the collection.

9 public boolean contains(Object It is used to search an element.


element)

10 public boolean It is used to search the specified collection i


containsAll(Collection<?> c) the collection.

11 public Iterator iterator() It returns an iterator.

12 public Object[] toArray() It converts collection into array.

13 public <T> T[] toArray(T[] a) It converts collection into array. Here, th


runtime type of the returned array is that of th
specified array.

14 public boolean isEmpty() It checks if collection is empty.

15 default Stream<E> It returns a possibly parallel Stream with th


parallelStream() collection as its source.

16 default Stream<E> stream() It returns a sequential Stream with th


collection as its source.

17 default Spliterator<E> It generates a Spliterator over the specifie


spliterator() elements in the collection.

18 public boolean equals(Object It matches two collections.


element)

19 public int hashCode() It returns the hash code number of th


collection.

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:

No Method Description
.

1 public boolean It returns true if the iterator has more elements otherwise
hasNext() returns false.

2 public Object next() It returns the element and moves the cursor pointer to th
next element.

3 public void remove() It removes the last elements returned by the iterator. It i
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.

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();

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. }

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.

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

Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH,
SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and AUTUMN
or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
According to the Java naming conventions, we should have all constants in
capital letters. So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants
(a variable that does not change). The Java enum constants are static and
final implicitly. It is available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data
type (also known as Enumerated Data Type) is used to define an enum in
Java. Unlike C/C++, enum in Java is more powerful. Here, we can define an
enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other
class, but it can implement many interfaces. We can have fields,
constructors, methods, and main methods in Java enum.

Set in Java
The set interface is present in java.util package and extends the Collection
interface. It is an unordered collection of objects in which duplicate values cannot
be stored. It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Collection interface and adds a feature
that restricts the insertion of the duplicate elements. There are two interfaces that
extend the set implementation namely SortedSet and NavigableSet.

In the above image, the navigable set extends the sorted set interface. Since a
set doesn’t retain the insertion order, the navigable set interface provides the
implementation to navigate through the Set. The class which implements the
navigable set is a TreeSet which is an implementation of a self-balancing tree.
Therefore, this interface provides us with a way to navigate through this tree.
public interface Set extends Collection
Creating Set Objects
Since Set is an interface, objects cannot be created of the typeset. We always
need a class that extends this list in order to create an object. And also, after the
introduction of Generics in Java 1.5, it is possible to restrict the type of object that
can be stored in the Set. This type-safe set can be defined as:
// Obj is the type of the object to be stored in Set
Set<Obj> set = new HashSet<Obj> ();

Java List
List in Java provides the facility to maintain the ordered collection. It
contains the index-based methods to insert, update, delete and search the
elements. It can have the duplicate elements also. We can also store the null
elements in the list.

The List interface is found in the java.util package and inherits the Collection
interface. It is a factory of ListIterator interface. Through the ListIterator, we
can iterate the list in forward and backward directions. The implementation
classes of List interface are ArrayList, LinkedList, Stack and Vector. The
ArrayList and LinkedList are widely used in Java programming. The Vector
class is deprecated since Java 5.

List Interface declaration


1. public interface List<E> extends Collection<E>

Map Interface in Java


In Java, Map Interface is present in java.util package represents a mapping
between a key and a value. Java Map interface is not a subtype of the Collection
interface. Therefore it behaves a bit differently from the rest of the collection
types. A map contains unique keys.

Geeks, the brainstormer should have been why and when to use Maps.
Maps are perfect to use for key-value association mapping such as dictionaries.
The maps are used to perform lookups by keys or when someone wants to
retrieve and update elements by keys. Some common scenarios are as follows:
● A map of error codes and their descriptions.
● A map of zip codes and cities.
● A map of managers and employees. Each manager (key) is associated with a
list of employees (value) he manages.
● A map of classes and students. Each class (key) is associated with a list of
students (value).

Creating Map Objects


Since Map is an interface, objects cannot be created of the type map. We always
need a class that extends this map in order to create an object. And also, after
the introduction of Generics in Java 1.5, it is possible to restrict the type of object
that can be stored in the Map.
Syntax: Defining Type-safe Map
Map hm = new HashMap();
// Obj is the type of the object to be stored in Map

Iterators in Java
A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a
Collection or Stream object’s elements one by one. In this article, we will learn
about Java Iterators and it’s working.
Types of Cursors in Java
There are three cursors in Java as mentioned below:
1. Iterator
2. Enumeration
3. ListIterator

1. Iterator
Iterators in Java are used in the Collection framework to retrieve elements one by
one. It is a universal iterator as we can apply it to any Collection object. By using
Iterator, we can perform both read and remove operations. It is an improved
version of Enumeration with the additional functionality of removing an element.

Iterator must be used whenever we want to enumerate elements in all Collection


framework implemented interfaces like Set, List, Queue, Deque, and all
implemented classes of Map interface. The iterator is the only cursor available
for the entire collection framework. An iterator object can be created by calling
the iterator() method present in the Collection interface.
Syntax
Iterator itr = c.iterator();

Methods of Iterator Interface in Java

The iterator interface defines three methods as listed below:


1. hasNext(): Returns true if the iteration has more elements.
public boolean hasNext();
2. next(): Returns the next element in the iteration. It
throws NoSuchElementException if no more element is present.
public Object next();
3. remove(): Removes the next element in the iteration. This method can be
called only once per call to next().
public void remove();
Note: remove() method can throw two exceptions namely as follows:
● UnsupportedOperationException : If the remove operation is not supported
by this iterator
● IllegalStateException : If the next method has not yet been called, or the
remove method has already been called after the last call to the next method.

You might also like