0% found this document useful (0 votes)
13 views74 pages

Java Notes

The document provides an introduction to Java, highlighting its simplicity, platform independence, and features such as multithreading and security. It covers various programming concepts including data types, operators, control statements, loops, arrays, and strings, along with example programs for practical understanding. Additionally, it discusses tools for Java development and the Object-Oriented Programming (OOP) concepts.

Uploaded by

santoshi555666
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
13 views74 pages

Java Notes

The document provides an introduction to Java, highlighting its simplicity, platform independence, and features such as multithreading and security. It covers various programming concepts including data types, operators, control statements, loops, arrays, and strings, along with example programs for practical understanding. Additionally, it discusses tools for Java development and the Object-Oriented Programming (OOP) concepts.

Uploaded by

santoshi555666
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 74

JAVA INTRODUCTION

 Java is a simple programing language


 Writing, compilation and debugging a program is very easy in java
 It helps to create reusable code
 Java has more features,

1. Platform independent
2. Open source
3. Multithreading
4. More secure
5. Robust

1. Platform independent
 During the compilation the java program converts into byte code
 Using byte code we can run the application to any platform such as windows, mac, linux, etc

2. Open source:
 A program in which source code is available to the general public for use and/or modification
from its original design at free of cost is called open source

3. Multithreading:
 Java supports multithreading
 It enables a program to perform several task simultaneously

4. More secure:
 It provides the virtual firewall between the application and the computer
 So it’s doesn't grant unauthorized access

5. Robust:
 Java has got excellent inbuilt exception handling features.
 Auto allocation and deallocation of memory handled by JVM.

TOOLS:
1. Notepad
2. Net bean
3. Eclipse
4. J Developer-oracle
5. RAD-IBM
 Nowadays we mostly used eclipse (75% of the people using).

OOPS CONCEPT:
1. Class
2. Object
3. Abstraction
4. Encapsulation
5. Inheritance
6. Polymorphism

Java Escape Sequence:

\n Next Line
\t Tab
\r Enter Key
\\ Displays \
\" Displays "
\' Displayes '

Difference between print and println:

Print method displays the results and keeps the cursor on the same line. Println displays the result and
throws the cursor to the next line.

Data Types:

Integer:

Data Type Memory Size


Byte 1 byte
Short 2 bytes
Int 4 bytes
Long 8 bytes

Range Formula : -2^n-1 to +2^n-1 - 1

Float:

Float 4 Bytes
Double 8 bytes

Float can represent up to 7 digits accurately after decimal point, whereas double can represent up to 15
digits accurately after decimal point

Character:

Data Type Memory Size Range


0 to
Char 2 Bytes 65535
Unicode system is an encoding standard that provides a unique number for every character no matter
what t he platform, program or languate.

Operators:

Arithmetic Operators
Operator Description
+ adds two operands
- subtract second operands from first
* multiply two operand
/ divide numerator by denumerator
% remainder of division
++ Increment operator increases integer value by one
-- Decrement operator decreases integer value by one

Relation Operators
Operator Description
== Check if two operand are equal
!= Check if two operand are not equal.
> Check if operand on the left is greater than operand on the right
< Check operand on the left is smaller than right operand
>= check left operand is greater than or equal to right operand
<= Check if operand on left is smaller than or equal to right operand

Logical Operators
Operator Description Example
&& Logical AND (a && b) is false
|| Logical OR (a || b) is true
! Logical NOT (!a) is false

CONTROL STATEMENT:
1. if
2. if.else
3. else.if

variable name camel notation


Difference between "=" and "=="
 = is used to assigning the value
 == is used for condition checking

Example Program:
public class IfCondition {
public static void main(String[] args) {
int empID=20;
if(empID==20){
System.out.println("valid");
}else {
System.out.println("not valid");
}
}
}

Output valid

Switch:
The Java switch statement executes one statement from multiple conditions. It is like if-else-if
ladder statement.
Example program:
public class sample {
public static void main(String[] args) {
int choice = 2;
switch (choice) {
case 1:
System.out.println("One");
break;
case 2:

System.out.println("Two");
break;
case 3:
System.out.println("THree");
break;
case 4:
System.out.println("Four");
break;
case 5:
System.out.println("Five");
break;
default:
System.out.println("Invalid");
break;
}
}
}
Note: Switch supports data types char, int , byte, short.
LOOPING:
1. for
2. while
3. do.while

For:
Example Program:
public class ForLoop {
public static void main(String[] args) {
System.out.println("Start");
for (int i = 1; i <= 3; i++) {
System.out.println(i);
}
System.out.println("End");

}
}
output:
Start
1
2
3
End
Inner for loop;
Example Program:
public class InnerForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 6; j++) {
System.out.print(i);
}
System.out.println();
}}}
Output:
111111
222222
333333
444444
555555
Println printline
Break:
 It will exit from the current loop

Example Program:
public class InnerForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break;
}
System.out.println(i);
}
}}
Output:
1
2
3
4

Continue:
 It will skip the particular iteration

Example Program:
public class InnerForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
System.out.println(i);
if (i == 5) {
continue;
}

}
}
}

Output
1
2
3
4
6
7
8
9
10

Basic programs using conditional statements:


EVEN NUMBER AND ODD NUMBER:
To print Even num:
Example Program:
public class InnerForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
output
2
4
6
8
10
12
14
16
18
20

To print Odd:
Example Program:
public class InnerForLoop {
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 1) {
System.out.println(i);
}
}
}
}
Output
1
3
5
7
9
11
13
15
17
19

Sum of odd:
Example Program:
public class SumofOddNum {
public static void main(String[] args) {
int count=0;
for(int i=1;i<=100;i++)
{
if(i%2==1){
count=count+i;
}
}
System.out.println(count);
}
}

Output:
2500
Factorial Numbers:
Example Program:
public class FactorialNumbers {
public static void main(String[] args) {
int count=1;
for(int i=1;i<=8;i++){
count=count*i;
}System.out.println(count);
}
}

Output:
40320
Another Example:
class ForLoopExample2 {
public static void main(String args[]){
for(int i = 1;;;){
System.out.println("The value of i is: "+i);
}
}
}

While:
 It is a entry level condition checking
Example Program:
public class sample {
public static void main(String[] args) {
int a = 10;
while (a <= 10) {
System.out.println(a);
a++;
}
}
}
Output :
10
Do-While:
 it is a exit level condition checking
 In do-while , even if condition fails , it will print one time
Example program:
public class sample {
public static void main(String[] args) {
int a = 10;
bool result = false;
do {
System.out.println(a);
a++;
if(a==15){
result = true;
}
} while (!result);

}
}
Output :
10
11
12
13
14
Exercise:

1. Program to write : 0 1 1 2 3 5 8 13 21 ..
2. Write a program to display diamond structure

Input and Output:

Stream

1. Carrys Data from Keyboard to Memory

System.in – This represent InputStream Object which by default represents – Keyboard

System.out – PrintStream Object which represents – Monitor

System.err – PrintStream Object which represents – Monitor

System.in InputStrea Buffered Data


m Reader Reader

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

Br.readLine();

Scanner sc = new Scanner(System.in);

Sc.nextInt();

Sc.nextLine();

Sc.nextFloat();

Different between Scanner and Buffered Reader:

1. BufferedReader read the Stream whereas Scanner parse it as tokens (When


Scanner receives a input it breaks the input into several pieces)
2. Buffered reader is synchronized where Scanner is asynchronized.
3. Buffered reader is fast compare to Scanner

Arrays:

An Array represents a group of elements of same data type.

Types of Array:

1. Single dimensional arrays (1D)


2. Multi Dimensional Arrays(2D, 3D)

Creating one dimensional array:

1. Int marks[] = {1, 2, 3, 4, 5};


2. Int marks[];
Marks = new int[5];
3. Int marks[] = new int [5];
4. Int [] marks = new int [5];

Example Program:

public class BasicArray {


public static void main(String[] args) {
int num[]=new int[5];
System.out.println(num[2]);
}
}

Output: 0
 If we didn't assign any value, it will takes the default value of data types(int)
 Default value of int is 0

Example Program:
public class BasicArray {
public static void main(String[] args) {
int num[]=new int[5];
num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;
System.out.println(num[2]);
}
}
Output: 30
 Overwrite the value:
public class BasicArray {
public static void main(String[] args) {
int num[]=new int[5];
num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;
num[2]=300;
System.out.println(num[2]);
}}
Output:
300
 If we overwrite the value, it takes last one

To find array length:


public class BasicArray {
public static void main(String[] args) {
int num[]=new int[5];
num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;
num[2]=300;
int len=num.length;
System.out.println(len);
}}

Output:
5
Using for loop:
public class BasicArray {
public static void main(String[] args) {
int num[]=new int[5];
num[0]=10;
num[1]=20;
num[2]=30;
num[3]=40;
num[4]=50;
num[2]=300;
for(int i=0;i<num.length;i++)
System.out.println(num[i]);
}
}

Output:
10
20
300
40
50
Two dimensional array:

public class MatrixAddition {

public static void main(String[] args) {


Scanner s = new Scanner(System.in);
System.out.print("Enter number of rows: ");
int rows = s.nextInt();
System.out.print("Enter number of columns: ");
int columns = s.nextInt();
int[][] a = new int[rows][columns];
int[][] b = new int[rows][columns];
System.out.println("Enter the first matrix");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
a[i][j] = s.nextInt();
}
}
System.out.println("Enter the second matrix");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
b[i][j] = s.nextInt();
}
}
int[][] c = new int[rows][columns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
c[i][j] = a[i][j] + b[i][j];
}
}
System.out.println("The sum of the two matrices is");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
System.out.print(c[i][j] + " ");
}
System.out.println();
}
}
}

Here is a sample execution.

Enter number of rows: 2


Enter number of columns: 3
Enter the first matrix
347
184
Enter the second matrix
321
104
The sum of the two matrices is
668
288

Strings:

1. Collection of characters enclosed in double quote.

Creating a String:

1. String s = “Test”;
2. String s = new String(“Hello”);
3. Char arr[] = {‘T’, ‘e’, ‘s’, ‘t’};
String s = new String(arr);

Some Basic Methods:


charAt():
 It is used to print the particular character

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1="Vengat";
System.out.println(s1);
char ch = s1.charAt(2);
System.out.println(ch);
}
}

Output:
Vengat
n
 2 takes as 0 to 2 (i.e) 0 1 2> v e n

Equqls():
 equals is a method is used to check our string index is true or false

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Vengat";
System.out.println(s1);
boolean b = s1.equals("Vengat");
System.out.println(b);
boolean b1 = s1.equals("vengat");
System.out.println(b1);}}
Output:
Vengat
true
false
 b1 is false because equals() is case sensitive

Equalsignorecase():
 It is like a equals() method but it is not case sensitive

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Vengat";
System.out.println(s1);
boolean b = s1.equals("Vengat");
System.out.println(b);
boolean b1 = s1.equalsIgnoreCase("vengat");
System.out.println(b1);
}}

Output:
Vengat
true
true
contains():
 Contains() is a method , is used to check the particular character or word in the string

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello welcome to java class";
System.out.println(s1);
boolean b = s1.contains("welcome");
System.out.println(b);
}
}

Output:
Hello welcome to java class
true
 If we check other than the string index, it shows false

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello welcome to java class";
System.out.println(s1);
boolean b = s1.contains("welcome");
System.out.println(b);
boolean b1 = s1.contains("hai");
System.out.println(b1);
}
}

Output:
Hello welcome to java class
true
false
split():
 split() is a method, is used to split the string by space or character or word or whatever

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello welcome to java class";
String[] x = s1.split(" "); // here we split by space
System.out.println(s1.length());
System.out.println(x.length);
String[] x1 = s1.split("o"); // here we split by "o"
System.out.println(s1.length());
System.out.println(x1.length);
}
}

Output:
27 //this whole string length s1
5 // this is after splitting by spacex
27 //this whole string length s1
4 // this is after splitting by "o"x1
For loop:
Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello welcome to java class";
String[] x = s1.split(" "); // here we split by space
for(int i=0;i<x.length;i++){
System.out.println(x[i]);
}
}
}
Output:
Hello
welcome
to
java
class
toUpperCase() and toLowerCase():
 toUpperCase() is used to convert the string into uppercase
 toLowerCase() is used to convert the string into lowercase

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello";
String m = s1.toLowerCase(); // to convert lowercase
System.out.println(m);
String m1 = s1.toUpperCase(); // to convert upper
System.out.println(m1);
}
}
Output:
hello
HELLO
subString();
 It is used to print from, which character we want in the string index

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello java";
String m = s1.substring(2);
// to print from 3rd character 0 1 2 l l o j a v a
System.out.println(m);
String m1 = s1.substring(2, 6);
// upto 6, 0 1 2 3 4 5 6H e |l l o |
System.out.println(m1);
}}

Output:
llo java
llo
indexOf():
 It is used to print the position of the character in the string
 If it is available means, its print the relevant position
 But if the character is not available , it will print "-1"
 Same Character present multiple times, it takes first one position

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello java";
int m = s1.indexOf("o"); // "o", to print o position
System.out.println(m);
int m1 = s1.indexOf("b"); // "b" is not in the string, so it
print "-1"
System.out.println(m1);
int m2 = s1.indexOf("a"); // multiple character "a", it takes
first one
System.out.println(m2);
}
}

Output:
4
-1
7
lastIndexof():
 If multiple same character , it takes last one

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello java";
int m = s1.indexOf("o"); // "o", to print o position
System.out.println(m);
int m1 = s1.indexOf("b"); // "b" is not in the string, so it
print "1"
System.out.println(m1);
int m2 = s1.indexOf("a"); // multiple character "a", it takes
first one
System.out.println(m2);
int m3 = s1.lastIndexOf("a"); // multiple character "a", it takes
last one
System.out.println(m3);
}
}
Output:
4
-1
7
9
replace():
 replace() is a method ,it is used to replace the index character or word

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello world";
String m = s1.replace("world", "java"); // to replace world to
java
System.out.println(m);
}
}
Output:
Hello java

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "This is manual Testing";
String m = s1.replace("manual", "Automation"); // to replace
manual to Automation
System.out.println(m);
}
}

Output:
This is Automation Testing
isEmpty():
 It is used to check the index length is zero or not,
 If its zero, its true otherwise false

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "";
boolean m = s1.isEmpty();// here index is empty, so its true
System.out.println(m);
String s2 = " ";
boolean m1 = s2.isEmpty();
// here index is not empty because space included
System.out.println(m1); // space is also a one character
}
}

Output:
true
false
startsWith() and endsWith():
 It is used to check the index starts with particular word or character
 As well as ends with

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "Hello java class";
boolean m = s1.startsWith("Hello");
System.out.println(m);
boolean m1 = s1.endsWith("class");
System.out.println(m1);
}
}
Output:
true
true
ASCII value:
 To find ascii value

Example Program:
public class Dummy {
public static void main(String[] args) {
char ch='M';
int x=ch;
System.out.println(x);
}
}

Output: 77
 Every character have one ASCII value
 A-Z 65 to 90
 a-z 97 to 122
 0-9 48 to 57
 remaining special characters

compareTo():
 It is a method, it is used to compare the character based on ASCII value

Example Program:
public class Dummy {
public static void main(String[] args) {
String s="A";
int i = s.compareTo("A");
System.out.println(i);
}
}

Output:
0
Here, A ASCII value is 65, so 65-65=0
Example Program:
public class Dummy {
public static void main(String[] args) {
String s="A";
int i = s.compareTo("B");
System.out.println(i);
}}
Output:
-1
Here, 65-66=-1
 If we use many character, it will compare only first differing character

Example Program:
public class Dummy {
public static void main(String[] args) {
String s="ABCD";
int i = s.compareTo("ABFK");
System.out.println(i);
}
}

Output:
-3 // 67-70=3
 If it is different length and same accuration, the output will be based on length
Example Program:
public class Dummy {
public static void main(String[] args) {
String s="ABCD";
int i = s.compareTo("AB");
System.out.println(i);
}
}
Output:
2
Here, ABCD length is 4
AB2, 4-2=2
 If different length and different accuration , it will compare the first differing character

Example Program:
public class Dummy {
public static void main(String[] args) {
String s="ABCD";
int i = s.compareTo("ACLK");
System.out.println(i);
}
}
Output:
1
Here, 66-67=1, BC=1

String Comparison:

When an object is create by JVM, it returns the memory address of the object as a hexadicimal number
which called object reference. When a new object is created, a new reference number is allotted to it.
public class stringComparison {

public static void main(String[] args) {


// TODO Auto-generated method stub
String s1 = "Test";
String s2 = new String("Test");

if(s1 == s2){
System.out.println("Same");
}
else{
System.out.println("Not Same");
}
System.out.println("Comparison index " + s1.compareTo(s2));
}
}
String Constant Pool:

String constant pool also known as String literal pool is a separate block of memory where the string
objects are held by JVM. If a string object is created directly, using assignment operator then it is stored
in String constant pool

Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "vengat";
String s2 = "vengat"; // literal string(same value so its
share the memory)
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
String x1=new String("vengat");
String x2=new String("vengat");// non literal string( its
won't share, create new memory
System.out.println(System.identityHashCode(x1));
System.out.println(System.identityHashCode(x2));
}
}

 identityHashcode() is used to print the reference value(storage reference)

Output:
31168322 // literal string share the memory if same value
31168322
17225372
5433634 // but non literal won't share

String Buffer:

String buffer class objects are mutable. Methods associated with String buffer class directly modifiied
the data.

StringBuffer Methods:

1. Sb.append();
2. Sb.insert(int position, String value);
3. Sb.delete(int I , int j);
4. Sb.reverse();
5. Sb.toString();
6. Sb.length();
7. Sb.subString(int i, int j);
8. Sb.replace(int I, int j, String value);
Example Program:
public class StringBasic {
public static void main(String[] args) {
String s1 = "vengat";
String s2 = "prabu"; // mutable string
System.out.println("Immutable string");
System.out.println(System.identityHashCode(s1));
System.out.println(System.identityHashCode(s2));
String r = s1.concat(s2);
System.out.println(r);
System.out.println(System.identityHashCode(r));
StringBuffer x1=new StringBuffer("vengat");
StringBuffer x2=new StringBuffer("prabu");// mutable string
System.out.println("mutable string");
System.out.println(System.identityHashCode(x1));
System.out.println(System.identityHashCode(x2));
x1.append(x2);
System.out.println(x1);
System.out.println(System.identityHashCode(x1));
}
}

Output:
Immutable string
31168322
17225372
vengatprabu
5433634 // here it takes new memory for concordinattion
mutable string
2430287
17689166
vengatprabu
2430287 // but here it takes x1 memory

Classes and Methods:

Class code along with method code is stored in ‘Method Aread’ of JVM. When an object is created, the
memory is allocated in Heap.JVM produces a unique reference number for the object callsed hash code
number.

Employee e1 = new Employee();


System.out.println(e1.hashCode);

Accessing Objects:
public class TestMain {
public static void main(String[] args) {

Person raju = new Person();


raju.talk();
}
}

public class Person {


String name;
int age;

void talk(){
System.out.println("Hello, I am " + name);
System.out.println("My age is " + age);
}
}

Initializing the Instance Variable:

public class TestMain {


public static void main(String[] args) {

Person raju = new Person();


raju.name = "Raju";
raju.age = 40;
raju.talk();
}
}

Access Modifiers:

1. Private
2. Public
3. Protected
4. Default

Question:

Can a class be private?

No, If we declare a class as private then it is not available to java compiler and hence a compile time
error occurs. Inner class can be private

Example Program:
public class TestMain {
public static void main(String[] args) {

Person raju = new Person();


Person venkat = new Person();
raju.talk();
venkat.talk();
}
}

public class Person {


private String name = "Raju";
private int age = 30;

void talk(){
System.out.println("Hello, I am " + name);
System.out.println("My age is " + age);
}
}

Output:

Hello, I am Raju
My age is 30
Hello, I am Raju
My age is 30

Constructors:

A Constructor is similar to a method that is used to intialize the instance variables. The sole purpose of a
constructor is to initialize the instance variables. A constructor has the following characteristics.

Person(){}

Person(String n, int i){}

1. The constructor name and class name should be same. Constructor should
end with pair of braces.
2. A Constructor may have or may not have parameters. Default constructors
and parameterized constructor
3. A Constructor doesn’t return any value
4. A constructor is automatically called and executed at the time of creating an
object.

Person raju = new Person()

Person raju = new Person(“Raju”, 22);

Example Program:
public class Person {
private String name;
private int age;

Person(String s , int i){


name = s;
age = i;
}
void talk(){
System.out.println("Hello, I am " + name);
System.out.println("My age is " + age);
}
}

public class TestMain {


public static void main(String[] args) {
Person raju = new Person("Raju", 30);
Person venkat = new Person("Venkat", 40);
raju.talk();
venkat.talk();
}
}

Understanding Methods:

public class TestMain {


public static void main(String[] args) {

Sum obj1 = new Sum(5, 6);


System.out.println("The sum is " + obj1.add());
}
}

public class Sum {


private double num1, num2;

public Sum(double x, double y){


num1 = x;
num2 = y;
}
public double add(){
return num1 + num2;
}
}

Static Methods:

A Static method is a method that doesn’t not act upon instance variables of a class. A static method is
declared by using the keyword ‘static’. Static methods are called using class. The reason why static
methods can not act on instance variables is that JVM first executes the static methods and they only it
created the objects. Since the objects are not available at the time of calling static methods. The
instance variables are also not available.
public class TestMain {
public static void main(String[] args) {
Sum obj1 = new Sum();
System.out.println("The sum is " + Sum.add(10, 11));
}
}
public class Sum {

public static double add(){


return num1 + num2;
}
}

Example Program:
public class TestMain {
public static void main(String[] args) {
Sum obj1 = new Sum();
System.out.println("The sum is " + Sum.add());
}
}
public class Sum {

static double x;
static int y;

public static double add(){


return x + y;
}
}

Instance Variable Vs Static Variable:

1. An instance variable is a variable whose separate copy is available to each


object. A Class variable is a variable whose single copy in memory is shared
by all objects.
2. Instance variables are created in the objects on heap memory. Class
variables are stored on method area.

Example Program:
public class TestMain {

public static void main(String[] args) {

staticVariables obj1 = new staticVariables();


staticVariables obj2 = new staticVariables();
++obj1.x;
System.out.println("x in Obj 1 " + obj1.x );
System.out.println("X in Obj 2 " + obj2.x);
}
}

public class staticVariables {

int x = 10;
}
This Keyword:

public class Person {

private String name;


private int age;

Person(String name , int age){


this.name = name;
this.age = age;
}

void talk(){
System.out.println("Hello, I am " + name);
System.out.println("My age is " + age);
}
}

public class TestMain {


public static void main(String[] args) {
Person raju = new Person("Raju", 40);
raju.talk();
}
}

Output:
12
vengat
vengat123@gmail.com
13
mohan
mohan123@gmail.com
14
vel
vel123@gmail.com

INHERITANCE:
 We can access one class property into another class using 'extend' keyword and reusuable
purpose

Child class Sub class


Parent class Super class
Types:
1. Single Inheritance
2. Multilevel Inheritance
3. Multiple Inheritances
4. Hybrid Inheritance
5. Hierarchical Inheritance

1. Single Inheritance :
 One parent class is directly support into one child class using extend keyword

Child Class Parent class

2. Multilevel Inheritance:
 One child class and more than one parent class

Child Class Parent Class Grand parent

3. Multiple Inheritance:

Parent class Child class Parent class

 More than one parent class parallely support into one child class but it won't suport in java
because

1. Priority problem
2. Compilation error/syntax error
(i.e) if both parent class having same method name it will get priority problem so it doesn;t work in java
Parent class child class  parent class

test () test()
 test () is a method name, it present in both parent class, so its get priority problem

4.Hybrid Inheritance:
 It is a combination of single and multiple inheritance

Class A

Class B Class C

Class D

5. Hierarchical Inheritance:
 One parent class and more than one child class

Child Class Child Class Child Class

Parent Class

public class Calculation {


int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:" + z);
}
public static void Subtraction(int x, int y) {
z = x - y;
System.out.println("The difference between the given numbers:" +
z);
}
}

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

Super Keyword:

1. It is used to differentiate the members of superclass from the members of


subclass, if they have same names.

2. It is used to invoke the superclass constructor from subclass.

class Super_class {

int num = 20;

public void display() {

System.out.println("This is the display method of superclass");

public class Sub_class extends Super_class {

int num = 10;

public void display() {

System.out.println("This is the display method of subclass");

public void my_method() {


Sub_class sub = new Sub_class();

sub.display();

super.display();

System.out.println("value of the variable named num in sub class:"+ sub.num);

System.out.println("value of the variable named num in super class:"+ super.num);

public static void main(String args[]) {

Sub_class obj = new Sub_class();

obj.my_method();

POLYMORPHISM:
 Poly-many
 Morphism-forms
 Taking more than one forms is called polymorphism or one task completed by many ways

It has 2 types,
1.Method overloading(static binding/compile time polymorphism)
2.Method overriding(dynamic binding/run time polymorphism)

1.Method overloading:
Class-same
Method-same
Argument-differ

 In a same class method name is same and the argument is different is called method overloading
 the argument is depends on
 data types
 data types count
 data type order

Example Program:
public class overLoading {
void add(int a, int b) {
System.out.println("The sume of two is " + (a + b));
}
void add(int a, int b, int c) {
System.out.println("The sum of three is " + (a + b + c));
}
}

public class overMain {


public static void main(String[] args) {
// TODO Auto-generated method stub
overLoading obj = new overLoading();
obj.add(5, 6);
}
}

2.Method overriding:
Class name-differ(using extends)
Method-same
Argument- same
 In a different class , the method name should be same and argument name should be same is
called overriding

Example Program:

class Bank{

int getRateOfInterest(){return 0;}

class SBI extends Bank{

int getRateOfInterest(){return 8;}

class ICICI extends Bank{

int getRateOfInterest(){return 7;}

class Test2{

public static void main(String args[]){


SBI s=new SBI();

ICICI i=new ICICI();

System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());

System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());

Can we override static method?

No, Static Method cannot be overridden. Because, static method is bound with class whereas
instance method is bound with object. Static belongs to class area and instance belongs to
heap area

Encapsulation:

Encapsulation in java is a mechanism of Wrapping the data and code together as a single unit. it is also
known as data hiding where variable are hidden outside of the class.

Example:
class Student {
private String name;

public String getName() {


return name;
}

public void setName(String name) {


this.name = name;
}
}

public class commandLineArguments {

public static void main(String[] args) {


Student s = new Student();
s.setName("vijay");
System.out.println(s.getName());
}
}
Singleton Driver:
public class Singleton {

private static Singleton singleton = new Singleton();

private Singleton() {
}

public static Singleton getInstance(String userName, String passWord) {


if (userName.equals("Abu") && passWord.equals("Test123"))
return singleton;
return null;
}

public void display(){


System.out.println("Display Function");
}

public class commandLineArguments {

public static void main(String[] args) {


Singleton tmp = Singleton.getInstance("Abu", "Test123");
tmp.display();
}
}

ABSTRACTION:
public class MyClass {
void calculate(double x) {
System.out.println("Square " + (x * x));
}
}

class common {
public static void main(String args[]) {
MyClass obj1 = new MyClass();
MyClass obj2 = new MyClass();
MyClass obj3 = new MyClass();
obj1.calculate(3);
obj2.calculate(3);
obj3.calculate(3);
}
}
 Abstraction is a process of hiding the implementation details from the user
 it has 2 types,

1.Partially abstraction(abstract class)


2.Fully abstraction(interface)

1.Partially Abstraction(Abstract class):


 It will support abstract method (without method body) and non-abstract method.
 We can’t create object for abstract class because in the method signature we didn't mention any
business logic. so
 In abstract method, we only mention abstract signature, won't create business logic
 It have 2 class, abstract class(sub class) and super class. we create object and business logic only
in super class, won't create in abstract class

Example Program:

abstract class
public abstract class Bank {
abstract void saving(); //method signature
abstract void current();
abstract void salary();
abstract void joint();
public void branchDetails(){
System.out.println("chennai");
}
}

super class
public class AxisBank extends Bank {
public void saving() { // method signature
System.out.println("saving regular"); // business logic
}
public void current() {
System.out.println("current");
}
public void salary() {
System.out.println("salary");
}
public void joint() {
System.out.println("joint");
}
public static void main(String[] args) {
AxisBank info = new AxisBank();
info.branchDetails();
info.salary();
info.saving();
}
}

Output:
chennai
salary
saving regular
2. INTERFACE/FULLY ABSTRACTION;
 It will support only abstract method, won't support non abstract method
 In interface "public abstract" is default. we no need to mention
 It using implements keywords

Example Program:1
interface
public interface Bank {
abstract void saving();
abstract void current();
abstract void salary();
abstract void joint();
public void branchDetails();
}
super class
public class AxisBank implements Bank {
public void saving() {
System.out.println("saving regular");
}
public void current() {
System.out.println("current");
}
public void salary() {
System.out.println("salary");
}
public void joint() {
System.out.println("joint");
}
public void branchDetails() {
System.out.println("chennai");
}
public static void main(String[] args) {
Bank info = new AxisBank();
info.branchDetails();
info.salary();
info.saving();
}
}
Output:
chennai
salary
saving regular
 multiple inheritance its won’t support in java but using interface its support
 here we have to create 2 interface(super class) and one sub class(normal). In the sub class we
implement both interface

Example Program:2
interface
public interface AxisBank {
public void test();
}
public interface HdfcBank {
public void test();
}
sub class(normal class)
public class Bank implements AxisBank, HdfcBank{
@Override
public void test() {
// TODO Autogenerated method stub
}
}

Difference between abstract class and interface


Abstract class:
 It is partially abstraction
 It support both abstract method and non-abstract method
 It’s using "extends" keyword
 Here "public abstract" have to mention

Interface:
 It is fully abstraction
 It support only abstract method
 It’s using "implement" keyword
 "public Abstract" is default. no need to mention

Example Program:2
interface
public interface AxisBank {
public void test();
}
public interface HdfcBank {
public void test();
}
sub class(normal class)
public class Bank implements AxisBank, HdfcBank{
@Override
public void test() {
// TODO Autogenerated method stub
}
}

Difference between abstract class and interface


Abstract class:
 It is partially abstraction
 It support both abstract method and non-abstract method
 It’s using "extends" keyword
 Here "public abstract" have to mention

Interface:
 It is fully abstraction
 It support only abstract method
 It’s using "implement" keyword
 "public Abstract" is default. no need to mention

Wrapper Classes in Java:

 They convert primitive data types into objects.


 The classes in java.util package handles only objects and hence wrapper classes help in this case
also.
 Data structures in the Collection framework, such as ArrayList and Vector, store only objects
(reference types) and not primitive types.

Data types Size Wrapper Class Default value


byte 1 Byte 0
short 2 Short 0
int 4 Integer 0
long 8 Long 0
float 4 Float 0.0
double 8 Double 0.0
boolean - Boolean false
char - Character -
Common Functions in Wrapper Class:

compareTo(Integer Obj) – This method compares the numerical value of two interver class objects and
returns 0, -ve value or +ve value

equals(Intger Obj) – Returns true or false

toString() – returns String of integer

parseInt(value) - To parse the input data to Respective wrapper type.

Command Line Arguments:

Command line arguments are used to get the data from the user during run time.

Example 1:

Input: Test
public class commandLineArguments {

public static void main(String[] args) {

System.out.println("Your first argument is: "+args[0]);


}
}

Output:

Your first argument is: This

Example 2:
public class commandLineArguments {
public static void main(String[] args) {

String strValue = args[0];


double doubleValue = Double.parseDouble(args[1]);
int intValue = Integer.parseInt(args[2]);
System.out.println("String Value" + strValue);
System.out.println("double Value" + doubleValue);
System.out.println("Integer Value" + intValue);
}
}

OutPut:

String Value Test


double Value 38.0
Integer Value 40

COLLECTIONS:
Why we go for collections:
 It will support dissimilar data types.
 It is dynamic memory allocation
 No memory wastage like array

It has 3 types,
1. List
2. Set
3. Map
1. List :( Interface)
 ArrayList(class)
 LinkedArrayList(c)
 vector(c)

2.Set:(Interface)
 Hashset(c)
 Linked hashset(c)
 Treeset(c)

3.Map:(Interface)
 Hashmap(c)
 Linked hashmap(c)
 Treemap(c)
 Hashtable(c)

List:
ArrayList:
Syntax:
List ex=new ArrayList();
Here,
Listinterface
exobject name
ArrayList() class
Example Program:
public class ArList {
public static void main(String[] args) {
List ex=new ArrayList();
ex.add(10);
ex.add(10000000000000000l);
ex.add(10.12f);
ex.add("Hai");
ex.add("A");
ex.add(true);
System.out.println(ex);
}
}
Output:
[10, 10000000000000000, 10.12, Hai, A, true]
 add() is a method, it is used to insert a value.
 Arraylist will display the output based on the insertion order

Generics:
 It will support particular datatypes or object only
 It is a features of jdk 1.5
 In the generics, we can mention only wrapper class
 < >- This is generic symbol, is used to define the particular datatype
 If we need integer datatype,

syntax:
List<Integer> ex=new ArrayList<Integer>();
Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
System.out.println(ex);
}
}

Output:
[10, 20, 30, 40, 40, 50]
 List allows the duplicate value
 ArrayList print in a insertion order

size():
 size is a method, it is used to find the size of the ArrayList

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
int i = ex.size();
System.out.println(i);
}}

Output:
6
get():
 get() is a method , it is used to print the particular value

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
int x = ex.get(3);
System.out.println(x);
}
}

Output:
40
 it takes the value from 0(i.e) 0 1 2 3 > 10 20 30 40

For loop:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
for(int i=0;i<ex.size();i++){
System.out.println(ex.get(i));
}
}
}

Output:
10
20
30
40
40
50
Enhanced for loop:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
for(Integer k:ex){
System.out.println(k);
}
}
}

Output:
10
20
30
40
40
50
Remove():
 remove is a method, it is used to remove the particular index value
 If we remove the particur index value, index order will not change
 After that the index value move to forward

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
ex.remove(3);
System.out.println(ex);
}
}

Output:
[10, 20, 30, 40, 50]
 In this output, index order is not change
 But the values moved to forward

Index based add():


 It is used to add the value based on the index

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
ex.add(2,100);
System.out.println(ex);
}
}

Output:
[10, 20, 100, 30, 40, 40, 50]
 In this o/p , if we insert one value based on index, after all the index value move to backward

set();
 set is a method, it is used to replace the value but index and value order will not change

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
ex.set(2,100);
System.out.println(ex);
}
}

Output:
[10, 20, 100, 40, 40, 50]
contains():
 contains() is a method it is used to check the particular value or object

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
boolean x = ex.contains(30);
System.out.println(x);
boolean y = ex.contains(100);
System.out.println(y);
}
}

Output:
true
false
clear():
 clear is a method it is used to clear the all index value

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
System.out.println(ex);// before clearing
ex.clear();
System.out.println(ex);// after clearing
}
}

Output:
[10, 20, 30, 40, 40, 50]
[]
indexof():
 indexof() is a method, it is used to print the position of the list

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
int x = ex.indexOf(30);
System.out.println(x);
}
}

Output:
2
Lastindexof():
 It is used to print the position from the last

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
int x = ex.lastIndexOf(40);
System.out.println(x);
}
}

Output:
4

addAll():
 addAll() is a method, it is used to copy from one list to another list

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
List<Integer> ex1 = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(40);
ex.add(50);
System.out.println(ex);
System.out.println(ex1);// before addAll
ex1.addAll(ex);
System.out.println(ex);
System.out.println(ex1);// After addAll
}
}

Output:
[10, 20, 30, 40, 40, 50]
[]
[10, 20, 30, 40, 40, 50]
[10, 20, 30, 40, 40, 50]
removeAll():
 removeAll() is a method , it is used to compare the both list and remove all the list1 values in list
2

(i.e)
list2=list2-list1
Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
List<Integer> ex1 = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex1.addAll(ex);
ex.add(100);
ex.add(200);
ex.add(300);
ex1.add(1000);
ex1.add(50);
ex1.add(2000);
ex1.add(3000);
System.out.println(ex);
System.out.println(ex1);
ex1.removeAll(ex);
System.out.println(ex1);
}
}

Output:
[10, 20, 30, 40, 50, 100, 200, 300]
[10, 20, 30, 40, 50, 1000, 50, 2000, 3000]
[1000, 2000, 3000]
 If we go for removeAll method, here ex1.removeAll(ex), ex1 compare to ex and remove all ex
values in the ex1.

retainAll():
 retainAll() is a method, it is used to compare both list and print the common values

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
List<Integer> ex1 = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex1.addAll(ex);
ex.add(100);
ex.add(200);
ex.add(300);
ex1.add(1000);
ex1.add(2000);
ex1.add(3000);
System.out.println(ex);
System.out.println(ex1);
ex1.retainAll(ex);
System.out.println(ex1);
}
}

Output:
[10, 20, 30, 40, 50, 100, 200, 300]
[10, 20, 30, 40, 50, 1000, 2000, 3000]
[10, 20, 30, 40, 50]
LinkedList:
systax:
List<Integer> ex = new LinkedList<Integer>();

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new LinkedList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
System.out.println(ex);
}
}
Output:
[10, 20, 30, 40, 50]
 it will also print in insertion order.

Vector:
syntax:
List<Integer> ex = new Vector<Integer>();
Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new Vector<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
System.out.println(ex);
}
}

Output:
[10, 20, 30, 40, 50]
 It will also print the same insertion order.
 in all the arraylist methods, will also support in LinkedList and Vector

ArrayList: Worst case


 In ArrayList deletion and insertion is a worst one because if we delete/insert one index value after
all the index move to forward/backward.
 It makes performance issue.

ArrayList: Best case


 In Arraylist retrieve/searching is a best one
 For ex we have 100 index is there, if we going to print 60th value, we can easily search

LinkedList: Best case


 Insertion and deletion is a best one because
 Here all values based on the seperate nodes. so, here we can easily delete/insert one value(i.e) if
we delete one value, the next node will join to the previous one

LinkedList: Worst case


 Searching/retrieving is a worst
 For ex, if we have 100 nodes, we have to print 90th node value, it will pass to all the previous
nodes and comes to first and then it will print.
 It’s makes performance issue

Difference between ArrayList and Vector:


ArrayList:
 Asynchronize
 It is not a thread safe

Vector:
 Synchronize
 Thread safe
Here,
Synchronize one by one(thread safe)
Asynchronizeparalally(not thread safe)
Example: ticket booking,
If one ticket is having,10 people is booking at a same time, what happen , the one person only booked the
ticket. because its a synchronize process. it allows one by one.
List<Integer> ex = new ArrayList<Integer>();
List<Integer> ex = new LinkedList<Integer>();
List<Integer> ex = new Vector<Integer>();
Example: Restaurant
You are in a restaurant with many other people. You order your food. Other people can also order their
food, they don't have to wait for your food to be cooked and served to you before they can order
here we can write these in different way,
ArrayList<Integer> ex = new ArrayList<Integer>();
LinkedList<Integer> ex = new LinkedList<Integer>();
Vector<Integer> ex = new Vector<Integer>();
User defined Array list:
 Here we can use our own data type

Class 1:
import java.util.ArrayList;
import java.util.List;

public class Employee extends New {

public static void main(String[] args) {


List<Employee> emp=new ArrayList<Employee>();
Employee E1=new Employee();
E1.setId(12);
E1.setName("vengat");
E1.setEmail("vengat123@gmail.com");
Employee E2=new Employee();
E2.setId(13);
E2.setName("mohan");
E2.setEmail("mohan123@gmail.com");
Employee E3=new Employee();
E3.setId(14);
E3.setName("vel");
E3.setEmail("vel123@gmail.com");
emp.add(E1);
emp.add(E2);
emp.add(E3);
for (Employee x : emp) {
System.out.println(x.getId());
System.out.println(x.getName());
System.out.println(x.getEmail());
}
}

List:
In the list we have to know these points,
 It is all insertion order
 It allows duplicate value
 It is index based

Set:
 It ignore the duplicate value
 It is value based

Hashset:
 It will print random order

Example Program:
public class ArList {
public static void main(String[] args) {
Set<Integer> ex = new HashSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
System.out.println(ex);
}
}
Output:
[50, 20, 40, 10, 30] // random order and ignore duplicate value
 It will allows one Null value and won't allow duplicate NULL

LinkedHashset:
 Insertion order
Example Program:
public class ArList {
public static void main(String[] args) {
Set<Integer> ex = new LinkedHashSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
System.out.println(ex);
}
}
Output:
[10, 20, 30, 40, 50] // insertion order
 It will also allows one Null value and won't allow duplicate NULL

TreeSet:
 Ascending order

Example Program:
public class ArList {
public static void main(String[] args) {
Set<Integer> ex = new TreeSet<Integer>();
ex.add(20);
ex.add(10);
ex.add(30);
ex.add(50);
ex.add(40);
ex.add(50);
System.out.println(ex);
}
}
Output:
[10, 20, 30, 40, 50]
Example Program:
public class ArList {
public static void main(String[] args) {
Set<String> ex = new TreeSet<String>();
ex.add("Ramesh");
ex.add("babu");
ex.add("Vasu");
ex.add("10000");
System.out.println(ex);
}
}

Output:
[10000, Ramesh, Vasu, babu]
Here,
 It will print ascending order
 Ascending order based on the ASCII value

(i.e)
 1ASCII value is 49
 RASCII value is 82
 VASCII value is 86
 bASCII value is 98

[49,82,86,98][10000, Ramesh, Vasu, babu] this is a way to print ascending order.


 TreeSet won't allow single Null value

Set:
 It is not maintaining any order(i.e)
 Hashset random order
 LinkedHashsetinsertion order
 Treeset ascending order
 It is value based

remove():
 remove is a method , it is used to remove particular value
public class ArList {
public static void main(String[] args) {
Set<Integer> ex = new TreeSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
ex.remove(40);
System.out.println(ex);
}
}

Output:
[10, 20, 30, 50]
 Normal for loop is not work here because it is not index based, it is value based

Enhanced for loop:


public class ArList {
public static void main(String[] args) {
Set<Integer> ex = new TreeSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
for(int i:ex){
System.out.println(i);
}
}
}

Output:
10
20
30
40
50
 All wrapper class default value is Null as well as all class default value is Null

Null:
 Null is a undefined/unknown/unassigned value
 Null is won't create any memory
 So Treeset will give exception in compile time if we use Null

Difference between List and Set:


List:
 It is all insertion order
 It allows duplicate value
 It is index based

Set:
 It is not maintaining any order(i.e)

Hashset random order


LinkedHashsetinsertion order
Treeset ascending order
 It is value based
 It ignores duplicate value

we can copy the values from List to set as well as set to list
Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex=new ArrayList();
Set<Integer> ex1 = new TreeSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
ex.add(10);
ex1.addAll(ex);
System.out.println(ex);
System.out.println(ex1);
}}

Output:
[10, 20, 30, 40, 50, 50, 10]
[10, 20, 30, 40, 50]
Here, set ignore the duplicate value
 we can find the duplicate count using size() method

Example Program:
public class ArList {
public static void main(String[] args) {
List<Integer> ex = new ArrayList();
Set<Integer> ex1 = new TreeSet<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
ex.add(50);
ex.add(50);
ex.add(10);
ex1.addAll(ex);
System.out.println(ex);
System.out.println(ex1);
int i = ex.size() ex1.size();
System.out.println(i);
}
}

Output:
[10, 20, 30, 40, 50, 50, 10]
[10, 20, 30, 40, 50]
2
Here 2 duplicate value is there

Map:
 It is key and value pair
 Here key+value is a one entry
 Key ignore the duplicate value and value allow the duplicate

Hashmap:
 It is a random order(based on key)

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
ex.put()
System.out.println(ex);
}
}

Output:
{50=fire, 20=Java, 40=.net, 10=Java, 30=sql}
 If duplicate key is there, it takes the last one
 Key will allows the only one Null
 Value allow the duplicate null

Linked Hashmap:
 Insertion order( based on key)
 Key will allows the only one Null
 Value allow the duplicate null

Map<Integer, String> ex = new LinkedHashMap<Integer, String>()

TreeMap:
 Ascending order(based on key)
 Key won't allow Null(even single null)
 Value allow the duplicate null

Map<Integer, String> ex = new TreeMap<Integer, String>()


Hashtable:
 Random order
 Both key and values are ignore the Null

Map<Integer, String> ex = new Hashtable<Integer, String>()


Difference between HashMap and HashTable:
HashMap:
 Key allows single null
 Asynchronies(not thread safe)

Hashtable:
 Key and value won't allow null
 Synchronize(thread safe)

Some Methods:
get():
 It is a method, it is used to print the value based on key

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
String s=ex.get(40);
System.out.println(s);
}
}
Output:
.net
keyset():
 It is a method, it is used to seperate the key

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
Set<Integer> s = ex.keySet();
System.out.println(s);
}
}

Output:
[50, 20, 40, 10, 30]
Value():
 It is a method, it is used to seperate the value

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
Collection<String> s = ex.values();
System.out.println(s);
}
}

Output:
[fire, Java, .net, Java, sql]

entryset():
 It is used to iterate the map

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
Set<Entry<Integer, String>> s = ex.entrySet();
for(Entry<Integer, String> x:s){
System.out.println(x);
}
}
}
Output:
50=fire
20=Java
40=.net
10=Java
30=sql
 We can print key and value seperately

Example Program:
public class ArList {
public static void main(String[] args) {
Map<Integer, String> ex = new HashMap<Integer, String>();
ex.put(10, "Java");
ex.put(20, "Java");
ex.put(30, "sql");
ex.put(40, ".net");
ex.put(50, "sales");
ex.put(50, "fire");
Set<Entry<Integer, String>> s = ex.entrySet();
for(Entry<Integer, String> x:s){
System.out.println(x.getKey());
System.out.println(x.getValue());
}
}
}

Output:
50
fire
20
Java
40
.net
10
Java
30
Sql

EXCEPTION:
 Exception is like a error, the program will terminated that line itself

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("Start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println(10/0);
System.out.println("4");
System.out.println("5");
System.out.println("End");
}

Output:
Start
1
2
3

Exception in thread "main" java.lang.ArithmeticException: / by zero


at org.exception.Exception.main(Exception.java:9)
 This is exception, if we getting error in run time , the program will be terminated from that line
 Here, java:9 is 9th line only we getting exception

Throwable:

Exception:
1. Unchecked exception(Exception that are checked by the JVM are called unchecked Exception)
2. Checked exception(Exception that are checked at compilation time by Java Compiler are called
checked exception)
Unchecked exception:
1. ArithmaticException
2. NullPointException
3. InputMismatchException
4. ArrayIndexOutOfBoundExcepion
5. StringIndexOutOfBoundExcepion
6. IndexOutOfBoundExcepion
7. NumberFormatException
Checked exception:
1. IOException
2. SQLException
3. FileNotFoundException
4. ClassNotFoundException

1. ArithmaticException:
 If we are trying to give any number divided by zero, we get Arithmatic exception.

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("Start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
System.out.println(10/0);
System.out.println("4");
System.out.println("5");
System.out.println("End");
}
}

Output:
Start
1
2
3
Exception in thread "main" java.lang.ArithmeticException: / by zero
at org.exception.Exception.main(Exception.java:9)

2. NullPointException:
 If we give Null in the string, it will throw the Null point exception. Because default value of
string is Null.

Example Program:
public class Exception {
public static void main(String[] args) {
String s= null;
System.out.println(s.length());
}
}

Output:
Exception in thread "main" java.lang.NullPointerException
at org.exception.Exception.main(Exception.java:6)

3.InputMismatchException:
 If we getting input from the user, the user need to give integer input but the user trying to input
string value , at this this we get input mismatch exception

Example Program:
public class Exception {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
System.out.println("PLs enter value");
int i=sc.nextInt();
System.out.println(i);
}
}

Output:
PLs enter value
hai
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at org.exception.Exception.main(Exception.java:9)

4. ArrayIndexOutOfBoundExcepion:
 In particular array, the index value is not available it will throw Array index of bound exception.

Example Program:
public class Exception {
public static void main(String[] args) {
int num[]=new int[4];
System.out.println(num[4]);
}

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
at org.exception.Exception.main(Exception.java:8)

5. StringIndexOutOfBoundExcepion:
 In particular String, the index value is not available it will throw String index Out of bound
exception.

Example Program:
public class Exception {
public static void main(String[] args) {
String s="Java";
char c = s.charAt(10);
System.out.println(c);
}
}

Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 10
at java.lang.String.charAt(Unknown Source)
at org.exception.Exception.main(Exception.java:8)

6. IndexOutOfBoundExcepion:
 In a list, the index value is not available it will throw index out of bound exception.

Example Program:
public class Exception {
public static void main(String[] args) {
List<Integer> ex = new ArrayList<Integer>();
ex.add(10);
ex.add(20);
ex.add(30);
ex.add(40);
System.out.println(ex.get(3));
System.out.println(ex.get(10));
}
}

Output:
40
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 10, Size: 4
at java.util.ArrayList.rangeCheck(Unknown Source)
at java.util.ArrayList.get(Unknown Source)
at org.exception.Exception.main(Exception.java:16)
7. NumberFormatException:
 if we give numbers in the string, we can convert the data type into integer. but if we give num and
char combination in the string, we can't convert to integer.
 if we trying to convert, it will throw number format exception

Example Program:
public class Exception {
public static void main(String[] args) {
String s="1234";
System.out.println(s+5);// string +5
int i = Integer.parseInt(s);
System.out.println(i+5);// Integer +5
String s1="123Abc45";
int j = Integer.parseInt(s1);
System.out.println(j+5);
}
}

Output:
12345
1239
Exception in thread "main" java.lang.NumberFormatException: For input string: "123Abc45"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at org.exception.Exception.main(Exception.java:13)

Exception:
The exception that are checked at compile time are called checked exception. The exception that re
checked at run time (JVM) called unchecked exception

public class firstProgram {

public static void main(String[] args) {


System.out.println("First program");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String valueEntered = br.readLine();
System.out.println("The Entered Value is " + valueEntered);
}
}

Checked Exception:
public class firstProgram {

public static void main(String[] args) throws IOException {


System.out.println("First program");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
String valueEntered = br.readLine();
System.out.println("The Entered Value is " + valueEntered);
}
}

Exception Handling:
1. Try
2. Catch
3. Finally
4. Throw
5. Throws
Errors:
1. Network error
2. JVM crack
3. out of memory
4. stack overflow
Try and catch:
 If we get exception, try will throw the exception and catch will catch the exception

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
try {
System.out.println(10/0);
}
catch(ArithmeticException e){
System.out.println("dont/by zero");
}
System.out.println("4");
System.out.println("5");
System.out.println("end");
}
}

Output:
start
1
2
3
dont/by zero
4
5
end
 Here we can enter the same exception or super class of the exception
(i.e)
 Super class of the all unexpected exception is run time exception/exception
 Super class of exception throwable
 So we can use runtime exception/exception/throwable instead of the particular exception

Example Program:
we can use throwable
try {
System.out.println(10/0);}
catch(Throwable e){
System.out.println("dont/by zero");
}
instead of
try {
System.out.println(10/0);}
catch(ArithmeticException e){
System.out.println("dont/by zero");
}
Finally:
 finally will execute always whether the exception through or not
 We can give the combination like trycatchfinally, we can't reverse/interchange
 If we give tryfinally, again it will show the exception

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
try {
System.out.println(10/0);}
catch(ArithmeticException e){
System.out.println("dont/by zero");
}finally{
System.out.println("final");
}
System.out.println("4");
System.out.println("5");
System.out.println("end");}}

Output:
start
1
2
3
dont/by zero
final
4
5
end

 Even if exception not through, finally will print

Example program:
public class Exception {
public static void main(String[] args) {
System.out.println("start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
try {
System.out.println(10/0);}
catch(NullPointerException e){
System.out.println("dont/by zero");
}finally{
System.out.println("final");
}
System.out.println("4");
System.out.println("5");
System.out.println("end");
}
}
Output:
start
1
2
3
final
Exception in thread "main" java.lang.ArithmeticException: / by zero
at org.exception.Exception.main(Exception.java:11)
 In between try ,catch and finally, we won't write any logics
 In one try block we can use n-number of catch blocks but we can't repeat the same exception
 In one try block we can handle only one exception

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
try {
System.out.println(10/0);}
catch(NullPointerException e){
System.out.println("null point");
}
catch(ArithmeticException e) {
System.out.println("dont/by zero");
}
finally{
System.out.println("final");
}
System.out.println("4");
System.out.println("5");
System.out.println("end");
}
}

Output:
start
1
2
3
dont/by zero
final
4
5
end
 In a try block, one catch we can use same excepion and another catch we use throwable exception
 At this time, it will through the first one if it is match, will print. if it is not correct will throw the
second
 throwable is the super class of all exception
 In more than one catch block, we can use like sub class and super class combination. But we can't
use reverse
sub class ArithmaticException, NullPointException,.....
super classThrowable/Exception
 if we give Super class and sub class combination, it will give compilation error

Example Program:
public class Exception {
public static void main(String[] args) {
System.out.println("start");
System.out.println("1");
System.out.println("2");
System.out.println("3");
try {
System.out.println(10/0);}
catch(NullPointerException e){
System.out.println("null point");
}
catch(Throwable e) {
System.out.println("dont/by zero");
}
finally{
System.out.println("final");
}
System.out.println("4");
System.out.println("5");
System.out.println("end");
}
}

Output:
start
1
2
3
dont/by zero
final
4
5
end
Example Program:
try {
System.out.println(10/0);}
catch(Throwable e) {
System.out.println("dont/by zero");
}
catch(NullPointerException e){
System.out.println("null point");
}
finally{
System.out.println("final");
}
 If we give like above, will get compile time exception/error because we can't reverse
 In one try block, we can write only one finally block

Throw and Throws:


Throw:
 Throw is a keyword, we can through any exception inside the method – basically for user defined
exception.
 At a time we can throw only one exception

Throws:
 Throws is a keyword, it is used to declare the exception(in method level) built in exception
 At a time we can declare more than one exception

Example Program:
public class Exception {
public static void main(String[] args) throws
InterruptedException, ArithmeticException,IOException{
info();
}
private static void info() throws IOException {
System.out.println("hello");
throw new IOException();
}
 If we try to throws the compile time exception in any method, we must handle it in compile time

You might also like