Java Notes 2024
Java Notes 2024
History of Java
Java was originally designed for interactive television, but it was too
advanced technology for the digital cable television industry at the time.
The history of Java starts with the Green Team. Java team members (also
known as Green Team), initiated this project to develop a language for
digital devices such as set-top boxes, televisions, etc. However, it was
suited for internet programming. After some time Java technology was
joined by Netscape.
Initially, Java was called "Greentalk" by James Gosling and at that time
the file extension was .gt.
Later on Oak was developed as a part of the Green Team project. Oak is a
symbol for strength and Oak is also a national tree in many countries like
the USA, Romania etc.
Oak was renamed as Java in 1995 because Oak was already a trademark
by Oak Technologies. Before selecting the Java word the team suggested
many names like dynamic, revolutionary, Silk, jolt, DNA, etc.
Features of Java
The features of Java are also known as java buzzwords. They are:
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Compiled and Interpreted
9. High Performance
10. Multithreaded
11. Distributed
1
12. Dynamic
Page
Simple:
Java is very easy to learn, and its syntax is simple, clean and easy to
understand.
Object-oriented:
Portable:
Platform Independent:
Secured:
Java is best known for its security. With Java, we can develop virus-free
systems. Java is secured because:
o No explicit pointer
o Java Programs run inside a virtual machine sandbox
Robust
Architecture-neutral:
High-performance:
Multithreaded:
Distributed:
Dynamic:
C++ vs Java
C++ Java
C++ is platform-dependent. Java is platform-independent.
C++ is mainly used for system Java is mainly used for application
programming. programming.
C++ supports Java doesn't support the goto
the goto statement. statement.
C++ supports multiple Java doesn't support multiple
inheritance. inheritance through class. It can
be achieved by interfaces in java.
C++ supports operator Java doesn't support operator
overloading. overloading.
C++ supports pointers. You can Java supports pointer internally.
write pointer program in C++. However, you can't write the
pointer program in java.
C++ supports both call by value Java supports call by value only.
and call by reference. There is no call by reference in
java.
C++ supports structures and Java doesn't support structures
unions. and unions.
code.
C++ supports virtual keyword Java has no virtual keyword. We
so that we can decide whether can override all non-static
or not override a function. methods by default.
At compile time, java file is compiled by Java Compiler (It does not
interact with OS) and converts the java code into bytecode.
What is JVM?
Java applications are called WORA (Write Once Run Anywhere). This
means a programmer can develop Java code on one system and can
expect it to run on any other Java enabled system without any
adjustment. This is all possible because of JVM.
• Loads code
• Verifies code
• Executes code
• Provides runtime environment
JVM Architecture
4. Stack : Java Stack stores frames.It holds local variables and partial
6
6. Native Method Stack : It contains all the native methods used in the
application.
1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler.
Java Keywords:
keywords are also known as reserved words. These are predefined words
by Java so it cannot be used as a variable or object name.
Variable
Variable is name of reserved area allocated in memory. In other words, it
is a name of memory location.
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called instance variable.
3) Static variable
It cannot be local.
You can create a single copy of static variable and share among all the
instances of the class. Memory allocation for static variable happens only
once when the class is loaded in the memory.
Example:
class A
{
int data=50;//instance variable
static int m=100;//static variable
void method()
{
int n=90;//local variable
}
}
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.
In Java language, primitive data types are the building blocks of data
manipulation. These are the most basic data types available in Java
language.
The eight classes of the java.lang package are known as wrapper classes
in Java. The list of eight wrapper classes are given below:
Autoboxing:
For example, byte to Byte, char to Character, int to Integer, long to Long,
float to Float, boolean to Boolean, double to Double, and short to Short.
9
Page
Since Java 5, we do not need to use the valueOf() method of wrapper
classes to convert the primitive into objects.
OUTPUT
20 20 20
Unboxing
Output
Page
10 10 10
Operators in Java
Operator is a symbol which is used to perform operations. For example:
+, -, *, / etc.
There are many types of operators in Java which are given below:
• Arithmetic operators
• Relation operators
• Logical operators
• Bitwise operators
• Assignment operators
• Conditional operators
• Widening Casting(Implicit)
When you are assigning a larger type value to a variable of smaller type,
then you need to perform explicit type casting. If we don't perform
casting then compiler reports compile time error.
Example:
OUTPUT
block will execute and if condition is false then block will not execute.
Page
Types of Decision Making Statement
1. if statements
2. if-else statements
3. if...else if... statement
4. Nested if-else statement
5. Switch statements
The if statement
Syntax:
if (condition)
{
// block of code will execute if the condition is true
}
If the condition evaluates to true, the code within if statement will
execute, but if the condition evaluates to false, then the code after the
end of if statement (after the closing of curly braces) will execute.
Syntax:
if (condition)
{
// block of code will execute if the condition is true
}
else
{
// block of code will execute if the condition is false
}
if (condition1)
{
// block of code will execute if condition1 is true
}
else if (condition2)
{
// block of code will execute if the condition1 is false and
condition2 is true
}
else
{
// block of code will execute if the condition1 is false and
condition2 is false
}
Syntax:
if (condition1)
{
Statement 1; //It will execute when condition1 is true
if (condition2)
{
Statement 2; //It will execute when condition2 is true
}
else
{
Statement 3; //It will execute when condition2 is false
}
}
Switch Statement
Syntax:
switch(expression)
{
case value1:
//code to be executed;
break; //optional
case value2:
//code to be executed;
break; //optional
......
14
default:
code to be executed if all cases are not matched;
Page
}
Looping Statement
for loop
Java for loop consists of 3 primary factors which define the loop itself.
These are the initialization statement, a testing condition, an increment or
decrement part for incrementing/decrementing the control variable.
A for loop is useful when you know how many times a task is to be
repeated.
Syntax:
While Loop
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
}
do while loop
The 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.
do
{
//code to be executed
}
while(condition);
We do not require to write code again and again. The method is executed
only when we call or invoke it.
Method Declaration
Return Type: Return type is a data type that the method returns. It may
have a primitive data type, object, collection, void, etc. If the method
does not return anything, we use void keyword.
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method:
In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.
Output:
User-defined Method
17
requirement.
public class Addition
{
public static void main(String[] args)
{
int a = 19;
int b = 5;
//method calling
int c = add(a, b);
System.out.println("The sum of a and b is = " + c);
}
//user defined method
public static int add(int n1, int n2)
{
int s;
s=n1+n2;
return s; //returning the sum
}
}
Output:
Example:
class Main
{
public int addNumbers(int a, int b)
{
int sum = a + b;
return sum;
}
public static void main(String[] args)
{
int num1 = 25;
int num2 = 15;
Output
18
Sum is: 40
Page
Command line argument
The command line argument is the argument that passed to a program
during runtime.
To access these arguments, you can simply traverse the args parameter
in the loop or use direct index value because args is an array of type
String.
For example, if we run a HelloWorld class that contains main method and
we provide argument to it during runtime, then the syntax would be like.
Output:
10
20
30
BufferedReader Class
Method Description
Example:
import java.io.*;
public class BufferedReaderExample
{
public static void main(String args[])throws Exception
{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter your name: ");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output
Enter your name:
Sachin Tendulkar
Welcome Sachin Tendulkar
20
Page
Scanner class
The Scanner class is mainly used to get the user input, and it belongs to
the java.util package.
Java provides various ways to read input from the keyboard, the
java.util.Scanner class is one of them.
The Java Scanner class breaks the input into tokens using a delimiter
which is whitespace by default. It provides many methods to read and
parse various primitive values.
There are various methods of Scanner class which can be used for
various data types.
Method Description
nextBoolean() Reads a boolean value from the user
nextByte() Reads a byte value from the user
nextDouble() Reads a double value from the user
nextFloat() Reads a float value from the user
nextInt() Reads an int value from the user
nextLine() Reads a String value from the user
nextLong() Reads a long value from the user
nextShort() Reads a short value from the user
Example:
import java.util.*;
public class ScannerExample
{
public static void main(String args[])
{
Scanner in = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = in.nextLine();
System.out.println("Name is: " + name);
in.close();
}
}
Output:
***End of UNIT-1***
21
Page
UNIT – 2
OOPs – Object Oriented Programming
Object-oriented programming (OOP) refers to a programming
methodology based on objects, instead of just functions and procedures.
The objects contain the data and the methods (or behaviour).
OOPs concepts:
Object:
Any entity that has state and behaviour is known as an object. For
example, a chair, pen, table, keyboard, bike, etc. It can be physical or
logical.
Class:
A class can also be defined as a blueprint from which you can create an
individual object. Class doesn't consume any space.
Inheritance:
When one object acquires all the properties and behaviours of a parent
object, it is known as inheritance. It provides code reusability. It is used
to achieve runtime polymorphism.
Polymorphism:
Abstraction:
Encapsulation:
Binding (or wrapping) code and data together into a single unit are known
as encapsulation. For example, a capsule, it is wrapped with different
medicines.
22
Page
o Fields
o Methods
o Constructors
o Blocks
o Nested class and interface
class <class_name>
{
field;
method;
}
Class variables also known as static variables are declared with the static
keyword in a class, but outside a method, constructor or a block. There
would only be one copy of each class variable per class, regardless of how
many objects are created from it.
Example:
Output
Instance variable = 0
Static variable = 30
Local variable = 100
23
Page
Methods in Java
Types of Method
There are two types of methods in Java:
o Predefined Method
o User-defined Method
Predefined Method:
In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as
the standard library method or built-in method. We can directly use
these methods just by calling them in the program at any point.
Output:
User-defined Method
int s;
s=n1+n2;
Page
Output:
The new keyword is used to allocate memory at runtime. All objects get
memory in Heap memory area.
Object:
An entity that has state and behaviour is known as an object e.g., chair,
bike, marker, pen, table, car, etc.
class Student
{
int id;//field or data member or instance variable
String name;
public static void main(String args[])
{
Student s1=new Student();//creating an object of Student
System.out.println(s1.id);//accessing member through reference
variable
System.out.println(s1.name);
}
}
Output:
O
null
class Student
{
int id;
String name;
}
class TestStudent1
{
public static void main(String args[])
{
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
25
}
Page
Objects as Parameters:
class Add
{
int a;
int b;
Output:
Sum of a and b : 13
26
Page
Garbage Collection
Advantages:
o It makes java memory efficient because garbage collector
removes the unreferenced objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM)
so we don't need to make extra efforts.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
27
finalize() method
The finalize() method is invoked each time before the object is garbage
collected. This method can be used to perform cleanup processing.
gc() method
The gc() method is used to invoke the garbage collector to perform
cleanup processing. The gc() is found in System and Runtime classes.
public static void gc(){}
Output:
object is garbage collected
object is garbage collected
Constructor
In Java, a constructor is a block of codes similar to the method. It is
called when an instance of the class is created. At the time of calling
constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one
constructor is called.
28
Page
Rules for creating a Java Constructor
Default Constructor
A constructor is called "Default Constructor" when it doesn't have any
parameter.
Example1:
class Demo
{
Demo()
{
System.out.println("This is a no argument constructor");
}
public static void main(String args[])
{
Demo obj = new Demo();
}
}
Example2:
class Student3
{
int id;
String name;
//method to display the value of id and name
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[])
{
Student3 s1=new Student3();
Student3 s2=new Student3();
29
s1.display();
Page
s2.display();
}
}
Output:
0 null
0 null
Parameterized Constructor
A constructor which has a specific number of parameters is called a
parameterized constructor.
Example:
class Student4
{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n)
{
id = i;
name = n;
}
//method to display the values
void display()
{
System.out.println(id+" "+name);
}
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
rollno=rollno;
name=name;
fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis1
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
0 null 0.0
31
0 null 0.0
Page
In this example, parameters (formal arguments) and instance variables
are same. So, we are using this keyword to distinguish local variable and
instance variable.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class TestThis2
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Output:
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)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}
}
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}
}
33
In this example, we have created two methods that differs in data type.
The first add method receives two integer arguments and second add
Page
In Java, a constructor is just like a method but without return type. It can
also be overloaded like Java methods.
class Student5
{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n)
{
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a)
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
Output:
111 Karan 0
222 Aryan 25
34
Page
Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the
properties and behaviours of a parent object.
The extends keyword indicates that you are making a new class that
derives from an existing class. The meaning of "extends" is to increase
the functionality.
The keywords extends and implements are used to inherit the features of
an already existing parent block in newly created child block. Using
extends keyword, a newly created class (subclass) can inherit the
features of an existing class (superclass). Using implements keyword a
newly created class can implement all the methods of an interface.
extends implements
The extends keyword is used to The implements keyword is used for
create a subclass using features of the implementation of an interface
a super class.
The extends keyword may not The implements keyword has to
override all the methods of a super implement all the methods of an
class. implemented interface.
A class can extend only one super A class can implement multiple
class. interafaces.
An interface can extend more than An interface cannot implement
one interface. another interface.
Example:
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}
Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}
Multilevel Inheritance
Example:
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
36
{
Page
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grand parent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}
Hierarchical Inheritance
Example:
class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class JavaExample
{
public static void main(String args[])
{
37
Multiple Inheritance
Example:
public abstract class SuperClass
{
public abstract void doSomething();
}
{
public void doSomething()
Page
{
System.out.println("doSomething implementation of B");
}
//ClassB own method
public void methodB()
{
}
}
public class ClassC extends ClassA, ClassB
{
public void test()
{
//calling super class method
doSomething();
}
}
For example, Student class can have reference of Address class but
vice versa does not make sense.
Class Address
{
int street_no;
String city;
String state;
int pin;
Address(int street_no, String city, String state, int pin )
{
this.street_no = street_no;
this.city = city;
this.state = state;
this.pin = pin;
}
}
39
Page
class Student
{
String name;
Address ad;
}
Here in the above code, we can see Student class has-a relationship
with Address class.
Interface in Java
An interface in Java is a blueprint of a class. It has static constants and
abstract methods.
In other words, you can say that interfaces can have abstract methods
and variables. It cannot have a method body.
interface <interface_name>
{
// declare constant fields
// declare methods that abstract by default.
}
Example:
interface B
{
}
Class A implements B
{
Example:
interface printable
{
void print();
}
class Derived implements printable
{
public void print()
{
System.out.println("Hello");
}
Output:
Hello
Class Interface
In class, you can instantiate In an interface, you can't instantiate
variable and create an object. variable and create an object.
Class can contain concrete(with The interface cannot contain
implementation) methods concrete (with implementation)
methods.
The access specifiers used with In Interface only one specifier is
classes are private, protected and used- Public.
public.
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Derived implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
Output:
Hello
Welcome
class A
{
}
class B extend A
{
A a1 = new B();
Here we can call the methods defined/declared in class ‘A’ but during
runtime it will call class B’s class overridden methods.
If the method is not overridden in child’s class then only parent’s method
which will be inherited to child will be called.
Example:
class Parent
{
int x=10;
void show()
{
System.out.println("parent-show");
}
void OnlyParentShow()
{
System.out.println("OnlyParentShow");
}
}
}
void OnlyChildShow()
Page
{
System.out.println("OnlyChildShow");
}
}
class ParentChild
{
child-show
OnlyParentShow
10
N.B:
show() is a method and overridden in child so child’s method is called.
Downcasting:
Example:
This is not possible because all the members of child class are not
available in parent.
If we call c.OnlyChildShow();
upcasting and then we can use that variable for downcasting as:
Page
Parent p = new Child();
Child c =(Child) p;
It is almost equivalent to
N.B:
Polymorphism
Polymorphism is one of the OOPs feature that allows us to perform a
single action in 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.
Method Overriding
If subclass (child class) has the same method as declared in the parent
class, it is known as method overriding in Java.
1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).
Example:
class Animal
45
{
public void eat()
Page
{
System.out.println("Eat all eatables");
}
}
Output:
Package
Package in Java is a collection of classes, sub-packages, and interfaces. It
helps organize your classes into a folder structure and make it easy to
locate and use them.
There are many built-in packages such as java, lang, awt, javax, swing,
net, io, util, sql etc.
Syntax:
package nameOfPackage;
Example:
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
3. java.util – This class contains basic utilities that can be useful while
implementing LinkedLists, Trees, HashMaps, and so on. It also has a
Scanner class for input-output operations to the program. It also contains
support for date and time.
Whenever you need to add a class within a package, just specify the
package name along with the “package” keyword at the beginning of the
program.
packages Mypack;
Example:
package mypack.testpack;
class MySubPackageProgram
{
public static void main(String args [])
{
System.out.println("My sub package program");
}
}
Output:
UNIT – 3
Arrays
An array is a collection of similar type of elements which has contiguous
memory location.
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.
48
Page
Advantages
Disadvantages
• Size Limit: We can store only the fixed size of elements in the
array. It doesn't grow its size at runtime.
Types of Array
dataType[] arr;
(or)
dataType []arr;
(or)
dataType arr[];
Instantiation of an Array
arrayRefVar=new datatype[size];
Example:
int a[]=new int[5];//declaration and instantiation
class Testarray
{
49
Output
10
20
30
40
50
We can declare, instantiate and initialize the java array together by:
class Testarray1
{
public static void main(String args[])
{
int a[]={33,3,4,5};
for(int i=0;i<a.length;i++)
{
System.out.println(a[i]);
}
}
}
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[];
Output:
123
245
445
Q: write a program to enter data into a 3x3 matrix and display it.
import java.util.Arrays;
import java.util.Scanner;
// read matrix
System.out.println("Enter 3x3 Matrix elements: ");
for(int i=0; i<3; i++)
{
for(int j=0; j<3; j++)
{
matrix[i][j] = obj.nextInt();
}
}
{
for(int j=0; j<3; j++)
Page
{
System.out.print(matrix[i][j]+ " ");
}
System.out.println();
}
}
}
Output
Enter 3x3 Matrix elements:
123456789
Entered Matrix:
123
456
789
3D array in Java
Here,
d1, d2, d3 = sizes of the dimensions
data_type = data type of the elements of the array
array_name = name of the 3d array
Example:
matrix[0][0][0] = 10;
matrix[0][0][1] = 20;
matrix[0][1][0] = 30;
52
matrix[0][1][1] = 40;
Page
matrix[1][0][0] = 80;
matrix[1][0][1] = 90;
matrix[1][1][0] = 15;
matrix[1][1][1] = 25;
// 2nd approach
int[][][] a = {{{15,20},{30,40}},{{25,50},{60,80}}};
Program:
public class ThreeDArrayEx
{
public static void main(String[] args)
{
//initialize 3-d array
int[][][] myArray = { { { 1, 2, 3 }, { 4, 5, 6 } }, { { 1, 4, 9 }, { 16,
25, 36 } }, { { 1, 8, 27 }, { 64, 125, 216 } } };
System.out.println("3x2x3 array is given below:");
//print the 3-d array
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 3; k++)
{
System.out.print(myArray[i][j][k] + "\t");
}
System.out.println();
}
System.out.println();
}
}
}
Output
3x2x3 array is given below:
1 2 3
4 5 6
1 4 9
16 25 36
1 8 27
64 125 216
String
String is a sequence of characters. But in Java, string is an object that
represents a sequence of characters.
1. By string literal
2. By new keyword
1) String Literal
1. String s="welcome";
Page
1. String s="welcome";
Each time you create a string literal, the JVM checks the "string constant
pool" first. If the string already exists in the pool, a reference to the
pooled instance is returned. If the string doesn't exist in the pool, a new
string instance is created and placed in the pool.
For example:
1. String s1="Welcome";
In the above example, only one object will be created. Firstly, JVM will not
find any string object with the value "Welcome" in string constant pool,
that is why it will create a new object. After that it will find the string with
the value "Welcome" in the pool, it will not create a new object but will
return the reference to the same instance.
2) By new keyword
In such case, JVM will create a new string object in normal (non-pool)
heap memory, and the literal "Welcome" will be placed in the string
constant pool. The variable s will refer to the object in a heap (non-pool).
Example:
55
charAt()
The java string charAt() method returns a char value at the given index
number.
The index number starts from 0 and goes to n-1, where n is length of the
string.
Example:
public class CharAtExample
{
public static void main(String args[])
{
String name="HelloJava";
char ch=name.charAt(4);//returns the char value at the 4th
index
System.out.println(ch);
}
}
OUTPUT
o
length()
The java string length() method length of the string. It returns count of
total number of characters. The length of java string is same as the
unicode code units of the string.
Example:
public class LengthExample
{
56
String s1="Hello";
String s2="java";
System.out.println("string length is: "+s1.length());
System.out.println("string length is: "+s2.length());
}
}
OUTPUT
5
4
substring()
We pass begin index and end index number position in the java substring
method where start index is inclusive and end index is exclusive. In other
words, start index starts from 0 whereas end index starts from 1.
Example:
public class SubstringExample
{
public static void main(String args[])
{
String s1="Hellojava";
System.out.println(s1.substring(2,4));//returns va
System.out.println(s1.substring(2));//returns vatpoint
}
}
OUTPUT
ll
llojava
Once string object is created its data or state can't be changed but a new
string object is created.
Example:
class Testimmutablestring
{
public static void main(String args[])
57
{
String s="Sachin";
Page
s.concat(" Tendulkar");
System.out.println(s);
}
}
OUTPUT
Sachin
Now it can be understood by the diagram given below. Here Sachin is not
changed but a new object is created with sachintendulkar. That is why
string is known as immutable.
Because java uses the concept of string literal. Suppose there are 5
reference variables, all refers to one object "sachin". If one reference
variable changes the value of the object, it will be affected to all the
reference variables. That is why string objects are immutable in java.
String compare
We can compare string in java on the basis of content and reference.
1. By equals() method
58
2. By = = operator
Page
3. By compareTo() method
1) String compare by equals() method
The String equals() method compares the original content of the string.
Example:
class Teststringcomparison1
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
}
OUTPUT
true
true
false
Example:
class Teststringcomparison3
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");
System.out.println(s1==s2);//true (because both refer to
same instance)
System.out.println(s1==s3);//false(because s3 refers to instance
created in nonpool)
}
}
OUTPUT
true
false
Example:
class Teststringcomparison4
{
public static void main(String args[])
{
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2));//0
System.out.println(s1.compareTo(s3));//1(because s1>s3)
System.out.println(s3.compareTo(s1));//-1(because s3 < s1 )
}
}
OUTPUT
0
1
-1
It is similar to String class in Java both are used to create string, but
stringbuffer object can be changed.
}
60
}
Page
OUTPUT
Hello
HelloJava
StringBuilder also used for creating string object that is mutable and non
synchronized. The StringBuilder class provides no guarantee of
synchronization. StringBuffer and StringBuilder both are mutable but if
synchronization is not required then it is recommend to use StringBuilder
class.
Java IO Stream
Java performs I/O through Streams.
Java encapsulates Stream under java.io package. Java defines two types
of streams. They are,
Byte stream is defined by using two abstract class at the top of hierarchy,
they are InputStream and OutputStream.
61
Page
These two abstract classes have several concrete classes that handle
various devices such as disk files, network connection etc.
These classes define several key methods. Two most important are
Character stream is also defined by using two abstract class at the top of
hierarchy, they are Reader and Writer.
62
Page
These two abstract classes have several concrete classes that handle
unicode character.
UNIT - 4
Exception Handling in Java
In this page, we will know about exception, its type and the difference
between checked and unchecked exceptions.
Exception
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10.statement 10;
Types of Exception:
There are mainly two types of exceptions: checked and unchecked where
error is considered as unchecked exception. The sun microsystem says
there are three types of exceptions:
1. Checked Exception
2. Unchecked Exception
3. Error
1)Checked Exception
The classes that extend Throwable class except RuntimeException and Error are
known as checked exceptions e.g.IOException, SQLException etc. Checked
exceptions are checked at compile-time.
2)Unchecked Exception
The classes that extend RuntimeException are known as unchecked exceptions
e.g. ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Unchecked exceptions are not checked at
compile-time rather they are checked at runtime.
3)Error
65
AssertionError etc.
Common scenarios of Exception Handling where exceptions may occur
There are given some scenarios where unchecked exceptions can occur.
They are as follows:
1. int a=50/0;//ArithmeticException
1. String s=null;
2. System.out.println(s.length());//NullPointerException
a[10]=50; //ArrayIndexOutOfBoundsException
1. try
2. catch
3. finally
4. throw
5. throws
try block
Java try block is used to enclose the code that might throw an exception.
It must be used within the method.
try
66
{
//code that may throw an exception
Page
}
catch(Exception_class_Name ref)
{
}
try
{
//code that may throw an exception
}
finally
{
}
Example:
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.
Example:
}
catch(ArithmeticException e)
{
System.out.println("Arithmetic Exception occurs");
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("ArrayIndexOutOfBounds Exception occurs");
}
catch(Exception e)
{
System.out.println("Parent Exception occurs");
}
System.out.println("rest of the code");
}
}
OUTPUT
Arithmetic Exception occurs
rest of the code
finally block
Java finally block is a block that is used to execute important code such
as closing connection, stream etc.
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;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
68
}
System.out.println("rest of the code...");
}
}
OUTPUT
5
finally block is always executed
rest of the code...
Case 2
Let's see the java finally example where exception occurs and not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
OUTPUT
finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Case 3
Let's see the java finally example where exception occurs and handled.
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:/ by zero
finally block is always executed
rest of the code...
throw keyword
Example:
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("not valid");
else
70
System.out.println("welcome to vote");
}
Page
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output:
Exception in thread main java.lang.ArithmeticException:not valid
Example:
import java.io.IOException;
class TestThrow1
{
void m()throws IOException
{
throw new IOException("device error");//checked exception
}
void n()throws IOException
{
m();
}
void p()
{
try
{
n();
}
catch(Exception e)
{
System.out.println("exception handled");
}
71
}
public static void main(String args[])
Page
{
TestThrow1 obj=new TestThrow1();
obj.p();
System.out.println("normal flow...");
}
}
OUTPUT
exception handled
normal flow...
throw throws
Java throw keyword is used to Java throws keyword is used to
explicitly throw an exception. declare an exception.
Checked exception cannot be Checked exception can be
propagated using throw only. propagated with throws.
Throw is followed by an instance. Throws is followed by class.
Throw is used within the method. Throws is used with the method
signature.
You cannot throw multiple You can declare multiple
exceptions. exceptions e.g.
public void method() throws
IOException, SQLException.
What is Thread?
A thread is a lightweight sub-process, the smallest unit of processing. It is
a separate path of execution.
Multithreading in Java
Multithreading in Java is a process of executing two or more threads
simultaneously to maximum utilization of CPU.
Multiple threads don't allocate separate memory area, hence they save
memory.
1) It doesn't block the user because threads are independent and you
Page
1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated
1) New
The thread is in new state if you create an instance of Thread class but
before the invocation of start() method.
2) Runnable
The thread is in runnable state after invocation of start() method, but the
thread scheduler has not selected it to be the running thread.
3) Running
The thread is in running state if the thread scheduler has selected it.
4) Non-Runnable (Blocked)
73
This is the state when the thread is still alive, but is currently not eligible
to run.
Page
5) Terminated
Example:
class MyThreadDemo
{
public static void main(String args[])
{
MyThread mt = new MyThread();
Thread t = new Thread(mt);
t.start();
}
}
classMyThreadDemo
{
74
{
MyThread mt = new MyThread();
mt.start();
}
}
}
public static void main(String args[])
{
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();
}
}
Output
running thread name is:Thread-0
running thread priority is:10
running thread name is:Thread-1
running thread priority is:1
75
Page
Java Synchronization
General Syntax:
synchronized (object)
{
//statement to be synchronized
}
Types of Synchronization
There are two types of synchronization:
1) Process Synchronization
Process Synchronization involves multiple processes or threads executing
simultaneously. They ultimately reach a state where these processes or
threads commit to a specific sequence of actions.
2) Thread Synchronization
In Thread Synchronization, more than one thread is trying to access a
shared space. The threads are synchronized in such a manner that the
shared space is accessed only by one thread at a time.
Interthread Communication
JDBC
JDBC stands for Java Database Connectivity, which is a standard Java API
for database-independent connectivity between the Java programming
language and a wide range of databases.
The JDBC API consists of classes and methods that are used to perform
76
various operations like: connect, read, write and store data in the
Page
database.
JDBC Architecture:
The JDBC API supports both two-tier and three-tier processing models for
database access. JDBC Architecture consists of two layers:
The JDBC driver manager ensures that the correct driver is used to access
each data source. The driver manager is capable of supporting multiple
concurrent drivers connected to multiple heterogeneous databases.
Advantage
• Easy to use
Disadvantage
The Native API driver uses the client-side libraries of the database. The
driver converts JDBC method calls into native calls of the database API. It
is not written entirely in java.
78
Page
Advantage
Disadvantage
This driver translates the JDBC calls into a database server independent
and Middleware server-specific calls. Middleware server further translates
JDBC calls into database specific calls. It is fully written in java.
Advantage
database.
Disadvantage
The thin driver converts JDBC calls directly into the vendor-specific
database protocol. That is why it is known as thin driver. It is fully written
in Java language.
Advantage:
Disadvantage:
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection
( "jdbc:oracle:thin:@localhost:1521:xe", "system", "password");
Statement stmt=con.createStatement();
con.close();
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+"
"+rs.getString(3));
}
catch(Exception e)
{
System.out.println(e);
}
}
}
In this example, we are connecting to an Oracle database and getting
data from emp table. Here, system and oracle are the username and
password of the Oracle database.
83
Page