0% found this document useful (0 votes)
12 views96 pages

3 - Java Notes Full

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, designed for a wide range of applications. It features simplicity, robustness, security, and supports object-oriented programming, making it suitable for various development needs. Key components include the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with various operators, control statements, and data types.

Uploaded by

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

3 - Java Notes Full

Java is a high-level, platform-independent programming language developed by Sun Microsystems in 1995, designed for a wide range of applications. It features simplicity, robustness, security, and supports object-oriented programming, making it suitable for various development needs. Key components include the Java Virtual Machine (JVM), Java Runtime Environment (JRE), and Java Development Kit (JDK), along with various operators, control statements, and data types.

Uploaded by

meghavamaravalli
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

JAVA

What is Java?

• Java is a high-level programming language that was first released in 1995 by Sun
Microsystems (now owned by Oracle Corporation).
• It is designed to be portable and platform-independent, meaning that Java code can
run on any computer or device that has a Java Virtual Machine (JVM) installed,
regardless of the underlying hardware or operating system.
• Java is commonly used for developing a wide range of applications, including web and
mobile applications, desktop software, games, and enterprise systems.

Who Developed Java?

• Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in
the year 1995. James Gosling is known as the father of Java.

What are the features of Java?

• Simple and Familiar: Java is designed to be easy to learn and use for developers, with
a syntax similar to C++. It also provides a standard library of pre-built functions to help
programmers perform common tasks more easily.
• Compiled and Interpreted: Java code is first compiled into an intermediate language
called bytecode, which can then be executed by a Java Virtual Machine (JVM) on any
platform that supports Java.
• Platform Independent: Java programs can run on any platform that has a Java Virtual
Machine (JVM) installed, regardless of the underlying hardware and operating system.
• Portable: Java code can be easily moved from one platform to another, as long as a
compatible JVM is available on the target platform.
• Architectural Neutral: Java is designed to be architecture-neutral, meaning that it can
run on any hardware architecture that has a compatible JVM.
• Object-Oriented: Java is based on the object-oriented programming paradigm, which
emphasizes the use of classes and objects to encapsulate data and behavior.
• Robust: Java is designed to be robust and able to handle errors and exceptions
gracefully, with features such as automatic memory management and strong type
checking.
• Secure: Java includes built-in security features, such as a bytecode verifier and a
security manager, to help prevent malicious code from executing on a system.
• Distributed: Java includes features for building distributed systems, such as remote
method invocation (RMI) and the Java Messaging Service (JMS).
• Multi-threaded and Interactive: Java supports multithreading, allowing multiple
threads to execute concurrently within a single program. It also provides a graphical
user interface (GUI) toolkit for building interactive applications.
• High Performance: Java is designed to be highly performant, with features such as
just-in-time (JIT) compilation and bytecode optimization.
• Dynamic and Extensible: Java includes features for dynamic class loading and
reflection, allowing programs to modify their behavior at runtime, and for building
extensible frameworks and libraries.

History of Java

• Java was developed in 1991 by a team of Sun engineers called the Green Team.
• Originally designed for small, embedded systems, Java was initially called "Greentalk"
and had the file extension .gt.
• In 1995, Java was renamed from "Oak" and developed as a programming language for
general-purpose use.

Java Versions

Term Full Form Physical Purpose


Existence

JVM Java Virtual Machine No Provides a runtime environment


for executing Java bytecode
JRE Java Runtime Yes Implements the JVM, and contains
Environment libraries and other files used at
runtime

JDK Java Development Kit Yes Includes the JRE, as well as


development tools such as a
compiler, debugger, and other
utilities

Simple Program of Java


class Simple{
public static void main(String args[]){
[Link]("Hello Java");
}
}

What is a Comment?
Comments in Java are the statements that are not executed by the compiler and interpreter.

Single-line Comments
• Single-line comments start with two forward slashes (//).
• Any text between // and the end of the line is ignored by Java (will not be executed).

Multi-line Comments
• Multi-line comments start with /* and ends with */.
• Any text between /* and */ will be ignored by Java.

What is a Variable?
• Variable is a name of memory location. It is used to store values.
• It is a combination of "vary + able" which means its value can be changed.

Rules for defining a variable in Java:


• The name of a variable must begin with a letter, underscore (_), or dollar sign ($). It
cannot begin with a number.
• The name of a variable can contain letters, numbers, underscores (_), or dollar signs
($). It cannot contain spaces or special characters such as !, @, #, %, etc.
• Java is case sensitive, so uppercase and lowercase letters are considered different.
Therefore, the variable names "name" and "Name" are different.
• The name of a variable should be descriptive and meaningful, so that other
programmers can understand the purpose of the variable in the code.
• Java has reserved keywords that cannot be used as variable names, such as "int",
"double", "if", "while", "class", etc.

What is a Data Type?


Data types represent the different values to be stored in the variable.

There are two types of data types:

o Primitive data types


o Non-primitive data types

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

What are Java Identifiers?


• Identifiers are the names of variables, methods, classes, packages and interfaces.

Rules of Identifiers

What are Java Keywords

• Java keywords are also known as reserved words. Keywords are particular words
that act as a key to a code. These are predefined words by Java so they cannot be
used as a variable or object name or class name.
What is a Token in Java
• Java Tokens are the smallest individual building block or smallest unit of a
Java program

What is Type Casting


• In Java, type casting is a method or process that converts a data type into
another data type in both ways manually and automatically.
• The automatic conversion is done by the compiler and manual conversion
performed by the programmer.
Java Variable Example: Narrowing (Typecasting)

class Simple{
public static void main(String[] args){
float f=10.5f;
//int a=f; //Compile time error
int a=(int)f;
[Link](f);
[Link](a);
}}
Output:
10.5
10

What is an Operator
• Operator in Java is a symbol that is used to perform operations. For example:
+, -, *, / etc.

1. Java Arithmetic Operators ( +, -, *, /, %)


Arithmetic operators are used to perform arithmetic operations on variables and data.
public class Main {
public static void main(String[] args) {
int x = 10;
int y = 5;

// Addition operator
int sum = x + y;
[Link]("Sum = " + sum);

// Subtraction operator
int difference = x - y;
[Link]("Difference = " + difference);
// Multiplication operator
int product = x * y;
[Link]("Product = " + product);

// Division operator
int quotient = x / y;
[Link]("Quotient = " + quotient);

// Modulus operator
int remainder = x % y;
[Link]("Remainder = " + remainder);
}
}
Output
Sum = 15
Difference = 5
Product = 50
Quotient = 2
Remainder = 0

Note: The % operator is mainly used with integers.

Java Assignment Operators ( = , +=, -=, *=, /=, %=)


Assignment operators are used in Java to assign values to variables.
class Main {
public static void main(String[] args) {

int a = 4,b;

b = a;
[Link]("var using =: " + b
b += a;
[Link]("var using +=: " + var);
b *= a;
[Link]("var using *=: " + var); }
}
Output
var using =: 4
var using +=: 8
var using *=: 32

3. Java Relational Operators (<, <=, >, >=, ==, !=)


Relational operators are used to check the relationship between two operands.
class Main {
public static void main(String[] args) {

int a = 7, b = 11;

[Link](a == b); // false


[Link](a != b); // true
[Link](a > b); // false
[Link](a < b); // true
[Link](a >= b); // false
[Link](a <= b); // true
}
}
Note: Relational operators are used in decision making and loops.

Java Logical Operators (&&, ||, !)


Logical operators are used to check whether an expression is true or false. They are used in
decision making.
class Main {
public static void main(String[] args) {

// && operator
[Link]((5 > 3) && (8 > 5)); // true
[Link]((5 > 3) && (8 < 5)); // false

// || operator
[Link]((5 < 3) || (8 > 5)); // true
[Link]((5 > 3) || (8 < 5)); // true
[Link]((5 < 3) || (8 < 5)); // false

// ! operator
[Link](!(5 == 3)); // true
[Link](!(5 > 3)); // false
}
}

Java Increment and Decrement operators (++, --)


Java also provides increment and decrement operators: ++ and -- respectively. ++ increases
the value of the operand by 1, while -- decrease it by 1.
class Main {
public static void main(String[] args) {

int a = 12, b = 12;


int result1, result2;
// increment operator
result1 = ++a;
[Link]("After increment: " + result1);

[Link]("Value of b: " + b);

// decrement operator
result2 = --b;
[Link]("After decrement: " + result2);
}
}
Output
Value of a: 12
After increment: 13
Value of b: 12
After decrement: 11

Java instanceof Operator


The instanceof operator checks whether an object is an instanceof a particular class. For
example,
class Main {
public static void main(String[] args) {

String str = "Programiz";


boolean result;

// checks if str is an instance of


// the String class
result = str instanceof String;
[Link]("Is str an object of String? " + result);
}
}
Output
Is str an object of String? true

Here, str is an instance of the String class. Hence, the instanceof operator returns true. To
learn more, visit Java instanceof.

Java Ternary Operator


The ternary operator (conditional operator) is shorthand for the if-then-else statement. For
example,
variable = Expression ? expression1 : expression2
class Java {
public static void main(String[] args) {

int a=1;
String result;

// ternary operator
result = (a==1) ? 1 : 0;
[Link](result);
}
}
Output
1

Control Statements

Java If-else Statements

The Java if statement is used to test the condition. It checks boolean


condition: true or false. There are various types of if statement in java.

• if statement
• if-else statement
• if-else-if ladder
• nested if statement
• Switch Case
Java IF Statement

The Java if statement tests the condition. It executes the if block if condition is true.

import [Link];

public class Main


{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
}
}
Output:
Enter a value
5
a is less than 10

Java IF-else Statement

The Java if-else statement also tests the condition. It executes the if block if condition is
true otherwise else block is executed.

import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
else
[Link](" a is not less than 10");
}
}
Output:
Enter a value
15
a is not less than 10

Java IF-else-if ladder Statement

The if-else-if ladder statement executes one condition from multiple statements.

import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("Enter a value");
int a=[Link]();
if(a<10)
[Link]("a is less than 10");
else if(a>10)
[Link](" a is greater than 10");
else
[Link]("a is equal to 10");
}
}

import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("Enter a value");
int a=[Link]();
if(a==1)
[Link]("one");
else if(a==2)
[Link](" two");
else if(a==3)
[Link]("three");
else
[Link]("wrong choice");
}
}
Output:
Enter a value
3
three

Java Switch Statement

The Java switch statement executes one statement from multiple conditions. It is like if-
else-if ladder statement.

import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);

[Link]("Enter a value");
int a=[Link]();
switch(a)
{
case 1:
[Link]("one");
break;
case 2:
[Link]("two");
break;
case 3:
[Link]("three");
break;
default:
[Link]("wrong choice");
break;
}
}
}
Output:
Enter a value
6
wrong choice

Java Switch Statement is fall-through

The java switch statement is fall-through. It means it executes all statement after first
match if break statement is not used with switch cases.
Java For Loop

The Java for loop is used to iterate a part of the program several times. If the number of
iteration is fixed, it is recommended to use for loop.

There are three types of for loop in java.

1. Simple For Loop


2. For-each or Enhanced For Loop
3. Labeled For Loop

Java Simple For Loop

The simple for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.

Example:
public class Main {
public static void main(String[] args) {
for(int i=1;i<=5;i++){
[Link](i);
}
}
}
Output:
1
2
3
4
5

public class Main


{
public static void main(String[] args) {
int i;
for(i=10;i>=1;i--)
[Link](i);
}
}
Java For-each Loop

The for-each loop is used to traverse array or collection in java. It is easier to use than
simple for loop because we don't need to increment value and use subscript notation.

It works on elements basis not index. It returns element one by one in the defined
variable.

Syntax:
for(Type var:array){
//code to be executed
}

Example:
public class ForEachExample {
public static void main(String[] args) {
int arr[]={12,23,44,56,78};
for(int i:arr){
[Link](i);
}
}
}

Output:
12
23
44
56
78

Java Labeled For Loop

We can have name of each for loop. To do so, we use label before the for loop. It is useful
if we have nested for loop so that we can break/continue specific for loop.

Normally, break and continue keywords breaks/continues the inner most for loop only.

Syntax:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
Example:
public class LabeledForExample {
public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break aa;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21

If you use break bb;, it will break inner loop only which is the default behavior of any
loop.

public class LabeledForExample2 {


public static void main(String[] args) {
aa:
for(int i=1;i<=3;i++){
bb:
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break bb;
}
[Link](i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33
Java While Loop

The Java while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed, it is recommended to use while loop.

Syntax:
while(condition){
//code to be executed
}

Example:
public class WhileExample {
public static void main(String[] args) {
int i=1;
while(i<=10){
[Link](i);
i++;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

public class Main


{
public static void main(String[] args) {
int i=10;
while(i>=1){
[Link](i);
i--;
}
}
}
Java do-while Loop

The Java do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended
to use do-while loop.

The Java do-while loop is executed at least once because condition is checked after loop
body.

Syntax:
do{
//code to be executed
}while(condition);

Example:
public class DoWhileExample {
public static void main(String[] args) {
int i=1;
do{
[Link](i);
i++;
}while(i<=5);
}
}

Output:
1
2
3
4
5

Java Break Statement

The Java break is used to break loop or switch statement. It breaks the current flow of the
program at specified condition. In case of inner loop, it breaks only inner loop.

public class BreakExample {


public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5)
break;
[Link](i);
}
}
}
Output:
1
2
3
4

Java Continue Statement

The Java continue statement is used to continue loop. It continues the current flow of the
program and skips the remaining code at specified condition. In case of inner loop, it
continues only inner loop.

Example:
public class ContinueExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
if(i==5){
continue;
[Link](i);
}
}
}
Output:
1
2
3
4
6
7
8
9
10

JAVA ARRAY
• Array is a collection of similar type of elements that have contiguous memory
location.
• Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
Advantage of Java Array
o Code Optimization: It makes the code optimized, we can retrieve or sort the data
easily.
o Random access: We can get any data located at any index position.

Disadvantage of Java Array


o Size Limit: We can store only 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.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Single Dimensional Array in java


Creating, Initializing, and Accessing an Array

An array declaration has two components: the type and the name.

Syntax to Declare an Array in java

dataType[] arr;
(or)
dataType []arr;
(or)
dataType arr[];

Instantiating an Array in Java

int a[]; //declaring array


a = new int[20]; // allocating memory to array
OR
int[] a = new int[20]; // combining both statements in one
Array Literal
In a situation, where the size of the array and variables of array are already known, array
literals can be used.
int[] a = new int[]{ 1,2,3,4,5,6,7,8,9,10 };
int[] a = { 1,2,3,4,5,6,7,8,9,10 };
// Declaring array literal

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 < [Link]; i++)
[Link]("Element at index " + i + " : "+ arr[i]);

Example of single dimensional java array


public class Main
{
public static void main(String[] args) {
int i;
int a[]=new int[]{2,5,7,5,4};
[Link]("values are ");
for(i=0;i<5;i++)
[Link](a[i]);
}
}

public class Main


{
public static void main(String[] args) {
int i;
int a[]=new int[]{2,5,7,5,4};
[Link]("values are ");
for(i=0;i<[Link];i++)
[Link](a[i]);
}
}
import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
int i;
int a[]=new int[10];
[Link]("enter 4 values ");
for( i=0;i<4;i++)
a[i]=[Link]();

[Link]("values are ");


for(i=0;i<4;i++)
[Link](a[i]);
}
}

Multidimensional array in java

In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in java


dataType[][] arrayRefVar; (or)
dataType [][]arrayRefVar; (or)
dataType arrayRefVar[][]; (or)
dataType []arrayRefVar[];

Example to instantiate Multidimensional Array in java


int[][] arr=new int[3][3];//3 row and 3 column

Example to initialize Multidimensional Array in java


arr[0][0]=1;
arr[0][1]=2;
arr[0][2]=3;
arr[1][0]=4;
arr[1][1]=5;
arr[1][2]=6;
arr[2][0]=7;
arr[2][1]=8;
arr[2][2]=9;
Example of Multidimensional java array
class Testarray3{
public static void main(String args[]){

//declaring and initializing 2D array


int arr[][]={{1,2,3},{2,4,5},{4,4,5}};

//printing 2D array
for(int i=0;i<3;i++){
for(int j=0;j<3;j++){
[Link](arr[i][j]+" ");
}
[Link]();
}

}}
Output:
123
245
445

JAVA STRING METHODS

public class Main{


public static void main(String args[]){
String s1="hello";
String s2="whatsup";
[Link]("string length is: "+[Link]());
[Link]("string length is: "+[Link]());

s1=[Link](" how are you");


[Link](s1);

[Link]([Link]());
[Link]([Link]());

String s1upper=[Link]();
[Link](s1upper);

String s3="HELLO HOW Are You?";


String s1lower=[Link]();
[Link](s1lower);

Output:
string length is: 5
string length is: 7
hello how are you
false
false
HELLO HOW ARE YOU
hello how are you?

Java String length():

The Java String length() method tells the length of the string. It returns count of total number
of characters present in the String.

Java String concat() :

The Java String concat() method combines a specific string at the end of another string and
ultimately returns a combined string. It is like appending another string.

Java String IsEmpty() :

This method checks whether the String contains anything or not. If the java String is Empty, it
returns true else false.

Java String Trim() :

The java string trim() method removes the leading and trailing spaces. It checks the unicode
value of space character (‘u0020’) before and after the string. If it exists, then removes the
spaces and return the omitted string.

Java String toLowerCase() :

The java string toLowerCase() method converts all the characters of the String to lower case.

Java String toUpperCase() :

The Java String toUpperCase() method converts all the characters of the String to upper case.
Java String ValueOf():

This method converts different types of values into [Link] this method, you can convert
int to string, long to string, Boolean to string, character to string, float to string, double to
string, object to string and char array to string. The signature or syntax of string valueOf()
method is given below:
public static String valueOf(boolean b)
public static String valueOf(char c)
public static String valueOf(char[] c)
public static String valueOf(int i)
public static String valueOf(long l)
public static String valueOf(float f)
public static String valueOf(double d)
public static String valueOf(Object o)

public class StringValueOfExample{


public static void main(String args[]){
int value=20;
String s1=[Link](value);
[Link](s1+17); //concatenating string with 20
}}
In the above code, it concatenates the Java String and gives the output – 2017.

Java String replace():


The Java String replace() method returns a string, replacing all the old characters or
CharSequence to new characters. There are 2 ways to replace methods in a Java String.

public class ReplaceExample1{


public static void main(String args[]){
String s1="hello how are you";
String replaceString=[Link]('h','t');
[Link](replaceString); }}

Java String equals() :

The Java String equals() method compares the two given strings on the basis of content of the
string i.e Java String representation. If all the characters are matched, it returns true else it
will return false.

public class EqualsExample{


public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hi";
[Link]([Link](s2)); // returns true
[Link]([Link](s3)); // returns false
}
}

Java String equalsIgnoreCase():

This method compares two string on the basis of content but it does not check the case like
equals() method. In this method, if the characters match, it returns true else false.

public class EqualsIgnoreCaseExample{


public static void main(String args[]){
String s1="hello";
String s2="HELLO";
String s3="hi";
[Link]([Link](s2)); // returns true
[Link]([Link](s3)); // returns false
}}

Java OOPs
What is OOPs?

In Java, OOPS (Object-Oriented Programming System) is a programming paradigm that


revolves around the concept of objects, which are instances of classes. OOPS is a way of
organizing and designing code to be more modular, reusable, and scalable.

What is an Object in Java?

In Java, an object is an instance of a class that encapsulates data and behavior.

Example: chair, bike, marker, pen, table, car etc. The example of intangible object is banking
system.

An object has state and behavior.

➢ State : represents data (value) of an object.


➢ Behavior : represents the behavior (functionality) of an object such as deposit,
withdraw etc.
What is a Class?

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 contains fields, methods, constructors, blocks, nested class and interface

Syntax to declare a class:

class class_name{
field;
method;
}

What is an Instance variable in Java?

A variable which is created inside the class but outside the method, is known as instance
variable.

Instance variable doesn't get memory at compile time. It gets memory at run time when
object(instance) is created. That is why, it is known as instance variable.

What is a method in Java?

In java, a method is like function i.e. used to expose behavior of an object.

What is new keyword in Java?

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

Object and Class Example-1:

class Student{
int id;
String name;
}

class Main{
public static void main(String args[])
{
Student s1=new Student();
Student s2=new Student();
[Link]=101;
[Link]="Raj";
[Link]=102;
[Link]="Ravi";

[Link]([Link]+" "+[Link]);
[Link]([Link]+" "+[Link]);
}
}

Output:
101 Raj
102 Ravi

Object and Class Example-2:


class Employee{
int id;
String name;
double salary;
}

class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();

[Link] = 1;
[Link]="Ram";
[Link] = 10000;

[Link] = 2;
[Link]="Ramu";
[Link] = 20000;

[Link]([Link]+" "+[Link] +" " +[Link]);


[Link]([Link]+" "+[Link] +" " +[Link]);
}
}

// example for method

class Employee{
int id;
String name;
double salary;

public void display() {


[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}
}

class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();

[Link] = 1;
[Link]="Ram";
[Link] = 10000;

[Link] = 2;
[Link]="Ramu";
[Link] = 20000;

[Link]();
[Link]();
}
}
Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 20000.0

Example for insert and display methods.

class Employee{
int id;
String name;
double salary;

public void insert(int i, String n, double s)


{
id = i;
name = n;
salary = s;
}

public void display() {


[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}

class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();

[Link](1,"Ram",10000);
[Link](2,"Ramu",2000);

[Link]();
[Link]();
}
}

Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0

Example for this keyword

class Employee{
int id;
String name;
double salary;

public void insert(int id, String name, double salary)


{
[Link] = id;
[Link] = name;
[Link] = salary;
}

public void display() {


[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}

class Main{
public static void main(String args[])
{
Employee e1 = new Employee();
Employee e2 = new Employee();

[Link](1,"Ram",10000);
[Link](2,"Ramu",2000);

[Link]();
[Link]();
}
}

Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0

Initializing values to objects by using Construtor

class Employee{
int id;
String name;
double salary;

Employee(int id, String name, double salary)


{
[Link] = id;
[Link] = name;
[Link] = salary;
}

public void display() {


[Link]("Employee ID: " + id);
[Link]("Employee Name: " + name);
[Link]("Employee Salary: " + salary);
}

class Main{
public static void main(String args[])
{
Employee e1 = new Employee(1,"Ram",10000);
Employee e2 = new Employee(2,"Ramu",2000);
[Link]();
[Link]();
}
}

Output:
Employee ID: 1
Employee Name: Ram
Employee Salary: 10000.0
Employee ID: 2
Employee Name: Ramu
Employee Salary: 2000.0

What is a Constructor in Java?

• It is a special type of method which is used to initialize the object.


• In Java, constructor is a block of codes similar to method. It is called when an instance
of object is created and memory is allocated for the object.

Rules for creating java constructor

There are basically two rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type
Types of java constructors

There are two types of constructors in java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor

A constructor is called "Default Constructor" when it doesn't have any parameter.

class Bike1{
Bike1()
{
[Link]("Bike1 constructor invoked");
}
}
class Main{

public static void main(String args[]){


Bike1 b=new Bike1();
}
}

Output:
Bike1 constructor invoked

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object.

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.
Note: Multiple inheritance and Hybrid is not supported in Java through class.

Single Level Inheritance Example

class Animal
{
void eat(){[Link]("eating...");}
}

class Dog extends Animal


{
void bark(){[Link]("barking...");}
}

class Main
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
[Link]();
}
}

Output:

barking...
eating...

Multilevel Inheritance Example

class Animal
{
void eat(){[Link]("eating...");}
}
class Dog extends Animal
{
void bark(){[Link]("barking...");}
}
class BabyDog extends Dog
{
void weep(){[Link]("weeping...");}
}
class Main
{
public static void main(String args[]){
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

class Animal
{
void eat()
{
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark()
{[Link]("barking...");
}
}
class Cat extends Animal
{
void meow()
{
[Link]("meowing...");
}
}
class TestInheritance3
{
public static void main(String args[])
{
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//[Link]
}
}
Output:
meowing...
eating...

Polymorphism in Java
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java:

• Compile time polymorphism and runtime polymorphism.


• We can perform polymorphism in java by method overloading and method overriding.
Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in java.

Rules for Java Method Overriding


1. method must have same name as in the parent class
2. method must have same parameter as in the parent class.
3. must be IS-A relationship (inheritance).

Example :

class Vehicle
{
void run()
{
[Link]("Vehicle is running");
}
}

class Bike2 extends Vehicle


{
void run()
{
[Link]("Bike is running safely");
}
}
public static void main(String args[])
{
Bike2 obj = new Bike2();
[Link]();
}

Output:
Bike is running safely

Method Overloading

What is Method Overloading in Java?

If a class has multiple methods having same name but different in parameters, it is known
as Method Overloading.

Advantage of method overloading

Method overloading increases the readability of the program.

Method Overloading: changing no. of arguments

class Adder{

static int add(int a,int b)


{
return a+b;
}

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


{
return a+b+c;}
}

class TestOverloading1
{
public static void main(String[] args)
{
[Link]([Link](11,11));
[Link]([Link](11,11,11));
}
}

Output:

22
33

ABSTRACTION
Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

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 that is declared with abstract keyword, is known as abstract class in java. It can
have abstract (method without body) and non-abstract methods (method with body).
• It needs to be extended and its method implemented. It cannot be instantiated.

Abstract method

• A method that is declared as abstract and does not have implementation is known as
abstract method.

Example abstract method

abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely..");
}
}
public class Main
{
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Output:
running safely..

Rule: If there is any abstract method in a class, that class must be abstract.
Interface in Java
• An interface in java is a blueprint of a class. It has static constants and abstract
methods.
• The interface in java is a mechanism to achieve abstraction. There can be only abstract
methods in the java interface not method body. It is used to achieve abstraction and
multiple inheritance in Java.
• Java Interface also represents IS-A relationship.
• It cannot be instantiated just like abstract class.

Why use Java interface?

There are mainly three reasons to use interface. They are given below.

o It is used to achieve abstraction.


o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.

The java compiler adds public and abstract keywords before the interface method. More, it
adds public, static and final keywords before data members.

In other words, Interface fields are public, static and final by default, and methods are public
and abstract.

Understanding relationship between classes and interfaces

As shown in the figure given below, a class extends another class, an interface extends
another interface but a class implements an interface.

Java Interface Example

interface printable
{
void print();
}
class A6 implements printable
{
public void print(){[Link]("Hello");
}

public static void main(String args[])


{
A6 obj = new A6();
[Link]();
}
}
Output:
Hello

Encapsulation in Java
Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the data members of the class
private. Now we can use setter and getter methods to set and get the data in it.

Simple example of encapsulation in java

public class Student


{
private String name;
public String getName()
{
return name;
}
public void setName(String name)
{
[Link]=name
}
}
class Test{
public static void main(String[] args)
{
Student s=new Student();
[Link]("vijay");
[Link]([Link]());
}
}
Output: vijay
Access Modifiers in java

There are 4 types of java access modifiers:

• private
• default
• protected
• public

There are many non-access modifiers such as static, abstract, synchronized, native, volatile,
transient etc.

Access within within outside outside


Modifier class package package by package
subclass only

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

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 compile time error.

Example
class A
{
private int data=40;
private void msg(){[Link]("Hello java");}
}

public class Simple{


public static void main(String args[]){
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}

Default access modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is
accessible only within package.

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.

[Link] [Link]
package pack; package mypack;
class A import pack.*;
{ class B{
void msg() public static void main(String args[]){
{ A obj = new A(); //Compile Time Error
[Link]("Hello"); [Link](); //Compile Time Error
} }
} }

In the above program, the scope of class A and its method msg() is default so it cannot be
accessed from outside the package.

Protected access modifier

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.
[Link] [Link]

package pack; package mypack;


public class A import pack.*;
{
protected void msg() class B extends A{
{ public static void main(String args[]){
[Link]("Hello"); B obj = new B();
} [Link]();
} }
}
Output:
Hello

4) public access modifier

The public access modifier is accessible everywhere. It has the widest scope among all
other modifiers.

[Link] [Link]
package pack; package mypack;
public class A{ import pack.*;
public void msg()
{ class B{
[Link]("Hello"); public static void main(String args[]){
} A obj = new A();
} [Link]();
}
}
Output:
Hello

This Keyword

The this keyword can be used to refer current class instance variable. If there is ambiguity
between the instance variables and parameters, this keyword resolves the problem of
ambiguity.

class Student{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee){
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display(){[Link](rollno+" "+name+" "+fee);}
}

class Main{
public static void main(String args[]){
Student s1=new Student(111,"ankit",5000);
Student s2=new Student(112,"sumit",6000);
[Link]();
[Link]();
}}
Output:
111 ankit 5000
112 sumit 6000

If local variables(formal arguments) and instance variables are different, there is no need to
use this keyword

static keyword

The static keyword in java is used for memory management mainly. We can apply java static
keyword with variables, methods, blocks and nested class. The static keyword belongs to the
class than instance of the class.

Java static variable

If you declare any variable as static, it is known static variable.

o The static variable can be used to refer the common property of all objects
o The static variable gets memory only once in class area at the time of class loading.

Advantage of static variable

It makes your program memory efficient (i.e it saves memory).

Example of static variable

class Student8{
int rollno;
String name;
static String college ="Gayathri College";

Student8(int r,String n){


rollno = r;
name = n;
}
void display (){[Link](rollno+" "+name+" "+college);}
}

public class Main


{
public static void main(String args[]){
Student8 s1 = new Student8(111,"Ram");
Student8 s2 = new Student8(222,"Arjun");

[Link]();
[Link]();
}
}
Output:
111 Ram Gayathri College
222 Arjun Gayathri College

2) Java static method

• If you apply static keyword with any method, it is known as static method.A static
method belongs to the class rather than object of a class. A static method can be
invoked without the need for creating an instance of a class. Static method can access
static data member and can change the value of it.

Example of static method

class Student9{
int rollno;
String name;
static String college = "ITS";

static void change(){


college = "BBDIT";
}

Student9(int r, String n){


rollno = r;
name = n;
}

void display (){[Link](rollno+" "+name+" "+college);}


}
class Main{

public static void main(String args[]){

Student9 s1 = new Student9 (111,"Karan");


Student9 s2 = new Student9 (222,"Aryan");
Student9 s3 = new Student9 (333,"Sonoo");

[Link]();
[Link]();
[Link]();

[Link]();
}
}
Output:
111 Karan ITS
222 Aryan ITS
333 Sonoo BBDIT

Q) why java main method is static?


Ans) because object is not required to call static method if it were non-static method, jvm
create object first then call main() method that will lead the problem of extra memory
allocation.

super keyword in java

The super keyword in java is a reference variable which is used to refer immediate parent
class object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly
which is referred by super reference variable.

1) super is used to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if
parent class and child class have same fields.

class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor(){
[Link](color);//prints color of Dog class
[Link]([Link]);//prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
[Link]();
}
}

Output:
black
white

In the above example, Animal and Dog both classes have a common property color. If we
print color property, it will print the color of current class by default. To access the parent
property, we need to use super keyword.

2) super can be used to invoke parent class method

The super keyword can also be used to invoke parent class method. It should be used if
subclass contains the same method as parent class. In other words, it is used if method is
overridden.

class Animal
{
void eat(){[Link]("eating...");
}
}
class Dog extends Animal
{
void eat(){[Link]("eating bread...");
}
void bark(){[Link]("barking...");}
void work()
{
[Link]();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
[Link]();
}}

Output:
eating...
barking...

In the above example Animal and Dog both classes have eat() method if we call eat() method
from Dog class, it will call the eat() method of Dog class by default because priority is given to
local.

To call the parent class method, we need to use super keyword.

Exception Handling in Java


The Exception Handling in Java is one of the powerful mechanism to handle the runtime
errors so that normal flow of the application can be maintained.

What is Exception Handling

Exception Handling is a mechanism to handle runtime errors such as


ClassNotFoundException, IOException, SQLException, RemoteException, etc

Problem without exception handling


import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter two values ");
int a= [Link]();
int b = [Link]();
int c=a/b; //may throw exception
[Link](c);
[Link]("rest of the code");
[Link]("rest of the code");

}
}

Output:
Exception in thread "main" [Link]: / by zero

Solution by exception handling

import [Link];
public class Main
{
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter two values ");
int a= [Link]();
int b = [Link]();
int c;
try {
c=a/b; //may throw exception
}
catch(ArithmeticException e)
{
[Link](e);
}
[Link]("rest of the code");
[Link]("rest of the code");

}
}

Output:
[Link]: / by zero
rest of the code

Types of Java Exceptions

There are mainly two types of exceptions: checked and unchecked. Here, an error is
considered as the unchecked exception. According to Oracle, there are three types of
exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error

Java Exception Handling Example

Java Exception Handling where we using a try-catch statement to handle the exception.

public class JavaExceptionExample{


public static void main(String args[]){
try{
//code that may raise exception
int data=100/0;
}catch(ArithmeticException e){[Link](e);}
//rest code of the program
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:/ by zero
rest of the code...

Common Scenarios of Java Exceptions

There are given some scenarios where unchecked exceptions may occur. They are as follows:
[Link] exception

A scenario where ArithmeticException occurs

If we divide any number by zero, there occurs an ArithmeticException.

int a=50/0; //ArithmeticException

2) NullPointerException

If we have a null value in any variable, performing any operation on the variable throws a
NullPointerException.

String s=null;
[Link]([Link]()); //NullPointerException

3) NumberFormatException

The wrong formatting of any value may occur NumberFormatException. Suppose I have a
string variable that has characters, converting this variable into digit will occur
NumberFormatException.

String s="abc";
int i=[Link](s);//NumberFormatException

4) ArrayIndexOutOfBoundsException

If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:

int a[]=new int[5];


a[10]=50; //ArrayIndexOutOfBoundsException

Java try-catch block


Java try block

Java try block is used to enclose the code that might throw an exception. It must be used
within the method.

If an exception occurs at the particular statement of try block, the rest of the block code will
not execute. So, it is recommended not to keeping the code in try block that will not throw an
exception.
Java try block must be followed by either catch or finally block.

Syntax of Java try-catch


try{
//code that may throw an exception
}catch(Exception_class_Name ref){}

Syntax of try-finally block


try{
//code that may throw an exception
}finally{}
Java catch block

Java catch block is used to handle the Exception by declaring the type of exception within the
parameter. The declared exception must be the parent class exception ( i.e., Exception) or the
generated exception type. However, the good approach is to declare the generated type of
exception.

The catch block must be used after the try block only. You can use multiple catch block with a
single try block.

Example

Here, we handle the exception using the parent class exception.

public class TryCatchExample4 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception by using Exception class
catch(Exception e)
{
[Link](e);
}
[Link]("rest of the code");
}

Output:
[Link]: / by zero
rest of the code
Example to print a custom message on exception.
public class TryCatchExample5 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception
}
// handling the exception
catch(Exception e)
{
// displaying the custom message
[Link]("Can't divided by zero");
}
}

Output:
Can't divided by zero
Example to resolve the exception in a catch block.

public class TryCatchExample6 {

public static void main(String[] args) {


int i=50;
int j=0;
int data;
try
{
data=i/j; //may throw exception
}
// handling the exception
catch(Exception e)
{
// resolving the exception in catch block
[Link](i/(j+2));
}
}
}

Output:
25

we handle the generated exception (Arithmetic Exception) with a different type of


exception class (ArrayIndexOutOfBoundsException.
public class TryCatchExample8 {

public static void main(String[] args) {


try
{
int data=50/0; //may throw exception

}
// try to handle the ArithmeticException using ArrayIndexOutOfBoundsException
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}

Output:
Exception in thread "main" [Link]: / by zero

Example to handle another unchecked exception.

public class TryCatchExample9 {

public static void main(String[] args) {


try
{
int arr[]= {1,3,5,7};
[Link](arr[10]); //may throw exception
}
// handling the array exception
catch(ArrayIndexOutOfBoundsException e)
{
[Link](e);
}
[Link]("rest of the code");
}

Output:
[Link]: 10
rest of the code
Example to handle checked exception.

import [Link];
import [Link];

public class TryCatchExample10 {

public static void main(String[] args) {

PrintWriter pw;
try {
pw = new PrintWriter("[Link]"); //may throw exception
[Link]("saved");
}
// providing the checked exception handler
catch (FileNotFoundException e) {

[Link](e);
}
[Link]("File saved successfully");
}
}
Output:
File saved successfully

Java Multi-catch block

A try block can be followed by one or more catch blocks. Each catch block must contain a
different exception handler. So, if you have to perform different tasks at the occurrence of
different exceptions, use java multi-catch block.

Points to remember
At a time only one exception occurs and at a time only one catch block is executed.

All catch blocks must be ordered from most specific to most general, i.e. catch for
ArithmeticException must come before catch for Exception.

Example of java multi-catch block.

public class MultipleCatchBlock1 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[7]=30/0;
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}
Output:
Arithmetic Exception occurs
rest of the code

Example 2

public class MultipleCatchBlock2 {

public static void main(String[] args) {

try{
int a[]=new int[5];

[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}

Output:
ArrayIndexOutOfBounds Exception occurs
rest of the code

Example 3

In this example, try block contains two exceptions. But at a time only one exception occurs
and its corresponding catch block is invoked.

public class MultipleCatchBlock3 {

public static void main(String[] args) {

try{
int a[]=new int[5];
a[5]=30/0;
[Link](a[10]);
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}

Output:
Arithmetic Exception occurs
rest of the code

Example 4
In this example, we generate NullPointerException, but didn't provide the corresponding
exception type. In such case, the catch block containing the parent exception
class Exception will invoked.

public class MultipleCatchBlock4 {

public static void main(String[] args) {

try{
String s=null;
[Link]([Link]());
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
[Link]("Parent Exception occurs");
}
[Link]("rest of the code");
}
}

Output:
Parent Exception occurs
rest of the code
Example 5

Let's see an example, to handle the exception without maintaining the order of exceptions
(i.e. from most specific to most general).

class MultipleCatchBlock5{
public static void main(String args[]){
try{
int a[]=new int[5];
a[5]=30/0;
}
catch(Exception e){[Link]("common task completed");}
catch(ArithmeticException e){[Link]("task1 is completed");}
catch(ArrayIndexOutOfBoundsException e){[Link]("task 2 completed");}
[Link]("rest of the code...");
}
}

Output:
Compile-time error

Java Nested try block

The try block within a try block is known as nested try block in java.

Sometimes a situation may arise where a part of a block may cause one error and the entire
block itself may cause another error. In such cases, exception handlers have to be nested.

Syntax:
....
try
{
statement 1;
statement 2;
try
{
statement 1;
statement 2;
}
catch(Exception e)
{
}
}
catch(Exception e)
{
}
....

Java nested try example


class Excep6{
public static void main(String args[]){
try{
try{
[Link]("going to divide");
int b =39/0;
}catch(ArithmeticException e){[Link](e);}

try{
int a[]=new int[5];
a[5]=4;
}catch(ArrayIndexOutOfBoundsException e){[Link](e);}

[Link]("other statement);
}catch(Exception e){[Link]("handeled");}

[Link]("normal flow..");
}
}

Java finally block

• Java finally block is a block that is used to execute important code such as closing
connection, stream etc.
• Java finally block is always executed whether exception is handled or not.
• Java finally block follows try or catch block.

Note: If you don't handle exception, before terminating the program, JVM executes finally
block(if any).

Why use java finally

Finally block in java can be used to put "cleanup" code such as closing a file, closing
connection etc.

Usage of Java finally

Let's see the different cases where java finally block can be used.

Case 1

Let's see the java finally example where exception doesn't occur.

class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:
5
finally block is always executed
rest of the code...

Case 2

java finally example where exception occurs and not handled.

class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
[Link](data);
}
catch(NullPointerException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:
finally block is always executed
Exception in thread main [Link]:/ by zero

Case 3

Java finally example where exception occurs and handled.

public class TestFinallyBlock2{


public static void main(String args[]){
try{
int data=25/0;
[Link](data);
}
catch(ArithmeticException e){[Link](e);}
finally{[Link]("finally block is always executed");}
[Link]("rest of the code...");
}
}
Output:Exception in thread main [Link]:/ by zero
finally block is always executed
rest of the code...
Rule: For each try block there can be zero or more catch blocks, but only one finally block.

Java throw keyword

• The Java throw keyword is used to explicitly throw an exception.


• We can throw either checked or uncheked exception in java by throw keyword. The
throw keyword is mainly used to throw custom exception.

syntax

throw exception;

example

public class TestThrow1{


static void validate(int age){
if(age<18)
throw new ArithmeticException("not valid");
else
[Link]("welcome to vote");
}
public static void main(String args[]){
validate(13);
[Link]("rest of the code...");
}
}

Output:
Exception in thread main [Link]:not valid

Java throws keyword

The Java throws keyword is used to declare an exception. It gives an information to the
programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be maintained.

Syntax of java throws


return_type method_name() throws exception_class_name{
//method code
}

Java throws example


import [Link];
class Testthrows1{
void m()throws IOException{
throw new IOException("device error");//checked exception
}
void n()throws IOException{
m();
}
void p(){
try{
n();
}catch(Exception e){[Link]("exception handled");}
}
public static void main(String args[]){
Testthrows1 obj=new Testthrows1();
obj.p();
[Link]("normal flow...");
}
}

Output:
exception handled
normal flow...

Rule: If you are calling a method that declares an exception, you must either caught or
declare the exception.

There are two cases:

Case1:You caught the exception i.e. handle the exception using try/catch.

Case2:You declare the exception i.e. specifying throws with the method.

Case1:

You handle the exception


In case you handle the exception, the code will be executed fine whether exception occurs
during the program or not.

import [Link].*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
public class Testthrows2{
public static void main(String args[]){
try{
M m=new M();
[Link]();
}catch(Exception e){[Link]("exception handled");}

[Link]("normal flow...");
}
}
Output:
exception handled
normal flow...

Case2:

You declare the exception


A)In case you declare the exception, if exception does not occur, the code will be executed
fine.

B)In case you declare the exception if exception occures, an exception will be thrown at
runtime because throws does not handle the exception.

A)Program if exception does not occur


import [Link].*;
class M{
void method()throws IOException{
[Link]("device operation performed");
}
}
class Testthrows3{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
[Link]();

[Link]("normal flow...");
}
}
Output:device operation performed
normal flow...

B)Program if exception occurs


import [Link].*;
class M{
void method()throws IOException{
throw new IOException("device error");
}
}
class Testthrows4{
public static void main(String args[])throws IOException{//declare exception
M m=new M();
[Link]();

[Link]("normal flow...");
}
}
Output:Runtime Exception

Java throw example

void m(){
throw new ArithmeticException("sorry");
}

Java throws example


void m()throws ArithmeticException{
//method code
}

Java throw and throws example


void m()throws ArithmeticException{
throw new ArithmeticException("sorry");
}

Java Custom Exception

If you are creating your own Exception that is known as custom exception or user-defined
exception. Java custom exceptions are used to customize the exception according to user
need. By the help of custom exception, you can have your own exception and message.

Example
class InvalidAgeException extends Exception{
InvalidAgeException(String s){
super(s);
}
}
class TestCustomException1{

static void validate(int age)throws InvalidAgeException{


if(age<18)
throw new InvalidAgeException("not valid");
else
[Link]("welcome to vote");
}

public static void main(String args[]){


try{
validate(13);
}catch(Exception m){[Link]("Exception occured: "+m);}

[Link]("rest of the code...");


}
}
Output:
Exception occured: InvalidAgeException:not valid
rest of the code...

Multithreading in Java
• Multithreading in java is a process of executing multiple threads simultaneously.
• Thread is basically a lightweight sub-process, a smallest unit of processing.
Multiprocessing and multithreading, both are used to achieve multitasking.
• But we use multithreading than multiprocessing because threads share a common
memory area. They don't allocate separate memory area so saves memory, and
context-switching between the threads takes less time than process.
• Java Multithreading is mostly used in games, animation etc.

Advantages of Java Multithreading

1) It doesn't block the user because threads are independent and you can perform multiple
operations at same time.

2) You can perform many operations together so it saves time.

3) Threads are independent so it doesn't affect other threads if exception occur in a single
thread.

Multitasking

Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to


utilize the CPU. Multitasking can be achieved by two ways:

o Process-based Multitasking(Multiprocessing)
o Thread-based Multitasking(Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process have its own address in memory i.e. each process allocates separate
memory area.
o Process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another require some time for saving and loading
registers, memory maps, updating lists etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o Thread is lightweight.
o Cost of communication between the thread is low.

What is Thread in java

A thread is a lightweight sub process, a smallest unit of processing. It is a separate path of


execution.

Threads are independent, if there occurs exception in one thread, it doesn't affect other
threads. It shares a common memory area.

As shown in the above figure, thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS and one
process can have multiple threads.

Note: At a time one thread is executed only.

How to create thread

There are two ways to create a thread:


1. By extending Thread class
2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.

Commonly used Constructors of Thread class:


o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the [Link] calls the run() method on
the thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public [Link] getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily
pause and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended
to be executed by a thread. Runnable interface have only one method named run().

1. public void run(): is used to perform action for a thread.

Java Thread Example by extending Thread class


class Multi extends Thread{
public void run(){
[Link]("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
[Link]();
}
}
Output:thread is running...

Java Thread Example by implementing Runnable interface


class Multi3 implements Runnable{
public void run(){
[Link]("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
[Link]();
}
}
Output:thread is running...
If you are not extending the Thread class,your class object would not be treated as a thread
[Link] you need to explicitely create Thread class [Link] are passing the object of
your class that implements Runnable so that your class run() method may execute.

Naming Thread and Current Thread

The Thread class provides methods to change and get the name of a thread. By default, each
thread has a name i.e. thread-0, thread-1 and so on. By we can change the name of the
thread by using setName() method. The syntax of setName() and getName() methods are
given below:

1. public String getName(): is used to return the name of a thread.


2. public void setName(String name): is used to change the name of a thread.

Example of naming a thread


class TestMultiNaming1 extends Thread{
public void run(){
[Link]("running...");
}
public static void main(String args[]){
TestMultiNaming1 t1=new TestMultiNaming1();
TestMultiNaming1 t2=new TestMultiNaming1();
[Link]("Name of t1:"+[Link]());
[Link]("Name of t2:"+[Link]());

[Link]();
[Link]();

[Link]("Sonoo Jaiswal");
[Link]("After changing name of t1:"+[Link]());
}
}
Output:
Name of t1:Thread-0
Name of t2:Thread-1
running…
running...
After changeling name of t1:Sonoo Jaiswal
Running

The join() method

The join() method waits for a thread to die. In other words, it causes the currently running
threads to stop executing until the thread it joins with completes its task.

Syntax:

public void join()throws InterruptedException

public void join(long milliseconds)throws InterruptedException

Example of join() method

class TestJoinMethod1 extends Thread{


public void run(){
for(int i=1;i<=5;i++){
try{
[Link](500);
}catch(Exception e){[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
[Link]();
try{
[Link]();
}catch(Exception e){[Link](e);}

[Link]();
[Link]();
}
}

Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

As you can see in the above example,when t1 completes its task then t2 and t3 starts
executing.

getName(),setName(String) and getId() method:

class TestJoinMethod3 extends Thread{


public void run(){
[Link]("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
[Link]("Name of t1:"+[Link]());
[Link]("Name of t2:"+[Link]());
[Link]("id of t1:"+[Link]());

[Link]();
[Link]();

[Link]("Sonoo Jaiswal");
[Link]("After changing name of t1:"+[Link]());
}
}

Output:
Name of t1:Thread-0
Name of t2:Thread-1
id of t1:8
running...
After changling name of t1:Sonoo Jaiswal
running...

Priority of a Thread (Thread Priority):

Each thread have a priority. Priorities are represented by a number between 1 and 10. In
most cases, thread schedular schedules the threads according to their priority (known as
preemptive scheduling). But it is not guaranteed because it depends on JVM specification
that which scheduling it chooses.

A real-time example where thread priority can be used is in an operating system. In an


operating system, there are many background processes and applications running
simultaneously. For example, if you are using a video conferencing application while also
running a heavy workload application, the system has to allocate resources to both the
applications.

Here, the video conferencing application requires real-time processing, which means that
the video frames have to be captured and displayed immediately without any delay. On
the other hand, the heavy workload application can take some time to complete its
execution. So, in this case, the thread running the video conferencing application can be
given a higher priority than the thread running the heavy workload application.

By giving a higher priority to the thread running the video conferencing application, the
operating system will allocate more CPU time to that thread, ensuring that the video
frames are captured and displayed without any delay. This way, thread priority can be
used to ensure that important tasks are executed with higher priority, while other tasks
are executed with lower priority.

3 constants defined in Thread class:

1. public static int MIN_PRIORITY


2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the


value of MAX_PRIORITY is 10.

Example of priority of a Thread:

class TestMultiPriority1 extends Thread{


public void run(){
[Link]("running thread name is:"+[Link]().getName());
[Link]("running thread priority is:"+[Link]().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
[Link](Thread.MIN_PRIORITY);
[Link](Thread.MAX_PRIORITY);
[Link]();
[Link]();

}
}
Output:running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1

Thread Scheduler in Java

1. In Java, a thread scheduler is responsible for scheduling the execution of threads.


2. The scheduler uses a preemptive scheduling algorithm to decide which thread should
run at any given time based on priority, state, and other factors.
3. The thread scheduler is important for multithreading in Java and allows multiple
threads to run efficiently and share resources effectively.
Sleep method in java

The sleep() method of Thread class is used to sleep a thread for the specified amount of time.

Syntax of sleep() method in java

The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws InterruptedException

Example of sleep method in java

class TestSleepMethod1 extends Thread{


public void run(){
for(int i=1;i<5;i++){
try{[Link](500);}catch(InterruptedException e){[Link](e);}
[Link](i);
}
}
public static void main(String args[]){
TestSleepMethod1 t1=new TestSleepMethod1();
TestSleepMethod1 t2=new TestSleepMethod1();

[Link]();
[Link]();
}
}

Output:

1
1
2
2
3
3
4
4

As you know well that at a time only one thread is executed. If you sleep a thread for the
specified time,the thread shedular picks up another thread and so on.
COLLECTIONS IN JAVA
A Collection is a group of individual objects represented as a single unit. Java provides
Collection Framework which defines several classes and interfaces to represent a group of
objects as a single unit.
The Collection interface ([Link]) and Map interface ([Link]) are the two
main “root” interfaces of Java collection classes.

Java Collections

1. ArrayList
2. LinkedList
3. Vector
4. HashSet
5. LinkedHashSet
6. TreeSet
7. HashMap
8. TreeMap
9. LinkedHashMap
10. Hashtable
11. Iterator and ListIterator

Data Structure Definition

ArrayList A dynamic array implementation in Java, allowing for resizable arrays with
constant time access to elements

LinkedList A data structure that consists of a sequence of nodes, each containing a


reference to the next node, and is useful for quick insertion and deletion
operations

Vector A legacy class similar to ArrayList, but with synchronized methods

HashSet A collection that does not allow duplicates and provides constant time
performance for add, remove, and contains operations

LinkedHashSet
A collection that maintains the order of elements as they were inserted, while
Data Structure Definition

still not allowing duplicates

TreeSet A sorted set implementation in Java, where elements are ordered using their
natural ordering, or by a Comparator object

HashMap A key-value pair data structure that allows for fast retrieval of values based on
their associated keys

TreeMap A sorted map implementation in Java, where keys are sorted using their natural
ordering, or by a Comparator object

LinkedHashMap A map that maintains the order of entries as they were inserted, while still
allowing for fast retrieval of values based on their associated keys

Hashtable A legacy class similar to HashMap, but with synchronized methods

Iterator and Interfaces used for iterating over collections, where Iterator is used for iterating
ListIterator forward, and ListIterator is used for iterating in both directions

Java Collections – List

A List is an ordered Collection (sometimes called a sequence). Lists may contain duplicate
elements. Elements can be inserted or accessed by their position in the list, using a zero-
based index.
ArrayList

• ArrayList is a dynamic data structure in Java that can be used to store and manipulate a
collection of elements.
• It is similar to an array but provides additional features such as automatic resizing and the
ability to insert or remove elements at any position.
• ArrayList is part of the Java Collections Framework and can be used to store objects of any
class or primitive data types.

Syntax:
ArrayList<String> alist=new ArrayList<String>();

Program
import [Link];
import [Link];
public class ArrayListExample {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<>();
// Add elements to the ArrayList
[Link](5);
[Link](2);
[Link](8);
[Link](1);
// Print the original ArrayList
[Link]("Original ArrayList: " + numbers);
// Remove an element from the ArrayList
[Link](2);
// Print the ArrayList after removing an element
[Link]("ArrayList after removing an element: " + numbers);
// Sort the ArrayList
[Link](numbers);
// Print the sorted ArrayList
[Link]("Sorted ArrayList: " + numbers);
}
}

LinkedList in Java

• A linked list is a data structure used for storing a collection of elements.


• Unlike arrays, linked lists are not stored in contiguous memory locations.
• Each element in a linked list is called a node, and it consists of two parts: the data and a
reference to the next node in the list.

LinkedList Program

import [Link];
public class LinkedListExample {
public static void main(String[] args) {
// Creating a Linked List
LinkedList<String> linkedList = new LinkedList<>();
// Adding elements to the Linked List
[Link]("Java");
[Link]("Python");
[Link]("JavaScript");
[Link]("LinkedList: " + linkedList);
// Adding an element at the first position
[Link]("C++");
[Link]("After adding an element at first position: " + linkedList);
// Adding an element at the last position
[Link]("Ruby");
[Link]("After adding an element at last position: " + linkedList);
// Removing the first element
[Link]();
[Link]("After removing the first element: " + linkedList);
// Removing the last element
[Link]();
[Link]("After removing the last element: " + linkedList);
// Sorting the Linked List in ascending order
[Link](String::compareTo);
[Link]("After sorting the Linked List: " + linkedList);
}
}
Vector in Java
• Vector is a dynamic array-like data structure that can resize itself automatically when
elements are added or removed from it.
• It is a part of the Java Collections Framework and is similar to ArrayList in many ways, but
with some additional features.
• Vector is thread-safe, which means that it can be accessed by multiple threads
simultaneously without causing any concurrency issues. However, this can come at the
cost of performance, so it is generally recommended to use ArrayList if you don't need
thread safety.
Vector Program

import [Link];
public class VectorExample {
public static void main(String[] args) {
// create a vector of strings
Vector<String> v = new Vector<String>();
// add elements to the vector
[Link]("apple");
[Link]("banana");
[Link]("cherry");
// print the vector
[Link]("Vector: " + v);
// add an element at a specific index
[Link](1, "grape");
// print the vector again
[Link]("Vector after adding 'grape' at index 1: " + v);
// remove an element at a specific index
[Link](2);
// print the vector again
[Link]("Vector after removing element at index 2: " + v);
}
}

HashSet Class in Java


• HashSet does not allow duplicate elements, which means that each element in the set
must be unique.
• Elements in a HashSet are not ordered or indexed, which means that they cannot be
accessed by position or sorted.
• HashSet uses hashing to determine whether an element is already in the set, which makes
it very efficient for adding, removing, and searching for elements.
HashSet Program

import [Link];
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
// Adding elements to the HashSet
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Pineapple");
// Printing the HashSet
[Link]("Fruits: " + fruits);
// Checking if an element is present in the HashSet
boolean isPresent = [Link]("Grapes");
[Link]("Is Grapes present? " + isPresent);
// Removing an element from the HashSet
[Link]("Pineapple");
// Printing the HashSet after removal
[Link]("Fruits after removal: " + fruits);
// Iterating over the HashSet using for-each loop
[Link]("Iterating over the HashSet:");
for (String fruit : fruits) {
[Link](fruit);
}
// Clearing the HashSet
[Link]();
[Link]("Fruits after clearing: " + fruits);
}
}
TreeSet Class in Java

• TreeSet is a collection class in Java that stores elements in a sorted order.


• It implements the Set interface and uses a tree structure (specifically, a self-balancing
binary search tree) to maintain the order of the elements.
• TreeSet allows you to perform set operations such as add, remove, and search efficiently,
and it is particularly useful when you need to store elements in a specific order, such as in
alphabetical order.
TreeSet Program:

import [Link];
public class HashSetExample {
public static void main(String[] args) {
HashSet<String> fruits = new HashSet<>();
// Adding elements to the HashSet
[Link]("Apple");
[Link]("Banana");
[Link]("Orange");
[Link]("Pineapple");
// Printing the HashSet
[Link]("Fruits: " + fruits);
// Checking if an element is present in the HashSet
boolean isPresent = [Link]("Grapes");
[Link]("Is Grapes present? " + isPresent);
// Removing an element from the HashSet
[Link]("Pineapple");
// Printing the HashSet after removal
[Link]("Fruits after removal: " + fruits);
// Iterating over the HashSet using for-each loop
[Link]("Iterating over the HashSet:");
for (String fruit : fruits) {
[Link](fruit);
}
// Clearing the HashSet
[Link]();
[Link]("Fruits after clearing: " + fruits);
}
}

Difference between HashSet and TreeSet

HashSet TreeSet

HashSet is an unordered collection. TreeSet is an ordered collection.

It uses hashing technique to store


It uses a red-black tree to store elements.
elements.

HashSet doesn't allow duplicates. TreeSet doesn't allow duplicates.


HashSet provides constant time
TreeSet provides O(log(n)) time performance for
performance for add, remove, and
add, remove, and contains operations.
contains operations.

HashMap in Java

• HashMap is a data structure in Java that stores elements in key-value pairs.


• It provides constant time performance for basic operations like add, remove, and search.
• HashMap allows null values for both keys and values, and it is not synchronized, which
means it is not thread-safe by default.

Hashmap Program
import [Link];
public class HashMapExample {
public static void main(String[] args) {
// Creating a HashMap with Integer keys and String values
HashMap<Integer, String> map = new HashMap<>();
// Adding key-value pairs to the HashMap
[Link](1, "John");
[Link](2, "Jane");
[Link](3, "Bob");
[Link](4, "Alice");
// Retrieving values from the HashMap using keys
String name1 = [Link](1);
String name3 = [Link](3);
[Link]("Name at key 1: " + name1);
[Link]("Name at key 3: " + name3);
// Removing a key-value pair from the HashMap
[Link](4);
// Iterating over the HashMap and printing all key-value pairs
for (Integer key : [Link]()) {
String value = [Link](key);
[Link]("Key: " + key + ", Value: " + value);
}
}
}

TreeMap in Java
• TreeMap is a class in Java's collections framework that provides a sorted map data
structure. It implements the Map interface, and allows key-value pairs to be stored in a
sorted order based on the keys.
• TreeMap uses a red-black tree data structure to maintain the key-value pairs in a sorted
order. This allows for efficient insertion, deletion, and retrieval operations with a worst-
case time complexity of O(log n).
• TreeMap provides methods to retrieve the first and last keys in the sorted order, as well
as methods to retrieve keys that are less than or greater than a given key. It also supports
a variety of methods for manipulating and iterating over the key-value pairs in the map.

TreeMap Program

import [Link].*;
public class TreeMapExample {
public static void main(String[] args) {
// Create a TreeMap
TreeMap<String, Integer> treeMap = new TreeMap<>();
// Add elements to the TreeMap
[Link]("Alice", 25);
[Link]("Bob", 30);
[Link]("Charlie", 35);
[Link]("David", 40);
// Print the TreeMap
[Link]("TreeMap: " + treeMap);
// Get the size of the TreeMap
[Link]("Size of TreeMap: " + [Link]());
// Check if the TreeMap contains a key
[Link]("TreeMap contains key 'Alice': " + [Link]("Alice"));
// Get the value associated with a key
[Link]("Value associated with key 'Bob': " + [Link]("Bob"));
// Remove an element from the TreeMap
[Link]("Charlie");
[Link]("TreeMap after removing 'Charlie': " + treeMap);
// Iterate over the TreeMap
[Link]("Iterating over TreeMap using entrySet():");
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " : " + [Link]());
}
}
}

LinkedHashMap in Java
• It maintains the order of insertion of elements, so the order in which elements are added
to the map is preserved.
• It provides a predictable iteration order, which is either the order of insertion or the order
of access (least-recently accessed to most-recently accessed).
• It has slightly slower performance than a regular HashMap due to the added overhead of
maintaining the linked list, but this is often negligible for small maps and can be worth it
for the benefits of maintaining order.

LinkedHashMap Program:

import [Link];
import [Link];
public class LinkedHashMapExample {
public static void main(String[] args) {
// Creating a LinkedHashMap of String keys and Integer values
Map<String, Integer> map = new LinkedHashMap<>();
// Adding key-value pairs to the LinkedHashMap
[Link]("John", 25);
[Link]("Sarah", 30);
[Link]("David", 40);
// Printing the contents of the LinkedHashMap
[Link]("Initial LinkedHashMap: " + map);
// Replacing the value for the key "Sarah"
[Link]("Sarah", 35);
// Removing the key-value pair for the key "David"
[Link]("David");
// Printing the updated contents of the LinkedHashMap
[Link]("Updated LinkedHashMap: " + map);
// Iterating over the keys and values of the LinkedHashMap using a for-each loop
for ([Link]<String, Integer> entry : [Link]()) {
[Link]([Link]() + " = " + [Link]());
}
}
}

Hashtable in java
• Hashtable is a data structure used for storing key-value pairs in Java.
• It uses the hash code of the key to store and retrieve values in a highly efficient way.
• Hashtable is synchronized, which means it is thread-safe and can be used in a multi-
threaded environment without any issues related to race conditions or thread
interference.
Hashtable Program
import [Link];
import [Link];
import [Link];
import [Link];
public class LinkedHashtableExample {
public static void main(String[] args) {
// Creating a new linked hashtable
LinkedHashMap<String, String> linkedHashtable = new LinkedHashMap<String, String>();
// Adding elements to the linked hashtable
[Link]("A", "Apple");
[Link]("B", "Ball");
[Link]("C", "Cat");
// Displaying the linked hashtable
[Link]("LinkedHashtable contents:");
[Link](linkedHashtable);
// Using an iterator to iterate over the linked hashtable
Iterator<[Link]<String, String>> iterator = [Link]().iterator();
while ([Link]()) {
[Link]<String, String> entry = [Link]();
[Link]("Key = " + [Link]() + ", Value = " + [Link]());
}
}
}

Difference between HashMap and Hashtable

HashMap Hashtable
Synchronization Not synchronized Synchronized

Performance Faster Slower


Does not allow null key or
Null values Allows null key and null values
values

Iterator Fail-fast iterator Enumerator

Java Iterator

In Java, an iterator is an interface that allows you to iterate over a collection of elements.

• An iterator provides a way to access each element of a collection sequentially, without


needing to know the internal details of the collection.
• It provides methods to check if there are more elements in the collection, and to retrieve
the next element in the sequence.
• By using an iterator, you can iterate over a collection of elements in a consistent and
predictable way, regardless of the specific type of collection or its implementation.

Iterator Program

import [Link];
import [Link];
public class IteratorExample {
public static void main(String[] args) {
// Create an ArrayList of integers
ArrayList<Integer> numbers = new ArrayList<Integer>();
// Add some integers to the ArrayList
[Link](10);
[Link](20);
[Link](30);
[Link](40);
// Get an iterator for the ArrayList
Iterator<Integer> iterator = [Link]();
// Use the iterator to print out the contents of the ArrayList
while ([Link]()) {
[Link]([Link]());
}
}
}

ListIterator in Java

In Java, ListIterator is an interface that provides the following functionalities:

• It extends the Iterator interface and allows bidirectional traversal of a list.


• It provides methods for adding, removing, and modifying elements in the list during
traversal.
• It also allows retrieval of the index of the current element, and the next and previous
elements in the list.
ListIterator Program

import [Link];
import [Link];
public class ListIteratorExample {
public static void main(String[] args) {
// Creating an ArrayList
ArrayList<String> names = new ArrayList<>();
// Adding elements to the ArrayList
[Link]("Alice");
[Link]("Bob");
[Link]("Charlie");
[Link]("David");
// Creating a ListIterator
ListIterator<String> iterator = [Link]();
// Iterating forward through the list
while ([Link]()) {
[Link]([Link]());
}
// Iterating backward through the list
while ([Link]()) {
[Link]([Link]());
}
}
}

Java Package

• A java package is a group of similar types of classes, interfaces and sub-packages.


• Package in java can be categorized in two form, built-in package and user-defined
package.
• There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql
etc.
• Here, we will have the detailed learning of creating and using user-defined packages.

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
2) Java package provides access protection.
3) Java package removes naming collision.
Simple example of java package

The package keyword is used to create a package in java.

//save as [Link]
package mypack;
public class Simple{
public static void main(String args[]){
[Link]("Welcome to package");
}
}

How to access package from another package?

There are three ways to access the package from outside the package.

1. import package.*;
2. import [Link];
3. fully qualified name.

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but
not subpackages.

The import keyword is used to make the classes and interface of another package accessible
to the current package.

Example of package that import the packagename.*


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello

2) Using [Link]

If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]


//save by [Link]

package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.A;

class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. [Link] and [Link]
packages contain Date class.

Example of package by import fully qualified name


//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
class B{
public static void main(String args[]){
pack.A obj = new pack.A();//using fully qualified name
[Link]();
}
}
Output:Hello

Note: If you import a package, subpackages will not be imported.

If you import a package, all the classes and interface of that package will be imported
excluding the classes and interfaces of the subpackages. Hence, you need to import the
subpackage as well.

Subpackage in java

Package inside the package is called the subpackage. It should be created to categorize the
package further.

Example of Subpackage
package [Link];
class Simple{
public static void main(String args[]){
[Link]("Hello subpackage");
}
}
Output:Hello subpackage

Java Wrapper Classes

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

The table below shows the primitive type and the equivalent wrapper class:

Primitive Data Type Wrapper Class

byte Byte

short Short

int Integer

long Long
float Float

double Double

boolean Boolean

Char Character

Sometimes you must use wrapper classes, for example when working with Collection objects,
such as ArrayList, where primitive types cannot be used (the list can only store objects):

Example

ArrayList<int> myNumbers = new ArrayList<int>(); // Invalid

ArrayList<Integer> myNumbers = new ArrayList<Integer>(); // Valid

Creating Wrapper Objects

To create a wrapper object, use the wrapper class instead of the primitive type. To get the
value, you can just print the object:

Example
public class Main {
public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link](myInt);
[Link](myDouble);
[Link](myChar);
}
}

Since you're now working with objects, you can use certain methods to get information about
the specific object.

For example, the following methods are used to get the value associated with the
corresponding wrapper
object: intValue(), byteValue(), shortValue(), longValue(), floatValue(), doubleValue(), charValue(), booleanV
alue().

This example will output the same result as the example above:
Example

public class Main {


public static void main(String[] args) {
Integer myInt = 5;
Double myDouble = 5.99;
Character myChar = 'A';
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Another useful method is the toString() method, which is used to convert wrapper objects to
strings.

In the following example, we convert an Integer to a String, and use the length() method of
the String class to output the length of the "string":

Example
public class Main {
public static void main(String[] args) {
Integer myInt = 100;
String myString = [Link]();
[Link]([Link]());
}
}

You might also like