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

Why Automation Testing

Need / benefits of Automation


Process where we can have automation
Platform for Automation
Language required for Automation
Core – Java (Concepts + Application)
Selenium
Framework
Git platform
Jenkins
Complete process at one go.
At the start point of every project / Sprint we start with the manual testing
then after we switch to the Automation part once the application gets stable.
To make sure the application is stable we have to perform one round of
manual testing over it then we should proceed with Automation.

We first perform the manual testing on the specific functionality then we


should move to the automation part here in the above diagram we have
perform the manual for Sprint 1 and then to the next sprint we will first write
the Automation code when developers are working on the current sprint work.
After the completion of Automation code we will wait for the current sprint
work on which we will first execute the automation code then we will move for
manual testing of current sprint.

Need of Automation:
1. To achieve the reliability we need automation.
2. To avoid human mistakes.
3. To improve the accuracy.
4. Time required to perform the repetitive actions become
less.
Language requirement:
1. Platform independent – Write for once and run
everywhere.
2. It should be simple – easy understand.
3. Portable language.
4. Robust – Error handling capability must be present.
5. Secured language.
6. There should be optimization available.

Java:
Java is available in 3 flavors:
1. Java – SE: It is also called as core java the full form of SE is
Standard Edition.
We use this flavor for building Automation testing (Web +
API), Data base testing etc.
2. Java – EE: It is also called as Advance Java the full form of
EE is Enterprise edition.
It is used to build the backend specific functionality like APIs.
3. Java – ME: The full form of ME is Micro Edition. It is used
for mobile based applications.
Architecture of Java:

Java comes with the block of complete java kit


which has development tools and JRE – java
runtime environment.
Java development tools: It is a component in
which we just develop the code on the basis of
compiler.
Compiler: It is block (software) which checks
whether .java is syntactically correct as per java
protocols. If it verified and there are no changes
required from user then it convert .java file
into .class file which is also called as byte code. If
it doesn’t follow the rules then it will throw an
error – compilation error so that user has to
modify the same.
JRE – Java Runtime Environment: It is responsible
to execute the code which we have written and
compiled. It has different component like JVM,
and system libraries.
JVM: Full form of jvm is java virtual machine
which first understand the code line by line and
execute the same followed by handing over the
output to the OS (operating system).
Here the understanding part is to be done by
interpreter which is also called as just in time
compiler which always interpret the next line of
the line which is being executed in advance once
execution done from jvm side then it handover
the interpreted code to jvm.
Once jvm hand over the output to OS then OS will
show that one to the user afterwards it raise an
acknowledgement which receives by jvm so that it
process the next line.
In this way process continues till the last line of
the file gets execute.
JDK = Dev tools + JRE
JRE = JVM + System libraries

https://www.eclipse.org/downloads/

Creation of project:
After installing eclipse go to file—New – Java
Project

Enter the name of project and click on finish:


Note: On finish we may get a pop up to create
module-info if that comes click on don’t create
button.
Java Basics
Class , object, methods and variables:

Class: Collection of object is called as class. It is


nothing but a blueprint of a plan or program that
we are going to execute.
A class comprises of numerous object and every
object is comprises of state and behavior.
Whenever we wants to define the plan in java
then we require a class.
If the plan gets differ from other plans then we
can represent through multiple classes.

Object: It is an entity which physically


consumes a memory when we execute
the plan / class and it comprises of two
things state and behavior in which state /
characteristics can be define by the help
of variable whereas behavior / actions can
be define with the help of methods.
Variable: It is an entity through which we
define the characteristics of an object.
Through which we define that how much
huge is the object. All the properties
example name length height color etc.

Methods: All the action we want to


perform in a sequence can be defined
inside a method.
Creation of package, class variable and
methods:
To create the package – right click on src –
New – package
Click on finish.
2. To create class Right click on package –
new – class
Click on finish.
Rules to define package, class, variable
and methods

1. Write the code in such a way that it is


relating to the physical quantity. It should so
much self explanatory.
2. We should write the name of package only
in lower case / small letter.
3. We should write first letter of every word
of the class in upper case / capital letters.
4. We should write first letter of every word
method as small letter and the remaining
word’s first letter should be capital.
Example:
additionOfTwoNumbers
Writing first program in java
Steps:
1. Create a class.
2. define main method inside the body of
class by typing - main and press Control +
space key.
Here double click on first suggestions / press
enter.

2. To print something as output – type syso


and press control +space then automatically a
print statement will appear.
Program:
package basicprogram;

public class FirstProgram {

public static void main(String[] args) {

System.out.println("This is my first
program");

Note: If we are defining anything other than


body inside the program then we have to
put ; at the end. If we do not write semi
colon at the end then we will get an error.
Final code:
public static void main(String[] args) {

System.out.println("This is my first
program");

System.out.println("This is my second
line");

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

Output
This is my first program
This is my second line
This is my third line

Example :

public static void main(String[] args) {

System.out.println("This is my first
program");

System.out.println("This is my second
line");

System.out.println("This is my third
line");

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

System.out.println("8 + 2");

System.out.println(8 + 2);

}
Output:
This is my first program
This is my second line
This is my third line
Last line
8 + 2
10

Assignment:
WAP to print the addition, substraction ,
multiplication and division of two numbers
Solution:
public static void main(String[] args) {

System.out.println(8 + 2);

System.out.println(8 - 2);

System.out.println(8 * 2);

System.out.println(8 / 2);

Output:
10
6
16
4
To execute the code we have following ways:
1. Click on green button.

2. Right click inside the class – Run As – Java


Application

3. Press Control+f11
Data Type: In java every single data that we
are defining must have some type that is
called as Data Type.
There are 2 categories of data type in java:

Integral datatype:
1. byte : The size of byte data type is 1 byte
Range of byte is : -128 to 127 / -27 to 27-1
Example:
public static void main(String[] args) {

// datatype variablename = value;

byte b = 10;
byte b2 = 127;
byte b4 = -128;
System.out.println(b);

Output:
10

Note: The maximum value and


minimum value of byte is +127 and
-128 respectively so that we
cannot define the max value beyond
127 and we cannot define minimum
value less than -128 otherwise we
will get an error.

2. short: The size of short data type is 2


byte
Range of short
-32768 to 32767 / -215 to 215-1

Example:
short s = 10;
System.out.println(s);

short s1 = 32767;

short s2 = -32768;

System.out.println(s2);// -32768

3. int: The size of int data type is 4 byte


Range of int
-2147483648 to 2147483647 / -231 to 231-1

Example:

int i = 500;

int i1 = 2147483647;

int i2 = -2147483648;

System.out.println(i2);// -2147483648

4. long: The size of long data type is 8 bytes


Range of long
-263 to 263-1
Note: Whenever we define long value then as
a suffix we have to add l to the value.

Example:
long data type

long l = 645454664546l;

long l1 = -323123123213213l;

System.out.println(l);

Output:
645454664546

Floating point data type:


1. float : The size of float data type is 4 bytes
The max and minimum number we can define
using float is:
Min: 1.4 x 10-45
Max: 3.4 x 1038
Note: While defining the float value we have to write f as a suffix to it.

Example:

float f = 56.23f;

System.out.println(f);

Output:
56.23

2. double: The size of double data type is 8


bytes
The max and minimum number we can define
using double is:

Min: 4.9 x 10-324


Max: 1.7 x 10308

Example:
double d = 66656.6565;

System.out.println(d);

Output:
66656.6565

Note:
In terms of popularity we prefer int from the
integral and double from floating point data type
to use in daily programming operations.

Non numeric data type:


1. Char : The size of character is 2 bytes in which
we can represent 65536 number of values using char
data type.
To define the character we have to use ‘’ only. And
we can define only one value inside ‘’ otherwise we
will get error.
Example:
public static void main(String[] args) {
char c = 'q';

char variable = '5';

char r = '&';

char g = '6';

char w = '%';

char q = ' ';

System.out.println(variable);

Output:
5

Boolean: This is a data type whose size is not


applicable as the value which can be accommodated
inside the Boolean is keywords.
The only value which is applicable to Boolean are
true and false.

Example:

boolean b = false;

boolean g1 = false;

boolean c1 = false;

System.out.println(g1);
Output: false

Non Primitive data type: The data type whose size


is not fixed that means as we try to put the data
it will accommodate the same by expanding or
contracting the memory is called as Non primitive
data type.
Example:
String class is non primitive data type.
Rule for String:
1. Whenever we type + with the String and then we
write any value it will get concatenated / merge /
join with that value.
Example:
String s1 = "Velocity";

String s2 = "Corporate";

System.out.println(s1+s2);//VelocityCorporate

System.out.println(s1+" "+s2);
//Velocity Corporate

2. Any operation we perform with the String


will give String as an output.
String s1 = "Velocity";

String s2 = "Corporate";

System.out.println(s1+' '+2);//Velocity 2

System.out.println(s1+2+3);//Velocity23

System.out.println(2+3+s2);//5Corporate

Assignment: WAP to print the output as:


The addition of 1 and 5 is 6

Rule to evaluate when we have =


Method : It is an entity which defines the logic
to get execute when we called it is called as
method.
There are 2 types of method:
1. Regular method
2. main method

1. Regular method: It is a type of method


which has two sub type:
a. static method
b. non static method
a. static method: A method in which we use
static keyword to define the static method is
called as static method.
// static method syntax:

// public static void name_of_method()


// {

// }

Generic Syntax of static method:

Components of static method:

Rules for static method:


1. We can call the static method by directly method
name or classname.methodname when it is inside the
same class (static method and calling method is
inside the same class).
2. We can call the static method into another class
by classname.methodname.

public static void printHello()


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

public static void main(String[] args) {

printHello();

printHello();

System.out.println("this is my test
class");

printHello();

}
Output:
Hello
Hello
Hello
Hello
this is my test class
Hello
Hello
public static void addition()
{
int a = 10;

int b = 20;

int c = a+b;

System.out.println(c);
}

public static void substraction()


{
int d = 10;

int e = 10;

int f = e-d;

System.out.println(f);
}

public static void multiplication()


{
int g = 10;

int h = 20;

int i = h*g;

System.out.println(i);
}

public static void division()


{
int j= 10;

int k = 10;

int l = j/k;

System.out.println(l);
}

public static void main(String[] args) {

// multiplication

multiplication();//200

// Addition

addition();//30

// substraction

substraction();//0

// division

division();//1

Output:
200
30
0
1
2. Non static method: The method in which we
don’t write any specific keyword for non static is
called as non static method.
Syntax:
public void name_of_method()
{
}

Generic syntax:

Rules:
1. To call the non static method we have to
create an object of the same class
compulsorily then on the basis of reference
variable of that object we can call the non
static method.
2. We cannot call non static method without
creating object whether it is in the same class
or different class.
3. We have to create the object of only that
class whose non static method we are going
to call.
4. One object can be used to call multiple
methods or we can have multiple objects to
call multiple method.

Example:
public class NonStaticMethod {

public void areaCalulator()


{
int length = 50;

int breadth = 10;

int area = length*breadth;

System.out.println("Area is "+area);

public void uniqueIDGenerator()


{
String name = "Daniel";

String id = name+"01";

System.out.println(id);

public static void main(String[] args) {

// Creation of object

// syntax - > classname variablename = new


Classname();

NonStaticMethod nsm = new


NonStaticMethod();

nsm.areaCalulator();

nsm.areaCalulator();

nsm.uniqueIDGenerator();

NonStaticMethod obj1 = new


NonStaticMethod();

obj1.areaCalulator();

obj1.uniqueIDGenerator();

}
Output:
Area is 500
Area is 500
Daniel01
Area is 500
Daniel01

Calling of non static method in another


class:

public class NonStaticMethod {

public void areaCalulator()


{
int length = 50;

int breadth = 10;

int area = length*breadth;

System.out.println("Area is "+area);

public void uniqueIDGenerator()


{
String name = "Daniel";

String id = name+"01";

System.out.println(id);

public class Test {


public static void main(String[] args) {

NonStaticMethod nsm = new NonStaticMethod();

nsm.areaCalulator();

nsm.uniqueIDGenerator();

Output:
Area is 500
Daniel01

Summary for Static and non static method:


Process of Execution of program:

1. start jvm
2. locate the .class file
3. load the .class file— static content
memory allocation
4. Execution of main method – Non static
content memory allocation and
de-allocation
5. unload the .class file – static
content memory de-allocation

6. shutdown of jvm.
Difference between Static and non static
method:

Sr.no Static method Non static method


1 It requires static It requires no
keyword to define. specific keyword to
define.
2 To call the static To call the non
method we should static method
write compulsorily we have
classname.methodname to create an object
/ method name if then we will be able
inside the same to call.
class.
3 Memory allocation of Memory allocation and
static is done at de-allocation of non-
the time of class static is done at the
loading whereas de- time of execution
allocation happens only.
at the time of class
unloading.
4 We don’t require to We cannot call non
create object for static method without
calling static object.
method

Note: We can call the static method by using


object but that is not recommendable to use.

2. main method: The method through without


which we cannot execute our program is
called as main method. It is a method which is
configured inside the jvm so that we are able
to execute it through class.

Main method is always static, Reason –


Because static content always gets memory
allocation at the time of class loading hence
main method is a method which must have
the memory then only it would be able to get
execute.

Questions specific to method:


1. Explain the type of method?
2. What is static method?
3. What is non static method?
4. What is the difference between static and
non static method?
5. Explain when can we use static and non
static and why?
Variables in java:
Variable: It is an entity which has the quality
to hold the properties of the object. It is used
to define the characteristics of an object.
There are 3 types of variable:
a. static variable
b. non static variable
c. local variable

a. static variable: The variable which we


define by using static keyword is called as
Static variable.
Static variable is also called as class level
variable.
These variable are only defined at the class
level i.e outside any method / block.
Rules:
1. We can only define the static variable at class level.
2. To call the static variable :
a. inside the same class: By classname.variablename /
directly variablename.
b. Outside the class: By classname.variablename.

Example:
public class A {

// Here we are discussing static variable

// syntax of static variable

// static data_type variable_name = value;

static int a = 50;

static boolean bol = true;

static String s = "Velocity";

public static void main(String[] args) {

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

int u = a+5;

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

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

System.out.println(a+s);//50Velocity

a = u;

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

}
}

Output:
50
55
50
50Velocity
55

public class VariableTest {

public static void main(String[] args) {

// calling of static variable

System.out.println(A.a);

System.out.println(A.bol);

}
Output:
50
True

Example for division:


public class Test2 {

static double a = 10;

static double b = 3;

static double c = 0;

public static void main(String[] args) {

c = a/b;

System.out.println(c);

}
Output:
3.33333333335

2. Non static variable: The variable


which always defined at the class level
and to define that variable compulsorily
we have to create the object and on that
basis we can call it.

Rule:
1. To call the non static method either
inside the same class or different class
we have to create the object then we can
call it.
2. We don’t define non static variable
inside any method we will only be able to
define the non static variable at class
level hence it is also called as Class
level variable.

Syntax:
// non static variable

// syntax: - data_type
variable_name = value;

Example:
public class B {

// non static variable

// syntax: - data_type variable_name = value;

String s = "abc";

double d = 56.23;

public static void main(String[]


args) {

B b = new B();

System.out.println(b.s);//abc

System.out.println(b.d);// 56.23

B b1 = new B();

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

Output:
abc
56.23
Abc

Calling of non static variable inside another


class:

public class B {

// non static variable

// syntax: - data_type variable_name = value;

String s = "abc";

double d = 56.23;

public class VariableTest {

public static void main(String[] args) {


// calling of non static variable

B b = new B();

System.out.println(b.s);//abc

String e = b.s+"def";

System.out.println(e);//abcdef
}

Output:

abc
abcdef

public class C {

// difference between static variable and non


static variable

// WAP to calculate the area of a land using only


non static variable

int length = 50;

int breadth = 10;

public static void main(String[] args) {

C c = new C();

int area = c.length * c.breadth;

System.out.println(area);

}
Some very important rules for Static and
non static:
Non Static:
1. Non static variable value gets change
with respect to object to object that is
it can varies from object to object.
Example:
public class D {

int i = 50;

static int j = 20;

int k = 60;

String s = "Daniel";

public static void main(String[] args) {

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

D d1 = new D();

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

System.out.println(d1.j);//20

j = 60;

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

d1.i = 30;
System.out.println(d1.i);//30

D d2 = new D();

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

System.out.println(d1.i);//30

D d3 = new D();

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

d2.i = 80;

System.out.println(d1.i);//30

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

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

d1.i = 50;

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

System.out.println(d1.s);//Daniel

d2.s = "Eder";

System.out.println(d2.s);//Eder

d3.s = "Ron";

System.out.println(d3.s);//Ron

}
2. Static variable: The value of static
variable doesn’t get change from object
to object it remains same for all the
objects. Also it shares its value with
all objects.

Assignment: WAP to store the data of


college students in terms of Student
name, Physics marks, classname.

Solution:
public class College {

String name = " ";

int physicsmarks = 0;

static String classyear =" ";

public static void main(String[] args) {

College s1 = new College();

s1.name = "Daniel";
s1.physicsmarks = 50;
classyear = "Ist year";

College s2 = new College();

s2.name = "Eder";

s2.physicsmarks = 60;

System.out.println(s2.name +" : " +


s2.physicsmarks);

Output:
Eder : 60
Difference between static and non-static variable:
Sr. Static variable Non static variable
no
1. Variable which get Variable which get
define using static define without using
keyword any specific
variable.
2. Value of static Value of non-static
variable doesn’t get variable get change
change with respect with respect to
to object. It share object.
its value between
every object.
3. To call the static To call non static
variable we don’t variable we have to
create the object create the object
compulsorily.
4. Memory allocation for Memory allocation
static variable gets for non-static
done at the time of variable gets done
class loading. at the time of
execution.

Note: Both static and non - static variable are


also called as Class level variable and Global
variable because those are defined at class level.

Default value: Whenever we don’t


assign / initialize any variable and
that is defined at class level then
default value gets stored inside the
variable. Default value is a value
which get store when we don’t assign
it.
Every data type has different default
value.
Example:
String – null
Int --- 0
Double – 0.0
Char – <space>
Boolean – false
public class DefaultValues {

// definition of variable
static String s;

int i;

static double d;

char c;

boolean b;

public static void main(String[] args) {

System.out.println(s);//null

DefaultValues dv = new DefaultValues();


System.out.println(dv.i);//0

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

System.out.println(dv.c);// <space>

System.out.println(dv.b);//false
}

}
3. local variable: The variable which we
define except class level is called as
local variable.
The scope / accessibility of local
variable can only be done inside the
curley braces in which we have defined
it. Beyond the curley braces where we
have defined local variable will not be
accessible.
Syntax: datatype variable_name = value

Example:
public class LocalVariable {

public static void main(String[] args) {

// Local variable
// syntax: datatype variable_name = value

int i = 50;

String s = "hello";

char c ='v';

System.out.println(c);

System.out.println();
}

Note in the above main method variable i, s and c


are local variable which can only be accessible
within the curley braces ({}) of main method

public static void m1()


{
int j = 20;

System.out.println(j);

public void m2()


{
int k = 30;

System.out.println(k);
}

Default value concept will not be applicable


for local variable that means before using of
local variable we have to compulsorily
initialize it.

If any of the variable specific to only a


single method then we should use local
variable.
Example:
Example to represent all 3 types of variable:
public class LocalVariable {

static int i = 70; // static variable

int j = 60; // non static variable

public static void main(String[] args) {


// Local variable
// syntax: datatype variable_name = value

int i = 50;// local variable

String s = "hello";// local variable

char c ='v'; // local variable

System.out.println(c);

System.out.println(i);
}

public static void m1()


{
int j = 20; // local variable

int i = 90; // local variable

System.out.println(i);
System.out.println(j);
}
public void m2()
{
int k = 30; // local variable

System.out.println(k);
}

Question:
Q1. Define Variable.
Q2. Types of variable
Q3. Difference between Static non static and
local variable?
Q4. How do you decide whether we should use
static , non static or local variable.

this keyword: It is a keyword which is


used to access the global variable inside
only in non-static area(non-static
method, constructor etc).
We cannot use this keyword inside static
area.
Example:
public class ThisKeyword {

int i = 10;

static String s = "abc";

public void m1()


{
int i = 20;

System.out.println(i);

System.out.println(this.i);

If we try to access the global variable


inside the static area then we will get
an error.

Calling of method into another method


1. Calling of static method inside
another static method.
2. Calling of static method inside non
static method
3. Calling of non-static method inside
static method
4. Calling of non-static method inside
another non static method.

1. Calling of static into another static:


Example
public static void m1()
{
System.out.println("m1 method is
executing");
}

public static void m2()


{
CallingOfStaticMethods.m1();

System.out.println("m2 method is
executing");
}

public static void main(String[] args) {

m2();

}
Output:
m1 method is executing
m2 method is executing

2. Calling of static method inside non


static method
public class CallingOfStaticMethods {

public static void m1()


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

public void m3()


{
m1();
}

3. Calling of non-static method inside


static method
Example:
public class CallingOfNonStaticMethod {

public void m1()


{
System.out.println("m1 is executing");
}

public static void m2()


{
CallingOfNonStaticMethod cons = new
CallingOfNonStaticMethod();
cons.m1();
}

public static void main(String[] args) {


m2();
}

4. Calling of non-static another non static method:


To call the non static method into another non
static method:
a. Both methods are inside the same class: We don’t
have to create the object to call the non static
into another non static which are inside the same
class.
b. Both methods are not inside the same class: We
have to compulsorily create the object to call the
method.
Example for the same class:
public class A {

// Calling non static into another non static

public void m1()


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

public void m2()


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

public static void main(String[] args) {

A a = new A();

a.m2();

Example for different class:


public class A {

// Calling non static into another non static

public void m1()


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

public void m2()


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

public class B {

public void m3()


{
A a = new A();

a.m2();
}

Categories of method:
There are 4 categories of method
1. Method with no return type and no argument.
2. Method with no return type and with argument
3. Method with return type and without argument
4. Method with return type and with argument

Method definition:
1. Method with no return and no argument:
Example:
public class NoReturnNoArgument {

public static void m1()


{

System.out.println("method with no return


and no argument");
}

public static void main(String[] args) {


m1();
}

2. Method with no return type and with argument: In


this we can execute the method with different set of
inputs and generate the corresponding output.
Example:
public class NoReturnWithArg {

public void m1(String s, int i, int j)


{
System.out.println(s);//velocity

System.out.println(i);//56
System.out.println(j);//78
}

public static void sum(int i, int j)


{
int k = i+j;

System.out.println(k);

public static void main(String[] args) {

NoReturnWithArg nrwa= new


NoReturnWithArg();

nrwa.m1("Velocity", 56, 78);

nrwa.m1("Ron", 20, 15);

sum(2,3);//5

sum(120, 30);//150

// WAP to define the calculator which can perform


any operation with multiple set of data

3. Method with return type and without argument:


In this method first the logic available inside the
method get execute then after the value which we are
returning will replace the method name where we are
calling it.
Example:
public static int m1()
{
int i = 10;
int j = 20;
int k = i+j;

System.out.println(k);

return 100;
}

public static void main(String[] args) {


int f = m1();

System.out.println(f);//100
}
Output:
30
100
Example:
public static String m2()
{
int roll = 20;

String studentid = "COEP"+roll;

return studentid;
}

public static void main(String[] args) {

String s = m2();
System.out.println(s);
}

4. . Method with return type and with argument:


This method will take the arguments to execute the
logic and generate the result also it will provide the
return value at the place where we have called the
method.
Example:
public static String calc(int a, String b)
{
String d = a+b;

return d;
}
public static void main(String[] args) {

String uidname = calc(80, "John");

String s = uidname+"california";

System.out.println(s);//80JohnCalifornia

Example 2:
public static String calc(int a, String b)
{
String d = a+b;

return d;
}

public void finalOutput(String s)


{
String finalvalue = s+"State";

System.out.println(finalvalue);
}
public static void main(String[] args) {

String uidname = calc(80, "John");

String s = uidname+"california";

System.out.println(s);//80JohnCalifornia

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

WithReturnWithArgument wrwa = new WithReturnWithArgument();

wrwa.finalOutput(s);// 80JohncaliforniaState

Assignment:
Solution:
public class FarmerLandCalculation {

public int areaCalculator(int length, int


breadth)
{
int area = length * breadth;

return area;
}

public static void main(String[] args) {

FarmerLandCalculation flc = new


FarmerLandCalculation();

int area1 = flc.areaCalculator(50, 30);

int area2 = flc.areaCalculator(20, 60);

int area3 = flc.areaCalculator(10, 80);

int totalarea = area1 + area2 + area3;


System.out.println("total area
is :"+totalarea);

}
Output:
total area is :3500

Assignment 2:
WAP to generate the output in following manner

Solution:
public static int m1()
{
int a =5+3;

return a;
}

public void m2(int b)


{
int c= b+2;

System.out.println(c);
}
public static void main(String[] args) {

int y = m1();

OutputOfOneIsInputToOther refvar = new


OutputOfOneIsInputToOther();

refvar.m2(y);

}
Output:
10

Conditional Statements:
The statements which are executed based
on some condition are called as
conditional statements.
Example:
If –else, if – elseif – else.
Syntax:
// syntax:
//
// if(boolean_condition)
// {
//// actions to get execute
// }
// else {
//// action to get execute if condition is false
// }

Note : Here if body will only be execute when if


condition gets true otherwise it will execute the
else body.
Example:

int a = 10;
int b = 20;

if(a<b)
{
System.out.println("a is greater than
b");
}
else
{
System.out.println("condition is
false");
}

Output:
a is greater than b

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

int a = 10;

int b = 20;
int k = 0;

if(a>60)
{
k = 30;
System.out.println(k);
}
else
{
System.out.println(k);
}

}
}

Output:
0

Note: If we define any variable inside the conditional


statements (if / else) then its scope will also become
within the block only. We will not be able to access
those variables in other part of the program except the
{} inside which we have defined those.
Else – if statement:
// syntax:

// if(boolean_condition1)
// {
// // will execute if condition1 gets true
// }
//
// else if (boolean_condition2) {
//
// // will execute if condition2 gets true
//
// }
//
// else if (boolean_condition3) {
//
// // will execute if condition3 gets true
//
// }
// else
// {
//// when no condition gets match
//

Example:
int a = 20;

int b = 30;

if(a>30)
{
System.out.println("a is greater than
30");
}

else if(b<20)
{
System.out.println("b is less than
20");
}
else if(a>15)
{
System.out.println("a is greater than
15");
}

else if(b>15)
{
System.out.println("b is greater than
15");
}

else
{
System.out.println("Else is executing
hence no match");
}

Output:
a is greater than 15

Assignment:
1. WAP to get the square and cube of a number?
Operators :
1. Arithmetic operator:
a. addition - +
b. substraction - -
c. multiplication *
d. division - /
e. modulus - %
Example:
int i =10;

int j = 2;

int l = 10%3;

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

Modulus is an operator which returns the


remainder of division

2. Conditional operator:
// greater than---> >

int a = 50;

int b = 20;

boolean c = a>b;
System.out.println(c);//true

// greater than or equal to---> >=

boolean d = b>=a;

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

boolean e = b>=20;

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

// Less than---> <

boolean f = a<60;

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

// Less than or equal to---> <=

boolean g = b<=a;
System.out.println(g);//true

// equals operator

boolean h = b==20;
System.out.println(h);//true

3. Logical operator: The operator which works on


Boolean principles are called as logical operator.
AND NOT
X Y Z
FALS FALS
FALSE E E TRUE FALSE
FALS
FALSE TRUE E FALSE TRUE
TRUE FALS FALS
E E
TRU
TRUE TRUE E

OR
X Y Z
FALS FALS
FALSE E E
TRU
FALSE TRUE E
FALS TRU
TRUE E E
TRU
TRUE TRUE E

a. AND operator (&&): It is an operator which is


used to compare two values by logical AND.
int a = 50;

int b = 60;

// Logical AND Operator

boolean c = a>50 && b==60;

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

boolean d = b==60 && a==50;

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

// Logical OR Operator

boolean e = a>50 || b==60;

System.out.println(e);//true
// Logical NOT Operator
boolean f = false;

boolean g = !f;

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

boolean h = a!=60;

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

boolean i = !(b==60);

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

}
Assignments:
Even / odd:
public static void main(String[] args) {
int a = 13;

int b = a%2;

boolean s = b==0;

if(s)
{
System.out.println(a+" is an even
number");
}
else
{
System.out.println(a+" is an odd
number");
}
}

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

int a = 18;

if(a>0 && a<=20)


{
System.out.println("number is between 0
and 20.");
}
else if(a>20 && a<=40)
{
System.out.println("number is between
21 and 40.");
}
else if(a>40 && a<=60)
{
System.out.println("number is between
41 and 60.");
}
else
{
System.out.println("number is out of
range");
}

}
initial value of final value of
Expression x value of y x
y = ++x; 10 11 11
y = x++; 10 10 11
y = --x; 10 9 9
y = x--; 10 10 9

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

int x = 10;

int y = ++x;

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

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

int w = 10;

int v = w++;
System.out.println("w value is :"+w);//11
System.out.println("v value is :"+v);//10

int t = 10;

int u = --t;

System.out.println("t value is :"+t);//9


System.out.println("u value is :"+u);//9

int r = 10;

int s = r--;

System.out.println("r value is :"+r);//9


System.out.println("s value is :"+s);//10

Loops: It is a way through which we can execute a


certain set of code multiple times as per our
requirement.
There are 3 types of loops:
1. while loop
2. do while loop
3. for loop
1. while loop:
public static void main(String[] args) {

// syntax:
//
// while(boolean_condition)
// {
// actions
// }

int a = 10;

while (a<15)
{
System.out.println("Hello");

a++;

Output:
Hello
Hello
Hello
Hello
Hello

WAP to print the table of 2 until 20 count:


public static void main(String[] args) {

int number = 2;
int multipliedvalue = 1;

while(multipliedvalue<=20)
{
int value = number *multipliedvalue;

System.out.println(number+" x
"+multipliedvalue+" = "+value);

multipliedvalue++;

}
Output:
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
2 x 4 = 8
2 x 5 = 10
2 x 6 = 12
2 x 7 = 14
2 x 8 = 16
2 x 9 = 18
2 x 10 = 20
2 x 11 = 22
2 x 12 = 24
2 x 13 = 26
2 x 14 = 28
2 x 15 = 30
2 x 16 = 32
2 x 17 = 34
2 x 18 = 36
2 x 19 = 38
2 x 20 = 40

2. do – while loop: A loop in which we want the


actions to get execute atleast once then we should
go for do-while loop.
// syntax:
// do
// {
// actions to be executed
// }
// while(boolean_condition);
Example:

do
{
System.out.println("hello");
}
while(10<5);

Output:
Hello

3. for loop:
// syntax:
// 1 2, 5, 8 4, 7
// for(any_java_statement; boolean_condition; any_java_statement)
// { 3, 6, 9
// actions to be executed
// }

public static void main(String[] args) {


int a= 5;

for(System.out.println("starting the
loop"); a<10; a++ )
{
System.out.println("executing the for
loop");
}
}

}
Output:
starting the loop
executing the for loop
executing the for loop
executing the for loop
executing the for loop
executing the for loop

Note : We can understand the sequence of execution


using the syntax.

Assignment:
WAP to print - ***** using single star
Solution
for(int i=1; i<=5; i++)
{
System.out.print("*");
}
Line change concept

public static void main(String[] args) {


System.out.print("a");

System.out.println("a");

System.out.println("b");
}
Output:
aa
b

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

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


{
if(i%2==0)
{
System.out.println(i);
}

}
Output:
0
2
4
6
8
10

Odd
public static void main(String[] args) {

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


{
if(i%2==0)
{

}
else
{
System.out.println(i);
}
}

Output:
1
3
5
7
9

Assignment Solution:
Factorial:
public static void main(String[] args) {
int number = 5;

int factorial = 1;

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


{
factorial= i*factorial;
}

System.out.println(factorial);

}
Output:
120

Steps to debug a program:


1. Apply the starting breakingpoint and ending
breaking point.
2. After applying debug points execute the
program using DebugAs java application.

3. Click on switch window:


4. Click on the button to execute in step by step
manner.

public static void main(String[] args) {

// WAP to print first 1000 numbers which can


get completely divide by 4--> While loop
int count =0;

int number = 1;

while(count <=1000)
{
if(number%4==0)
{
System.out.println(number);
count++;
}

number++;

WAP to print
*****
*****
*****
*****

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:

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

Logic to create the pattern


Step 1
I/J 1 2 3 4 5
1 *
2 * *
3 * * *
4 * * * *
5 * * * * *

Step 2
I J
1 1
2 1, 2
3 1, 2, 3
4 1, 2, 3, 4
5 1, 2, 3, 4, 5

Step 3 I J
1 J>=1 && J<=1
2 J>=1&& J<=2
3 J>=1 && J<=3
4 J>=1 && J<=4
5 J>=1 && J<=5
Step 4 I J
1
2
3 J>=1 && J<=I
4
5

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

public static void main(String[] args) {

for(int i=1; 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:
*
**
***
****

Pattern to practice:
*
* *
* * *
* * * *
* * * * *

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

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

* * * * *
* * * *
* * *
* *
*
Pattern 2
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:
*
**
***
****
*****

Constructor: It is a special block which always gets


execute whenever we are executing an object.
OR
It is a block which always get executes whenever
we creates an object.
Syntax:
// syntax of constructor-

// access_modifier classname()
// {
// actions to be performed
// }

Example:

public class Test {

public Test()
{
System.out.println("Hello I am
constructor");
}

public static void main(String[] args) {

Test t = new Test();

}
Output:
Hello I am constructor

Rules of constructor:
1. Constructor name and class name must be same.
2. Constructor cannot have a return type that means
we cannot even write void, any data type as well.
3. Whenever we creates an object automatically
constructor gets execute.
4. We can have multiple constructor inside a class.
5. Constructor can take arguments.
6. We can call only one constructor inside an
another constructor if we try to call multiple then
we will get an error.
Example:
public class B {

// Calling of one constructor into another one

public B()
{
this("hello");
this (45.58, false);// this is not valid as
we can call only one constructor inside another and
that too in first line of the constructor only.
System.out.println("Zero argument
constructor");

}
public B(String s)
{
System.out.println("one argument
constructor");
}

public B(double d, boolean f)


{
System.out.println("two argument
constructor");
}

7. Constructor call must be at the first line only.


If we try to call it at any line other than first
of constructor then we get an error.

Example:
public class A {

// Calling of one constructor into another one

public A()
{

System.out.println("Zero argument
constructor");
this("hello");// this is not valid as we
are calling the constructor at other than 1 line

public A(String s)
{
System.out.println("one argument
constructor");
}

public A(double d, boolean f)


{
System.out.println("two argument
constructor");
}

Types of constructor:
1. Default constructor
2. User defined constructor

1. default constructor: Whenever we don’t have any


constructor inside the class then jvm will
automatically creates the constructor which is
called as default constructor.
Default constructor body is empty which means it
doesn’t have any code in it.

2. User defined constructor: The constructor which


is defined by the user then that constructor is
called as user defined constructor.

public Test()
{
System.out.println("Hello I am
constructor");
}

Use of constructor:
1. Whenever we wants to execute something right
after the creation of object then we use
constructor.
OR
Whenever we wants a business logic to get execute
on the creation of object we need a constructor.

2. It is used to store the value inside the


variables
OR
It is used to initialize the data members

Example:
public class Student {

String name;

int physicsmarks;

static String classyear;

public Student(String studentname, int


phymarks)
{
name = studentname;

physicsmarks= phymarks;
}

public static void main(String[] args) {

classyear = "firstyear";

Student s1 = new Student("Cesar", 50);

Student s2 = new Student("Diana", 90);

System.out.println(s2.physicsmarks);

Output:
90
Note: Majorly constructor is used to initialize the
data members in most of the cases.

Example 2 using this keyword:


public class Student {

String name;

int physicsmarks;

static String classyear;

public Student(String name, int physicsmarks)


{
this.name = name;

this.physicsmarks= physicsmarks;
}

public static void main(String[] args) {

classyear = "firstyear";

Student s1 = new Student("Cesar", 50);

Student s2 = new Student("Diana", 90);

System.out.println(s2.physicsmarks);

}
Output:
90

Constructor with Arguments:


We can have multiple argument for a constructor:
Example:
public class Test {

// syntax of constructor-

// access_modifier classname()
// {
// actions to be performed
// }

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

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

public Test(int i, String s)


{
System.out.println("two argument
constructor");
}

public static void main(String[] args) {

Test t = new Test();

Test t1 = new Test();

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

Test t2 = new Test(90, "stringvalue");

Output:
zero argument constructor
zero argument constructor
**************************************
two argument constructor

Calling of one constructor into


another one:
Example:
// Calling of one constructor into another one

public A()
{
this(56.23,true );// calling of two argument constructor
System.out.println("Zero argument constructor");
}

public A(String s)
{
System.out.println("one argument constructor");
}

public A(double d, boolean f)


{
System.out.println("two argument constructor");
}

public static void main(String[] args) {

A a = new A();

}
Output:
two argument constructor
Zero argument constructor

Example 3:
public class C {

public C()
{
this("Pune");
System.out.println("Zero argument
constructor");

public C(String s)
{
this(89.56, false);
System.out.println("one argument
constructor");
}

public C(double d, boolean f)


{
System.out.println("two argument
constructor");
}

public static void main(String[] args) {

C c = new C();

Output:
two argument constructor
one argument constructor
Zero argument constructor

Questions:
Define constructor and usage.
Elaborate more about the constructor

OOPs concepts
Definition: Full form of OOPs is Object oriented
Programming concepts it is the way to optimize the
code using different concepts those are representing
oops.

Inheritance:

Definition: Inheritance is an oops concept which says


we can access all the properties of a class(Super class /
parent class) into another class(Sub class / child class)
directly when we have written extends keyword after
defining the child class.
To perform the inheritance we have to use extends
keyword after class name of child class and write the
name of parent class.
It doesn’t matter whether the child / parent class in
inside the same package or different package we can
follow the inheritance.
Example:
public class Parent {

public void home()


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

public void furniture()


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

public void car()


{
System.out.println("car method from parent
class");
}
public static void surname()
{
System.out.println("surname method from
parent class");
}

public class Child extends Parent


{

public void bike()


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

public static void main(String[] args) {

Child c = new Child();

c.home();

c.car();

c.furniture();

surname();

c.bike();

}
}

Output:
Home method from parent class
car method from parent class
furniture method from parent class
surname method from parent class
Bike method from child class

Rules of inheritance:
1. We can have the inheritance only in one direction
but not in other direction.
2. A parent class / super class can have multiple child
classes but opposite part of it is not possible.
Example:
public class Parent {

public void home()


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

public void furniture()


{
System.out.println("furniture method from
parent class");
}
public void car()
{
System.out.println("car method from parent
class");
}

public static void surname()


{
System.out.println("surname method from
parent class");
}
public class Child extends Parent
{

public void bike()


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

public class Child2 extends Parent


{

public static void main(String[] args) {

surname();

Child2 c2 = new Child2();

c2.home();

c2.furniture();

c2.car();

}
}
Output when we execute Child2
surname method from parent class
Home method from parent class
furniture method from parent class
car method from parent class

3. Type of inheritance : There are 2 types of


inheritance:-
a. Single level inheritance: In this we have only one
layer of parent and child combination is present.

b. Multilevel inheritance: When we have more than


one layer inheritance then it is called as multilevel
inheritance.
Example:
public class GrandParent {

public void farm()


{
System.out.println("Farm method from
Grandparent class");
}

}
public class Parent extends GrandParent
{

public void home()


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

public void furniture()


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

public void car()


{
System.out.println("car method from parent
class");
}

public static void surname()


{
System.out.println("surname method from
parent class");
}
public class Child extends Parent
{

public void bike()


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

public static void main(String[] args) {

Child c = new Child();

c.home();//parent class method

c.car();//parent class method


c.furniture();//parent class method

surname();// parent class method

c.bike();// child class method

c.farm();//grandparent classs method

Multiple inheritance: When we have more than one


class as a parent class of a child class then that
combination is called as Multiple inheritance.
Note: For a java class multiple inheritance is not
possible.
Multiple inheritance: When we are trying to extends
multiple classes (2 or more than 2) to another class
then it will throw an error which gets invalid.
We cannot extend more than one class at a time. This
is called as multiple inheritance.
Due to the multiple inheritance we have observed an
issue diamond ambiguity.

Diamond ambiguity : When we have same name of


method available in two different independent classes
and we have extended those two classes using another
class then compiler may get confuse to call which
method if the parent classes has the same name of
methods in it that’s why we don’t allow to create
multiple parent class of a child class.
Has a Relationship: Whenever we access the methods
of another class by creating object of it then it
represents HAS a relationship.
2. IS a relationship: Whenever we are accessing the
methods of one class to another class by extending it
then it represents IS a relationship

Note : Inheritance is required to get the repeatability


inside the code so that we don’t have to define the
method multiple times inside a class if we have some
common feature then we should define it somewhere
and access through inheritance.
Inheritance for Variable:
We can access the variables inside the child class same
as methods if two classes are following inheritance
principle.
Example:
public class A {

int a = 10;
String b = "Pune";

static String d = "Mumbai";


}
public class B extends A{

int c = 50;

public static void main(String[] args) {

B b = new B();

System.out.println(b.a);

System.out.println(b.c);

System.out.println(d);
}

Output:
10
50
Mumbai
Super keyword: It is a keyword which is used to access
the global variable from the parent class inside the
child class non static area.
Example:
public class A {

int a = 10;
String b = "Pune";

static String d = "Mumbai";


String city = "Uri";
static String country = "USA";

}
public class B extends A{

int c = 50;

int a = 90;

String city = "Delhi";

static String country ="India";

public void m1()


{
System.out.println("value of a without
super keyword = "+a);//90
System.out.println("value of a with super
keyword = "+super.a);//10
System.out.println(country);//India
System.out.println(super.country);//USA

System.out.println(super.b);// Pune
}

public void m2()


{
System.out.println(city);//Delhi
System.out.println(super.city);//Uri
}

public static void main(String[] args) {

B b = new B();

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

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

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

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

}
Output:
90
50
Mumbai
value of a without super keyword = 90
value of a with super keyword = 10
India
USA
Pune
Delhi
Uri
Constructor with respect to inheritance:
Child Constructor by default call the parent class
constructor but constructor doesn’t follow inheritance.
Example when child class constructor is able to call
parent:
public class DCons {

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

}
public class ECons extends DCons
{
public ECons()
{
System.out.println("ECons one argument
constructor");
}

public static void main(String[] args) {

ECons ec = new ECons();

}
}
Output:
DCons zero argument constructor
ECons zero argument constructor

Example: Constructor is not able to call the parent


class constructor:
public class DCons {

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

}
public class ECons extends DCons
{
public ECons(int i)
{
System.out.println("ECons one argument
constructor");
}

public static void main(String[] args) {

ECons ec = new ECons(80);

}
}
Output:
DCons zero argument constructor
ECons one argument constructor

In the above example 2 if we don’t provide the one


argument object then child class object will give an
error to resolve the same we have to provide the value
of argument inside the object. But by default that
object without argument will not be able to access the
parent class constructor.
Hence constructor is not following inheritance.

Zero argument constructor from parent class can


directly be called from Child class but if we have any
argument based constructor inside the parent class
then to call that constructor we have to define the
argument value using “super()” inside the first line as
we can only call the constructor at first line.
Example:
public class DCons {
public DCons(int a)
{

System.out.println(a);
System.out.println("DCons one argument
constructor");
}

}public class ECons extends DCons


{
public ECons(int i)
{
super(40);
System.out.println("ECons one argument
constructor");
}

public static void main(String[] args) {

ECons ec = new ECons(80);

Output:
40
DCons one argument constructor
ECons one argument constructor
Questions:
1. Define the inheritance
2. Why it is required?
3. Types of inheritance?
4. Can we inherit variable as well using inheritance?
5. Explain constructor with respect to inheritance.

Solution:
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");
}
}

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");
}
}

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");
}
}

public class D extends E {

public void m9()


{
a.m1();
b.m5();
c.m7();

public void m10()


{
a.m3();
b.m6();

public static void main(String[] args) {

D d = new D();

d.m9();

d.m10();

}
public class E {

A a;

B b;

C c;
public E()
{
a = new A();

b = new B();

c = new C();
}
}
Output when we execute D class:
m1 method from A class
m5 method from B class
m7 method from C class
m3 method from A class
m6 method from B class

Access modifiers:
Definition:
It is a set of keywords which represents the entity(
variable, method, class etc) to be accessible at a
specific location based on the keywords.

There are different types of access modifiers


based on the type of entity:
1. Class level access modifiers:
a. public
b. <default>
c. final
d. abstract
a. public : If any of the class become public then it
will be accessible throughout the project (in all
package)
Example:

b. <default>: If we declare any class as default


then we will be able to access within the package
but not outside the package.

c. final: This is an access modifier which works


along with public or default but not alone.
If we declare a class as final then we will not be
able to create its child class.
Example: = final public class

Example 2 = <default> final class


final class Test3 {

2. Method / Variable level access modifiers:


There are 4 types of access modifiers:
a. public
b. <default>
c. private
d. protected

a. public: Whenever we declare the method /


variable as public then we will be able to access
that method / variable throughout the project
provided the class which contains the public
method / variable is also accessible at that
location.
Example:

b. <default> : Whenever we declare the method /


variable as <default> then we will be able to access
that method / variable within the package only
but not outside the package.
Example:

void m3()
{
System.out.println("default m3 non static
method from Test4 class");
}

static void m4()


{
System.out.println("default m4 static
method from Test4 class");
}
c. private: Whenever we declare any method / variable
as private then we will be able to access that method /
variable only within the class but not outside the class.
Example:

private void m5()


{
System.out.println("private m5 non static
method from Test4 class");
}

private static void m6()


{
System.out.println("private m6 static
method from Test4 class");
}

d. protected: Whenever we declare any


method / variable as protected then
for non static metod / variable:
within the package it will be act same as
<default> access modifier, but for outside
the package a method / variable can only be
accessible inside the child class using child
class reference variable only.
Example:
public class A {

// This class is used to discuss protected access


modifiers

protected void m9()


{
System.out.println("Protected non static m9
method from A class");
}

package accesstest;

import accessmodifiers.A;

public class B extends A{

public static void main(String[] args) {

A a = new A();

B b = new B();

b.m9();

}
Output:
Protected non static m9 method from A class

Example 2:

public class A {

// This class is used to discuss protected access


modifiers

protected void m9()


{
System.out.println("Protected non static m9
method from A class");
}

public class B extends A{

public static void main(String[] args) {

A a = new A();

B b = new B();

b.m9();

}
package accesstest;

public class C extends B


{

public static void main(String[] args) {

B b = new B();

// b.m9(); // this is not valid as m9 method


is protected from A class so can be accessible
through child class reference variable inside the
child class only.

C c =new C();

c.m9();// this is valid

Output:
Protected non static m9 method from A class

For static protected method: It will act same


as <default> access modifier but for outside
the package static method / variable can only
be accessible inside the Child class only by
directly variable name /
classname.variable_name
Example:
public class A {

// This class is used to discuss protected access


modifiers

protected static void m10()


{
System.out.println("Protected static m10
method from A class");
}

package accesstest;

import accessmodifiers.A;

public class B extends A{

public static void main(String[] args) {

A a = new A();

B b = new B();

b.m9();

A.m10();// static method from A class which


can be accessible only inside the child class for
outside the package

B.m10();// static method from A class which


can be accessible only inside the child class for
outside the package
}
package accesstest;

public class C extends B


{

public static void main(String[] args) {

B b = new B();

// b.m9(); // as m9 method is protected from A


class so can be accessible through child class
reference variable inside the child class only.

C c =new C();

c.m9();

B.m10();

C.m10();

m10();

}
Output:
Protected non static m9 method from A class
Protected static m10 method from A class
Protected static m10 method from A class
Protected static m10 method from A class
Summary:
Visibility Private Default Protected public
Within the same class Yes Yes Yes Yes
From the child class of
same package No Yes Yes Yes
From the non child class of
same package No Yes Yes Yes
Yes(inside the child class
From the child class of using child class
outside the package No No reference variable) Yes
From the nonchild class of
outside package No No No Yes

Polymorphism:
Definition: It is an oops concept which defines
the way to achieve portability on the basis of
2 concepts which are the types of
polymorphism-
1. Overloading
2. Overriding
Polymorphism is the way through which can
provide the ability to the method having
same name but the actions of the same would
get differ is called polymorphism.

Types of polymorphism:
1. Overloading
2. Overriding

1. Overloading:
Method can be called as overloaded if they have the
same name but different arguments / signatures.
Example:
public class Test {
public void m1()
{
System.out.println("first m1 method");
}

public void m1(int i)


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

public static void m1(String s, String t)


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

All the above 3 methods are overloaded method

Some important key points for overloading:


1. Type of method doesn’t make any difference to call
the method as overloaded.
public void m1(int i)
{
System.out.println("Second m1 method");
}

public static void m1(String s, String t)


{
System.out.println("Static m1 method");
}
Both methods are overloaded one.
2. Return type of the method doesn’t make any
difference to call the method as overloaded method.
public static void m1(String s, String t)
{
System.out.println("Static m1 method");
}

public int m1(double d)


{
System.out.println("mehtod with return
type");

return 80;
}
Both methods are overloaded method

Note: Main method can be overloaded.


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

Test2 t2 = new Test2();

t2.m1(false);

t2.m1();

main();
}

public static void main()


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

Output:
Boolean argument m1 method
first m1 method
main method with no argument

3. Access modifier of a method doesn’t make


any difference to call the method as
overloaded method.
Example:
public static void m1(char c)
{
System.out.println("public Static method
with char argument");

void m1(int a, int b, int c) {


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

private void m1(double d, int i)


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

Note: All three methods are called as overloaded


method
4. We can overload the constructor as well as it
can take arguments also we can have multiple
constructor inside a class.
Example:
public Test()
{
System.out.println("Constructor with 0
argument");
}

public Test(int i)
{
System.out.println("Constructor with 1
argument");
}
5. Overloading method will execute based on
Reference variable. Hence it is called compile time
polymorphism.
6. Overloading is also called as Early binding.

Overriding:
Two methods can be called as
overridden if the name of methods are
exactly same and their arguments are
also same with the classes has
inheritance relationship with
eachother.
Inside the overriding runtime object
will define which class method to get
execute.
Example:
public class Parent {

public void home()


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

public void furniture()


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

public void car()


{
System.out.println("car method from parent
class");
}

public void marry()


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

}
public class Child extends Parent {

public void bike()


{
System.out.println("Child class bike");
}

public void marry()


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

public static void main(String[] args) {

Child c = new Child();

c.home();

c.car();

c.bike();

c.marry();
}

}
Output after executing Child class:
Home method from parent class
car method from parent class
Child class bike
Child class marry method

Example
Rules for overriding:
1. Whenever any method inside the parent class
becomes final then child class will not be able to
override it.
Example:
public class Parent {
public final void marry()
{
System.out.println("marry method from
Parent class");
}
}
public class Child extends Parent {
public void marry()
{
System.out.println("Child class marry
method");
}
}
Note: Here the marry method for child class becomes
invalid as any method inside parent class becomes
final then we cannot override it.

2. Method return type inside the parent and child


class must be same if we don’t make it same then
we will not be able to override them we will get
error.
Example:

public class A {

public String m1()


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

return "abc";
}

}
public class B extends A {

public int m1()


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

}
Note : Above example will give error as it has
String return type for one and int return for other
it must be same for overriding.

3. Method having different type (static and non


static) cannot be overridden.
To make the method as overridden we have to define
those as same type and specifically non static
only. We cannot override the static method.
Example:
public class A {
public void m2()
{
System.out.println("non static method m2
from A class");
}

public class B extends A {


// method having different type cannot be
overridden

public static void m2()


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

Note: Here the above combination will throw error


as the type of both the methods must be same and to
override the method we need to make those
compulsorily as non static only.
4. Access modifier: For method to be overridden the
access modifier scope inside the child class must
be same / improved but access modifier should not
get decrease.
If scope inside the child class get decrease then
we will get an error.
Example:
public class A {

public void m3()


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

public class B extends A {

void m3()
{
System.out.println("default non static
method m3 from B class");
}
}

Note: Here the scope of m3 method access modifier


gets reduce hence we are getting here an error.

Another way to create object when we have


classes following inheritance:
Parent class reference variable can be
use to hold child class object but vice
versa is not possible.
Example:

public class C {

}
public class D extends C{

public static void main(String[] args) {

C c = new C();// parent object

D d = new D();// child object

C c1 = new D();// Child object

}
Note : Here the highlighted object is referring to
the parent reference is used to hold child class
object.
Example:
public class C {

// This class is to understand another way to


create object for the class has parent and child
relation

public void m1()


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

public class D extends C{


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

public static void main(String[] args) {

C c = new C();// parent object

c.m1();//C class method

D d = new D();// child object

d.m1();// D class method


C c1 = new D();// Child object

c1.m1();// D class method

}
Output when we execute D class then :
m1 method from C class
m1 method from D class
m1 method from D class

5. In overriding the method will get call based on


the runtime object.
That’s why overriding is called as Run time
polymorphism
Overriding is also called as Late binding.

Example:
public class C {

// This class is to understand another way to


create object for the class has parent and child
relation

public void m1()


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

public void m2()


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

}
public class D extends C{
public void m1()
{
System.out.println("m1 method from D
class");
}

public void m2()


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

public static void main(String[] args) {

C c = new C();// parent object

c.m1();//C class method

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

c.m3(); // C class m3 method

D d = new D();// child object

d.m1();// D class method


d.m2(); // D class m2 method

d.m3();// C class m3 method


C c1 = new D();// Child object

c1.m1();

c1.m2(); // D child m2 method

Output:
m1 method from C class
m2 method from C class
m3 method from C class
m1 method from D class
m2 method from D class
m3 method from C class
m1 method from D class
m2 method from D class

Note: In overriding the method will get execute


based on runtime object only whereas inside the
Overloading method will execute based on Reference
variable.

6. Static method doesn’t follow overriding as


because inside the overriding run time will decide
which method to get execute but we don’t recommend
to call the static method using object but if we
try to call using object then it will not follow
runtime object rule as we have for non static
method.
Static method is following method hiding but not
overriding.
Method hiding: Method will always be called based
on reference variable.

Example:
public class StaticA {

// Here we will check the impact of overriding on


static method

public static void m1()


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

public static void m2()


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

}
public class StaticB extends StaticA

public static void m1()


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

public static void main(String[] args) {


StaticA a = new StaticA();

a.m1();

StaticB b = new StaticB();

b.m1();

StaticA sa = new StaticB();

sa.m1();

7. Overriding with respect to variables: We cannot


have the variables as overridden as they called on
the basis of reference variable only but not the
runtime object hence variable doesn’t follow
overriding.
Example:
public class ParentVar {

String city = "Pune";

}
public class ChildVar extends ParentVar
{
String city = "Mumbai";

public static void main(String[] args) {

ChildVar cv = new ChildVar();

System.out.println(cv.city);// mumbai

ParentVar pv = new ParentVar();

System.out.println(pv.city);// pune

ParentVar pv1 = new ChildVar();

System.out.println(pv1.city);//Pune

}
Output:
Mumbai
Pune
Pune

Questions for overriding:


Scenario 1: return types are different
Scenario 2: method types are different
Scenario 3: both method are static
Scenario 4: method are non-static but arguments are
different
Scenario 5: Access modifier got reduces

Note: Main method can be overloaded but cannot be


overridden because it is static method and we
cannot override a static method.
Constructor can be overloaded but cannot be
overridden as the name of the class and constructor
name must be same and overriding says method name
must be same.

Difference between overloading and overriding:

Sr. no Overloading Overriding


1 Method name must be Method name must be
same but argument same and argument
must be different must be same.
2 Method signature Method signature must
must be different be same
3 Method return type Method return type
has no should be same.
restrictions.
i.e can be of any
type
4 Private, static, Private, static,
final method can be final methods cannot
overloaded. be overridden.
5 Access modifiers Scope of access
usage for modifier must be same
overloading has no or in incremental
restriction order inside the
child class.
6 Method resolution Method resolution is
is based on based on run time
reference variable object.
7 Also called as Also called as Run
compile time time polymorphism,
polymorphism, Early Late binding and
binding and static dynamic polymorphism.
polymorphism.

Encapsulation: It refers to the


integration data(variable) and
code(method) into a single unit.
This can be achieved by datahiding
and abstraction.

Datahiding: Declaring a variable


as private and accessing the same
inside public method that means
hiding the variable from every
other classes and allow only
public method of the same class to
access is called as datahiding.

public class BankServer {

private double cust1balance = 50000;

public String getBalance(int pin) {


String s = "";
if (pin == 1234) {
s = "your balance is " + cust1balance;
}

else {
s = "please check the pin and try
again";
}

return s;

public static void main(String[] args) {


BankServer bs = new BankServer();

String output = bs.getBalance(1234);

System.out.println(output);
}

}
Output:
your balance is 50000.0

Abstraction: Hiding the


implementation from the end user by
calling the method into another class
is called as Abstraction.
Encapsulation = Data hiding +
Abstraction
Example:
public class BankServer {

private double cust1balance = 50000;

public String getBalance(int pin) {


String s = "";
if (pin == 1234) {
s = "your balance is " + cust1balance;
}

else {
s = "please check the pin and try
again";
}

return s;
}

public void withdrawlCash(int pin, double


amount)
{
if(pin == 1234)
{
if(amount <= cust1balance)
{
cust1balance = cust1balance - amount;

System.out.println("Please collect the


cash and your balance is "+cust1balance);
}
else
{
System.out.println("Insufficient
balance");
}
}
else
{
System.out.println("Incorrect pin");
}

}
public class ATMMachine {

public static void main(String[] args) {


BankServer bs = new BankServer();

String output = bs.getBalance(1234);//


abstraction

System.out.println(output);
bs.withdrawlCash(1234, 5000);
}

Output:
your balance is 50000.0
Please collect the cash and your balance is 45000.0

Getter and setter method:


Getter method : The method whose
name startswith get word then it
is called as getter method.
Generally this is used to read the
value of any variable based on the
logic.
Setter method: The method whose
name starts with set word then it
is called as setter method.
Generally this is used to update
the value of any variable based on
the logic.
Example:
public class Test {

String name;

public String getName()// getter method


{
return name;
}

public void setName(String name)// setter


method
{
this.name = name;
}

public static void main(String[] args) {


Test t = new Test();

t.setName("David");

String n = t.getName();

System.out.println(n);//David
}

Questions:
1.define Encapsulation
2. Data hiding and Abstraction
3. Give me an example of encapsulation
4. getter and setter method
Arrays in java: Collection of
homogeneous elements represented
by single reference variable is
called Array.
Example:

Size of the array is always fixed that means if we


have defined the array of size 8 then we will not
be able to add 9th element inside the array.

We can define array in 2 ways:


a. By creating object:
public static void main(String[] args) {
// first way to define the array:

// syntax:
// datatype [] referencevariablename = new
datatype[size_of_array];

int [] a = new int[5];

a[0] = 80;

a[1] = 70;

a[2] = 45;

a[4] = 10;

a[3] = 6;

System.out.println(a[2]);//45

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


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

Output:
45
80
70
45
6
10
To find the count of elements present inside an
array :

referencevariable.length;
Example:
int sizeofarray = a.length;

System.out.println("Size of array is" +


sizeofarray);

Iterating the array using the length:


int sizeofarray = a.length;

System.out.println("Size of array is" +


sizeofarray);

for(int i = 0; i<sizeofarray; i++)


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

Output:
Size of array is6
80
70
45
6
10
12
Another way to define the array:
public static void main(String[] args) {

// syntax
// data_type variablename[] = {value1, value2,
value3};

String s [] = {"Pune", "Delhi", "Mumbai",


"Kolkata", "Chennai"};

int size = s.length;

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

for(int i=0; i<size; i++)


{
System.out.println(s[i]);

Output:
5
Pune
Delhi
Mumbai
Kolkata
Chennai

Assignment:
1. Consider an int array having size 5 and WAP to
print the addition of all the elements of array:
Solution:
public static void main(String[] args) {

int [] a = {10, 20, 30, 8, 5};

int sum = 0;

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


{
sum = sum + a[i];
}

System.out.println(sum);

}
2. WAP to print the addition of all the elements of
array which are at even index position
Solution:
public static void main(String[] args) {

int [] a = {10, 20, 30, 8, 5};

int sum = 0;

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


{
if(i%2 ==0)
{
sum = sum + a[i];
}

}
System.out.println(sum);

3. WAP to print the addition of all the elements of


array which are at odd index position
Solution:
public static void main(String[] args) {

int [] a = {10, 20, 30, 8, 5};

int sum = 0;

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


{
if(!(i%2 ==0))
{
sum = sum + a[i];
}

System.out.println(sum);

4. WAP to print the addition of all the elements of


array which are even inside an array
5. WAP to print the addition of all the elements of
array which are odd inside an array
For Each loop / Advance for loop:
In this we don’t have to define the starting point
and the last point to iterate.
Example:
public static void main(String[] args) {

int [] a = {10, 20, 30, 8, 5};

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

}
Output :
10
20
30
8
5

WAP to find out the missing number from an array:


Sorting of array:
We can use Arrays.sort(arrayname) to perform the
sorting operation in ascending order inside an
array.
Example:
public static void main(String[] args) {

int a [] = {5, 6, 10, 2, 56};

Arrays.sort(a);

for(int value :a)


{
System.out.println(value);
}
}
Output:
2
5
6
10
56

You might also like