Chapter 2-4 Oop
Chapter 2-4 Oop
2 04/25/2024
In Java language, primitive data types are the building
3 04/25/2024
4 04/25/2024
Cont’d…
5 04/25/2024
Variables in java
A variable is a container which holds the value while
and static.
6 04/25/2024
Cont’d…
Local variable
blocks.
You can use this variable only within that method and the
7 04/25/2024
Cont’d…
Instance variable:
8 04/25/2024
Cont’d…
Static variables:
A variable that is declared as static key word is.
It cannot be local.
You can create a single copy of the static variable and share it
9 04/25/2024
Example
1. public class A
2. {
3. static int m=100;//static variable
4. void method()
5. {
6. int n=90;//local variable
7. }
8. public static void main(String args[])
9. {
10. int data=50;//instance variable
11. }
12.}//end of class
10 04/25/2024
Sr. No. Local variables Instance variables Static variables
11 04/25/2024
Cont’d…
3. A local variable starts its The object associated with The static variable has the
lifetime when the method the instance variable same lifetime as the
is invoked. decides its lifetime. program.
5. Used to store values that Used to store values that Used for storing constants.
are required for a are needed to be accessed
particular method. by different methods of
the class.
12 04/25/2024
Comments
Comments make your code easy to understand, modify, and use.
15 04/25/2024
Relational operator
Is equal to ==
Not equal to !=
Greater than >
Greater than or equal to >=
Less than <
Less than or equal to <=
16 04/25/2024
Logical operator
17 04/25/2024
Assignment operator
18 04/25/2024
Control statements
Java compiler executes the code from top to bottom.
1. if statements
2. switch statement
2. Loop statements
1. do while loop
2. while loop
3. for loop
4. for-each loop
20 04/25/2024
cont’d…
1. Jump statements
1. break statement
2. continue statement
21 04/25/2024
Decision making statements
As the name suggests, decision-making statements decide
22 04/25/2024
Cont’d…
If Statement:
In Java, the "if" statement is used to evaluate a condition.
specific condition.
The condition of the If statement gives a Boolean value,
23 04/25/2024
Cont’d…
Simple if statement:
It is the most basic statement among all control flow
statements in Java.
It evaluates a Boolean expression and enables the
program to enter a block of code if the expression
evaluates to true.
Syntax of if statement is given below.
24 04/25/2024
25 04/25/2024
Cont’d..
example
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y > 20) {
6. System.out.println("x + y is greater than 20");
7. }
8. }
9. }
26 04/25/2024
Cont’d…
if-else statement
The if-else statement is an extension to the if-statement,
evaluated as false.
27 04/25/2024
28 04/25/2024
Cont’d…
example
1. public class Student {
2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10.}
11.}
29 04/25/2024
Cont’d…
if-else-if ladder:
chain.
30 04/25/2024
31 04/25/2024
Cont’d…
example
1. public class Student {
2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }
32 04/25/2024
Cont’d….
Nested if-statement
In nested if-statements, the if statement can contain
33 04/25/2024
Cont’d…
34 04/25/2024
Cont’d….
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
35 04/25/2024
Switch Statement:
In Java, Switch statements are similar to if-else-if
statements.
The switch statement contains multiple blocks of code
statements.
It also enhances the readability of the program.
36 04/25/2024
Cont’d…
• The case variables can be int, short, byte, char, or
condition is satisfied.
• It is optional, if not used, next case is executed.
38 04/25/2024
39 04/25/2024
Cont’d…
1. public class Student implements Cloneable {
2. public static void main(String[] args) {
3. int num = 2;
4. switch (num){
5. case 0:
6. System.out.println("number is 0");
7. break;
8. case 1:
9. System.out.println("number is 1");
10. break;
11. default:
12. System.out.println(num);
13. }
14. }
15. }
40 04/25/2024
Reptation statement
In programming, sometimes we need to execute the block
particular condition.
In Java, we have three types of loops that execute similarly.
42 04/25/2024
43 04/25/2024
Cont’d…
1. for(initialization, condition, increment/decrement) {
2. //block of statements
3. }
example
4. public class Calculattion {
5. public static void main(String[] args) {
6. // TODO Auto-generated method stub
7. int sum = 0;
8. for(int j = 1; j<=10; j++) {
9. sum = sum + j;
10.}
11. System.out.println("The sum of first 10 natural numbers is " + sum);
12.}
13.}
44 04/25/2024
Java for-each loop
45 04/25/2024
Cont’d…
example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\
n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10.}
46 04/25/2024
Cont’d…
Java while loop
47
3. } 04/25/2024
Cont’d…
48 04/25/2024
Cont’d..
example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10.}
11.}
49 04/25/2024
cont’d…
Java do-while loop
The do-while loop checks the condition at the end of the loop after
checked in advance.
1. do
2. {
3. //statements
4. } while (condition);
50 04/25/2024
Cont’d….
51 04/25/2024
Cont’d…
Example
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10.}
11.}
52 04/25/2024
Jump Statements
and continue.
53 04/25/2024
Cont’d…
Java break statement
As the name suggests, the break statement is used to break
nested loop.
Can not stated independently, it can only be written inside
55 04/25/2024
Cont’d….
Java continue statement
56 04/25/2024
Cont’d…
1. public class ContinueExample {
2.
3. public static void main(String[] args) {
4. // TODO Auto-generated method stub
5.
6. for(int i = 0; i<= 2; i++) {
7.
8. for (int j = i; j<=5; j++) {
9.
10. if(j == 4) {
11. continue;
12. }
13. System.out.println(j);
14. }
15. }
16. }
17.
18. }
57 04/25/2024
Chapter Three
Objects and Classes in Java
Class- A class can be defined as a template/blueprint that describes the
color, name, breed as well as behaviors – wagging the tail, barking, eating.
An object is an instance of a class
Java provides a reserved keyword class to define a class.
58 04/25/2024
Class
A class is a group of objects which have common properties. It is a template or
blueprint from which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
• Fields
• Methods
• Constructors
• Blocks
59 04/25/2024
Cont’d….
Instance variable in Java
A variable which is created inside the class but outside the method is known as an
instance variable. Instance variable doesn't get memory at compile time. It gets
memory at runtime when an object or instance is created. That is why it is known
as an instance variable.
60 04/25/2024
Class declaration
In general, class declaration includes the following in the order as it
appears:
1. Modifiers: A class can be public or has default access.
2. class keyword: The class keyword is used to create a class.
3. Class name: The name must begin with an initial letter (capitalized
by convention).
4. Superclass (if any): The name of the class's parent (superclass), if
any, preceded by the keyword extends. A class can only extend
(subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.
61 04/25/2024
The General Form of a Class
A class is declared by use of the class keyword.
class <class_name>{
field;
method;
}
The data, or variables, defined within a class are called instance
variables.
The code is contained within methods. Collectively, the methods
and variables defined within a class are called members of the class
62 04/25/2024
object
An object in Java is the physical as well as a logical entity, whereas,
ID. The value of the ID is not visible to the external user. However,
it is used internally by the JVM to identify each object uniquely.
63 04/25/2024
Cont’d
Object and Class Example:
64 04/25/2024
Creating methods and constructor in side the class
A method is a block of code or collection of statements or a set of code
65 04/25/2024
Method Declaration
66 04/25/2024
cont’d…
Method Signature: Every method has a method signature. It is a part of the method
It specifies the visibility of the method. Java provides four types of access specifier:
• Public: The method is accessible by all classes when we use public specifier in our
application.
• Private: When we use a private access specifier, the method is accessible only in the
• Protected: When we use protected access specifier, the method is accessible within
• Default: When we do not use any access specifier in the method declaration, Java
67 04/25/2024
uses default access specifier by default. It is visible only from the same package only.
Cont’d…
Return Type: Return type is a data type that the method returns. It may have a
primitive data type, object, collection, void, etc. If the method does not return
anything, we use void keyword.
Method Name: It is a unique name that is used to define the name of a method.
in the pair of parentheses. It contains the data type and variable name. If the
method has no parameter, left the parentheses blank.
Method Body: It is a part of the method declaration. It contains all the actions
69 04/25/2024
Types of Method
There are two types of methods in Java:
• Predefined Method
• User-defined Method
Predefined Method
It is also known as the standard library method or built-in method.
We can directly use these methods just by calling them in the program
at any point.
Some pre-defined methods are length(), equals(), compareTo(),
sqrt(), etc.
70 04/25/2024
Cont’d…
When we call any of the predefined methods in our program, a series of
Example:
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
71 04/25/2024
User defined method
The method written by the user or programmer is known as a user-
72 04/25/2024
Return type
A return statement causes the program control to transfer
73 04/25/2024
Cont’d…
74 04/25/2024
Cont’d…
75 04/25/2024
constructor
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is syntactically
similar to a method.
Once defined, the constructor is automatically called immediately after
even void.
This is because the implicit return type of a class’ constructor is the
76 04/25/2024
Cont’d…
Every time an object is created using the new() keyword, at least one
constructor is called.
It calls a default constructor if there is no constructor available in the
77 04/25/2024
Default constructor
//Java Program to create and call a default constructor
class memory{
//creating a default constructor
memory(){System.out.println(“is memorized");}
//main method
public static void main(String args[]){
//calling a default constructor
memory b=new memory();
}
}
78 04/25/2024
Parametrized constructor
//Java Program to demonstrate the use of the parameterized constructor.
class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}
80 04/25/2024
Cont’d
Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple
example where we are going to initialize the object through a reference variable.
class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);
//printing members with a white space
}
}81 04/25/2024
Cont’d
We can also create multiple objects and store information in it through reference
variable.
class Student{
int id;
String name;
}
class TestStudent3{
public static void main(String args[]){
//Creating objects
Student s1=new Student();
Student s2=new Student();
//Initializing objects
s1.id=101;
s1.name=“Aster";
s2.id=102;
s2.name=“Abebe";
//Printing data
System.out.println(s1.id+" "+s1.name);
System.out.println(s2.id+" "+s2.name);
}
82 04/25/2024
}
Cont’d…
Object and Class Example: Initialization through method
In this example, we are creating the two objects of Student class and
83 04/25/2024
Cont’d
class Student{
int Stud_id;
String name;
void insertRecord(int r, String n){
Stud_Id=r;
name=n;
}
void displayInformation()
{
System.out.println(Stud_id+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(“DTU00/tech2015”,“Aster");
s2.insertRecord(“DTU01/tech2015”,“Abebe");
s1.displayInformation();
s2.displayInformation();
84 } 04/25/2024
}
Cont’d
Object and Class Example: Initialization through a constructor
class Student{
int Stud_id;
String name;
Student(int r, String n){
Stud_Id=r;
name=n;
}
void displayInformation()
{
System.out.println(Stud_id+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1. Student(“DTU00/tech2015”,“Aster");
s2. Student(“DTU01/tech2015”,“Abebe");
s1.displayInformation();
s2.displayInformation();
}85 04/25/2024
}
Java Modifier Types
Modifiers are keywords that you add to those
definitions to change their meanings.
has a wide variety of modifiers, including the
following:
Java Access Modifiers
Non Access Modifiers(reading assignment)
86 04/25/2024
Java Access Modifiers
Java provides a number of access modifiers to set
access levels for classes, variables, methods, and
constructors. The four access levels are:
Visible to the package, the default. No modifiers are
needed.
Visible to the class only (private).
Visible to the world (public).
Visible to the package and all subclasses (protected).
87 04/25/2024
Cont’d…
Access within class within outside outside
Modifier package package by package
subclass only
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
88 04/25/2024
private
package pack;
class A{
private int data=40; );//private instance variable
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
89 04/25/2024
Private constructor
package pack;
class A{
private A(){}//private constructor
void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();//Compile Time Error
}
}
90 04/25/2024
Default Access Modifier - No Keyword
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
91 04/25/2024
protected
The protected access modifier is accessible within package and
92 04/25/2024
Cont’d…
package pack;
public class A{
protected void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
93 04/25/2024
Public
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
94
} 04/25/2024
}
95 04/25/2024
interface
An interface in Java is a blueprint of a class. It has static constants
inheritance.
• It can be used to achieve loose coupling.
96 04/25/2024
Cont’d…
97 04/25/2024
Instance
1. interface Bank{
2. float rateOfInterest();
3. }
4. class SBI implements Bank{
5. public float rateOfInterest(){return 9.15f;}
6. }
7. class PNB implements Bank{
8. public float rateOfInterest(){return 9.7f;}
9. }
10. class TestInterface2{
11. public static void main(String[] args){
12. Bank b=new SBI();
13. System.out.println("ROI: "+b.rateOfInterest());
14. }}
98 04/25/2024
Chapter four
Chap 4 Object Oriented
Programming Concepts
"Inheritance"
Java – Inheritance : Inheritance can be defined as the
100 04/25/2024
Cont’d…
Syntax:
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
101 04/25/2024
102 04/25/2024
Cont’d…
Eg.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
103 04/25/2024
keywords
Super keyword:
1. Super can be used to refer immediate parent class instance
variable.
2. super can be used to invoke immediate parent class
method.
3. super() can be used to invoke immediate parent class
constructor.
104 04/25/2024
Cont’d…
1. class Animal{
2. String color="white";
3. }
4. class Dog extends Animal{
5. String color="black";
6. void printColor(){
7. System.out.println(color);//prints color of Dog class
8. System.out.println(super.color);//prints color of Animal class
9. }
10. }
11. class TestSuper1{
12. public static void main(String args[]){
13. Dog d=new Dog();
14. d.printColor();
15. }}
105 04/25/2024
Cont’d…
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void eat(){System.out.println("eating bread...");}
6. void bark(){System.out.println("barking...");}
7. void work(){
8. super.eat();
9. bark();
10. }
11. }
12. class TestSuper2{
13. public static void main(String args[]){
14. Dog d=new Dog();
15. d.work();
16. }}
106 04/25/2024
Cont’d…
1. class Animal{
2. Animal(){System.out.println("animal is created");}
3. }
4. class Dog extends Animal{
5. Dog(){
6. super();
7. System.out.println("dog is created");
8. }
9. }
10.class TestSuper3{
11.public static void main(String args[]){
12.Dog d=new Dog();
13.}}
107 04/25/2024
Cont’d…
Instance of:
Used to check the subclass is actually in super class
public class Animal {
109 04/25/2024
HAS - A relationship
These relationships are mainly based on the usage.
114 04/25/2024
Types of Inheritance
On the basis of class, there can be three types of inheritance
115 04/25/2024
Cont’d…
116 04/25/2024
Single level Inheritance
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10.d.bark();
11.d.eat();
12.}}
117 04/25/2024
Multilevel Inheritance
Eg.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat(); 04/25/2024
118
16. }}
Hierarchical inheritance
Eg.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
119 04/25/2024
Java Polymorphism
is the ability of an object to take on many forms.
120 04/25/2024
Cont’d….
Method overriding:
121 04/25/2024
Cont’d…
Rules for Java Method Overriding
1. The method must have the same name as in the parent
class
2. The method must have the same parameter as in the
parent class.
3. There must be an IS-A relationship (inheritance).
122 04/25/2024
Cont’d…
Eg.
1. //Java Program to illustrate the use of Java Method Overriding
2. //Creating a parent class.
3. class Vehicle{
4. //defining a method
5. void run(){System.out.println("Vehicle is running");}
6. }
7. //Creating a child class
8. class Bike2 extends Vehicle{
9. //defining the same method as in the parent class
10. void run(){System.out.println("Bike is running safely");}
11.
12. public static void main(String args[]){
13. Bike2 obj = new Bike2();//creating object
14. obj.run();//calling method
15. }
16. }
123 04/25/2024
Cont’d…
Method Overloading in Java
If a class has multiple methods having same name but
different in parameters
Method overloading increases the readability of the
program
There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type
124 04/25/2024
Cont’d…
Method Overloading: changing no. of arguments
1. class Adder{
2. static int add(int a,int b){return a+b;}
3. static int add(int a,int b,int c){return a+b+c;}
4. }
5. class TestOverloading1{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(11,11,11));
9. }}
125 04/25/2024
Cont’d…
Method Overloading: changing data type of
arguments
1. class Adder{
2. static int add(int a, int b){return a+b;}
3. static double add(double a, double b){return a+b;}
4. }
5. class TestOverloading2{
6. public static void main(String[] args){
7. System.out.println(Adder.add(11,11));
8. System.out.println(Adder.add(12.3,12.6));
9. }}
126 04/25/2024
Cont’d…
127 04/25/2024
128 04/25/2024