Introduction To OOP Handout 1
Introduction To OOP Handout 1
These are the machine independent programming languages, which are easy to write,
read, edit and understand.
The languages like Java, .Net, Pascal, COBOL, C++, C, C# and other (which are very
popular now to develop user end applications). These languages come under the high
level programming language category.
High level programming languages have some special keywords, functions and class
libraries by using them we can easily build a program for the computer.
Computer does not understand program written in such languages directly, as I have
written above that computer understands only Machine code. So, here programming
translators are required to convert a high level program to its equivalent Machine cod
The programs are written in High Level programming languages and are
independent that means a program written on a system can be run on another
system.
Easy to understand - Since these programming languages have keywords,
functions, class libraries (which are similar to English words) we can easily
understand the meaning of particular term related to that programming
language.
Easy to code, read and edit - The programs written in High Level
programming languages are easy to code, read and edit. Even we can edit
programs written by other programmers easily by having little knowledge of
that programming language.
Since, High Level language programs are slower than Low level language
programs; still these programming languages are popular to develop User End
Applications.
Since, there is no such category of computer programming languages, but the programming
languages that have features of low level and high level programming languages come
under this category.
Hence, we can say that the programming languages which have features of Low Level
as well as High Level programming languages known as "Middle Level"
programming language.
C programming languages is the best example of Low Level Programming languages as it
has features of low level and high level programming languages both.
Overview of OO principles
Object-Oriented Programming (OOP) is the term used to describe a programming
approach based on objects and classes. The object-oriented paradigm allows us to organise
software as a collection of objects that consist of both data and behaviour. This is in contrast
to conventional functional programming practice that only loosely connects data and
behaviour.
Since the 1980s the word 'object' has appeared in relation to programming languages, with
almost all languages developed since 1990 having object-oriented features. Some languages
have even had object-oriented features retro-fitted. It is widely accepted that object-oriented
programming is the most important and powerful way of creating software.
// DEPARTMENT is a constant
public static final String DEPARTMENT = "Development ";
The static variable can be used to refer the common property of all objects (that is not unique for each
object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
It makes your program memory efficient (i.e it saves memory)
class Student8{
int rollno;
String name;
static String college ="ITS";
s1.display();
s2.display();
}
}
Example.
public class Employee {
+ : accessible
blank : not accessible
In this example, we have created two classes A and Simple. A class contains
private data member and private method. We are accessing these private members
from outside the class, so there is compile time error
1. class A{
2. private int data=40;
3. private void msg()
4. {System.out.println("Hello java");}
5. }
6. public class Simple{
7. public static void main(String args[]){
8. A obj=new A();
9. System.out.println(obj.data);//Compile Time Error
10. obj.msg();//Compile Time Error
11. }
12. }
2.default access modifier: In this example, we have created two packages pack and mypack. We are accessing the
A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.
1. /save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
The protected access modifier is accessible within package and outside the package but through inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the
class.
1. //save by A.java
2. package pack;
3. public class A{
4. protected void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. obj.msg();
9. }
10. }
We will learn more about access modifiers and package in detail in Lab class or in Try it online in class
in //www.javatpoints.com or www.tutorialspoint.com the above code is the example of Java package while
using A protected A/Modifier.
There are eight primitive datatypes supported by Java. Primitive datatypes are predefined by the language and
named by a keyword. Let us now look into the eight primitive data types in detail.
byte
short
int
long
float
boolean
char
Reference Datatypes
Reference variables are created using defined constructors of the classes. They are used to access objects.
These variables are declared to be of a specific type that cannot be changed. For example, Employee,
Puppy, etc.
Class objects and various type of array variables come under reference datatype.
Default value of any reference variable is null.
A reference variable can be used to refer any object of the declared type or any compatible type.
Example: Animal animal = new Animal("giraffe");
Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following
groups −
Arithmetic Operators
Relational Operators
Bitwise Operators
Logical Operators
Assignment Operators
Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The
following table lists the arithmetic operators −
Example
public class Test {
public static void main(String args[]) {
int a = 10;
int b = 20;
System.out.println("a == b = " + (a == b) );
System.out.println("a != b = " + (a != b) );
System.out.println("a > b = " + (a > b) );
System.out.println("a < b = " + (a < b) );
System.out.println("b >= a = " + (b >= a) );
System.out.println("b <= a = " + (b <= a) );
}
}
Output
a == b = false
a != b = true
a > b = false
a < b = true
b >= a = true
b <= a = false
Assume Boolean variables A holds true and variable B holds false, then −
c = a + b;
System.out.println("c = a + b = " + c );
c += a ;
System.out.println("c += a = " + c );
c -= a ;
System.out.println("c -= a = " + c );
c *= a ;
System.out.println("c *= a = " + c );
a = 10;
c = 15;
c /= a ;
System.out.println("c /= a = " + c );
a = 10;
c = 15;
c %= a ;
System.out.println("c %= a = " + c );
c <<= 2 ;
System.out.println("c <<= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c >>= 2 ;
System.out.println("c >>= 2 = " + c );
c &= a ;
System.out.println("c &= a = " + c );
c ^= a ;
System.out.println("c ^= a = " + c );
c |= a ;
System.out.println("c |= a = " + c );
}
}
Simple assignment operator. Assigns values from right side operands to left C = A + B will assign value of
=
side operand. A + B into C
Add AND assignment operator. It adds right operand to the left operand and C += A is equivalent to C = C
+=
assign the result to left operand. +A
Subtract AND assignment operator. It subtracts right operand from the left C -= A is equivalent to C = C –
-=
operand and assign the result to left operand. A
Multiply AND assignment operator. It multiplies right operand with the left C *= A is equivalent to C = C
*=
operand and assign the result to left operand. *A
/= Divide AND assignment operator. It divides left operand with the right C /= A is equivalent to C = C /
operand and assign the result to left operand. A
Modulus AND assignment operator. It takes modulus using two operands and C %= A is equivalent to C = C
%=
assign the result to left operand. %A
<<= Left shift AND assignment operator. C <<= 2 is same as C = C << 2
>>= Right shift AND assignment operator. C >>= 2 is same as C = C >> 2
&= Bitwise AND assignment operator. C &= 2 is same as C = C & 2
^= bitwise exclusive OR and assignment operator. C ^= 2 is same as C = C ^ 2
|= bitwise inclusive OR and assignment operator. C |= 2 is same as C = C | 2
Operators precedence..??
int x = 34;
int y = ++x;
The value of x is first incremented to 34 and is then assigned to y. Therefore x is now 35 and y is also 35.
int x = 34;
int y = x++;
x is first assigned to y and then incremented by one. Therefore, x becomes 35 while y is assigned with the value 34.
int s = 34;
s++; // s is now 35
int s= 34;
++s; // s is now 35
Casting
We have already come across casting quite a number of types. In order to help you, we will now recollect all that we
have learnt about casting till now and then learn something in addition to what you have already learnt.
Casting refers to the conversion of one data type to another. When we cast a particular variable, the data type of the
variable itself is not altered. For example, in the following code, when we cast, num1 to a double; the variable num1
does not change its data type from int to double. Instead, a new copy of num1 is made and its data type is changed to
double.
short a = 347;
int b= 347347;
short c = (short)a;
int d = (short) b;
System.out.println(c);
System.out.println(d);
Flow controll
1. Decision and Repetition Statements (6 hours)
As a program executes, the interpreter always keeps track of which statement is about to be executed. We call this
the control flow, or the flow of execution of the program.
First step: In for loop, initialization happens first and only one time, which means that the initialization part of for
loop only executes once.
Second step: Condition in for loop is evaluated on each iteration, if the condition is true then the statements inside
for loop body gets executed. Once the condition returns false, the statements in for loop does not execute and the
control gets transferred to the next statement in the program after for loop.
Third step: After every execution of for loop’s body, the increment/decrement part of for loop executes that updates
the loop counter.
Fourth step: After third step, the control jumps to second step and condition is re-evaluated.
class ForLoopExample2 {
public static void main(String args[]){
for(int i=1; i>=1; i++){
System.out.println("The value of i is: "+i);
}
}
}
This is an infinite loop as the condition would never return false. The initialization step is setting up the value of
variable i to 1, since we are incrementing the value of i, it would always be greater than 1 (the Boolean expression:
i>1) so it would never return false. This would eventually lead to the infinite loop condition. Thus it is important to
see the co-ordination between Boolean expression and increment/decrement operation to determine whether the loop
would terminate at some point of time or not.
// infinite loop
for ( ; ; ) {
// statement(s)
}
For loop example to iterate an array:
Here we are iterating and displaying array elements using the for loop.
class ForLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
for(int i=0; i<arr.length; i++){
System.out.println(arr[i]);
}
}
}
Output:
2
11
45
9
Syntax of while loop
while(condition)
{
statement(s);
}
How while Loop works?
In while loop, condition is evaluated first and if it returns true then the statements inside while loop execute. When
condition returns false, the control comes out of loop and jumps to the next statement after while loop.
Note: The important point to note when using while loop is that we need to use increment or decrement statement
inside while loop so that the loop variable gets changed on each iteration, and at some point condition returns false.
This way we can end the execution of while loop otherwise the loop would execute indefinitely.
Output:
10
9
8
7
6
5
4
3
2
Infinite while loop
class WhileLoopExample2 {
public static void main(String args[]){
int i=10;
while(i>1)
{
System.out.println(i);
i++;
}
}
}
This loop would never end, its an infinite while loop. This is because condition is i>1 which would always be true as
we are incrementing the value of i inside while loop.
while (true){
statement(s);
}
Example: Iterating an array using while loop
Here we are iterating and displaying array elements using while loop.
class WhileLoopExample3 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0 too
int i=0;
while(i<4){
System.out.println(arr[i]);
i++;
}
}
}
Output:
2
11
45
9
Syntax of do-while loop:
do
{
statement(s);
} while(condition);
How do-while loop works?
First, the statements inside loop execute and then the condition gets evaluated, if the condition returns true then the
control gets transferred to the “do” else it jumps to the next statement after do-while.
Output:
10
9
8
7
6
5
4
3
2
Example: Iterating array using do-while loop
Here we have an integer array and we are iterating the array and displaying each element using do-while loop.
class DoWhileLoopExample2 {
public static void main(String args[]){
int arr[]={2,11,45,9};
//i starts with 0 as array index starts with 0
int i=0;
do{
System.out.println(arr[i]);
i++;
}while(i<4);
}
}
Output:
2
11
45
9
Continue statement is mostly used inside loops. Whenever it is encountered inside a loop, control directly jumps to
the beginning of the loop for next iteration, skipping the execution of statements inside loop’s body for the current
iteration. This is particularly useful when you want to continue the loop but do not want the rest of the
statements(after continue statement) in loop body to execute for that particular iteration.
Syntax:
continue word followed by semi colon.
continue;
Example: continue statement inside for loop
public class ContinueExample {
System.out.print(j+" ");
}
}
}
Output:
012356
As you may have noticed, the value 4 is missing in the output, why? because when the value of variable j is 4, the
program encountered a continue statement, which makes it to jump at the beginning of for loop for next iteration,
skipping the statements for current iteration (that’s the reason println didn’t execute when the value of j was 4).
Flow Diagram of Continue Statement
Same thing you can see here. We are iterating this loop from 10 to 0 for counter value and when the counter value is
7 the loop skipped the print statement and started next iteration of the while loop.
Output:
10 9 8 6 5 4 3 2 1 0
a) Use break statement to come out of the loop instantly. Whenever a break statement is encountered inside a loop,
the control directly comes out of loop and the loop gets terminated for rest of the iterations. It is used along with if
statement, whenever used inside loop so that the loop gets terminated for a particular condition.
The important point to note here is that when a break statement is used inside a nested loop, then only the inner loop
gets terminated.
b) It is also used in switch case control. Generally all cases in switch case are followed by a break statement so that
whenever the program control jumps to a case, it doesn’t execute subsequent cases (see the example below). As
soon as a break is encountered in switch-case block, the control comes out of the switch-case body.
break;
Example – Use of break in a while loop
In the example below, we have a while loop running from o to 100 but since we have a break statement that only
occurs when the loop value reaches 2, the loop gets terminated and the control gets passed to the next statement in
program after the loop body.
Output:
The same thing you can see here. As soon as the var value hits 99, the for loop gets terminated.
Output:
var: 100
var: 99
Out of for-loop
Example – Use of break statement in switch-case
public class BreakExample3 {
switch (num)
{
case 1:
System.out.println("Case 1 ");
break;
case 2:
System.out.println("Case 2 ");
break;
case 3:
System.out.println("Case 3 ");
break;
default:
System.out.println("Default ");
}
}
}
Output:
Case 2
Class in Java
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.
fields
methods
constructors
blocks
nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
In this example, we have created a Student class that have two data members id and name. We are creating the
object of the Student class by new keyword and printing the objects value.
1. By reference variable
2. By method
3. By constructor
Initializing object simply means storing data into object. Let's see a simple example where we are going to initialize
object through reference variable.
File: TestStudent2.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent2{
6. public static void main(String args[]){
7. Student s1=new Student();
8. s1.id=101;
9. s1.name="Sonoo";
10. System.out.println(s1.id+" "+s1.name);//printing members with a white space
11. }
12. }
Output:
101 Sonoo
We can also create multiple objects and store information in it through reference variable.
File: TestStudent3.java
1. class Student{
2. int id;
3. String name;
4. }
5. class TestStudent3{
6. public static void main(String args[]){
7. //Creating objects
8. Student s1=new Student();
9. Student s2=new Student();
10. //Initializing objects
11. s1.id=101;
12. s1.name="Sonoo";
13. s2.id=102;
14. s2.name="Amit";
15. //Printing data
16. System.out.println(s1.id+" "+s1.name);
17. System.out.println(s2.id+" "+s2.name);
18. }
19. }
Output:
101 Sonoo
102 Amit
In this example, we are creating the two objects of Student class and initializing the value to these objects by
invoking the insertRecord method. Here, we are displaying the state (data) of the objects by invoking the
displayInformation() method.
File: TestStudent4.java
1. class Student{
2. int rollno;
3. String name;
4. void insertRecord(int r, String n){
5. rollno=r;
6. name=n;
7. }
8. void displayInformation(){System.out.println(rollno+" "+name);}
9. }
10. class TestStudent4{
11. public static void main(String args[]){
12. Student s1=new Student();
13. Student s2=new Student();
14. s1.insertRecord(111,"Karan");
15. s2.insertRecord(222,"Aryan");
16. s1.displayInformation();
17. s2.displayInformation();
18. }
19. }
Output:
111 Karan
222 Aryan
File: TestEmployee.java
1. class Employee{
2. int id;
3. String name;
4. float salary;
5. void insert(int i, String n, float s) {
6. id=i;
7. name=n;
8. salary=s;
9. }
10. void display(){System.out.println(id+" "+name+" "+salary);}
11. }
12. public class TestEmployee {
13. public static void main(String[] args) {
14. Employee e1=new Employee();
15. Employee e2=new Employee();
16. Employee e3=new Employee();
17. e1.insert(101,"ajeet",45000);
18. e2.insert(102,"irfan",25000);
19. e3.insert(103,"nakul",55000);
20. e1.display();
21. e2.display();
22. e3.display();
23. }
24. }
Output:
There is given another example that maintains the records of Rectangle class.
File: TestRectangle1.java
1. class Rectangle{
2. int length;
3. int width;
4. void insert(int l, int w){
5. length=l;
6. width=w;
7. }
8. void calculateArea(){System.out.println(length*width);}
9. }
10. class TestRectangle1{
11. public static void main(String args[]){
12. Rectangle r1=new Rectangle();
13. Rectangle r2=new Rectangle();
14. r1.insert(11,5);
15. r2.insert(3,15);
16. r1.calculateArea();
17. r2.calculateArea();
18. }
19. }
20. Output:
21. 55
22. 45
Construction
In Java, constructor is a block of codes similar to method. It is called when an instance of object is created and
memory is allocated for the object.
Everytime an object is created using new() keyword, atleast one constructor is called. It is called a default
constructor.
Note: It is called constructor because it constructs the values at the time of object creation. It is not necessary to
write a constructor for a class. It is because java compiler creates a default constructor if your class doesn't have any.
1. <class_name>(){}
1. class Bike1{
2. Bike1()
3. {
4. System.out.println("Bike is created");
5. }
6. public static void main(String args[]){
7. Bike1 b=new Bike1();
8. }
9. } Output:Bike is created
To provide the default values to the object like 0, null etc. depending on the type
class Student3{
int id;
String name;
void display()
{
System.out.println(id+" "+name);
}
public static void main(String args[]){
Student3 s1=new Student3();
Student3 s2=new Student3();
s1.display(); s2.display();
}
OUtput
0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a default
constructor.Here 0 and null values are provided by default constructor.
222 Aryan
Output