0% found this document useful (0 votes)
11 views

Java basics

The document provides a comprehensive guide on automation testing using Java, covering essential programming concepts, data types, methods, and object-oriented programming principles. It includes practical examples, installation instructions for Eclipse IDE, and the integration of Selenium for browser automation. Additionally, it highlights the need for automation testing to improve reliability, accuracy, and efficiency in software development.

Uploaded by

dheerajk3435
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views

Java basics

The document provides a comprehensive guide on automation testing using Java, covering essential programming concepts, data types, methods, and object-oriented programming principles. It includes practical examples, installation instructions for Eclipse IDE, and the integration of Selenium for browser automation. Additionally, it highlights the need for automation testing to improve reliability, accuracy, and efficiency in software development.

Uploaded by

dheerajk3435
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 230

Automation testing

Programming language-
Set of lines
Run that line of code
Output-

Target:
-1. Operation of system
0. Set up – Software installation and its usage
1. Programming language
Basic terminologies about language - Java
Rules to write code
- Data type
Types of data type
Sub types with example
- Variables
o Types of variables
o Examples of variable
o Understanding of usage of variable in
real time.
- Methods
Types of methods
Concept and its usage
Conditional Statements
Loops
Object oriented programming concept -
OOPS
Inheritance
Polymorphism
Encapsulation
Abstract
Interface
Exception handling
String class
Practice problems
Casting
Collection
Map

Selenium
- Setup and configuration
- Basic concept
- Java and Selenium combination
o Basic controlling of the browser
o Webelements
o Handling of multiple elements
 Text field
 Dropdown
 Calendar
 Hover
 Page switching
 Iframe
 Window handling
o Actions class
o Screenshot
o Scroll
o Git
o Jenkins

BDD – cucumber – Automation java


API Testing- Automation - RestAssured

Need of Automation Testing:

1. To achieve the reliability we need automation.


2. To avoid the human mistakes we need automation
3. To improve the accuracy.
4. To reduce the testing efforts we require automation
Features of Java:
1. Java is a platform independent language. Tagline of
java is “Write once and run anywhere”
2. Java is a portable language: we can implement a logic
according to the requirement so that the same code can
be used in multiple forms.
3. Java is a Robust language: It has error handling
capabilities which can execute the program even if there
is some abnormal situation arrives in the code.
4. Java is a secured language.
5. Java is a multithreaded language- We can execute
multiple programs at a same time using java.
6. Java is object oriented programming language so that
we can achieve optimization of the code.
7. Java is a case sensitive language.
8. Java is a simple language.
Architecture of java:

JDK is a platform independent entity where as JRE is a


platform dependent entity.

Installation of Eclipse IDE tool to write the java code and


execute the same
1. Go to the url: https://www.eclipse.org/downloads/
2. Click on the highlighted button:
3. Click on download:

4. Double click on the downloaded file and it will start


the installation.
5. Select the Eclipse IDE for Java developer:

6. Click on install button and it will start the installation


part
Class, variables and Object:
1. Object: It is an entity which has properties
(variables) and behavior (methods).
2. Class: Collection of object is called as class. It is a
way to plan the program in java.
3. Variables: It is an entity which defines the property
of object which defines the memory consumption of
object.
4. Package : Collection of classes is called as package. A
package can have multiple classes in it.
5. Project: It is an entity which has the collection of
packages that has multiple classes and classes can have
multiple objects and every object property can be
defined using variables and behavior can be define
using methods.
Project creation:
Steps:
1. Go to file – New – Java Project

2. Enter the name of project and click on finish button.


2. Right click on src folder – new – package
3. Enter the name of package in small letters and then click
on finish
5. Right click on package and then select class
6. Enter the name of class and click on finish
Writing the first program:
Steps to create the program:
1. Create a class inside the package.
2. Create a method inside the class by-
Type – main and then press CTRL+Space then select the first
option.

3. Inside the main method type – syso then press


CTRL+SPACE then select the first one / or it directly comes
over the screen.
Example:
package basics;

public class FirstProgram {

public static void main(String[] args) {

System.out.println("This is my first
line of program");
System.out.println("This is my second
line of program");
System.out.println("This is my third line
of program");

Output:
To check the output press the green button to execute it:

This is my first line of program


This is my second line of program
This is my third line of program

Note: In java every program gets always execute from top to


bottom only.
Data types:

Java is a strongly typed language which means every line which has
data must have some type otherwise we will get compilation error.
To define a specific type to the data is called as Datatype.
1. Primitive
2. Non Primitive
There are 2 categories of datatype:
1. Numeric
2. Non numeric

1. Numeric:
a. Integral data type:
i. byte: Size of the byte is 1 byte
range of byte is -128 to 127 (-27 to 27-1)

public static void main(String[] args) {

// formula: datatype variablename = value;

byte var1 = 100;

System.out.println(var1);

2. short : Size of short is 2 bytes


range of short is -32768 to 32767 (-215 to 215-1)

Example:
short var = 2;

System.out.println(var);

short var2 = 32767;

3. int: size of the int is 4 bytes


range of int is -2147483648 to 2147483647 (-231 to 231-1)
Example:

int i = 2;

int j = 128;

int k = 32767;

int l = 2147483647;
int m = -2147483648;
System.out.println(l);

4. long size of long is 8 bytes


range of int is -263 to 263-1

example:
long u = 45l;
System.out.println(u);

2. Floating point data type:


The data types in which we can store the
numeric values interms of decimal.
1. float: The size of float is 4 bytes
Range: Maximum: 3.4 x 1038
Minimum: 1.4 x 10-45

Example:
float f = 58.33f;
float g = 8989898.544566f;

System.out.println(f);
Output:
58.33

2. double: The size of double is 8 bytes


Range: Maximum: 1.79x 10308
Minimum: 4.9 x 10-324
Example:

double d = 89.96;
double w =
899898989898989.6565656565656566;

System.out.println(d);
Output:
89.96

Note: It is recommended to use int as a data


type for integral type of data whereas double
for floating point data type (decimal values)

Non numeric data types:


1. Char – 2 bytes: In this we can define
single value inside the single quotes (‘’)
Example:
char var1 = 'a';

char var2 = '1';

char var3 = '!';

char var4 = '6';

char var5 = 'A';

System.out.println(var3);

2. boolean :It is a data type in which we can


only define 2 values and those are true and
false.
The size of Boolean is not applicable as the
value of Boolean can be true and false which
are the reserved keywords.
Example:
boolean b = true;

boolean c = false;

System.out.println(c);

Addition program:
public static void main(String[] args) {

int i = 10;

int j = 20;

int k = i+j;

System.out.println(k);

// Assignment - Write a Program to perform


substraction and multiplication in java

Note: Value assignment always happens from


right to left
Assignment:

public static void main(String[] args) {

int i = 10;

int j = 20;

int k = i+j;

System.out.println(k);//30

// Assignment - Write a Program to perform


substraction and multiplication in java

// substraction

int l = 60;

int m = 10;

int n = l-m;
System.out.println(n);//50

// Multiplication

int z = 20;

int y = 80;

int x = z*y;

System.out.println(x);//1600

// Division

double e = 100000000;

double f = 565656;

double g = e/f;

System.out.println(g);//
176.78589107160536

Output:
30
50
1600
176.78589107160536

Non Primitive: A data type in which no size is


defined that means it can have the size as per
the data.

String : It is a class which is a non


primitive data type in which we define the
value inside “”.
There is no boundation to put the type of
value
e.g. alphabets, numbers, special characters

Example:
public static void main(String[] args) {
// datatype variablename = value;

String s = "this is string value";

System.out.println(s);//this is string
value

Output:
this is string value

Note:

Ways to execute the program:


1. Click on the green button
2. Right click inside the class and select Run
as – java application

3. Press CRTL + F11

Rules for string data type:

public class NonPrimitive {

public static void main(String[] args) {


// datatype variablename = value;

String s = "this is string value";

System.out.println(s);//this is string
value
// 1. Concatenation +

String s1 = "Pune";

String s2 = "Mahanagar";

String s3 = s1+s2;

System.out.println(s3);//PuneMahanagar

String s4 = s1+" "+s2;

System.out.println(s4);

Output:
this is string value
PuneMahanagar
Pune Mahanagar

Note: Whenever we use + with String data type


then it is called as concatenation.
Concatenation means it will join 2 Strings
value

Whenever we concat anything with String then


it will become String.

Example:
String s5 = "Mumbai";

String s6 = "India's financial capital is ";

String s7 = s6+s5;

System.out.println(s7);//India's financial capital is Mumbai

System.out.println(s6+s5);//India's financial capital is Mumbai


Output:
this is string value
PuneMahanagar
Pune Mahanagar
India's financial capital is Mumbai
India's financial capital is Mumbai

Note: We can put the variables with expression


inside the print statement (syso) as well
which can be of any type

Example:
String s5 = "Mumbai";
String s6 = "India's financial capital is ";
System.out.println(s6+s5);//India's financial
capital is Mumbai

int a = 10;

int b = 20;

System.out.println(a+b);//30

2. Concatenation with String and number:

We can put concatenation with string and


number as well which will evaluate the output
based on the concatenation rule.

Example:
int c = 50;

int d = 20;
int e = c+d;

System.out.println(e);//70

System.out.println("The addition of c
and d is "+e);// The addition of c and d is 70

Example 2:

String with numbers:

int z = 100;

int y = 20;

int e = z+y;

System.out.println(e);//70

System.out.println("The addition of
"+z+" and "+y+" is "+e);// The addition of 100
and 20 is 120

Output:
this is string value
PuneMahanagar
Pune Mahanagar
India's financial capital is Mumbai
India's financial capital is Mumbai
30
120
The addition of 100 and 20 is 120

Assignment: Write a program in which print the


output as –

The addition of 100 and 20 is 120


The difference of 100 and 20 is 80
The multiplication of 100 and 20 is
2000
The division of 100 and 20 is 5

Solution:;

public static void main(String[] args) {

int a = 10;
int b = 20;

int c = b-a;

System.out.println("The difference
between "+a+" and "+b+" is "+c);

// multiplication

int d = a*b;

System.out.println("The multipliation
of "+a+" and "+b+" is "+d);

// division

int e = b/a;

System.out.println("The division of
"+b+" by "+a+" is "+e);

Output:
The difference between 10 and 20 is 10
The multipliation of 10 and 20 is 200
The division of 20 by 10 is 2
Rules for String with number:
1. Whenever we perform any thing with string
then the output value will always be String
only
2. Evaluation in the () bracket will happen
only in left to right direction
Examples:
// String with numbers:

int z = 100;

int y = 20;

int e = z+y;

System.out.println(e);//70

System.out.println("The addition of
"+z+" and "+y+" is "+e);// The addition of c
and d is 70

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

System.out.println(20+2);//22

System.out.println("20"+"2");//202

System.out.println("20"+2);//202

System.out.println("20"+2+2);//2022

System.out.println("50"+true);//50true

System.out.println(5+3+"53");//853
}
Methods: The entity which defines the
behaviour of the object is called as Method.
Inside the method we can define the logic
which can be executed as per our requirement.
To execute the method we have to call it.

There are 2 types of method:


1. Regular method
2. Main method

1. Regular method: There are two types of


regular method:
i. static method
ii. non static method

i. Static method: It is a method in which we


have to define it using static keyword and
having the following syntax:
// Syntax:
// public static void method_name()
// {
// logic which we want to run
// }

To call the static method:


1. Just write the name of method along with
the parenthesis () i.e directly
mehthod_name();
2. Using classname.method_name();

Example:
public class StaticMethod {
// Syntax:
// public static void method_name()
// {
// logic which we want to run
// }

public static void methodOne()


{
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");

public static void main(String[] args) {

// calling the static method inside the


main method

methodOne();

Output:
hello
hello
hello
hello
hello

Example 2:
public class StaticMethod {
// Syntax:
// public static void method_name()
// {
// logic which we want to run
// }

public static void methodOne()


{
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");

public static void addition()


{
int a = 10;

int b = 50;

int c = a+b;

System.out.println(c);
}

public static void main(String[] args) {

// calling the static method inside the


main method

addition();

methodOne();

methodOne();

methodOne();
addition();
}

Output:
60
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
hello
60

}
Assignment:
WAP to create a calculator class which can
perform addition, multiplication, subtraction
and division operation :
Solution:
public class Calculator {

public static void addition()


{
int a = 10;

int b = 50;

int c = a+b;

System.out.println(c);
}

public static void substraction()


{
int a = 10;

int b = 50;

int c = a-b;

System.out.println(c);
}

public static void multiplication()


{
int a = 10;

int b = 50;

int c = a*b;

System.out.println(c);
}

public static void division()


{
double a = 10;

double b = 50;

double c = a/b;

System.out.println(c);
}

public static void main(String[] args) {

addition();//60

substraction();//-40

multiplication();//500

division();//0.2

Output:
60
-40
500
0.2

Calling of static method into another class:


We can call the static method into any class
of the project which can be done only using
classname.methodname();

Example:
public class StaticMethod {
// Syntax:
// public static void method_name()
// {
// logic which we want to run
// }

public static void methodOne()


{
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");
System.out.println("hello");

public static void addition()


{
int a = 10;

int b = 50;

int c = a+b;

System.out.println(c);
}

public class Test {

public static void main(String[] args) {

StaticMethod.methodOne();

StaticMethod.addition();
}

}
Output:
hello
hello
hello
hello
hello
60

Non Static method: It is a method which


defines without using “static” keyword. To
call this method we have to compulsorily
create the object first and then we will be
able to call it.

Rules to call non static method:


To call the non-static method either in the
same class or different class we have to first
create the object then we have to call it by
using the reference variable.method_name();

Syntax:
// public void name_of_method()
// {
// logic which is to be executed
// }

Syntax for Object:


// classname variable_name = new
classname();

Example:
public class NonStaticMethod {
public void m1()
{
System.out.println("m1 non static
method from NonStaticMethod class");
}

public static void main(String[] args) {

NonStaticMethod nsm = new NonStaticMethod();

nsm.m1();

Output:
m1 non static method from NonStaticMethod
class

Example 2:
// Syntax:
// public void name_of_method()
// {
// logic which is to be executed
// }

public void m1()


{
System.out.println("m1 non static
method from NonStaticMethod class");
}
public void m2()
{
System.out.println("Non static
method m2");
}

public static void main(String[] args)


{

// create object:
// Syntax:
// classname variable_name = new
classname();

NonStaticMethod nsm = new


NonStaticMethod();

nsm.m1();

nsm.m1();

nsm.m2();

Output:
m1 non static method from NonStaticMethod
class
m1 non static method from NonStaticMethod
class
Non static method m2

Example 3:

// Syntax:
// public void name_of_method()
// {
// logic which is to be executed
// }

public void m1()


{
System.out.println("m1 non static
method from NonStaticMethod class");
}

public void m2()


{
System.out.println("Non static
method m2");
}

public static void main(String[] args)


{

// create object:
// Syntax:
// classname variable_name = new
classname();

NonStaticMethod nsm = new


NonStaticMethod();

nsm.m1();//m1 non static method from


NonStaticMethod class

nsm.m1();//m1 non static method from


NonStaticMethod class

nsm.m2();//Non static method m2


NonStaticMethod nsm2 = new
NonStaticMethod();

nsm2.m1();//m1 non static method from


NonStaticMethod class

nsm.m1();//m1 non static method from


NonStaticMethod class

Output:
m1 non static method from NonStaticMethod
class
m1 non static method from NonStaticMethod
class
Non static method m2
m1 non static method from NonStaticMethod
class
m1 non static method from NonStaticMethod
class

Main method: It is method which is of static


type and it is a special method through which
the program gets execute according to the top
to bottom order (main method). If we don’t
have the main method then we will not be able
to execute the program.

The word and syntax: “public static void


main(String[] args) {
}”
This is already configured in JVM that means
if we have exactly same syntax then only we
will be able to execute our program otherwise
we will not be.

Variables: It is an entity which is used to


define the properties of an object. That means
it is used to hold a value which can be used
further.
There are 3 types of variables:

1. static variable
2. non static variable
3. local variable

1. Static variable: A variable which defines


at the class level (only inside the class body
but not other than this) and to define we have
to use a keyword – static
To call the static variable:
1. Directly by variable name if it is inside
the same class.
2. Classname.variable name if it is inside the
same class / outside the class.

// Syntax to define the static variable

// static datatype variable_name = value;

public class StaticVariable {

static int a = 50;

public static void main(String[] args) {

System.out.println(a);//50

System.out.println(StaticVariable.a);//50

Accessing the static variable in another


class:
public class StaticVariable {

static int a = 50;

public class Test {

public static void main(String[] args) {

System.out.println(StaticVariable.a);

Example 3:
public class StaticVariable {

// Syntax to define the static variable

// static datatype variable_name = value;

static int a = 50;

public static void main(String[] args) {

System.out.println(a);//50

System.out.println(StaticVariable.a);//50
a = 90;

System.out.println(a);//90

Output:
50
50
90

Example 4:
public class StaticVariable {

// Syntax to define the static variable

// static datatype variable_name = value;

static int a = 50;

public class Test {

public static void main(String[] args) {

System.out.println(StaticVariable.a);//50

StaticVariable.a = 60;
System.out.println(StaticVariable.a);//60

Output:
50
60

2. Non Static variable: It is a type of


variable in which we don’t use keyword –
“static” to define the non-static variable. It
is defined at the class level.
To call non-static variable inside the same
and different class we have to compulsorily
create the object and then using the reference
variable we have to call it.
// syntax:

// datatype variable_name = value;


Example 1: - Calling it inside the same class
public class NonStaticVariable {

String s = "abc";

int i = 10;

public static void main(String[] args) {

NonStaticVariable nsv = new


NonStaticVariable();

System.out.println(nsv.s);//abc
NonStaticVariable nsv1 = new
NonStaticVariable();

System.out.println(nsv1.i);//10

System.out.println(nsv.i);//10

nsv.s = "def";

System.out.println(nsv.s);
}

}
Output:
abc
10
10
def
Example 2: Calling inside other class:

public class Test {

public static void main(String[] args) {

System.out.println(StaticVariable.a);//50

StaticVariable.a = 60;

System.out.println(StaticVariable.a);//60

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

NonStaticVariable var = new


NonStaticVariable();

System.out.println(var.i);

System.out.println(var.s);

Output:
50
60
*****************************
10
Abc

Note: Static and non static variable are


accessible throughout the class hence they are
called as Global variable.

Concept of static and non-static variable:


Non static variable’s value can get differ
from object to object.
Static variable value will remain same for all
the objects.

Example:
public class G {
static int i = 50; // static variable

int j = 80; // non static variable


public static void main(String[] args) {

System.out.println(i);//50

G g1 = new G();

System.out.println(g1.j);//80

g1.j = 70;

System.out.println(g1.j);//70

g1.j = 100;

System.out.println(g1.j);//100

G g2 = new G();

System.out.println(g2.j);//80

System.out.println(g1.j);//100

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

System.out.println(i);//50

i = 90;

System.out.println(i);//90

System.out.println(g1.i);//90

System.out.println(g2.i);//90

g1.i = 120;

System.out.println(g1.i);//120

System.out.println(g2.i);//120
System.out.println(i);//120

Output:
50
80
70
100
80
100
******************************************
50
90
90
90
120
120
120

Program execution sequence:

1. JVM will start


2. Load the class- static content memory
allocation
3. Locate the main method
4. Execute the main method—non static content
memory allocation and de-allocate
5. Unload the class – Static content memory de
-allocation
6. JVM will shutdown
Sr.no Static variable Non static
variable
1 We use static No keyword is
keyword to define required to define
the static the non static
variable variable.
2 Static variable Non static
share its memory variable’s value
with all the gets differ from
object that means object to object.
its value doesn’t
change object to
object.
3 It get called It is compulsory
using directly to create the
variable name / object first
classname.variable before calling the
name. non static
variable.
4 Memory allocation Memory allocation
happens at the happens at the
time of class time of execution
loading. of main method.

3. Local variable: It is a variable which gets


define inside any two curley braces other than
class.
If a variable is not defined at the class
level then it is called as Local variable.

The scope of local variable is always between


the two curley braces only that means it will
be accessible only with in the curley braces
where we have defined those but not outside of
curley braces.
Example:
package variables;

public class LocalVariable {

int u = 80;// non static variable


static int j = 80;// static variable

public static void m1()


{
int i = 20;// local variable

System.out.println(i);
}

public static void main(String[] args) {

int l = 80;// local variable


String s = "abc";// local variable

System.out.println(l);//80
System.out.println(s);//abc

Output:
80
abc
Calling of one method into another method:
a. Calling of static method into another
static method.
b. Calling of static method into non-static
method
c. Calling of non-static method into static
method
d. Calling of non-static method into another
non-static method

a. Calling of static method into another


static method.

public class A {

public static void m1()


{
System.out.println("m1 method");
}
public static void m2()
{
m1();
System.out.println("m2 method");
}

public static void main(String[] args) {


m2();
}

}
Output:
m1 method
m2 method

b. Calling of static into non static method:


Example:
public class A {

public static void m1()


{
System.out.println("m1 method");
}

public void m3()


{
System.out.println("m3 method");
m1();
}

public static void main(String[] args) {

A a = new A();

a.m3();
}

Output:
m3 method
m1 method

c. Calling of non-static inside static method:


public class B {

public static void m4()


{
B b = new B();
b.m5();//calling of non-static method
into static method
System.out.println("m4 method");
}

public void m5()


{
System.out.println("m5 method");
}

public static void main(String[] args) {


m4();
}

Output:
m5 method
m4 method
d. Calling of non static into another non
static:
public class B {

// calling of non static into another non


static method

public void m6()


{
System.out.println("non static m6
method");
}

public void m7()


{
m6();
System.out.println("non static m7
method");
}

public static void main(String[] args) {


m4();

B b = new B();
b.m7();
}

Output:
non static m6 method
non static m7 method

Calling of non-static method into another non


static method which are in different classes:
To call them we have to compulsorily create
the object and then we will be able to call
them.

Example:
public class B {

public void m6()


{
System.out.println("non static m6
method");
}
}

public class C {

public void m8()


{
B b = new B();

b.m6();
System.out.println("Method 8");
}

public static void main(String[] args) {

C c = new C();

c.m8();

Output when we execute C class:


non static m6 method
Method 8
Note: If we have same name variable (non
static and local variable) inside the same
class then whenever we try to access the any
variable then it will access always to the
nearest one.

This keyword: It is a keyword which is used to


access the global variable (static and non
static) inside non static area (non-static
method, Constructor)

Example:
public class Test3 {

int i = 50;

public void m1()


{
int i = 80;

System.out.println(i);//80

System.out.println(this.i);//50

public static void m2()


{
Test3 t3 = new Test3();
System.out.println(t3.i);

int i = 90;

System.out.println(i);
}

public static void main(String[] args) {


Test3 t3 = new Test3();

t3.m1();
}

Output:
80
50

Example for static, non static and Local


variable:
public class H {

int i = 50;// global variable


static int j = 90;// global variable

String k = "def";

public void m2()


{
System.out.println(i);//50
System.out.println(this.i);//50

int i = 60;//local variable

System.out.println(i);//60

System.out.println(this.i);

System.out.println(k);//def

System.out.println(this.k);//def
System.out.println(this.j);//90
System.out.println(j);//90

public static void m1()


{
System.out.println(j);//90

H h = new H();

System.out.println(h.i);//50

// System.out.println(this.j);// this
keyword is not applicable inside the static
area
}

public static void main(String[] args) {

// System.out.println(this.i);// this
keyword is not applicable inside the static
area
System.out.println(j);

Output:
90

College program:
public class College {

String name;
static String collegename;
int age;
int mathsmarks;
int physicsmarks;

public static void main(String[] args) {

College student1 = new College();

student1.name = "Albert";
student1.age = 12;
student1.mathsmarks = 50;
student1.physicsmarks = 40;
collegename = "Coep";

College student2 = new College();

student2.name = "Daniel";
student2.age = 21;
student2.mathsmarks = 60;
student2.physicsmarks = 70;

System.out.println(student2.name);//Daniel

System.out.println(student1.physicsmarks);//40

}
}
Output:
Daniel
40
Assignment:
WAP to store the values of following variables
for 3 customers:

Customername
Mobilenumber
Serviceprovider
Cityname

Solution:
public class MobileSubscriber {

String customername;
long mobile;
static String companyname;
static String cityname;

public static void main(String[] args) {


MobileSubscriber cust1 = new
MobileSubscriber();
cust1.customername = "eder";
cust1.mobile = 9876543210l;
companyname = "Airtel";
cityname = "Pune";

MobileSubscriber cust2 = new


MobileSubscriber();
cust2.customername = "Daniel";
cust2.mobile = 9866543210l;

}
Default value: If any of the non-static /
static variable don’t have the values assigned
then they will by default have default values
stored init.

Default values are:


Int – 0
Double – 0.0
Char - <single_space>
Booolean – false
String - null

Note default value concept is not applicable


for local variable it is only applicable for
global variable only (static and non static)

Categories of method: We can define the method


in specific terms that is categories of
method.
Every category is applicable for both static
and non-static method.
There are 4 categories of method:
a. Method with no argument and no return type.
b. Method with argument and no return type.
C. Method with no argument and with return
type.
d. Method with argument and with return type.

a. Method with no argument and no return type.


Example:

// no return and no argument

public void m1()


{
System.out.println("method with no
return and no argument");
}
b. Method with argument and with no return
type

// no return and with argument

public void m2(int i)


{
System.out.println(i);
}

public static void main(String[] args) {

A a = new A();
a.m2(60);

a.m2(80);

Output:
60
80

Example:
public void m3(int i)
{
int j = i+2;

System.out.println(j);
}

public static void main(String[] args) {


A a = new A();
a.m3(8);

Output:
10

Example:
public void m4(int h, int k)
{
int l = h+k;

System.out.println(l);
}

public static void main(String[] args) {

A a = new A();
a.m4(9, 2);
}
Output:
11

Assignment :
WAP to create the calculator which should be
able to perform addition, multiplication,
substraction and division

c. Method with return and no argument:


public class B {
// method with return type and no argument

public static String m5()


{
return "abc";
}

public int m6()


{
System.out.println("This is method with
return and no arg");

return 70;

public String uniqueId()


{
String name = "Ron";

int roll = 50;

String id = name+roll;

return id;
}

public static void main(String[] args) {

B b = new B();

int var = b.m6();

System.out.println(var);//70

int y = var + 2;

System.out.println(y);//72
String idvalue = b.uniqueId();

System.out.println(idvalue);//Ron50

String collegename = "coep";

String finalcode = collegename+idvalue;

System.out.println(finalcode);//coepRon50
}
}

Output:
This is method with return and no arg
70
72
Ron50
coepRon50

d. method with return type and with argument


//method with return type and with argument

public static String m9(String s, int i)


{
String word = s+" "+i;

System.out.println(word);

return word;
}

public int m10(String a, boolean b)


{
String c =a+b;

return 50;
}
public static void main(String[] args) {
String s1= m9("India",7);//India 7

String area = s1+" largest country";

System.out.println(area);// India 7
largest country

System.out.println(m9("Russia", 1));

C c = new C();

System.out.println(c.m10("abc",
false));//50

Output:
India 7
India 7 largest country
Russia 1
Russia 1
50
Solution:
public class AreaCalc {

public int area(int length, int breadth) {

int landArea = length * breadth;

return landArea;

public static void main(String[] args) {

AreaCalc land = new AreaCalc();

int area1 = land.area(50, 50);//2500

int area2 = land.area(80, 20);//1600

int area3 = land.area(10, 20);//200

int totalArea = area1+area2+area3;

System.out.println("Total area is
"+totalArea);

Output:
4300
Operators:
1. Arithmetic operator:

public class ArithmeticOperator {

// addition '+'
// substraction '-'
// multiplication '*'
// division '/'

// modulus '%'
public static void main(String[] args) {
int i = 2;

int j = 10;

int k = j/i;

System.out.println(k);//5

int l = j%i;// remainder

System.out.println(l);//0

int o = 10 % 3;

System.out.println(o);//1

}
}

Output:
5
0
1

Note: Modulus ‘%’ is an operator which


provides the remainder of the division of the
numbers on which we have applied the modulus
operator ‘%’

2. Conditional operators:
// greater than '>'

boolean isGreater = 10>8;

System.out.println(isGreater);//true
int u = 90;

int v = 78;

boolean g = u>v;

System.out.println(g);//true

// less than '<'

int t = 40;

int e = 60;

boolean r = e<t;

System.out.println(r);

// greater than or equal to '>='

int y = 90;

int j = 90;

boolean h = y >= j;

System.out.println(h);// true

Output

True

// less than or equal to '<='

int p = 87;

int q = 96;
boolean w = p <= q;

System.out.println(w);// true

// equal to '=='

int s = 23;

int f = 62;

boolean c = s==f;

System.out.println(c);//false

Note: ‘==’ is considered as equal to operator


which is used to check the condition whether
they are equal or not but ‘=’ is an assignment
operator which is used to assign the value
from right to left.

Assignment:
// WAP to verify all the given sides of a
structure is forming a square or not
// a = 10
// b= 10
// c = 10
// d = 10

If and else:
// syntax for if - else

// if(boolean_condition)
// {
// actions to be executed if
boolean_condition is true
// }
// else
// {
// actions to be executed if
boolean_condition is false
// }

Example:
int n = 56;

int x = 96;

if(n>=x)
{
System.out.println("n is greater than
x");
}
else
{
System.out.println("n is smaller
than x");
}
Output:
n is smaller than x

Rules for if and else:

1. If can only have Boolean condition init


which means inside the () we have to provide
value or expression in terms of Boolean.

2. else is an optional block but if we wanted


to use else then we have to write it
immediately after the if block.
Logical operators:
AND
False False False
False True False
True False False
True True True

OR
False False False
False True True
True False True
True True True
Examples:
// AND -> &&
// OR -> ||

int i = 50;

int j = 70;

int k = 80;
// false true
boolean y = i > 60 && k < 100;

System.out.println(y);// false

boolean z = i <= 70 && k >= 50;

System.out.println(z);// true

boolean u = i == 50 && j > 50 && k <


90;

System.out.println(u);// true

boolean t = i > 60 || k < 100;


System.out.println(t);// true

// NOT -> !

boolean r = false;

boolean o = !r;

System.out.println(o);// true

int p = 90;

int q = 101;

boolean e = !(p > q);

System.out.println(e);// true

boolean w = q != 90;

System.out.println(w);// true
}

Loops: It is a block which has the ability to


execute same logic multiple times then it is
called as loops.

There are 3 types of loops:


1. while loop
2. do-while loop
3. for loop
public static void main(String[] args) {

// syntax of while loop

// while(boolean_condition)
// {
// Action to be executed if condition
is true
// }

int i = 5;//6//7//8//9//10

while(i<10)//5<10, 6<10, 7<10,8<10,


9<10, 10<10
{
System.out.println("Hello");

i = i +1;//7//8//9//10
}

Output:
Hello
Hello
Hello
Hello
Hello

WAP to print the even number from 1 to 10

Solution:
public static void main(String[] args) {

int number = 1;

while(number<=10)
{

int remainder = number % 2;

if(number !=1 && remainder==0)


{
System.out.println(number);
}

number = number + 1;

}
Output:
2
4
6
8
10

Executing the project in DEBUG mode:


1. Apply the debug points by double click on
the line number from which we want to start
the debug and ending line as well.
2. Right click and select Debug as Java
application

3. Click on switch button

4. Press this button as displayed inside the


image:
5. Once we execute the program and if we want
to go back to the java mode then we have to
press Java icon as displayed inside the image:

2. Do – While : In this loop first do will


execute irrespective of while condition
whether it is true / false. But for the next
time it depends on the while condition if it
is true then only it will execute the do block
but if it is false then it wont.
Do –while is a loop in which logic inside the
do block will execute atleast once
irrespective of while condition
Example:
public static void main(String[] args) {

// syntax:
// do
// {
// //Actions to be executed
// }
// while(boolean_condition);

int i = 5;

do
{
System.out.println("Hello");
i = i +1;
}
while(i>10);

}
Output:
Hello

For loop:

Example:
int i = 50;
int j = 60;

for(System.out.println("first statement");
i<j; System.out.println("third statement"))
{
System.out.println("Actions are
executing");

i = i+1;
}

Output
first statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement
Actions are executing
third statement

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

int number = 2;
for(int i = 1; i<=10; i= i+1 )
{
int j = number*i;

System.out.println(j);//0, 2, 4,
}
}
Output:
2
4
6
8
10
12
14
16
18
20

Assignment:
WAP to print the table of 2 like:
2 x 1 = 2
2 x 2 = 4

And so on till 10th position


Solution:
public static void main(String[] args) {
int number = 2;
for(int i=1; i<=10; i= i+1)
{

int multiResult= number*i;

System.out.println(number+" x "+i+"
= "+multiResult);

}
}

Assignment:
WAP using for loop to print keeping the use of
* inside the program only once:

*****
Solution:
public static void main(String[] args) {

for(int i=1; i<=5; i= i+1)


{
System.out.print("*");
}
}

Difference between print and println

public static void main(String[] args) {

System.out.println("123");// first
print the automatically change the line
System.out.println("456");
System.out.print("789");// just print
the value but not change the line
System.out.println("012");
}

Output:
123
456
789012
Note: If we write println then after
printing it has to change the line but if we
don’t write ln then it will just print but
not change the line after printing the
statement.

Increment and Decrement Operators:


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

int x = 10;

int y = x++;// first value will


transfer the value to y and then increment

System.out.println(y);//10

System.out.println(x);//11

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

int u = 10;
int v = ++u;// first increment and then
transfer the value to v

System.out.println(u);//11

System.out.println(v);//11
System.out.println("**************************
******************");
int p = 10;
int q = p--;// first transfer the value
to q and then decrement the value of p

System.out.println(p);//9

System.out.println(q);//10

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

int c = 10;
int d = --c;// first decrement and then
transfer the value to d

System.out.println(c);//9

System.out.println(d);//9

Output:
10
11
********************************************
11
11
********************************************
9
10
********************************************
9
9
Assignment:
WAP to print the pattern like:

*****
*****
*****
*****
*****

Solution:
public static void main(String[] args) {

for(int j=1; j<=5; j++)


{
for(int i= 1; i<=5; i++)
{
System.out.print("*");
}

System.out.println();
}
}
Output:
*****
*****
*****
*****
*****
Break keyword: It is a keyword which can only
be used inside loops and once it gets execute
then it will terminate that loop right away
and comes out from the program.

Example:
public static void main(String[] args) {
int number = 2;
for(int i=1; i<=10; i= i+1)
{
int multiResult= number*i;

System.out.println(number+" x
"+i+" = "+multiResult);

if(i==5)
{
break;
}

Output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10

Continue keyword: It is a keyword which can


only be used inside the loop in which if it
execute then it will not allow the next line
of the code to get execute, it will directly
move the code to execute for the next
incremented / decremented value.
Example:
public static void main(String[] args) {

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


{
int remainder = i%2;

if(remainder ==0)
{
continue;
}

System.out.println(i);
}

}
Output:
1
3
5
7
9

WAP to print the even number from 1 to 10


using continue keyword

Constructor:
Definition: It is a special block which gets
execute once object gets created. Constructor
get called automatically once we execute the
object statement. The area of constructor is
also non static area.
// Syntax:

// public name_of_class()
// {
// actions to be executed when constructor
gets execute
// }

Example:

public Test()
{
System.out.println("Constructor is
executing");
}

public static void main(String[] args) {

Test t = new Test();


}

Output:

Constructor is executing
There are 2 types of constructor:
1. Default constructor
2. User defined constructor

1. Default constructor: If we don’t define any


constructor inside a class then at the time of
execution JVM will automatically create the
constructor which doesn’t have any code in it
and that is called as Default constructor,
which will execute at the time of object
creation.

2. User defined constructor: A constructor


created by a user is called as user defined
constructor.

Example:

public class Test {


// Syntax:

// public name_of_class()
// {
// actions to be executed when constructor
gets execute
// }

public Test()
{
System.out.println("Constructor is
executing");
}

public static void main(String[] args) {

Test t = new Test();


}

Output:
Constructor is executing

Rules of constructor:

1. Name of class and constructor name must be


same and if we don’t do it then we will get an
error.

2. Constructor cannot have a return type but


still we define a return type to the
constructor then that would not be considered
as Constructor it will be called as method.

3. We can have multiple constructor present


inside the class those can be of argument /
with argument based.

Example:
public class A {
// Multiple constructors inside the class

public A()
{
System.out.println("zero argument
constructor");
}

public A(int i)
{
System.out.println("One argument
constructor");

System.out.println("Value of argument
is "+i);
}

public static void main(String[] args) {

A a1 = new A();

A a2 = new A(10);

Output:
zero argument constructor
One argument constructor
Value of argument is 10

4. We can call one constructor inside another


constructor as well using this (); which must
present on the first line only and we can call
only one constructor inside another
constructor.
Example:

// Multiple constructors inside the class

public A()
{
System.out.println("zero argument
constructor");
}

public A(int i)
{
this();

System.out.println("One argument
constructor");

System.out.println("Value of argument
is "+i);
}

public static void main(String[] args) {

A a1 = new A();

A a2 = new A(10);

}
Output:
zero argument constructor
zero argument constructor
One argument constructor
Value of argument is 10

Example 2:

// Multiple constructors inside the class

public A()
{
System.out.println("zero argument
constructor");
System.out.println("**************Zero
argument*****************");
}

public A(int i)
{
this();

System.out.println("One argument
constructor");

System.out.println("Value of argument
is "+i);
System.out.println("**************one
argument*****************");
}

public A(String s, boolean b)


{
this(60);

System.out.println("2 argument
constructor");
System.out.println(s+b);
System.out.println("**************two
argument*****************");
}
public static void main(String[] args) {

A a1 = new A();

A a2 = new A(10);

A a3 = new A("abc", false);

Output:
zero argument constructor
**************Zero argument*****************
zero argument constructor
**************Zero argument*****************
One argument constructor
Value of argument is 10
**************one argument*****************
zero argument constructor
**************Zero argument*****************
One argument constructor
Value of argument is 60
**************one argument*****************
2 argument constructor
abcfalse
**************two argument*****************

5. Constructor doesn’t follow the inheritance


as whenever we create the object of child
class it by default called the parent class
constructor but if we directly try to access
the parent class constructor then it is not
possible hence it is not following
inheritance.
Example:

public class Pcons {

public Pcons()
{
System.out.println("Zero argument
constructor from Pcons");
}
}

public class Ccons extends Pcons {

public Ccons(int i)
{
System.out.println("one argument child
class constructor");
}

public static void main(String[] args) {


Ccons c = new Ccons();
}
}
Output: Error as we are not able to access the
parent class constructor directly

Usage of constructor:

1. It is used to execute the logic inside the


constructor whenever we create the object.
2. It is used to initialize the variables.
Example:
public class College {

String name;
static String collegename;
int age;
int mathsmarks;
int physicsmarks;

public College(String nameOfStudent, int a,


int mmarks, int pmarks)
{ name = nameOfStudent;
age = a;
mathsmarks = mmarks;
physicsmarks = pmarks;
}

public static void main(String[] args) {

College s1 = new College("Daniel", 12,


56, 80);
College s2 = new College("Eder", 13,
65, 72);

System.out.println(s1.name);

Output:
Daniel

OR this can be done in this way as well:


public class College {
String name;
static String collegename;
int age;
int mathsmarks;
int physicsmarks;

public College(String name, int age, int


mathsmarks, int physicsmarks) {
this.name = name;
this.age = age;
this.mathsmarks = mathsmarks;
this.physicsmarks = physicsmarks;
}

public static void main(String[] args) {

College s1 = new College("Daniel", 12,


56, 80);
College s2 = new College("Eder", 13,
65, 72);

System.out.println(s1.name);

}
Output:
Daniel
Code:
public static void main(String[] args) {
for(int i=0; i<=5; i++)
{

for(int j=1; j<=5; j++)


{
if(j>=1&&j<=i)
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}

System.out.println();
}
}

Output:
*
**
***
****
*****

Assignment:
WAP to draw the star patter for these :

// *
// **
// ***
// ****
// *****

public static void main(String[] args) {


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

for(int j=1; j<=5; j++)


{
if(j>=(6-i) && (j<=5))
{
System.out.print("*");
}
else
{
System.out.print(" ");
}
}

System.out.println();
}
}

Output:
*
**
***
****
*****

OOPs concept:
Inheritance: It is a process in which we
acquire the property of one class into another
class by using extends keyword to connect
those classes.

To apply the inheritance we have to use


extends keyword in that class (Sub / Child
class) which will acquiring the property of
another (Super / parent class).
Rules for inheritance:
1. In inheritance all the properties of the
parent / Super class can be acquired by Child
class, Child class can access all the
methods / variables from the parent class
directly as it has them in the same class.
2. We can apply the inheritance in only one
direction that means we cannot apply the
inheritance for both the classes that is
invalid. Either parent is being extends by
child or child is being extend by parent but
not both.

public class Child extends Parent


{
}

These two are not possible only one of them is


possible.

Example:
package inheritance;
public class A {

public void m1()


{
System.out.println("M1 method");
}

public void m2()


{
System.out.println("M2 method");
}

public static void m3()


{
System.out.println("M3 static from A
class");
}

package inheritance;

public class B extends A


{

public void m4()


{
System.out.println("m4 method");
}

public static void main(String[] args) {

B b = new B();

b.m4();

b.m1();
b.m2();

m3();

}
}

Output when we execute B class

Example 2:
public class Parent {

public void home()


{
System.out.println("Home from parent");
}

public void car()


{
System.out.println("Car from parent");
}

public void furniture()


{
System.out.println("furniture from
parent");
}

public void capital()


{
System.out.println("Capital from
parent");
}

public static void main(String[] args) {

Parent p = new Parent();


p.car();

// p.bike();// this is not allowed because


inheritance is applicable only in one
direction

}
public class Child extends Parent
{

public void bike()


{
System.out.println("Bike from child");
}

public static void main(String[] args) {


Child c = new Child();

c.home();

c.car();

c.bike();

}
}

Output when we execute child class:


Home from parent
Car from parent
Bike from child

3. Variable can also be accessible from the


child class of parent class.
public class Parent {

static String s = "abc";

int i = 20;

public class Child extends Parent


{

public static void main(String[] args) {


Child c = new Child();

System.out.println(c.i);

System.out.println(s);

}
}

Output:
20
Abc

Super keyword: It is a keyword which is used


to access the global variable of parent class
inside non static area of child class.
Example:
public class A {
String ps1 = "Pune";

public class B extends A


{
String ps1 = "Mumbai";

public void m4()


{
System.out.println(this.ps1);//mumbai

System.out.println(super.ps1);//Pune

System.out.println("m4 method");
}

public static void main(String[] args) {

B b = new B();

b.m4();
}

Output on executing B class:


Mumbai
Pune
m4 method

Sr. This Super


no
1 It is used to It is used to access
access the global the global variable
variable inside the inside the non-
non-static area of static area of the
the same class. Parent class.
2 Inheritance is not Inheritance is
required to use mandatory to use
this keyword. super keyword.

3. There are 2 types of inheritance:


a. Single level inheritance
b. Multi-level inheritance
a. Single level: If a class is extending
another class is called as Single level
inheritance

public class Parent {

public class Child extends Parent {

b. Multilevel inheritance: If there are more


than single level of inheritance then it is
called as Multilevel inheritance.
Example:
public class GrandParent {

public class Parent extends GrandParent {

public class Child extends Parent


{

4. We can only have a single parent for a


class we cannot define multiple parent for a
class, which is called as Multiple inheritance
and it is not possible for classes.

Exaample:
public class C {

public void profit()


{
System.out.println("Profit method from
C");
}

} public class D {

public void profit()


{
System.out.println("Profit method from
D");
}

}
public class E extends C, D{-- here we get
error

public static void main(String[] args) {

E e = new E();

e.profit();

Multiple inheritance introduce diamond


ambiguity problem hence it is not valid
because inside the Parent 1 and Parent 2 class
can have name method name and if we allow this
multiple inheritance then there will be a
confusion with compiler that which method will
it call.
This is called as Diamond ambiguity issue.
Constructor doesn’t follow the inheritance as
whenever we create the object of child class
it by default called the parent class
constructor but if we directly try to access
the parent class constructor then it is not
possible hence it is not following
inheritance.
Example:

public class Pcons {

public Pcons()
{
System.out.println("Zero argument
constructor from Pcons");
}
}

public class Ccons extends Pcons {

public Ccons(int i)
{
System.out.println("one argument child
class constructor");
}

public static void main(String[] args) {


Ccons c = new Ccons();
}
}
Output: Error as we are not able to access the
parent class constructor directly
Note:
We cannot call Parent class constructor
directly inside the code in terms of
inheritance, first we have to call the child
class constructor and then it will call parent
class constructor.

Child class constructor will always call first


parent class constructor if parent class has
zero argument constructor then we don’t have
to call it inside child class constructor it
will automatically executes.

If parent class has any non-zero argument


constructor then it is the responsibility of
the child class constructor to call first the
parent class constructor inside the child
class constructor using Super keyword.

Super(): It is used to call the parent class


constructor inside the child class
constructor.
Calling of super() must be at first line only.

Example:
public class Pcons {

public Pcons(String s)
{

System.out.println(s);
System.out.println("one argument
constructor from Pcons");
}
}

public class Ccons extends Pcons {

public Ccons(int i)
{
super("abc");
System.out.println("one argument child
class constructor");
}

public static void main(String[] args) {


// Ccons c = new Ccons();// Error which says
we need to first call the Child class
constructor then we will be able to call the
parent class constructor

Ccons c = new Ccons(50);


}
}

Output:
abc
one argument constructor from Pcons
one argument child class constructor

Through inheritance we have achieved


Reusability.
Access modifiers: It is defined
as a set of keyword which can be used with
class, method, variables etc to define in
terms of their accessibility at that which
location.

It applicable for:
1. Class
2. Methods
3. Variables etc.

1. Class level access modifiers: for


classes applicable access modifiers are:
a. public
b. <default>
c. final
d. abstract- Will study after
encapsulation

a. public: If a class declared as public


then it is accessible throughout the
project.

Example:

public class Test1 {

}
b. <default>: If a class is declared as
<default> then it is accessible only
within the package but not outside the
package.
To define the default class we just don’t
write any access modifier to declare a
class as default.
Example:

class Test2 {

c. final : It is a modifier which doesn’t


allow a class to create its child class
if it is declared as final.
Final is a modifier which can be used
along with either public or default.
Example1:
public final class Test3 { --- using public
}

Example 2:
final class Test3 { --- using <default>

Method / variable level access modifier:


1. public
2. <default>
3. private
4. protected
1. public: If we declare a method /
variable as public then it will be
accessible throughout the project
provided that class will be accessible at
that location.

Example:
public static int i = 50;
public static void m1()
{
System.out.println("public m1 method
from MT class");
}

Note : We need to make sure the location at


which class is accessible only in that
location we can access the method.
Class must be accessible to access the method.

Example:

class MT {

public static void m1()


{
System.out.println("public m1 method
from MT class");
}

Here this class is default and method is public hence


method will only be accessible inside the package.
2. <default>: If we declare a method / variable as
default then it will be accessible only within the
same package where we have defined it.
Example
static String s = "abc";
static void m2()
{
System.out.println("default static m2 method from MT
class");
}

3. private: If we declare a method / variable as


private then it will be accessible only within the
same class.

Example:
private boolean b = false;
private void m3()
{
System.out.println("Private m3 method");

public static void main(String[] args) {

MT mt = new MT();

mt.m3();
}

Note: private method doesn’t follow the inheritance as it is


not even accessible outside the class.

4. protected: If we declare a method / variable as


protected then it will be accessible with the same
package as default also for outside the project it
can only be accessible inside the child class using
child class reference variable.

Example:
package accessmodifiers;

public class A {

protected int i = 90;


protected void m1()
{
System.out.println("m1 protected method");
}

}
package accesstest;

import accessmodifiers.A;

public class B extends A {

public static void main(String[] args) {

A a = new A();

// a.m1(); m1 is protected hence it will be called on


the basis of child class variable inside the child classs
only

B b = new B();

b.m1();// valid as B is a child class

package accesstest;

import accessmodifiers.A;

public class C extends B {

public static void main(String[] args) {

A a = new A();

// a.m1();// m1 is protected hence it will be called on the


basis of child class variable inside the child classs only
B b = new B();

// b.m1();

C c = new C();
c.m1();

Note:Rule for is applicable for non static method


it is not applicable static method as they don’t get
called using object reference variable.

5. final : It is a modifier applicable for both


method and variable and it can be used along with
public, default, protected and private.

If we declare a method as final then we will not be


able to override it.
Example:
public final void marry()
{
System.out.println("Marry method
suggested by Parent class");
}
If we declare a variable as final then we will not be
able to update the value of that variable.

Example:
public class Parent {

final int i = 60;

static final int j = 90;

public static void main(String[] args) {


Parent p = new Parent();

System.out.println(p.i);

System.out.println(j);

p.i = 80;

j = 40;

Abstract modifier: It is a modifier


applicable for class and methods.
Whenever we have any kind of partial
information available (something is complete
and incomplete) then to define the same
condition together inside a class we use
abstract modifier for methods and classes.
Rules for abstract:
1. A class can have both complete (concrete
method) and incomplete methods (abstract
method).
2. If a method is declared as abstract then we
cannot create a body of it.
3. Inside a class if there is atleast one
method is abstract method then it is
compulsory to declare that class as abstract.
Example
package abstractdiscussion;

public abstract class A {

public void f1()


{
System.out.println("feature 1 code");
}

public void f2()


{
System.out.println("feature 2 code");
}

public abstract void f3();

public abstract void f4();

public abstract void f5();

}
4. Any class can be declared as abstract if it
doesn’t have any abstract method or no methods
inside it.
Example:

5. If any class is declared as abstract then


we cannot create the object of that class.
Example:
In the above example we are getting error
at line 23 which says that we cannot
create an object because if a class is
abstract then we cannot create an object
for that.

6. To execute the methods available


inside the abstract then we have to
extends abstract class by child class and
inside that class we can provide the
implementation (complete the incomplete
methods) and then we can create the
object of child class and through which
we can execute the methods which were
already complete and which are just
completed by child class.

Example:

public class B extends A{

public void f3() {


System.out.println("f3 code completion
inside B class");

}
public void f4() {
System.out.println("f4 code completion
inside B class");

public void f5()


{
System.out.println("f5 code completion
inside B class");
}

public static void main(String[] args) {

B b = new B();

b.f1();
b.f2();
b.f5();
}

}
Output:
feature 1 code
feature 2 code
f5 code completion inside B class
Example 2:
public abstract class A {

public void f1()


{
System.out.println("feature 1 code");
}

public void f2()


{
System.out.println("feature 2 code");
}

public abstract void f3();

public abstract void f4();

public abstract void f5();

public abstract void f6();

public abstract class B extends A{

public void f3() {


System.out.println("f3 code completion
inside B class");

public void f4() {


System.out.println("f4 code completion
inside B class");

}
public void f5()
{
System.out.println("f5 code completion
inside B class");
}
public class C extends B
{
public void f6() {
System.out.println("f6 from c class");

}
public static void main(String[] args) {
C c = new C();

c.f1();
c.f2();
c.f4();
c.f6();
}

}
Output:
feature 1 code
feature 2 code
f4 code completion inside B class
f6 from c class

7. Inside an abstract class we cannot have a


method as static abstract. That means we
always have to define a static method as
complete otherwise it will give error.
Static method cannot be abstract.
Example:
In the above example it says error for method
f7();

Note: We cannot override the static method as


it cannot be overridden hence we cannot define
it inside the child class as overridden
method.
Here Class A combination is invalid as it is
final class which cannot be overridden and it
has abstract method which class must be
abstract.
In B class it is abstract hence it can have
complete as well as incomplete method in it.
Hence B is valid combination.

Abstract with respect to constructor:

8. An abstract class can have the


constructor inside it and that
constructor will get execute based on
object of child class. As when we create
the object of child class then it will
automatically call the parent class
constructor.
Example:
public abstract class A {

public A()
{
System.out.println("zero argument
constructor");
}

public void f1()


{
System.out.println("feature 1 code");
}

public void f2()


{
System.out.println("feature 2 code");
}

public static void f7()


{
System.out.println("Static method non-
abstract from A Class");
}

public abstract void f3();

public abstract void f4();

public abstract void f5();

public abstract void f6();

}
public abstract class B extends A{

public void f3() {


System.out.println("f3 code completion
inside B class");

}
public void f4() {
System.out.println("f4 code completion
inside B class");

public void f5()


{
System.out.println("f5 code completion
inside B class");
}

}
public class C extends B
{
public void f6() {
System.out.println("f6 from c class");

}
public static void main(String[] args) {
C c = new C();

c.f1();
c.f2();
c.f4();
c.f6();
}

Output when we execute C class:


zero argument constructor
feature 1 code
feature 2 code
f4 code completion inside B class
f6 from c class

9. Variable cannot be abstract inside the


abstract class.

Polymorphism: Whenever we have same


method name but on that basis we derive
different logic is called as Polymorphism. The
word polymorphism represents many forms.
There are 2 types of polymorphism:
a. Overloading
b. Overriding
a. Overloading: Two methods can be called as
overloaded only if:
i. If the name of methods are same.
ii. If the argument of them are different
atleast their order of argument must be
different.

Example:
public class A {

public void m1()


{
System.out.println("Method with 0
argument");
}

public void m1(int i)


{
System.out.println("method with 1
argument");
}

public void m1(int i, String s)


{
System.out.println("method with 2
argument");
}

public void m1(String s, int i)


{
System.out.println("method with 2
argument");
}

All the above methods are overloaded methods.


iii. Return type doesn’t make any difference
to make the method as overloaded method.
Example:
public void m1(String s, int i)
{
System.out.println("method with 2
argument");
}

public int m1(int i, boolean b)


{
return 50;
}

iv. Overloading rule is applicable for both


static and non-static in which if a method is
non static and other is static and they are
having the same name but different argument
then they are called as Overloaded method.

In overloading method execution depends on


reference variable hence it is called as
compile time polymorphism.

It is called as static polymorphism.

Example:

public void m1()


{
System.out.println("Method with 0
argument");
}
public static void m1(String s)
{
System.out.println("M1 static method");

System.out.println(s);
}

v. Access modifier doesn’t make any difference


to call two methods as overloaded method.
public int m1(int i, boolean b)
{
return 50;
}

int m1(int i, boolean b, String s)


{
return 50;
}

Note: These method are called as overloaded


method.

vi. Overloading is not applicable for variable


it is only applicable for methods only.

vii. Constructor can be overloaded inside a


class because it can have same name and
different argument.
Example:

public class A {

public A()
{
System.out.println("0 argument
constructor");
}

public A(int i)
{
System.out.println("1 argument
constructor");
}

Overriding: Two methods are called as


overridden if they are having same name,
arguments and those class are having the
relationship of inheritance then these metho ds
are called as overriding method.

1. Execution of method for overridden depends


on run time object of the class whichever
class’s object we create it will be called on
that object.
Hence it is also called as Run time
polymorphism.

Example:
public class Parent {

public void home()


{
System.out.println("Home from parent");
}

public void car()


{
System.out.println("Car from parent");
}

public void furniture()


{
System.out.println("furniture from
parent");
}

public void capital()


{
System.out.println("Capital from
parent");
}

public class Child extends Parent {

public void bike()


{
System.out.println("Bike from child");
}

public void furniture()


{
System.out.println("Furniture method
from Child class");
}

public static void main(String[] args) {

Child c = new Child();

c.home();

c.furniture();
}

Output:
Home from parent
Furniture method from Child class

2. If a method inside the parent class


declared as final then it cannot be overridden
inside the child class.
Example:
public class Parent {

public final void marry()


{
System.out.println("Marry method
suggested by Parent class");
}

public class Child extends Parent {

public void bike()


{
System.out.println("Bike from child");
}

public void furniture()


{
System.out.println("Furniture method
from Child class");
}

public void marry()


{
System.out.println("Marry method by
Child class");
}

Note: here child will get error as marry


method is final

3. If methods are overridden then they should


have same return type inside the parent and
child class.

Example:
public class Parent {

public void home()


{
System.out.println("Home from parent");

}
}
public class Child extends Parent {

public int home()


{
System.out.println("Child class home
method");
int rent = 15000;
return rent;

}
}

The above example is not valid as the return


type of the methods are not same, it should be
same.
4. The scope of the access modifier inside the
child class must be same / greater than parent
class then only we will be able to override
the method.

Example:
public class Parent {

public void home()


{
System.out.println("Home from parent");

}
}
public class Child extends Parent {

int home()
{
System.out.println("Child class home
method");
int rent = 15000;
return rent;

}
}

In the above example scope of child class


method gets reduces hence it cannot be
overridden.

5. If two classes have relationship of parent


and child then we can create the object by
parent reference and child object.
P p = new C();
Here P is parent class and C is child class.
And on that particular object if:
Method is overridden then it will be called on
the basis of run time object.
Method is not overridden then it will get
called on the basis of reference variable.

Due to this concept of calling of method on


the basis of runtime object / reference
variable overriding is also called as Dynamic
polymorphism.

Example:
package polymorphism;

public class B {

public void m1()


{
System.out.println("B class m1
method");
}

public void m2()


{
System.out.println("B class m2
method");
}

public void m3()


{
System.out.println("B class m3
method");
}

public void m4()


{
System.out.println("B class m4
method");
}

}
package polymorphism;

public class C extends B {

public void m1()


{
System.out.println("C class m1
method");
}

public void m2()


{
System.out.println("C class m2
method");
}

public static void main(String[] args) {

C c = new C();
c.m1();//C class m1 method

B b = new B();

b.m1();// B class m1 method

B bb = new C();

// C cc = new B(); - This object is


invalid as Parent class can hold the child
class object but child class cannot hold
parent class object

bb.m1();// C class m1 method


bb.m2();//C class m2 method

bb.m3();// B class m3 method.

}
}

Output:
C class m1 method
B class m1 method
C class m1 method
C class m2 method
B class m3 method

6. Static method doesn’t follow overriding if


we try to call the static method using the
object then it will execute based on reference
variable. It seems to be overridden but it is
not. This particular concept is called method
hiding but not overriding.

Method hiding: If two classes are following


inheritance relationship and it has static
method having same name, same argument with
same return type then it will not execute
based on the Object but it will execute based
on reference variable hence it is called as
Method hiding.

Example:
public class B {
public static void m5()
{
System.out.println("m5 static method
from B class");
}

public class C extends B {


public static void m5()
{
System.out.println("m5 static method
from C class");
}

public static void main(String[] args) {

C c = new C();

B b = new B();

B bb = new C();

c.m5();

b.m5();

bb.m5();

Output:
m5 static method from C class
m5 static method from B class
m5 static method from B class

Note: Overriding is applicable for only non-


static method.
7. Variable (static and non static) doesn’t
follow overriding as they execute on the basis
of reference variable but not runtime object
if the name of variable is same in both the
parent and child class.
public class B {

int i = 50;

public class C extends B {

int i = 60;

public static void main(String[] args) {

C c = new C();
B b = new B();

B bb = new C();

System.out.println(c.i);//60

System.out.println(b.i);//50

System.out.println(bb.i);//50

}
8. Constructor doesn’t follow overriding as
the name of constructor must be same as the
name of class.
Difference between overloading and overriding:
Sr. no Overloading Overriding
1 Method name is Method name is same
same but arguments but arguments
are different should also be same
atleast order must is called as
be different is Overriding.
called as
Overloading.
2 Method execution / Method execution /
resolution based resolution based on
on reference runtime object.
variable
3 Static and non Only non static
static method method follows
follow overriding.
overloading.
4 Method return type Method return type
doesn’t make must be same for
difference for overriding.
overloading.
5 Access modifier Access modifier
can be any for should have greater
method scope inside the
overloading. child class or
should have the
same scope but it
cannot have lesser
scope to call the
method as
overridden.
6 Constructor follow Constructor doesn’t
overloading follow overriding.
7 It is also called It is also called
as Static as Dynamic
polymorphism and polymorphism and
compile time run time
polymorphism. polymorphism.
8 Final method can Final method cannot
be overloaded be overridden.
Through polymorphism we have achieved
Portability.

Main method can be overloaded but cannot be


overridden as it is static method.

Encapsulation:
It is an oops concept through which we can achieve
the security.

Whenever we have a data / variable available


as private and that is being called inside the
public method of the class then this concept
is called as DataHiding. Because of data
hiding we hide the data from other classes as
it is private.

When we call that particular method in another


class then it just show the name of the
functionality but not displaying internal
implementation to the end user this is called
as Abstraction.

If we combine both data hiding and abstraction


then it became Encapsulation.
public class SBIServer {

private int customerBalance = 50000;

public void getBalance(int pin)


{
if(pin==1234)
{

System.out.println(customerBalance);
}
else
{
System.out.println("Incorrect pin
please try again");
}
}

public void setBalance(int pin, int amount)


{
if (pin == 1234)
{
if(amount<customerBalance)
{
customerBalance=
customerBalance - amount;
System.out.println("Your
account balance is :"+customerBalance);
}
}

else
{
System.out.println("Incorrect pin
please try again");
}
}
}

public class HDFCATM {

public static void main(String[] args) {

SBIServer server = new SBIServer();

server.getBalance(1234);//Abstraction

server.setBalance(1234, 20000);

Output:
50000
Your account balance is :30000

We can define the encapsulation using getter


and setter methods.
Getter method: A method whose name starts with
‘get’ word and it is used fetch or read the
data then it is called as getter method.
Example:

public void getBalance(int pin)


{
if(pin==1234)
{

System.out.println(customerBalance);
}
else
{
System.out.println("Incorrect pin
please try again");
}
}
Setter method: A method whose name starts with
‘set’ word and it is used to update the
information then it is called as Setter
method.
public void setBalance(int pin, int amount)
{
if (pin == 1234)
{
if(amount<customerBalance)
{
customerBalance=
customerBalance - amount;
System.out.println("Your
account balance is :"+customerBalance);
}
}

else
{
System.out.println("Incorrect pin
please try again");
}
}
Solution:
package assignmentofmulticlassmethodcalling;

public class A {

public void m1()


{
System.out.println("m1 method from A
class");
}

public void m2()


{
System.out.println("m2 method from A
class");
}

public void m3()


{
System.out.println("m3 method from A
class");
}

}
package assignmentofmulticlassmethodcalling;

public class B {

public void m4()


{
System.out.println("m4 method from B
class");
}

public void m5()


{
System.out.println("m5 method from B
class");
}

public void m6()


{
System.out.println("m6 method from B
class");
}
}
package assignmentofmulticlassmethodcalling;

public class C {

public void m7()


{
System.out.println("m7 method from C
class");
}

public void m8()


{
System.out.println("m8 method from c
class");
}

public void m9()


{
System.out.println("m9 method from C
class");
}

}
package assignmentofmulticlassmethodcalling;

public class D extends E{

public void m10()


{
System.out.println("*******M10 method
started******************");

a.m3();
b.m4();
c.m9();
System.out.println("*******M10 method
end******************");
}

public void m11()


{
System.out.println("*******M11 method
started******************");

c.m7();
a.m2();

System.out.println("*******M11 method
end******************");
}

public static void main(String[] args) {

D d = new D();

d.m10();

d.m11();

}
package
assignmentofmulticlassmethodcalling;

public class E {
A a;
B b;
C c;
public E()
{
a = new A();
b = new B();
c = new C();
}

Output on executing D class:


*******M10 method started******************
m3 method from A class
m4 method from B class
m9 method from C class
*******M10 method end******************
*******M11 method started******************
m7 method from C class
m2 method from A class
*******M11 method end******************
Interface: It is an entity in which we have
only abstract methods are possible. It is used
when we don’t know anything about the
functionality implementation.
Rules:
1. Every method inside an interface is by
default public and abstract whether we define
it or not.
Note: Here these methods are of same category
that is all of them are public and abstract.

2. To implement the interface by a class we


need to use implements keyword inorder to
connect.
Example:
public interface Interface1 {

public void m1();

public abstract void m2();

void m3();

}
package interfacediscussion;

public class A implements Interface1


{
public void m1() {

System.out.println("This m1 from A
class");
}

public void m2() {


System.out.println("This m2 from A
class");

public void m3() {

System.out.println("This m2 from A
class");
}

public static void main(String[] args) {

A a = new A();

a.m1();
a.m2();
a.m3();

Output:
This m1 from A class
This m2 from A class
This m2 from A class

Example 2:

public interface Interface1 {

public void m1();

public abstract void m2();

void m3();

public abstract class A implements Interface1


{

public void m1() {

System.out.println("This m1 from A
class");
}

public void m3() {

System.out.println("This m2 from A
class");
}
}

public class B extends A


{

public void m2() {


System.out.println("this is method 2
from B class");
}

public static void main(String[] args) {

B b = new B();

b.m2();

b.m1();

b.m3();

Output:
this is method 2 from B class
This m1 from A class
This m2 from A class

3. We can implement any number of classes by


an interface.
Example:
public interface Interface2 {
public void m4();

public void m5();

public void m6();

} public class D implements Interface2 {

public void m4() {

public void m5() {

public void m6() {

public class C implements Interface2{

public void m41() {


// TODO Auto-generated method stub

@Override
public void m5() {
// TODO Auto-generated method stub
}

@Override
public void m6() {
// TODO Auto-generated method stub

@Override
public void m4() {
// TODO Auto-generated method stub

4. A class can implements multiple interfaces


at a time by defining them with comma
separated but that class has the
responsibility to implements all the methods
from all the interfaces.

Example:
public interface Interface3 {

public void m10();

public void m11();

}
public interface Interface1 {

public void m1();

public abstract void m2();


void m3();

}
public interface Interface2 {

public void m4();

public void m5();

public void m6();

public class E implements Interface3,


Interface2, Interface1 {

public void m10() {

public void m11() {

@Override
public void m4() {
// TODO Auto-generated method stub

}
@Override
public void m5() {
// TODO Auto-generated method stub

@Override
public void m6() {
// TODO Auto-generated method stub

@Override
public void m1() {
// TODO Auto-generated method stub

@Override
public void m2() {
// TODO Auto-generated method stub

@Override
public void m3() {
// TODO Auto-generated method stub

Note: This is the example of multiple


inheritance as one class E implementing
Interface1, Interface2 and Interface3 together
and it can do that because no interface can
have the complete method so they don’t have
implementation available hence it is
applicable.

5. We can extends an interface with another


interface by using extends keyword which is
used to extending the properties of an
interface into the child interface.

Example:
public interface Interface4 {

public void m12();

public void m13();

}
public interface Interface5 extends
Interface4{

public void m13();

public void m14();


}
public class F implements Interface5
{

public void m12() {

public void m13() {

public void m14() {

Note: here we have a common method inside both


interface4 and interface5 so if any of the
class which implements the interface5 then it
has to implement all the methods from
interface4 as well as interface5 and if there
is any common method between interface4 and
interface5 then that class will implement it
only once.

6. An interface can implements any number of


interfaces at a time.
Example:
7. Constructor is not applicable for
interface.

8. We can extends the class and implements the


interface together but order must be extends
followed by implements
Example:
public class Login extends OpenBrowser
implements Interface1, Interface2
{

public void enterUsername()


{

@Override
public void m1() {
// TODO Auto-generated method stub

@Override
public void m2() {
// TODO Auto-generated method stub
}

@Override
public void m3() {
// TODO Auto-generated method stub

@Override
public void m4() {
// TODO Auto-generated method stub

@Override
public void m5() {
// TODO Auto-generated method stub

@Override
public void m6() {
// TODO Auto-generated method stub

9. If a method is common in both interfaces


then a class is implementing both interfaces,
it has to define the method only once as it is
common.
But if the methods inside the interfaces are
having different return type then it is not
possible to implements both the interfaces by
that class.
Example:
package interfacediscussion;

public interface Interface6 {

public void m15();

public void m16();

}
package interfacediscussion;

public interface Interface7 {

public int m15();

public void m18();

}
package interfacediscussion;

public class G implements Interface6,


Interface7{

@Override
public void m18() {
// TODO Auto-generated method stub

@Override
public void m15() {
// TODO Auto-generated method stub

}
@Override
public void m16() {
// TODO Auto-generated method stub

Note:Here m15 method implementation is not


possible.

10. We can have static method inside an


interface and that method must be complete it
is not allowed to be incomplete inside an
interface.

From java 8 static methods are allowed inside


the interfaces.

Example:
public interface StaticMethodInterface {

public static void m1()


{
System.out.println("static method from
interface");
}

public static void main(String[] args) {

m1();

StaticMethodInterface.m1();

}
}
Output:
static method from interface
static method from interface

11. Variables can be defined inside an


interface and those are by default public
static and final whether we define them or
not.

Example:
public interface StaticMethodInterface {

int i = 20;

public static void m1()


{
System.out.println("static method
from interface");
}

public static void main(String[] args)


{

m1();

StaticMethodInterface.m1();

System.out.println(StaticMethodInterface.i);
}
}

Output:
static method from interface
static method from interface
20

Difference between Interface and Abstract:

Sr Interface Abstract
no
1 All the methods We can define
inside an interface complete as well as
are by default incomplete methods
public and abstract inside the class.
whether we define it
or not but static
method is an
exception.
2. All methods and Methods and
variable are by variable inside the
default public. abstract class need
not be public.
3 Constructor is not Constructor is
allowed inside the allowed.
interface
4 If we don’t know If we have partial
about the information then we
implementation then can use abstract.
of anything then we
can use interface.
5 Interface must be Abstract class
implements by a should be extends
class another class.
6 Every variable Every variable need
inside an interface not be public
are by default static and final.
public static and
final.

Exception handling:
Definition: Any unwanted event occurs during
the execution of code which cause the
termination of program abnormally then it is
called as Exception.
And when we handle this situation after
exception arrived and the code gets terminated
normally then it is called as Exception
handling.

There are 2 ways to handle the exception:


a. using try-catch
b. using throws keyword
a. using try – catch:

Example:
package exceptionhandling;

public class Test {

public static void main(String[] args) {

System.out.println("first line");

int k;
try {// all risky code

int i = 10;

int j = 0;

k = i/j;
}
catch(ArithmeticException e)
{
System.out.println("Exception
arrived hence executing the catch block");
k= 2;

System.out.println(k);

System.out.println("20th line");

System.out.println("last line");

}
}

Output:
first line
Exception arrived hence executing the catch
block
2
20th line
last line

1. Inside the try block we need to write risky


code which can cause the exception and inside
that try block if any of the exception arrived
then it will leave that try block remaining
code as it is and search for the catch block
of the same exception which we had available
inside the try block.

2. If we get the same catch block available


then exception will get handle but if it
doesn’t match with the try then it will not be
able to handle the exception and code will
terminate in an abnormal manner.

Example:
public class Test {

public static void main(String[] args) {

System.out.println("first line");

int k;
try {// all risky code

int i = 10;

int j = 0;

k = i / j;

System.out.println("inside try
after the exception");
} catch (ArithmeticException e) {
System.out.println("Exception
arrived hence executing the catch block");
k = 2;

System.out.println(k);

System.out.println("20th line");

System.out.println("last line");
}

3. Inside the try block we need to write the


risky code and also immediate catch block that
is catch block must be after the try in an
immediate manner.

4. If we have a try block which has got the


exception and we don’t have corresponding
catch block then code will terminate in an
abnormal manner.

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

System.out.println("first line");

int k;
try {// all risky code

int i = 10;

int j = 0;

k = i / j;

System.out.println("inside try
after the exception");

catch (NullPointerException e) {
System.out.println("Exception
arrived hence executing the catch block");
k = 2;
}

System.out.println(k);

System.out.println("20th line");

System.out.println("last line");

}
Output:
first line
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at
exceptionhandling.Test2.main(Test2.java:16)

Example of Nullpointer exception:


package exceptionhandling;

public class A {

public void m1()


{
System.out.println("m1 method");
}

public void m2()


{
System.out.println("m2 method");
}

}
package exceptionhandling;

public class B {
A a;

public void m3() {


System.out.println("m3 method from B
class");

a.m1();

a.m2();

public static void main(String[] args) {


B b = new B();

b.m3();
}

Output:
m3 method from B class
Exception in thread "main"
java.lang.NullPointerException: Cannot invoke
"exceptionhandling.A.m1()" because "this.a" is
null
at exceptionhandling.B.m3(B.java:10)
at exceptionhandling.B.main(B.java:19)

5. We can have multiple catch blocks available


with a try block in this case if any exception
arrived then it will check the catch block
whether it is matching if it is not then it
will move to the next catch block and try to
match the same if still not match with any of
the catch block then it will throw the
exception.

Example:

public static void main(String[] args) {

try
{
int i = 10/0;
}
catch (NullPointerException e) {

System.out.println("Null pointer
exception arrived");

}
catch (ArrayIndexOutOfBoundsException
a) {

System.out.println("Array index out


of bound exception arrived");

}
catch(StringIndexOutOfBoundsException
r)
{
System.out.println("String index
out of bound");
}

}
Output:
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at
exceptionhandling.TryCatchCombination.main(Try
CatchCombination.java:10)

6. We cannot have multiple try block with


single catch block but we can have try with
multiple catch block.

7. A parent catch block can also handle the


exception arrived inside the try block. Hence
we can write the Parent class specific catch
block inside the catch statement.

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

try
{
int i = 10/0;
}
catch (NullPointerException e) {

System.out.println("Null pointer
exception arrived");

}
catch (ArrayIndexOutOfBoundsException
a) {

System.out.println("Array index out


of bound exception arrived");

}
catch(StringIndexOutOfBoundsException
r)
{
System.out.println("String index
out of bound");
}

catch (RuntimeException e) {

System.out.println("Run time
Exception catch block executing");

Output
Run time Exception catch block executing
Note: Here ArithmeticException arrived hence
it can be handled by its parent i.e
RuntimeException and it will be able to handle
the exception. So we should always write the
parent class exception at the last.
IF we write parent first and then child then
child class catch block code will become
unreachable code and we get compile time
error.
Try – catch – finally:

finally: It is a block which we can write with


try – catch – finally or try – finally.
finally block will always get execute whether
we get an exception or not.
Example:
public static void main(String[] args) {

try
{
int i = 10;
int j = 0;
int k = i/j;

catch (ArithmeticException e) {
System.out.println("NPE");
}
finally
{
System.out.println("Finally is
executing");

Output:
NPE
Finally is executing

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

try
{
int i = 10;
int j = 0;
int k = i/j;

catch (NullPointerException e) {
System.out.println("NPE");
}
finally
{
System.out.println("Finally is
executing");
}

}
Output:
Finally is executing
Exception in thread "main"
java.lang.ArithmeticException: / by zero
at
exceptionhandling.TryCatchFinally.main(TryCatc
hFinally.java:11)
Categories of exception:
There are 2 categories of exception:
1. Checked : whenever we write the code and
compiler suggests to handle the exception then
this category is called as Checked category of
exception.
Example:

public static void main(String[] args) {


System.out.println("Before try block");
try {

String path = "F:\\Desktop\\


VimanNagar\\9 Sept\\
Nonstaticvbjdsfjdfjdsfariable.png";

FileInputStream fis =new


FileInputStream(path);

System.out.println("lastline of try
block");

catch (FileNotFoundException e)
{
System.out.println("File not found
exception arrived");

}
}
}

Example 2:

public static void main(String[] args) {

System.out.println("This is first
line");

try {
Thread.sleep(5000);
}
catch (InterruptedException e)
{
System.out.println("Catch block is
executing");
}

System.out.println("This is last
line");
}

Output:
This is first line
This is last line

2. Unchecked : whenever we write the code and


compiler doesn’t suggests to handle the
exception then this category is called as Un-
Checked category of exception.
Example:
public static void main(String[] args) {

System.out.println("first line");

int k;
try {// all risky code

int i = 10;

int j = 0;

k = i / j;

System.out.println("inside try
after the exception");

catch (ArithmeticException e) {
System.out.println("Exception
arrived hence executing the catch block");
k = 2;

Final vs finally vs finalize()

Finalize(): It is a method which is used to


clear the memory of unused object and free the
space. It is internally called by garbage
collector.
Throw keyword: It is a keyword which is used
to throw the exception deliberately inside the
code.
To use this we can simply write the keyword
throw and create an object for class whose
exception we wants to throw.

Example:
public class ThrowKeyword {

public static void main(String[] args) {

int i = 50;

int j = 20;

if(i>j)
{
throw new
NullPointerException("something went wrong
please try again later !!!");
}
}

Output:
Exception in thread "main"
java.lang.NullPointerException: something went
wrong please try again later !!!
at
exceptionhandling.ThrowKeyword.main(ThrowKeywo
rd.java:14)

Difference between Throw and throws keyword:


Sr. no Throw keyword Throws keyword
1 It is used to throw It is used to
the exception handle the
inside the program exception which
deliberately occurs as an
error while
during compile
time.
2 It can be used It is used
inside the method. outside the
method.

Error: It a child class of Throwable class. In


this we get the abnormal termination of the
program due to the insufficiency of the
infrastructure available to execute the code.
To resolve this we need to improve the system
performance.

It has multiple child classes some of them


are:
StackoverFlowError
AssertionError
Example of stackoverflow error:
package exceptionhandling;

public class ErrorDiscussion {

public static void m1()


{
System.out.println("M1 method");
m2();
}

public static void m2()


{
System.out.println("M2 method");
m1();
}

public static void main(String[] args) {


m1();

Output:
M2 method
M1 method
M2 method
M1 method
M2 methException in thread "main"
java.lang.StackOverflowError
at
java.base/java.io.PrintStream.writeln(PrintStr
eam.java:722)
at
java.base/java.io.PrintStream.println(PrintStr
eam.java:1028)
Arrays in Java:
Definition: Group of homogenous elements when
represented by a single entity is called as
Array.

Syntax to define the array:

// syntax to define array:


// data_type [] variable_Name = new
data_type [size-of-array];
Example:
public static void main(String[] args) {

int [] i = new int[5];

i[0] = 50;
i[1] = 90;
i[2] = 2;
i[3] = 96;
i[4] = 48;

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

}
Output:
50

Length of array: It is defined as number of


values / elements that can be stored inside an
array.

Example
public static void main(String[] args) {
// syntax to define array:
// data_type [] variable_Name = new
data_type [size-of-array];

int [] i = new int[5];

i[0] = 50;
i[1] = 90;
i[2] = 2;
i[3] = 96;
i[4] = 48;

int sizeOfArray = i.length;


System.out.println(sizeOfArray);
}
Output:
5

Another Way to define the array:

public static void main(String[] args) {

int [] a = {5, 8, 9, 63, 88};

int sizeOFArray = a.length;

System.out.println(sizeOFArray);

}
Output:
5

Assignment:
// Assignment: WAP to print all the elements
present inside the array using for loop

for(int a=0; a<sizeOfArray; a++)


{
System.out.println(i[a]);
}

Example for ArrayIndexOutOfBoundException:

public static void main(String[] args) {


// syntax to define array:
// data_type [] variable_Name = new
data_type [size-of-array];

int [] i = new int[5];

i[0] = 50;
i[1] = 90;
i[2] = 2;
i[3] = 96;
i[4] = 48;
i[5] = 96;// this line will throw the
exception as array size is 5 which is defined
hence we cannot provide more than 5

System.out.println(i[0]);//50
}

Output:
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException:
Index 5 out of bounds for length 5
at arraydisc.Test.main(Test.java:17)

Sorting of array :
public static void main(String[] args) {

int a [] = {85, 5, 2, 76, 102, 98};

Arrays.sort(a);

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


{
System.out.println(a[i]);
}
}

Output:
2
5
76
85
98
102

For each loop: It is a loop which is used for


those type of data in which we have a variable
representing multiple value. For example
array, collection

Example
:

public static void main(String[] args) {

int a [] = {85, 5, 2, 76, 102, 98};

for(int t:a)
{
System.out.println(t);
}

String [] s = new String[3];

s[0] = "Pune";

s[1] = "Bangalore";

s[2] = "Delhi";

for(String ss:s)
{
System.out.println(ss);
}

}
Output:
85
5
2
76
102
98
Pune
Bangalore
Delhi

Separate 0 and 1 from the array:

public class Separate0and1 {

public static void main(String[] args) {

int a [] = {0,1,0,1,1,1,1,0,0,0};

Arrays.sort(a);

for(int aa :a)
{
System.out.print(aa);
}

}
Output:
0000011111
WAP to swap 2 numbers

A= 5;
B= 6;

Solution:
public static void main(String[] args) {

int a = 10;

int b = 20;

int c = a;

a = b;

b = c;

System.out.println(a);

System.out.println(b);

Output:
20
10

// Assignment2: WAP to add all the odd


elements from the array

// Assignment3: WAP to add all the even


elements from the array

// Assignment4: WAP to add all the odd index


position elements from the array
public static void main(String[] args) {
int a [] = {1, 2, 3, 5, 6, 7};

// addition of odd index position


int sum = 0;
for(int i=0; i<a.length; i++)
{
if(i%2!=0)
{
sum = sum + a[i];
}
}

System.out.println(sum);

Output:
14

// Assignment5: WAP to add all the even index


position elements from the array

public static void main(String[] args) {

int a [] = {1, 2, 3, 5, 6, 7};

// WAP to print the missing number from


Array
}

Solution:
public static void main(String[] args) {

int a [] = {1, 2, 3, 4, 6, 7};

// WAP to print the missing number from


Array

for(int i=0; i<a.length-1; i++)


{
boolean isCorrect = a[i] + 1 ==
a[i+1];

if(!isCorrect)
{
System.out.println(a[i]+1);
}
}
}

Output:
5

Alternate way to sort the array in descending


order and to sort the same in ascending order
then we need to change the >
public static void main(String[] args) {

int a [] = {10, 56, 0, 82, 96};

int var;

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


{
for(int j=i+1; j<a.length; j++)
{
if(a[i]<a[j])
{
var = a[j];

a[j] = a[i];

a[i] = var;
}
}
}

for(int aa :a)
{
System.out.print(aa+" ");
}

}
Output:
96 82 56 10 0

Copy one array into another array:

public static void main(String[] args) {

int a [] = {10, 56, 0, 82, 96};

int[] b = Arrays.copyOf(a, a.length);// to


copy array a into array b

for(int bb:b) {

System.out.println(bb);
}
Output:
10
56
0
82
96

Assignment: WAP to swap the largest and


smallest number inside the original array a
without changing the positions of other
elements
int a [] = {10, 56, 0, 82, 96};

Solution:
public static void main(String[] args) {

int a [] = {10, 56, 0, 82, 96};

int[] b = Arrays.copyOf(a, a.length);// to


copy array a into array b
System.out.println("b array is ");
for(int bb:b) {

System.out.print(bb+" ,");
}
System.out.println();

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

Arrays.sort(b);
System.out.println("Smallest element from b
array is "+b[0]);

int lastIndex = b.length-1;

System.out.println("Largest element from b


array is "+b[lastIndex]);
// finding the index position of largest and
smallest element in array a
int largestindex = 0;
int smallestindex = 0;
for(int i=0; i<a.length; i++)
{
if(a[i]== b[0])
{
System.out.println("Smallest
element index is "+i);
smallestindex =i;

}
if(a[i]==b[lastIndex])
{
System.out.println("Largest element
is "+i);

largestindex = i;
}

int c = 0;

//Swapping the largest and smallest elements

c = a[smallestindex];

a[smallestindex] = a[largestindex];

a[largestindex] = c;

// Printing the a array

for(int aa:a)
{
System.out.print(aa+" ");
}

// Steps
// sort b array
// find out the largest and smallest number of
b
// Find out the index position of smallest and
largest number in a
// Swap the index position in array a

Output:
b array is
10 ,56 ,0 ,82 ,96 ,
*********************************
Smallest element from b array is 0
Largest element from b array is 96
Smallest element index is 2
Largest element is 4
10 56 96 82 0

String class:
String is a class present inside java.lang
package. It is an immutable class as it is not
changing the original string value if we try
to perform any of the operation to the string.

Example:
public class StringClassConcept {

public static void main(String[] args) {


String a = "abc";

String b = a + "software";

System.out.println(b);//abcsoftware

a.concat("software");

System.out.println(a); // abc--> immutable

System.out.println("**************************
******************");
// string buffer

StringBuffer sb = new StringBuffer("abc");

sb.append("software");

System.out.println(sb);// abcsoftware -
mutable

Output:
abcsoftware
abc
********************************************
Abcsoftware

In this example we have stringbuffer class as


well which is mutable in nature and that will
allow to change its original value if try to
perform any operation hence it is called as
mutable class.

Concept of String class:


Definition: It is a class which is present inside java.lang
package in this class we have multiple methods which are
used to manipulate the String / data.
Or
Sequence of character when we represent using double
quotes is called as String.

If we create an object using new keyword


then it allocates the memory at both
places i.e heap area as well as SCP area.
Every time if we have new keyword then it
create an object inside the heap area but
for SCP area it first checks whether the
same content is present or not if it is
not present then it will create an object
but if it is already present then it
won’t create any new object.
If we have an object without new keyword
then it will only create the object into
the SCP area but not inside the heap
area. The object created inside the SCP
area depends on the already available
content if it is already available then
it just point it otherwise it creates a
new one.

Example:
public static void main(String[] args) {
// There are 2 ways to define the string

String s1 = new String("abc");

String s2 = new String("def");

String s3 = new String("abc");

String s4 = "ghi";

String s5 = "abc";

String s6 = "ghi";
// equals method- It compares the content
of 2 string values

boolean isequal = s4.equals(s6);

System.out.println(isequal);

boolean isEqual2 = s5.equals(s1);

System.out.println(isEqual2);

// == it is used to check whether the


string is pointing to the same object or not

boolean isequal3 = s5 == s1;


System.out.println(isequal3);

boolean isequal4 = s4==s6;

System.out.println(isequal4);

}
Output:
true
true
false
true

Methods from String class:


1. Length(): This method returns the number of
character present inside the String.
Example:
// 1. length()
String s1 = "Pune";

int countOfCharacter = s1.length();

System.out.println(countOfCharacter);//4

2. charAt(int i): This method returns the


character available at provided index
position.
Example:
// 2. charAt(int i)

String s2 = "Mumbai";

char ch = s2.charAt(3);

System.out.println(ch);//b

3. equals(String s): This method returns true


if the provided string is exactly match with
the compared string.
Example:
3. equals

String s3 = "Mumbai";

String s4 = "mumbai";

boolean isEqual = s3.equals(s4);

System.out.println(isEqual);// false

4. equalsIgnoreCase(String): This method


returns true if the provided string matches
with the given string without consider their
case.

Example:
String s3 = "Mumbai";
String s4 = "mumbai";

boolean isEquals = s3.equalsIgnoreCase(s4);

System.out.println(isEquals);

5. toLowerCase(): This method returns the


lowercase String.
Example
// 5. toLowerCase()

String s5 = "BangaloRe";

String s6 = s5.toLowerCase();

System.out.println(s6);//bangalore

6. toUpperCase(): This method returns the


Uppercase String.

// 6. toUpperCase()

String s7 = "Chennai";

String s8 = s7.toUpperCase();

System.out.println(s8);//CHENNAI
7. subsString(int begin): This method returns
a String which starts with the provided int
index position.
Example:
// 7. subsString(int begin)

String s9 = "Ahmednagar";

String s10 = s9.substring(5);


System.out.println(s10);//nagar

8. subsString(int begin, int end): This method


returns the String which starts with begin
index and ends with index position + 1.

Example:
// subsString(int begin, int end)

String s11 = "Srinagar";

String s12 = s11.substring(0, 3);

System.out.println(s12);//Sri

9. replace(char old, char new): This method


returns a String by replacing the character
with the provided the second argument
character.
// 9. replace(char old, char new)

String s13 = "Vishakhapattnam";

String s14 = s13.replace('a', 'A');

System.out.println(s14);//VishAkhApAttnAm
10. replace(String old, String new): This
method returns a String which is the
replacement of first argument string with the
second argument string.

// 10. replace(String old, String new)

String s15 = "Ahmedabad";

String s16 = s15.replace("Ahmed", "Hyder");

System.out.println(s16);//Hyderabad
11. trim(): This method removes the spaces
present in starting and trailing part of the
string but it CANNOT remove the intermediate
space from the string.
Example:
// 11. trim()

String s17 = " Hello World


";

String s18 = s17.trim();

System.out.println(s18);//Hello World

// WAP to print all the character of


string line by line

// WAP to print reverse of string


// WAP to print reverse of string

System.out.println("**************************
***");
String reverse =
"";//o//ol//oll//olle//olleH
String s0 = "Hello";
for(int i=s0.length()-1; i>=0; i-- )
{
reverse = reverse + s0.charAt(i);
}

System.out.println("Reverse of String
"+s0+" is "+reverse);//olleH

// WAP to print all the character of


string line by line
String linebyline= "abc";
for(int i = 0; i<linebyline.length();
i++)
{

char c = linebyline.charAt(i);

System.out.println(c);
}

// 12. indexOf(char ch): This method return


the index position of the provided character
as an argument.

String s19 = "abcdaf";

int index = s19.indexOf('a');

System.out.println(index);//2

13. split(String s): This method return


Array of String which stores the splited
values of the string on the basis of the
string value we provide as an argument.

String s20 = "This is String";

String[] s21 = s20.split(" ");

for(String ss:s21)
{
System.out.println(ss);
Output:
This
is
String

// Assignment: WAP to reverse a String without


reversing the characters
// Input = This is String
// Output = String is This

// 14. startsWith(String s) : This method


returns true if the String starts with the
provided argument String otherwise false

String s22 = "Denver";

boolean isStarts = s22.startsWith("Den");

System.out.println(isStarts);//true

//15 . endsWith(String s): This method returns


true if the String ends with the provided
argument String otherwise false

String s23 = "New York";

boolean s24 = s23.endsWith("rk");

System.out.println(s24);//true

Converting the primitive data type into String


value
//Convert the primitive data type into String
int i = 20;

String s25 = String.valueOf(i);

System.out.println(s25+2);//202

boolean s26 = false;


String s27 = String.valueOf(s26);

System.out.println(s27);//false

Convert the String into primitive data type

// Convert the String into primitive data type

String s28 = "60";

int s29 = Integer.parseInt(s28);

System.out.println(s29+2);//62

Note : If we try to convert any string which


is not the correct value of the targeted data
type then it will throw the exception –
NumberFormatException

String s30 = "86.55";

double s31 = Double.parseDouble(s30);

System.out.println(s31);//86.55

16. toCharArray():This method returns


character array from the provided String.
Example:
//16. toCharArray()

String s32 = "pennsylvania";

char[] s33 = s32.toCharArray();

for(char cc:s33)
{
System.out.println(cc);
}

Output:
p
e
n
n
s
y
l
v
a
n
i
a

//17. isDigit(char c) : This method returns


true if the provided character is number
otherwise it return false.

char s34 = '9';

boolean isnumber = Character.isDigit(s34);

System.out.println(isnumber);//true
18. isAlphabetic(char c): This method returns
true if the provided character is alphabet.
Example:

//18. isAlphabetic(char c)

boolean isalpha = Character.isAlphabetic('a');

System.out.println(isalpha);//true

//Assignment : WAP to remove the alphabet from


the string- Hell24oW2or3ld

//Assignment: WAP to remove the digits from


the String - Hell24oW2or3ld

19. replaceAll(String regex, String


replacevalue):
This method returns the String based on the
range provided inside the regex.

Example:
//19 replaceAll(String regex)

String s35 = "Spring";

String s36 = s35.replaceAll("[A-Z]", "a");

System.out.println(s36);//apring

String s37 = s35.replaceAll("[A-D]", "ab");


System.out.println(s37);//Spring

String s38 = "Houston";

String s39 = s38.replaceAll("[a-z]", "q");

System.out.println(s39);//Hqqqqqq

String s40= "Spring";

String s41 = s40.replaceAll("[A-Za-k]", "!");

System.out.println(s41);//!pr!n!

String s42 = "ta#&m!pa";

String s43 = s42.replaceAll("[^a-z]", "");

System.out.println(s43);//tampa

String s44 = "A2c4c!ent$ure%";

String s45 = s44.replaceAll("[^A-Za-z0-9]",


"");

System.out.println(s45);//A2c4centure

Casting: Conversion of a datatype into another


convertable one is called as Casting.

There are two types of casting:


1. Primitive casting
2. Non primitive casting

1. Primitive casting: It is a casting in which


we are converting a primitive data type into
another primitive data type.

There are 2 types of primitive casting:

1. Implicit casting
2. Explicit casting

1. Implicit casting : Casting of lower order


primitve data type into higher primitive order
data type. Inside implicit casting there is no
chance of data loss as we are moving from
lower data type to higher one.
// syntax for primitive casting:

//data_type variablename =(data_type_to which


we want to cast)variable_to_casted;

// Implicit casting

byte b = 20;

int ii = (int)b;

System.out.println(ii);//20

short s = 90;

long y = (long)s;
System.out.println(y);//90

2. Explicit casting: Casting of higher order


primitve data type into lower order primitive
data type. Inside explicit casting there is a
chance of data loss as we are moving from
higher data type to lower one.

Example:

// Explicit casting

int i = 10;

byte bb = (byte)i;

System.out.println(bb);//10

int k = 129;

byte cc = (byte)k;

System.out.println(cc);//-127

Output:
10
-127

Note: Both implicit and explicit casting can


be performed on same category of data.
Non Primitive casting: It applies to the non
primitive data type and it has 2 types :
1. Up casting
2. Down casting

1. Up casting: Whenever we try to cast from


child class to parent class then it is called
as Up casting.
Example:
public class Parent {

public void home()


{
System.out.println("Home from parent");
}

public void car()


{
System.out.println("Car from parent");
}

public void furniture()


{
System.out.println("furniture from
parent");
}

public void marry()


{
System.out.println("Marry method from
Parent class");
}

}
public class Child extends Parent
{
//data_type variablename =(data_type_to
which we want to cast)variable_to_casted;

public void bike()


{
System.out.println("Bike");
}

public void marry()


{
System.out.println("Marry method from
Child class");
}

public static void main(String[] args) {

Child c = new Child();

Parent p1 = (Parent)c;// Up casting

p1.marry();//child class marry method

p1.car();// Parent class car method

p1.home();// parent class home method

2. Down casting: Whenever we try to cast from


Parent class to Child class then it is called
as Down casting. IF we try to perform down
casting directly then it will throw an
exception as child class cannot be used to
hold the object of parent class. And therefore
it throws the exception – ClassCastException

Example:
package casting;

public class Parent {

public void home()


{
System.out.println("Home from
parent");
}

public void car()


{
System.out.println("Car from
parent");
}

public void furniture()


{
System.out.println("furniture from
parent");
}

public void marry()


{
System.out.println("Marry method
from Parent class");
}

public class Child extends Parent


{
//data_type variablename =(data_type_to
which we want to cast)variable_to_casted;

public void bike()


{
System.out.println("Bike");
}

public void marry()


{
System.out.println("Marry method from
Child class");
}

Parent p = new Parent();

Child cc = (Child)p;// Down casting

cc.marry();

cc.home();

cc.car();

Output:
Exception in thread "main"
java.lang.ClassCastException: class
casting.Parent cannot be cast to class
casting.Child (casting.Parent and
casting.Child are in unnamed module of loader
'app')
at casting.Child.main(Child.java:33)

To perform the down casting we need to have up


casting available then we can perform the
downcasting.

Example:

Child c = new Child();

Parent p1 = (Parent)c;// Up casting


Child cc1 = (Child)p1;// down casting which is
performed after up casting

cc1.marry();// Child class marry method

cc1.home();// parent class home method

cc1.car();// parent class car method

You might also like