JAVA INTRODUCTION

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

JAVA INTRODUCTION :

- Java was introduced in 1995 by James Gosling at Sun Microsystems.

- James Gosling is considered as the father of Java.

- Java can used on many platforms and devices.

- Java is used to create mobile devices, softwares, web apss, desktop apps etc. etc.

- Java Code is processed through a compiler which translated our code into bytecode that an
operating system can read.

Our JAVA Code -------------> Compiler -----------> byteCode (001110010101010101) ------> OS can read

- Java is a programming language.

==================================================

Java Key Features :

- Object Oriented : Java uses the concepts like classes and objects. Java is a Object Oriented
Language.

- Platform Independence : It works on the concept of WORA (Write Once and Run Anywhere)

Lets say we can write the code on Windows Machine and we can run in Linux Machine.

- Automatic Memory Management : Java is basically having a terms as garbage collector which
automatically handles the memory allocation.

===================================================

3 major pillars that we have in JAVA :


1) JDK

2) JRE

3) JVM

1) JDK : Java Development KIT :

A complete toolkit for developing the Java Application or programs.

JDK = JRE + JVM

Whenever we are supposed to write the code, we need to have JDK for sure.

2) JRE : Java Runtime Enviroment :

It is a package that have all the neccesary libraries that we need to run the code.

3) JVM (Java Virtual Machine) :

- It is a component of JRE which actually execute the code.

JRE is the complete enviroment for running Java Code while JVM is a specific component within JRE
that actually executes the code.

===========================================================================

Eclipse IDE Setup

Java Setup

go to google.com

write Download Java


Download and install it.

JAVA AND ECLIPSE

Go to Google.com

Download JAVA

Download ECLIPSE

1) Download JAVA

2) Install JAVA

3) Press Window Button and write cmd

4) Open CMD (Command Prompt)

5) write java -version

It will show you the version of JDK that you have installed.

-----------------------------------------------------------------

1- Press Window Button Again

2- Write Environment Variable

3- Click Environment Variable Button

4- Click PATH under system Variables

5- Click PATH and Click EDIT

6- Click New

7- Go to you JDK installed bin file program files (generally in C drive)

8- Copy this path till bin folder.

9- Paste this in Step 6

10-Click OK
11- Click OK

Why we are setting up this Environment variable of Java in System Variable :

Answer : Sometimes, the system is unable to find Java in our machine so whenever we are adding
this bin path to Environment Variable,

our system is able to find Java.

------------------------------------------------------------------

Any Questions ???????????????

NO

------------------------------------------------------------------

For mac machines,

1) Write Download Java for Mac in Google.com

2) Open the Oracle Link

3) Go to Mac tab

4) Click on .dmg file and download will start.

5) Once the download is done, install this file.

6) go to terminal

7) Run the command as java -version

------------------------------------------------------------------

How to download ECLIPSE in our machine :

1) Write Download Eclipse in google.com


2) Open the first link of eclipse.org

3) Click on Download Button

4) It will redirect you to a new page, click on this new download button.

5) Now, ECLIPSE will be downloaded.

6) Open your downloads folder and double click on downloaded .exe file of ECLIPSE.

7) Your eclipse will be installed now.

8) Open Eclipse.

9) It will ask you a couple of options like "Eclipse IDE for Java Developers etc". ?

19) Click on "Eclipse IDE for Java Developers".

20) Your Eclipse will be installed in this way.

===================================================================

How to create new Java Project in Eclipse :

1) Click file

2) Click New

3) Select "Project".

4) Select Java Project (Double click on "Java Project" option).

5) Write any Project Name

6) Cilck on Finish

7) Your Java Project will be created

===================================================================

Double Click on Project and then right click on the src folder

Go to new and select the new package and create any new package with any name (Package name
should start with small Letter).

Right click on this package.

Go to New

click on "Class"
Now give any class name and make sure to start it with Capital letter.

Select checkbox of public static void main

Cick OK

===================================================================

How to create main method in Java :

Inside you class, write "main"

Press CTRL + Space

Select First Option or Press Enter

===================================================================

Whenever Java code runs, it looks for main method

To terminate a line in Java we have to use semicolon ;

To print anything in Console log in Java, we use System.out.println("any string you can pass here");

(The shortcut to write System.out.println is -> write syso and then press Ctrl + space)

To save a program, press CTRL + S

===================================================================

What are the data types in Java :

2 types

1) Primitive Data type

2) Non Primitive Data Type

Primitive Data Types :

- int
- double

- float

- char

- boolean

- byte

- short

- long

====================================================================

int -> It is used for whole numbers (integers).

Example :

age of a person is 25.

int age = 25;

Range : -2147483648 to 2147483647

=====================================================================

double : it is used for decimal numbers (floating point numbers)

Example is :

double price = 19.99

double can be used to store large decimal values

======================================================================

float : This is also used for decimal numbers but it less precise than double.
Example is :

float temperature = 36.6f;

It requires f at the end of number.

=====================================================================

char :

it is used for single character.

Example is :

char grade = 'A'

We need to always give the value in single quotes.

=====================================================================

boolean : it is used to store 'true'/'false' values.

It only stores true/false.

Example :

boolean isThisJavaBatchFunny = true;

=====================================================================

byte, short, long, String, Araays......

String :

It is a sequence of characters.
Example :

String myStr = "Subhadrshini, Prasanthi and Anmol comes in evening Java Automation Batch";

There is my Home and my Home name is "PerfectHeaven".

String homeName = "PerfectHeaven";

=====================================================================

short range :

-32768 to 32767

short int = 32760

short int = 10000

short sum = num1 + num2;

=====================================================================

DATA TYPE :

Primitive

Non-Primitive

Primitive : int, double, char, boolean, byte, long, short, float

Non-Primitive : String and Arrays

=====================================================================
String name1 = "Hmanshu";

String name2 = "Sathya";

String nameAfterConcatination;

nameAfterConcatination = name1 + name2;

System.out.println(nameAfterConcatination);

=====================================================================

How to write a variable name (common rule for all the data type):

There are very simple rules to write a variable name :

1) variable name cant be started with a number

Wrong Syntax :

int 1num = 25;

Correct Syntax :

int num1 = 25;

2) variable name cant have spaces :

Wrong Syntax :

String first name = "Himanshu";

Correct Syntax :
String firstName = "Himanshu";

3) variable name cant contain a special character (except $ and underscore) :

Wrong Syntax :

long *num = 2500000000;

long num* = 2500000000;

long nu*m = 2500000000;

Correct Syntax :

long _num = 2500000000;

long num_2 = 500000000;

4) variable name should be written in a camelCaseWay :

camelCasing : first word should be small, and first letter of every other word should be in CAPS.

String myFirstName = "Himanshu";

String myBrotherName = "Ashish";

int myBatchHeadCountInEveningBatch = 22;

char firstLetterOfMyFatherName = 'A';

=================================================================

if (compare) {

body

}
it is not neccesary to write the else statement.

=================================================================

if (compare) {

body

else {

body

=================================================================

switch case :

package basicJavaPrograms;

public class SwitchCaseUsage {

public static void main(String[] args) {

useSwitchCase();

}
public static void useSwitchCase() {

int day = 2;

switch(day) {

case 1:

System.out.println("Its Monday");

case 2:

System.out.println("Its Tuesday");

case 3:

System.out.println("Its Wednesday");

case 4:

System.out.println("Its Thursday");

case 5:

System.out.println("Its Friday");

default :

System.out.println("Its not a weekday ========== Please have


fun");

=========================================================

package basicJavaPrograms;

public class SwitchCaseUsage {


public static void main(String[] args) {

useSwitchWithLoop();

public static void useSwitchCase() {

int day = 2;

switch(day) {

case 1:

System.out.println("Its Monday");

break;

case 2:

System.out.println("Its Tuesday");

break;

case 3:

System.out.println("Its Wednesday");

break;

case 4:

System.out.println("Its Thursday");

break;

case 5:

System.out.println("Its Friday");

break;

default :

System.out.println("Its not a weekday ========== Please have fun");

public static void useSwitchForString() {

String name = "Happy";


switch(name) {

case "Himanshu":

System.out.println("This is a mentor");

break;

case "Prasanthi":

System.out.println("This is a learner");

break;

case "Anmol":

System.out.println("This is a learner");

break;

default :

System.out.println("not sure");

break;

public static void useSwitchWithLoop() {

String name = "Happy";

for(int i=1;i<=2;i++) { // i=1 // i=2

switch(name) {

case "Himanshu":

System.out.println("This is a mentor");
break;

case "Prasanthi":

System.out.println("This is a learner");

break;

case "Anmol":

System.out.println("This is a learner");

break;

default :

System.out.println("not sure");

break;

name = "Anmol";

// It is not mandatory to write the default code in switch case

==================================================================================
===

Keywords in Java :

package basicJavaPrograms;

public class Keywords {


public static void main(String[] args) {

// What are the keywords in Java :

/* Keywords are some reserved words that have a predefined meaning and can not be used
an identifier

* We can not give some variable name as as keyword name

* We can not give some method name as as keyword name

* We can not give some class name as as keyword name

*/

keywords that we use in Java :

// class

// public

// private

// protected

// static

// void

// int

// String
// float

// double

// short

// long

// byte

// char

// boolean

// if

// else

// for

// while

// do while

// continue

// break

// return

// final

// finally

// finalize

// switch

// super

// this

// case

// try

// catch

// finally

// throw

// throws

// abstract

// package

// new

// extends
// implements

// default

// interface

==================================================================================
===

Array In Java

An array in Java is used to hold many values of same data type.

- Array is always fixed in size (we need to define the size of an array when declaring it.

- Array can store the values of same data type

- Array values are accessed with index starts from 0 (zero).

- Array is defined by using square brackets []

int[] i = {2,3,4,12,15}; // This is the first way to define the array

int[] j = new int[8]; // This is the another way to define the array

int i[] = {2,14,78,90}; // this is also correct (very rare people use this)

int []i = {15,60,89,70}; // this is also correct (very rare people use this)

==================================================================================
===

ArrayIndexOutOfBoundsException :

We have an array size = 4


can we access its 5th element ??

==================================================================================
===

package basicJavaPrograms;

public class ArraysInJava {

public static void main(String[] args) {

methodForStringArray();

public static void methodForUnderstandingArrays() {

// int[] myArr = {45,86,900};

int[] myArr = new int[5]; // Total it can store only 5 values

myArr[0] = 500; // position1

myArr[1] = 87; // position2

myArr[2] = 90; // position3

myArr[3] = 92; // position4

myArr[4] = 2000; // position5

System.out.println("value at position 3 is :: " + myArr[2]);

public static void methodForStringArray() {


String[] myArr = {"Himanshu", "Sathya","Mohammad","Jegan G", "Anish","Rahul"};

// System.out.println("name at position 2 is :: " + myArr[1]);

// System.out.println("name at position 4 is :: " + myArr[3]);

// System.out.println("Total names in the array are :: " + myArr.length);

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

System.out.println(myArr[i]);

==================================================================================
===

String class

String is immutable - once created cant be destroyed.

String pool : if we have multiple variables with the same value, all the variables are pointing out to
the same value.

We have so many methods of String class that we can directly use.


package basicJavaPrograms;

public class StringInJava {

public static void main(String[] args) {

charAtMethod();

public static void stringProgram() {

// String Class

// This program is very very very important

String s1 = "Himanshu";

String s2 = "Himanshu";

String s3 = new String("Himanshu");

if(s1==s2) { // In case of String this == refers to the memory reference

System.out.println("s1 and s2 are equal"); // This will be printed

if(s1.equals(s2)) { // This compares the value of String

System.out.println("s1 and s2 are again equal"); // This will be printed

if(s1==s3) {

System.out.println("s1 and s3 are equal"); // This will not be printed

if(s1.equals(s3)) {

System.out.println("s1 and s3 are again equal"); // This will be printed

// This is an open forum - discuss altogether


public static void lowerCaseMethodOfString() {

String name = "HiManshu";

System.out.println("Name is :: " + name.toLowerCase()); // This is an inbuilt method

public static void upperCaseMethodOfString() {

String name = "HiManshu";

System.out.println("Name is :: " + name.toUpperCase()); // This is an inbuilt method

public static void compareTwoStrings() {

String name1 = "Himanshu";

String name2 = "HIMANSHU";

if(name1.equals(name2)) {

System.out.println("both the names are equal");

else {

System.out.println("names are not equal");

public static void comapareTwoStringWithIgnoreCase() {

String name1 = "Himanshu";

String name2 = "HIMANSHu";

if(name1.equalsIgnoreCase(name2)) {

System.out.println("both names are equal");

else {

System.out.println("both names are not equal");

}
public static void charAtMethod() {

String name = "Himanshu";

System.out.println("Char at position 2 in name is :: " + name.charAt(1));

==================================================================================
====

Access Modifiers

OOPS Concepts

==================================================================================
====

Use of Static and Instance variables :

There are 3 types of variables we have in Java :

1) Static Variable

2) Instance Variable

3) Local Variable

Local Variable :

package basicJavaPrograms;

public class LocalVariables {


public static void main(String[] args) {

String name1 = "Jegan G"; // name = Jegan G

String name2 = "Prasanthi";

methodForlocalVariableUsage();

System.out.println("name1 is :: " + name1);

System.out.println("name2 is :: " + name2);

// Local variables should always be initialized

// Local variables is having the limited scope

public static void methodForlocalVariableUsage() {

int i=10;

// System.out.println("value of i is :: " + i);

i = 1000;

// System.out.println("value of i is :: " + i);

String name1 = "Himanshu"; // name = Himanshu

String name2 = "Mukilan";

System.out.println("name1 is :: " + name1);

System.out.println("name2 is :: " + name2);

==================================================================================
===

Static Variable :
// static variable is having its existence at the class level

// we can't use the static keyword for a variable in a method because static works on class level

// Any other class can access the static variable/method of another class by using its className

// Example : className.staticMemberName (member means variables and methods)

package basicJavaPrograms;

public class ClassForStaticVariableInJava {

static String organisationName = "Guvi";

public static void main(String[] args) {

System.out.println("organisation name is :: " + organisationName);

public static void sum() {

int a = 10;

int b = 20;

int c = a + b;

System.out.println("sum is :: " + c);

package basicJavaPrograms;

public class Class2ToAccessStaticVariable {

public static void main(String[] args) {


String orgName = ClassForStaticVariableInJava.organisationName;

System.out.println("organisation name is :: " + orgName);

ClassForStaticVariableInJava.sum();

============================================================================

Instance Variable In Java :

Now, what do mean by instance..

instance means object.

It means, instance variable works at the object level.

How to create an object.

whenever we put "new" keyword before the classNameWithParanthesis(), its object is created.

package basicJavaPrograms;

public class Class1 {

public static void main(String[] args) {

}
public static void sum() {

System.out.println("I am sum method");

public static void subtract() {

System.out.println("I am subtract method");

public void multiply() {

System.out.println("I am multiply method");

public void divide() {

System.out.println("I am divide method");

package basicJavaPrograms;

public class Class2 {

public static void main(String[] args) {

Class1 myObject = new Class1();

myObject.multiply();

myObject.divide();
Class1.sum();

Class1.subtract();

package basicJavaPrograms;

public class Class2 {

public static void main(String[] args) {

Class1 myObject = new Class1();

myObject.multiply();

myObject.divide();

Class1.sum();

Class1.subtract();

Class1 myObject2 = new Class1();

myObject2.multiply();

myObject2.divide();

}
=============================================================================

Constructor In Java :

1) Constructor in java means a method that is having exactly the same name as className.

2) Contructor never has return statement.

3) Contructor will be called automatically when the object of its class is created.

4) Yes we can overload the constructor

5) There are 2 types of constructor : Default Construtor, Paramterized Constructor

package basicJavaPrograms;

public class ClassForConstuctor {

public ClassForConstuctor() {

System.out.println("I am a default constructor");

public void m1() {

System.out.println("i am m1");

public void m2() {

System.out.println("i am m2");

}
package basicJavaPrograms;

public class Class3 {

public static void main(String[] args) {

Class1.sum(); // static method calling

Class1.subtract(); // static method calling

new ClassForConstuctor(); // Object will be created & contructor is called

ClassForConstuctor myObject = new ClassForConstuctor(); // Object will be created


& contructor is called

myObject.m1();

myObject.m2();

// Static methods are called with the className in another class

// Non static methods are called with the object in another class

// Contructor is by default called when object of its class is created

package basicJavaPrograms;

public class ClassForConstuctor {

public static void main(String[] args) {

m2();
}

public ClassForConstuctor() {

System.out.println("I am a default constructor");

public void m1() {

System.out.println("i am m1");

public static void m2() {

System.out.println("i am m2");

new ClassForConstuctor();

What is a parametarized constructor :

What is a parameter :

package basicJavaPrograms;

public class ClassToUnderstandParameter {

public static void main(String[] args) {

subtract(25, 25);

m3(58, "Himanshu");
}

public static void sum(int a, int b) {

int c = a+b;

System.out.println("addition is ::" + c);

public static void subtract(int c, int d) {

int e = c - d;

System.out.println("subtraction is ::" + e);

public static void m3(int a, String b) {

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

System.out.println("name is :: " + b);

Parameterized Contsructor :

package basicJavaPrograms;

package basicJavaPrograms;

public class Class5 {

public Class5() {

System.out.println("I am in the default constructor");

}
public Class5(int number) {

System.out.println("I am in parameterized constrctor and number is :: " + number);

public Class5(int a, int b, int c) {

System.out.println("I am in parameterized constrctor and the summation is :: " +


(a+b+c));

public Class5(String firstName, String lastName) {

System.out.println("FullName is " + (firstName + lastName));

public Class5(String orgName) {

System.out.println("Organisartion name is :: " + orgName);

package basicJavaPrograms;

package basicJavaPrograms;

public class Class6 {

public static void main(String[] args) {

new Class5();

new Class5(15);

new Class5(15, 5, 5);


new Class5("Himanshu", "Guvi");

new Class5("Guvi");

===============================================================================

Access Modifiers :

What are the access modifiers :

1) Default

2) public

3) private

4) protected

==================================================================

- OOPS Concepts (Encapsulation - Getters and Setters, Abstraction , Polymorphism - Overloading and
Overridding, Inheritance)

- Difference between Abstract Class and Interface

- Interface Implementation

==================================================================
OOPS :

1) Encapsulation

2) Polymorphism

3) Abstraction

4) Inheritance

-------------------------------------------------------------------

Polymorphism :

Poly - many

phism - forms

Polymorphism - many forms

it means we are having many forms of a method

Overloading

Overridding

Overloading :

We have same method name in the same class, but we have 3 conditions in overloading.

1) methods having same name but no. of paramters are different

2) methods having same name but type of paramters are different

3) methods having same name, no. of parameters are same, type of parameters are same but order
of paramters are different

In case of constructor, we call it as constructor overloding.


In case of method, we call it as method overloading.

package basicJavaPrograms;

public class ClassForOverlodingConcept {

public static void main(String[] args) {

sum(50, 50);

sum(2, 2, 3);

sum(20, "Prasanthi");

sum("Prasanthi",30);

public static void sum(int a, int b) {

int c = a + b;

System.out.println("sum of 2 numbers is :: " + c);

public static void sum(int a, int b, int c) {

int d = a + b + c;

System.out.println("sum of 3 numbers is :: " + d);

public static void sum(int a, String b) {

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

System.out.println("name is :: " + b);

public static void sum(String a, int b) {

System.out.println("firstName is " + a);


System.out.println("numberNow is :: " + b);

============================================================================

Assignment is :

Q1 : Make a class with 5 constructors and call all these 5 constructors in same class by its object

Q2 : Make a class with 5 constructors and call all these 5 constructors in another class by its object

Q3 : Make a class with 5 overloaded methods and call all these 5 methods in the same class.

Q4 : Make a class with 5 overloaded methods and call all these 5 methods in the another class.

Status of Assignment :

Subhadarshini - Yes

Prasanthi - 3 Done

Jegan G - Yes

Sathya - Yes

Deepa - 1 Done, 3 left

Anish - 1 done, 3 left

Rathi Devi - Yes

Abhiramasundari - 1 done, 3 left

Shaffna - Yes

Manish - Yes

Prabhu - NO

Mukilan - NO

Madhunika - NO
Anmol - NO

Mohammad - NO

Anbarasan - NO

durairam - NO

============================================================================

- OOPS Concepts (Encapsulation - Getters and Setters, Abstraction , Polymorphism - Overloading and
Overridding, Inheritance)

- Difference between Abstract Class and Interface

- Interface Implementation

============================================================================

OOPS Concepts :

1) Polymorphism

2) Abstraction

3) Encapsulation

4) Inheritance

Polymorphism : Overloading and Overridding

Overloading is already covered above.

Overridding :

Overridding is an another type of Polymorphism.

Another names of overridding are : "Run Time Polymorphism", and "Dynamic Method Dispatch".
-----------------------------------------------------------------------------

Overloading is a concept that is application in single class.

Overridding is a concept that is applicable in Parent and Child Class.

To learn overridding we first need to learn what is "Inheritance".

What is Inheritance :

- Inheritance is one of the OOPS concept wherein one class can inhibit the data members of another
class by using Parent Child relation.

- 'extends' keyword is used to inherit another class.

- 'implements' keyword is used to inherit another interface.

Child Class can access parent class methods freely without creating the Object.

===============================================================================

Static and nonStatic method calling in same class :

package basicJavaPrograms;

public class StaticNonStaticCallingInSameClass {

public static void main(String[] args) {

m1Static();

m2Static();
}

public static void m1Static() {

System.out.println("I am m1Static ");

m2Static();

public static void m2Static() {

System.out.println("I am m2Static ");

public void m1NonStatic() {

System.out.println("I am m1NonStatic ");

m1Static();

m2NonStatic();

public void m2NonStatic() {

System.out.println("I am m2NonStatic ");

===============================================================================

use of return keyword :

how to create a method :


<accessModifier - public> <mention whether its a static or nonStatic> <return type void/int/String>
<methodName> () {

Body of method

package basicJavaPrograms;

public class UseOfReturnKeyword {

public static void main(String[] args) {

int num3 = 20;

int sumOf3Numbers;

sumOf3Numbers = sumOfTwoNumebrs(20,10) + num3;

System.out.println("summation of 3 numbers is :: " + sumOf3Numbers);

public static int sumOfTwoNumebrs(int num1, int num2) {

int c = num1 + num2;

return c;

==================================================================================
===

package basicJavaPrograms;
public class UseOfReturnKeyword {

public static void main(String[] args) {

int num3 = 20;

int sumOf3Numbers;

sumOf3Numbers = sumOfTwoNumebrs(20,10) + num3 + 100;

System.out.println("summation of 3 numbers is :: " + sumOf3Numbers);

public static int sumOfTwoNumebrs(int num1, int num2) {

int c = num1 + num2;

int d = 5;

int e = 5;

int f = c + d + e;

return f;

==================================================================================
===

Overridding :

ClassA - Child

ClassB - Parent

ClassC - Overridding
package basicJavaPrograms;

public class ClassAChild extends ClassBParent {

public void showGuviDetails() {

System.out.println("I am a child class method");

package basicJavaPrograms;

public class ClassBParent {

public void showGuviDetails() {

System.out.println("I am a parent class method");

package basicJavaPrograms;

public class ClassCForOverridding {

public static void main(String[] args) {

ClassBParent obj1 = new ClassBParent();

// obj1.showGuviDetails();
System.out.println("=================================");

ClassAChild obj2 = new ClassAChild();

// obj2.showGuviDetails();

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

// ClassAChild obj3 = new ClassBParent(); // This is wrong statement

ClassBParent obj4 = new ClassAChild();

obj4.showGuviDetails();

obj4 = new ClassBParent();

obj4.showGuviDetails();

===================================================================

Encapsulation :

- Encapsulation is one of the OOPS concepts of Java.

- Encapsulation means we are encapsulating data memebers in a class.

- We are hiding the implemenation details from other users.

- We use getters and setters in encapsulation.

use of this keyword in java :


this keyword is used to have a reference of same class.

this.num means we are referring the num variable of same class where in this line is written.

----------------------------------------------------------------

package basicJavaPrograms;

public class ClassForEncapsulation {

private int num;

public void setNum(int num) {

this.num = num;

public int getNum() {

return this.num;

package basicJavaPrograms;

public class CallingEncapsulationDataMembers {

public static void main(String[] args) {

ClassForEncapsulation myObj = new ClassForEncapsulation();

myObj.setNum(10);
myObj.getNum();

================================================================================

Inheritance :

- This is one of the OOPS concept of Java.

- Multi Level Inheritance is allowed in Java.

- Multiple Inheritance is not allowed in Java (for classes)

- Mulitiple Inheritance is allowed in Java only in case of Interface.

- extends keyword is used to inherit a class.

- implements keyword is used to inherit a interface

Class A extends Class B - Correct

Class B extends Class C - Correct

Class A extends Class B,C - Incorrect

Class A imlpements interface B,C - Correct

package basicJavaPrograms;

public class ClassA extends ClassB{

public static void main(String[] args) {

ClassA a = new ClassA();


a.callMethod();

public void callMethod() {

sum();

subtract();

package basicJavaPrograms;

public class ClassB extends ClassC{

public static void main(String[] args) {

public void sum() {

System.out.println("I am sum method of classB");

package basicJavaPrograms;

public class ClassC {


public void sum() {

System.out.println("sum method of ClassC");

public void subtract() {

System.out.println("subtract method of ClassC");

=================================================================================

Use of Super Keyword In Java :

Super Keyword is used to call Parent Class methods/variables/constructor.

package basicJavaPrograms;

public class ClassParent1 {

public void sum() {

System.out.println("I am sum method of Parent Class");

package basicJavaPrograms;

public class ClassChild1 extends ClassParent1{


public static void main(String[] args) {

ClassChild1 myObj = new ClassChild1();

myObj.callSumMethod();

public void sum() {

System.out.println("I am sum method of Child Class");

public void callSumMethod() {

super.sum();

Important Thing about super keyword is :

- Whenever the child class is called, its parent class constructor will always be called.

- It means super() (of parent class) is always hidden.

- It means if we have constructor in child class and parent class both, in that case also whenever we
are creating the object of child class,

first of all Parent Class Constuctor will be called and then child class constructor will be called.

- The first line (hidden line) of every constructor is "super();"

package basicJavaPrograms;

public class ClassParent1 {

public void sum() {


System.out.println("I am sum method of Parent Class");

public ClassParent1() {

System.out.println("I am default constructor of Parent Class");

package basicJavaPrograms;

public class ClassChild1 extends ClassParent1{

public static void main(String[] args) {

ClassChild1 myObj = new ClassChild1();

myObj.callSumMethod();

public ClassChild1() {

System.out.println("I am the default constructor of Child Class");

public void sum() {

System.out.println("I am sum method of Child Class");

public void callSumMethod() {

super.sum();
}

==================================================================================

package basicJavaPrograms;

public class ClassChild2 extends ClassParent2{

public ClassChild2() {

System.out.println("I am the default constructor of Child class");

public static void main(String[] args) {

ClassChild2 myObj = new ClassChild2();

package basicJavaPrograms;

public class ClassParent2 extends ClassGrandParent2{

public ClassParent2() {

System.out.println("I am default constructor of Parent Class");

}
package basicJavaPrograms;

public class ClassGrandParent2 {

public ClassGrandParent2() {

System.out.println("I am default constructor of Grand Parent Class");

=============================================================

Abstraction :

What is abstraction :

- This is one of the OOPS concept of Java wherein we are hidding the implemenation details from the
actual user.

- User only calls the method and not aware of the logic written inside.

- Abstraction is achieved in Java using abstract keyword.

- Abstract Classes are the example of Abstracttion.

- One Abstract Class can have one of more than one abtract method.

- Concrete methods are the methods which have body (where in abstract methods are the one
which does not have any body).

- Abstract Classes cant be instantiated (We cant create the object of Abstract Class).

- Abstract Classes are inherited by another classes using extends keyword.

- When any other class extends the abstract class, it always have to have all the abstract methods
inside it.
- When any other class extends the abstract class, it always need to give the body of all the abstract
methods inside.

package basicJavaPrograms;

public abstract class AnimalClass {

// abstract method

public abstract void sound();

// Concrete Method (having body)

public void sleep() {

System.out.println("this animal sleeps");

package basicJavaPrograms;

public class DogClass extends AnimalClass{

public static void main(String[] args) {

DogClass myObj = new DogClass();

myObj.sleep();

myObj.sound();

@Override

public void sound() {


System.out.println("Dog barks");

package basicJavaPrograms;

public class LionClass extends AnimalClass{

public static void main(String[] args) {

LionClass myObj = new LionClass();

myObj.sleep();

myObj.sound();

@Override

public void sound() {

System.out.println("Lion Roars");

===========================================================================

package basicJavaPrograms;

public abstract class FourWhellerClass {


public abstract void carName();

public abstract void carColor();

public abstract void tyreType();

public abstract void fuelType();

public abstract void isSunroofAvailable();

public void numberOfWheels() {

System.out.println("This is a car with stupny, so total 5 wheels are there");

package basicJavaPrograms;

public class MarutiAltoClass extends FourWhellerClass{

@Override

public void carName() {

System.out.println("Car Name is Maruti Alto");

@Override

public void carColor() {

System.out.println("Car color is red");

@Override

public void tyreType() {

System.out.println("Normal wheels are there");


}

@Override

public void fuelType() {

System.out.println("Car is available in CNG and Petrol");

@Override

public void isSunroofAvailable() {

System.out.println("Sunroof is not avaiable");

public void altoCarSpeciality() {

System.out.println("I am the cheapest car in the world");

public static void main(String[] args) {

MarutiAltoClass myObj = new MarutiAltoClass();

myObj.carName();

myObj.carColor();

myObj.tyreType();

myObj.fuelType();

myObj.isSunroofAvailable();

myObj.altoCarSpeciality();

myObj.callNumberOfWheels();

public void callNumberOfWheels() {

numberOfWheels();

}
}

package basicJavaPrograms;

public class HyundaiCretaClass extends FourWhellerClass{

@Override

public void carName() {

System.out.println("Car Name is Hyundai Creta");

@Override

public void carColor() {

System.out.println("Car color is white");

@Override

public void tyreType() {

System.out.println("tyre type is Alloy wheels");

@Override

public void fuelType() {

System.out.println("Car is avaialbe in Petrol only");

@Override

public void isSunroofAvailable() {


System.out.println("Yes Sunroof is avaiable");

public void hyundaiCarSpeciality() {

System.out.println("my Car AC is best in the world");

public static void main(String[] args) {

HyundaiCretaClass myObj = new HyundaiCretaClass();

myObj.carName();

myObj.carColor();

myObj.tyreType();

myObj.fuelType();

myObj.isSunroofAvailable();

myObj.hyundaiCarSpeciality();

myObj.callNumberOfWheels();

public void callNumberOfWheels() {

numberOfWheels();

=================================================================================

Assignment :

1) Create an abstract class named as "ElectronicDevice" having


abstract methods as "deviceColor", "turnOn", "turnOff".

2) Create 1st class named as "Heater" that extends abstract

class "ElectronicDevice" and implement all its unimplemented methods.

3) Create 2nd class named as "Geyser" that extends abstract

class "ElectronicDevice" and implement all its unimplemented methods.

4) Create 3rd class named as "InductionCooker" that extends

abstract class "ElectronicDevice" and implement all its unimplemented

methods.

You have 25 min, we will connect at 08:00

=================================================================================

Interface :

- Interface is the one wherein all the methods are abstract method.

- There is no need to use abstract keyword (by default all methods are abstract in an interface).

- By using Interface, we can achieve multiple inheritance.

- If we want to create a concrete method in interface then it is mandatory to keep it static.

- Interface cant be instantiated (we cant create the object of an interface).

- implements keyword is used to inherit an interface.

In Java Classes, multilevel inheritance is allowed but multiple inheritance is not allowed.

If we want to use multiple inheritance in java, this can only be achieved using Interface.

Interface is giving a basic architecture (basic methods) one class must have when it is implementing
that interface.

One interface can extend another interface by using the word "extends" ( we cant use implements
keyword here).

Note :
Multiple inheritance is not allowed in case of Abstract Classes. (one abstract class cant extend more
than one abstract class).

Multiple inheritance is not allowed in case of normal classes. (one class cant not extend more than
one class)

Mulitiple inheritance is only allowed in case of interfaces. (one class can implement any number of
interfaces).

Important Point : One class can extend one class and can also implement interface.

================================================================================

package basicJavaPrograms;

public interface MobileInterface {

void mobileColor();

void mobileScreenSize();

void mobileRamSize();

void mobileBattery();

package basicJavaPrograms;

public interface AppleDeviceInterface {

void iOSVersion();

void chargerType();

package basicJavaPrograms;
public class ApplePhoneClass implements MobileInterface, AppleDeviceInterface{

@Override

public void iOSVersion() {

System.out.println("iOS version is iOS-18");

@Override

public void chargerType() {

System.out.println("charger is C type charger");

@Override

public void mobileColor() {

System.out.println("we have 4 colors of apple phone");

@Override

public void mobileScreenSize() {

System.out.println("Screen size is 7 inches");

@Override

public void mobileRamSize() {

System.out.println("Ram size is 8Gb");

@Override

public void mobileBattery() {

System.out.println("mobile battery is 20000 mAH");

}
}

package basicJavaPrograms;

public interface AndroidDeviceInterface {

void androidVersion();

void isCallRecordingFeatureAvailable();

package basicJavaPrograms;

public class AndroidPhoneClass implements MobileInterface, AndroidDeviceInterface{

@Override

public void androidVersion() {

System.out.println("Android version is sandwitch");

@Override

public void isCallRecordingFeatureAvailable() {

System.out.println("Yes call recording feature is available");

@Override

public void mobileColor() {

System.out.println("Available in 7 colors of rainbow");

}
@Override

public void mobileScreenSize() {

System.out.println("Mobile screen size is 8 inches");

@Override

public void mobileRamSize() {

System.out.println("ram size is 16GB");

@Override

public void mobileBattery() {

System.out.println("Mobile battery is 30000mAH");

==================================================================================

Assignment is :

Create one interface I1 having methods as sum(), subtract().

Create one more interface I2 with 2 new methods and that extends the above interface.

Create a class that implements only I2 (not I1) and check how many methods we need to implement
in this class.
Send me the code in chat window once done.

You have 5-10 minutes to work on it, we will connect at 06:20 to discuss.

==================================================================================

Abhiramasundari -

Anbarasan - Yes

Anish - Yes

Anmol -

Rathi - Yes

Deepa - NO

Durairam - No Show

Jegan - Yes

Madhunika -

Manish - Yes

Prabhu - NO

Prasanthi - Partially Done

Rajeswari - No Show

Sathya - Yes

Shaffna - Yes

Somasekar -

Subhadarshini - Yes

==================================================================================
=

Collection and Collections :

=> Collection is an interface.


=> Collections is a class that implements collection interface (collection framework).

=> As we all know that we can never create the object of an interface so we cant create the object of
collection.

We can create the object of collections class (It means we can only instantiate the collections classes
but not the collection interface).

Collection interfaces : Map, List, Set

Collection Classes : ArrayList, LinkedList, HashSet, TreeSet, LinkedHashSet, HashMap

Collections classes has so many predefined methods for searching, sorting etc.

List, Set, Map (ArrayList, HashSet, HashMap).

==================================================================================
====

List :

- List is an interface.

- It comes under collection framework.

- It stores the data in the form of index.

- We can get the value from the list using index.

- We can add the values in a list in the insertion order.

- List is not fixed in size (like Array).

- It allows duplicate values.

- It allows null values.

Lets say : I have so many fruits and I need to add the fruits name in a list.
List<String> myFruitsList = new ArrayList<>();

myFruitsList.add("Apple"); // It will add Apple to the list.

myFruitsList.add("Mango"); // It will add Mango to the list.

How to get the value from List :

using get method of list and pass the index in this get method (index is always 1 less than the
position).

myFruitsList.get(1); // it will return the value that is there at position 2.

==================================================================================
=====

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.List;

public class ListExamples {

public static void main(String[] args) {

methodFordynamicValuesInAList("Himanshu","Subhadarshini","Manish");

methodFordynamicValuesInAList("Anmol","Prasanthi","Anish");

public static void myMethodOfList() {

List<String> myFruitsList = new ArrayList<>();

myFruitsList.add("Apple");

myFruitsList.add("Mango");

myFruitsList.add("Orange");

System.out.println("fruit name at position 1 is :: " + myFruitsList.get(0));


System.out.println("fruit name at position 2 is :: " + myFruitsList.get(1));

System.out.println("fruit name at position 3 is :: " + myFruitsList.get(2));

public static void methodFordynamicValuesInAList(String value1, String value2, String


value3) {

List<String> myList = new ArrayList<>();

myList.add(value1);

myList.add(value2);

myList.add(value3);

System.out.println(myList);

=================================================================================

Assignment:

Create a new List named as myList1 having 10 integer values.

Take 3rd and 7th value from this List and return the sum of these 2 numbers.

Create a new list and add this addition in this new list named as myList2.

Any doubt in this assignment ?

Lets connect at 08:15 (you guys have 10 minutes to work on this). OKAY ?????????

=================================================================================

package basicJavaPrograms;
import java.util.ArrayList;

import java.util.List;

public class ListAssignment {

public static void main(String[] args) {

methodForAssignment();

public static void methodForAssignment() {

List<Integer> myList1 = new ArrayList<>();

myList1.add(10);

myList1.add(25);

myList1.add(38);

myList1.add(42);

myList1.add(70);

myList1.add(90);

myList1.add(100);

myList1.add(120);

myList1.add(11);

myList1.add(14);

int sum = myList1.get(2) + myList1.get(6);

System.out.println("Sum is :: " + sum);

List<Integer> myList2 = new ArrayList<>();

myList2.add(sum);

// System.out.println(myList2);

System.out.println("value in list 2 is :: " + myList2.get(0));


}

=========================================================================

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.List;

public class ListAssignmentAlternateWay {

public static void main(String[] args) {

methodForListAssignment();

public static void methodForListAssignment() {

int[] myArray = {10,25,38,42,70,90,100,120,11,14};

List<Integer> myList = new ArrayList<>();

for(int index=0;index<myArray.length;index++) {

myList.add(myArray[index]);

System.out.println("value in the list at index " + index + " is " +


myList.get(index));

int myListSize = myList.size();

System.out.println("my list size is :: " + myListSize);


int sum = myList.get(2) + myList.get(6);

System.out.println("Sum is :: " + sum);

List<Integer> myList2 = new ArrayList<>();

myList2.add(sum);

System.out.println("value in list2 is :: " + myList2.get(0));

==================================================================================
==

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.List;

public class ListAssignmentAlternateWay {

public static void main(String[] args) {

methodForListAssignment();

public static void methodForListAssignment() {

int[] myArray = {10,25,38,42,70,90,100,120,11,14};

List<Integer> myList = new ArrayList<>();

for(int index=0;index<myArray.length;index++) {
myList.add(myArray[index]);

System.out.println("value in the list at index " + index + " is " +


myList.get(index));

int myListSize = myList.size();

System.out.println("my list size is :: " + myListSize);

int sum = myList.get(2) + myList.get(6);

System.out.println("Sum is :: " + sum);

List<Integer> myList2 = new ArrayList<>();

myList2.add(sum);

System.out.println("value in list2 is :: " + myList2.get(0));

System.out.println("myList2 size is :: " + myList2.size()); // 1

myList2.remove(0);

System.out.println("myList2 size is :: " + myList2.size()); // 0

================================================================

Assignment :

1) Create an array having 10 String values.

2) create a new list -> Create a for loop.

3) Pass all these 10 values from the array to this new list (using the above for loop).
4) Add 2 more (new) values in this list.

5) Get the size of list.

6) Get the value that we have at index 5.

7) Remove one value from the list at index 5.

8) Now again, Get the value that we have at index 5.

9) Create a new list.

10) Copy all values from list1 to list2 (created in step 9).

==================================================================================
=================

Jegan G - Yes

Subhadarshini - Yes

Rathi Devi - Yes

Somesekar - Yes

Abhiramasundari - Yes

Anbarasan - Yes

Anish - Yes

Durairam - Yes

Manish - Yes

Prabhu - Yes

Shaffna - Yes

Amritha - In Progress

Mohammed - No Show

Prasanthi - Not Completed the recording yet as per her

Sathya -

Rajeshwari -

Anmol - Yes

Deepa - In Progress

==================================================================================
=======
LinkedList is Java :

- It is a class in Java that is used to store elements.

- It takes more memory than ArrayList.

- Insertion and Deletion of elements in the LinkedList is fast.

- LinkedList works on node basis.

first node -> next node -> next node.

- Singly Linked List.

- Doubly Linked List.

Singly Linked List :

Node1 -> Node2 -> Node3 -> Node4

Doubly Linked List :

Node1->Node2->Node3-> Node4

Node1<-Node2<-Node3<-Node4

Linked List :

Head -> Node1 -> Node2 -> Node3 -> Node4

==================================================================================
==========

LinkedList Implementation :
package createqadoc.CreateQADoc;

import java.util.LinkedList;

public class LinkedListImplementation {

public static void main(String[] args) {

methodForLinkedListUnderstanding();

public static void methodForLinkedListUnderstanding() {

LinkedList<String> myList = new LinkedList<String>();

myList.add("Himanshu");

myList.add("Anmol");

myList.add("Manish");

myList.add("Prasanthi");

myList.add("Anish");

System.out.println("Value at 1st index is :: " + myList.get(1));

System.out.println("my list is :: " + myList);

myList.addFirst("Deepa"); // This method does not exist in ArrayList

System.out.println("Value at 1st index is :: " + myList.get(1));

System.out.println("my list after adding first new element is :: " + myList);

myList.addLast("Durairam"); // This method does not exist in ArrayList

System.out.println("my list is after adding last new element is :: " + myList);

myList.add(2, "Subhdarshini");
System.out.println("my list is after adding new element in the middle is :: " +
myList);

myList.remove(1);

System.out.println("my list is after removal of element is :: " + myList);

==================================================================================
====================

Set is an interface.

HashSet is class.

Important Thing about set is :

It does not allow duplicates.

It does not work on index level.

No Insertion Order is saved in Set.

package createqadoc.CreateQADoc;

import java.util.HashSet;

import java.util.Set;

public class SetImplementation {

public static void main(String[] args) {

myMethodForSetUnderstanding();
}

public static void myMethodForSetUnderstanding() {

Set<String> mySet = new HashSet<>();

mySet.add("Apple");

mySet.add("Banana");

mySet.add("Kiwi");

mySet.add("Potato");

System.out.println(mySet); // There is no insertion order in the Set (does not work


on index level)

mySet.add("Potato");

System.out.println(mySet); // Duplicate values are not allowed in Set

// 12, 16, 20, 67, 12, 78, 90, 82, 12, 16,20, 20, 21, 20 - ArrayList

// create a set of above numbers so that all the unique values will be fetched

// compare set with the List to get the iteration(no. of count) of all the integer values

==================================================================================
===========

Exception Handling :

Exception :

Anything which is going wrong in my program (interruption) / error.


Why to handle this exception :

So that we can have an idea why and where the error is there in the code and we can fix it.

package createqadoc.CreateQADoc;

public class BasicOfExceptionHandling {

public static void main(String[] args) {

int[] myArray = new int[10];

try {

System.out.println(myArray[15]);

catch (Exception e) {

e.printStackTrace();

==================================================================================
=================

Assignment :

Task 1 : Create one ArrayList and one LinkedList and write a program to add 10 numbers and then
delete 2 numbers

at index 5 and 6.
Task 2 : Create a list and add 10 values and create a new Hashmap and put all these 10 values in a
Hashmap as :

key is 1,2,3,4,5,6,7,8,9,10

value : 10 values in the list

1 - Himanshu

2 - Subhadarshini

3- Anmol

4 - Anish

Task 3 : Create a set and try to include duplicate in set, and check whether it is allowed or not ?

==================================================================================
==================

Task 1:

Create an ArrayList of 10 String values and Paste it in 2 Hashmaps.

1st Hashmap :

1=Himanshu

2=Subhadarshini

3=Deepa

4=Prasanthi

5=Abhiramasundari

2nd HashMap :

6=Himanshu

7=Anmol
8=Manish

9=Anish

10=Mohammed

Task 2 :

Create an ArrayList of 10 values.

Paste it in a Hashmap like : 1,StringValue1 2,StringValue2 and so on.

Create a new LinkedList and add the values of hashmap in this linkedList.

==================================================================================
==================

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class ArrayListHashMapAssignment1 {

static List<String> myList = new ArrayList<>();

public static void main(String[] args) {

addValuesToList();

firstHashMapHavingValuesFromList();

secondHashMapHavingValuesFromList();

public static void addValuesToList() {

myList.add("Himanshu");
myList.add("Subhadarshini");

myList.add("Deepa");

myList.add("Prasanthi");

myList.add("Abhiramasundari");

myList.add("Himanshu");

myList.add("Anmol");

myList.add("Manish");

myList.add("Anish");

myList.add("Mohammed");

public static int getSizeOfMyList() {

int sizeOfMyList = myList.size();

return sizeOfMyList;

public static void firstHashMapHavingValuesFromList() {

HashMap<Integer, String> myMap1 = new HashMap<>();

int sizeOfMyList = getSizeOfMyList();

for(int index=0;index<sizeOfMyList/2;index++) {

myMap1.put(index+1, myList.get(index));

System.out.println("hashMap 1 is :: " + myMap1);

public static void secondHashMapHavingValuesFromList() {

HashMap<Integer, String> myMap2 = new HashMap<>();

int sizeOfMyList = getSizeOfMyList();

for(int index=5;index<sizeOfMyList;index++) {

myMap2.put(index+1, myList.get(index));

}
System.out.println("hashMap 2 is :: " + myMap2);

==================================================================================
===========

Another way to do it :

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class ArrayListHashMapAssignment1 {

static List<String> myList = new ArrayList<>();

static int sizeOfList;

public static void main(String[] args) {

addValuesToList();

firstHashMapHavingValuesFromList();

secondHashMapHavingValuesFromList();

public static void addValuesToList() {

myList.add("Himanshu");
myList.add("Subhadarshini");

myList.add("Deepa");

myList.add("Prasanthi");

myList.add("Abhiramasundari");

myList.add("Himanshu");

myList.add("Anmol");

myList.add("Manish");

myList.add("Anish");

myList.add("Mohammed");

sizeOfList = myList.size();

public static void firstHashMapHavingValuesFromList() {

HashMap<Integer, String> myMap1 = new HashMap<>();

for(int index=0;index<sizeOfList/2;index++) {

myMap1.put(index+1, myList.get(index));

System.out.println("hashMap 1 is :: " + myMap1);

public static void secondHashMapHavingValuesFromList() {

HashMap<Integer, String> myMap2 = new HashMap<>();

for(int index=5;index<sizeOfList;index++) {

myMap2.put(index+1, myList.get(index));

System.out.println("hashMap 2 is :: " + myMap2);

}
==================================================================================
=========

Task 2 :

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.HashMap;

import java.util.List;

public class ProblemSolving2 {

static List<String> myArrayList = new ArrayList<>();

static List<String> myLinkedList = new ArrayList<>();

static HashMap<Integer, String> myMap = new HashMap<>();

public static void main(String[] args) {

myArrayList.add("Himanshu");

myArrayList.add("Subhadarshini");

myArrayList.add("Deepa");

myArrayList.add("Prasanthi");

myArrayList.add("Abhiramasundari");

myArrayList.add("Himanshu");

myArrayList.add("Anmol");

myArrayList.add("Manish");

myArrayList.add("Anish");

myArrayList.add("Mohammed");

for(int index=0;index<myArrayList.size();index++) {

myMap.put(index+1, myArrayList.get(index));
}

System.out.println(myMap);

for(int index=0;index<myArrayList.size();index++) {

myLinkedList.add(index, myMap.get(index+1));

System.out.println(myLinkedList);

==================================================================================
=========

TreeMap:

TreeMap works in a similar way like HashMap but :

HashMap allows one null key and TreeMap does not allow any null key.

HashMap allows multiple null values but TreeMap does not allow any null value.

HashMap does not have keys in the ordered way (asceding) but Treemap has keys in ordered form
(ordered does not mean indexing).

TreeMap implemets map interface like Hashmap implements Map interface.

==================================================================================
=========

package basicJavaPrograms;

import java.util.TreeMap;
public class TreeMapImplementation {

public static void main(String[] args) {

myMethodToUnderstandTreeMap();

public static void myMethodToUnderstandTreeMap() {

TreeMap<String, String> myTreeMap = new TreeMap<>();

myTreeMap.put("Himanshu", "Mentor");

myTreeMap.put("Prasanthi", "Student");

myTreeMap.put("Manish", "Learner");

myTreeMap.put("Anmol", "Leaner");

System.out.println(myTreeMap);

==================================================================================
============

How to sort TreeMap values using Collections.sort :

package basicJavaPrograms;

import java.util.ArrayList;

import java.util.Collections;

import java.util.List;

import java.util.TreeMap;
public class TreeMapImplementation {

public static void main(String[] args) {

myMethodToUnderstandTreeMap();

public static void myMethodToUnderstandTreeMap() {

TreeMap<Integer, String> myTreeMap = new TreeMap<>();

myTreeMap.put(1, "Mentor");

myTreeMap.put(2, "Student");

myTreeMap.put(3, "Learner");

myTreeMap.put(4, "ExpertLearner");

System.out.println(myTreeMap);

List<String> myList = new ArrayList<>(myTreeMap.values());

Collections.sort(myList);

System.out.println(myList);

==================================================================================
==========

Exception Handling :

- Anything unwanted/unexpected issue we are getting in the code is an exception.

- We need to handle such exception else our code will be stopped then and there (where we are
getting the exception).
- We use try, catch, finally blocks to handle exception.

- We use throw and throws to handle exception.

- Exception is a class in Java that is the parent of all the other exception classes like :
ArrayIndexOutOfBoundsException, NullPointerException etc.

- There are 2 types of exception :

- Checked Exception

- Unchecked Exception.

Checked Exception occurs at Compile time.

Unchecked Exception occurs at Runtime.

==================================================================================
==========

Whenever we have anything risky, we can put it in a try block and we can catch the exception in
catch block.

Whenever we get the exception, the code after it will not be executed :

package basicJavaPrograms;

public class ExceptionHandling {

public static void main(String[] args) {

arrayIndexOutOfBoundException();

public static void arrayIndexOutOfBoundException() {

String[] myArray = new String[2];

myArray[0] = "Subhadarshini";

myArray[1] = "Sathya";
System.out.println("================Code execution is
Started==============================");

System.out.println(myArray[0]);

System.out.println(myArray[1]);

System.out.println(myArray[2]);

System.out.println("================Code execution is
done=================================");

==================================================================================
========================

handle with try and catch :

try {

catch() {

=====================================================================

package basicJavaPrograms;
public class ExceptionHandling {

public static void main(String[] args) {

arrayIndexOutOfBoundException();

public static void arrayIndexOutOfBoundException() {

try {

String[] myArray = new String[2];

myArray[0] = "Subhadarshini";

myArray[1] = "Sathya";

System.out.println("================Code execution is
Started==============================");

System.out.println(myArray[0]);

System.out.println(myArray[1]);

System.out.println(myArray[2]);

System.out.println("================Code execution is
done=================================");

catch (Exception e) {

e.printStackTrace();

=====================================================================

So, whenever we get any exception in try block, the code automatically moves the execution to
catch block :
package basicJavaPrograms;

public class ExceptionHandling {

public static void main(String[] args) {

arrayIndexOutOfBoundException();

public static void arrayIndexOutOfBoundException() {

try {

String[] myArray = new String[2];

myArray[0] = "Subhadarshini";

myArray[1] = "Sathya";

System.out.println("================Code execution is
Started==============================");

System.out.println(myArray[0]);

System.out.println(myArray[1]);

System.out.println(myArray[2]);

catch (Exception e) {

e.printStackTrace();

System.out.println("================Code execution is
done=================================");

=====================================================================

RunTime Exception - It is always our fault.


=====================================================================

package basicJavaPrograms;

public class ExceptionHandling2 {

public static void main(String[] args) {

getDivisionOfTwoNumbers(12, 6);

getDivisionOfTwoNumbers(12, 0);

getDivisionOfTwoNumbers(12, 2);

public static void getDivisionOfTwoNumbers(int num1, int num2) {

try {

int division = num1/num2;

System.out.println("Division is :: " + division);

catch (Exception e) {

System.out.println("Error : Dont use zero as num2");

e.printStackTrace();

=====================================================================

- Whenever you use childException, always use Parent exception at last so that if there is any new
child exception comes in your code, that will be

handled by Exception (parent Exception Class).


- Multiple catch blocks are allowed.

=====================================================================

package basicJavaPrograms;

public class ExceptionHandling3 {

public static void main(String[] args) {

getDivisionOfTwoNumbers(12, 6);

getDivisionOfTwoNumbers(12, 0);

getDivisionOfTwoNumbers(12, 2);

public static void getDivisionOfTwoNumbers(int num1, int num2) {

try {

int division = num1/num2;

System.out.println("Division is :: " + division);

catch (NullPointerException e) {

System.out.println("Error : Dont use zero as num2");

e.printStackTrace();

catch (Exception e) {

System.out.println("Exception Class Error : Dont use zero as num2");

}
=====================================================================

package basicJavaPrograms;

public class ExceptionHandling3 {

public static void main(String[] args) {

getDivisionOfTwoNumbers(12, 6);

getDivisionOfTwoNumbers(12, 0);

getDivisionOfTwoNumbers(12, 2);

public static void getDivisionOfTwoNumbers(int num1, int num2) {

try {

int division = num1/num2;

System.out.println("Division is :: " + division);

catch (ArithmeticException e) {

System.out.println("Error : Dont use zero as num2");

e.printStackTrace();

=====================================================================

Why to use multiple catch blocks :

package basicJavaPrograms;
public class ExceptionHandling3 {

public static void main(String[] args) {

getDivisionOfTwoNumbers(12, 6);

getDivisionOfTwoNumbers(12, 0);

getDivisionOfTwoNumbers(12, 2);

public static void getDivisionOfTwoNumbers(int num1, int num2) {

try {

int division = num1/num2;

System.out.println("Division is :: " + division);

catch (ArithmeticException e) {

System.out.println("Error : Dont use zero as num2");

e.printStackTrace();

catch (NullPointerException e) {

System.out.println("dont use any null value");

catch (Exception e) {

System.out.println("Something went wrong");

=====================================================================
Finally block :

1) Only one finally block is allowed.

2) This will always be executed even if there is no exception in try.

3) Finally block will always be executed.

4) Finally block is used to write some important code like dbConnectionClose, ExcelClose,
DriverQuite etc.

=====================================================================

whenever we are using try,

it is always mandatory to use either catch / finally or both of these.

=====================================================================

try {

catch() {

finally {

=====================================================================
package basicJavaPrograms;

public class ExceptionHandling4 {

public static void main(String[] args) {

method2ForUnderstandingFinally();

public static void methodForUnderstandingFinally() {

try {

int[] myArray = new int[2];

catch (Exception e) {

System.out.println("I am catching exception");

finally {

System.out.println("Dont worry I will always be executed");

public static void method2ForUnderstandingFinally() {

try {

int[] myArray = new int[2];

System.out.println(myArray[10]);

catch (Exception e) {

System.out.println("I am catching exception");

finally {

System.out.println("Dont worry I will always be executed");


}

=====================================================================

Throws keyword :

- It is just to help the other developrs so that if they are using the method they can handle the
exception.

- throws is used near the method signature (methodName where we have created the method).

- throws is just an information that whenever you are calling this method, this can have the
mentioned exception (mentioned near method signature)

=====================================================================

package basicJavaPrograms;

public class ExceptionHandling5 {

public static void main(String[] args) {

try {

methodToUnderstandThrows();

catch (ArrayIndexOutOfBoundsException e) {

System.out.println("I have handled ArrayIndexOutOfBoundsException


exception");

}
public static void methodToUnderstandThrows()throws ArrayIndexOutOfBoundsException {

int[] myArray = new int[2];

myArray[0] = 23;

myArray[1] = 56;

for(int index=0;index<=myArray.length;index++) {

System.out.println(myArray[index]);

======================================================================

throw keyword is used to have our own customized exception.

======================================================================

throw is added in the code whenver we need to explicitly print the exception.

======================================================================

package basicJavaPrograms;

public class ExceptionHandling6 {

public static void main(String[] args) {

methodToUnderstandThrow(23);

methodToUnderstandThrow(123);

}
public static void methodToUnderstandThrow(int a) {

int age = a;

if (age > 100) {

throw new ArithmeticException("Please enter correct age");

else {

System.out.println("Your age is :: " + age);

========================================================================

package basicJavaPrograms;

public class ExceptionHandling6 {

public static void main(String[] args) {

methodToUnderstandThrow(23);

methodToUnderstandThrow(123);

methodToUnderstandThrow(500);

public static void methodToUnderstandThrow(int a) {

int age = a;

if (age > 100) {

throw new ArithmeticException();


}

else {

System.out.println("Your age is :: " + age);

========================================================================

package basicJavaPrograms;

public class ExceptionHandling6 {

public static void main(String[] args) {

methodToUnderstandThrow(23);

methodToUnderstandThrow(123);

methodToUnderstandThrow(5);

public static void methodToUnderstandThrow(int a) {

try {

int age = a;

if (age > 100) {

throw new ArithmeticException("Please enter the correct age");

else {

System.out.println("Your age is :: " + age);

}
catch (ArithmeticException e) {

System.out.println("handle this");

===========================================================================

use only try and finally (when we dont want to catch the exception using catch) :

package basicJavaPrograms;

public class ExceptionHandling7 {

public static void main(String[] args) {

useTryAndFinally();

public static void useTryAndFinally() {

try {

int[] i = new int[2];

System.out.println("Array creation is done");

finally {

System.out.println("I will always be executed");

}
============================================================================

package basicJavaPrograms;

public class ExceptionHandling7 {

public static void main(String[] args) {

useTryAndFinally();

public static void useTryAndFinally() {

try {

int[] i = new int[2];

System.out.println("Array creation is done");

finally {

System.out.println("Database has been closed");

System.out.println("=== Done =====");

============================================================================

This question is just for the interview purpose :-------------------

What is a case when finally will not be executed :


Answer : Finally block will always be executed but there are cases when it will not be executed also :

Case 1 : When we use System.exit();

package basicJavaPrograms;

public class ExceptionHandling7 {

public static void main(String[] args) {

useTryAndFinally();

public static void useTryAndFinally() {

try {

int[] i = new int[2];

System.out.println("Array creation is done");

System.exit(0);

finally {

System.out.println("Database has been closed");

System.out.println("=== Done =====");

Case 2 : If we have any exception in the finally block also, the complete finally block will not be
executed.

package basicJavaPrograms;
public class ExceptionHandling7 {

static int[] myArray = new int[2];

public static void main(String[] args) {

useTryAndFinally();

public static void useTryAndFinally() {

try {

System.out.println("Array creation is done");

finally {

System.out.println(myArray[10]);

System.out.println("Database has been closed");

System.out.println("=== Done =====");

==================================================================================
=======

18-Nov-2024 :

Read the data from Excel :

APACHE POI Library - Java Library


We never call excel file as excel in APACHE POI.

We call it as "workbook".

WORKBOOK

SHEET

ROW

COLUMN

CELL

==================================================================================
=========

REVIEW TASK FOR JAVA :

PROJECT :

School Management System :

Students

Teachers

- Register Students.

- Assign the teachers to Subject.

- Display the details of Teachers.

TO DO :
1. Encapsulation :

Create any class that has private fields for creating getters and setters method.

2.Inheritance

Parent Class -> Person

Child Classes -> Student and Teacher (both the classes have common properties like name, age from
Person class).

3.Polymorphism

Create one class that has method :

behave() -> We have the code how students behaves

behave() -> We have the code how teachers behaves

4.Abstraction

abstractClassForTeacher{

work();

Teacher Class extends this abstract class and implement work method and have some in this work
method.

==================================================================================
==================

Java Project :

In Java Project, we need download the JARS manually and we need to add them in the build Path of
the project.

Maven Project :

We dont need to download any JAR manually and we can simply add the dependencies in POM>xml
file and we are done.
==================================================================================
==================

How to create a MAVEN Project :

Go to File -> New -> Project -> Maven Project -> Next -> Select any quickstart archietype -> Give any
name in artifact ID -> Click FINISH.

In console, We need to write Y

Press Enter.

Maven Project Creation is done (you will see a message as BUILD SUCCESS).

==================================================================================
=================

POM.xml :

<dependencies>

<dependency>

</dependency>

<dependency>

</dependency>

<dependency>

</dependency>

<dependency>

</dependency>

</dependencies>
==================================================================================
==================

You might also like