You are on page 1of 63

UNIT-I

A way of viewing world :

A way of viewing the world is an idea to illustrate the object-oriented


programming concept with an example of a real-world situation.

Let us consider a situation, I am at my office and I wish to get food to my family


members who are at my home from a hotel. Because of the distance from my
office to home, there is no possibility of getting food from a hotel myself. So, how
do we solve the issue?

To solve the problem, let me call zomato (an agent in food delevery community),
tell them the variety and quantity of food and the hotel name from which I wish to
delever the food to my family members. Look at the following image.

Agents and Communities

To solve my food delivery problem, I used a solution by finding an appropriate


agent (Zomato) and pass a message containing my request. It is the responsibility
of the agent (Zomato) to satisfy my request. Here, the agent uses some method to

1
do this. I do not need to know the method that the agent has used to solve my
request. This is usually hidden from me.

So, in object-oriented programming, problem-solving is the solution to our


problem which requires the help of many individuals in the community. We may
describe agents and communities as follows.

An object-oriented program is structured as a community of interacting


agents, called objects. Where each object provides a service (data and
methods) that is used by other members of the community.
In our example, the online food delivery system is a community in which the
agents are zomato and set of hotels. Each hotel provides a variety of services that
can be used by other members like zomato, myself, and my family in the
community.

Messages and Methods

In object-oriented programming, every action is initiated by passing a


message to an agent (object), which is responsible for the action. The receiver
is the object to whom the message was sent. In response to the message, the
receiver performs some method to carry out the request. Every message may
include any additional information as arguments.
In our example, I send a request to zomato with a message that contains food
items, the quantity of food, and the hotel details. The receiver uses a method to
food get delivered to my home.

Methods:

A method is a block of code or collection of statements or a set of code grouped


together to perform a certain task or operation. It is used to achieve the reusability of
code. We write a method once and use it many times. We do not require to write code
again and again. It also provides the easy modification and readability of code, just by

2
adding or removing a chunk of code. The method is executed only when we call or
invoke it.

The most important method in Java is the main() method.

Responsibilities

In object-oriented programming, behaviors of an object described in terms of


responsibilities.

In our example, my request for action indicates only the desired outcome (food
delivered to my family). The agent (zomato) free to use any technique that solves
my problem. By discussing a problem in terms of responsibilities increases the
level of abstraction. This enables more independence between the objects in
solving complex problems.

Classes and Instances


Class:
 Class is a blueprint of an object.
 Class is a collection of variables and methods.
 Class is logical view of an object.
syntax of CLASS

class <ClassName>
{
attributes/variables;
Constructors();
methods();
}
INSTANCE
Instance is an Object of a class which is an entity with its own attribute
values and methods.

3
All objects are instances of a class.
Instance is allocating memory for non-static members of a class.

Syntax of Creating an Instance


ClassName refVariable;
refVariable = new Constructor();
or

ClassName refVariable = new Constructor();

Classes Hierarchies

A graphical representation is often used to illustrate the relationships among the


classes (objects) of a community. This graphical representation shows classes
listed in a hierarchical tree-like structure. In this more abstract class listed near the
top of the tree, and more specific classes in the middle of the tree, and the
individuals listed near the bottom.

In object-oriented programming, classes can be organized into a hierarchical


inheritance structure. A child class inherits properties from the parent class
that higher in the tree.

Method Binding, Overriding, and Exception

Connecting a method call to the method body is known as binding.

There are two types of binding

1. Static Binding (also known as Early Binding).


2. Dynamic Binding (also known as Late Binding).

static binding
When type of the object is determined at compiled time(by the compiler), it is known as
static binding.

If there is any private, final or static method in a class, there is static binding.

4
Dynamic binding
When type of the object is determined at run-time, it is known as dynamic binding.

Method Overriding:

If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that
has been declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding


o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o Method overriding is used for runtime polymorphism

Exceptions:
Exception is an abnormal condition that arises in the code sequence.
Exceptions occur during compile time or run time.
throwable is the super class in exception hierarchy.
Compile time errors occurs due to incorrect syntax.
Run-time errors happen when
o User enters incorrect input
o Resource is not available (ex. file)
o Logic error (bug) that was not fixed
Summary of OOPS:
OOP stands for Object-Oriented Programming. OOP is a programming paradigm
in which every program is follows the concept of object. In other words, OOP is a
way of writing programs based on the object concept.
The object-oriented programming paradigm has the following core concepts.

 Encapsulation
 Inheritance
 Polymorphism
 Abstraction

5
The popular object-oriented programming languages are Smalltalk, C++, Java,
PHP, C#, Python, etc.

Encapsulation

Encapsulation is the process of combining data and code into a single unit (object /
class). In OOP, every object is associated with its data and code. In programming,
data is defined as variables and code is defined as methods. The java programming
language uses the class concept to implement encapsulation.

Inheritance

Inheritance is the process of acquiring properties and behaviors from one object to
another object or one class to another class. In inheritance, we derive a new class

6
from the existing class. Here, the new class acquires the properties and behaviors
from the existing class. In the inheritance concept, the class which provides
properties is called as parent class and the class which recieves the properties is
called as child class. The parent class is also known as base class or supre class.
The child class is also known as derived class or sub class.
In the inheritance, the properties and behaviors of base class extended to its
derived class, but the base class never receive properties or behaviors from its
derived class.
In java programming language the keyword extends is used to implement
inheritance.

Polymorphism

7
Polymorphism is the process of defining same method with different
implementation. That means creating multiple methods with different behaviors.
The java uses method overloading and method overriding to implement
polymorphism.
Method overloading - multiple methods with same name but different parameters.
Method overriding - multiple methods with same name and same parameters.

Abstraction

Abstraction is hiding the internal details and showing only esential functionality. In
the abstraction concept, we do not show the actual implemention to the end user,
instead we provide only esential things. For example, if we want to drive a car, we
does not need to know about the internal functionality like how wheel system
works? how brake system works? how music system works? etc.

Java Buzz Words


Java is the most popular object-oriented programming language. Java has many
advanced features, a list of key features is known as Java Buzz Words. The java team
has listed the following terms as java buzz words.

 Simple
 Secure
8
 Portable
 Object-oriented
 Robust
 Architecture-neutral (or) Platform Independent
 Multi-threaded
 Interpreted
 High performance
 Distributed
 Dynamic

Simple
Java programming language is very simple and easy to learn, understand, and code.
Most of the syntaxes in java follow basic programming language C and object-oriented
programming concepts are similar to C++. In a java programming language, many
complicated features like pointers, operator overloading, structures, unions, etc. have
been removed. One of the most useful features is the garbage collector it makes java
more simple.

Secure
Java is said to be more secure programming language because it does not have
pointers concept, java provides a feature "applet" which can be embedded into a web
application. The applet in java does not allow access to other parts of the computer,
which keeps away from harmful programs like viruses and unauthorized access.

Object-oriented
Java is said to be a pure object-oriented programming language. In java, everything is
an object. It supports all the features of the object-oriented programming paradigm. The
primitive data types java also implemented as objects using wrapper classes, but still, it
allows primitive data types to archive high-performance.

Architecture-neutral (or) Platform Independent


Java has invented to archive "write once; run anywhere, any time, forever". The java
provides JVM (Java Virtual Machine) to to archive architectural-neutral or platform-
independent. The JVM allows the java program created using one operating system can
be executed on any other operating system.

Multi-threaded
Java supports multi-threading programming, which allows us to write programs that do
multiple operations simultaneously.

Interpreted

9
Java enables the creation of cross-platform programs by compiling into an intermediate
representation called Java bytecode. The byte code is interpreted to any machine code
so that it runs on the native machine.

High performance
Java provides high performance with the help of features like JVM, interpretation, and
its simplicity.

Dynamic
Java is said to be dynamic because the java byte code may be dynamically updated on
a running system and it has a dynamic memory allocation and deallocation (objects and
garbage collector).

Overview of Java
Java is a computer programming language. Java was created based on C and C++.
Java uses C syntax and many of the object-oriented features are taken from C++.
Before Java was invented there were other languages like COBOL, FORTRAN, C, C++,
Small Talk, etc. These languages had few disadvantages which were corrected in Java.
Java also innovated many new features to solve the fundamental problems which the
previous languages could not solve. Java was invented by a team of 13 employees of
Sun Microsystems, Inc. which is lead by James Gosling, in 1991. The team includes
persons like Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan, etc., Java
was developed as a part of the Green project. Initially, it was called Oak, later it was
changed to Java in 1995.

History of Java

10
 The C language developed in 1972 by Dennis Ritchie had taken a decade to
become the most popular language.
 In 1979, Bjarne Stroustrup developed C++, an enhancement to the C language
with included OOP fundamentals and features.
 A project named “Green” was initiated in December of 1990, whose aim was to
create a programming tool that could render obsolete the C and C++
programming languages.
 Finally in the year of 1991 the Green Team was created a new Programming
language named “OAK”.
 After some time they found that there is already a programming language with
the name “OAK”.
 So, the green team had a meeting to choose a new name. After so many
discussions they want to have a coffee. They went to a Coffee Shop which is just
outside of the Gosling’s office and there they have decided name as “JAVA”.

Execution Process of Java Program


The following three steps are used to create and execute a java program.

 Create a source code (.java file).


 Compile the source code using javac command.
 Run or execute .class file uisng java command.

11
Data Types in Java

Data types represent the different values to be stored in the variable. In java, there
are two types of data types:

o Primitive data types


o Non-primitive data types

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

12
byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte


Example:

class Datatypes{
public static void main(String[] args) {
int myNum = 5; // integer (whole number)
float myFloatNum = 5.99f; // floating point number
char myLetter = 'D'; // character
boolean myBool = true; // boolean
String myText = "Hello"; // String
System.out.println(myNum);
System.out.println(myFloatNum);
System.out.println(myLetter);
System.out.println(myBool);
System.out.println(myText);
}
}
O/p:

5
5.99
D
True
Hello
lo

Variable:

13
Variable is name of reserved area allocated in memory. In other words, it is
a name of memory location.

 The value stored in a variable can be changed during program execution.


 Variables in Java are only a name given to a memory location. All the
operations done on the variable affect that memory location.
 In Java, all variables must be declared before use.

1. int data=50;//Here data is variable


Types of Variable

There are three types of variables in java:

o local variable
o instance variable
o static variable

1) Local Variable

A variable which is declared inside the method is called local variable.

14
2) Instance Variable

A variable which is declared inside the class but outside the method, is called
instance variable . It is not declared as static.

3) Static variable

A variable that is declared as static is called static variable. It cannot be local.

We will have detailed learning of these variables in next chapters.

Example to understand the types of variables in java


1. class A{
2. int data=50;//instance variable
3. static int m=100;//static variable
4. void method(){
5. int n=90;//local variable
6. }
7. }//end of class

Java Array

Array is a collection of similar type of elements that have contiguous memory


location.

Java array is an object the contains elements of similar data type. It is a data
structure where we store similar elements. We can store only fixed set of elements
in a java array.

Array in java is index based, first element of the array is stored at 0 index.

15
Advantage of Java Array
o Code Optimization: It makes the code optimized, we can retrieve or sort
the data easily.
o Random access: We can get any data located at any index position.

Disadvantage of Java Array


o Size Limit: We can store only 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.

Types of Array in java

There are two types of array.

o Single Dimensional Array


o Multidimensional Array

Declaration, Instantiation and Initialization of Java Array

We can declare, instantiate and initialize the java array together by:

1. int a[]={33,3,4,5};//declaration, instantiation and initialization

Let's see the simple example to print this array.

1. class Testarray1{
2. public static void main(String args[]){
3.
4. int a[]={33,3,4,5};//declaration, instantiation and initialization
5.
6. //printing array
7. for(int i=0;i<a.length;i++)//length is the property of array
8. System.out.println(a[i]);
9.
10.}}
Output:33
3

16
4
5

Example of Multidimensional Java Array

Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional
array.

1. //Java Program to illustrate the use of multidimensional array


2. class Testarray3{
3. public static void main(String args[]){
4. //declaring and initializing 2D array
5. int arr[][]={{1,2,3},{2,4,5},{4,4,5}};
6. //printing 2D array
7. for(int i=0;i<3;i++){
8. for(int j=0;j<3;j++){
9. System.out.print(arr[i][j]+" ");
10. }
11. System.out.println();
12. }
13. }}

Output:

1 2 3
2 4 5
4 4 5

Java Operators
Operators:
An operator is a symbol that performs an operation. An operator acts on variables
called operands.

Arithmetic operators:These operators are used to perform fundamental operations


like
addition, subtraction, multiplication etc.

17
Operator Meaning Example Result
+ Addition 3+4 7
- Subtraction 5-3 2
* Multiplication 5*5 25
/ Division(gives 14/7 2
quotient)
% Modulus(gives 20%7 6
remainder)

Program 1:Write a program to perform arithmetic operations


//Addition of two numbers
classAddTwoNumbers
{
public static void mian(String args[])
{
int i=10, j=20;
System.out.println("Addition of two numbers is : " + (i+j));
System.out.println("Subtraction of two numbers is : " + (i-j));
System.out.println("Multiplication of two numbers is : " + (i*j));
System.out.println("Quotient after division is : " + (i/j) );
System.out.println("Remainder after division is : " +(i%j) );
}
}
Output:

Assignment operator:This operator (=) is used to store some value into a variable.

Simple Assignment Compound Assignment


x=x+y x += y
x=x–y x -= y
x=x*y x *= y

18
x = x /y x /= y

Unary operators:As the name indicates unary operator’s act only on one operand.

Operator Meaning Example Explanation


- Unary j = -k; k value is negated and stored into j
minus
++ Increment b++; b value will be incremented by 1
Operator ++b; (called as post incrementation)
b value will be incremented by 1
(called as pre incrementation)
-- Decrement b--; b value will be decremented by 1
Operator --b; (called as post decrementation)
b value will be decremented by 1
(called as pre decrementation)

Relational operators:These operators are used for comparison purpose.

Operator Meaning Example


== Equal x == 3
!= Not equal x != 3
< Less than x<3
> Greater than x>3
<= Less than or equal to x<=3
>= Greater than or equal to x>=3

Logical operators:Logical operators are used to construct compound conditions. A


compound condition is a combination of several simple conditions.
Operator Meaning Example Explanation
&& And if(a>b && a>c) If a value is greater
operator System.out.print(“yes”); than b and c
then only yes is
displayed
|| Or operator if(a==1 || b==1) If either a value is 1
System.out.print(“yes”); or b value is 1

19
then yes is displayed
! Not operator if( !(a==0) ) If a value is not
System.out.print(“yes”); equal to zero then
only yes is displayed

Bitwise operators: These operators act on individual bits (0 and 1) of the


operands. They
act only on integer data types, i.e. byte, short, long and int.

Operator Meaning Explanation


& Bitwise AND Multiples the individual bits of operands.
| Bitwise OR Adds the individual bits of operands.
^ Bitwise XOR Performs Exclusive OR operation .
<< Left shift Shifts the bits of the number towards left a
specified number of positions.
>> Right shift Shifts the bits of the number towards right a
specified number of positions and also
preserves the sign bit.
>>> Zero fill right Shifts the bits of the number towards right a
shift specified number of positions and it stores 0
(Zero) in the sign bit.
~ Bitwise Gives the complement form of a given number
complement by
changing 0’s as 1’s and vice versa.

Java Unary Operator Example: ++ and --


class OperatorExample{
public static void main(String args[]){
int x=10;
System.out.println(x++);//10 (11)
System.out.println(++x);//12
System.out.println(x--);//12 (11)
System.out.println(--x);//10
}}

Output:

20
10
12
12
10
Java Unary Operator Example 2: ++ and --
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=10;
System.out.println(a++ + ++a);//10+12=22
System.out.println(b++ + b++);//10+11=21
}}

Output:

22
21
Java Arithmetic Operator Example
class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
System.out.println(a+b);//15
System.out.println(a-b);//5
System.out.println(a*b);//50
System.out.println(a/b);//2
System.out.println(a%b);//0
}}

Output:

15
5
50
2
0

21
Java Arithmetic Operator Example: Expression
class OperatorExample{
public static void main(String args[]){
System.out.println(10*10/5+3-1*4/2);
}}

Output:

21
Java Shift Operator Example: Left Shift
class OperatorExample{
public static void main(String args[]){
System.out.println(10<<2);//10*2^2=10*4=40
System.out.println(10<<3);//10*2^3=10*8=80
System.out.println(20<<2);//20*2^2=20*4=80
System.out.println(15<<4);//15*2^4=15*16=240
}}

Output:

40
80
80
240
Java Shift Operator Example: Right Shift
class OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

Output:

2
5
2

22
Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn't check second condition if first condition is false.
It checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is
true or false.

class OperatorExample{
public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a<b&&a<c);//false && true = false
System.out.println(a<b&a<c);//false & true = false
}}

Output:

false
false
Java Ternary Operator Example
class OperatorExample{
public static void main(String args[]){
int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:

Java Expressions
In any programming language, if we want to perform any calculation or to frame any
condition etc., we use a set of symbols to perform the task. These set of symbols makes
an expression.
In the java programming language, an expression is defined as follows.

23
An expression is a collection of operators and operands that represents a
specific value.
In the above definition, an operator is a symbol that performs tasks like arithmetic
operations, logical operations, and conditional operations, etc.
Operands are the values on which the operators perform the task. Here operand can
be a direct value or variable or address of memory location.

Expression Types
In the java programming language, expressions are divided into THREE types. They are
as follows.

 Infix Expression
 Postfix Expression
 Prefix Expression

The above classification is based on the operator position in the expression.

Infix Expression
The expression in which the operator is used between operands is called infix
expression.
The infix expression has the following general structure.

Example

Postfix Expression
The expression in which the operator is used after operands is called postfix
expression.
The postfix expression has the following general structure.

Example

24
Prefix Expression
The expression in which the operator is used before operands is called a prefix
expression.
The prefix expression has the following general structure.

Example

Java Control Statements


In java, the default execution flow of a program is a sequential order. But the sequential
order of execution flow may not be suitable for all situations. Sometimes, we may want
to jump from line to another line, we may want to skip a part of the program, or
sometimes we may want to execute a part of the program again and again. To solve
this problem, java provides control statements.

In java, the control statements are the statements which will tell us that in which order
the instructions are getting executed. The control statements are used to control the
order of execution according to our requirements. Java provides several control
statements, and they are classified as follows.

Types of Control Statements


In java, the control statements are classified as follows.

25
 Selection Control Statements ( Decision Making Statements )
 Iterative Control Statements ( Looping Statements )
 Jump Statements

Let's look at each type of control statements in java.

Selection Control Statements


In java, the selection statements are also known as decision making statements or
branching statements. The selection statements are used to select a part of the
program to be executed based on a condition. Java provides the following selection
statements.

 if statement
 if-else statement
 if-elif statement
 nested if statement
 switch statement

Iterative Control Statements


In java, the iterative statements are also known as looping statements or repetitive
statements. The iterative statements are used to execute a part of the program
repeatedly as long as the given condition is True. Using iterative statements reduces
the size of the code, reduces the code complexity, makes it more efficient, and
increases the execution speed. Java provides the following iterative statements.

 while statement
 do-while statement
 for statement
 for-each statement

Jump Statements
In java, the jump statements are used to terminate a block or take the execution control
to the next iteration. Java provides the following jump statements.

 break
 continue
 return

Read more about Jump Statements in java

Java Iterative Statements

26
while statement in java
The while statement is used to execute a single statement or block of statements
repeatedly as long as the given condition is TRUE. The while statement is also known
as Entry control looping statement. The syntax and execution flow of while statement is
as follows.

Java Program
public class WhileTest {

public static void main(String[] args) {

int num = 1;

while(num <= 10) {


System.out.println(num);
num++;
}

System.out.println("Statement after while!");

do-while statement in java


The do-while statement is used to execute a single statement or block of statements
repeatedly as long as given the condition is TRUE. The do-while statement is also
known as the Exit control looping statement. The do-while statement has the
following syntax.

27
Java Program
public class DoWhileTest {

public static void main(String[] args) {

int num = 1;

do {
System.out.println(num);
num++;
}while(num <= 10);

System.out.println("Statement after do-while!");

for statement in java


The for statement is used to execute a single statement or a block of statements
repeatedly as long as the given condition is TRUE. The for statement has the following
syntax and execution flow diagram.
In for-statement, the execution begins with the initialization statement. After the
initialization statement, it executes Condition. If the condition is evaluated to true, then
the block of statements executed otherwise it terminates the for-statement. After the
block of statements execution, the modification statement gets executed, followed by
condition again.
Let's look at the following example java code.

Java Program
28
public class ForTest {

public static void main(String[] args) {

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


System.out.println("i = " + i);
}

System.out.println("Statement after for!");


}

When we run this code, it produce the following output.

for-each statement in java


The Java for-each statement was introduced since Java 5.0 version. It provides an
approach to traverse through an array or collection in Java. The for-each statement also
known as enhanced for statement. The for-each statement executes the block of
statements for each element of the given array or collection.

Java Program
public class ForEachTest {

public static void main(String[] args) {

int[] arrayList = {10, 20, 30, 40, 50};

29
for(int i : arrayList) {
System.out.println("i = " + i);
}

System.out.println("Statement after for-each!");


}

Java Classes
 The java class is a template of an object.
 Class is a collection of variables and methods.
 Class is a blueprint of an object.
 Class is logical view of an object.
A class in Java can contain:
o fields
o methods
o constructors
o blocks
o nested class and interface
Every class in java forms a new data type. Once a class got created, we can generate
as many objects as we want. Every class defines the properties and behaviors of an
object. All the objects of a class have the same properties and behaviors that were
defined in the class.
Every class of java programming language has the following characteristics.
Look at the following picture to understand the class and object concept.

30
Creating a Class
In java, we use the keyword class to create a class. A class in java contains properties
as variables and behaviors as methods. Following is the syntax of class in the java.

Syntax
class <ClassName>{
data members declaration;
methods defination;
}

🔔 The ClassName must begin with an alphabet, and the Upper-case letter is preferred.
🔔 The ClassName must follow all naming rules.

31
Creating an Object
In java, an object is an instance of a class.

o Object is a real world entity.


o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class. instance is allocating memory for non-static
members of a class.

When an object of a class is created, the class is said to be instantiated. All the objects
that are created using a single class have the same properties and methods. But the
value of properties is different for every object.

An object has three characteristics:

 State - Represents data values that are associated with an object.


 Behavior - Represents actions can be performed by an object.
 Identity - It is the name given to the class.

Following is the syntax of Object in the java.

Syntax
<ClassName> <objectName> = new <ClassName>( );

🔔 The objectName must begin with an alphabet, and a Lower-case letter is preferred.
🔔 The objectName must follow all naming rules.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
32
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();
e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Output:

101 ajeet 45000.0


102 irfan 25000.0
103 nakul 55000.0

Method in Java

 A method is sub block of a class. the logic should be return inside the
method.
 A method represents a group of statements to perform a task.
 A method is like function i.e. used to expose behavior of an object.
 A Java method is a collection of statements that are grouped together to
perform an operation.

Advantage of Method
o Code Reusability
o Code Optimization

33
General form of method:

Type name(parameter-list)
{

//body of the method


}

Example program on method.


Class Student{
Int sno;
double math;
double phy;
double chem;
void getAverage() //method defination
{
double avg=(math+phy+chem.)/3;
System.out.println(“average marks of student: “+sno+” is “+avg);
}
Public class Methoddemo
{
Public static void main(String[] args)
{
Student stumar=new Student();
stumar.sno=101;
stumar.math=95;
stumar.phy=80;
stumar.chem=85;
stumar.getAverage(); //method call
}
}
Output:
Average marks of student: 101 is 86.6666666666

34
Constructor
A constructor is a special method of a class that has the same name as the class name.
The constructor gets executes automatically on object creation. It does not require the
explicit method call. A constructor may have parameters and access specifiers too. In
java, if you do not provide any constructor the compiler automatically creates a default
constructor.
Let's look at the following example java code.

Example
public class ConstructorExample {

ConstructorExample() {
System.out.println("Object created!");
}
public static void main(String[] args) {

ConstructorExample obj1 = new ConstructorExample();


ConstructorExample obj2 = new ConstructorExample();
}

Output:

🔔 A constructor can not have return value.


Java String Handling
A string is a sequence of characters surrounded by double quotations. In a java
programming language, a string is the object of a built-in class String.

The java.lang.String class is used to create a string object.

35
How to create a string object?
There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
Java String literal is created by using double quotes. For Example:

1. String s="welcome";

Each time you create a string literal, the JVM checks the "string constant pool" first. If
the string already exists in the pool, a reference to the pooled instance is returned. If the
string doesn't exist in the pool, a new string instance is created and placed in the pool.
For example:

1. String s1="Welcome";
2. String s2="Welcome";//It doesn't create a new instance

In the above example, only one object will be created. Firstly, JVM will not find any string
object with the value "Welcome" in string constant pool that is why it will create a new
object. After that it will find the string with the value "Welcome" in the pool, it will not
create a new object but will return the reference to the same instance.

36
Note: String objects are stored in a special memory area known as the "string constant
pool".

Why Java uses the concept of String literal?


To make Java more memory efficient (because no new objects are created if it exists
already in the string constant pool).

2) By new keyword
1. String s=new String("Welcome");//creates two objects and one reference variable

In such case, JVM will create a new string object in normal (non-pool) heap memory,
and the literal "Welcome" will be placed in the string constant pool. The variable s will
refer to the object in a heap (non-pool).

Java String Example


StringExample.java

1. public class StringExample{


2. public static void main(String args[]){
3. String s1="java";//creating string by Java string literal
4. char ch[]={'s','t','r','i','n','g','s'};
5. String s2=new String(ch);//converting char array to string
6. String s3=new String("example");//creating Java string by new keyword
7. System.out.println(s1);
8. System.out.println(s2);
9. System.out.println(s3);
10. }}

Output:

java
strings
example

The above code, converts a char array into a String object. And displays the String
objects s1, s2, and s3 on console using println() method.

37
Java String class methods
The java.lang.String class provides many useful methods to perform operations on
sequence of char values.

No. Method Description

1 char charAt(int index) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

6 String substring(int beginIndex, int endIndex) It returns substring for given begin
index and end index.

7 boolean contains(CharSequence s) It returns true or false after matching


the sequence of char value.

8 static String join(CharSequence delimiter, It returns a joined string.


CharSequence... elements)

9 static String join(CharSequence delimiter, Iterable<? It returns a joined string.


extends CharSequence> elements)

10 boolean equals(Object another) It checks the equality of string with


the given object.

38
Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties
and behaviors of parent object. It is an important part of OOPs (Object Oriented
programming system).

The idea behind inheritance in java is that you can create new classes that are built
upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of parent class. Moreover, you can add new methods and fields
in your current class also.

Inheritance represents the IS-A relationship, also known as parent-


child relationship.

Why use inheritance in java


o For Method Overriding (so runtime polymorphism can be achieved).

o For Code Reusability.

Terms used in Inheritence


o Class: A class is a group of objects which have common properties. It is a
template or blueprint from which objects are created.
o Sub Class/Child Class: Subclass is a class which inherits the other class. It
is also called a derived class, extended class, or child class.
o Super Class/Parent Class: Super class is the class from where a subclass
inherits the features. It is also called a base class or a parent class.
o Reusability: As the name specifies, reusability is a mechanism which
facilitates you to reuse the fields and methods of the existing class when you
create a new class. You can use the same fields and methods already defined
in previous class.

Syntax of Java Inheritance


1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }

The extends keyword indicates that you are making a new class that derives from
an existing class. The meaning of "extends" is to increase the functionality.

39
In the terminology of Java, a class which is inherited is called parent or super class
and the new class is called child or subclass.

Example

classCalculation{
int z;

publicvoid addition(int x,int y){


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

publicvoidSubtraction(int x,int y){


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

publicclassMy_CalculationextendsCalculation{
publicvoid multiplication(int x,int y){
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

publicstaticvoid main(Stringargs[]){
int a =20, b =10;
My_Calculation demo =newMy_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Compile and execute the above code as shown below.

javac My_Calculation.java
javaMy_Calculation
After executing the program, it will produce the following result −
Output
40
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

In java programming, multiple and hybrid inheritance is supported through


interface only. We will learn about interfaces later.

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For
Example:

41
Single Inheritance Example

File: TestInheritance.java

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.}}

Output:

barking...
eating...

42
Multilevel Inheritance Example

File: TestInheritance2.java

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();
16.}}

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example

File: TestInheritance3.java

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

43
9. }
10.class TestInheritance3{
11.public static void main(String args[]){
12.Cat c=new Cat();
13.c.meow();
14.c.eat();
15.//c.bark();//C.T.Error
16.}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not
supported in java.

Consider a scenario where A, B and C are three classes. The C class inherits A and
B classes. If A and B classes have same method and you call it from child class
object, there will be ambiguity to call method of A or B class.

Since compile time errors are better than runtime errors, java renders compile time
error if you inherit 2 classes. So whether you have same method or different, there
will be compile time error now.

1. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. Public Static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?

44
12.}
13.}

Compile Time Error

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

There are many non-access modifiers, such as static, abstract, synchronized, native,
volatile, transient, etc. Here, we are going to learn the access modifiers only.

mazon Alexa Can Now Mimic the Voice of a Deceased Relative

Understanding Java Access Modifiers


Let's understand the access modifiers in Java by a simple table.

Access within within outside package by subclass outside

45
Modifier class package only package

Private Y N N N

Default Y Y N N

Protected Y Y Y N

Public Y Y Y Y

🔔 The public members can be accessed everywhere.


🔔 The private members can be accessed only inside the same class.
🔔 The protected members are accessible to every child class (same package or other
packages).
🔔 The default members are accessible within the same package but not outside the
package.

Example
class ParentClass{
int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {
System.out.println("Inside ParentClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}

class ChildClass extends ParentClass{

void accessData() {

46
System.out.println("Inside ChildClass");
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
//System.out.println("d = " + d); // private member can't be accessed
}

}
public class AccessModifiersExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();
obj.accessData();

}
}

o/p:

Constructors 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.

It is a special type of method which is used to initialize the object.

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 class. In such case, Java compiler
provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

47
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.

Rules for creating Java constructor


There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Note: We can use access modifiers

while declaring a constructor. It controls the object creation. In other words, we can have
private, protected, public or default constructor in Java.

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:


1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of obje
creation.

48
1. //Java Program to create and call a default constructor
2. class Bike1{
3. //creating a default constructor
4. Bike1(){System.out.println("Bike is created");}
5. //main method
6. public static void main(String args[]){
7. //calling a default constructor
8. Bike1 b=new Bike1();
9. }
10. }
Test it Now

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null,
etc., depending on the type.

49
Java Parameterized Constructor
A constructor which has a specific number of parameters is called a parameterized
constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two
parameters. We can have any number of parameters in the constructor.

1. //Java Program to demonstrate the use of the parameterized constructor.


2. class Student4{
3. int id;
4. String name;
5. //creating a parameterized constructor
6. Student4(int i,String n){
7. id = i;
8. name = n;
9. }
10. //method to display the values
11. void display(){System.out.println(id+" "+name);}
12.
13. public static void main(String args[]){
14. //creating objects and passing values
15. Student4 s1 = new Student4(111,"Karan");
16. Student4 s2 = new Student4(222,"Aryan");
17. //calling method to display the values of object
18. s1.display();
19. s2.display();
20. }
21. }

50
Output:

111 Karan
222 Aryan

Super Keyword in Java


The super keyword in Java is a reference variable which is used to refer immediate
parent class object.

Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.

Usage of Java 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.

51
1) super is used to refer immediate parent class
instance variable.
We can use super keyword to access the data member or field of parent class. It is used
if parent class and child class have same fields.

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. }}
TeOutput:
MJava Tricky Program 23 - Main method signature
black
white

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used
in many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it
is called blank final variable or uninitialized final variable. It can be initialized in the

52
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of
final keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but
It can't be changed because final variable once assigned a value can never be changed.

1. class Bike9{
2. final int speedlimit=90;//final variable
3. void run(){
4. speedlimit=400;
5. }
6. public static void main(String args[]){
7. Bike9 obj=new Bike9();
8. obj.run();
9. }
10. }//end of class
Output:Compile Time Error

53
Java Pylymorphism
The polymorphism is the process of defining same method with different
implementation. That means creating multiple methods with different behaviors.
In java, polymorphism implemented using method overloading and method overriding.

Ad hoc polymorphism
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc
polymorphism carried out with a method overloading concept.
In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded
with the respective overloaded method based on the arguments.
The ad hoc polymorphism implemented within the class only.
Let's look at the following example java code.

Example
import java.util.Arrays;

public class AdHocPolymorphismExample {

void sorting(int[] list) {


Arrays.parallelSort(list);
System.out.println("Integers after sort: " + Arrays.toString(list) );
}
void sorting(String[] names) {
Arrays.parallelSort(names);
System.out.println("Names after sort: " + Arrays.toString(names) );
}

public static void main(String[] args) {

AdHocPolymorphismExample obj = new AdHocPolymorphismExample();


int list[] = {2, 3, 1, 5, 4};
obj.sorting(list); // Calling with integer array

String[] names = {"rama", "raja", "shyam", "seeta"};


obj.sorting(names); // Calling with String array
}

54
}

When we run this code, it produce the following output.

Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same
arguments but different implementations. In a java programming language, pure
polymorphism carried out with a method overriding concept.
In pure polymorphism, the method binding happens at run time. Pure polymorphism is
also known as run-time polymorphism. Every function call binding with the respective
overridden method based on the object reference.
When a child class has a definition for a member function of the parent class, the parent
class function is said to be overridden.
The pure polymorphism implemented in the inheritance concept only.
Let's look at the following example java code.

Example
class ParentClass{

int num = 10;

void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);

55
}
}

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


obj.showData();

obj = new ChildClass();


obj.showData();

}
}

When we run this code, it produce the following output.

Java Method Overriding


The method overriding is the process of re-defining a method in a child class that is
already defined in the parent class. When both parent and child classes have the same
method, then that method is said to be the overriding method.
The method overriding enables the child class to change the implementation of the
method which aquired from parent class according to its requirement.
In the case of the method overriding, the method binding happens at run time. The
method binding which happens at run time is known as late binding. So, the method
overriding follows late binding.
The method overriding is also known as dynamic method dispatch or run time
polymorphism or pure polymorphism.
Let's look at the following example java code.

Example
class ParentClass{

int num = 10;

56
void showData() {
System.out.println("Inside ParentClass showData() method");
System.out.println("num = " + num);
}

class ChildClass extends ParentClass{

void showData() {
System.out.println("Inside ChildClass showData() method");
System.out.println("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


obj.showData();

obj = new ChildClass();


obj.showData();

}
}

When we run this code, it produce the following output.

10 Rules for method overriding


While overriding a method, we must follow the below list of rules.

 Static methods can not be overridden.


 Final methods can not be overridden.
 Private methods can not be overridden.

57
 Constructor can not be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent has it.
 The access specifier of the overriding method can be changed, but the visibility
must increase but not decrease. For example, a protected method in the parent
class can be made public, but not private, in the child class.
 If the overridden method does not throw an exception in the parent class, then
the child class overriding method can only throw the unchecked exception,
throwing a checked exception is not allowed.
 If the parent class overridden method does throw an exception, then the child
class overriding method can only throw the same, or subclass exception, or it
may not throw any exception.

Java Abstract Class


An abstract class is a class that created using abstract keyword. In other words, a class
prefixed with abstract keyword is known as an abstract class.
In java, an abstract class may contain abstract methods (methods without
implementation) and also non-abstract methods (methods with implementation).
We use the following syntax to create an abstract class.

Syntax
abstract class <ClassName>{
...
}

Let's look at the following example java code.

Example
import java.util.*;

abstract class Shape {


int length, breadth, radius;
Scanner input = new Scanner(System.in);

58
abstract void printArea();

class Rectangle extends Shape {


void printArea() {
System.out.println("*** Finding the Area of Rectangle ***");
System.out.print("Enter length and breadth: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Triangle ***");
System.out.print("Enter Base And Height: ");
length = input.nextInt();
breadth = input.nextInt();
System.out.println("The area of Triangle is: " + (length * breadth) / 2);
}
}

class Cricle extends Shape {


void printArea() {
System.out.println("\n*** Finding the Area of Cricle ***");
System.out.print("Enter Radius: ");
radius = input.nextInt();
System.out.println("The area of Cricle is: " + 3.14f * radius *
radius);
}

59
}

public class AbstractClassExample {


public static void main(String[] args) {
Rectangle rec = new Rectangle();
rec.printArea();

Triangle tri = new Triangle();


tri.printArea();

Cricle cri = new Cricle();


cri.printArea();
}
}

Java Object Class


In java, the Object class is the super most class of any class hierarchy. The Object
class in the java programming language is present inside the java.lang package.
Every class in the java programming language is a subclass of Object class by default.
The Object class is useful when you want to refer to any object whose type you don't
know. Because it is the superclass of all other classes in java, it can refer to any type of
object.

Methods of Object class


The following table depicts all built-in methods of Object class in java.

60
Return
Method Description Value

getClass() Returns Class class object object

hashCode() returns the hashcode number for object being used. int

equals(Object compares the argument object to calling object. boolean


obj)

clone() Compares two strings, ignoring case int

concat(String) Creates copy of invoking object object

toString() eturns the string representation of invoking object. String

notify() wakes up a thread, waiting on invoking object's monitor. void

notifyAll() wakes up all the threads, waiting on invoking object's monitor. void

wait() causes the current thread to wait, until another thread notifies. void

wait(long,int) causes the current thread to wait for the specified milliseconds void
and nanoseconds, until another thread notifies.

finalize() It is invoked by the garbage collector before an object is being void


garbage collected.

Java Forms of Inheritance


The inheritance concept used for the number of purposes in the java programming
language. One of the main purposes is substitutability. The substitutability means that
when a child class acquires properties from its parent class, the object of the parent

61
class may be substituted with the child class object. For example, if B is a child class of
A, anywhere we expect an instance of A we can use an instance of B.
The substitutability can achieve using inheritance, whether using extends or implements
keywords.
The following are the differnt forms of inheritance in java.

 Specialization
 Specification
 Construction
 Eextension
 Limitation
 Combination

Specialization
It is the most ideal form of inheritance. The subclass is a special case of the parent
class. It holds the principle of substitutability.

Specification
This is another commonly used form of inheritance. In this form of inheritance, the
parent class just specifies which methods should be available to the child class but
doesn't implement them. The java provides concepts like abstract and interfaces to
support this form of inheritance. It holds the principle of substitutability.

Construction
This is another form of inheritance where the child class may change the behavior
defined by the parent class (overriding). It does not hold the principle of substitutability.

Eextension
This is another form of inheritance where the child class may add its new properties. It
holds the principle of substitutability.

Limitation
This is another form of inheritance where the subclass restricts the inherited behavior. It
does not hold the principle of substitutability.

Combination

62
This is another form of inheritance where the subclass inherits properties from multiple
parent classes. Java does not support multiple inheritance type.

Benefits and Costs of Inheritance in


java
The inheritance is the core and more usful concept Object Oriented Programming. It
proWith inheritance, we will be able to override the methods of the base class so that
the meaningful implementation of the base class method can be designed in the derived
class. An inheritance leads to less development and maintenance costs.vides lot of
benefits and few of them are listed below.

Benefits of Inheritance
 Inheritance helps in code reuse. The child class may use the code defined in the
parent class without re-writing it.
 Inheritance can save time and effort as the main code need not be written again.
 Inheritance provides a clear model structure which is easy to understand.
 An inheritance leads to less development and maintenance costs.
 With inheritance, we will be able to override the methods of the base class so
that the meaningful implementation of the base class method can be designed in
the derived class. An inheritance leads to less development and maintenance
costs.
 In inheritance base class can decide to keep some data private so that it cannot
be altered by the derived class.

Costs of Inheritance
 Inheritance decreases the execution speed due to the increased time and effort it
takes, the program to jump through all the levels of overloaded classes.
 Inheritance makes the two classes (base and inherited class) get tightly coupled.
This means one cannot be used independently of each other.
 The changes made in the parent class will affect the behavior of child class too.
 The overuse of inheritance makes the program more complex.

63

You might also like