0% found this document useful (0 votes)
13 views83 pages

Java Unit 1

The document provides an overview of Java programming, emphasizing object-oriented programming concepts such as encapsulation, inheritance, polymorphism, and abstraction. It explains the structure of object-oriented programs as communities of interacting agents (objects) and details the execution process of Java programs, data types, and variables. Additionally, it highlights Java's key features, history, and its evolution from earlier programming languages.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views83 pages

Java Unit 1

The document provides an overview of Java programming, emphasizing object-oriented programming concepts such as encapsulation, inheritance, polymorphism, and abstraction. It explains the structure of object-oriented programs as communities of interacting agents (objects) and details the execution process of Java programs, data types, and variables. Additionally, it highlights Java's key features, history, and its evolution from earlier programming languages.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

R18 - UNIT-1 - Java Programming

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 delivery community), tell them the
variety and quantity of food and the hotel name from which I wish to deliver 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 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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 1


Messages and Methods

To solve my problem, I started with a request to the agent zomato, which led to still more
requests among the members of the community until my request has done. Here, the members
of a community interact with one another by making requests until the problem has satisfied.
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.

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

In object-oriented programming, all objects are instances of a class. The method invoked by an
object in response to a message is decided by the class. All the objects of a class use the same
method in response to a similar message.
In our example, the zomato a class and all the hotels are sub-classes of it. For every request
(message), the class creates an instance of it and uses a suitable method to solve the problem.

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

In the class hierarchy, both parent and child classes may have the same method which
implemented individually. Here, the implementation of the parent is overridden by the child. Or

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 2


a class may provide multiple definitions to a single method to work with different arguments
(overloading).
The search for the method to invoke in response to a request (message) begins with the class of
this receiver. If no suitable method is found, the search is performed in the parent class of it. The
search continues up the parent class chain until either a suitable method is found or the parent
class chain is exhausted. If a suitable method is found, the method is executed. Otherwise, an
error message is issued.

OOP Concepts in Java


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

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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 3


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 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 receives the properties is called as child class. The parent class is also known as base class
or super 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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 4


Polymorphism

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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 5


Abstraction

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 6


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
• 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 simpler.

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.

Portable

Portability is one of the core features of java which enables the java programs to run on any
computer or operating system. For example, an applet developed using java runs on a wide
variety of CPUs, operating systems, and browsers connected to the Internet.

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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 7


Robust

Java is more robust because the java code can be executed on a variety of environments, java
has a strong memory management mechanism (garbage collector), java is a strictly typed
language, it has a strong set of exception handling mechanism, and many more.

Architecture-neutral (or) Platform Independent

Java has invented to archive "write once; run anywhere, anytime, 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

Java enables the creation of cross-platform programs by compiling into an intermediate


representation called Java byte code. 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.

Distributed

Java programming language supports TCP/IP protocols which enable the java to support the
distributed environment of the Internet. Java also supports Remote Method Invocation (RMI),
this feature enables a program to invoke methods across a network.

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 8


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
• 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 using java command.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 9


Java Data Types
Java programming language has a rich set of data types. The data type is a category of data stored
in variables. In java, data types are classified into two types and they are as follows.

• Primitive Data Types


• Non-primitive Data Types

Primitive Data Types

The primitive data types are built-in data types and they specify the type of value stored in a
variable and the memory size. The primitive data types do not have any additional methods.
In java, primitive data types includes byte, short, int, long, float, double, char, and boolean.
The following table provides more description of each primitive data type.
Data Meaning Memory Range Default
type size Value

byte Whole numbers 1 byte -128 to +127 0

short Whole numbers 2 bytes -32768 to +32767 0

int Whole numbers 4 bytes -2,147,483,648 to +2,147,483,647 0

long Whole numbers 8 bytes -9,223,372,036,854,775,808 to 0L


+9,223,372,036,854,775,807

float Fractional 4 bytes - 0.0f


numbers

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 10


double Fractional 8 bytes - 0.0d
numbers

char Single character 2 bytes 0 to 65535 \u0000

boolean unsigned char 1 bit 0 or 1 0 (false)

Non-primitive Data Types

In java, non-primitive data types are the reference data types or user-created data types. All non-
primitive data types are implemented using object concepts. Every variable of the non-primitive
data type is an object. The non-primitive data types may use additional methods to perform
certain operations. The default value of non-primitive data type variable is null.
In java, examples of non-primitive data types
are String, Array, List, Queue, Stack, Class, Interface, etc.

Primitive Vs Non-primitive Data Types

Primitive Data Type Non-primitive Data Type

These are built-in data types These are created by the users

Does not support additional methods Support additional methods

Always has a value It can be null

Starts with lower-case letter Starts with upper-case letter

Size depends on the data type Same size for all

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 11


Java Variables
A variable is a named memory location used to store a data value. A variable can be defined as a
container that holds a data value.
In java, we use the following syntax to create variables.

data_type variable_name;
(or)
data_type variable_name_1, variable_name_2,...;
(or)
data_type variable_name = value;
(or)
data_type variable_name_1 = value, variable_name_2 = value,...;

In java programming language variables are classified as follows.

• Local variables
• Instance variables or Member variables or Global variables
• Static variables or Class variables
• Final variables

Local variables

The variables declared inside a method or blocks are known as local variables. A local variable is
visible within the method in which it is declared. The local variable is created when execution
control enters into the method or block and destroyed after the method or block execution
completed.
Let's look at the following example java program to illustrate local variable in java.

public class LocalVariables {

public void show() {


int a = 10;
//static int x = 100;
[Link]("Inside show method, a = " + a);
}
public void display() {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 12


int b = 20;
[Link]("Inside display method, b = " + b);
// trying to access variable 'a' - generates an ERROR
[Link]("Inside display method, a = " + a);
}
public static void main(String args[]) {
LocalVariables obj = new LocalVariables();
[Link]();
[Link]();
}
}

Instance variables or member variables or global variables

The variables declared inside a class and outside any method, constructor or block are known as
instance variables or member variables. These variables are visible to all the methods of the class.
The changes made to these variables by method affects all the methods in the class. These
variables are created separate copy for every object of that class.
Let's look at the following example java program to illustrate instance variable in java.

public class ClassVariables {

int x = 100;

public void show() {


[Link]("Inside show method, x = " + x);
x = x + 100;
}
public void display() {
[Link]("Inside display method, x = " + x);
}

public static void main(String[] args) {


ClassVariables obj = new ClassVariables();

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 13


[Link]();
[Link]();
}
}

Static variables or Class variables

A static variable is a variable that declared using static keyword. The instance variables can be
static variables but local variables cannot. Static variables are initialized only once, at the start of
the program execution. The static variable only has one copy per class irrespective of how many
objects we create.
The static variable is access by using class name.
Let's look at the following example java program to illustrate static variable in java.
Example

public class StaticVariablesExample {

int x, y; // Instance variables


static int z; // Static variable

StaticVariablesExample(int x, int y){


this.x = x;
this.y = y;
}
public void show() {
int a; // Local variables
[Link]("Inside show method,");
[Link]("x = " + x + ", y = " + y + ", z = " + z);
}

public static void main(String[] args) {


StaticVariablesExample obj_1 = new StaticVariablesExample(10, 20);
StaticVariablesExample obj_2 = new StaticVariablesExample(100, 200);
obj_1.show();

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 14


StaticVariablesExample.z = 1000;
obj_2.show();
}
}

Final variables

A final variable is a variable that declared using final keyword. The final variable is initialized only
once, and does not allow any method to change its value again. The variable created
using final keyword acts as constant. All variables like local, instance and static variables can be
final variables.
Let's look at the following example java program to illustrate final variable in java.
Example

public class FinalVariableExample {


final int a = 10;
void show() {
[Link]("a = " + a);
a = 20; //Error due to final variable cann't be modified
}
public static void main(String[] args) {
FinalVariableExample obj = new FinalVariableExample();
[Link]();
}
}

Java Arrays
An array is a collection of similar data values with a single name. An array can also be defined as,
a special type of variable that holds multiple values of the same data type at a time.
In java, arrays are objects and they are created dynamically using new operator. Every array in
java is organized using index values. The index value of an array starts with '0' and ends with 'zise-
1'. We use the index value to access individual elements of an array.
In java, there are two types of arrays and they are as follows.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 15


• One Dimensional Array
• Multi Dimensional Array

Creating an array

In the java programming language, an array must be created using new operator and with a
specific size. The size must be an integer value but not a byte, short, or long. We use the following
syntax to create an array.
Syntax

data_type array_name[ ] = new data_type[size];


(or)
data_type[ ] array_name = new data_type[size];

Let's look at the following example program.

public class ArrayExample {


public static void main(String[] args) {
int list[] = new int[5];
list[0] = 10;
[Link]("Value at index 0 - " + list[0]);
[Link]("Length of the array - " + [Link]);
}
}

In java, an array can also be initialized at the time of its declaration. When an array is initialized
at the time of its declaration, it need not specify the size of the array and use of the new operator.
Here, the size is automatically decided based on the number of values that are initialized.
Example

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

NullPointerException with Arrays

In java, an array created without size and initialized to null remains null only. It does not allow us
to assign a value. When we try to assign a value it generates a NullPointerException.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 16


Look at the following example program.
Example

public class ArrayExample {

public static void main(String[] args) {

short list[] = null;

list[0] = 10;
[Link]("Value at index 0 - " + list[0]);

ArrayIndexOutOfBoundsException with Arrays

In java, the JVM (Java Virtual Machine) throws ArrayIndexOutOfBoundsException when an array
is trying to access with an index value of negative value, value equal to array size, or value more
than the array size.
Look at the following example program.

public class ArrayExample {

public static void main(String[] args) {

short list[] = {10, 20, 30};

list[4] = 10;
[Link]("Value at index 0 - " + list[0]);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 17


}

Looping through an array

An entire array is accessed using either simple for statement or for-each statement. Look at the
following example program to display sum of all the lements in a list.

import [Link];
public class ArrayExample {

public static void main(String[] args) {

Scanner read = new Scanner([Link]);


int size, sum = 0;
[Link]("Enter the size of the list: ");
size = [Link]();
short list[] = new short[size];

[Link]("Enter any " + size + " numbers: ");

for(int i = 0; i < size; i++) // Simple for statement


list[i] = [Link]();

for(int i : list) // for-each statement


sum = sum + i;

[Link]("Sum of all elements: " + sum);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 18


Multidimensional Array

In java, we can create an array with multiple dimensions. We can create 2-dimensional, 3-
dimensional, or any dimensional array.
In Java, multidimensional arrays are arrays of arrays. To create a multidimensional array variable,
specify each additional index using another set of square brackets. We use the following syntax
to create two-dimensional array.

data_type array_name[ ][ ] = new data_type[rows][columns];


(or)
data_type[ ][ ] array_name = new data_type[rows][columns];

When we create a two-dimensional array, it created with a separate index for rows and columns.
The individual element is accessed using the respective row index followed by the column index.
A multidimensional array can be initialized while it has created using the following syntax.

data_type array_name[ ][ ] = {{value1, value2}, {value3, value4}, {value5, value6},...};

When an array is initialized at the time of declaration, it need not specify the size of the array and
use of the new operator. Here, the size is automatically decided based on the number of values
that are initialized.

int matrix_a[ ][ ] = {{1, 2},{3, 4},{5, 6}};

The above statement creates a two-dimensional array of three rows and two columns.

Java Operators
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich
set of operators.
In java, operators are classified into the following four types.

• Arithmetic Operators
• Relational (or) Comparison Operators
• Logical Operators
• Assignment Operators
• Bitwise Operators
• Conditional Operators

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 19


Let's look at each operator in detail.

Arithmetic Operators

In java, arithmetic operators are used to performing basic mathematical operations like addition,
subtraction, multiplication, division, modulus, increment, decrement, etc.,
Operator Meaning Example
+ Addition 10 + 5 = 15
- Subtraction 10 - 5 = 5
* Multiplication 10 * 5 = 50
/ Division 10 / 5 = 2
% Modulus - Remainder of the Division 5%2=1
++ Increment a++
-- Decrement a--

▪ The addition operator can be used with numerical data types and character or string data
type. When it is used with numerical values, it performs mathematical addition and when
it is used with character or string data type values, it performs concatenation (appending).
▪ The modulus (remainder of the division) operator is used with integer data type only.
▪ The increment and decrement operators are used as pre-increment or pre-
decrement and post-increment or post-decrement.
When they are used as pre, the value is get modified before it is used in the actual
expression and when it is used as post, the value is get modified after the actual
expression evaluation.

Let's look at the following example program.

public class ArithmeticOperators {

public static void main(String[] args) {


int a = 10, b = 20, result;
[Link]("a = " + a + ", b = " + b);

result = a + b;
[Link]("Addition : " + a + " + " + b + " = " + result);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 20


result = a - b;
[Link]("Subtraction : " + a + " - " + b + " = " + result);

result = a * b;
[Link]("Multiplucation : " + a + " * " + b + " = " + result);

result = b / a;
[Link]("Division : " + b + " / " + a + " = " + result);

result = b % a;
[Link]("Modulus : " + b + " % " + a + " = " + result);

result = ++a;
[Link]("Pre-increment : ++a = " + result);

result = b--;
[Link]("Post-decrement : b-- = " + result);
}
}

Relational Operators (<, >, <=, >=, ==, !=)

The relational operators are the symbols that are used to compare two values. That means the
relational operators are used to check the relationship between two values. Every relational
operator has two posible results either TRUE or FALSE. In simple words, the relational operators
are used to define conditions in a program. The following table provides information about
relational operators.
Operator Meaning Example

Returns TRUE if the first value is smaller than second value 10 < 5 is
<
otherwise returns FALSE FALSE

Returns TRUE if the first value is larger than second value 10 > 5 is
>
otherwise returns FALSE TRUE

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 21


Returns TRUE if the first value is smaller than or equal to second 10 <= 5 is
<=
value otherwise returns FALSE FALSE

Returns TRUE if the first value is larger than or equal to second 10 >= 5 is
>=
value otherwise returns FALSE TRUE

10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE

Returns TRUE if both values are not equal otherwise returns 10 != 5 is


!=
FALSE TRUE

Look at the following example program.

public class RelationalOperators {


public static void main(String[] args) {
boolean a;
a = 10<5;
[Link]("10 < 5 is " + a);
a = 10>5;
[Link]("10 > 5 is " + a);
a = 10<=5;
[Link]("10 <= 5 is " + a);
a = 10>=5;
[Link]("10 >= 5 is " + a);
a = 10==5;
[Link]("10 == 5 is " + a);
a = 10!=5;
[Link]("10 != 5 is " + a);
}

Logical Operators

The logical operators are the symbols that are used to combine multiple conditions into one
condition. The following table provides information about logical operators.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 22


Operator Meaning Example
false &
Logical AND - Returns TRUE if all conditions are TRUE otherwise
& true =>
returns FALSE
false
false |
Logical OR - Returns FALSE if all conditions are FALSE otherwise
| true =>
returns TRUE
true
true ^
Logical XOR - Returns FALSE if all conditions are same otherwise
^ true =>
returns TRUE
false
Logical NOT - Returns TRUE if condition is FLASE and returns FALSE if !false =>
!
it is TRUE true
false &
short-circuit AND - Similar to Logical AND (&), but once a decision is
&& true =>
finalized it does not evaluate remianing.
false
false |
short-circuit OR - Similar to Logical OR (|), but once a decision is
|| true =>
finalized it does not evaluate remianing.
true

The operators &, |, and ^ can be used with both boolean and integer data type values. When
they are used with integers, performs bitwise operations and with boolean, performs logical
operations.

Logical operators and Short-circuit operators both are similar, but in case of short-circuit
operators once the decision is finalized it does not evaluate remaining expressions.

Look at the following example program.

public class LogicalOperators {

public static void main(String[] args) {

int x = 10, y = 20, z = 0;


boolean a = true;

a = x>y && (z=x+y)>15;


[Link]("a = " + a + ", and z = " + z);

a = x>y & (z=x+y)>15;


[Link]("a = " + a + ", and z = " + z);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 23


}

Assignment Operators

The assignment operators are used to assign right-hand side value (Rvalue) to the left-hand side
variable (Lvalue). The assignment operator is used in different variants along with arithmetic
operators. The following table describes all the assignment operators in the java programming
language.
Operator Meaning Example
= Assign the right-hand side value to left-hand side variable A = 15
+= Add both left and right-hand side values and store the result into left- A += 10
hand side variable
-= Subtract right-hand side value from left-hand side variable value and A -= B
store the result into left-hand side variable
*= Multiply right-hand side value with left-hand side variable value and A *= B
store the result into left-hand side variable
/= Divide left-hand side variable value with right-hand side variable value A /= B
and store the result into the left-hand side variable
%= Divide left-hand side variable value with right-hand side variable value A %= B
and store the remainder into the left-hand side variable
&= Logical AND assignment -
|= Logical OR assignment -
^= Logical XOR assignment -

Look at the following example program.

public class AssignmentOperators {


public static void main(String[] args) {
int a = 10, b = 20, c;
boolean x = true;
[Link]("a = " + a + ", b = " + b);
a += b;
[Link]("a = " + a);
a -= b;
[Link]("a = " + a);
a *= b;

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 24


[Link]("a = " + a);
a /= b;
[Link]("a = " + a);
a %= b;
[Link]("a = " + a);
x |= (a>b);
[Link]("x = " + x);
x &= (a>b);
[Link]("x = " + x);
}
}

Bitwise Operators

The bitwise operators are used to perform bit-level operations in the java programming language.
When we use the bitwise operators, the operations are performed based on binary values. The
following table describes all the bitwise operators in the java programming language.

Let us consider two variables A and B as A = 25 (11001) and B = 20 (10100).


Operator Meaning Example
A&B
& the result of Bitwise AND is 1 if all the bits are 1 otherwise it is 0
⇒ 16 (10000)
A|B
| the result of Bitwise OR is 0 if all the bits are 0 otherwise it is 1
⇒ 29 (11101)
the result of Bitwise XOR is 0 if all the bits are same otherwise it A^B
^
is 1 ⇒ 13 (01101)
the result of Bitwise once complement is negation of the bit ~A
~
(Flipping) ⇒ 6 (00110)
A << 2
the Bitwise left shift operator shifts all the bits to the left by the
<< ⇒ 100
specified number of positions
(1100100)
the Bitwise right shift operator shifts all the bits to the right by A >> 2
>>
the specified number of positions ⇒ 6 (00110)

Look at the following example program.

public class BitwiseOperators {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 25


public static void main(String[] args) {
int a = 25, b = 20;
[Link](a + " & " + b + " = " + (a & b));
[Link](a + " | " + b + " = " + (a | b));
[Link](a + " ^ " + b + " = " + (a ^ b));
[Link]("~" + a + " = " + ~a);
[Link](a + ">>" + 2 + " = " + (a>>2));
[Link](a + "<<" + 2 + " = " + (a<<2));
[Link](a + ">>>" + 2 + " = " + (a>>>2));
}
}

Conditional Operators

The conditional operator is also called a ternary operator because it requires three operands.
This operator is used for decision making. In this operator, first, we verify a condition, then we
perform one operation out of the two operations based on the condition result. If the condition
is TRUE the first option is performed, if the condition is FALSE the second option is performed.
The conditional operator is used with the following syntax.
Syntax

Condition ? TRUE Part : FALSE Part;

Look at the following example program.

public class ConditionalOperator {

public static void main(String[] args) {

int a = 10, b = 20, c;

c = (a>b)? a : b;

[Link]("c = " + c);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 26


}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 27


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.

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 28


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

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 29


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.

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 30


• 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

Java Selection Statements


In java, the selection statements are also known as decision making statements or branching
statements or conditional control 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
• nested if statement
• if-else if statement
• switch statement

if statement in java

In java, we use the if statement to test a condition and decide the execution of a block of
statements based on that condition result. The if statement checks, the given condition then
decides the execution of a block of statements. If the condition is True, then the block of

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 31


statements is executed and if it is False, then the block of statements is ignored. The syntax and
execution flow of if the statement is as follows.

Let's look at the following example java code.

import [Link];
public class IfStatementTest {
public static void main(String[] args) {
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
int num = [Link]();
if((num % 5) == 0) {
[Link]("We are inside the if-block!");
[Link]("Given number is divisible by 5!!");
}
[Link]("We are outside the if-block!!!");
}
}

In the above execution, the number 12 is not divisible by 5. So, the condition becomes False and
the condition is evaluated to False. Then if statement ignores the execution of its block of
statements.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 32


if-else statement in java

In java, we use the if-else statement to test a condition and pick the execution of a block of
statements out of two blocks based on that condition result. The if-else statement checks the
given condition then decides which block of statements to be executed based on the condition
result. If the condition is True, then the true block of statements is executed and if it is False, then
the false block of statements is executed. The syntax and execution flow of if-else statement is
as follows.

Let's look at the following example java code.

import [Link];

public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner([Link]);


[Link]("Enter any number: ");
int num = [Link]();

if((num % 2) == 0) {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 33


[Link]("We are inside the true-block!");
[Link]("Given number is EVEN number!!");
}
else {
[Link]("We are inside the false-block!");
[Link]("Given number is ODD number!!");
}

[Link]("We are outside the if-block!!!");

Nested if statement in java

Writing an if statement inside another if-statement is called nested if statement. The general
syntax of the nested if-statement is as follows.

if(condition_1){
if(condition_2){
inner if-block of statements;
...
}
...
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 34


Java Program

import [Link];

public class NestedIfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner([Link]);


[Link]("Enter any number: ");
int num = [Link]();

if (num < 100) {


[Link]("\nGiven number is below 100");
if (num % 2 == 0)
[Link]("And it is EVEN");
else
[Link]("And it is ODD");
} else
[Link]("Given number is not below 100");

[Link]("\nWe are outside the if-block!!!");

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 35


if-else if statement in java
Writing an if-statement inside else of an if statement is called if-else-if statement.
The general syntax of the an if-else-if statement is as follows.
Syntax

if(condition_1){
condition_1 true-block;
...
}
else if(condition_2){
condition_2 true-block;
condition_1 false-block too;
...
}

Let's look at the following example java code.

import [Link];

public class IfElseIfStatementTest {

public static void main(String[] args) {

int num1, num2, num3;


Scanner read = new Scanner([Link]);
[Link]("Enter any three numbers: ");
num1 = [Link]();
num2 = [Link]();
num3 = [Link]();

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 36


if( num1>=num2 && num1>=num3)
[Link]("\nThe largest number is " + num1) ;

else if (num2>=num1 && num2>=num3)


[Link]("\nThe largest number is " + num2) ;

else
[Link]("\nThe largest number is " + num3) ;

[Link]("\nWe are outside the if-block!!!");

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 37


Switch statement in java
Using the switch statement, one can select only one option from more number of options very
easily. In the switch statement, we provide a value that is to be compared with a value associated
with each option. Whenever the given value matches the value associated with an option, the
execution starts from that option. In the switch statement, every option is defined as a case.
The switch statement has the following syntax and execution flow diagram.

Let's look at the following example java code.

import [Link];

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner([Link]);


[Link]("Press any digit: ");

int value = [Link]();

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 38


switch( value )
{
case 0: [Link]("ZERO") ; break ;
case 1: [Link]("ONE") ; break ;
case 2: [Link]("TWO") ; break ;
case 3: [Link]("THREE") ; break ;
case 4: [Link]("FOUR") ; break ;
case 5: [Link]("FIVE") ; break ;
case 6: [Link]("SIX") ; break ;
case 7: [Link]("SEVEN") ; break ;
case 8: [Link]("EIGHT") ; break ;
case 9: [Link]("NINE") ; break ;
default: [Link]("Not a Digit") ;
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 39


Java Iterative Statements
The java programming language provides a set of iterative statements that are used to execute
a statement or a block of statements repeatedly as long as the given condition is true. The
iterative statements are also known as looping statements or repetitive statements. Java
provides the following iterative statements.

• while statement
• do-while statement
• for statement
• for-each statement

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.

Let's look at the following example java code.

public class WhileTest {


public static void main(String[] args) {
int num = 1;
while(num <= 10) {
[Link](num);
num++;

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 40


}
[Link]("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.

Let's look at the following example java code.

public class DoWhileTest {


public static void main(String[] args) {
int num = 1;

do {
[Link](num);
num++;

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 41


}while(num <= 10);

[Link]("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.

public class ForTest {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 42


public static void main(String[] args) {

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


[Link]("i = " + i);
}

[Link]("Statement after for!");


}

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.
In for-each statement, we cannot skip any element of given array or collection.

The for-each statement has the following syntax and execution flow diagram.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 43


Let's look at the following example java code.

public class ForEachTest {


public static void main(String[] args) {
int[] arrayList = {10, 20, 30, 40, 50};
for(int i : arrayList) {
[Link]("i = " + i);
}
[Link]("Statement after for-each!");
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 44


Java Jump Statements
The java programming language supports jump statements that used to transfer execution
control from one line to another line. The java programming language provides the following
jump statements.
1. break statement 2. continue statement
3. labeled break and continue statements 4. return statement

break statement in java


The break statement in java is used to terminate a switch or looping statement. That means the
break statement is used to come out of a switch statement and a looping statement like while,
do-while, for, and for-each.

Using the break statement outside the switch or loop statement is not allowed.

The following picture depicts the execution flow of the break statement.

Let's look at the following example java code.

public class JavaBreakStatement {


public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {
if(i == 30)
break;
[Link](i);
}
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 45


continue statement in java
The continue statement is used to move the execution control to the beginning of the looping
statement. When the continue statement is encountered in a looping statement, the execution
control skips the rest of the statements in the looping block and directly jumps to the beginning
of the loop. The continue statement can be used with looping statements like while, do-while,
for, and for-each. When we use continue statement with while and do-while statements, the
execution control directly jumps to the condition. When we use continue statement with for
statement the execution control directly jumps to the modification portion
(increment/decrement/any modification) of the for loop. The continue statement flow of
execution is as shown in the following figure.

Let's look at the following example java code.

public class JavaContinueStatement {


public static void main(String[] args) {
int list[] = {10, 20, 30, 40, 50};
for(int i : list) {
if(i == 30)
continue;
[Link](i);
}
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 46


Labeled break and continue statement in java
The java programming language does not support goto statement, alternatively, the break and
continue statements can be used with label.
The labeled break statement terminates the block with specified label. The labeled continue
statement takes the execution control to the beginning of a loop with specified label.
Let's look at the following example java code.

import [Link];

public class JavaLabelledStatement {


public static void main(String args[]) {

Scanner read = new Scanner([Link]);

reading: for (int i = 1; i <= 3; i++) {


[Link]("Enter a even number: ");
int value = [Link]();

verify: if (value % 2 == 0) {
[Link]("\nYou won!!!");
[Link]("Your score is " + i*10 + " out of 30.");
break reading;
} else {
[Link]("\nSorry try again!!!");
[Link]("You let with " + (3-i) + " more options...");

continue reading;
}
}
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 47


return statement in java
In java, the return statement used to terminate a method with or without a value. The return
statement takes the execution control to the calling function. That means the return statement
transfer the execution control from called function to the calling function by carrying a value.
▪ Java allows the use of return-statement with both, with and without return type
methods.

In java, the return statement used with both methods with and without return type. In the case
of a method with the return type, the return statement is mandatory, and it is optional for a
method without return type. When a return statement used with a return type, it carries a value
of return type. But, when it is used without a return type, it does not carry any value. Instead,
simply transfers the execution control.
Let's look at the following example java code.

import [Link];
public class JavaReturnStatementExample {
int value;
int readValue() {
Scanner read = new Scanner([Link]);
[Link]("Enter any number: ");
return [Link]=[Link](); }
void showValue(int value) {
for(int i = 0; i <= value; i++) {
if(i == 5)
return;
[Link](i);
} }
public static void main(String[] args) {
JavaReturnStatementExample obj = new JavaReturnStatementExample();
[Link]([Link]());
} }

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 48


Java Classes
Java is an object-oriented programming language, so everything in java program must be based
on the object concept. In a java programming language, the class concept defines the skeleton of
an object.
The java class is a template of an object. The class defines the blueprint of an object. 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.

• Identity - It is the name given to the class.


• State - Represents data values that are associated with an object.
• Behavior - Represents actions can be performed by an object.

Look at the following picture to understand the class and object concept.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 49


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.

Creating an Object

In java, an object is an instance 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. Following is the syntax of class
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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 50


Java Methods
A method is a block of statements under a name that gets executes only when it is called. Every
method is used to perform a specific task. The major advantage of methods is code re-usability
(define the code once, and use it many times).
In a java programming language, a method defined as a behavior of an object. That means, every
method in java must belong to a class.
Every method in java must be declared inside a class.
Every method declaration has the following characteristics.

• returnType - Specifies the data type of a return value.


• name - Specifies a unique name to identify it.
• parameters - The data values it may accept or recieve.
• { } - Defienes the block belongs to the method.

Creating a method

A method is created inside the class and it may be created with any access specifier. However,
specifying access specifier is optional.
Following is the syntax for creating methods in java.
Syntax

class <ClassName>{
<accessSpecifier> <returnType> <methodName>( parameters ){
...
block of statements;
...
}
}

▪ The methodName must begin with an alphabet, and the Lower-case letter is preferred.
▪ The methodName must follow all naming rules.
▪ If you don't want to pass parameters, we ignore it.
▪ If a method defined with return type other than void, it must contain the return
statement, otherwise, it may be ignored.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 51


Calling a method

In java, a method call precedes with the object name of the class to which it belongs and a dot
operator. It may call directly if the method defined with the static modifier. Every method call
must be made, as to the method name with parentheses (), and it must terminate with a
semicolon.
Syntax

<objectName>.<methodName>( actualArguments );

▪ The method call must pass the values to parameters if it has.


▪ If the method has a return type, we must provide the receiver.

Let's look at the following example java code.

import [Link];
public class JavaMethodsExample {
int sNo;
String name;
Scanner read = new Scanner([Link]);
void readData() {
[Link]("Enter Serial Number: ");
sNo = [Link]();
[Link]("Enter the Name: ");
name = [Link]();
}
static void showData(int sNo, String name) {
[Link]("Hello, " + name + "! your serial number is " + sNo);
}
public static void main(String[] args) {
JavaMethodsExample obj = new JavaMethodsExample();
[Link](); // method call using object
showData([Link], [Link]); // method call without using object
}
}

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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 52


Variable arguments of a method

In java, a method can be defined with a variable number of arguments. That means creating a
method that receives any number of arguments of the same data type.
Syntax

<returnType> <methodName>(dataType...parameterName);

Let's look at the following example java code.

public class JavaMethodWithVariableArgs {


void diaplay(int[] list) {
[Link]("\nNumber of arguments: " + [Link]);
for(int i : list) {
[Link](i + "\t");
}
}
public static void main(String[] args) {
JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();

[Link](1, 2);
[Link](10, 20, 30, 40, 50);

}
}

When a method has the normal parameter and variable-argument, then the variable argument
must be specified at the end in the parameters list.

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.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 53


Let's look at the following example java code.

public class ConstructorExample {

ConstructorExample() {
[Link]("Object created!");
}
public static void main(String[] args) {

ConstructorExample obj1 = new ConstructorExample();


ConstructorExample obj2 = new ConstructorExample();
}

A constructor cannot 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.
In the background, the string values are organized as an array of a character data type.
The string created using a character array cannot be extended. It does not allow appending more
characters after its definition, but it can be modified.
Let's look at the following example java code.
Example

char[] name = {'J', 'a', 'v', 'a', ' ', 'T', 'u', 't', 'o', 'r', 'i', 'a', 'l', 's'};
//name[14] = '@'; //ArrayIndexOutOfBoundsException
name[5] = '-';
[Link](name);

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 54


The String class defined in the package [Link] package. The String class
implements Serializable, Comparable, and CharSequence interfaces.
The string created using the String class can be extended. It allows us to add more characters
after its definition, and also it can be modified.
Let's look at the following example java code.
Example

String siteName = "[Link]";


siteName = "[Link]";

Creating String object in java

In java, we can use the following two ways to create a string object.

• Using string literal


• Using String constructor

Let's look at the following example java code.

String title = "Java Tutorials"; // Using literals

String siteName = new String("[Link]"); // Using constructor

▪ The String class constructor accepts both string and character array as an argument.

String handling methods


In java programming language, the String class contails various methods that can be used to
handle string data values. It containg methods like concat( ), compareTo( ), split( ), join( ), replace(
), trim( ), length( ), intern( ), equals( ), comparison( ), substring( ), etc.
The following table depicts all built-in methods of String class in java.
Method Description Return
Value
charAt(int) Finds the character at given index char
length() Finds the length of given string int
compareTo(String) Compares two strings int
compareToIgnoreCase(String) Compares two strings, ignoring case int

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 55


concat(String) Concatenates the object string with argument String
string.
contains(String) Checks whether a string contains sub-string boolean
contentEquals(String) Checks whether two strings are same boolean
equals(String) Checks whether two strings are same boolean
equalsIgnoreCase(String) Checks whether two strings are same, ignoring boolean
case
startsWith(String) Checks whether a string starts with the specified boolean
string
endsWith(String) Checks whether a string ends with the specified boolean
string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
indexOf(String) Finds the first index of argument string in object int
string
lastIndexOf(String) Finds the last index of argument string in object int
string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
replaceAll(String, String) Replaces the first string with second string at all String
occurrences.
substring(int, int) Extracts a sub-string from specified start and String
end index values
toLowerCase() Converts a string to lower case letters String
toUpperCase() Converts a string to upper case letters String
trim() Removes whitespace from both ends String
toString(int) Converts the value to a String object String
split(String) splits the string matching argument string String[]
intern() returns string from the pool String
join(String, String, ...) Joins all strings, first string as delimiter. String

Let's look at the following example java code.

public class JavaStringExample {


public static void main(String[] args) {
String title = "Java Tutorials";
String siteName = "[Link]";

[Link]("Length of title: " + [Link]());


[Link]("Char at index 3: " + [Link](3));

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 56


[Link]("Index of 'T': " + [Link]('T'));
[Link]("Last index of 'a': " + [Link]('a'));
[Link]("Empty: " + [Link]());
[Link]("Ends with '.com': " + [Link](".com"));
[Link]("Equals: " + [Link](title));
[Link]("Sub-string: " + [Link](9, 14));
[Link]("Upper case: " + [Link]());
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 57


Java Inheritance Basics
The inheritance is a very useful and powerful concept of object-oriented programming. In java,
using the inheritance concept, we can use the existing features of one class in another class. The
inheritance provides a greate advantage called code re-usability. With the help of code re-
usability, the commonly used code in an application need not be written again and again.

The inheritance can be defined as follows.

The inheritance is the process of acquiring the properties of one class to another class.

Inheritance Basics
In inheritance, we use the terms like parent class, child class, base class, derived class, superclass,
and subclass.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 58


The Parent class is the class which provides features to another class. The parent class is also
known as Base class or Superclass.
The Child class is the class which receives features from another class. The child class is also
known as the Derived Class or Subclass.
In the inheritance, the child class acquires the features from its parent class. But the parent
class never acquires the features from its child class.

There are five types of inheritances, and they are as follows.

• Simple Inheritance (or) Single Inheritance


• Multiple Inheritance
• Multi-Level Inheritance
• Hierarchical Inheritance
• Hybrid Inheritance

The following picture illustrates how various inheritances are implemented.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 59


The java programming language does not support multiple inheritance type. However, it
provides an alternate with the concept of interfaces.

Creating Child Class in java


In java, we use the keyword extends to create a child class. The following syntax used to create
a child class in java.
Syntax

class <ChildClassName> extends <ParentClassName>{


...
//Implementation of child class
...
}

In a java programming language, a class extends only one class. Extending multiple classes is
not allowed in java.

Let's look at individual inheritance types and how they get implemented in java with an example.

Single Inheritance in java


In this type of inheritance, one child class derives from one parent class. Look at the following
example code.

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Value of a is " + a);
}
}
public class SingleInheritance {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 60


public static void main(String[] args) {

ChildClass obj = new ChildClass();


[Link](100);
[Link]();

Multi-level Inheritance in java


In this type of inheritance, the child class derives from a class which already derived from another
class. Look at the following example java code.

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
[Link]("Inside ChildChildClass!");
}
}
public class MultilevelInheritance {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 61


public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


[Link](100);
[Link]();
[Link]();

Hierarchical Inheritance in java


In this type of inheritance, two or more child classes derive from one parent class. Look at the
following example java code.

class ParentClass{
int a;
void setData(int a) {
this.a = a;
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass!");
[Link]("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
[Link]("Inside ChildClassToo!");
[Link]("Value of a is " + a);
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 62


public class HierarchicalInheritance {

public static void main(String[] args) {

ChildClass child_obj = new ChildClass();


child_obj.setData(100);
child_obj.showData();

ChildClassToo childToo_obj = new ChildClassToo();


childToo_obj.setData(200);
childToo_obj.display();

Hybrid Inheritance in java


The hybrid inheritance is the combination of more than one type of inheritance. We may use any
combination as a single with multiple inheritances, multi-level with multiple inheritances, etc.,

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 63


Java Access Modifiers
In Java, the access specifiers (also known as access modifiers) used to restrict the scope or
accessibility of a class, constructor, variable, method or data member of class and interface.
There are four access specifiers, and their list is below.

• default (or) no modifier


• public
• protected
• private

In java, we cannot employ all access specifiers on everything. The following table describes where
we can apply the access specifiers.

Let's look at the following example java code, which generates an error because a class does not
allow private access specifier unless it is an inner class.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 64


private class Sample{
...
}

In java, the accessibility of the members of a class or interface depends on its access specifiers.
The following table provides information about the visibility of both data members and methods.

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

Let's look at the following example java code.

class ParentClass{

int a = 10;
public int b = 20;
protected int c = 30;
private int d = 40;

void showData() {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 65


[Link]("Inside ParentClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
[Link]("d = " + d);
}
}
class ChildClass extends ParentClass{
void accessData() {
[Link]("Inside ChildClass");
[Link]("a = " + a);
[Link]("b = " + b);
[Link]("c = " + c);
//[Link]("d = " + d); // private member can't be accessed
}
}
public class AccessModifiersExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
[Link]();
[Link]();
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 66


Java Constructors in Inheritance
It is very important to understand how the constructors get executed in the inheritance concept.
In the inheritance, the constructors never get inherited to any child class.
In java, the default constructor of a parent class called automatically by the constructor of its
child class. That means when we create an object of the child class, the parent class constructor
executed, followed by the child class constructor executed.
Let's look at the following example java code.

class ParentClass{
int a;
ParentClass(){
[Link]("Inside ParentClass constructor!");
}
}
class ChildClass extends ParentClass{
ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
class ChildChildClass extends ChildClass{
ChildChildClass(){
[Link]("Inside ChildChildClass constructor!!");
}
}
public class ConstructorInInheritance {
public static void main(String[] args) {
ChildChildClass obj = new ChildChildClass();
}
}

However, if the parent class contains default and parameterized constructor, then only the
default constructor called automatically by the child class constructor.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 67


Let's look at the following example java code.

class ParentClass{
int a;
ParentClass(int a){
[Link]("Inside ParentClass parameterized constructor!");
this.a = a;
}
ParentClass(){
[Link]("Inside ParentClass default constructor!");
}
}
class ChildClass extends ParentClass{

ChildClass(){
[Link]("Inside ChildClass constructor!!");
}
}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

The parameterized constructor of parent class must be called explicitly using


the super keyword.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 68


Java super keyword
In java, super is a keyword used to refers to the parent class object. The super keyword came into
existence to solve the naming conflicts in the inheritance. When both parent class and child class
have members with the same name, then the super keyword is used to refer to the parent class
version.
In java, the super keyword is used for the following purposes.

• To refer parent class data members


• To refer parent class methods
• To call parent class constructor

The super keyword is used inside the child class only.

super to refer parent class data members


When both parent class and child class have data members with the same name, then the super
keyword is used to refer to the parent class data member from child class.
Let's look at the following example java code.

class ParentClass{

int num = 10;

class ChildClass extends ParentClass{

int num = 20;

void showData() {
[Link]("Inside the ChildClass");
[Link]("ChildClass num = " + num);
[Link]("ParentClass num = " + [Link]);
}
}

public class SuperKeywordExample {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 69


public static void main(String[] args) {
ChildClass obj = new ChildClass();

[Link]();

[Link]("\nInside the non-child class");


[Link]("ChildClass num = " + [Link]);
//[Link]("ParentClass num = " + [Link]); //super can't be
used here

super to refer parent class method


When both parent class and child class have method with the same name, then the super
keyword is used to refer to the parent class method from child class.
Let's look at the following example java code.

class ParentClass{

int num1 = 10;

void showData() {
[Link]("\nInside the ParentClass showData method");
[Link]("ParentClass num = " + num1);
}
}

class ChildClass extends ParentClass{


int num2 = 20;
void showData() {

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 70


[Link]("\nInside the ChildClass showData method");
[Link]("ChildClass num = " + num2);
[Link]();
}
}
public class SuperKeywordExample {
public static void main(String[] args) {
ChildClass obj = new ChildClass();
[Link]();
//[Link](); // super can't be used here
}
}

super to call parent class constructor


When an object of child class is created, it automatically calls the parent class default-constructor
before its own. But, the parameterized constructor of parent class must be called explicitly using
the super keyword inside the child class constructor.
Let's look at the following example java code.

class ParentClass{

int num1;
ParentClass(){
num1 = 10;
[Link]("\nInside the ParentClass default constructor"+num1);
}

ParentClass(int value){
num1 = value;
[Link]("\nInside the ParentClass parameterized constructor"+num1);

}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 71


class ChildClass extends ParentClass{

int num2;

ChildClass(){
super(100);
num2 = 200;
[Link]("\nInside the ChildClass constructor"+num2);

}
}

public class SuperKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}

To call the parameterized constructor of the parent class, the super keyword must be the first
statement inside the child class constructor, and we must pass the parameter values.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 72


Java final keyword
In java, the final is a keyword and it is used with the following things.

• With variable (to create constant)


• With method (to avoid method overriding)
• With class (to avoid inheritance)

Let's look at each of the above.

final with variables


When a variable defined with the final keyword, it becomes a constant, and it does not allow us
to modify the value. The variable defined with the final keyword allows only a one-time
assignment, once a value assigned to it, never allows us to change it again.
Let's look at the following example java code.

public class FinalVariableExample {


public static void main(String[] args) {
final int a = 10;
[Link]("a = " + a);
a = 100; // Can't be modified
}
}

final with methods


When a method defined with the final keyword, it does not allow it to override. The final method
extends to the child class, but the child class cannot override or re-define it. It must be used as it
has implemented in the parent class.
Let's look at the following example java code.

class ParentClass{
int num = 10;
final void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 73


class ChildClass extends ParentClass{

void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


[Link]();

}
}

final with class


When a class defined with final keyword, it cannot be extended by any other class.
Let's look at the following example java code.

final class ParentClass{

int num = 10;

void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 74


class ChildClass extends ParentClass{

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 75


Java Polymorphism
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 or Compile time 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.

import [Link];
public class AdHocPolymorphismExample {
void sorting(int[] list) {
[Link](list);
[Link]("Integers after sort: " + [Link](list) );
}
void sorting(String[] names) {
[Link](names);
[Link]("Names after sort: " + [Link](names) );

}
public static void main(String[] args) {
AdHocPolymorphismExample obj = new AdHocPolymorphismExample();
int list[] = {2, 3, 1, 5, 4};
[Link](list); // Calling with integer array
String[] names = {"rama", "raja", "shyam", "seeta"};
[Link](names); // Calling with String array
} }

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 76


Pure polymorphism or Run time 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.

class ParentClass{
int num = 10;
void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}
class ChildClass extends ParentClass{
void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}
public class PurePolymorphism {
public static void main(String[] args) {
ParentClass obj = new ParentClass();
[Link]();
obj = new ChildClass();
[Link]();
}
}

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 77


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

class ParentClass{

int num = 10;

void showData() {
[Link]("Inside ParentClass showData() method");
[Link]("num = " + num);
}
}

class ChildClass extends ParentClass{

void showData() {
[Link]("Inside ChildClass showData() method");
[Link]("num = " + num);
}
}

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();


[Link]();
obj = new ChildClass();
[Link]();
}
}

10 Rules for method overriding


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

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 78


• Static methods cannot be overridden.
• Final methods cannot be overridden.
• Private methods cannot be overridden.
• Constructor cannot 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.

abstract class <ClassName>{


...
}

Let's look at the following example java code.

import [Link].*;
abstract class Shape {
int length, breadth, radius;
Scanner input = new Scanner([Link]);
abstract void printArea();
}
class Rectangle extends Shape {
void printArea() {
[Link]("*** Finding the Area of Rectangle ***");

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 79


[Link]("Enter length and breadth: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Rectangle is: " + length * breadth);
}
}

class Triangle extends Shape {


void printArea() {
[Link]("\n*** Finding the Area of Triangle ***");
[Link]("Enter Base And Height: ");
length = [Link]();
breadth = [Link]();
[Link]("The area of Triangle is: " + (length * breadth) / 2);
}
}

class Cricle extends Shape {


void printArea() {
[Link]("\n*** Finding the Area of Cricle ***");
[Link]("Enter Radius: ");
radius = [Link]();
[Link]("The area of Cricle is: " + 3.14f * radius * radius);
}
}

public class AbstractClassExample {


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

Triangle tri = new Triangle();


[Link]();

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 80


Cricle cri = new Cricle();
[Link]();
}
}

An abstract class cannot be instantiated but can be referenced. That means we cannot create
an object of an abstract class, but base reference can be created.

In the above example program, the child class objects are created to invoke the overridden
abstract method. But we may also create base class reference and assign it with child class
instance to invoke the same. The main method of the above program can be written as follows
that produce the same output.

public static void main(String[] args) {


Shape obj = new Rectangle(); //Base class reference to Child class instance
[Link]();
obj = new Triangle();
[Link]();
obj = new Cricle();
[Link]();
}

8 Rules for method overriding


An abstract class must follow the below list of rules.

• An abstract class must be created with abstract keyword.


• An abstract class can be created without any abstract method.
• An abstract class may contain abstract methods and non-abstract methods.
• An abstract class may contain final methods that cannot be overridden.
• An abstract class may contain static methods, but the abstract method cannot be static.
• An abstract class may have a constructor that gets executed when the child class object
created.
• An abstract method must be overridden by the child class; otherwise, it must be defined
as an abstract class.
• An abstract class cannot be instantiated but can be referenced.

Java Object Class

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 81


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 [Link] 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.
Return
Method Description
Value
getClass() Returns Class object object
hashCode() Returns the hash code number for object being used. int
equals(Object obj) Compares the argument object to calling object. boolean
clone() Compares two strings, ignoring case int
concat(String) Creates copy of invoking object object
toString() Returns the string representation of invoking object. String
notify() Wakes up a thread, waiting on invoking object's monitor. void
Wakes up all the threads, waiting on invoking object's
notifyAll() void
monitor.
Causes the current thread to wait, until another thread
wait() void
notifies.
Causes the current thread to wait for the specified
wait(long,int) milliseconds and nanoseconds, until another thread void
notifies.
It is invoked by the garbage collector before an object is
finalize() void
being garbage collected.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 82


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 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 different forms of inheritance in java.

• Specialization
• Specification
• Construction
• Extension
• 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.

Extension
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
This is another form of inheritance where the subclass inherits properties from multiple parent
classes. Java does not support multiple inheritance type.

R18-JP-Unit1 Notes - Prepared by Dr. P. Sammulal, Professor of CSE, JNTUH Page 83

You might also like