Unit 1
Unit 1
UNIT I
UNIT I INTRODUCTION TO OOPS
CONCEPTS AND CLASSES
Introduction to Object Oriented Programming, Java buzzwords, Java
Programming Basics, Sample programs, Data types and operators,
Control statements. Classes: Classes, Objects, Methods, Constructors,
this and static keywords, Method and Constructor Overloading, Access
modifiers, Polymorphism. Arrays: One Dimensional and multi-
dimensional arrays
Before object Oriented Programming???
Procedural Programming Language : -
• Divided a program into a set of functions.
• Data stored in a bunch of variables. Functions
that operate on the data. This style of
programming is very simple and
straightforward.
• If make a change to one function, several others
function break. It becomes problematic.
Object Oriented Programming came to solve this
problem.
Object Oriented Programming
Object Oriented Programming,
• Combine a group of related variables and functions
into a unit, call that unit a object.
• Refer these variables as properties; Refer these
functions as methods.
Let us example,
Java User Input (Scanner)
• The Scanner class is used to get user input, and it is found in the java.util package.
Read Integer:-
int num1;
Scanner sc = new Scanner(System.in);
System.out.println("Enter First Number: ");
num1 = sc.nextInt();
System.out.println("Sum of these numbers: "+ num1);
Read String:-
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter username");
String userName = myObj.nextLine(); // Read user input
System.out.println("Username is: " + userName); // Output user input
Introduction to object Oriented Programming
• Object-Oriented Programming is a methodology or paradigm to
design a program using classes and objects.
• Object Oriented programming is a programming style which is
associated with the concepts like class, object, Inheritance,
Encapsulation, Abstraction, Polymorphism.
• Most popular programming languages like Java, C++, C#, Ruby,
etc. follow an object-oriented programming paradigm.
• It simplifies software development and maintenance by providing
some concepts:
Contd…Introduction to object Oriented
Programming
• Object
• Class
• Inheritance
• Polymorphism
• Abstraction
• Encapsulation
Object
• Objects have states and behaviors.
Relational Operators
• These operators are used to check for relations like equality, greater than, less
than.
• They return boolean result after the comparison and are extensively used in
looping statements as well as conditional if else statements.
Operators in Java..Contd..
Relational Operators example:
Relational comparison < > <= >=
equality == !=
Logical Operators
Logical operators are used to determine the logic between variables or
values
Operators in Java..Contd..
Logical Operators example:
Operator Name Description Example
&& Logical and Returns true if both statements are true x < 5 && x < 10
|| Logical or Returns true if one of the statements is x < 5 || x < 4
true
! Logical not Reverse the result, returns false if the !(x < 5 && x < 10)
result is true
OUTPUT
======
10 is even? true
Operators in Java..Contd..
Java Member Access Operator
• The Java member access operator is a dot (.) symbol that is used to
access data members and member methods of a class by its objects.
Java Comma Operator
• Java comma operator is a ',' sign that is used to separate function
arguments, and to declare more than one variable of same type in
one statement.
Java Array Index Operator
• Java array index operator, a set of square brackets ([]), is used to
declare and access array elements.
Operators in Java
Java new Operator
• The Java new operator is used to create a new object.
• Operator new is a Java keyword.
• It is followed by a call to a constructor, which initializes the new
object.
• Note that declaring an object and creating an object are two different
things.
• Simply declaring a reference variable does not create an object.
• For that, we need to use the new operator. The new operator creates
an object by allocating memory to it and returns a reference to that
memory location.
Operators in Java..contd..
public class constructordemo {
int value1;
int value2;
constructordemo(){
value1 = 10;
value2 = 20;
System.out.println("Inside Constructor");
}
public void display(){
System.out.println("Value1 === "+value1);
System.out.println("Value2 === "+value2);
}
public static void main(String args[]){
constructordemo d1 = new constructordemo();
d1.display();
}
}
Control statements
• Java control statements cause the flow of execution to advance and
branch based on the changes to the state of the program.
• Control statements are divided into three groups:
1) selection statements allow the program to choose different parts of
the execution based on the outcome of an expression
2) iteration statements enable program execution to repeat one or
more statements
3) jump statements enable your program to execute in a non-linear
fashion
A program can execute from top to bottom but if we use a control
statement.
Control statements..Contd..
Simple if Statement
• Simple if statement is the basic of decision-making statements in Java.
It decides if certain amount of code should be executed based on the
condition.
class ifTest
{
public static void main(String args[])
{
int x = 5;
if (x > 10)
System.out.println("Inside If");
System.out.println("After if statement");
}
}
Control statements..Contd..
if…else Statement
• In if…else statement, if condition is true then statements in if block
will be executed but if it comes out as false then else block will be
executed.
class ifelseTest
{
public static void main(String args[])
{
int x = 9;
if (x > 10)
System.out.println("i is greater than 10");
else
System.out.println("i is less than 10");
System.out.println("After if else statement");
}
}
Control statements..Contd..
Nested if statement
• Nested if statement is if inside an if block. It is same as normal if…else
statement but they are written inside another if…else statement.
class nestedifTest else
{ System.out.println("i is greater than 10 and
public static void main(String args[]) odd number");
{ }
int x = 25; else
{
if (x > 10) System.out.println("i is less than 10");
{ }
if (x%2==0) System.out.println("After nested if
System.out.println("i is greater than 10 and statement");
even number"); }
Control statements..Contd..
Switch Statement
• Java switch statement compares the value and executes one of the
case blocks based on the condition. It is same as if…else if ladder.
Rule:
• case value must be of the same type as expression used in switch
statement
• case value must be a constant or literal. It doesn’t allow variables
• case values should be unique. If it is duplicate, then program will give
compile time error
Control statements..Contd..
class switchDemo{ case 2:
public static void main(String args[]){ System.out.println("i is 2");
int i=2; break;
switch(i)
{ default:
case 0: System.out.println("i is not in the
System.out.println("i is 0"); list");
break; break;
case 1: }
System.out.println("i is 1"); }
break; }
Control statements..Contd..
Looping Statements in Java
• Looping statements are the statements which executes a block of code repeatedly
until some condition meet to the criteria.
• Loops can be considered as repeating if statements.
• There are 3 types of loops available in Java.
• for
• while
• do-while
For Statement
• It is the most common and widely used loop in Java.
• It is the easiest way to construct a loop structure in code as initialization of a
variable, a condition and increment/decrement are declared only in a single line of
code.
• It is easy to debug structure in Java.
Control statements..Contd..
• It is the easiest way to construct a loop structure in code as
initialization of a variable, a condition and increment/decrement are
declared only in a single line of code.
• It is easy to debug structure in Java.
class forLoopTest
{
public static void main(String args[])
{
for (int j = 1; j <= 5; j++)
System.out.println(j);
}
}
//1 2 3 4 5
Control statements..Contd..
while
• while loops are simplest kind of loop. It checks and evaluates the
condition and if it is true then executes the body of loop.
• This is repeated until the condition becomes false.
class whileLoopTest Output:
{ 1
public static void main(String 3
args[]) 5
7
{ 9
int j = 1;
while (j <= 10)
{
System.out.println(j);
j = j+2;
}
}
}
Control statements..Contd..
do…while
• do…while works same as while loop.
• It has only one difference that in do…while, condition is checked after
the execution of the loop body.
• That is why this loop is considered as exit control loop.
• In do…while loop, body of loop will be executed at least once before
checking the condition. class dowhileLoopTest do
{ {
public static void System.out.println(j);
main(String args[]) j = j+1;
{ } while (j <= 10);
int j = 10; }
} //10
Constructor and Constructor Overloading
• In Java a constructor is a block of codes similar
to the method. It is called when an instance of
the class is created.
• At the time of calling constructor, memory for
the object is allocated in the memory.
• Every time an object is created using the new()
keyword, at least one constructor is called.
• Unlike Java methods, a constructor has the same
name as that of the class and does not have any
return type.
• There are two types of constructors in Java: no-
argconstructor, parameterized constructor
and default constructor.
Constructor Example
Constructor Types - No-Arg Constructors
• a Java constructor may or may
not have any parameters
(arguments).
• If a constructor does not accept
any parameters, it is known as
a no-argument constructor. For
example,
private Main() {
// body of the constructor
}
Output:
Constructor Types - Parameterized Constructor
• A Java constructor can also
accept one or more parameters.
Such constructors are known as
parameterized constructors
private Main(String lang) {
// body of the constructor
}
Output:
Constructor Types - Default Constructor
• If we do not create any
constructor, the Java compiler
automatically create a no-arg
constructor during the
execution of the program.
• This constructor is called
default constructor.
Output:
Rules on Java Constructor
• Constructors are invoked implicitly when you instantiate objects.
there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
What is use of this keyword?
Example #2 – this: to invoke current class method
Output
hello n
hello m
What is use of this keyword?
• Example #3 – to invoke current class constructor
Output
hello a
10
What is use of this keyword?
• Example #4 – Calling parameterized constructor from default
constructor:
Output
5
hello a
What is use of static keyword?
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and
nested classes. The static keyword belongs to the class than an
instance of the class.
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable gets memory only once in the class area at the time
of class loading.
• It makes your program memory efficient (i.e., it saves memory).
What is use of static keyword?
• Example #1:
“Static Variable”
Output???
What is use of static keyword?
• Example #2 – Static Method:
• If you apply static keyword
with any method, it is known as
static method.
• A static method can be invoked
without the need for creating an
instance of a class.
Output:
from m1
What is use of static keyword?
• Example #3 – Static class
• A static class is a class that is
created inside a class, is called a
static nested class in Java.
• It cannot access non-static data
members and methods. It can be
accessed by outer class name.
• The static nested class cannot
access non-static (instance) data
members
Output:
data is 30
Arrays
• Normally, an array is a collection of similar type of elements which
have a contiguous memory location.
• Java array is an object which contains elements of a similar data type.
Additionally, The elements of an array are stored in a contiguous
memory location. It is a data structure where we store similar
elements.
• We can store only a fixed set of elements in a Java array.
• Array in Java is index-based, the first element of the array is stored at
the 0th index, 2nd element is stored on 1st index and so on.
Arrays..Contd..
Advantages
Code Optimization: It makes the code optimized, we can retrieve or sort the
data efficiently.
Random access: We can get any data located at an index position.
Disadvantages
Size Limit: We can store only the fixed size of elements in the array.
• It doesn't grow its size at runtime.
• To solve this problem, collection framework is used in Java which grows
automatically.
Types of Array in java
There are two types of array.
• Single Dimensional Array
• Multidimensional Array
Arrays..Contd..
Syntax
dataType[] arr; (or)
dataType []arr; (or)
dataType arr[];
//printing array
for(int i=0;i<a.length;i++)//length is the
property of array
System.out.println(a[i]);
}}
Arrays..Contd..example#2
import java.util.Scanner; for (int i = 0; i < count; i++)
public class JavaExample {
{ num[i] = scan.nextInt();
public static void main(String[] args) }
{
int count; scan.close();
System.out.print("Array Elements are: ");
//User inputs the array size for (int i = 0; i < count ; i++)
Scanner scan = new Scanner(System.in); {
System.out.print("Enter number of System.out.print(num[i] + ", ");
elements you want in the array: "); }
count = scan.nextInt(); }
}
int num[] = new int[count];
System.out.println("Enter array
elements:");
Two Dimensional Array
• The two-dimensional array can be defined as an array of arrays.
• The 2D array is organized as matrices which can be represented as the
collection of rows and columns.
Declaration of two dimensional Array in Java
• Consider the following example.
Two dimensional array:
int[][] twoD_arr = new int[10][20];
int[][] arr = { { 1, 2 }, { 3, 4 } };
System.out.println("arr[0][0] = " +
arr[0][0]);
}
}
OUTPUT:???
Two Dimensional Array
What is use of this keyword?
Use of ‘this’ keyword
The this keyword refers to the current object in a method or
constructor. The most common use of the this keyword is to
eliminate the confusion between class attributes and parameters
with the same name.
Usage of Java this keyword,
1.this can be used to refer current class instance variable.
2.this can be used to invoke current class method (implicitly)
3.this() can be used to invoke current class constructor.
4.this can be passed as an argument in the method call.
5.this can be passed as argument in the constructor call.
6.this can be used to return the current class instance from the method.
What is use of this keyword?
Example #1 – this: to refer current class instance variable
there is ambiguity between the instance variables and parameters, this keyword
resolves the problem of ambiguity.
What is use of this keyword?
Example #2 – this: to invoke current class method
Output
hello n
hello m
What is use of this keyword?
• Example #3 – to invoke current class constructor
Output
hello a
10
What is use of this keyword?
• Example #4 – Calling parameterized constructor from default
constructor:
Output
5
hello a
What is use of static keyword?
• The static keyword in Java is used for memory management mainly.
• We can apply static keyword with variables, methods, blocks and
nested classes. The static keyword belongs to the class than an
instance of the class.
1) Java static variable
• If you declare any variable as static, it is known as a static variable.
• The static variable gets memory only once in the class area at the time
of class loading.
• It makes your program memory efficient (i.e., it saves memory).
What is use of static keyword?
• Example #1:
“Static Variable”
Output???
What is use of static keyword?
• Example #2 – Static Method:
• If you apply static keyword
with any method, it is known as
static method.
• A static method can be invoked
without the need for creating an
instance of a class.
Output:
from m1
What is use of static keyword?
• Example #3 – Static class
• A static class is a class that is
created inside a class, is called a
static nested class in Java.
• It cannot access non-static data
members and methods. It can be
accessed by outer class name.
• The static nested class cannot
access non-static (instance) data
members
Output:
data is 30
Polymorphism in Java
• Polymorphism in Java is a concept by which we can perform a single
action in different ways. Polymorphism is derived from 2 Greek words:
poly and morphs. The word "poly" means many and "morphs" means
forms. So polymorphism means many forms.
• There are two types of polymorphism in Java: compile-time
polymorphism and runtime polymorphism.
Type 1: Compile-time polymorphism
• It is also known as static polymorphism. This type of polymorphism is
achieved by function overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
• Method Overloading: When there are multiple functions with the same
name but different parameters then these functions are said to
be overloaded.
Polymorphism in Java
Example #1 Method Overloading
Polymorphism in Java
Example #2 Method Overloading
Polymorphism in Java
Example #3 Method Overloading
Polymorphism in Java
Type 2: Run Time polymorphism
• It is also known as dynamic polymorphism. This type of polymorphism is achieved
by method overriding.
• Dynamic polymorphism is a process or mechanism in which a call to an overridden
method is to resolve at runtime rather than compile-time. It is also known as
runtime polymorphism.
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).
Polymorphism in Java
Example #1 Method Overriding
Polymorphism in Java
Example #2 Method Overriding
OUTPUT
subclass1
subclass2