[Go to site: main page, start]

0% found this document useful (0 votes)
8 views127 pages

Java Full Notes

Java is a high-level, object-oriented programming language used for software development and automation scripting. It is platform-independent due to its bytecode, which can be executed on any device with a Java Virtual Machine (JVM). The document also covers Java installation, architecture, tokens, variables, methods, and the differences between static and non-static members.

Uploaded by

deepakdenniz840
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)
8 views127 pages

Java Full Notes

Java is a high-level, object-oriented programming language used for software development and automation scripting. It is platform-independent due to its bytecode, which can be executed on any device with a Java Virtual Machine (JVM). The document also covers Java installation, architecture, tokens, variables, methods, and the differences between static and non-static members.

Uploaded by

deepakdenniz840
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

Java Is a high level programming language which is used to communicate between

a human and machine

Low level – It is hard to understand when compared to High Level.

so we have various programming languages like C ,C++ ,Java ,python, Ruby C#

As a Tester , how will Java be useful to you?

You will be writing Automation scripts in Java, to execute test cases automatically.

Java is an object oriented programming language which is used to develop the


software.

In Java, we create something called an object. Through this object we do certain


procedures to write the code.

We use objects like tools for programming.

Class - In java , class is a container.

What does it contain?

Methods, Variables

How to install java on your machine?

1. Download jdk from Oracle website


2. Create a dummy oracle account for download.

3. Install the downloaded exe file.

4. Set path, copy the path of JDK from your installed folder path of java

And, in System variable section, create new System variable called


JAVA_HOME in variable name and the copied path , paste it in variable value.

5. Cope the bin folder bath from Java installed directory.

6. Paste it in Environment variable , path section - Select path and paste it in


list of path.

7. Confirm by checking in cmd by typing java -version and javac.

Java software requirements :

Editor - Eclipse - where you write the program ,

JDK Java Development kit , execution area like command prompt.

Java Architecture
We will write a program in an editor like editplus, Eclipse

We save the file with an extension .java.

So whenever we write java code, the editor will have 2 components internally :

1. Compiler

2. Interpreter

● Syntax

● Rules

● Translate from .java file to .class

Compiler checks for the following 2 things :


If we violate any syntax or rules we get a compile time error.

We we find any abnormal statements we get Run time error.(Example - arithmetic


exception)

Compiler compiles the code and generates .class file.

This .class file can be run in any machine.

That is why Java is Platform Independent.

.class file is also called as byte code.

Why is java Platform Independent?

Because The byte code can be executed at any device, any platform.

.class file is an intermediate file which is given as input to an interpreter which will
convert the .class file to a binary file.

Binary - Bi means 2, Either True or False, Either 1 or 0.

Interpreter will do the following :

● Read line by line

● Execute the code

● Translate from .class file to binary file- 10101011100000111111


The program will get executed from left to right, top to bottom.

JIT : Just in time - It is responsible to convert from .class file to binary format

JVM : Java Virtual Machine , it is responsible for code execution.

JRE : Java runtime Environment - It is an environmental setup to run the program.

JDK : Java development kit : It is a kit which consists of all the library files and
utilities to develop the java programs.

.
Tokens in Java :

It is a small unit in a Java program.

In Tokens we have :

1. Identifiers

2. Keywords

3. Literals

4. Operators

5. Separators.

1. Identifiers - It is a name given for any java program.

2. Keywords : In java we have predefined keywords.

Rules/syntax - Where Java/Compiler expects to use only these key-words.

If the compiler detects mistakes in the usage of keywords , it will throw

Compiler time error

English - 26 alphabets.

In java we have 50 keywords :

abstract

Continue
Default

Do

Double

Else

Enum

Extends

Final

Finally

Float

For

Goto

Assert

Boolean

Break

Byte

Case

Catch

Char

Class

Const

If

Implements

Import

Instance of

Int
Interface

Long

Native

New

Package

Private

Protected

Public

Return

Short

Static

Strict fp

Super

Switch

Synchronise

This

Throw

Transient

Try

Void

Volatile

while
Literals

There are 4 kinds of literals

[Link] literal

Integer -> 1,2,3,4,88,99,900000

Decimal – 3.22,0.55, 9.6,99.99, 3.142

2. Character Literal -> Character literal is always enclosed in single quote.

‘A’, ’a’, ‘9’,’c’, ‘*’, ‘a’ , ‘v’ , ‘2’, ‘4’

[Link] Literal -> “” Strings are always enclosed in Double quotes.

“Akshay”, “12qwsaf(&*”, “21323” , “i” , “”

Empty String - “”

If you give Double quotes and not write anything in between quotes, then it is called
an Empty String

4. Boolean Literal – TRUE / FALSE.

Operators – they are the symbols which is used to perform an operation on the
operands.

Used to do some function - Mathematical, Concatenation

Different type of operators :

1. Unary Operators :
Postfix

(expression) ++,

(expression) - -

Prefix

++(expression),

-- (expression)

2. Arithmetic operator –

a)Multiplicative - *,/,%

2*2 = 4

4*4 = 16

4/2= 2

10/2=5

9%3 = 0

10%3 = 1

90%7= 6

b) Additive -> +, -

c) shift - >>>,<<, >>>

Shift Operator - Will shift the values in corresponding Binary.

The binary of value of 4 = 100

Left shift 2 times for 4

<<4 = 16

10000
Right shift

4 >> = 5

100

00100

3. Relational operators :

Comparison - < , > ,==, >=, <= ,!=

To find the which variable greater than each other ,less than each other, equal to
each other, not equal to each other

3. Bitwise

Bitwise AND - & - It is a binary operator denoted by the symbol &. It


returns 1 if and only if both bits are 1, else returns 0.

1&1=1

1&0=0

0&1=0

0&0=0

Bitwise OR - ^ - It is a binary operator denoted by the symbol ^


(pronounced as caret).

Logic - It returns 0 if both bits are the same, else returns 1.

1^1= 0

1^0= 1

0^1=1

0^0=0
Bitwise Inclusive OR - |

It is a binary operator denoted by the symbol | (pronounced as a pipe). It


returns 1 if either of the bit is 1, else returns 0.

1|1=1

1|0=1

0|1=1

0|0=0

4. Logical Operator –

Logical AND - &&

Example -

Requirement - I want to check for both the condition, and return true only if both of
them are satisfied.

if(Physics_marks>35 && Chemistry_marks > 35 && Maths_marks > 35){

Passed

} else

Failed

LOGICAL OR - ||

Example -

if(chapati || RIce || Roti || Gobi )

sysout(“Happy”);
6. Assignment operator - = , += , -= , *=, /=,%=, &=,^=, |=, <<=,>>=

A +=10;

A = A +10;

A= -10;

A = A-10;

A+b = C

Separators -

Separators are used to separate the given code.

Braces - {} - Opening and closing Your class, Method, some loop statement.
Conditional Statement.

Brackets – [] - Used to define arrays, and also used to iterate.

Parenthesis – () -Used to enclose Method Definition.

Semicolon - ; Used to end a line of code in Java.

Comma - , is used to separate variables.

System - is a class,

println() - It is a method, which takes string as an argument.

Argument - The variables mentioned in between () are called as arguments.


(40+40)

(“the value is”+20)

(“the value is”+20+20)

(20+”is the value”)

(20+20”is the value”)

(“the value is”+(20+20))

(“the value is”+1/2)

(“the value is”+(1/2))

+ - is used for adding numbers and also for Concatenation.

Variables -

Variable is a named memory location which can store some value , and it can
change n number of times.

Variable are of 2 types :

1. Primitive. - Int, byte , short,long, float, double char, boolean.

Example - 6,10,0.10, 0.09049210493204324343, ‘t’, true,false

We cannot create object of Primitive.

Primitive Data types are not of Class.

Default values of Variables (Only Global) :

Byte - 0
Short - 0

Int - 0

Long - 0

Float - 0.0

Double - 0.0

Char - \u0000

Boolean - false

2. Non Primitive - Reference Variable type/ class type - Array, string or any
class type.

Global variables can be declared inside class outside the method.

Local variables can be declared inside method.

Furtherly they can be classified into 2 types based on type of declaration :

1. Global variable
2. Local variable.

Local Variable :

● Any variable which is declared inside a method is called a Local variable.

● The scope of the local variable is from the beginning of method till end of
the method.

● It will not have any default value.

● Local variables should always be initialised before utilisation.

Initialisation - Giving an initial value to a variable.


Global Variables.

● Any variable which is declared outside the method and inside the class is
called as Global variable.

● The scope of global variable is from the beginning of class till the end of
class.- it can be inside methods also.

● It will have a default value.

● Once Global variable is declared immediately in the next line we dont have
to initialise or reinitialize.

Variable declaration :

Syntax -

Datatype variable_name;

Int number;

Float pi ;

Variable Initialization :

Syntax -

Variable_name = value;

Example -

Number = 10;

Pi = 3.142;

Variable Utilisation :

[Link](pi)

Variable Initialization and declaration in a single line :


Int number =10 ;

Variable Re initialization

Int y = 15;

y= 20;

[Link](y)

Copying the value of one variable to another variable.

Int c = 30;

Int d;

d= c;

Default values of Variables (Only Global) :

Byte - 0

Short - 0

Int - 0

Long - 0

Float - 0.0

Double - 0.0

Char - \u0000

Boolean - false
Note :

the default value of char in java is \u0000 which denotes null character and this is
why blank is printed as default value.

If you assign '\u0000' to any char variable then also you will find the same output as
shown above.

Assignment -

2) Write a program to use variables in print statement - Bank account information -

Account number , account name , Bank name , IFSC code, Branch name, Available
balance , Gender - M/F.

3) Write program to store the details of a student, - studentname, student_gender,


student_rollno, dob, marks, total_marks , classname, section_name,
owner_of_school, school_name, cityn_ame, parent_mobile_no

3) Write a program to multiply 3 numbers using multiply methods

4) Write a program to divide 2 numbers using divide method.

5) Write a program to print the remainder of numbers using the remainder method.

remainder=a%b

6) Write program to multip;y 2 numbers using method with parameter.

7) Write program to multiply 2 numbers using method with return type.

Method : is like a function which will perform an operation/activity – Logic.

Methods are re usable

Access specifier : It can be Public, Private, Protected.


Modifier - can be static or non static

Return type - void , int, double , float , string , boolean

Arguments- whatever is enclosed in the ‘()’

Components of main method :

Access specifier - Public

Modifier - Static

Return type - void

Identifier/Method name = main

Arguments - String[] args

Method : is like a function which will perform an operation/activity – Logic.

Methods are re usable

Access specifier : It can be Public, Private, Protected.

Modifier - can be static or non static

Return type - void , int, double , float , string , boolean

Arguments- whatever is enclosed in the ‘()’

Components of main method :

Access specifier - Public

Modifier - Static

Return type - void


Identifier/Method name = main

Arguments - String[] args

Method with Parameter

Whenever we want to give input for the method from Main method, then we go
for Method with parameter.

In the below program , we are giving values to a and b in main method as


parameters, hence it is called as Method with parameter.

public class add_method_with_parameter {

// Implementing Method with parameter.

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

int result;

result = a+b;

[Link](result);
}

public static void main(String[] args) {

[Link]("Main method starts ");

add(10,15);

[Link]("Main method ends here");

Method with return type.

Things to remember while writing method with return type.

1. Change the Return type of method from void to the datatype of the
returning variable. (Example from void to int in add program)

2. Add a return statement in your method.


3. To collect the returned value, we have to use a variable ( int result =
add(2,3))

Program for method with Return Type :

public class add_with_return_type {

public static int add(int a, int b) {

int result;

result = a+b;

return result;

//the return keyword internally returns the value to the main method
//[Link](result);

public static void main(String[] args) {

[Link]("Main method starts ");

int addition;

addition =add(10,15);

// with the help of result variable , we are able to store the returned

//value from the add method.

[Link](addition);

[Link]("Main method ends here")

Java main() Method – public static void main(String[] args)


In Java programs, the point from where the program starts its execution or
simply the entry point of Java programs is the main() method. Hence, it is one of the
most important methods of Java, and having a proper understanding of it is very important.

Assignment -

1. WP for method with return type as well as method with parameter for
dividing 2 numbers , multiplying and area of circle.( 3 programs)

Static Keyword

Static members of a class can be static variable and static method

Any member declared with the keyword static is called as static member of
the class.

Is Main method a Static member of the class?

Main method is static member of the class.

Properties of static :

1. Static is always associated with class.

2. Static is not associated with Object.

3. Static is always a single copy wrt memory.

4. Static members are stored in the static pool area.


5. Whenever we want to access static members then we use the
syntax

Syntax :

` For methods - [Link]()

For variables - [Link]

6. To access static methods we don’t need to create an object, we can


access them through class, Because static members are always
associated with Class.

Static pool area - is a part of memory , where all the static members
are stored.

Non static :

Any member declared without the keyword static is called a Non-static


member of the class.

Very Important Interview Question

Properties of Non static :

1. Wrt Memory - Non-static has multiple copies in memory.

2. Where is it Stored - Non static members will be stored in Heap


memory.

3. Association - Non-static is always associated with objects.


4. How to access - Whenever we want to access non-static members
, then we have to create an object..

Properties of static :

1. Wrt Memory - Static is always a single copy wrt memory.

2. Where is it Stored - Static members are stored in the static pool


area

a.

3. Association - Static is always associated with class,Static is not


associated with Object.

4. How to access - We access static members by Class name.

Static - Class

Non static - Objects.

Syntax for accessing Non static members :

For variables :

Object.variable_name;

New classname().variable_name();

For methods :
[Link]();

New classname().methodname();

Syntax for Object creation :

new class_name();

What really happens when you create an object?

● Whenever we create an object , a random memory space is allocated to


heap memory.

● And the constructor will initialise the non static members into Heap
memory.

Note :

Single copy : for static

Since we don’t create object for accessing static members, no object is


created that occupies space in memory,hence static members have single
copy.

Multiple copes meaning for Non static - When we want to access non
static members multiple times, we have to create object multiple times.

If we create object multiple times then it will occupy multiple spaces in


memory that’s why non static members have multiple copies.
JVM memory

Heap memory is a memory allocation for non static and objects., used to
store non static members.

Class loader - Whenever we execute a class, then the class loader loads the
class for execution.

Stack - In stack the main program is executed, stack is responsible for


execution..

Stack - is a data structure, in where the elements which are added first can
only be removed last . Stored in First in , Last out format.

Method area - It is used to store method body and definition.

Static pool area : is a memory allocation for Static members, used to store
static members of the class.

Conditional statements:

1. if(Condition)

If the condition is true, then it will enter the if block.

If the condition is false, then it will skip the if block


Real life example -

1) if I study java now, I will get placed.

2) If i eat the food, then food will get digested.

3) If I party, next morning I will get a hangover.

4) If i watch a movie, then I will be entertained.

2. if(Condition)

} else

If the condition is true then if block will be executed,

If the condition is false, then else block will be executed.


Real life example -

if I study Java now, I will get placed. Else Not get job

If i eat the food, then food will get digested else I will stay hungry

If I party, next morning I will wake up late, else I will wake up early.

If i watch a movie, then I will be entertained, else I will get bored

3. if(Condition)

} else

if ( condition )

Else

Syntax :

For static :

[Link];

For non static

[Link]();
if(Condition){

if(Condition){

} else {

} else {

For Loop :

To RE EXECUTE THE STATEMENTS MULTIPLE TIMES.

for (initialization; condition; incrementation/decrementation) {

// Code to be executed that you want to be repeated.

Condition -

If the condition is True then it will enter the loop

If the condition is false , it will exit the loop.

Syntax :

for(Int i = 0; i<n ; i ++){

}
While loop :

Meaning of while -

1) Stay in the class while i go for a quick break.

2) Listen to me , while also I am writing on the blackboard.

3) Don’t drink while you’re driving.

while (condition) {

// Code to be executed as long as the condition is true

Do While loop :

do {

// Code to be executed

while (condition);

Note :

● do-while loop guarantees that the block of code inside the loop will be

executed at least once, and then it checks the condition. The loop will

continue to execute as long as the condition is true


● that the break statement can be used in both while and do-while loops to exit

the loop prematurely if a certain condition is met.

What are Strings in Java?


Strings are the type of objects that can store the character of values and in
Java, Strings are Non Primitive in nature.

String name = "January";

Ways of Creating a String


There are two ways to create a string in Java:

● String Literal

String name = "January";

● Using new Keyword

String s = new String(“Welcome”);

Strings are [Link] cannot change the values of strings.

Programs :

package Day2;
public class Dowhiledemo {
public static void main(String[] args) {
int num=11;

//do while loop makes sure that the do clock gets executed atleast once , irrespective
// whether the condition is true or false.

do {

[Link](num);
num++;

}while(num<=10);
}
}

2.
package Day2;
public class even {
public static void main(String[] args) {
// even numbers from 1 to 10

for(int i=1;i<=10;i++) {

if(i%2==0) {

[Link](i);

}
}

//modulas(%) - will give us the remainder when we divide 2 numbers


// 1st iteration

//1%2 =1

// 2%2=0

//3%2=1

//4%2=0

}
}

3.
package Day2;
public class fordemo {
public static void main(String[] args) {
// requirement is i have to print 1 to 10
// I have to skip 26 value

// i want to exit the loop at 45

int n =50;

for(int i=1;i<=n;i++) {
if(i==26) {

continue; // if we want to skip a value and continue with the next


iteration we use continue
}

if(i>=46) {

break;// It will break from the loop


}

[Link](i);

}
}

4. package Day2;
public class ifelse {
public static void main(String[] args) {
int number=5;

if(number==50) {

[Link]("number is equal to 50");

}else
if(number>50)

[Link]("greater than 50");

else

[Link]("less than 50");


}

}
}
5. package Day2;
public class Method3 {

// Method with return type and method with parameter -


public static void main(String[] args) {
String res=concat("omkar","rahul");

[Link](res);

}
public static String concat(String name1,String name2) {

String result =name1+name2;

return result;

}
}
6.
package Day2;
public class nestedif {
public static void main(String[] args) {

int marks=34;

if(marks>35) {

if(marks>80) { // nested if

[Link]("Distinction");

}
else // nested if ends here

[Link]("Exam passed");

}// outer if ends here


else {

[Link]("failed");
}

}// main method ends


}
7.
package Day2;
public class ReturnType {

static int n=10;

// It is stored in the memory only once.


// Methpd with Return type example

public static void main(String[] args) {

//Whenever we return a variable from a method to main


// we should always catch/store it in a variable.

int res;

res = mod();

[Link](res);
}
public static int mod() {

int a =10;
int b =3;

int result =a%b;

// Method with return type - It should return a variable to the main method

return result;

}
8.
package Day2;
public class subtract {
int a;
public static void main(String[] args) {

char c = 'a';

subtract(10,6); // input from the main method - Method with paramater.

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

int result = a-b;

[Link](result);

9.
package Day2;
public class whiledemo {
public static void main(String[] args) {

// Requirement - 1 to 100
int i=1;

while(i<=100) {

if(i==100) {

break;
}

[Link](i);
i++;

}
}
10.

package stringdemo;
public class StringMethods {
public static void main(String[] args) {

String s1 = "masai";

String s4 ="MASAI";

//String is a class, and Non Primitive,


// and we can create an object of Non Primitive.

String s2 = new String("MoolyaEd");

String s3 ="January February March";

[Link](s1);
[Link](s2);

//Pre Defined Methods in String class

// CharAt Method
[Link]([Link](0));
[Link]([Link](2));
//Concat method
[Link]([Link](s2));

// Contains
[Link]([Link]("Z"));
[Link]([Link]("E"));
// To Uppercase
[Link]([Link]());
[Link]([Link]());

// Trim - removes spaces - start and end of string


[Link]([Link]());

//Starts with
[Link]([Link]("M"));

// Equals
[Link]([Link](s1));

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

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

[Link]([Link]('a', 'b'));
[Link](s1); // Strings are Immutable - Mutation means change

String[] spl = [Link](" ");

for(int i=0;i<[Link];i++) {

[Link]("Individual element"+spl[i]);

String[] spl2 = [Link]("E");

for(int j=0;j<[Link];j++) {

[Link](spl2[j]);

}
}

JVM memory

Heap memory is a memory allocation for non static and objects., used to
store non static members.

Class loader - Whenever we execute a class, then the class loader loads the
class for execution.

Stack - In stack the main program is executed, stack is responsible for


execution..

Stack - is a data structure, in where the elements which are added first can
only be removed last . Stored in First in , Last out format.
Method area - It is used to store method body and definition.

Static pool area : is a memory allocation for Static members, used to store
static members of the class.

Assignment - 1) WAP to calculate the area of parallelogram( area = b*h)

Method with parameter, method with return type and also it should follow with
2 different class with object creation.

2) WAP to calculate the area of square ( area = side*side)

Method with parameter, method with return type and also it should follow with
2 different [Link] object creation.

3) WAP to print even nos from 10 to 1.

4) Wap to print odd nos from 10 to 1.

5) WAP to find factorial of a given number.

Class and Objects.


Class - Class is a container to create methods, variables and objects.

Class is a blueprint for the Data members.

Object - Object is a real time entity which has state and behaviour.

Object is the Instance of the class.

State defines what data it can hold , and behaviour defines the way object
behaves.

State means , different objects can be having different kind of data,input,


information then we say that it is having a different state.

Behaviour - With different implementations, we can make the object behave


differently. Example - Polymorphism.

OOPS - polymorphism is an example of different state and behaviour

Assignment -

Write 5 programs that should contain 2 classes, one with main method, other
with all the methods both static and non static.

Create an object to access all non static members - local methods, global

Access static members - methods, variables.


Nokia nk=new Nokia();

nk - reference variable

new Nokia() - object

what is Nokia nk?

nk is a reference variable of the type Nokia class.

object was created with new Nokia(), and we are storing the object inside a reference
variable which is of the type Nokia class.

nk is a non primitive variable.

Whenever we create an object, it will have both state and a behaviour.

The object address is stored in a variable called Reference Variable..

Creating object and storing it in a reference variable.

Class cherry{

Public void notes(){

sys(“note1”);

sys(“note2”);

sys(“note3”);
}

Class Home{

main(){

cherry reference_var = New Cherry();

rederence_var.notes();

Arrays :

Array is a linear data structure which is used to store homogeneous type of


data.

Homogeneous - same Data type.

Interview Question :
Properties / Disadvantages of Array :

● Size of array is always fixed.

● We can store only homogenous type of data.

1. Array Declaration .

Syntax :

Datatype[] array_name;

Int[] rollno;

String[] names;

2. Array Initialization :

Syntax :

Array_name = new datatype[size] ;

Example -

Rollno = new int[5]


3. Store the Value in arrays.

Syntax :

Array_name[index ] = value;

Rollno[0] = 1;

4. Array Utilisation

[Link](rollno[0]);

[Link](rollno[1]);

5. How to find the length of an array.

Syntax : [Link] ;

[Link]([Link]);

6 .How to print complete array .


for(int i =0 ; i< [Link] ; i++){

[Link](rollno[i])

7 . How to reassign the values to array .

Rollno[4] = 20;

8. Array Declaration and store the values directly.

Syntax :

Datatype array_name[] = {V1, V2, V3};

Example -

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


Assignment -

WAP to declare, initialise and utilise arrays - string , int , char datatypes

- IPL team

- File system - int files , string files , char files.

Programs :

1) Object Demo (2 classes)

package objectdemo2;
public class Car {
public static void main(String[] args) {

//We have to create an object

Tesla tl = new Tesla();

// Accessing Non static members


[Link]();

[Link]();

// access static members

[Link]();

[Link]();

[Link]([Link]);

[Link]([Link]);

[Link]([Link]);

[Link]([Link]);

[Link]([Link]);

}
}

Class 2 :
package objectdemo2;
public class Tesla {

int price = 900000;


String manufacturer = "USA";
String owner = "ELon musk";
char rating = 'A';
boolean safety = true;

public static void autopilot() {

[Link]("Autopilot fetaure");

public static void EvEngine() {

[Link]("Engine is Driven by Electric batteries");

public void Teslasafety() {

[Link]("Safetyfeatures");

public void performance() {

[Link]("Performance is 1000kms per charge");

2. Scanner Demo -

package stringdemo;
import [Link];
public class ScannerDemo {
public static void main(String[] args) {
// Step 1 - Create object of Scanner class

[Link]("Entering student details");

Scanner se = new Scanner([Link]);

String name= [Link]();


double weight=[Link]();
boolean citizenof_earth= [Link]();
int height = [Link]();

[Link](name);
[Link](weight);
[Link](citizenof_earth);
[Link](height);

}
}

3. Switch Case

package stringdemo;
import [Link];
public class SwitchcaseDemo {
public static void main(String[] args) {
// I want to write the logic for Multiple choices
// I will design a calculator

Scanner s = new Scanner([Link]);


[Link]("Enter the operation");

String operation = [Link]();

[Link]("Enter the two numbers");

int a = [Link]();
int b = [Link]();

switch (operation) {
case "add":
[Link](a+b);
break; // we need to break from the switch when we execute a operation.

case "subtract":
[Link](a-b);
break;

case "Multiply":
[Link](a*b);
break;

case "Divide":
[Link](a/b);
break;

default:
[Link]("Invalid value : add only +, - , * , / for operations");
break;

}
}

4. package ObjectsDemo;
public class array1 {
public static void main(String[] args) {
//Integer array

// Declaration of array with fixing the length


int array1[] = new int[6];

array1[0]=123;
array1[1]=234;
array1[2]=435;
array1[3]=88;
array1[4]=123;
array1[5]=909;

[Link](array1[5]);

for(int i=0;i<=[Link]-1;i++) {

[Link](array1[i]);

}
}
}

5. package ObjectsDemo;
public class chararray {
public static void main(String[] args) {
char c[] = new char[5];

char c1[]= {'a','s','h','a'};

/*
* c[0]='r'; c[1]='a'; c[2]='h'; c[3]='u'; c[4]='l';
*/

[Link](c[2]);

for(int j=0;j<[Link];j++) {

[Link](c[j]);
}

}
}

6.

package ObjectsDemo;
public class Masai {

int min_marks = 35;


String coursename="SDET101";

public static void hackathon() {

[Link]("hackathon is defined for Masai students");

public static void zmc() {


[Link]("Zoom marathon challenge");

//non static method


public void scrum() {

[Link]("Scrum is defined for Masai students");

public void evaluation() {

[Link]("Evaluation is defined for Masai students");

7.

package ObjectsDemo;
public class MoolyaEd {
public static void selenium() {

[Link]("Selenium in MoolyaEd curriculum ");

public static void conferences() {

[Link]("Online conference by a Guest speaker");

public static void main(String[] args) {


// I have to access the methods writtin In Masai class
// We have to create an object of Masai class

Masai ms = new Masai();

// using reference variable and . operator we can access methods from Masai

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

[Link]([Link]);

[Link](ms.min_marks);

//To access static methods

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

// Through objects

//[Link]();

//[Link]();

//Accessing static methods withtin the same class


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

MoolyaEd med = new MoolyaEd();


[Link]();

[Link]();

}
}

8.
package ObjectsDemo;
public class StringArrayDemo {
public static void main(String[] args) {
String str[] = {"razi","omkar","rahul","prashanti","rushi","jyotsna"};

[Link](str[2]);

for (int i = 0; i < [Link]; i++) {

[Link](str[i]);

}
}
}
9.

package ObjectsDemo;
import [Link];
public class switchdemo {
public static void main(String[] args) {
Scanner s = new Scanner([Link]);
[Link]("Enter the operation");

String operation = [Link]();

//String operation = "-";

int a =10;
int b =9;

switch (operation) {
case "+":
[Link](a+b);

break;

case "-":
[Link](a-b);
break;

default:
break;
}

}
}

Access Specifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors,
methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.

2. Default: The access level of a default modifier is only the package. It


cannot be accessed from outside the package.

If you do not specify any access level, it will be the default.

3. Protected: The access level of a protected modifier is within the package


and outside the package through child . If you do not make the child class,
it cannot be accessed from outside the package.

Outside the package access - we create a child class and use


extends(Inheritance), then only we can access the protected methods outside
the package.

4. Public: The access level of a public modifier is everywhere. It can be


accessed from within the class, outside the class, within the package and
outside the package.

Constructors :

Constructor is a special method or a member of the class which is used to initialise


the data members.

Data members are nothing but variables.


String s = new String();

Whenever we create an object, every time constructor is invoked.

Rules / Properties of Constructor :

1. Constructor name should always be the same as the class name.

2. Constructor will not have any return type.

3. Constructor will not return any value.

4. Constructor is always Non static.

5. Whenever an object is created , Constructor will get invoked.

Class cherry{

New Cherry();
Here , Cherry(); is a constructor.

In Constructor, we have 2 types :

1. Default Constructor – If we don’t explicitly write any constructor in our


class, and if we just create an object, then the Default Constructor will be
invoked.

2. User defined Constructor. – Whenever we explicitly write a constructor


inside our class, that we can call it as User Defined Constructor

WHenever we create an object, constructor will be invoked.

WHen we create an object, we can also initialise the global variables.

this keyword

WHen do we use this keyword?

We use this keyword while initialising global variables in Constructor , when the
name of the global variable is the same as the variables declared in
Constructor.

This keyword is used when global variable name is same as local variable
name.

This keyword is used to identify global variable.


What will ‘this’ keyword do?

It will point out to the global variables.

This keyword can only be used in a non static body.

Whenever we want to point to global variables and differentiate between global


and local variables then we use this keyword.

Inheritance :

Inheriting the properties from one class to another class is called Inheritance.

● Both non static and static methods can be inherited.

In Inheritance , we have 5 types :

1. Single level Inheritance.

2. Multi level Inheritance.

3. Hierarchical Inheritance.

4. Multiple Inheritance.

5. Hybrid Inheritance.

Syntax for Inheritance :


Child_classname extends Parent_classname

1. Single level Inheritance :

A subclass/Child class inheriting the properties from only one super


class/Parent Class is called Single level Inheritance.

One Parent Class - One Child Class

Super class : The class from which the subclass in inheriting the properties
from is called as Super class

Also called Parent class, Base class.

Subclass : The class where the properties are being inherited is called a
Subclass - Child Class.

Programs :

1) Constructor program

package Day4;
public class Amazon {
// Why constructor? - TO initialise some data members.

// Step 1 - Declare global variables.

String username;
long mobile;
String emailid;

// Can we write 1 method inside another method?

//Step 2 - Define constructor and Initialise Data members with Method with Paramater.

Amazon(String uname,long mob,String email){

username=uname;
mobile=mob;
emailid=email;

public Amazon() {

}
// Step 3 - Create an object - and pass the values from the constructor in the paramater.
public static void main(String[] args) {

Amazon amz = new Amazon("razi123", 908921223, "razi123@[Link]");

Amazon amz2 = new Amazon("rahul", 903243, "rahul@[Link]");

Amazon amz3 = new Amazon();

// Prininting the initialized value from object

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

// Values of Default constructor will print the default values of thier respictice data
types
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

}
}

2. Constructor Program 2
package Day4;
public class Infosys {

// This program demonstrates the usage of this keyword (When global and local variable are
having
//same name)

String CEO_name;
int emp_count;

// local variables are always defined inside the method.


//We declared local and global name are same.
//

public Infosys(String CEO_name,int emp_count){

this.CEO_name= CEO_name;// the compiler is not able to differentiate between


//local and global variables
this.emp_count=emp_count;

public static void main(String[] args) {

Infosys inf= new Infosys("narayan murthy", 20000);


//Infosys i = new Infosys();/// default constructor will be invoked.

[Link](inf.CEO_name);
[Link](inf.emp_count);

}
}

3. Method Overloading Program

package Overload_Day4;
public class Multiplication {
public static void main(String[] args) {

Multiplication ml = new Multiplication();


// Based on the input that we are giving, that particular method gets invoked at
compile time.

[Link]("overloading 1 double and 1 integer"+[Link](6.787878787,6));

[Link]("overloading with 2 integers"+[Link](10,20));

[Link]("overloading with 2 floats"+[Link](0.65f,9.3f));

[Link]("overloading 1 float and 1 integer"+[Link](8.9f,0));

[Link]();

void multiply(){

int a=10;
int b=99;

[Link](a*b);
}

public static int multiply(int a, int b) {

return a*b;

private float multiply(float c,int d) {

return c*d;

double multiply(double e, int f) {

return e*f;

protected float multiply(float g,float h) {

return g*h;
}

4. Inheritance - Parent class

package inheritance;
//this is my parent class
public class Meta {
String CEO="Mark zuckerberg";

int shares = 100000;

long emp_count=10000;

public void algorithm() {

[Link]("Base algorithm of Meta");

}
public void video_team() {

[Link]("Video team of Meta");

Child class

package inheritance;
//this is my child class
public class Instagram extends Meta{
// empty class

}
Main method class :

package inheritance;
public class Test {
// Implementation of Single level Inheritance
public static void main(String[] args) {

// creating object of child class


Instagram ig = new Instagram();

// from ig object ,I will try to access Parent class properties.

[Link]();
ig.video_team();

[Link]([Link]);
[Link](ig.emp_count);
[Link]([Link]);

}
}

Inheritance :

Inheriting the properties from one class to another class is called Inheritance.

● Both non static and static methods can be inherited.

In Inheritance , we have 5 types :

1. Single level Inheritance.


2. Multi level Inheritance.

3. Hierarchical Inheritance.

4. Multiple Inheritance.

5. Hybrid Inheritance.

Syntax for Inheritance :

Child_classname extends Parent_classname

1. Single level Inheritance :


A subclass/Child class inheriting the properties from only one super
class/Parent Class is called Single level Inheritance.

One Parent Class - One Child Class

Super class : The class from which the subclass in inheriting the properties
from is called as Super class

Also called Parent class, Base class.

Subclass : The class where the properties are being inherited is called a
Subclass - Child Class.
2. Multi Level Inheritance :

A subclass(Father class) inheriting the properties from it’s


superclass(Grandfather class) in turn one more sub class(Son class)
inheriting the properties from it’s superclass(Father) is called Multi level
Inheritance.

Multilevel Inheritance happening

Example - Grandfather , Father, Son.

Father extends grandfather.

Son extends father

3. Hierarchical Inheritance
Multiple subclasses inheriting the property from only one super class is called
Hierarchical Inheritance.

4. Multiple Inheritance
A subclass inheriting the property from multiple super class is called Multiple
Inheritance.

In Java, Every class Inherits a class called Object class.

Multiple Inheritance is not possible in Java through classes.

Here, Class A is the Object class


● Multiple inheritance is not possible in Java through classes.

● Object class : Is the Supermost class and it is the topmost class in


Hierarchy.

● Every class in java Inherits Object class.

● Since both parent classes extends Object class which is the supermost
class,

● This will create ambiguity/ confusion to the child class as to which class it
needs to inherit from

● Hence, Multiple Inheritance is not possible in Java through classes.

● This is also called as Diamond problem.

Note : Multiple Inheritance is possible in Java only through Interfaces.

5. Hybrid Inheritance.
It is a combination of two types of Inheritances.

Multilevel Inheritance and Hierarchical Inheritance is called as Hybrid Inheritance

Hint : Hybrid - Multilevel and Hierarchial

Gfather, father , Uncle, Son

Father extends Gfather.

Uncle Extends Gfather

Son extends Father


Implementation class ->

Multi level Inheritance - Create an object of Son and access both father and
grandfather methods.

Hierarchical Inheritance : Create object for uncle and father and access Gfather
methods

Whenever we use Inheritance, in technical terms we say that , there ‘is a


relationship’ between two or more classes.

In Java, we use Inheritance by using the keyword ‘extends’

Assignment for next class :

Prepare for Complete Inheritance and types of Inheritance and present in class.

How to present : PPT / word showing visual representation of Inheritance and


explain.

- Write program for Hierarchical and Hybrid Inheritance

Pass by reference.

Calling Invoking the method by passing a reference of a class is called Pass by


reference.
When do we use?

● We use Pass by reference of a class, when we want to access non static


members of that class.

● And when we don't have to create object multiple times, then we can just
pass the reference and access the data members(Variables and methods)

OOPS – Object Oriented Program System.

Method Overloading :

Developing multiple methods with the same name but variation in the
arguments list is called as Method overloading.

Variation in arguments list means -

● Variation in the data type.

● Variation in the order of [Link] the argument.

● Variation in the length of arguments.

Rules of Method Overloading :

● The method name should be same in all the methods.

● There should be variation in the argument list.

● The method can be static or non-static.


● There is no restriction on access specifiers, modifiers, and return
type.

Assignment - WAP to demonstrate method overloading taking whatsapp


class, develop methods send() arguments - int, string , int and string , string &
int.

2. Assignment - WAP to demonstrate method overloading taking facebook


class, develop methods post()

Method Overriding :

Pre Requisite : Here, Inheritance is involved i.e there should be a relationship


between 2 classes.

Developing a method in the subclass/ child class with the same name and
signature as in the super class/ parent class but with different
implementation in the subclass.

2 classes,

Parent – Public static void run(); à Basic implementation

Child – Public static void run(); -> Advanced Implementation.

This process is called Method Overriding.


Overriding - Modifying the existing .

In java - Replaces the method in parent.

Class Student extends Teacher

Class teacher - java(){

// basics java

Class Student - java(){

// Advanced java concepts

Rules :

1. The method name and signature should be the same as in the super
class.

2. The method should be only non-static.

3. There should always be a ‘is a relationship’/ Inheritance between


classes.

Assignment = write 2 programs for method overriding -


Write overriding for Ios 10 , ios

Write overloading implementation taking math operation math() - add,


subtract., divide , multiply, mod.

Iphone 11, iphone 12.

Objects are also called Instances.

Polymorphism : (Many forms)

An object showing different behavior at different stages of its life cycle is


called Polymorphism.

Many forms of an object is Polymorphism.

Different stages of Life cycle -1) Compile time. 2) Run time.

In polymorphism we have 2 types :

1) Compile time Polymorphism - Method overloading

2) Runtime Polymorphism. - Method overriding.


1) Compile time Polymorphism :

The method declaration getting binded to its definition at the compile


time by the compiler based on the arguments passed is called Compile
time Polymorphism.

● When the method Declaration gets binded to it’s definition at


Compile time, it is called as Early Binding.

● Once the method declaration gets binded to its definition it


cannot be rebinded hence it is called Static Binding.

● Example of Compile time Polymorphism is : Method


Overloading.

Interview :

What is early binding? - Compile time polymorphism.

What is late binding? - Runtime polymorphism.

Method overloading – Creating of objects is not mandatory.

Method overriding – Creating objects is a must.

2. Runtime Polymorphism :
● The Method Declaration getting binded to its definition at the
Run time by the JVM based on the objects created is called
as Run time Polymorphism.

● The method declaration getting binded to its definition at Run


time is called as Late Binding.

● Once the method declaration is binded to its definition it can


be rebinded hence it is called as Dynamic Binding.

● Method Overriding is an example of Run time Polymorphism.

· WHile executing, It will have a look at both the classes - because of Inheritance

· Jvm will implement child class implementation and choose not to implement
parent class method.

· this decision is done by the JVM at the Run time.


· Hence we call this as Run time Polymorphism.

Assignment :

1) Present both Compile time and Run time polymorphism


with the example – > Code.

Programs :

1) Multi level inheritance 👍


package multilevel_inheritance;
// Supermost class (Grandparent)
public class Apple {

int founded_date=1976;
String founder= "Steve jobs";

public void apple1() {

[Link]("Apple 1 architecture");

public static void operating_system() {

[Link]("IOS from apple1");

}
}
package multilevel_inheritance;
//Intermediate class (Parent class)
public class macintosh extends Apple{

public static void laptop() {

[Link]("Portable computers");

public void ipad() {

[Link]("Ipad version 1");


}

}
package multilevel_inheritance;
// Sub class of macintosh
public class VisionPro extends macintosh{
public static void virtualreality() {

[Link]("Launched in 2023");

}
}
package multilevel_inheritance;
public class Test {
// Implementing Multi level Inheritance in this package
public static void main(String[] args) {

VisionPro vp = new VisionPro();

//Accessing Apple class methods and variables.- Grandparent class


vp.apple1();
[Link](vp.founded_date);
[Link]([Link]);

// accessing static members


[Link]("accessing static members from different classes");
[Link]();
[Link]();
VisionPro.operating_system();

// Access parent class from the sons class object

//[Link]();

[Link]();

[Link] Overriding Program.

package multilevel_inheritance;
public class Test {
// Implementing Multi level Inheritance in this package
public static void main(String[] args) {
VisionPro vp = new VisionPro();

//Accessing Apple class methods and variables.- Grandparent class


vp.apple1();
[Link](vp.founded_date);
[Link]([Link]);

// accessing static members


[Link]("accessing static members from different classes");
[Link]();
[Link]();
VisionPro.operating_system();

// Access parent class from the sons class object

//[Link]();

[Link]();

}
package overriding;
public class Windows11 extends Windows{
//The decision of JVM to execute the overridden implementation is happening at the
run
// time , that is why it is called as Run time Polymorphism.

public void paint() {

[Link]("WIndows 11 version of Paint");

public void taskmanager() {

[Link]("WIndows 11 version of task manager");

public static void main(String[] args) {

Windows11 w = new Windows11();

//Using overrided methods.


[Link]();

[Link]();

[Link]();

//WHile executing, It will have a look at both the classes - because of


Inheritance
//Jvm will implement child class implementation and choose not to implement
parent class method.
// this decision is done by the JVM at the Run time.
//Hence we call this as Run time Polymorphism.

Abstraction :

Hiding the complexity of the system and exposing only the required
functionality to the end user is called as Abstraction.

● We declare all the essential properties in the interface/ Abstract


class and we provide all the implementation in the subclass.

● We just write abstract methods which hide the complexity.


Pre Requisites – To understand Abstraction – Methods , Inheritance, Method
Overriding,

Concrete Method , Abstract method, Concrete class, Abstract class.

Concrete Method : Any method which has both declaration and body is
called as Concrete method.

Example :

Public void display(){

Int var1;

[Link](“asdsadasdsavcx”);

Concrete class :

Any class which has concrete methods is called as Concrete class.

It means the class must have methods with the body.

Concrete class must have concrete methods.

Concrete class cannot have abstract methods.

Example :
Class A{

Int rollno;

String name;

Void display(){

[Link](“asdsadasdsavcx”);

Abstract method :

Any method which is declared with the keyword abstract and which doesn’t
have a method body is called as Abstract method.

Example :

Abstract public void display();


Abstract class :

Any class which is declared with the keyword abstract is called as Abstract
class.

Abstract classes might have both abstract methods and concrete methods.

Abstract class Sample{

Abstract void display();

Properties of Abstract class and methods

● An abstract class can have abstract methods and concrete methods.

● If a class consists of abstract methods then compulsorily the class


should be declared as abstract.

● An abstract method cannot be declared as static, final and private.

● If any of the abstract methods is not overridden in the subclass then


the subclass should be declared as Abstract.(Overriding in Multi
Level Inheritance)

● We cannot create an object for abstract class and interface because


it might have abstract methods.

● Through abstract class we can achieve Abstraction and through


interface we can achieve 100 % Abstraction.
Encapsulation : Capsule - tablet

Encapsulation in Java is a process of wrapping code and data together into a


single unit,

for example, a capsule which is mixed of several medicines.

Hiding the data members using Private access specifiers, and giving indirect
access to the user from only getters and setters is called Encapsulation.

Encapsulation is used for Data Hiding and Data Security.

Steps to Achieve Encapsulation :

Step 1 :We can create a fully encapsulated class in Java by making all the data
members of the class private.

Step 2 : Now we can use setter and getter methods to set and get the data in it.

By providing only a setter or getter method, you can make the class read-only or
write-only

It provides you the control over the data

It is a way to achieve data hiding in Java because other class will not be able to
access the data through the private data members.

Company – Infosys

Client – Bank of Australia.


Development team of Bank of Australia. – Infosys, TCS, Cognizant , Bank of
Australia.

//A Java class which is a fully encapsulated class.

//It has a private data member and getter and setter methods.

package [Link];

public class Student{

//private data member

private String name;

//getter method for name

public String getName(){

return name;

//setter method for name

public void setName(String name){

[Link]=name

//A Java class to test the encapsulated class.


class Test{

public static void main(String[] args){

//creating instance of the encapsulated class

Student s=new Student();

//setting value in the name member

[Link]("vijay");

//getting value of the name member

[Link]([Link]());

Wrapper class :

The wrapper class in Java provides the mechanism to convert primitive into object
and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects
and objects into primitives automatically. The automatic conversion of primitive into
an object is known as autoboxing and vice-versa unboxing.

AutoBoxing

UnBoxing.

For every Primitive data type , we have a subsequent wrapper class as shown
above.

Autoboxing
The automatic conversion of primitive data type into its corresponding wrapper
class is known as auto boxing
For example, byte to Byte, char to Character, int to Integer, long to Long, float to
Float, boolean to Boolean, double to Double, and short to Short.

//AutoBoxing example of Int to Integer

// Converting Int to Integer

int i =30;

Integer jobj=i;

//Converting char(primitive ) to Character(It's object type)

char c='k';

Character jkobj=c;

Unboxing

The automatic conversion of wrapper type into its corresponding primitive type is
known as unboxing.

It is the reverse process of autoboxing. Since Java 5, we do not need to use the
intValue() method of wrapper classes to convert the wrapper type into primitives.
//Unboxing example - converting from object type to primitive type

Integer a = new Integer(9);

int num = a;

Methods that are useful in Wrapper classes :

1. toString() Method

We can use the toString() method to convert the Wrapper object or primitive to
String. There are a few forms of the toString() method:
A. public String toString(): Every wrapper class contains the following
toString() method to convert Wrapper Object to String type.

Example :

class Demo {

public static void main(String[] args)

Integer I = new Integer(10);

String s = [Link]();

[Link](s);

String s1 = [Link]('a');

[Link](s1);

String s1 = [Link](11110000, 4);

[Link](s1);
}

Programs :

1. Wrapper programs
package wrapperdemo;
public class CharacterDemo {
public static void main(String[] args) {
char c = 'a';

char c1='0';

boolean status = [Link](c);


boolean digitstatus = [Link](c1);

String s1 = [Link](c1);

[Link](status);

[Link](digitstatus);
}
}

2. Wrapper Demo 2

package wrapperdemo;
public class Demo1 {
public static void main(String[] args) {
int i=50; // primitive data type variable

[Link]("primitive value"+i);
// Autoboxing - is used to convert primitive to Wrapper Class type

Integer wrapper_variable = i;

[Link]("Wrapper variable value"+wrapper_variable);


// The value will be same but the type of the variable is changed.

char c = 'a';

[Link](c);

Character obj2 = c;

[Link](c);

// unboxing- Conversion from Wrapper type to primitive type.

@SuppressWarnings("removal")
Integer i1 = new Integer(100);

[Link]("i1 value of wrapper type is "+i1);

int num = i1;

[Link]("Primitive"+num);

}
}

3. Wrapper Demo 3

package wrapperdemo;
public class Wrappermethods {

// public void display();


public static void main(String[] args) {
String s = "1000";

String s1 = "moolyaEd100";

// parseInt is used whenever we have

float f1 = 4.5f;

//int a1 =(int) f1;


//I have to convert this string into a integer

int num = [Link](s);

[Link](num);

//int num1= [Link](s1);

//[Link](num1);

// Here, if we try to convert s1 to int , we will get NumberFormatException

int number= 909090;

String strvar = [Link](number);

[Link](strvar);

}
}

Encapsulation Program

1.

package encapsulation;
public class BankOfAustralia {

// Confidential data - The data is sensitive and kindly keep all


// the data as private and provide indirect access only.

// Step 1 - declare all the data members as private


private String customername;
private String accountnumber;
private String accountpin;

public String getCustomername() {


return customername;
}
public void setCustomername(String customername) {
[Link] = customername;
}

public String getAccountnumber() {


return accountnumber;
}

public void setAccountnumber(String accountnumber) {


[Link] = accountnumber;
}

public String getAccountpin() {


return accountpin;
}

public void setAccountpin(String accountpin) {


[Link] = accountpin;
}

//Implement getters and setters.

}
2. package encapsulation;
public class Customer {
public static void main(String[] args) {
BankOfAustralia ba = new BankOfAustralia();

[Link]("9021-21432-324234");

[Link]("123435");

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

}
}

Getter setter Demo


package encapsulation;
public class GettersetterDemo {

private String password;

// getter for password

public String getpassword() {

return password;

} // Getter is mainly used to read the data.

// setter method

public void setpassword(String password) {

[Link] = password;

}// Setter is used to Write some data.

public static void main(String[] args) {

GettersetterDemo gs = new GettersetterDemo();

[Link]("09sadlan*(*(*");

[Link]("randompassword");

String password =[Link]();

[Link](password);

}
}

Abstraction program :
[Link] abstraction;
public abstract class Airtel {

//cooncrete method

//If you want to override a method , then we should not use static
public static void call() {

[Link]("calling feature in airtel");

// Abstract methods

public abstract void sms();


public abstract void internet4g();
public abstract void roaming();

}
2.
package abstraction;
public class AirtelMain extends Airtel{

public static void main(String[] args) {

AirtelMain am = new AirtelMain();

[Link]();
am.internet4g();
[Link]();

}
@Override
public void internet4g() {
[Link]("4g service from Airtel Main");

}
@Override
public void roaming() {
[Link]("Roaming service from Airtel Main");
}
@Override
public void sms() {
[Link]("Sms service from Airtel Main");

}
}

Interface

● Interface is a java type to write abstract members.

● Interface is by default abstract.

● Interface has 2 members : 1) variable 2 ) Methods.

● Interface doesn’t support Constructors.

● Variables in interface are by default static and final.- Whatever


variables you define here should be of constant values.

● Methods in Interface are by default public and abstract.

● Interface is by default Abstract.

● The class which provides Implementation for the abstract method is


called Implementation class.(Overriding the abstract methods)

● We cannot create an object for the interface.

● If we want to use Inheritance from an interface to another class then


Java provides a keyword called “Implements”.

● Through Interface we can achieve 100 % Abstraction – All the


methods are abstract and no concrete method.

To understand Interface – Class, Method, Inheritance , Abstraction, Method


Overriding , Abstract methods, classes, access specifers, modifiers , return
type.

Multiple inheritance is Interface is possible.

Interface doesn’t extend Object class(Supermost class). That is why Multiple


inheritance in Interface is Possible.

How? Create 2 interfaces as parent , create a class which is a single child,


use implements and override the parent methods.
Syntax of Interface :

Interface name_of_Interface

Variables;Exception Handling in Java

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

Dictionary Meaning: Exception is an abnormal condition.

Exception Handling is a mechanism to handle runtime issues/ Exceptions.

Exceptions in Java : (Few Examples of Exceptions)

1. IOException.

2. SQLException.

3. ClassNotFound Exception

4. Null pointer Exception

5. Arithmetic Exception.
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is
considered as the unchecked exception

1. Checked Exception
2. Unchecked Exception
Difference between Checked and Unchecked
Exceptions
1) Checked Exception

The exceptions which occur at Compile time are called Checked Exceptions. Also
called as Compile time Exception

The classes that directly inherit the Throwable class except RuntimeException and
Error are known as checked exceptions. For example, IOException, SQLException,
etc. Checked exceptions are checked at compile-time.

2) Unchecked Exception

The exception that will occur at Run time is called an Unchecked Exception.

Also called as Run time Exception

The classes that inherit the RuntimeException are known as unchecked exceptions.

example,ArithmeticException,NullPointerException,
ArrayIndexOutOfBoundsException, etc. Unchecked exceptions are not checked at
compile-time, but they are checked at runtime.

3) Error

Error is irrecoverable. Some examples of errors are OutOfMemoryError,


VirtualMachineError, AssertionError etc.
Java Exception Keywords

Java provides five keywords that are used to handle the exception. The following table describes
each.

Keyword Description

try The "try" keyword is used to specify a block where we should place an exception
code. It means we can't use try block alone. The try block must be followed by
either catch or finally.

catch The "catch" block is used to handle the exception. It must be preceded by try block
which means we can't use catch block alone. It can be followed by finally block
later.

finally The "finally" block is used to execute the necessary code of the program. It is
executed whether an exception is handled or not.

throw The "throw" keyword is used to throw an exception.

throws The "throws" keyword is used to declare exceptions. It specifies that there may
occur an exception in the method. It doesn't throw an exception. It is always used
with method signature.
Difference Between throw and Throws.

Throw Throws

1)Throw is used inside method 1) Throws is used at the Method


Signature

2)Throw is used to throw a particular 2) Throws is used handle Exception


Exception. that may occur in the code.

3)We create object of Exception class in 3) Object is not created in Throws


throw keyword

4) Syntax – throw new 4)Syntax –


ArithmaticException(“Message”)
Public void display() throws
InterruptedException{

Throw keyword is not suggested by the Throws keyword is suggested by IDE.


IDE

Interview Question –

1) Difference between throw and throws.

Syntax of throw keyword :


Main(){

Throw new ArithematicException(“Handled divide by zero case”);

if(age<18) {

//throw Arithmetic exception if not eligible to vote

throw new ArithmeticException("Person is not eligible to vote");

else {

[Link]("Person is eligible to vote!!");

1. int a=50/0;//ArithmeticException

String s=null;

2. [Link]([Link]());//NullPointerException

String s="abc";

3. int i=[Link](s);//NumberFormatException
Assignment - 1) Write 2 programs to demonstrate Encapsulation - Password , Bank
details.

2) Write program to handle exception using try, catch, finally.

Throws Keyword

Java throws keyword


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

● Exceptions can also be handled by using throws keyword.

Throws needs to added to the Method Declaration.

Syntax - method_name() throws Exception_class{

For example -

Public void display() throws NumberFormatException{

// Exception occurs , will be taken care by throws Exception_class declared in the


method Declaration.

Interview Question - What else in Java we can use instead of if else condition
without using if and else?

Answer : We can use try catch block as an if else condition.


If condition is replaced by - Try block

Else Condition is replaced - Catch block.

If else condition cannot be used to handle Exceptions.

Try catch block will only work as If else condition if an exception occurs at try
Block.

2) What all keyword can we use to Handle the Exception?

Answer : try, catch, finally , throws.

3) What keyword can we use to throw an Exception?

Answer – throw.

Programs :

package interfaceprograms;
public interface Government {

public static final String president = "";

void corporatepolicies();
void taxpolicies();
void pensionpolicies();
void corporatepolicies(String s1, String s2);

package interfaceprograms;
public class CityGovernment implements Government{

String citymayor;
int seats;

CityGovernment(String mayor){ // Constructor overloading

citymayor=mayor;

CityGovernment(int seats){

[Link]=seats;
}

@Override
public void corporatepolicies(String s1,String s2) {
// TODO Auto-generated method stub
[Link](s1);
[Link](s2+"Policies");

}
@Override
public void taxpolicies() {
// TODO Auto-generated method stub
[Link]("implementation of tax in city");
}
@Override
public void pensionpolicies() {
// TODO Auto-generated method stub
[Link]("implementation of pension in city");
}
@Override
public void corporatepolicies() {
// TODO Auto-generated method stub
[Link]("implementation of corporate in city");
}

package interfaceprograms;
public class Test {
public static void main(String[] args) {
CityGovernment cg = new CityGovernment("Ravindra Bhosle");
[Link]([Link]);

//[Link];

[Link]();

[Link]("City corporate", "State Corporate");

[Link]();

[Link]();

CityGovernment cg1= new CityGovernment(5);

}
}

2. Exception Handling Programs :

package exceptionhandling;
public class ArithematicExceptionDemo {
public static void main(String[] args) {

try {

[Link](9/0);

catch(ArithmeticException a){

[Link]();

int a =100;
String name="omkar";

[Link]("Omkar marks is "+a+name);

}
}
package exceptionhandling;
public class NullPointerDemo {
public static void main(String[] args) {
try {
String a = null;

[Link]([Link]());

catch(Throwable t) {

[Link]();

//[Link](a);// if we try to access a which is in try block , it will not allow

[Link]("Exception handled");
}
}

package exceptionhandling;
public class NumberFormatDemo {
public static void main(String[] args) {

try {
String s= "Satyam123";

int a=[Link](s);

[Link](a);

// try catch block will not solve your exception , it will only handle the exception
// handling the abrupt stopping of execution.

catch(NumberFormatException n) {

[Link]("exception handled");
[Link]();

finally {

[Link]("finally block code");


int a=10 , b=10;

[Link](a+b);
}

}
}

package exceptionhandling;
public class Throwkeyworddemo {
public static void main(String[] args) {
int age =16;
try {

if(age<18) {

throw new MasaiException("age less than 18, ineligible to vote");

}
else
[Link]("Eligible");

catch(MasaiException e) {

[Link]();
[Link]("Exception handled");

}
finally {
[Link]("after age checking execute this statement");
}

[Link]("after finally");

}
}

Custom Exception class :

package exceptionhandling;
// This is a Custom Exception class
//We are handling exception using this exception class which extends the Exception class
public class MasaiException extends Throwable {
String message;

MasaiException(String message){

[Link]=message;

public void handle() {

[Link]("Exction handled by Masai class"+message);

Disadvantages of Array :

1) The length of array is always fixed.


2) Arrays only store Homogenous type of data.

Collections :

The Collection in Java is a framework that provides an architecture to store and


manipulate the group of objects/elements/data/information.

We can store Heterogeneous data - Integer, String, [Link]

Java Collections can achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion.

What is Collection framework

The Collection framework represents a unified architecture for storing and


manipulating a group of objects. It has:
1. Interfaces and its implementations classes

Implements – is used between an interface(Parent) and a class(Child).

Class implements Interface.

Extends – is used between 2 classes.

Also is used between 2 interfaces


Hierarchy of Collection Framework

Iterable Interface

The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the subclasses of
Collection interface also implement the Iterable interface.
Collection Interface

The Collection interface is the interface which is implemented by all the classes in the
collection framework. It declares the methods that every collection will have

. In other words, we can say that the Collection interface builds the foundation on which the
collection framework depends.

Some of the methods of Collection interface are Boolean add ( Object obj), Boolean addAll
( Collection c), void clear(), etc. which are implemented by all the subclasses of Collection
interface

List Interface

List interface is the child interface of Collection interface. It inhibits a list type data structure
in which we can store the ordered collection of objects. It can have duplicate values.

List -

1) Insertion order is maintained.

2) Duplicate values are allowed.

3 4 3 5 3 10 3

List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.

ArrayList
The ArrayList class implements the List interface.

It uses a dynamic array to store the duplicate element of different data types.

The ArrayList class maintains the insertion order

The elements stored in the ArrayList class can be randomly accessed.

Queue Interface
.

Queue interface maintains the first-in-first-out order. It can be defined as an


ordered list that is used to hold the elements which are about to be processed.
There are various classes like PriorityQueue, Deque, and ArrayDeque which
implements the Queue interface.

9 8 7 6 5 4 3

Real time example –

IRCRTC ticket booking.- at 1.30 pm – 100 people tried to book a ticket in


Janshatabdi express.

Movie ticket – bookmyshow.

Properties :

[Link] we want the objects/ elements to have a First in First out processing.

[Link] order is not maintained


When we want the objects/ elements to have a First in First out processing.

Example - Ticket bookings -

Email sending - 100 people -

Insertion order is not maintained

PriorityQueue

The PriorityQueue class implements the Queue interface. It holds the elements or
objects which are to be processed by their priorities. PriorityQueue doesn't allow
null values to be stored in the queue.

PriorityQueue doesn’t permit null.

If we try to add elements which are not comparable with each other, then it will
throw ClassCastException.

We can add only comparable elements in PriorityQueue.


We can add only Homogenous Mixture in Priority Queue.

Methiods in Priority Queue.

· boolean add(E element): This method inserts the specified element into
this priority queue.

· public peek(): This method retrieves, but does not remove, the head of
this queue, or returns null if this queue is empty.

· public poll(): This method retrieves and removes the head of this queue,
or returns null if this queue is empty.

PriorityQueue<String> queue=new PriorityQueue<String>();

[Link]("Amit Sharma");

Iterator itr=[Link]();

while([Link]()){

[Link]([Link]());

[Link]();

[Link]();
Set Interface
It is unordered collection.

We cannot store Duplicate values.

Set is the only interface out of 3 , where we cannot store duplicate values.

Set Interface in Java is present in [Link] package.

It extends the Collection interface.

It represents the unordered set of elements which doesn't allow us to store the duplicate
items. We can store at most one null value in Set. Set is implemented by HashSet,
LinkedHashSet, and TreeSet.

HashSet

HashSet class implements Set Interface.

It is unordered collection.

We cannot store Duplicate values.

elements in the HashSet. contains unique items


HashSet<String> set=new HashSet<String>();

[Link]("Ravi"); [Link]("Vijay");

Map Interface -

Map is not a child of Collection Interface.

When we need to store the data in the form of Key, Value Pair.

Employee ID(Key) Employee name(Value)

123 Omkar

1234 Rahul

432 Saran

Emp_id - Key , Emp_name - Value.

Keys - Unique , Only max one Null value,

Values - Duplicate values. Multiple Values.

Class - HashMap is a class which implements Map Interface.


Java HashMap
Java HashMap class implements the Map interface which allows us to store key and value
pair, where keys should be unique. If you try to insert the duplicate key, it will replace the
element of the corresponding key. It is easy to perform operations using the key index like
updation, deletion, etc. HashMap class is found in the [Link] package

○ Java HashMap contains values based on the key.

○ Java HashMap contains only unique keys.

○ Java HashMap may have one null key and multiple null values.

○ Java HashMap maintains no order.

You cannot store duplicate keys in HashMap. However, if you try to store duplicate
key with another value, it will replace the value.
HashMap<Integer,String> map=newHashMap<Integer,String>();

[Link](1,"Mango"); //Put elements in Map

[Link](2,"Apple");

[Link](1);

Programs :

package collectionsdemo;
import [Link];
import [Link];
public class ArrayListTest {
public static void main(String[] args) {
// ArrayList Declaration

ArrayList ar = new ArrayList();

// Adding elements inside arraylist.

[Link](1);
[Link]('k');
[Link]("january batch");
[Link](false);
[Link](1.67f);
[Link](90.09302903);
[Link](83242342);

[Link](ar); // print arraylist

[Link]("Length of arraylist is"+[Link]());

[Link]([Link](0)); // u can access a particular element.

[Link](2);

[Link](ar);

ArrayList ar2 = new ArrayList();


[Link](ar);

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

[Link](ar2);

[Link](4);
[Link]("omkar");

[Link](ar);

[Link]("after removing all"+ar2);

[Link]("omkar");

[Link](4);

[Link]();

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

[Link](ar2);

}
}

package collectionsdemo;

import [Link];
import [Link];

public class HashsetDemo {

public static void main(String[] args) {

// Hashset doesnt allow Duplicate values


// Unordered collection.

HashSet hs = new HashSet();

[Link]("jyotsna");
[Link]("rahul");
[Link]("saran");

[Link]("saran");

[Link](null);

[Link](null);

[Link]('M');

[Link](true);

[Link](false);

[Link](hs);

[Link](true);

[Link](hs);

// how to create a homegenous collection

HashSet<Integer> h = new HashSet<Integer>();


HashSet<Character> hc = new HashSet<Character>();
ArrayList<Integer> ar = new ArrayList<Integer>();

[Link]('v');

[Link]('a');

[Link]('l');

[Link]('1');
[Link](null);

[Link](hc);

[Link](1);

[Link](1);

[Link](90);

[Link](45);

[Link](0);

[Link](h);

[Link](h);

[Link](ar);

package collectionsdemo;
import [Link];
public class PQueueDemo {

// Priority Queue will allow duplicates, but will not allow null values
public static void main(String[] args) {
PriorityQueue pq = new PriorityQueue();

[Link](100);
[Link](101);
[Link](200);
[Link](201);
[Link](900);
[Link](pq);

[Link](700);
[Link](800);

[Link](pq);

[Link]();

[Link]("after remove() "+pq);


[Link]([Link]());

[Link]("after poll() "+pq);


[Link]([Link]());

[Link]("after peek"+pq);

[Link](820);
//[Link](7.5);

//[Link]("india");

[Link](pq);

PriorityQueue pq1 = new PriorityQueue();

[Link](10000);
[Link](420);
[Link](820);
[Link](pq);
//[Link](pq1);
// IT compares both the quees and retains only the common element and it removes other
elements

[Link](420);
[Link](820);
//[Link](null);

//[Link]("pq prioritry queue after retain all()"+pq);


[Link](pq1);

}
}

package collectionsdemo;

import [Link];
import [Link];
import [Link];

public class RemoveDuplicate {

// Remove Duplicates from an array list using collections

public static void main(String[] args) {


// TODO Auto-generated method stub

ArrayList ar = new ArrayList();

[Link](1);
[Link](1);
[Link](2);
[Link](2);
[Link](2);
[Link](3);
[Link](3);
[Link](null);
[Link](13);
[Link](4);
[Link](4);
[Link](4);
[Link](5);
[Link](null);

[Link](ar);

ArrayList un = new ArrayList();

for (int i = 0; i < [Link]()-1; i++) {

if([Link](i)!=[Link](i+1)) {

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

[Link]("un collectio is"+un);


HashSet hs = new HashSet();

[Link](ar);

[Link](hs);

package Day7;
import [Link];
import [Link];
public class ToSortCollection {
public static void main(String[] args) {
ArrayList<Integer> a = new ArrayList<Integer>();
[Link](45);
[Link](23);
[Link](53);
[Link](13);
[Link](99);
[Link](69);

[Link](a);

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

You might also like