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

Core Java

The document provides an overview of Core Java, detailing programming concepts, Java program structure, data types, operators, and control flow statements such as if-else and switch. It explains the Java compilation process, the role of the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), as well as the history and installation of Java. Additionally, it includes examples of Java programs and their outputs, illustrating various programming constructs and data types.

Uploaded by

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

Core Java

The document provides an overview of Core Java, detailing programming concepts, Java program structure, data types, operators, and control flow statements such as if-else and switch. It explains the Java compilation process, the role of the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM), as well as the history and installation of Java. Additionally, it includes examples of Java programs and their outputs, illustrating various programming constructs and data types.

Uploaded by

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

Core Java

Program: A set of instruction is known as program.

Programming Language: A language used to write a program is known as programming language. It


is divided into three categories:
1. Low Level Programming Language: It consists of “0” and “1” i.e. binary digits. It can be understood
only by machine not human.
2. Middle Level Programming Language: It is also called as Assembly Level Programming Language
which is made up of commands. Ex: DEL, CMD, Microprocessor.
3. High Level Programming Language: It is made up of English Instruction. Ex: C, C++, Java

NOTE:
1. A Java program is also called as source code.
2. All Java program has .Java extension.
3. A Java Program consists of 3 stages:
a. Coding
b. Compilation (Javac followed by program_name or Class_name)
c. Execution (Java followed by program_ name or Class_Name)
4. Java Compiler: It takes the Source file as its input and generates Byte code as an Output.
5. The extension of Byte code is .class
6. Java Compiler checks Syntax error in a Java program, if the program has any error at the
compilation stage-it gives a Compile time error.
7. Java Virtual Machine (JVM): It takes Byte Code as input and generates Machine code as output.
8. JVM is also called as interpreter.
9. Byte code: It is neither in the form of user-understandable nor in the form of binary digits i.e.
machine understandable, so byte code is also called as Intermediate Programming Language. Only
JVM can understand byte code. JAVA only generates Byte Codes.
10. JAVA is both compiled and Interpreted Programming Language.

Java Program Javac


(source code) (java compiler) JVM
Processor
.java .class machine code

Coding Compilation (it will take Execution (take byte


source code & convert into code & generates in machine
Byte code. Code i.e ‘0’ & ‘1’.
Output

If error occurred i.e called as compile time error.

11. Byte code is platform independent.


12. JVM is Platform dependent.
13. Machine code is Platform dependent.
14. JAVA is platform independent because it generates byte code after compilation.

Components of JAVA:

1. JDK (Java Development tool Kit): It provides a platform or environment to develop Java program.
2. JRE (Java Runtime Environment): It provides a platform or environment to run Java program.
3. JVM (Java virtual Machine): It executes or run the program line by line.
4. JDK = JRE + JVM.
5. JRE = JVM + other files.

JRE

JVM
J

JDK

History of Java:
1. Java was invented by James Gosling and his team.
2. Java was developed by ‘SUN MICROSYSTEM’ in the year 1995.
3. In the year of 2000, Oracle Corporation acquired ‘SUN MICRO SYSTEM’.
4. Earlier name of JAVA is ‘OAK’.
5. According to Sun microsystem Java is categorised into 3 types:
a.J2SE (Java 2 standard edition): It is used to develop Java stand-alone Application.
b.J2EE (Java 2 Enterprise edition)
c. J2ME (Java 2 Micro edition)
Note: J2EE & J2ME are used to develop java web application.
6. Core Java comes under J2SE.
7. Advanced Java comes under J2EE.
8. Framework comes under J2ME.
9. Java version starts from Java 1.0 to Java 1.8(latest).

Installation of JDK
1. Download the JDK software.
2. Double Click on [Link] files.
3. Click on next option.
4. Click on finish.
How to set the path?
1. Go to My computer >> select C drive >> select program files>> select Java >> Select JDK 1.8
>>select bin option.
2. Copy the path.
3. Go to my computer >> Right click >>select properties>> select Advanced system setting.
4. Select Environment variables>> select new.
5. Give the path name as a “Path’’ or “JAVA_HOME”.
6. Click on finish option.

Why to setup Path?


1. Because our operating system should recognise that we are developing and running Java Program.
2. Javac is a command which is used to compile the java program. EX: Javac program [Link]
3. Java is a command which is used to Run or execute the Java program. Ex: Java Program name
4. We have to select the path up to that bin folder because java and Javac executable files, which is
available inside bin folder.
Java programs:
1. class Demo
{
public static void main (String [] args)
{
[Link](“welcome to Java”);
}
}
Output: Welcome to Java

2. class Demo1
{
public static void main (String [] args)
{
[Link](“India\n\tUSA\n\t\tUK”);
}
}
Output: India
USA
UK
Note:

1. D: is used to move to D drive.


2. cd is a command which is used to change the directory.
3. “\n” and “\t” are escape sequences, “\n” used for new line and “\t” used for new tab.
5. The first character of class name should always be in upper case.
6. A Class name and a program name must be same.
3. class Add
{
public static void main(String[] args)
{
[Link](10+20);
}}
Output: 30

4. class value{
public static void main(String[] args){
int i=20;
[Link]("Value of i is "+i);
}}
Output:
Value of i is 20

[Link] Value{
public static void main(String[] args){
int i=20;
int j=10, k=40;
[Link]("Value of i is "+i+"\nValue of j is "+j+"\nValue of k is "+k);
}}
Output:
Value of i is 20
Value of j is 10
Value of k is 40

6. class Value{
public static void main(String[] args){
int i=20;
int j=10, k=40;
[Link](i+"\n"+j+"\n"+k);
}}
Output:
20
10
40

7. class India
{
public static void main(String[] args)
{
int i=20;
int j=10;
[Link]("I love India "+i+"\n I hate Pakistan "+j+" I love Qspiders");
}}
Output:
I love India 20
I hate Pakistan 10 I love Qspiders

DATA TYPES:
Data type is categorised into 2 types:
1. Primitive Data types: Data type which is supported by programming language is called primitive
data type. It is also called as inbuilt data type or predefined data types.

2. Non Primitive Data types: Data type which is supported by programmer or user is called Non
primitive data type. It is also called as User defined Data type.
Examples: String, class, interface and Arrays

Primitive Data types:

There two types of Primitive Data Types, Numeric and non-numeric.

Numeric Data Type: Integer and Real


Integer: It can hold only whole numbers, it can’t hold fractional numbers.
Integer Data Type are:
a. byte (it can hold 8 bit data i.e. -128 to 127)
b. short (2 bytes)
c. Int (4 bytes)
d. long (8 bytes)

Real Number: It can hold both whole numbers and fractional numbers.
Real number data types are:
a. float (4 bytes)
b. double (8 bytes)

Non-numeric data types are:


a. char (2 bytes)
b. Boolean (1 bit)

NOTE:
*In Java Programing language Boolean values are either true or false; it shouldn’t be 0 and 1.
*Character values should be enclosed inside single quotes.
*String values should be enclosed inside double quotes.
*Boolean values should be in lower case i.e. true or false not True or False.
*While we are initializing fractional values to the float data type at the end we need to provide ‘f’
character because JVM would treat fractional values as double value by default.

Operators:

These are the symbols used to perform different actions. They are categorized into 5 types.
1. Arithmetic Operator: It is mainly used to perform mathematical operations. These are arithmetic
operators: + , - , * , / , %
2. Relational Operators: It is mainly used to perform comparison operations. These are relational
operators: >, <, >= , <= , == , !=

3. Logical operators: It is used to perform logical operations. These are logical operators: &&, ||, !

4. Assignment operators: It is used to assign values to the variable and it allows a programmer to
create a chain of expression. These are assignment operators: = , += , -= , *= , /=
5. Ternary Operator or conditional operator:
syntax: i > j ? i :j ;

If the first expression is true, it will execute second statement. If the first expression is false
it will skip the second statement and it will execute third statement.
Program:
[Link] Demo{
public static void main(String[] args){
int i=80, j=40;
int k = i>j?i:j;
[Link]("The value of k is " + k);
}
}
output: Value of k is 80
8. class Demo{
public static void main(String[] args){
int i=10;
if(i){
[Link]("Hello");
}
}
}
Output: error: incompatible types: int cannot be converted to Boolean
9. class Demo{
public static void main(String[] args){
int i=10;
int j=30;
if(i=j){
[Link]("Hello");
}
}
}
Output: error: incompatible types: int cannot be converted to Boolean
10. class Demo{
public static void main(String[] args){
boolean i=false;
if(i){
[Link]("Hi");
}
[Link]("Hello");
}
}
Output:Hello
11. class Demo{
public static void main(String[] args){
boolean i=true;
if(i){
[Link]("Hi");
}
[Link]("Hello");
}
}
Output:
Hi
Hello
12. class Demo{
public static void main(String[] args){
if(true)
[Link]("Hi");
[Link]("Hello");
}
}
Output:
Hi
Hello
13. class Demo{
public static void main(String[] args){
if(false)
[Link]("Hi");
[Link]("Hello");
}
}
Output:
Hello

IF CONDITION:
syntax: if (condition)
{ }
1. If condition satisfied or if the condition is true, it will enter inside the if block and it will execute
the statement.
2. Once if statement is executed, after the if block if any executable statements are present those
statements would be executed.
3. If the condition is not satisfied or if the condition is false, it will come out of the if block and after
the if block if any executable statements are present, those statement would be executed.
4. In if condition curly braces are optional.
5. If condition allows Boolean data type values.
6. If we try to provide any other data type value, it will give compile time error i.e. incompatible data
type.
IF ELSE CONDITION:
syntax: if (condition)
{ }
else
{ }
Case1: If the condition is satisfied it will enter inside the if block and execute the if statement. Once
if block is executed then else part won’t be executed. After the else part if any executable
statements are present then those part will be executed.
Case2: If condition is false it won’t execute if block, it will execute else part and after the else part if
any executable statements are present then those statement would be executed.

Note: The outcome of Relational operator and Logical operator is always Boolean value.

14. class Demo{


public static void main(String[] args){
int i=10;
int j=30;
if(i>j){
[Link](i+ " is greater number.");
}
else{[Link](j+ " is greater number.");
}
}
}
Output:
30 is greater number.

15. Write a program to check whether the number even or not?


class Demo{
public static void main(String[] args){
int i=10;
if(i%2==0){
[Link](i+ " is an even number.");
}
else{[Link](i+ " is an odd number.");
}
}
}
Output:10 is an even number.
16. Write a program to check candidate is eligible or not for IAS exam?

class Demo{
public static void main(String[] args){
int age=35;
if(age>=21 && age<=35){
[Link]("The candidate is eligible for IAS exam.");
}
else{ [Link]("The candidate is not eligible for IAS exam.");
}
}
}
Output: The candidate is eligible for IAS exam.
17. Write a program to print sanju if the number is divisible by 3 and to print geetha if the number is
divisible by 5 and to print sanju weds geetha if the number is divisible by both?
class Demo{
public static void main(String[] args){
int i=15;
if(i%3==0 && i%5==0){
[Link]("Sanju weds Geetha.");
}
else if(i%3==0){[Link]("Sanju");
}else if(i%5==0){
[Link]("Geetha");
}
}
}
Output: Sanju weds Geetha.

18. class Atm{


public static void main(String[] args){
double balance=5000.0;
double withdrawl=4000.0;
if(withdrawl<=balance){
balance=balance-withdrawl;
[Link]("You have withdrawn " + withdrawl + "\nYour remaining account balance is " +
balance);
}
else{
[Link]("Insufficient balance");
}
}
}
output: You have withdrawn 4000.0
Your remaining account balance is 1000.0
Nested if:
syntax: if (condition)
{ if (condition)
{ }
else
{ }
}
else
{ }

19. class Atm{


public static void main(String[] args){
double balance=5000.0;
double withdrawl=6000.0;
int pincode=1234;
if(pincode==1234){
if(withdrawl<=balance){
balance=balance-withdrawl;
[Link]("You have withdrawn " + withdrawl + "\nYour remaining account balance is " +
balance);
}
else{
[Link]("Insufficient balance !! try later");
}
}else {[Link]("Invalid pincode");
}
}
}
output: Insufficient balance !! try later

20. class Grade{


public static void main(String[] args){
int marks=80;
if(marks>90 && marks<=100){
[Link]("Grade A");
}else if(marks>80 && marks<=90){
[Link]("Grade B");
}else if(marks>70 && marks<=80){
[Link]("Grade C");
}else{
[Link]("Grade D");
}
}
}
output: Grade C
Switch:
[Link] we want to execute multiple condition then switch condition is required.
2. In switch condition curly braces are mandatory.
3. In switch condition if we want to write any executable statement, we have to write under the case
or default.
4. If any of the case condition is not satisfied then it will execute the default.
5. The allowed data types inside the switch conditions are byte, short, int, char and string. (char and
string are added in java 1.07 version).
6. We can write default anywhere inside the switch condition.
Syntax:
switch (condition)
{case: // statements;
break;
case: // statements;
break;
default: // statements;
}
21. class Grade{
public static void main(String[] args){
char grade ='A';
switch(grade){
case'A':
[Link]("First class with distinction");
break;
case'B':
[Link]("First class");
break;
case'C':
[Link]("Second class");
break;
case'D':
[Link]("Just pass");
break;
case'E':
[Link]("Fail");
break;
default:
[Link]("Invalid grade");
}
}
}
Output: First class with distinction

22. class Switch{


public static void main(String[] args){
int i =3;
switch(i){
case 1:
[Link]("Sunday");
break;
case 2:
[Link]("Monday");
break;
case 3:
[Link]("Tuesday");
break;
case 4:
[Link]("Wednesday");
break;
case 5:
[Link]("Thursday");
break;
case 6:
[Link]("Friday");
break;
case 7:
[Link]("Saturday");
break;
default:
[Link]("Invalid day");
}
}
}
Output: Tuesday

23. class sample {


public static void main (String[] args)
{

int day = 10;


switch (day)
{
[Link] ("hi");
}
}
}

Output: error: case or default expected

1. we can pass an expression inside the switch.


Ex: a.) class sample {
public static void main(String[] args)
{
int i = 10*12;
switch(i){
case 10*12:
[Link]("hi");
break;
default: [Link]("hello");
}
}
}
output: hi
b) class sample {
public static void main(String[] args)
{int i = 10*12;
switch(i){
case 120:
[Link]("hi");
break;
default: [Link]("hello");
}
}
}
output: hi
2. Duplicate case level shouldn’t be allowed inside the switch condition.
Ex: class sample{
public static void main(String[] args)
{int i =12;
switch(i){
case 12:
[Link]("hi");
break;
case 12:
[Link]("hello");
break;
default: [Link]("invalid");
}
}
}
output: gives compile time error because duplicate case level shouldn’t be allow.

For loop:
syntax: for (initialisation; condition;increment/decrement)
{ //statements;
}
1. In for loop initialisation part is always executed once.
2. In for loop, first it will execute initialisation.
3. Once the initialisation part is executed control moves to the condition.
4. It will check whether the condition is true or false.
5. If the condition is true, it will enter inside the for loop and it will execute the statements.
6. If the condition is false it will come out of the for loop.

Increment or Decrement Operator:


1. Increment operator can be categorised into 2 types:
a. Pre increment: If you apply the increment operator before the variable it is called pre
increment. In pre increment first it will increment the value then it will initialise to the
variable. Ex: ++a;
b. Post increment: : If you apply the increment operator after the variable it is called post
increment. In post increment first it will initialised the value then it will increment to one.
Ex: a++;
Decrement Operator: It can be categorised into 2 types:
a. Pre decrement: If we apply the decrement operator before the variable it is called pre
decrement. In pre decrement, first it will decrement the value then it will initialise variable.
Ex: --a;
b. Post decrement: If we apply decrement operator after the variable it is called post
decrement. In post decrement first it will initialise the value then it will decrement to one.
Ex: a--;

Example of for program:


class For{
public static void main(String[] args){
for(int i=1;i<=10;i++)
{
[Link](i);
}
[Link]("********");
for(int k=10;k>=0;k--)
{
[Link](k);
}
}
}

Syntax for Nested for Loop:


for (initialisation; condition;increment/decrement)
{
for (initialisation; condition;increment/decrement)
{ }
}
Example of Nested for program:
Q: Write a program to print table of 2?
class Nested{
public static void main(String[] args){
for(int i=2;i<=2;i++)
{
for(int k=1;k<=10;k++)
{
[Link](i+"*"+k+"="+i*k);
}
[Link]("********");
}
}
}
2. class Star{
public static void main(String[] args){
for(int i=1;i<=5;i++)
{
for(int k=1;k<=i;k++)
{
[Link]("*"+ "");
}
[Link](" ");
}
}
}
output: *
**
***
****
*****

While & Do while Loop:


While loop: While is a pretested loop. In while condition before executing the statement first it will
check the condition if the condition is satisfied it will enter inside the while loop and it will execute
the statements, if the condition is not satisfied it will come out of the while loop.
In while condition we are not using a semicolon.

Syntax:
while (condition)
{ //statements

Do While: Do while is a post tested loop. Before checking the condition at least once it will execute
the statements then it will check the condition.
In do while at the end of the while condition we have to use a semicolon.

Syntax:
do
{ //statements

} while(condition);
Ex Q. Write a program to print from 1 to 10 using while loop.
class Whileloop
{public static void main (String [] args)
{ int i = 1;
while(i<=10)
{ [Link](i);
i++;
}}}
Note: 1. Num%10 123%103
2. Num/10123/1012

3. Any prime number gives only 2 count of ‘0’ reminder.

Q2. Write a program to reverse a number.


class Whileloop
{public static void main (String [] args)
{
int i = 123456;
int rev = 0;
while (i != 0)
{
int rem = i%10;
i = i/10;
rev= rev*10+rem;
}
[Link]("Reverse number is "+ rev);
}
}
output:Reverse number is 654321

[Link] a program to find wheather the number is Strong or not?


public class Strong {
public static void main(String[] args) {
{int num= 145;
int temp = num;
int sum = 0;
while (num != 0)
{int rem = num%10;
int fact = 1;
for(int i=1;i<=rem;i++)
{
fact = fact*i;
}
sum = sum+fact;
num= num/10;
}
if (sum==temp){
[Link](temp+" is a strong number");
}
else
{[Link](temp+" is not a strong number");
}
}
}
}
Output:
145 is a strong number
Class and Object:
Class
1. Class is a blueprint in Java.
2. Class is a logical entity.
3. A class is also called as Master copy or template.
Object:
1. Object is a real word entity. This is having some states and behaviours.
2. An object is a physical entity.
3. An object is also called as an instance of a class.
Note:
1. without class we cannot create an object.
2. A class is required to create an object.
3. By using a single class, we can create a multiple objects.
4. Class is a keyword and it is a non-primitive data type.

Syntax of a class:

Class classname
{Data type variable;
Data type variable;
return type method name()
{ //statements
}// end of method
return type method name()
{ //statements
}// end of method
}//end of class

Ex: class Remote


{
String name;
String colour;
void switchon()
{ }
void switchoff()
{ }
}
Notes:
1. The variable which is declared inside the class and outside the method is called Instance
variables.
2. The variable which is declared inside the method is called local variable.
3. Instance variables are also called as a states or Data members or fields.
4. Methods are also called as a Behaviour or Functional member or Actions.
5. Data members and functional members are the members of the class.
6. A class can have N number of data members and functional members.

Object Creation:

Remote r = new Remote ();


a. Remote is a class name.
b. r is Reference variable, it is a variable which refers to the object. By using the reference variable
we can access data members and functional members or members of the class.
c. new is an operator which allocate some memory for the object .
d. Remote() is a Constructor.

Eclipse:
1. Eclipse is a IDE (Integrated development environment).
2. [Link] .org.//downloads.
3. Downloaded.
4. Select eclipse folder, click on [Link] file.
5. Select a workplace.
6. Select workbench.
7. Select open perspective.
8. Select java perspective.
9. Go to file select new, select a java project, give project name, and click on finish.
10. Elaborate the project, right click on src, select new, select a class, give the class name, Sand
click on finish.
11. For the main method shortcut is main+ ctrl +space
12. For the [Link]() Sysout+ ctrl+ space

Ex:
public class Remote {
String name="Sony";//initialisation process
String color="Black";//also called as
instance,variables,datamembers
double cost=500.0;

void switchOn()//methods,behaviours,functional members


{
[Link]("Switch on");
}

void switchOff()
{
[Link]("Switch off");
}
public static void main(String[] args) {

Remote r = new Remote();// object creation


[Link]("Invoking Data Members");
[Link]("Remote name is "+[Link]);
[Link]("Remote color is "+[Link]);
[Link]("Remote price is "+[Link]);
[Link]("Invoking functional Members");
[Link]();
[Link]();
}//end of main method
}// end of class
Output: Invoking Data Members
Remote name is Sony
Remote color is Black
Remote price is 500.0
Invoking functional Members
Switch on
Switch off
# By using a single class , we can create a multiple objects:
Ex:
[Link] Pen
{String name;
String color;
double cost;
}
public class demoo {
public static void main(String[] args) {
Pen p1= new Pen();
[Link]= "Parker";
[Link] = "Black";
[Link] = 400.0;
[Link]("Pen name is "+ [Link]+"\npen color is "+ [Link]+ "\npen cost is"+ [Link]);
Pen p2= new Pen();
[Link]= "Reynolds";
[Link] = "Blue";
[Link] = 30.0;
[Link]("*************");
[Link]("Pen name is "+ [Link]+"\npen color is "+ [Link]+ "\npen cost is"+ [Link]);
Pen p3= new Pen();
[Link]= "Montex";
[Link] = "Red";
[Link] = 40.0;
[Link]("*************");
[Link]("Pen name is "+ [Link]+"\npen color is "+ [Link]+ "\npen cost is"+ [Link]);
}
}

Output: Pen name is Parker


pen color is Black
pen cost is 400.0
*************
Pen name is Reynolds
pen color is Blue
pen cost is 30.0
*************
Pen name is Montex
pen color is Red
pen cost is 40.0

2. class Ticket
{int no_of_tickets=20;
void avaibalitiy ()
{[Link]("Availability tickets are: " + no_of_tickets);
}
void book(int n)
{if (no_of_tickets >= n)
{ no_of_tickets = no_of_tickets -n;
[Link]("User booked " +n + "Tickects");
[Link]("Avalability tickets are "+ no_of_tickets);
}
else
{[Link]("Tickets are not availaible ");
}
}
void cancel( int m)
{ no_of_tickets = no_of_tickets+m;
[Link]("user cancelled "+ m+"tickets");
[Link]("Availability tickets are "+ no_of_tickets);
}
}
public class Demo2 {
public static void main(String[] args) {
Ticket t = new Ticket();
[Link]();
[Link](10);
[Link](5);
}
}
output:
Availability tickets are: 20
User booked 10Tickects
Avalability tickets are 10
user cancelled 5tickets
Availability tickets are 15

METHOD:
1. Method is just like a function which performs some functionality is called method.
Syntax:
return _type method name()
{//statements;
}
2. A method can have n number of input parameters or arguments.
3. Every method has a return type.
Ex:
divison()
{
[Link](“Hi”);
}
output: gives a compile time error because every method has a return type.

4. The variable which is declared inside the method is called as local variable.
5. If the method is not returning any value, then make the return type as Void.
6. If the method is returning any value, then make the return type as particular data type
(method data type should be same as return variable data type).
7. A method can return only one value at a time.
Ex:
Double mul(int p, double q)
{
double r= p*q;
double r1 + p+q;
return r;
return r1;
}
output: It gives compile time error because we can’t return more than one values.

8. If you want to a method to return more than one value at a time, it can be done by using
Arrays concept.
9. Return is the last logical statement inside the method.
Ex:
Double mul(int p, double q)
{ double r= p*q;
double r1= p+q;
return r;
[Link](“Hi”);
}
output: It gives compile time error because return should be last statements inside a
method.

Advantages of method:
1. Reusability.
2. Individual choice of calling i.e we can call only required methods.
IQ3. We can call all the methods inside the S.O.P except if the method return type is void.
EX:
class calculator
{
void add(int a, int b)
{
int c = a+b;
[Link]("value is "+ c);
}
int sub(int x, int y){
int z = x-y;
return z;
}
double mul (int p, double q)
{
double r = p*q;
return r;
}
}
public class Demo4 {
public static void main(String[] args) {
calculator c = new calculator();
[Link](20,10);
[Link](50,50);// we can call a method multiple time
[Link]([Link](20, 10));
[Link]([Link](10, 2.0));
//[Link]([Link](10,20)); compile time error
}
}
output:
value is 30
value is 100
10
20.0

Constructor:
1. Rules of the constructor:

a. Constructor name should be same as a Class name.


b. Constructor can’t have any return type even Void.

2. Constructor is executed during the object creation.


3. A constructor can have an n number of arguments.
4. The variable which is declared inside the constructor is called local variables.
5. Constructor can be categorised into 2 types:
a. Default Constructor.
b. User define constructor.
User define constructor: The constructor which is generated by user is called user defined
constructor. It is also called as an explicit constructor.
It can be categorised into:
i) User define parameterised Constructor: If the constructor is containing any arguments or if the
user is passing any value inside the constructor is called user define parameterised constructor.
Ex:
public class Demo {
Demo(String s, int i) // Parameterized constructor
{
[Link]("value of I is "+i+ "\nvalue of S is "+s);
}
void display()// Method
{
[Link]("I am inside the Display method");
}
public static void main(String[] args)
{
Demo d = new Demo("Rashda",10);
[Link]();
}
}
Output: value of I is 10
Value of S is Rashda
I am inside the Display method

ii) User define Non parameterised Constructor: If the constructor is not having any argument or if
the user is not passing any value inside the constructor is called user define non parameterised
constructor.
Ex:
public class Demo {
Demo() // Non parameterized constructor
{
[Link]("I am inside the constructor");
}
void display()// Method
{
[Link]("I am inside the Display method");

}
public static void main(String[] args) {
Demo d = new Demo();
[Link]();
}
}
Output:
I am inside the constructor
I am inside the Display method

Default Constructor:

1. The constructor which is generated by compiler is called default Constructor.


2. The Default Constructor does not have any implementation (statement).
3. Every CLASS has a default constructor.
4. Default constructor is also called as Implicit Constructor.
Ex:
1. public class Demo {
public static void main (String[] args) {
Demo d = new Demo(10);
}
}
output: gives compile time error , because there is no parameterised constructor, which is present
inside the class.
2. public class Sample{
public static void main(String[] args) {
Sample s = new Sample();
}
}
output: No compile time error
In the above program JVM executed the default constructor which is generated by compiler.
Note:
1. If a user is defining any constructor inside the class, then compiler will not generate any default
constructor.
2. If the user is not defining any constructor inside the class then only compiler will generate default
constructor.
3. Constructor constructs an object and initialises the state.
Ex: public class Sample{
Sample(int i)
{
[Link](i);
}
public static void main(String[] args) {
Sample s = new Sample(10);
Sample s1 = new Sample();

}
}
Output: gives compile time error, because there is no default constructor is present in the above
class.

Purpose of Constructor:
1. Object creation.
2. To initialise the states i.e initialising the local variable values to the instance variables.
Note:
1. We can’t access the local variable value outside the method and outside the constructor.
2. Local variable value is within the method scope or within the constructor scope.
3. Constructor can’t return any value.
Ex:
class Student
{
String name;
int id;
String collegename;
Student(String n,int i,String c) // Constructor
{
name = n;
id = i;
collegename = c;
}
void display()
{[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is John
Id is 1
college name is KIT
Name is Mike
Id is 2
college name is KIT
Name is Adam
Id is 3
college name is KIT

Note: Whenever the local variable and instance variable name are same JVM will get
confused to identify local variable and instance variable. If we want to overcome this
problem we have to use this keyword. this is a keyword it always refers to the instance
variables of the current class.
Ex:
1. class Student
{
String name;
int id;
String collegename;
Student(String name, int id, String collegename) // Constructor
{
name = name;
id = id;
collegename = collegename;
}
void display()
{
[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is Null
Id is 0
college name is Null
Name is Null
Id is 0
college name is Null
Name is Null
Id is 0
college name is Null

[Link] Student
{
String name;
int id;
String collegename;
Student(String name,int id,String collegename) // Constructor
{
[Link] = name;
[Link] = id;
[Link] = collegename;
}
void display()
{
[Link]("Name is "+name+"\n Id is "+ id + "\n college name is "+ collegename);
}
}
public class Sample {
public static void main(String[] args) {
Student S1 = new Student ("John",1,"KIT");
[Link]();
Student S2 = new Student ("Mike",2,"KIT");
[Link]();
Student S3 = new Student ("Adam",3,"KIT");
[Link]();
}
}
output:
Name is John
Id is 1
college name is KIT
Name is Mike
Id is 2
college name is KIT
Name is Adam
Id is 3
college name is KIT

# Default Value:
String = Null
int = 0
byte = 0
short = 0
long = 0
float = 0.0
double = 0.0
char = space
Boolean = false
Method Overloading:
In a class when we have more than one method, having the same name with different input
parameters is called Method Overloading.
1. Different input parameters in the sense, we can change the number of parameter.
Ex: Void search (int i)
{
}
void search (int i , int j)
{
}
2. We can change the data types of the parameter.
Ex: Void search (int i)
{
}
void search (double d)
{
}
3. We can change the sequence of parameter.
Ex: Void search (int i , double d)
{
}
void search (double d , int i)
{
}
4. In method overloading return type doesn’t makes any difference (each method may have
different return type, it needn’t be same).
Ex: int search(int i)
{
return i ;
}
double search(double d )
{
return d;
}
5. In method overloading variable name is NOT considered, it may have same or different variable
names.

int search(int i)
{
return i ;
}
double search(double i )
{
return i ;
}
Note: Method Overloading is mainly used for searching purpose.

Ex:
public class Demo1
{
int Search(int i)
{
return i;
}
double Search (double i)
{
return i;
}
int Search (int i ,int j)
{
return i+j;
}
void Search (double d , String s)
{
[Link](d+"\n"+s);
}
void Search ( String s, double d)
{
[Link](s+"\n"+d);
}
public static void main(String[] args)
{
Demo1 d = new Demo1();
[Link]([Link](20));
[Link]([Link](20.0));
[Link]([Link](90,40));
[Link]("abc", 9.0);
[Link](3.0, "Rashda");
}
}
Output:
20
20.0
130
abc
9.0
3.0
Rashda

Ex:
1.)
void m1()
{
}
int m1()
{
int i= 10;
return i;
}
Output: Compile time error (not method overloading)

2.)
void m1(int i)
{
}
void m1(String s)
{
}
void m1(int j)
{
}
Output: Compile time error (not method overloading)
3.)
void m1()
{
}
void m1(int i, int j)
{
}
void m1(int i , int j, char c)
{
} // Method overloading.
4.)
void m1()
{
}
void m2(int i)
{
} // Not Method overloading, because method names are different.

Constructor Overloading:
1. In a class when we have more than one constructor having the same name but different input
parameters is called Constructor Overloading.
2. Different parameters in the sense, we can change the number of parameters.
3. We can change the data types of parameter.
4. We can change the sequence of the parameter.
5. In Constructor overloading variable name shouldn’t be considered.

Note: Constructor overloading is mainly used for object creation along with searching purpose.
Ex:
class Employee
{
Employee (String name)
{
[Link](name);
}
Employee (double sal)
{
[Link](sal);
}
Employee (String name, int id)
{
[Link](name+ "\n"+ id);
}
Employee (int id, String name)
{
[Link](name + "\n" +id);
}
}
public class Demo2
{
public static void main(String[] args)
{
Employee e1 = new Employee("John");
Employee e2 = new Employee("40000.0");
Employee e3 = new Employee(1,"Mike");
Employee e4 = new Employee("Adam", 2);
}
}
Output:
John
40000.0
Mike
1
Adam
2
INHERITANCE:
1. Acquiring the properties of one class by the other class is called Inheritance.
2. Inheritance is achieved by using a keyword Extends.
3. Inheritance is achieved by keeping all the common properties in a one class, that class is
called Parent class or Super class or Main class.
4. The class that acquires common properties from the Super class is called as Child or Sub
Class.
5. Once if we write extends keyword the properties which is present in Parent class is
automatically inherit to the Child class.
6. If we create an Object of Parent class we can access the properties of only Parent class.
7. If we create an Object of child class, that object is shared with Parent class and Child class i.e
we can access the properties of both Parent and Child class.
8. Inheritance is also called as is a relationship or Generalisation.

Types of Inheritance:
1. Single level Inheritance: One class is extended by only one class is called Single level
Inheritance.

Extends
B

Ola cab

Ola share

In this example Ola share inherit the features of Ola cab (booking, cancel, and tracking)

Ex:
class Employee1 //Parent class
{
double bonus = 2000.0;//Parent class variable
void working()//parent class method
{
[Link]("Working");
}
}
class Developer extends Employee1// child class
{
double sal = 50000.0;//child variable
void development()//child method
{
[Link]("developing code...");
}
}
public class Sample1 {
public static void main(String[] args) {
[Link]("Accessing parent members");
Employee1 e = new Employee1();//parent class object
[Link]([Link]);
[Link]();
[Link]("Accessing both parent and child");
Developer d = new Developer();// child class object
[Link]([Link]);
[Link]([Link]);
[Link]();
[Link]();
}
}
Output:
Accessing parent members
2000.0
Working
Accessing both parent and child
2000.0
50000.0
Working
developing code...

2. Multi Level Inheritance:


One class is extended by one class in turn that class is extended by other class is
called multi level inheritance.

B
C

Ex:
While upgrading an application from one version to another version, in each upgrade new
version inherit features from previous one version.

1.0

1.1

1.2

Here we need to create only version 1.2 object, because it will automatically inherit the
features of 1.1 and 1.0.

Ex:
class flipkart
{
String prodname = "Mobile";
double cost = 20000.0;
String Color = "Black";
void orderdetails()
{
[Link]("Welcome to Flipkart");
[Link]("Product name is"+prodname +
"\nproduct color is"+Color+"\nproduct cost is"+cost);
}
}
class Firststatus extends flipkart
{
void packing()
{
[Link]("Your product has been packed succeessfully");
}
void Shipping()
{
[Link]("Your product has been shipped");
}
}
class Finalstatus extends Firststatus
{
void deliverystatus()
{
[Link]("Your product has been delivered succeessfully");
}
}
public class Sample1 {
public static void main(String[] args) {
Finalstatus f = new Finalstatus();
[Link]();
[Link]();
[Link]();
[Link]();
}
}
output:
Welcome to Flipkart
Product name is Mobile
product color is Black
product cost is20000.0
Your product has been packed successfully
Your product has been shipped
Your product has been delivered successfully
3. Hierarchy:
When one super class is extended by so many subclasses it is called hierarchy inheritance.

B C D

Ex:

Employee

Test
Developer Engineer Manager
Ex:
class Employee2
{
String name;
int empid;
double sal;
String designation; //declaration
void swipecard()
{
[Link]("Employee name is "+ name+"\nEmployee Id is "+empid);
[Link]("Swiped Card");
}
void empfulldetails()
{
[Link]("****full details****");
[Link]("Employee name is "+name+"\nEmployee Id is "+empid+
"\nEmployee salary is "+sal+"\nEmployee Designation is "+designation);
}
}
class Developer extends Employee2
{
Developer(String n,int i, String d, double s)
{
name =n;
empid = i;
sal = s;
designation = d;
}
void developcode()
{
[Link]("Developing code");
}
}
class Tester extends Employee2
{
Tester(String n,int i, String d, double s)
{
name =n;
empid = i;
sal = s;
designation = d;
}
void testApplication()
{
[Link]("Testing the Application");
}
}
public class Sample1 {
public static void main(String[] args) {
Developer d = new Developer("Sushma", 1,"Developer",1000);
[Link]();
[Link]();
[Link]();
Tester t = new Tester ("Anupama",2,"Tester",2000);
[Link]();
[Link]();
[Link]();
Tester t1 = new Tester ("Uday",3,"Tester",3000);
[Link]();
[Link]();
[Link]();
}
}
Output:
Employee name is Sushma
Employee Id is 1
Swiped Card
Developing code
****full details****
Employee name is Sushma
Employee Id is 1
Employee salary is 1000.0
Employee Designation is Developer
Employee name is Anupama
Employee Id is 2
Swiped Card
Testing the Application
****full details****
Employee name is Anupama
Employee Id is 2
Employee salary is 2000.0
Employee Designation is Tester
Employee name is Uday
Employee Id is 3
Swiped Card
Testing the Application
****full details****
Employee name is Uday
Employee Id is 3
Employee salary is 3000.0
Employee Designation is Tester
#Multiple: One subclass can inherit only one Super class at a time, if it tries to inherit multiple Super
class, JVM will get confused or it will leave ambiguity. So multiple inheritance is not possible in JAVA
by using class. But it is possible by using Interface.

Ex:

B(m1) C(m1)

Class A extends B, C
{ A a = new A();
a.m1();}
In the above diagram class B and Class C are containing m1 method and we are invoking this m1
method by using A class object, then JVM will get confused should we need to invoke the m1
method which is present in B class or C class. This problem is known as ambiguity problem or
Diamond problem.
Ex:
class A
{
}
class B
{
}
class c
{
}
class D extends B, C
{
}

Output: Compile time error because in JAVA, we can’t use multiple inheritance by using class.

#Cyclic Inheritance:

Any subclass can inherit any Parent class but Parent class can’t inherit subclass, so cyclic inheritance
is not possible in JAVA.

A
B

class A extends B
{
}
class B extends A
{
}
output: Compile time error because, cyclic inheritance is not possible in JAVA.

Note:
1. JAVA supports only 3 kinds of Inheritance by using class i.e Single level, Multi-level, and Hierarchy.
2. JAVA doesn’t support multiple and Cyclic Inheritance.

Advantages of Inheritance:
1. Reusability.
2. Extendibility.
3. It takes less time to build an application.
4. Application takes less memory.
5. Execution is faster.
6. We can improve the performance of application.

Note: Inheritance is mainly used to upgrade an Application.

Note:

1. Local variable should be initialised.


2. We can’t declare local variable before we use.
3. Default values will be applicable only for Instance variable.
4. Default values will not be applicable for local variable.
Ex: public class Demo
{
Int i ;
void m1()
{String s;
[Link] (s); // use, compile time error
}
public static void main (String [] args)
{
Demo d = new Demo();
[Link](d.i);//0
}
}
Note: The super most class in JAVA is Object Class(each and every class is directly or
indirectly inheriting Object class).
CONSTRUCTOR CHAINING:
1. Any constructor of a class wants to call Constructor of the same class by using this statement or
this statement is used to call current class constructor.
2. We can’t have more than one this statement inside the constructor.
Ex: cube(double h)
{
this(h,4.0);
this(h,6.0,9.0);
}
output: Compile time error because we can't have more than one this statements inside the
constructor.

3. This statement should be the first line of code inside any constructor.
Ex: cube(double h)
{
[Link]("Hi");
this(h,4.0);
}
output: Compile time error because this state statement should be first line of code inside any
constructor.

EX: (this statement)


class cube
{
double height;
double width;
double length;
cube(double h)
{
this(h,4.0);
}
cube(double h,double w)
{
this(h,w,5.0);
}
cube(double h,double w, double l)
{
height =h;
width= w;
length = l;
}
void volumeofcube()
{
double volume = height*length*width;
[Link]("Volume of the Cube is "+volume);
}
}
public class Sample2 {
public static void main(String[] args) {
cube c1 = new cube(3.0);
[Link]();
}
}
output: Volume of the Cube is 60.0

4. We can call any constructor inside other constructor, there is no sequence restriction.

IQ: What is super and this statement in java?

5. Any constructor of a class wants to call constructor of the Super class by using Super statement or super
statement is used to call a super class constructor.

6. Super statement should be the first line of the code inside any Constructor.
7. We can’t have more than one super statement inside the Constructor.
8. We can have either this statement or super statement inside the constructor , i.e we shouldn’t
write this and super statement at a time inside the Constructor.
Ex: (super statement)
[Link] Cube//parent class
{
double height;
double width;
double length;
Cube(double l)
{
this(l,3.0);
}
Cube(double l,double w)
{
this(l,w,4.0);
}
Cube(double l,double w, double h)
{
height =h;
width= w;
length = l;
}
void display()
{
double volume = height*length*width;
[Link]("Volume of the Cube is "+volume);
}
}
class Cube1 extends Cube//child
{
Cube1()
{
super(3.0);
}
}
public class Sample2 {
public static void main(String[] args) {
Cube1 c1 = new Cube1();
[Link]();
}
}
output:

Volume of the Cube is 36.0

Packages:
Packages are nothing but collection of folders, which segregate different classes or files according to
related folders.
Q. Why packages?
Ans: Packages are required that we can easily categorised class or files.
Q. How to create a Package?
Ans: a. Create a java project
b. Under the src right click select new select a package give a package name click on
finish.
c. Under the package right click select newselect a classgive the class name click on
finish.
Note:
i. If the project is commercial we have to start the package name by using com.
ii. If the project is Organisational we have to start the package name by using org.
iii. If the project is Educational we have to start the package name by using edu.
iv. If the project is government we have to start the package name by using gov.
Import:
Import is a keyword, it indicates the JVM, that we are importing particular classes from the particular
package.
1. Package declaration should be the first line of the code in any class.
2. Import statement should be immediate next line of package declaration.
3. Star (*) represents importing all the classes from one package to another package.
Fully qualified Path name: It is a path which shows the location of class or file.

Ex:
package [Link];
public class Admin {
public void addproduct()
{
[Link]("Added product");
}
}
package [Link];
import [Link].*;
import [Link].*;
public class User {
Admin a = new Admin();
void display()
{
[Link]();
[Link]("Displayed product");
}
public static void main(String [] args)
{
User u = new User();
[Link]();
}
}
Output:
Added product
Displayed product

Note:
1. The default package in JAVA is [Link].
2. [Link] package is already imported in every Java file.
3. [Link]String, class, [Link], threads, Exception handling.
4. [Link] Scanner, collection, Date and framework.
5. [Link]  File handling.
6. [Link]  swings.
7. [Link]  simpledate format.

Note:
1. If we uses the class which is present in [Link] package, no need to import the package
explicitly.
2. If we use the class which is present in other class than [Link] package, then we have to import
the package explicitly.
Access Modifier:
Outer class/ Variables Method Constructor
Inner class

Public Yes Yes Yes Yes

Private No/Yes(I.C) Yes Yes/ Yes


No(Abstract
method)

Default Yes Yes Yes Yes

Protecte No/Yes(I.C) Yes Yes Yes


d Public:

1. Public is a highly visible Access modifier in Java.


2. We can access public members anywhere in the class i.e., we can access public members inside
the class, outside the class and outside the package.
Private:
1. Private is a highly restricted Access modifier in Java.
2. We can access private members within the class.
3. Private members can’t be access outside the class and outside the package.
Default:
1. If we don’t mention any access modifier by default, it would be taken as a default Access modifier.
2. We can access default members within the class and outside the class.
3. We can access default members anywhere in the same package.
4. Default access modifier is a package level access modifier.
5. Default members can’t be accessed outside the package.
Protected:
1. We can access protected members inside the class and outside the class in a same package.
2. We can access protected members anywhere in a same package.
3. Protected members can’t be accessed outside the package, but we can access protected members
outside the package only in case of Inheritance.
Ex:
[Link] A;
public class A {
public void pubmeth()
{
[Link]("Public method");
}
private void primeth()
{
[Link]("Private method");
}
void defameth()
{
[Link]("Default method");
}
protected void protecmethod()
{
[Link]("Protected method");
}
public static void main(String [] args)
{
[Link]("Accessing members inside the class");
A a = new A();
[Link]();
[Link]();
[Link]();
[Link]();
C c = new C();
[Link]("Accessing members outside the class");
[Link]();
}
}
class C
{
A a = new A();
void displ()
{
[Link]();
//[Link](); compile time error
[Link]();
[Link]();
}
}
Output:
Accessing members inside the class
Public method
Private method
Default method
Protected method
Accessing members outside the class
Public method
Default method
Protected method
2. package B;
import A.*;
public class B extends A
{
A a= new A();
void show()
{
[Link]();
//[Link]();compile time error
//[Link]();compile time error
protecmethod();
}
public static void main(String [] args)
{
B b = new B();
[Link]("Accessing members outside the package");
[Link]();
}
}
Output:
Accessing members outside the package
Public method
Protected method

Access Modifier:
1. Defines the scope of the every member.
2. In java Access modifiers are used to control the members of the class or variable or method or
constructor.
3. There are Eleven Access Modifiers available in Java:
Public, private, protected, Static, Abstract, Final, Synchronized, Transient, Volatile, Strictf, and
Native.
Note:
1. Abstract methods shouldn’t be private.
2. Outer class can’t be private and protected.
3. We can give any kind of Access modifiers to the inner class.
4. We shouldn’t give any access modifiers to the local variables, because we can’t access the local
variable value outside the method. Hence there is no use of giving access modifiers to the local
variables.

Has a relationship:
1. Associating an object of a class into the object of the other class is called Has a relationship , or
one object is containing another object is called Has a relationship.
2. Has a relationship is also called Aggregation.
Ex: Car has a Music System
Car has an Engine.
Person has a mobile.
Mobile has a battery.
Ex:
[Link] Car
{
String name = "Innova";
double cost= 300000.0;
String color = "Black";
MusicSystem m = new MusicSystem();// has a relationship
Engine e = new Engine();// has a relationship
void drive()
{
[Link]("Driving");
}
class MusicSystem
{
String name = "Sony";
double cost = 35000.0;
void PlayMusic()
{
[Link]("Playing music");
}
}
class Engine
{
String name ="Bosch";
}
}
public class Demo {
public static void main(String[] args) {
Car c = new Car();
[Link]("Car name is "+[Link]);
[Link]("Car color is "+[Link]);
[Link]();
[Link]("MusicSystem name is "+[Link]);
[Link]("MusicSystem cost is "+[Link]);
[Link]();
[Link]("Engine name is "+[Link]);
}
}
Output:
Car name is Innova
Car color is Black
Driving
MusicSystem name is Sony
MusicSystem cost is 35000.0
Playing music
Engine name is Bosch

2. class Mobile
{
Battery b = new Battery();//Has a relationship
void MakeCall()
{
[Link]("Jio Calling");
[Link]();
}
void sendmsg()
{
[Link]("Texting...");
[Link]();
}
void PlayGames()
{
[Link]("Playing Candycrush...");
[Link]();
}
void charging()
{
[Link]("Charging...");
[Link]();
}
}
class Battery
{
int charge = 100;
void recharge()
{
charge = charge+20;
}
void discharge()
{
charge = charge-10;
}
}
public class Demo3 {
public static void main(String[] args) {
Mobile m = new Mobile();
[Link]("Battery status is "+ [Link]+"%");
[Link]();
[Link]();
[Link]();
[Link]("Battery status is "+ [Link]+"%");
[Link]();
[Link]("Battery status is "+ [Link]+"%");
}
}
Output:
Battery status is 100%
Jio Calling
Texting...
Playing Candycrush...
Battery status is 70%
Charging...
Battery status is 90%
Note:
1. (I.Q) Private members can’t be inherited , because private members scope is within the class.
2. (I.Q) Constructor can’t be inherited, because Constructor name should be same as class name and
Constructor are not the members of the class, rather than Constructors are special members of the
class.
3. Every non Parameterised Constructor by default having a super statement, that super statement
is used to call super class Constructor.
Ex:
class Alpha
{
Alpha()
{
[Link]("I am in Alpha Constructor");
}
}
class Beta extends Alpha
{
Beta()
{
[Link]("I am in Beta Constructor");
}
}
class Gama extends Beta
{
Gama()
{
[Link]("I am in Gama constructor");
}
}
public class Demo4
{
public static void main(String[] args) {
Gama g = new Gama();
}
}
Output:
I am in Alpha Constructor
I am in Beta Constructor
I am in Gama constructor

Method Overriding:
1. It is a process of giving the child specific implementation by keeping the Parent method is called
Method Overriding.
2. Method Overriding is possible only in case of Inheritance.
3. While overriding the method return type, method name and parameters must be same, but
Implementation can be different.

Advantages: It is the one way to give child specific implementation.


Ex:
public class MyApplication1
{
void register()//Parent method
{
[Link]("Username should consist of four characters");
[Link]("Password should consist of four characters");
//parent implementation
}
void login(String name, String password)
{
if([Link]("Sushma")&& [Link]("Sushma123@"))
{
[Link]("Loggined Successfully");
}//parent implementation
}
}
public class MyApplication2 extends MyApplication1
{
void register()//Parent method, Method overriding
{
[Link]("Username Should consist of four Characters");
[Link]("Password should consist of 6 Characters and it must contain a special character
and a number ");
//child implementation
}
}
public class Sample3 {
public static void main(String[] args) {
MyApplication2 m = new MyApplication2();//Child class
[Link]();
[Link]("Sushma", "Sushma123@");
}
}
Output:
Username Should consist of four Characters
Password should consist of 6 Characters and it must contain a special character and a number
Loggined Successfully

Note: Method overloading is possible in case of Inheritance and without inheritance also.
Ex:
class Application
{
void register()//Parent method
{
[Link]("I am in Application");
}
}
class Application1 extends Application
{
void register(String name)//child method
{
[Link]("I am in Application1");
}
}
public class Sample3 {
public static void main(String[] args) {
Application1 a = new Application1();
[Link]();
[Link]("Sushma");
}
}
Output:
I am in Application
I am in Application1

Assignment: Q. Person has a Mobile, Mobile has a Setting, Setting has a Wifi?
class Person
{
String name = "Angel";
Mobile m = new Mobile();
void Talkingonmobile()
{
[Link](name+" talking on "+[Link]+" Mobile");
[Link]();
}
}
class Mobile
{
Setting s = new Setting();
String name = "Samsung";
double cost = 20000.0;
void checkingsetting()
{
[Link]("Checking Wifi connection in Mobile");
[Link]();
}
}
class Setting
{
Wifi w = new Wifi();
void connectedwifi()
{
[Link]("Settting....");
[Link]();
}
}
class Wifi
{
void statuswifi()
{
[Link]("connecting...");
}
void connectingwifi(String ssid, String Password)
{
if([Link]("Rashda") && [Link]("123!@#") )
{
[Link]("connected to Wifi....");
}
}
}public class Hasarelationship
{
public static void main(String[] args) {
Person p= new Person();
[Link]();
[Link]("Rashda","123!@#");
}
}
Output:
Angel talking on Samsung Mobile
Checking Wifi connection in Mobile
Settting....
connecting...
connected to Wifi....

Note:
While Overriding the method, access modifier visibility goes on Increasing i.e. If the parent class
method is Private then the child class method can be Private or default or protected or public.
If the parent class method is default then the child class method can be default or protected or
public but it shouldn’t be private.
If the parent class method is protected then the child class method can be protected or public but it
shouldn’t be private and default.
If the parent class method is public then the child class method can be public but it shouldn’t be
private, default and protected.

(I.Q)Rules of Method overriding:


1. Return type, method name, parameters must be same but implementations can be different.
2. Overriding is possible only in case of Inheritance.
3. Access member’s visibility goes on increasing.
Note:
1. We can give any type of access modifiers while overloading the Method.
2. We can’t Override Private method.
3. We can overload private method.

Typecasting:
1. Converting from one data type to other data type is called Typecasting.
2. Typecasting can be categorised into 2 types:
a. Implicit Typecasting:
i) Compiler will performs implicit typecasting.
ii) If we want to assign smaller data type value to bigger data type then it is called implicit
typecasting.
iii) There is no loss of information in implicit typecasting.
iv) It is also called as an up casting or widening conversion.

Ex:
public class ImplicitTypeCasting {
public static void main(String[] args) {
char c = 'A';
int i = c; //implicit type casting, Taking ASCII value A.
[Link](i);
int j = 30;
double d = j;//implicit type casting
[Link](d);
}
}
Output:
65
30.0
b. Explicit Typecasting:
i) Java doesn’t support to assign the bigger data type value to the smaller data type, but still if
we want to assign programmer has to typecasting explicitly .
ii) Programmer will perform explicit typecasting.
iii) There is loss of information in explicit typecasting.
iv) It is also called as down casting or narrowing conversion.
Ex:
public class ExplicitTypecasting {
public static void main(String[] args) {
double d = 30.0;
//int i = d; compile time error
int i = (int)d; //Explicit type casting
[Link](i);
int j = 90;
//byte b = j; compile time error
byte b = (byte)j; // Explicit type casting
[Link](b);
}
}
Output:
30
90
Up casting:
1. Any parent can refer to the any of the child class object in the entire Inheritance hierarchy or
assigning the child class object to the parent class reference variable is called Up casting.
2. By using parent class reference variable, we can access only parent class members.
3. By using a parent class object, we can’t access child specific members, but in case of overriding we
can take the implementation of child class.
Syntax: Parent p = new child();
Ex:
class Veg
{
void cook()// parent method
{
[Link]("Cooking...");
}
void chop()//Parent method
{
[Link]("Chopping");
}
}
class Carrot extends Veg
{
void preparehalwa()//Childmethod
{
[Link]("Prepare Halwa...");
}
void cook()//Parent method,Method Overriding
{
[Link]("Carrot cooking..");//Child implementation
}
}
public class Upcasting {
public static void main(String[] args) {
/* Veg v = new Veg();//Parent object
[Link]();
[Link]();
//[Link](); compile time error
Carrot c = new Carrot();// Child object
[Link]();
[Link]();
[Link]();*/
Veg v1 = new Carrot();
[Link]();
[Link]();
// [Link](); compile time error
}
}
Output:
Chopping
Carrot cooking..

Note:1. Variables of a class can’t be override.

2. If we calling same name variable present in both super and sub class by using child object then it
will execute child variable, because child object first consider child members.

Note: Super is a Keyword it is used to call super class members.


Ex:
class Alpha1
{
int i=10;//parent variable
void display()//parent method
{
[Link]("I am in parent class");
}
}
class Beta1 extends Alpha1
{
int i=40;//child variable
void display()//overriding,parent method
{
[Link](super.i);
[Link]("I am in child class");
}
}
public class Super {
public static void main(String[] args) {
Alpha1 a = new Beta1();
[Link]( "value of i is "+a.i);//10
[Link]();
Beta1 b = new Beta1();//Child object
[Link]("Value of i is "+b.i);//40(because first consider child member)
[Link]();
}
}
Output:
value of i is 10
10
I am in child class
Value of i is 40
10
I am in child class
Instanceof Operator:
1. Instance of operator is a comparison operator, it will check whether the object is a specified class
type or not.
2. If it is a specified class type it returns true, if it is not specified class type it returns false.
Ex:
class Alpha2
{
void display()//parent method
{
[Link]("I am in parent class");
}
}
class Beta2 extends Alpha2
{
void display()//overriding,parent method
{
[Link]("I am in child class");
}
}
public class Instanceof {
public static void main(String[] args) {
Alpha2 a = new Alpha2();
[Link]( a instanceof Alpha2);//true
[Link]( a instanceof Beta2);//false
Beta2 b = new Beta2();
[Link]( b instanceof Alpha2);//true
[Link]( b instanceof Beta2);//true
Alpha2 a1 = new Beta2();
[Link]( a1 instanceof Alpha2);//true
[Link]( a1 instanceof Beta2);//true
}
}
Output:
true
false
true
true
true
true
Down Casting:
1. Java doesn’t support to assign the superclass object to the subclass reference variable(it will give a
compile time error).
2. Still if we wanted to convert then explicitly programmer has type casted.
3. Java doesn’t support to convert the super class object to the sub class directly, if we are trying to
convert it gives a runtime error i.e. class cast exception.
4. If we wanted to overcome this problem or to achieve down casting, first we have to make it as up
casting then we have to achieve down casting.

Note: Without Up casting we can’t achieve Down casting.

Ex:
class Alpha3
{
void display()//parent method
{
[Link]("I am in parent class");
}
}
class Beta3 extends Alpha3
{
void display()//overriding,parent method
{
[Link]("I am in child class");
}
}
public class Downcasting {
public static void main(String[] args) {
//Alpha3 a = new Beta3();upcasting
//Beta3 b = new Alpha3();Compile time error
/*Beta3 b = (Beta3) new Alpha3();//runtime error, Class cast exception
[Link]();
*/
Alpha3 a = new Beta3();//upcasting
Beta3 b = (Beta3) a;//downcasting
[Link]();
}
}
Output:
I am in child class

Ex:
class Animal//parent class
{
}
class Dog extends Animal//Child class
{
}
class Cat extends Animal//Child class
{
}
class Cow extends Animal// child class
{
}
class Display
{
void convert(Animal a)
{
if (a instanceof Dog)
{
Dog d = (Dog)a;
[Link]("Animal converted to Dog");
}
else if(a instanceof Cat)
{Cat c= (Cat)a;
[Link]("Animal converted to Cat");
}
else if(a instanceof Cow)
{Cow c= (Cow)a;
[Link]("Animal converted to Cow");
}
}
}
public class Downcasting1 {
public static void main(String[] args) {
Display d = new Display();
[Link](new Cow());
}
}
Output:
Animal converted to Cow
Static and Non Static:
If we make any variable as a static access modifiers i.e. we can call it as a static variable.
EX:
[Link] Student1
{
String name;
int Id;
static String Collegename = "KIT";
Student1(String n, int i)//constructor
{
name= n;
Id= i;
}
void Display()//method
{[Link]("Name is "+name+"\nId is "+Id+"\nCollegename is "+Collegename);
}
}
public class Staticnonstatic {
public static void main(String[] args) {
Student1 s1 = new Student1("John",1);
Student1 s2 = new Student1("Mike",2);
Student1 s3 = new Student1("Adam",3);
[Link]();
[Link]();
[Link]();
}
}
Output:
Name is John
Id is 1
Collegename is KIT
Name is Mike
Id is 2
Collegename is KIT
Name is Adam
Id is 3
Collegename is KIT

2. NameNonstatic
Id Nonstatic
Trainername Static

3. EmpnameNonstatic
Emp Id Nonstatic
Companyname Static

Note:
1. Any Non static method wants to call a non static method, we can call it directly by using method
name.
2. Any static method wants to call static method; we can call it directly by using method name.
3. Any Non static method wants to call a static method; we can call it by using class name.
[Link] Static method wants to call non static method, we can call it by using Object.
Ex:
public class Staticnonstatic1 {
void m1()
{
[Link](" m1 method");
}
static void m2()
{
new Staticnonstatic1().m1();
[Link](" m2 method");
}
void m3(){
Staticnonstatic1.m2();
[Link](" m3 method");
}
void m4()
{
m3();
[Link](" m4 method");
}
static void m5()
{m2();
[Link](" m5 method");
}
public static void main(String[] args) {
Staticnonstatic1 s = new Staticnonstatic1();
s.m4();
m5();//m5 and main both are static , so we can directly call it.
}
}
Output:
m1 method
m2 method
m3 method
m4 method
m1 method
m2 method
m5 method

Note:
1. If any static members present in same class, we can access it by using Class name or members
name.
2. If any static members present in different class, we can access it by using Class name.
3. If any Non static members are present in same class or different class, we have to call it by using
Object.
Ex:
class Employee1
{
String empname= "Adam";
static String Companyname= "Infosys";
void m1()
{
[Link]("m1 method");
}
static void m2()
{
[Link]("m2");
}
}
public class Staticnonstatic2 {
String name= "John";//non static
static String Trainername= "Sushma";//Static
void m3()//non static
{
[Link]("m3 method");
}
static void m4()//static
{
[Link]("m4");
public static void main(String[] args) {
[Link]("Static members accessing by using members name");
[Link](Trainername);
m4();
[Link]("Static members accessing by using class name");
[Link]([Link]);
Staticnonstatic2.m4();
//[Link](name); compile time error.
[Link]("Non Static members accessing by using Object ");
Staticnonstatic2 s= new Staticnonstatic2();
[Link]([Link]);
s.m3();
[Link]("Static members accessing in different class");
[Link]([Link]);
Employee1.m2();
[Link]("Non static members accessing by using Object");
Employee1 e = new Employee1();
[Link]([Link]);
e.m1();
}
}
Output:
Static members accessing by using members name
Sushma
m4
Static members accessing by using class name
Sushma
m4
Non Static members accessing by using Object
John
m3 method
Static members accessing in different class
Infosys
m2
Non static members accessing by using Object
Adam
m1 method

Note:
1. Static members doesn’t belong to the object, rather than it belongs to the class, hence static
members are also called as class members.
2. Non static members belong to the Object.
3. We can’t inherit static members.
4. Static methods can’t be overridden.
5. Static methods can be overloaded.
6. We can’t override main method, because it is static.
7. We can overload the main method.
8. There is a only one copy of the static members created inside the memory.
9. For each and every object, different copy should be created for non static members.
10. We can inherit non static members.
11. We can override non static members.
EX:
class Veg1//parent class
{
void cook()//parent method
{
[Link]("cooking...");//parent implementation
}
static void chop()// Parent method
{
[Link]("Chopping...");
}
}
class Carrot1 extends Veg1//Child class
{
void cook()//parent method,method overriding
{
[Link]("Carrot cooking...");//child implementation
}
static void chop()// child method, Method hiding
{
[Link]("Carrot Chopping...");
}
}
public class Staticnonstaic3 {
public static void main(String[] args) {
Veg1 v = new Carrot1();//Upcasting
[Link]();//carrot cooking
[Link]();//chopping
}
}
Output:
Carrot cooking...
Chopping...

Note:
1. In the above program , if both the members are non static i.e. we can call it as method
Overriding.
2. If both the methods are static i.e we can call it as method hiding (it look likes a method overriding,
but it is not a method overriding, it is method hiding)
3. By using the child class object, we can use the parent class static members but those static
members can’t be inherited to the child class.(because child object is also an object of parent class)
Ex:
class Animal1
{void eating()
{
[Link]("Eating..");
}
static void Sleeping()
{
[Link]("Sleeping..");
}
}
class Dog1 extends Animal1
{
void barking()
{
[Link]("Barking...");
}
}
public class staticnonstatic4 {
public static void main(String[] args) {
Dog1 d= new Dog1();
[Link]();
[Link]();
}
}
Output:
Eating..
Sleeping..

Static Block:
1. Static block is a block which is executed even before the main method.
2. JVM is always giving highest priority to the static block even before the main method, then priority
goes to the main method.
3. If a class is containing multiple static blocks then based on the sequences static block should be
executed.
Ex:
1. public class Static {
static //static block
{
[Link]("hello");
}
static
{
[Link]("hello1");
}
static
{
[Link]("hello2");
}
public static void main(String[] args) {
[Link]("Hi");
}
}
Output:
hello
hello1
hello2
Hi
2.
public class mysql {
static
{
checklicence();
checkservice();
checkport();
}
mysql()
{
[Link]("My SQL is Application is launched");
}
public static void main(String[] args) {
mysql m = new mysql();
}
static void checklicence()
{[Link]("licenced issued");
}
static void checkservice()
{
[Link]("Service is on");
}
static void checkport()
{
[Link]("Port number is present");
}
}
Output:
licenced issued
Service is on
Port number is present
My SQL is Application is launched
Non Static Block:
[Link] static blocks are executed at the time of object creation.
2. If the class is having multiple non static blocks then based on the sequence non static blocks
should be executed.
3. If the class is containing static block, Non static block, Constructor then the 1 st priority is goes to
static block, 2nd priorities is goes to non-static block and 3rd priority is goes to Constructor.
Ex:
[Link] class Nonstatic {
{
//nonstatic block, Instance block
[Link]("I am in Nonstatic block");
}
{
[Link]("I am in Nonstatic1 block");
}
{
[Link]("I am in Nonstatic2 block");
}
public static void main(String[] args) {
Nonstatic n = new Nonstatic();
[Link]("I am in main method");
}
}
Output:
I am in Nonstatic block
I am in Nonstatic1 block
I am in Nonstatic2 block
I am in main method
2.
public class staNonstaCon {
static
{[Link]("I am in static block");
}
staNonstaCon()
{
[Link]("I am in Constructor");
}
{
[Link]("I am in Non static block");
}
public static void main(String[] args) {
staNonstaCon s = new staNonstaCon();
}
}
Output:
I am in static block
I am in Non-static block
I am in Constructor
Note:
1. Static block allows only static members, it doesn’t allow non-static members.
2. Non static block allows both static and non-static members.
Ex:
public class staticblock {
static int i = 10;
int j= 20;
static//static block
{
//int x= i+j; Compile time error
}
{//Non static block
int k= i+j;
[Link](k);
}
public static void main(String[] args) {
staticblock s = new staticblock();
}
}
Output:
30
Note:
1. Non static members gets initialised at the time of object creation, because non static members
belongs to object.
2. Static members get initialised at the time of class loading, because static members belongs to
class.
3. Static members are stored in static pool of the Heap area.
4. Non static members are stored in non-static pool of the Heap area.
5. Object and instance variables are stored in a Heap area.
6. Methods and local variables are stored in a stack area.
7. PC register holds the instructions.
8. Other than Java language code would be stored in a Native.
9. Class loader is responsible to load the class.
10. For loading .class file memory is required.
11. Execution engine helps to execute the program.
Difference b/w Static and Non static members:

Static members Non static members

1. Also called as a class member. 1. Also Known as Object members.


2. Static members are loaded only once for 2. Non Static members are loaded for every
the entire program execution. object of a class.
3. Static members are loaded into the Heap 3. Non Static members are loaded into Heap
by class loader. memory by JVM.
4. Static members are stored in static pool. 4. Non Static members are stored in Non-static
5 Static members can be accessed through pool.
class name. 5 Non Static members can be accessed through
6. If the static member changes, it gets Object.
changed for entire program. 6. If the Non static members of an instance
change, that change will not reflect in other
object.

Difference b/w Static block and Non static block:

Static block Non static block

1. Static block gets executed before the 1. Non static block gets executed at the time of
main method. object creation.
2. Static blocks are used to initialise the 2. Non Static blocks are used to initialise the non
static members of the class. static members of the class.
3. Static block is also called as Static 3. Non Static block also called as instance
initialisation block. initialisation block.
4. Static block allows only static members 4. Allows both Static and non-static members.
of the class. 5. Non Static block gets executed whenever the
5 Static block gets executed only once for object is created.
the entire program execution.

POLYMORPHISM:
1. Poly means many, morphism means forms.
2. Polymorphism in java is a concept which we can perform single action by different ways is called
polymorphism.
3. OR the process of representing one form in a multiple forms is known as polymorphism.
4. Polymorphism can be categorised into 2 types:
a. Compile time Polymorphism:
[Link] the type of the object is determined at compile time by compiler is called compile time
polymorphism.
2. Compile time polymorphism is also called as a method overloading.
3. Compile time polymorphism is nothing but static polymorphism, static binding or early binding.
Ex: (a method overloading program), real time example of compile time polymorphism is flipkart
search.
b. Run time Polymorphism:
1. If the type of the object is determined at runtime by JVM is called Run time polymorphism.
2. It is also called Method overriding or Dynamic binding or Dynamic polymorphism or Late binding.
3. Run time polymorphism can be achieved by using the concept of Inheritance, Method overriding
and up casting.
4. In Runtime polymorphism based on the Object it will be showing multiple behaviours.
Ex: (a method overriding program), real time example updating App.
FINAL:
1. If we make any variable as a final it is called final variable.
2. We can’t change the value of final variable; it works like a constant value.
Ex: Pie value, Aadhar card number, PAN number, DOB.
3. We can’t override final method.
4. We can’t inherit final class.
5. We can’t declare final variable.
6. Final variable should be initialised.
Ex:
public class Final {
final int i = 80;//instance variable
void m1()//method
{
i= 90;//instance variable,compile time error because we can't change final variable value
[Link](i);
}
public static void main(String[] args) {
Final f = new Final();
f.m1();
}
}
Output:
Compile time error
Abstraction:
It is a process of hiding the implementation details from the user and we are exposing necessary
details to the user is called Abstraction.
Ex: Lose coupling (one object is compatible with any other object i.e. it is not tightly couple with only
one object)
Abstract method: A method which doesn’t have any implementation. It is incomplete method.
Ex: void show ();
Concrete method: : A method which is having implementation. It is complete method.
Ex: void show ()
{

Abstract Class:
1. Abstract class is an incomplete class.
2. It is a combination of abstract method and concrete method.
3. Abstract method is a method, which doesn’t have any implementation.
4. Concrete method is a method which is having implementation.
5. If any abstract methods are present in a class, then make the abstract method as abstract access
modifiers.
6. If any abstract methods are present in a class then make the class as an Abstract access modifier.
7. It is mandatory for a child class to override the Abstract method which is present in an abstract
class.
8. If we don’t override the Abstract method which is present in a class, make the child class as
Abstract.
9. We can’t create an object of Abstract class.
Ex:
1.
abstract class player//abstract class, incomplete class
{
void playsong()//concrete method
{
[Link]("Playing song");
}
abstract void pausecontrol();//abstract method, incomplete method
abstract void screencontrol();
}
class vlc extends player//child class
{void pausecontrol()
{
[Link]("press 'spacebar' to pause the song");
}
void screencontrol()
{
[Link]("press 's' to control the screen");
}
}
class Windows extends player//child class
{
void pausecontrol()
{
[Link]("press 'p' to pause the song");
}
void screencontrol()
{
[Link]("Do change sin the main button");
}
}
public class Abstract {
public static void main(String[] args) {
vlc v = new vlc();
[Link]();
[Link]();
[Link]();
[Link]("<________________>");
Windows w = new Windows();
[Link]();
[Link]();
[Link]();
[Link]("<________________>");
}
}
Output:
Playing song
press 'spacebar' to pause the song
press 's' to control the screen
<________________>
Playing song
press 'p' to pause the song
Do change sin the main button
<________________>

Note: Up casting is used to achieve, loose coupling in abstraction.


2.
import [Link];
abstract class watch//abstract class
{
void showdate()//concrete method
{
[Link]("Date is"+new Date());
}
abstract void showweather();//Abstract method
}
class Rolex extends watch// child class
{
void showweather() {
[Link]("Wheather is Sunny");
}
}
class Smartwatch extends watch// child class
{
void showweather() {
[Link]("Wheather is Rainy");
}
}
class Fastrack extends watch// child class
{
void showweather() {
[Link]("Wheather is Foggy");
}
}
class Display// normal class
{
void show(watch w)//normal method
{
[Link]();
[Link]();
}
}
public class Absract1 {
public static void main(String[] args) {
Display d = new Display();
[Link](new Smartwatch());
[Link](new Rolex());
[Link](new Fastrack());
}
}
Output:
Date isFri May 12 14:50:05 IST 2017
Wheather is Rainy
Date isFri May 12 14:50:05 IST 2017
Wheather is Sunny
Date isFri May 12 14:50:05 IST 2017
Wheather is Foggy

Note:
[Link] using Abstract class , we can achieve loose coupling.
2. By using Abstract class, we can achieve 0 to 100% abstraction.

I.Q: Can Abstract class have a constructor?


Ans: yes, we can have but we have to call by using Super statements.
Ex:
abstract class Animal
{
Animal()
{
[Link]("I am in Abstract class");
}
}
class Alpha extends Animal
{
Alpha()
{
super();
[Link]("I am in Alpha class");
}
}
public class Abstract {
public static void main(String[] args) {
Alpha a = new Alpha();
}
}
Output:
I am in Abstract class
I am in Alpha class
I.Q Abstract class can have a main method?
yes,
Ex:
public class Abstract1 {
public static void main(String[] args) {
[Link]("Hi");
}
}
Output: Hi
I.Q Does multiple Inheritance possible in JAVA, by using abstract class?
No.
I.Q Can Abstract class Inherit an Object class?
Yes.
Interface:
1. Interface is a media between two different systems.
2. Interface contains all the method as Abstract.
3. Concrete methods wouldn’t be present inside Interface.
4. A class inherits other class by using extends keyword.
5. A class inherits interface by using implements keyword.
6. An Interface inherits other Interface by using extends keyword.
7. Interface can’t be the child of any class.
8. It is mandatory for child class to override the abstract method present in Interface.
9. If you are not overriding Abstract method then you should make child class as Abstract.
10. Interface can’t contain any constructor.
11. Interface can’t have main method.
12. Interface can’t inherit Object class.
13. If any abstract method is present in the interface then no need to make the abstract method as
abstract access modifiers.
Ex:
1.
interface iswitch
{
void switchon();
void switchof();
}
class ledlight implements iswitch
{public void switchon()
{
[Link]("Ledlight On");
}
public void switchof()
{
[Link]("Ledlight Off");
}
}
class Solarlight implements iswitch
{public void switchon()
{
[Link]("Solarlight On");}
public void switchof()
{
[Link]("Solarlight Off");
}
}
public class Interface {
public static void main(String[] args) {
ledlight l = new ledlight();
[Link]();
[Link]();
[Link]("<______>");
Solarlight s = new Solarlight();
[Link]();
[Link]();
}
}
Output:
Ledlight On
Ledlight On
<______>
Solarlight On
Solarlight Off

2.
package assignment;
interface sim
{void makecall();
void sendmsg();
}
class jio implements sim
{
public void makecall() {
[Link]("Jio calling");
}
public void sendmsg() {
[Link]("Jio sending msg ");
}
}
class Airtel implements sim
{
public void makecall() {
[Link]("Airtel calling");
}
public void sendmsg() {
[Link]("Airtel sending msg ");
}
}
class mobile
{
void insertsim(sim s)
{
[Link]();
[Link]();
}
}
public class Abstract2 {
public static void main(String[] args) {
mobile m = new mobile();
[Link](new Airtel());
}
}
Output:
Airtel calling
Airtel sending msg

Note:
1. By using interface we can achieve loose coupling.
2. By using interface we can achieve 100% Abstraction.
3. Multiple inheritance is possible in java by using Interface.
4. A class can inherit other class at the same time, we can implement multiple interfaces.
5. Interface contains all the methods by default Abstract and public.
6. We can’t give any access modifiers to the Abstract method, inside the interface.
7. We can give any kind of access modifiers to the Abstract method, inside the Abstract class.

Note: Abstract methods shouldn’t be private, static and final because we can’t override private,
final and static method.

8. Inside the interface all the variables are by default Public, final and static.
Ex:
package [Link];
interface A
{
int i=10;// A interface variable
}
interface b extends A
{
int i=20;
}
public class rashda {
public static void main(String[] args) {
[Link](A.i);
[Link](b.i);
}
}
Output:
10
Abstract Class Interface
20
1. It contains both Abstract and 1. It contains only Abstract method.
concrete method.
Difference
2. Inside the abstract class we 2. We can’t give any kind of access between Abstract
modifiers to the abstract method
can give any kind of access class and
modifiers to the abstract inside the interface, because by
default it would be public and interface:
method.
3. We can give any kind of access Abstract.
modifiers to the variables inside 3. We can’t give any kind of access
the Abstract class. modifiers to the variables inside the
interface, because by default it
4. In abstract class we can’t would be public, static and final.
achieve multiple inheritance. 4. We can achieve multiple
inheritances by using Interface.
5. If any class is inheriting 5. If any class is inheriting interface
Abstract class by using extends by using implements keywords.
keywords.
6. If any Abstract methods are
6. If any Abstract methods are present in interface no need to make
present in abstract class explicitly it as an abstract access modifiers
we have to give abstract access because by default it would be
modifiers to the abstract abstract.
method. 7. Interface can’t contain
7. Abstract class can contain Constructor.
Constructor but we have to call it 8. Interface can’t have main method.
by using Super statement. 9. Interface can’t inherit Object class.
8. Abstract class can having main 10. We can achieve 100%
method (it works like a normal Abstraction in Interface.
class)
[Link] class inherit Object
class.
10. We can achieve 0 to 100%
Abstraction in abstract class.
Note:
1. Interface contain all the variables are by default final and static because if it is not a final , the
other class can change the implementation. But interface can’t contain any implementation.
2. If it is not a static, it can belong to other classes also, so other class can change the
implementation, so by default it would be static.
3. We can’t declare a variable inside the interface because those variables are by default final.

toString ():
toString() is a method , which is present inside the Object class. If we pass the reference variable
inside the S.O.P, it will invoke toString () method and this toString () method internally call hashcode
() method and hashcode () method returns hashcode to the toString () method. This toString ()
method it will convert hashcode into hexadecimal and it returns the implementation in the following
format: classname @ hashcode.
Ex:
[Link] class Demo {
public static void main(String[] args) {
Demo d = new Demo();
[Link](d);
}
}
Output:
[Link]@15db9742

2. public class Demo extends Object {


public String toString()
{
return "123";
}
public static void main(String[] args) {
Demo d = new Demo();
[Link](d);
}
}
output:123

STRING:
1. String is a non-primitive data type.
2. String is a final class, which is present in java. Lang package.
3. Strings are immutable i.e. once if the content is fix we can’t modify the content of String.
Ex:
1.
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
[Link](s2);
[Link](s1);
}
}
output:
Sushma

2.
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
String s3=[Link](s2);
[Link](s3);
}
}
Output:
SushmaQSP
3.
package [Link];
public class Sample {
public static void main(String[] args) {
String s1= "Sushma";
String s2= "QSP";
s1=[Link](s2);
[Link](s1);
}
}
Output:
SushmaQSP

Inbuilt methods of the String class:


public class string {
public static void main(String[] args) {
String s= " javadeveloper";
String s1="JAVA";
[Link]("Length of string "+[Link]());
[Link]("Uppercase method "+[Link]());
[Link]("Lowercase method "+[Link]());
[Link]("Startswith method "+[Link]("j"));
[Link]("Endswith method "+ [Link]("r"));
[Link]("CharAt "+[Link](2));
[Link]("Index of method "+[Link]('d'));
[Link]("Substring "+[Link](5, 8));
[Link](s);
[Link]([Link]());
}
}
Output:
Length of string 14
Uppercase method JAVADEVELOPER
Lowercase method java
Startswith method false
Endswith method true
CharAt a
Index of method 5
Substring dev
javadeveloper
javadeveloper

There are 2 ways to create a String object:


[Link] literal:
i. If we enclose the string content inside the double quotes i.e. we can call it as a String literal.
ii. In case of String literal if the both the string object contains is same, it will not create a more
object, it will refer to the same memory allocation.
iii. String literal objects are stored in String constant pool.
Ex:
String s1 = “abc”s1  abc  1000
String s2 = “pqr”s2  pqr  2000
String s3 = “abc”s3  abc  1000
String s4 = “pqr”s4  pqr 2000

2. By using new Keyword:


i. In case of new keyword, if both the string object contain is same , it is not referred to the same
memory allocation.
ii. It creates different object and refer to different memory allocation.
iii. New keyword objects are stored in String non constant pool.
Ex:
String s1 = new String(“abc”)s1  abc  5000
String s2 = new String(“pqr”)s2  pqr  6000
String s3 =new String( “abc”)s3  abc  7000

in the above example there are 2 string objects created, but the object will refer to non-constant
pool(new keyword object).
Double equals (==) and equals method:
Double equals is always checking references and equals()method always check contains of the
string.
Ex:
1. public class Equals {
public static void main(String[] args) {
String s1="abc";//1000
String s2="pqr";//2000
String s3 ="abc";//1000
[Link](s1==s2);//false
[Link](s1==s3);//true
[Link]([Link](s2));//false
[Link]([Link](s3));//true
}
}
output:
false
true
false
true

2.
public class Equals {
public static void main(String[] args) {
String s1=new String("abc");//1000
String s2=new String("pqr");//2000
String s3 =new String ("abc");//3000
[Link](s1==s2);//false
[Link](s1==s3);//false
[Link]([Link](s2));//false
[Link]([Link](s3));//true
}
}
output:
false
false
false
true
3.
public class Equals {
public static void main(String[] args) {
String s1=new String("abc");//1000
String s2=new String("pqr");//2000
String s3 =new String ("abc");//1000
String s4="abc";
String s5="pqr";
String s6 ="abc";
[Link](s1==s4);//false
[Link](s1==s6);//false
[Link](s6==s3);//false
[Link](s5==s2);//false
[Link](s2==s4);//false
[Link](s3==s5);//false
[Link]([Link](s4));//true
[Link]([Link](s5));//true
}
}
output:
false
false
false
false
false
false
true
true
Ex: (String to Integer)
public class StringtoInteger {
public static void main(String[] args) {
String s1="10";
String s2="20";
[Link](s1+s2);
int i = [Link](s1);
int j = [Link](s2);
[Link](i+j);
/* String s5="Sushma";
int k =[Link](s5);
[Link](k);*/ //run time error, number format Exception.
}
}
Output:
1020
30

Note:
[Link] the size is known ,then we have to use for loop.
2. Whenever size is unknown, then we have to use for each loop.
Syntax:
for (data type variable: Array/collection)
{
}

Ex:
[Link] class Foreach {
public static void main(String[] args) {
String s= "Welcome to qspider institute";
String []s1=[Link]("\\s");
for(String obj: s1)
{[Link](obj);
}
}
}Output:
Welcome
to
qspider
institute

2. public class Equals {


public static void main(String[] args) {
String s1="abc";
String s2="Abc";
[Link](s1==s2);//false
[Link]([Link](s2));//false
[Link]([Link](s2));//true
[Link]([Link]('a', 'p'));
}
}
output:
false
false
true
pbc

I.Q: Can we create final class Object?


Ans: yes, we can create an object of final class.

Note:
Every string class is overridden toString() method and it returns the implementation as String value.
Ex: (without overriding toString())
1. public class String1 {
public static void main(String[] args) {
Demo d = new Demo();//object
String s = "Sushma";//object
[Link](d);
[Link](s);
}
}
Output:
Demo@15db9742
Sushma
2. (with overriding toString())
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public String toString()
{
return"["+name+"]";
}
public static void main(String[] args) {
String s1="Sushma";
[Link](s1);
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link](e1);
[Link](e2);
}
}
Output:
Sushma
[Raj]
[Raj]
Note:
1. Object class equals() method checks references but if we override equals ()method, it checks
contents.
2. In String class equals method is overridden and that equals method checks contents of the string.
Ex: (without overriding equals() method)
1. public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link](e2));
[Link]([Link](s2));//equals method overridden
}
}
Output:
false
true
Q.(V.V.I) WAP to compare two object values?( (with overriding equals( ) method)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public boolean equals([Link] o)
{
Employee12 e = (Employee12) o ;
return name==[Link];
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link](e2));
[Link]([Link](s2));
}
}
Output:
true
true
Q. WAP to use override hash code method?
 To generate hash code right clickgo to source click on generate hash code.
1.(without overriding hashcode)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
}
Output:
-1807166421
-1807166421
366712642
1829164700
2.(with overriding hashcode)
public class Employee12 {
String name;
Employee12(String n)
{
name= n;
}
public static void main(String[] args) {
String s1="Sushma";
String s2="Sushma";
Employee12 e1= new Employee12("Raj");
Employee12 e2= new Employee12("Raj");
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
[Link]([Link]());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : [Link]());
return result;
}
@Override
public boolean equals([Link] obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != [Link]())
return false;
Employee12 other = (Employee12) obj;
if (name == null) {
if ([Link] != null)
return false;
} else if (![Link]([Link]))
return false;
return true;
}
}
Output:
-1807166421
-1807166421
81946
81946
Q:WAP to reverse a String?
import [Link];
public class String1 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a String");
String s = [Link]();
String rev="";
for(int i= [Link]()-1;i>=0;i--)
{
rev=rev+[Link](i);
}
[Link]("String reverse: "+rev);
}
}

String Buffer and String Builder:


1. String buffer is a class which is present in [Link] package.
2. String builder is a class which is present in [Link] package.
3. String Buffer & String builder are mutable.
4. String Buffer & String builder object are stored in heap area.
Difference between String Buffer & String builder:

String Buffer String builder

1. String buffer is mutable. 1. String builder is mutable.


2. String buffer is Synchronized. 2. String builder is not Synchronized.
3. String buffer is single threaded. 3. String buffer is multi-threaded.
4. String buffer is thread safe. 4. String builder is not thread safe.
5. String buffer is slower. 5. String buffer is faster.

Ex:
package [Link];
public class SBufferBuilder {
public static void main(String[] args) {
StringBuffer s1= new StringBuffer("abc");
StringBuffer s2= new StringBuffer("pqr");
[Link](s2);
[Link](s1);
StringBuilder s3= new StringBuilder("abc");
StringBuilder s4= new StringBuilder("pqr");
[Link](s4);
[Link](s3);
String s5="abc";
String s6= "pqr";
[Link](s6);
[Link](s5);
}
}
Output:
abcpqr
abcpqr
abc

I.Q: Difference between (==), equal () method and compare to () method?


Compare to () method:
1. If both the strings are equal it returns 0.
2. If the first string is greater than second one it returns positive value.
3. If the first string is less than second string it returns negative value.
Ex:
public class Compareto {
public static void main(String[] args) {
String s1="abc";
String s2="pqr";
String s3="abc";
[Link]([Link](s2));
[Link]([Link](s3));
[Link]([Link](s1));
}
}
output:
-15
0
15
Note: Every string class is overridden toString()method.
Ex:
public class Stringobject {
public static void main(String[] args) {
String s=new String("abc");
[Link](s);
}
}
output:
abc
Note: String is Synchronised & it is thread safe & it is single threaded.
Questions:
[Link] is String?
2. Does String are mutable or immutable? If it is mutable explain the concept of immutable?
3. Difference b/w String, String buffer, String Builder?
4. Explain inbuilt methods in String class?
5. How many ways is there to create a string object?
6. Difference b/w double equal, equals () method and compare to () method?
7. Difference b/w hash code and equals () method?
8. Difference b/w String buffer, String Builder?

ARRAY:
Array is a collection of homogeneous data type value.
Advantages: By using a single variable we can represent multiple values.
Drawback:
1. Array always allows homogeneous(same) data type value.
2. Array is of fixed size.
3. There is no utility methods are present in array for every action (e.g.: sort, contain).
4. There is no underlying data structure for Array.
Declaration of Array:
Single Dimensional Array 2 Dimensional Array 3 Dimensional Array
int [] i; int[] [] i; int[][][]i;
int i [] ; int i [] [] ; int i [][][];
int [] i; int[]i [] ; int[][][] i;
char [] c; int[] [] i; int[] []i[];
double [] d; int[] [][]i;
String [] s; int[] i[][];
Note: we can create nth dimensional Array.

Array creation:

int [] i = new int [3];


[]=Dimension.
i =variable.
new = operator.
[3]= size.
Ex:
String[] s = new String[4];
byte[] b = new byte[3];
char [][] c= new char [3][3];
int [][] i =new int[2][2];
int [][][] i =new int[3][3][3];
Note:
1. At a time of Array declaration we shouldn’t specify the size of Array.
Ex: int a [3]; (give compile time error)
2. . At a time of Array creation we should specify the size of Array.
Ex: int [] i =new int []; (give compile time error)
Ex:
1. int [] i =new int []; //false
2. Byte b =10;
int [] i =new int [b]; //true
3. int [] i =new int [‘A’]; // true
4. int [] i =new int [-3]; //false
5. long l = 10;
int [] i =new int [l]; // false
Note:
Array can be created by using new keyword. Every Array object has corresponding classes
i.e. only on programming language level.
Ex:
Class:
Demo d = new Demo(); Demo
int [] i =new int[3]; [I
int [][] i =new int[3][3]; [[I
char [] c =new char [3]; [c
double [D
long [L
Byte [B
Short [S
Float [F
Boolean [Z

Multi-Dimensional Array:
In java programming language multi-dimensional arrays are implemented on Arrays of Arrays
concept.
1.

int [][] =a new int[4][];


a[0]= new int[2];
a[1]= new int[3];
a[2]= new int[1];
a[3]= new int[2];
a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
a[1][2]=50;
a[2][0]=60;
a[3][0]=70;
a[3][1]=80;

2.

int [][] =a new int[3][2];


a[0][0]=10;
a[0][1]=20;
a[1][0]=30;
a[1][1]=40;
a[2][0]=50;
a[2][1]=60;
Ex:
1.
public class Array {
public static void main(String[] args) {
int[] a= new int[4];
[Link](a);//[I@hc
[Link](a[0]);//0
}
}
output:
[I@15db9742
0
[Link] class Array1 {
public static void main(String[] args) {
int[] []a= new int[4][2];
[Link](a);//[[I@hc
[Link](a[0]);//[I@hc
[Link](a[0][0]);//0
}
}
output:
[[I@15db9742
[I@6d06d69c
0
[Link] class Array3 {
public static void main(String[] args) {
int[] []a= new int[4][];
[Link](a);//[[I@hc
[Link](a[0]);//null
[Link](a[0][0]);//Null Pointer Exception
}}
Output:
[[I@15db9742
null
Null Pointer Exception(NPE)
Declaration, creation and Initialisation in single line:
[Link] [] I; Declaration
i= new int[3]; Creation
i[0]=1;
i[1]=2; Initialisation
i[2]=3;
i[3]=4;//Array index out of bound exception.

2. Int [] a= {1, 2, 3];


3. Char [] c={‘a’,’b’,’c’,’d’};
4. Int [][] a= {{1,2,3}{4,5}};

Ex:
public class Array4 {
public static void main(String[] args) {
int []a={1,4,6,8,9};
[Link]([Link]);
[Link]("<-------->");
for(int i=0;i<[Link];i++)
{
[Link](a[i]);
}
}
}
output:
5
<-------->
1
4
6
8
9
[Link] to find out sum of the Array elements?
public class Array5 {
public static void main(String[] args) {
int []a={1,4,6,8,9};
int sum=0;
for(int i=0;i<[Link];i++)
{sum=sum+a[i];
}
[Link]("Sum of array elemts "+ sum);
}
output:
Sum of array elemts 28

Arrays class method:


Ex:
import [Link];
public class Arraysclassmethod {
public static void main(String[] args) {
int []arr={2,3,10,9,4,6};
[Link]([Link](arr));
[Link](arr);
[Link]([Link](arr));
[Link]([Link](arr, 9));
[Link]([Link](arr, 11));//give a negative value
}
}
Output:
[2, 3, 10, 9, 4, 6]
[2, 3, 4, 6, 9, 10]
4
-7
Scanner Class:
1. Scanner is a class which is present in [Link].
2. Scanner is a class which is used to take a input from keyboard.
3. Scanner class method:
nextInt(), nextShort(), nextByte(), nextLong(), nextFloat(), nextDouble() , nextChar(),
nextBoolean().
Ex:
[Link] [Link];
public class Array6 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter a value");
int a =[Link]();
[Link]("Enter b value");
int b =[Link]();
int c = a+b;
[Link]("value of c is "+c);
}
}
Output:
Enter a value
12
Enter b value
13
value of c is 25
2. import [Link];
public class Array7 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter size of Array");
int n =[Link]();
int[] a = new int[n];
[Link]("Enter array elements");
for(int i=0;i<[Link];i++)
{a[i]=[Link]();
}
[Link]("<----------->");
for(int i=0;i<[Link];i++)
{[Link](a[i]);
}
}
}
output:
Enter size of Array
5
Enter array elements
1
2
3
4
5
<----------->
1
2
3
4
5

3.
import [Link];
public class Array8 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter m size");
int m =[Link]();
[Link]("Enter n size");
int n =[Link]();
int[][] a = new int[m][n];
[Link]("Enter array elements");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
a[i][j]=[Link]();
}
}
[Link]("<-------->");
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
[Link](a[i][j]+" ");
}
[Link]();
}
}
}
output:
Enter m size
3
Enter n size
3
Enter array elements
1
21
3
4
5
6
7
8
9
<-------->
1 21 3
456
789

Encapsulation:
1. Encapsulation is a process of binding the data and code into a single component; it ensures that
data and code is safe. It is not freely available outside of the class.
2. Encapsulation can be achieved by declaring the fields as a private, by giving access to this field via
getter and setter.
Ex:
import [Link];
class Employee{
private String name;
private int id;
private int age;
private double sal;
public String getName() {
return name;}
public void setName(String name) {
[Link] = name;}
public int getId() {
return id;}
public void setId(int id) {
[Link] = id;}
public int getAge() {
return age;}
public void setAge(int age) {
[Link] = age;}
public double getSal() {
return sal;}
public void setSal(double sal) {
[Link] = sal;}
}
class DataBase{
void StoreData(Employee e)
{
[Link]("Name is "+[Link]()+"\nEmp Id is "+[Link]()+"\nEmployee age
is "+[Link]() +"\nEmployee salary is "+[Link]());
}
}
public class Encapsulation {
public static void main(String[] args) {
Scanner sc=new Scanner([Link]);
[Link]("Enter name:");
String name = [Link]();
[Link]("Enter Emp Id:");
int id = [Link]();
[Link]("Enter Age:");
int age = [Link]();
[Link]("Enter salary:");
double sal = [Link]();
Employee e = new Employee();
[Link](name);
[Link](id);
[Link](age);
[Link](sal);
DataBase d =new DataBase();
[Link](e);
}
}
output:
Enter name:
abc
Enter Emp Id:
1
Enter Age:
22
Enter salary:
5000
Name is abc
Emp Id is 1
Employee age is 22
Employee salary is 5000.0

Wrapper Class:
Converting from primitive data type to object and object to primitive data type is called wrapper
class.
Primitive (data type) Object (class)
1. byte Byte
2. short Short
3. int Integer
4. long Long
5. float Float
6. double Double
7. char Character
8. boolean Boolean

Wrapper class is of 2 types:


a. Auto boxing:
Converting from primitive to object is called Auto boxing.
Ex:
public class Autoboxing {
public static void main(String[] args) {
int i=10;//primitive value
Integer j = [Link](i);//autoboxing
Integer k=j;
[Link](i+"\n"+j+"\n"+k);
double d=50.0;//primitive value
Double d1 = [Link](d);//autoboxing
Double d2=d1;
[Link](d+"\n"+d1+"\n"+d2);
}
}
Output:
10
10
10
50.0
50.0
50.0
b. Auto unboxing:
Converting from object to primitive is called Auto unboxing.
Ex:
public class Autounboxing {
public static void main(String[] args) {
Integer i=new Integer(10);//object value
int j = [Link]();// primitive, autounboxing
int k=j;
[Link](i+"\n"+j+"\n"+k);
Double d=new Double(90.0);//object value
double d1 = [Link]();//primitive,autounboxing
double d2=d1;
[Link](d+"\n"+d1+"\n"+d2);
}
}
Output:
10
10
10
90.0
90.0
90.0
EXCEPTION HANDLING:
1. Exception is a class which is present in [Link] package.
2. Exception is runtime scenario.
3. All exception occurs at runtime.
4. Exceptions are caused by programmer.
5. Exception can be handled by programmer.
6. Unexpected or unwanted event that disturbs the normal flow of execution is called exception.
7. Exception handling is mainly used to handle exception.
8. Errors are caused due to lack of system resources.
9. Errors can’t be handled by a programmer.
Exception can be categorised into two types:
a. Checked exception: The exception which is checked by compiler at compile time is called checked
exception. It is also called as compile time exception.
b. Unchecked exception: The exception which is not checked by compiler is called unchecked
exception.

Throw able

Exception (root of Error(Stack over flow,


exception is throw Out of memory)
able class)

Checked Exception Unchecked exception

1. Class not found exception. 1. Arithmetic exception.


2. File not found exception. 2. Null pointer exception.
3. Class cast exception. 3. Array index out of bound exception.
4. SQL exception. 4. Number format exception.
5. IO exception.
Unchecked exception scenario:
a. Airthmetic Exception:
int I = 10/0;
[Link](i);
output: Airthmetic exception.
b. Null pointer exception:
String s =null;
[Link]([Link]);
output: Null pointer exception.
c. Array index out of bound exception:
int [] a = new int[3]; a[10]=10;
output: Array index out of bound exception.
d. Number format exception:
String s =”abc”;
int I =[Link](s);
[Link](i);
output: Number format exception.

There are 5 keywords present in exception handling:


[Link]
2. catch.
3. throw.
4. throws.
5. finally.
try catch block:
1. try block should be always followed by either catch block or finally block.
Ex: try
{

}
output: It gives a compile time error, because try block should be followed by either catch or finally.
2. try block can be followed by multiple catch block.
3. The lines of code which may or not may not give an exception have to be enclosed inside try
block.
4. Once if the exception occurs inside the try block, control will immediately come out of try block by
not executing rest of the code.
5. Once if the control comes out of try block, it will search for corresponding catch block.
6. Once if the corresponding catch block found, that catch block is executed and rest of the catch
blocks wouldn’t be executed and after the catch block if any executable statements are present,
then those statements would be executed.
7. If the corresponding catch block is not found then program will get terminated and the
statements after the catch block wouldn’t be executed.
Note: After handling the exception in catch block the control will not go back to try block, so we
always write less codes inside the try block.
Syntax (try & catch block):
try
{
}
catch ()
{

Central flow of try catch block:


try
{Statement1
Statement2
Statement3

}
catch ()
{ Statement4

}
Statement5
Case1: There is no exception statement 1, 2, 3 and 5 will execute.
Case2: If Exception occurs at statement 2 and if there is corresponding catch block then statement 1,
4 and 5 will execute.
Case3: If exception occurs at statement 2 and corresponding catch block is not found then
statement1 followed by abnormal termination.
Note: If any exception occurred which is not a part of try block i.e. always abnormal termination.
Ex:
1. package exceptionHandling;
public class Sample {
public static void main(String[] args) {
int num1=10;
int num2=0;
try
{
int num3=num1/num2;
[Link](num3);
[Link]("Hi");
}
catch (ArithmeticException e
{
[Link]("Arithmatic Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
Output: Arithmatic Exception Handled
I am out of Try n Catch Block
[Link] class Sample1 {
public static void main(String[] args) {
try
{String s = null;
[Link]([Link]());}
catch (ArithmeticException e)
{[Link]("Arithmatic Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:Run Time Error
Exception in thread "main" [Link] at
[Link]([Link])
3. public class Sample3 {
public static void main(String[] args) {
try{
int[] i=new int[4];
i[9]=10;}
catch (ArithmeticException e){
[Link]("Arithmatic Exception Handled");
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Array Index Out Of Bound Handled");
}
catch(Exception e)
{
[Link]("General Exception");}
[Link]("I am out of Try n Catch Block");}
}
Output:
Array Index Out Of Bound Handled
I am out of Try n Catch Block

Note: catch (Exception e) is a general exception, if there is no specific exception for try block then it
will execute general exception.
Ex:
4. public class Sample4 {
public static void main(String[] args) {
try
{
int[] i=new int[4];
i[3]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(Exception e)
{[Link]("General Exception Handled");}
}
catch (NumberFormatException e)
{
[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
General Exception Handled
I am out of Try n Catch Block
5.
package exceptionHandling;
public class Sample5 {
public static void main(String[] args) {
try{
int[] i=new int[4];
i[8]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(Exception e)
{
[Link]("General Exception Handled");
}
}
catch (NumberFormatException e)
{[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
Exception in thread "main" [Link]: 8
at [Link]([Link])
6.
public class Sample6 {
public static void main(String[] args) {
try
{int[] i=new int[4];
i[3]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(NullPointerException e)
{
[Link]("Null Pointer Exception Handled");
}
}
catch (NumberFormatException e)
{[Link]("Number Format Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:
Number Format Exception Handled
I am out of Try n Catch Block
Note:
1. We can have nested try catch block.
2. If the nested try catch block is not handled the exception, it will throw the exception to the main
try block and if the main try block is having any corresponding catch block, then that catch block will
handle the exception.
7. public class Sample7 {
public static void main(String[] args) {
try
{int[] i=new int[4];
i[9]=10;
try{
String s = "Sushma";
int j=[Link](s);
[Link](j);
}catch(ArrayIndexOutOfBoundsException e)
{[Link]("ArrayIndexOutOfBounds Exception Handled");}
}
catch (NumberFormatException e){
[Link]("Number Format Exception Handled");
}
[Link]("I am out of Try n Catch Block");
}
}
output:
Exception in thread "main" [Link]: 9
at [Link]([Link])
Note:
Catch block should be most specific to most general, it shouldn’t be most general to most specific.
Ex:
public class Sample8 {
public static void main(String[] args) {
try{int i=10/0;
[Link](i);}
catch (Exception e){
[Link]("General Exception Handled");
}
catch(ArithmeticException e)
{
[Link]("Arithmetic Exception Handled");}
[Link]("I am out of Try n Catch Block");
}
}
Output:gives compile time error.
Note:
We shouldn’t write executable statement between try catch block.
Ex:
public class Sample9 {
public static void main(String[] args) {
try{int i=10/0;
[Link](i);}
[Link]("Hi");
catch(Exception e)
{[Link]("General Exception Handled");
}
}
}
output: gives compile time error.
Ex:
public class Sample9 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(Exception e)
{
[Link](e);
}
}
}
Output:
[Link]: / by zero
Note:
There are 3 ways to get exception information:
[Link] message()method: It returns only description of the exception.
[Link] () method: It returns description along with the exception name.
[Link] () method: It returns description, exception name & location.
Ex: public class Sample10 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(Exception e)
{//[Link]([Link]());
//[Link]([Link]());
[Link]();
}
}
}
Output:
[Link]: / by zero
at [Link]([Link])
finally:
1. It is a block which is executed for sure, even if you handle the exception.
2. If we want some code to be execute without fail, then we must write that code inside finally block.
3. finally block is mainly used to clean up the resources.
4. It is always recommend to write clean up code inside the finally block.
5. A single try block can have only one finally block.
Ex:
1. public class Sample11 {
public static void main(String[] args) {
try
{
int i=10/0;
[Link](i);
}
catch(NullPointerException e)
{
[Link]("NullPointerException handled");}
finally{
[Link]("I am in finally block");}
[Link]("Hi");}
}
output:
I am in finally block
Runtime error.
2.
public class Sample12{
public static void main(String[] args) {
try{
int i=10/0;
[Link](i);
}
catch(ArithmeticException e)
{[Link]("ArithmeticException handled");}
finally
{[Link]("I am in finally block");
}
[Link]("Hi");
}
}
output:
ArithmeticException handled
I am in finally block
Hi

I.Q: When finally block will not execute?


If we provide [Link](0) in try block.
Ex:
public class Sample12{
public static void main(String[] args) {
try
{ [Link]("Helooo”)
[Link](0);
int i=10/0;
[Link](i);
}
catch(ArithmeticException e)
{
[Link]("ArithmeticException handled");
}
finally
{
[Link]("I am in finally block");
}
[Link]("Hi");
}
}
output:
Helooo
program terminated.
Custom Exception:
The exception which is created by programmer is called custom exception or user define exception.
How to write a custom exception:
Syntax:
class class name extends exception/runtime exception
{
public String toString()
{
return””;}
or
public String getMessage()
{
return””;}
Ex:
[Link] exceptionHandling;
import [Link];
class Mock
{
public String toString()
{
return "Sorry you are not eligible to attend interview";
}
}
class Display
{
void check(int rate)
{
if(rate>5)
{
[Link]("All the best");
}
else
{
Mock m= new Mock();
[Link](m);}
}
}
public class throwexample {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter Mock rating");
int rate= [Link]();
Display d = new Display();
[Link](rate);
}
}
Output:
Enter Mock rating
2
Sorry you are not eligible to attend interview
[Link] [Link];
class Mock1 extends Exception//custom exception class
{
public String toString()
{
return "Sorry you are not eligible to attend interview";
}
}
class Display1
{void check(int rate) throws Mock1{
if(rate>5){
[Link]("All the best");
}
else
{
throw new Mock1();}
}
}
public class throwandthrows {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter Mock rating");
int rate= [Link]();
Display1 d = new Display1();
try {
[Link](rate); }
catch(Mock1 m)
{[Link](m);
}
}
}
output:
Enter Mock rating
1
Sorry you are not eligible to attend interview
or
Enter Mock rating
8
All the best

Method name (arguments) method signature.

3. package exceptionHandling;
import [Link];
class MinAge extends Exception//custom exception class
{
public String toString()
{
return "Sorry your age should be greater than 18";
}
}
class MaxAge extends Exception//custom exception class
{
public String toString()
{
return "Sorry your age should be less than 30";
}
}
class Display2
{
void check(int age) throws MinAge,MaxAge
{
if(age>18&&age<30)
{
[Link]("License issued");
}
else if(age<18)
{
throw new MinAge();
}
else if(age>30){
throw new MaxAge();
}
}
}
public class throwandthrows2 {
public static void main(String[] args) {
Scanner sc= new Scanner([Link]);
[Link]("Enter age");
int age= [Link]();
Display2 d = new Display2();
try
{
[Link](age);
}
catch(MinAge m)
{[Link](m);
}
catch(MaxAge n)
{[Link](n);
}
}
}
Output:
Enter age
14
Sorry your age should be greater than 18

throw and throws:


throw is keyword which is used to create a custom exception object and it is throwing the custom
exception object to the programmer by using throws.
throws doesn’t actually throw the custom exception object to the programmer, just it is indicating to
the programmer there is a possibility of exception, will be getting at the runtime. So, the
programmer responsibility is to handle the exception.

throw throws

1. throw is used to throw an exception 1. throws is used to declare an exception


explicitly. 2. throws keyword which is used with the
2. throw keyword should be used inside method signature.
the method. 3. throws followed by instance.
3. throw followed by instance. 4. By using throws we can declare multiple
4. By using throw we can throw only one exceptions.
exception.

Note:
Checked exception are handle in 2 ways:
[Link]&catch block:
handle the exception in the same method where the exception occur.
[Link]:
throws is used to delicate the exception handling to the caller method so that the caller method
provide handling code.

Difference between Array and Collection:

Array Collection
1. Array allows Homogeneous data type 1. Collection allows Homogeneous data type
values. values.
2. It is of fixed size. 2. It is growable and shrinkable.
3. No utility methods are present. 3. Utility methods are present.
4. No underlying data structure for Array. 4. Every collection classes have underlying data
5. With respect to performance Array is structure.
good. 5. With respect to performance collection is bad.
6. With respect to memory Array is bad. 6. With respect to memory collection is good.

Collection:
1. It is an interface which is present in [Link] package.
2. It is collection of individual object as single entity.
Note: Route of collection is iterable.
Collections:
It is a utility class and all the utility methods are present in collection class.
Methods of collections:
1. Add(object o)
2. addAll(collection c)
[Link](object o)
4. removeAll(collection c)
5. Size
6. Contains (object o)
7. containsAll(collection c)
8. Get (int index)
[Link] ()
10. Iterator ()

There are nine interfaces present in collection and framework:


1. Collection.
2. List (I): List is a Child interface of collection interface. If we want to represent group of individual
object as a single entity where duplicate objects are allowed and insertion order is preserved.

Collection (I)

List (I) v1.2

Array List(c) v1.2 Linked list(c) v1.2 Vector(c) v1.0

Stack(c) v1.0
Note:
Vector and stack are legacy classes (which ever classes introduced in earlier version we call it as
legacy classes).
3. Set (I): It is a child class interface of collection interface. If we want to represent group of objects
as a single entity where duplicate objects is not allowed and insertion order is not preserved then we
should go for Set interface.

Collection (I)

Set (I)

Hash set(c)

Linked Hash set(c)

4. Sorted Set (I): It is a child class interface of collection interface. If we want to represent group of
objects as a single entity where duplicate objects are not allowed but insertion order is preserved.

Collection (I)

Set (I)

Sorted Set (I)

4. Navigable Set (I): It is a child class interface of Sorted set interface. Mainly used for navigation
purpose.

Collection (I)

Set (I)

Sorted Set (I)

Navigable set (I)


5. Queue (I): It is a child class interface of collection interface. If we want to represent group of
individual objects as a single entity where priority is given to processing then we should go for
queue.
Collection (I)

Queue (I)

Priority Queue (C)

Note: collection is mainly used to transfer collection of individual object from one place to another
place.

Note: Whenever we are adding the value to the collection classes there is 2 operations performed
internally
1. Up casting.
2. Autoboxing.
Ex:
import [Link];
public class collection1 {
public static void main(String[] args) {
ArrayList a= new ArrayList();
[Link](5);
[Link]("rashda");
[Link]('a');
[Link](20.0);
[Link](5);
[Link](a);
}
}
output:
[5, rashda, a, 20.0, 5]

Note:
1. Every collection classes is overridden toString() method and it returns the implementation in the
following format: [obj1, obj2, obj3…….]
[Link] we add values to the collection classes every collection class would be treated as object
and there are 2 operations that get performed internally : [Link] b. Up casting.
Ex: import [Link];
public class collection2 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
[Link](4);
[Link]("Sushma");
[Link](2.0);
[Link]('a');
[Link](4);
for(Object obj : a)
{
[Link](obj);
}
}
}
output:
4
Sushma
2.0
a
4

<( open angular trace)


>(close angular trace)
Note:
1. hasNext () is a method ,it returns true if the collection is having one or more elements. It returns
false , if the collection has no element.
[Link]() is a method used to return an object.

Ex:
import [Link];
import [Link];
public class collection3 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
[Link](4);
[Link]("Sushma");
[Link](2.0);
[Link]('a');
[Link](4);
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
Output:
4
Sushma
2.0
a
4

I.Q: How to make collection classes as a homogeneous?


Ans: [Link] using generic object.
2. Non generic object allows both homogeneous and heterogeneous value. But generic object allows
only homogeneous value.
Ex:
1. Non generic object: Arraylist a = new arrayList();
2. Generic object:
ex: import [Link];
public class collection4 {
ArrayList <Integer> a = new ArrayList<Integer>();
[Link](4);
[Link]("Sushma");//compile time error
[Link](2.0);//compile time error
[Link]('a');//compile time error
[Link](4);
}
}
Q. Display collection elements in reverse?
//have to use listliteral method.
import [Link];
import [Link];
public class collection4 {
public static void main(String[] args) {
LinkedList a= new LinkedList();
[Link](4);
[Link](1);
[Link]("abc");
[Link]('a');
[Link](5.0);
ListIterator it =[Link]();
[Link]("<.....Forward direction.....>");
while([Link]())
{[Link]([Link]());
}
[Link]("<.....Backward direction.....>");
while([Link]())
{[Link]([Link]());
}
}
}
output
<.....Forward direction.....>
4
1
abc
a
5.0
<.....Backward direction.....>
5.0
a
abc
1
4

[Link] to display even number and remove add number from collection?
import [Link];
import [Link];
public class collection5 {
public static void main(String[] args) {
ArrayList l= new ArrayList();
[Link](4);
[Link](1);
[Link](5);
[Link](6);
[Link](10);
[Link](l);
Iterator it = [Link]();
while([Link]())
{Integer i=(Integer) [Link]();
if(i%2==0)
{
[Link](i);
}
else
{[Link]();
}
}
[Link](l);
}
}
output:
[4, 1, 5, 6, 10]
4
6
10
[4, 6, 10]
[Link] to delete abc, add spider when qspider , replace jspider with sushma?
package collection;
import [Link];
import [Link];
public class Collection6{
public static void main(String[] args) {
LinkedList l = new LinkedList();
[Link]("abc");//remove
[Link]("qspider");//add spider
[Link]("jspider");//sushma
[Link]("pqr");
[Link]("xyz");
[Link](l);
ListIterator it = [Link]();
while([Link]())
{String s= (String)[Link]();
if([Link]("abc"))
{
[Link]();
}
else if([Link]("qspider"))
{[Link]("spider");
}
else if([Link]("jspider"))
{
[Link]("Sushma");
}
}
[Link](l);
}
}
output
[abc, qspider, jspider, pqr, xyz]
[qspider, spider, Sushma, pqr, xyz]
Q.
import [Link];
import [Link];
public class collection7 {
public static void main(String[] args) {
Vector v = new Vector();
[Link](2);
[Link]("abc");
[Link]('a');
[Link](5.0);
[Link](2);
Enumeration e= [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
2
abc
a
5.0
2

Types of Cursor:
[Link]:
a. It was introduced in 1.o version.
b. It is applicable only for legacy classes and it is not applicable for Array list, linked list and set
interface classes. Hence it is not universal cursor. It is a single directional cursor i.e. we can display
the object only in forward direction. By using Enumeration cursor we can perform only read
operation.
2. Iterator:
a. It is a universal cursor i.e. it is applicable for all kind of list interface classes and set interface
classes.
b. It is a single directional cursor i.e. we can display the elements only in forward direction. By using
iterator we can perform only read and remove operation (we can’t perform addition and
replacement).
3. List iterator:
a. It is a bidirectional cursor i.e. we can display the elements in both forward & backward direction.
b. It is not a universal cursor i.e. it is applicable only for all kind of list interface classes and it is not
applicable for set interface classes.
c. By using List iterator we can perform read, remove, add and replacement operation.

Array List:
[Link] dynamic array to store the elements.
2. In Array list bit shifting is required, if any elements are removed from the Array or if any elements
added to the array all the bits are shifted to the memory, so manipulation is slow.
3. All the methods of Array list are not synchronized and not a thread safe and it is multithreaded. 4.
Once if the array list object is created the initial capacity of Array list is 10, once if it exceeds it uses
one formula to create the memory allocation i.e.
new capacity = old capacity *3/2+1
4. The underlying data structure is dynamic Array.
5. Duplicate objects are allowed, Insertion order is preserved, heterogeneous values are allowed.
6. It is an index based collection, Array list is best choice if our frequent operation is retrievable.
Array list implements random access interface, this random access interface helps us to retrieve the
object faster.
Linked list:
[Link] doubly linked list to store the elements.
2. In linked list bit shifting is not required, so manipulation is fast.
3. The underlying data structure is doubly linked list.
4. Duplicate objects are allowed, Insertion order is preserved, heterogeneous values are allowed.
5. It is a best choice if our frequent operation is addition or deletion. It is a worst choice if our
frequent operation is retrievable (compare to array list).
Vector:
[Link] dynamic array to store the elements.
2. All the methods of vector are synchronized and it is a single threaded and it is a thread safe.
3. It is internally uses dynamic Array to store the elements.
4. Duplicate objects are not allowed, Insertion order is preserved, heterogeneous values are allowed.
5. It is a best choice if our frequent operation is retrievable. Every methods of vector are
synchronised.
Note:
1. Array list and vector are best choice if our frequent operation is retrievable. (Retrievable means in
between storing and displaying we don’t required any addition and deletion).
2. Array list and vector are worst choice if our frequent operation is addition or deletion.
3. Linked list is a best choice if our frequent operation is addition or deletion.
Hash Set:
1. Hash set is a child interface of set interface.
2. The underlying data structure is hash table.
3. Duplicate objects are not allowed, Insertion order is not preserved, heterogeneous objects are
allowed.
Ex:
import [Link];
import [Link];
public class hasset {
public static void main(String[] args) {
HashSet h = new HashSet();
[Link](7);
[Link](1);
[Link](9);
[Link]("sushma");
[Link](7);
[Link](h);
[Link]("<....for each loop......>");
for(Object o:h)
{
[Link](o);
}
[Link]("<.......Iterator cursor........>");
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
[1, 7, sushma, 9]
<....for each loop......>
1
7
sushma
9
<.......Iterator cursor........>
1
7
sushma
9
Linked Hash Set:
[Link] Hash set is a child class of hash set.
2. Duplicate objects are not allowed, Insertion order is preserved, heterogeneous objects are
allowed.
Ex:
import [Link];
import [Link];
public class linkedhashset {
public static void main(String[] args) {
LinkedHashSet h = new LinkedHashSet();
[Link](7);
[Link](1);
[Link](9);
[Link]("sushma");
[Link](7);
Iterator it = [Link]();
while([Link]())
{[Link]([Link]());
}
}
}
output:
7
1
9
sushma
Tree Set:
Duplicate objects are not allowed, Insertion order is preserved, heterogeneous objects are not
allowed, if we are trying to add heterogeneous object we will get class cast exception(because
objects are inserted /display in ascending order).Insertion order is not preserved because object will
be inserted according to ascending order.
Ex:
import [Link];
import [Link];
public class treeset {
public static void main(String[] args) {
TreeSet t = new TreeSet();
[Link](7);
[Link](1);
[Link](9);
//[Link]("sushma"); gives compile time error,class cast exception
[Link](4);
[Link](10);
[Link](4);
Iterator it = [Link]();
while([Link]())
{
[Link]([Link]());
}
}
}
output:
1
4
7
9
10

Note: the number one searching mechanism is hashing mechanism (hash set or linked hash set)
I.Q: Why hash set and linked hash set or set don’t allow duplicate values?
Ans: Because hash set and linked hash set uses hash table to store the value where duplicate object
not allowed to store .when we create duplicate object , it get stored in same hash bucket in hash
table.
Ex:
public class collection8 {
public static void main(String[] args) {
collection8 d= new collection8();
[Link](d);//classname@hashcode,in hexadecimal.
[Link]([Link]());//hashcode, in decimal
}
}
output:
collection.collection8@15db9742
366712642
Map:
Map is an interface which is present in [Link] package. If we want to represent collection of
individual object as a key value pair then we should go for map interface.
Syntax: Map<key, value>
Key is an object, value is an object, duplicate keys are not allowed, and duplicate values are
allowed.
1. Hash Map:
The underlying data structure is Hash table. Duplicate keys are not allowed. However, duplicate
values are allowed, insertion order is not preserved i.e. we can’t maintain the order.
Ex:
import [Link];
import [Link];
public class hashmap {
public static void main(String[] args) {
HashMap<Integer,String> h= new HashMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
1 Mike
2 john
5 Sam
10 Adam

2. Linked Hash Map: The underlying data structure is Hash table. Duplicate keys are not allowed,
duplicate values are allowed, and insertion order is preserved.
Ex:
import [Link];
import [Link];
public class linkedhashmap {
public static void main(String[] args) {
LinkedHashMap<Integer,String> h= new LinkedHashMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
2 john
1 Mike
10 Adam
5 Sam

3. Tree Map:
Duplicate keys are not allowed, duplicate values are allowed, insertion order is not preserved all the
elements are sorted according to ascending order.
Ex:
import [Link];
import [Link];
public class treemap {
public static void main(String[] args) {
TreeMap<Integer,String> h= new TreeMap<Integer,String>();
[Link](2, "john");
[Link](1, "Mike");
[Link](10, "Adam");
[Link](5, "Sam");
[Link](1, "pqr");
[Link](7, "abc");
for([Link] obj: [Link]())
{
[Link]([Link]()+"\t\t"+[Link]());
}
}
}
output:
1 pqr
2 john
5 Sam
7 abc
10 Adam
Note:
[Link] () method:
It is a method used to add object to the map interface.
2. Enter Set ():
It is a method used to iterate the object from map interface.
3. Map is an interface; Entry is a sub interface of Map interface.
4. getkey () and get value () methods are available inside [Link].
5. getkey () is a method which is used to get all the keys.
6. getvalue() is a method used to get all the values.
File Handling:
Q. WAP to create a text file?
import [Link];
import [Link];
public class createtextfile
{
public static void main(String[] args)throws IOException
{
File f = new File("[Link]");
[Link]([Link]());
try
{
[Link]();
}
catch(IOException e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.

[Link] to check what is the output if we are not providing a name while creating the file?
import [Link];
import [Link];
public class createtextfile2
{
public static void main(String[] args)throws IOException
{
File f = new File(" ");
[Link]([Link]());
try
{
[Link]();
}
catch(IOException e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
false
Handled
false
Note: mkdir() is a folder used to create a folder.
Ex:
import [Link];
import [Link];
public class createfolder {
public static void main(String[] args) throws IOException
{
File f = new File("Rashda");
[Link]([Link]());
try
{
[Link]();
}
catch(Exception e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.
Note:
1. FileWriter is a class which is present in [Link] package.
2. Flush() is a method used to cleanup all the resources.
[Link] tocreate a folder or file anywhere in the document?
import [Link];
import [Link];
public class createdir {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\FileRashda1\\[Link]");
[Link]([Link]());
try
{
[Link]();
}
catch(Exception e)
{
[Link]("Handled");
}
[Link]([Link]());
}
}
output:
For the first time execution false & true, and second time execution output is true & true.
Q5. WAP to store the data to the text file?
import [Link];
import [Link];
public class storetextinfile {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]");
[Link]("Qspider is a institute");
[Link]();
[Link]("execute");
}
}
output:execute
Q6. WAP to append data?
import [Link];
import [Link];
public class appenddata {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]",true);
[Link]("jspider is a institute");
[Link]();
[Link]("execute");
}
}
output: execute
Note:
In fileWriter it store all the data character by character another drawback is it doesn’t support line
separator.
BufferdWriter:
It is a class which is present in [Link] package. It can’t communicate directly with any text file; it has
to communicate via FileWriter.
In BufferedWriter, it will store the data line by line.
If we want to overcome the drawbacks associated with FileWriter then we have to go for
Bufferedwriter.
Ex:
import [Link];
import [Link];
import [Link];
public class appenddatainnextline {
public static void main(String[] args) throws IOException
{
FileWriter f = new FileWriter("D:\\FileRashda1\\[Link]",true);
BufferedWriter b=new BufferedWriter(f);
[Link]("Qspider");
[Link]();
[Link]("jspider");
[Link]();
[Link]("spider");
[Link]();
[Link]();
[Link]("execute");
}
}
output:execute
Note:
1. FileReader is a class which is present in [Link] package.
2. Read () is a method used to read data character by character. Once if it is reaches end of the file
i.e. equal to -1.
3. Read() method return type is int.
Ex:
[Link] to read the data from the text file?
import [Link];
import [Link];
public class readdata {
public static void main(String[] args) throws IOException
{
FileReader f = new FileReader("D:\\FileRashda1\\[Link]");
int i;
while((i=[Link]())!=-1)
{[Link]((char)i);
}
}
}
output:
Qspider
jspider
spider
Note:
[Link] is a class present in [Link] package.
2. ReadLine () is a method that reads all the data line by line.
3. In BufferedReader once it reaches to the end of the line i.e. equal to null.
Ex:
import [Link];
import [Link];
import [Link];
public class readdatafromtextfile {
public static void main(String[] args) throws IOException
{
FileReader f = new FileReader("D:\\FileRashda1\\[Link]");
BufferedReader b= new BufferedReader(f);
String s;
while((s=[Link]())!=null)
{[Link](s);
}
}
}
output:
Qspider
jspider
spider
[Link] to list all the files? which is present in the given folder?
package filehandling;
import [Link];
import [Link];
public class listfiles {
public static void main(String[] args) throws IOException
{
File f = new File("D:\\FileRashda1 ");
File [] f1=[Link]();
for(File obj:f1)
{[Link](obj);
}
}
}
output:
D:\FileRashda1 \[Link]
D:\FileRashda1 \[Link]
D:\FileRashda1
[Link] take input from user using inuputstreamreader?
package filehandling;
import [Link];
import [Link];
import [Link];
public class bufferreader {
public static void main(String[] args) throws IOException
{
InputStreamReader i= new InputStreamReader([Link]);
BufferedReader b = new BufferedReader(i);
[Link]("Enter name");
String s= [Link]();
[Link](s);
}
}
output:
Enter name
rashda
rashda
Q. WAP to read the second line from the given file?
package filehandling;
import [Link];
import [Link];
import [Link];
public class secondlinefromfile {
public static void main(String[] args) throws IOException
{
String f=[Link]([Link]("D:\\FileRashda1\\[Link]")).get(1);
[Link](f);
}
}
output:
jspider

[Link] to count how many words are present in the given file?
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class countwordsinfile {
public static void main(String[] args) throws IOException
{File f = new File("[Link]");
[Link]();
if ([Link]())
{
[Link]("Total Words=" + getWordCount(f));
} else
{
[Link]("File does not exists!");
}
}
private static int getWordCount(File f) {
int words = 0;
try {
FileReader T = new FileReader(f);
BufferedReader br = new BufferedReader(T);
String line = [Link]();
while (line != null) {
String[] words1 = [Link](" ");
for (String w : words1) {
words++;
}
line = [Link]();
}
} catch (IOException e) {
[Link]("Handled"+e);}
return words;}
}

Multitasking:
Executing several task simultaneously is called multitasking. Multitasking is divided into 2 types:
[Link] or process based multitasking:
Executing several task simultaneously, where each task is having an independent process i.e. we can
call it as a multiprocessing.
2. Multithreading or Thread based multitasking:
Executing several tasks simultaneously, where each task is having an independent part of the same
program is called multithreading.
Thread:
[Link] is a class , which is present in [Link] package.
2. Thread has a separate path of execution.
3. Threads are independent i.e. if any exception occurs to the one thread it doesn’t affect to the
other thread.
4. Threads shares common memory.
Thread Life cycle:
Thread life cycle consist of 5 states:
[Link] or new state:
The thread is in a new state, once we create the object of thread class.
2. Runnable state:
Once we start the execution of thread, thread moves from new to runnable state.
3. Running state:
Once the threads are selected by thread scheduler, that thread is moving from runnable to running
state.
4. Dead state:
Once the run method invocation complete threads are move from running to dead state and the
threads get destroyed.
5. Block state:
In this state threads are still alive but not eligible to run.
Thread Scheduler:
It is just a part of JVM. There is no guarantee which thread would get selected by thread scheduler.
Methods of thread class:
1. Start() method: It is used to start the execution of thread.
2. Run () method: it is used to perform some action of the thread.
3. Sleep () method: it causes the currently executing thread to sleep for the specified number of
millisecond.
4. Wait () method: it makes the thread to wait in waiting state.
5. Notify () method: It wakes up only one thread, present in waiting state.
6. Notify All () method: It wakes up all the threads, present in waiting state.
7. getpriority () method: It returns priority of a thread.
8. setpriority() method: It changes the priority of thread.
9. getname() method: It returns name of a thread.
10. setname() method: It changes name of the thread.
Ex:
[Link] thread class:
public class extendingthreadclass extends Thread
{
public void run()
{
for(int i=0;i<=5;i++)
{
[Link](i);
}
}
public static void main(String[] args) {
extendingthreadclass d= new extendingthreadclass();//thread object
[Link]();
}
}
output:
0
1
2
3
4
5
[Link] runnable interface:
package thread;
public class implementingrunnableinterface implements Runnable {
public void run()
{
for(int i=0;i<=5;i++)
{
[Link](i);
}
}
public static void main(String[] args) {
implementingrunnableinterface d= new implementingrunnableinterface();//thread object
Thread t= new Thread(d);
[Link]();
}
}
output:
0
1
2
3
4
5
EX: sleep method:
public class sleep {
public static void main(String[] args)throws InterruptedException
{Thread t = new Thread();
[Link]("Hi");
[Link](3000);
[Link]("heloo");
[Link](3000);
[Link]("Bye");
[Link](3000);
[Link]("Qspider");
}
}
output:
Hi
heloo
Bye
Qspider
EX: (Multithreading)
class Display
{ void print(int n)
{
for(int i=1;i<=5;i++)
{
[Link](n*i);
try
{
[Link](3000);}
catch(InterruptedException e)
{
[Link]("Handled");
}
}
}
}
class MyThread1 extends Thread{
Display d;
MyThread1(Display d)
{this.d=d;}
public void run()
{
[Link](5);
}
}
class MyThread2 extends Thread
{
Display d;
MyThread2(Display d)
{this.d=d;}
public void run()
{
[Link](10);
}
}
public class Multithreading {
public static void main(String[] args) throws InterruptedException
{Display d= new Display();
MyThread1 m = new MyThread1(d);//Thread class object
MyThread2 n=new MyThread2(d);
[Link]();
[Link]();
}
}
output:
5
10
10
20
15
30
20
40
25
50
Note:
[Link] a user define class extended thread class then the object of user defined class is of thread
class object.
2. In the above program if you make the display class print method as a synchronized i.e. we can
make it single threaded and output is as:
output:
5
10
15
20
25
10
20
30
40
50
Synchronization:
[Link] java it is capability to control the access of multithread to any shared resource.
2. Java Synchronization is better option if we want to allow only one thread to access the shared
resource.
3. It is mainly used to prevent the consistency problem.
4. If we make any method as synchronised, we can call it as synchronised method.
5. Synchronization is built around an internal entity known as lock.
6. Every object has a lock associated with it.
7. Synchronised method is used to lock an object for any shared resource.
8. When a thread invokes a synchronised method it automatically acquires lock for that object and
releases it when the thread completes its task.
Q. WAP to sort in ascending order?
package thread;
import [Link];
import [Link];
class Movie implements Comparable<Movie>
{
String name;
double rating;
int year;
Movie(String n, double r, int y)
{name=n;
rating= r;
year= y;
}
public int compareTo(Movie m)
{
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;}
}
public class sortobjects {
public static void main(String[] args)
{Movie m1= new Movie("Ricky",9.0,2016);
Movie m2= new Movie("Fastandfurious",10.0,2017);
Movie m3= new Movie("Bahubali",8.0,2015);
ArrayList<Movie> a = new ArrayList<Movie>();
[Link](m1);
[Link](m2);
[Link](m3);
[Link](a);
for(Movie obj :a)
{[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
}
}
output:
Bahubali 8.0 2015
Ricky 9.0 2016
Fastandfurious 10.0 2017
Difference between Comparable and comparator:

Comparable Comparator

1. Comparable provides single sorting 1. Comparator provides multiple sorting


sequence, in other words, we can sort the sequence, in other words, we can sort the
collection on the basis of single element collection on the basis of multiple element such
such as name or rating or year. as name, rating or year.
2. It affects the original class i.e. actual 2. It doesn’t affect the original class i.e. actual
class is modified. class is not modified.
3. Comparable provides compare to () 3. Comparator provides compare () method to
method to sort the elements. sort the elements.
4. Comparable is an interface present in 4. Comparator is an interface present in [Link]
[Link] package. package.
5. In Comparable we can sort the list 5. We can sort the list elements of comparator
elements of the comparable type by using type by using [Link] () method and
[Link] () method and passing list passing list, comparator object as argument.
as argument. ex: [Link](list, comparator object)
ex: [Link](list)

Note:
1. Compare method() ,compares the first object with 2nd object.
2. Compareto () method is used to compare the current object with the specified object.
3. Compareto () method is used mergesort () method to sort the element.

Ex: (comparator)
import [Link];
import [Link];
import [Link];
class Movie1
{
String name;
int year;
double rating;
Movie1(String n, int y, double r)
{
name= n;
year= y;
rating =r;
}
}
class Yearcomparator implements Comparator<Movie1>
{
public int compare(Movie1 m1, Movie1 m2) {
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;
}
}
class Ratingcomparator implements Comparator<Movie1>
{
public int compare(Movie1 m1, Movie1 m2) {
if([Link]>[Link])
return 1;
else if([Link]<[Link])
return -1;
else
return 0;
}
}
public class comparator
{
public static void main(String[] args) {
Movie1 m1= new Movie1("Ricky", 2015,10.0);
Movie1 m2= new Movie1("Bahubali", 2017,8.0);
Movie1 m3= new Movie1("fastandFurious", 2016,9.0);
ArrayList<Movie1> a= new ArrayList <Movie1>();
[Link](m1);
[Link](m2);
[Link](m3);
[Link]("Sorting based on year");
[Link](a, new Yearcomparator());
for(Movie1 obj : a)
{
[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
[Link]("Sorting based on rating");
[Link](a, new Ratingcomparator());
for(Movie1 obj : a)
{
[Link]([Link]+"\t\t"+[Link]+"\t\t"+[Link]);
}
}
}
output:
Sorting based on year
Ricky 10.0 2015
fastandFurious 9.0 2016
Bahubali 8.0 2017
Sorting based on rating
Bahubali 8.0 2017
fastandFurious 9.0 2016
Ricky 10.0 2015

Object Array:
Object Array allows both homogeneous and as well as heterogeneous value. We can iterate the
object Array element by using for loop or for each loop.
Ex:
[Link] class objectarray {
public static void main(String[] args) {
Object [] o= new Object[5];
o[0]=1;
o[1]=2.0;
o[2]='A';
o[3]="Rashda";
o[4]=true;
[Link]("By using for each loop");
for(Object obj : o)
{
[Link](obj);
}
[Link]("By using for loop");
for(int i=0;i<[Link];i++)
{[Link](o[i]);
}
}
}
output:
By using for each loop
1
2.0
A
Rashda
true
By using for loop
1
2.0
A
Rashda

2.
public class Arrayobject
{
public static void main(String[] args) {
Object [] o= new String[5];
o[0]=1;
o[1]=2.0;
o[2]='A';
o[3]="Rashda";
o[4]=true;
[Link]("By using for each loop");
for(Object obj : o)
{
[Link](obj);
}
[Link]("By using for loop");
for(int i=0;i<[Link];i++)
{[Link](o[i]);
Object [] o1= new Integer[5];
o1[0]=1;
o1[1]=2.0;
o1[2]='A';
o1[3]="Rashda";
o1[4]=true;
for(Object obj : o1)
{
[Link](obj);
}
}
}
}
output:
Gives runtime error ArrayStoreException.

I.Q: Difference between Array value of index and Array store exception?
Array Store Exception:
Whenever we are trying to add incompatible data type value , gives runtime error i.e. Array store
exception.

Singleton Class:
Singleton class is mainly used to create a single Object. In Singleton class, we must make the
constructor as private so that an object can’t be created outside of the class. Singleton pattern helps
us to keep only one instance of a class at any time. The purpose of singleton is to control the object
creation by keeping a private constructor.
Ex:
public class Mysingleton {
private static Mysingleton obj;
private Mysingleton()
{
}
static Mysingleton getInstance()
{
if(obj== null)
{
obj= new Mysingleton();
}
return obj;
}
void show()
{
[Link]("Hi");
}
public static void main(String[] args) {
Mysingleton m= [Link]();
[Link]();
}
}
Marker Interface:
[Link] is an interface that doesn’t contain any data . Ex: serialsable.
2. Converting from object to byte code is called serialisation.
3. Converting from bytecode to object is called as deserialization.
4. For serialisation, we need to use objectoutputstream class and have to use writeobj () method.
Ex: class CarRace implements Serialisable
{String Pn =”abc”;
int level=3;
int score = 1000;
Public static void main(String [] args)
{Fileoutputstream f= new Fileoutputstream(“[Link]”);//need to provide full path as D://[Link]
objectoutputstream o = new objectoutputstream(f);
CarRace c = new CarRace();
[Link](c);
[Link]();
}
}
5. For deserialization, we need to use objectinputstream class and have to use readobj () method.
Ex: class CarRace
{ Public static void main(String [] args)
{FileInputstream f= new FileoInputstream(“[Link]”);
objectInputstream obj = new objectinputstream(f);
CarRace c = ( CarRace) [Link]();
[Link](“[Link]”);
[Link](“[Link]”);
[Link](“[Link]”);
[Link]();
}
}
Stack overflow:
If the memory is not available to create a stack frame in the stack memory then we will get stack
overflow error.
Ex:
public class recurssion {
static void m1(){
m1();
[Link]("m1");
}
public static void main(String[] args) {
m1();
}
}
output:
gives runtime error(stack overflow).
[Link] to print 1 to 10 without using for loop?
public class recurssion {
static void m1(int i){
if(i<=10)
{
[Link](i);
i++;
m1(i);
}}
public static void main(String[] args) {
m1(1);
}
}

Finalize:
finalize is a method , which is used to remove the unused object from the memory.
finally is a method.
final is a class.

Inner class:
A class is contain in another class is called inner class. Inner class is mainly used to give the security
to the particular class.
Ex:
class Facebook//outerclass
{
Album a= new Album();
void login()
{[Link]("loginned succesfully");
[Link]();
}
class Album//nested class, inner class
{
void displayimages()
{
[Link]("Displaying images");
}
}
}
public class innerclass {
public static void main(String[] args) {
Facebook f= new Facebook();
[Link]();
}
}
output:
loginned successfully
Displaying images

You might also like