0% found this document useful (0 votes)
22 views88 pages

Jp-I Notes

The document provides an overview of object-oriented programming (OOP) concepts, illustrating them through a food delivery example. It covers key principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's features and data types. Additionally, it outlines the history and execution process of Java programs, differentiating between primitive and non-primitive data types.
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)
22 views88 pages

Jp-I Notes

The document provides an overview of object-oriented programming (OOP) concepts, illustrating them through a food delivery example. It covers key principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's features and data types. Additionally, it outlines the history and execution process of Java programs, differentiating between primitive and non-primitive data types.
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
You are on page 1/ 88

UNIT I

OBJECT ORIENTED THINGING


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.
Messages and Methods

To solve my problem, I started with a request to the agent zomato, which led to still more requestes 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

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.

Example of static binding

class Dog{

private void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Dog d1=new Dog();

d1.eat();

Dynamic binding

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

Example of dynamic binding

class Animal{

void eat(){System.out.println("animal is eating...");}

class Dog extends Animal{

void eat(){System.out.println("dog is eating...");}

public static void main(String args[]){

Animal a=new Dog();

a.eat();

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

Summary of object oriented concepts

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.

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

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.

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, 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

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

AN 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 uisng java command.
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 Memory Default


Meaning Range
type size Value
Whole
byte 1 byte -128 to +127 0
numbers
Whole
short 2 bytes -32768 to +32767 0
numbers
Whole
int 4 bytes -2,147,483,648 to +2,147,483,647 0
numbers
Whole -9,223,372,036,854,775,808 to
long 8 bytes 0L
numbers +9,223,372,036,854,775,807
Fractional
float 4 bytes - 0.0f
numbers
Fractional
double 8 bytes - 0.0d
numbers
Single
char 2 bytes 0 to 65535 \u0000
character
boolean unsigned char 1 bit 0 or 1 0 (false)

Example

public class PrimitiveDataTypes {

byte i;

short j;

int k;

long l;

float m;

double n;

char ch;

boolean p;

public static void main(String[] args) {

PrimitiveDataTypes obj = new PrimitiveDataTypes();


System.out.println("i = " + obj.i + ", j = " + obj.j + ", k = " + obj.k + ", l = " + obj.l);

System.out.println("m = " + obj.m + ", n = " + obj.n);

System.out.println("ch = " + obj.ch);

System.out.println("p = " + obj.p);

Output

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.

Example

public class NonPrimitiveDataTypes {

String str;

public static void main(String[] args) {

String name = "BTech Smart Class!";

String wish = "Hello, ";

NonPrimitiveDataTypes obj = new NonPrimitiveDataTypes();

System.out.println("str = " + obj.str);

//using addition method

System.out.println(wish.concat(name));

}
}

Output

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

VARIABLES AND ARRAYS

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.

Syntax

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 a block 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.

Example

public class LocalVariables {

public void show() {

int a = 10;

//static int x = 100;

System.out.println("Inside show method, a = " + a);

public void display() {

int b = 20;

System.out.println("Inside display method, b = " + b);

// trying to access variable 'a' - generates an ERROR

System.out.println("Inside display method, a = " + a);

public static void main(String args[]) {

LocalVariables obj = new LocalVariables();

obj.show();

obj.display();

}
Output

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.

Example

public class ClassVariables {

int x = 100;

public void show() {

System.out.println("Inside show method, x = " + x);

x = x + 100;

public void display() {

System.out.println("Inside display method, x = " + x);

public static void main(String[] args) {

ClassVariables obj = new ClassVariables();

obj.show();

obj.display();

Output
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 can not. 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.

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

System.out.println("Inside show method,");

System.out.println("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();

StaticVariablesExample.z = 1000;

obj_2.show();

Output

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 it's value again. The variable created using final keyword acts as
constant. All variables like local, instance, and static variables can be final variables.

Example

public class FinalVariableExample {

final int a = 10;

void show() {

System.out.println("a = " + a);

a = 20; //Error due to final variable cann't be modified

public static void main(String[] args) {

FinalVariableExample obj = new FinalVariableExample();

obj.show();

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

 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];

Example

public class ArrayExample {

public static void main(String[] args) {

int list[] = new int[5];

list[0] = 10;

System.out.println("Value at index 0 - " + list[0]);

System.out.println("Length of the array - " + list.length);

}
}

Output

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.

Example

public class ArrayExample {

public static void main(String[] args) {

short list[] = null;

list[0] = 10;

System.out.println("Value at index 0 - " + list[0]);

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

Example

public class ArrayExample {

public static void main(String[] args) {

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

list[4] = 10;

System.out.println("Value at index 0 - " + list[0]);

Output

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.

Example
import java.util.Scanner;

public class ArrayExample {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

int size, sum = 0;

System.out.print("Enter the size of the list: ");

size = read.nextInt();

short list[] = new short[size];

System.out.println("Enter any " + size + " numbers: ");

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

list[i] = read.nextShort();

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

sum = sum + i;

System.out.println("Sum of all elements: " + sum);

Output

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.

Syntax

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.

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.

Example

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

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

OPERATORS
An operator is a symbol used to perform arithmetic and logical operations. Java provides a rich set of
operators.

In java, operators are clasiffied into the following four types.

 Arithmetic Operqators
 Relational (or) Comparision Operators
 Logical Operators
 Assignment Operators
 Bitwise Operators
 Conditional Operators

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 concatination (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 expresion and when it is
used as post, the value is get modified after the the actual expression evaluation.

Example

public class ArithmeticOperators {

public static void main(String[] args) {

int a = 10, b = 20, result;

System.out.println("a = " + a + ", b = " + b);

result = a + b;

System.out.println("Addition : " + a + " + " + b + " = " + result);

result = a - b;

System.out.println("Subtraction : " + a + " - " + b + " = " + result);

result = a * b;

System.out.println("Multiplucation : " + a + " * " + b + " = " + result);

result = b / a;

System.out.println("Division : " + b + " / " + a + " = " + result);

result = b % a;

System.out.println("Modulus : " + b + " % " + a + " = " + result);


result = ++a;

System.out.println("Pre-increment : ++a = " + result);

result = b--;

System.out.println("Post-decrement : b-- = " + result);

}}

Output

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 otherwise 10 < 5 is
<
returns FALSE FALSE
Returns TRUE if the first value is larger than second value otherwise 10 > 5 is
>
returns FALSE TRUE
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 value 10 >= 5 is
>=
otherwise returns FALSE TRUE
10 == 5 is
== Returns TRUE if both values are equal otherwise returns FALSE
FALSE
10 != 5 is
!= Returns TRUE if both values are not equal otherwise returns FALSE
TRUE

Example

public class RelationalOperators {

public static void main(String[] args) {

boolean a;

a = 10<5;
System.out.println("10 < 5 is " + a);

a = 10>5;

System.out.println("10 > 5 is " + a);

a = 10<=5;

System.out.println("10 <= 5 is " + a);

a = 10>=5;

System.out.println("10 >= 5 is " + a);

a = 10==5;

System.out.println("10 == 5 is " + a);

a = 10!=5;

System.out.println("10 != 5 is " + a);

Output

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.

Operator Meaning Example


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

Example

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;

System.out.println("a = " + a + ", and z = " + z);

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

System.out.println("a = " + a + ", and z = " + z);

Output

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-hand
+= A += 10
side variable
Subtract right-hand side value from left-hand side variable value and store
-= A -= B
the result into left-hand side variable
Multiply right-hand side value with left-hand side variable value and store
*= A *= B
the result into left-hand side variable
Divide left-hand side variable value with right-hand side variable value and
/= A /= B
store the result into the left-hand side variable
Divide left-hand side variable value with right-hand side variable value and
%= A %= B
store the remainder into the left-hand side variable
&= Logical AND assignment -
|= Logical OR assignment -
^= Logical XOR assignment -

Example

public class AssignmentOperators {

public static void main(String[] args) {

int a = 10, b = 20, c;

boolean x = true;

System.out.println("a = " + a + ", b = " + b);

a += b;

System.out.println("a = " + a);

a -= b;

System.out.println("a = " + a);

a *= b;

System.out.println("a = " + a);

a /= b;

System.out.println("a = " + a);

a %= b;
System.out.println("a = " + a);

x |= (a>b);

System.out.println("x = " + x);

x &= (a>b);

System.out.println("x = " + x);

Output

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)
A^B
^ the result of Bitwise XOR is 0 if all the bits are same otherwise it is 1
⇒ 13 (01101)
~A
~ the result of Bitwise once complement is negation of the bit (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 the A >> 2
>>
specified number of positions ⇒ 6 (00110)
Example

public class BitwiseOperators {

public static void main(String[] args) {

int a = 25, b = 20;

System.out.println(a + " & " + b + " = " + (a & b));

System.out.println(a + " | " + b + " = " + (a | b));

System.out.println(a + " ^ " + b + " = " + (a ^ b));

System.out.println("~" + a + " = " + ~a);

System.out.println(a + ">>" + 2 + " = " + (a>>2));

System.out.println(a + "<<" + 2 + " = " + (a<<2));

System.out.println(a + ">>>" + 2 + " = " + (a>>>2));

}}

Output

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;

Example

public class ConditionalOperator {

public static void main(String[] args) {


int a = 10, b = 20, c;

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

System.out.println("c = " + c);

Output

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.
Postfix Expression

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

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.

Control Statements
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.

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

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

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

Example

import java.util.Scanner;

public class IfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

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

System.out.println("We are inside the if-block!");

System.out.println("Given number is divisible by 5!!");

System.out.println("We are outside the if-block!!!");

Output
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 the if statement ignores the execution of its block of statements.

When we enter a number which is divisible by 5, then it produces the output as follows.

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.

Example

import java.util.Scanner;
public class IfElseStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

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

System.out.println("We are inside the true-block!");

System.out.println("Given number is EVEN number!!");

else {

System.out.println("We are inside the false-block!");

System.out.println("Given number is ODD number!!");

System.out.println("We are outside the if-block!!!");

}}

Output

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.

Syntax

if(condition_1){

if(condition_2){
inner if-block of statements;

...

...

Example

import java.util.Scanner;

public class NestedIfStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

int num = read.nextInt();

if (num < 100) {

System.out.println("\nGiven number is below 100");

if (num % 2 == 0)

System.out.println("And it is EVEN");

else

System.out.println("And it is ODD");

} else

System.out.println("Given number is not below 100");

System.out.println("\nWe are outside the if-block!!!");

Output
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;

...

Output

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

import java.util.Scanner;

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner(System.in);

System.out.print("Press any digit: ");

int value = read.nextInt();

switch( value )

case 0: System.out.println("ZERO") ; break ;

case 1: System.out.println("ONE") ; break ;

case 2: System.out.println("TWO") ; break ;

case 3: System.out.println("THREE") ; break ;

case 4: System.out.println("FOUR") ; break ;


case 5: System.out.println("FIVE") ; break ;

case 6: System.out.println("SIX") ; break ;

case 7: System.out.println("SEVEN") ; break ;

case 8: System.out.println("EIGHT") ; break ;

case 9: System.out.println("NINE") ; break ;

default: System.out.println("Not a Digit") ;

Output

In java, the case value of a switch statement can be a String value.

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

ipublic 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!");

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

Example

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.

Example

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!");


}

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.

In for-each statement, we can not skip any element of given array or collection.

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

public class ForEachTest {

public static void main(String[] args) {

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

for(int i : arrayList) {

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

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

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

 break statement
 continue statement
 labelled break and continue statements
 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.
Java Program

public class JavaBreakStatement {

public static void main(String[] args) {

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

for(int i : list) {

if(i == 30)

break;

System.out.println(i);

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.
Java Program

public class JavaContinueStatement {

public static void main(String[] args) {

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

for(int i : list) {

if(i == 30)

continue;

System.out.println(i);

Labelled break and continue statement in java


The java programming langauge does not support goto statement, alternatively, the break and continue
statements can be used with label.

The labelled break statement terminates the block with specified label. The labbeled contonue statement
takes the execution control to the beginning of a loop with specified label.

Java Program

import java.util.Scanner;

public class JavaLabelledStatement {

public static void main(String args[]) {

Scanner read = new Scanner(System.in);

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


System.out.print("Enter a even number: ");

int value = read.nextInt();

verify: if (value % 2 == 0) {

System.out.println("\nYou won!!!");

System.out.println("Your score is " + i*10 + " out of 30.");

break reading;

} else {

System.out.println("\nSorry try again!!!");

System.out.println("You let with " + (3-i) + " more options...");

continue reading;

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.

Java Program

import java.util.Scanner;

public class JavaReturnStatementExample {

int value;

int readValue() {

Scanner read = new Scanner(System.in);

System.out.print("Enter any number: ");

return this.value=read.nextInt();

void showValue(int value) {

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

if(i == 5)

return;

System.out.println(i);

public static void main(String[] args) {

JavaReturnStatementExample obj = new JavaReturnStatementExample();

obj.showValue(obj.readValue());

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

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.

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

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.

Example

import java.util.Scanner;

public class JavaMethodsExample {

int sNo;

String name;

Scanner read = new Scanner(System.in);

void readData() {

System.out.print("Enter Serial Number: ");

sNo = read.nextInt();

System.out.print("Enter the Name: ");

name = read.next();
}

static void showData(int sNo, String name) {

System.out.println("Hello, " + name + "! your serial number is " + sNo);

public static void main(String[] args) {

JavaMethodsExample obj = new JavaMethodsExample();

obj.readData(); // method call using object

showData(obj.sNo, obj.name); // 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.

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

Example

public class JavaMethodWithVariableArgs {

void diaplay(int...list) {

System.out.println("\nNumber of arguments: " + list.length);

for(int i : list) {

System.out.print(i + "\t");
}

public static void main(String[] args) {

JavaMethodWithVariableArgs obj = new JavaMethodWithVariableArgs();

obj.diaplay(1, 2);

obj.diaplay(10, 20, 30, 40, 50);

When a method has both 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.

Example

public class ConstructorExample {

ConstructorExample() {

System.out.println("Object created!"); }

public static void main(String[] args) {

ConstructorExample obj1 = new ConstructorExample();

ConstructorExample obj2 = new ConstructorExample();

}
A constructor cannot have return value.

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 can not be extended. It does not allow to append 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] = '-';

System.out.println(name);

The String class defined in the package java.lang 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.

Example

String siteName = "btechsmartclass.com";

siteName = "www.btechsmartclass.com";

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
Example

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

String siteName = new String("www.btechsmartclass.com"); // 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.

Return
Method Description
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
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 case boolean
Checks whether a string starts with the specified
startsWith(String) boolean
string
Checks whether a string ends with the specified
endsWith(String) boolean
string
getBytes() Converts string value to bytes byte[]
hashCode() Finds the hash code of a string int
Finds the first index of argument string in object
indexOf(String) int
string
Finds the last index of argument string in object
lastIndexOf(String) int
string
isEmpty() Checks whether a string is empty or not boolean
replace(String, String) Replaces the first string with second string String
Replaces the first string with second string at all
replaceAll(String, String) String
occurrences.
Extracts a sub-string from specified start and end
substring(int, int) String
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
Return
Method Description
Value
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

Java Program

public class JavaStringExample {

public static void main(String[] args) {

String title = "Java Tutorials";

String siteName = "www.btechsmartclass.com";

System.out.println("Length of title: " + title.length());

System.out.println("Char at index 3: " + title.charAt(3));

System.out.println("Index of 'T': " + title.indexOf('T'));

System.out.println("Last index of 'a': " + title.lastIndexOf('a'));

System.out.println("Empty: " + title.isEmpty());

System.out.println("Ends with '.com': " + siteName.endsWith(".com"));

System.out.println("Equals: " + siteName.equals(title));

System.out.println("Sub-string: " + siteName.substring(9, 14));

System.out.println("Upper case: " + siteName.toUpperCase());

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


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.

Single Inheritance in java

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

Example

class ParentClass{

int a;

void setData(int a) {

this.a = a;

class ChildClass extends ParentClass{

void showData() {

System.out.println("Value of a is " + a);

public class SingleInheritance {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

obj.setData(100);
obj.showData();

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.

Example

class ParentClass{

int a;

void setData(int a) {

this.a = a;

class ChildClass extends ParentClass{

void showData() {

System.out.println("Value of a is " + a);

class ChildChildClass extends ChildClass{

void display() {

System.out.println("Inside ChildChildClass!");

}
public class MultipleInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();

obj.setData(100);

obj.showData();

obj.display();

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.

Example

class ParentClass{

int a;

void setData(int a) {

this.a = a;

class ChildClass extends ParentClass{

void showData() {

System.out.println("Inside ChildClass!");

System.out.println("Value of a is " + a);

}
}

class ChildClassToo extends ParentClass{

void display() {

System.out.println("Inside ChildClassToo!");

System.out.println("Value of a is " + a);

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.,
MEMBER ACCESS

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 specifies on everything. The following table describes where we can
apply the access specifies.
Example

private class Sample{

...

In java, the accessibility of the members of a class or interface depends on its access specifies. 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.

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() {

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();

}
Constructors

In the inheritance, the constructors never get inherited to any child class.

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.

Example

class ParentClass{

int a;

ParentClass(){

System.out.println("Inside ParentClass constructor!");

class ChildClass extends ParentClass{

ChildClass(){

System.out.println("Inside ChildClass constructor!!");

class ChildChildClass extends ChildClass{

ChildChildClass(){

System.out.println("Inside ChildChildClass constructor!!");

}
public class ConstructorInInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();

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

Example

class ParentClass{

int a;

ParentClass(int a){

System.out.println("Inside ParentClass parameterized constructor!");

this.a = a;

ParentClass(){

System.out.println("Inside ParentClass default constructor!");

class ChildClass extends ParentClass{

ChildClass(){

System.out.println("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.

SUPER USES

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.

Example

class ParentClass{

int num = 10;

class ChildClass extends ParentClass{

int num = 20;

void showData() {
System.out.println("Inside the ChildClass");

System.out.println("ChildClass num = " + num);

System.out.println("ParentClass num = " + super.num);

public class SuperKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

obj.showData();

System.out.println("\nInside the non-child class");

System.out.println("ChildClass num = " + obj.num);

//System.out.println("ParentClass num = " + super.num); //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.

Example

class ParentClass{

int num1 = 10;

void showData() {
System.out.println("\nInside the ParentClass showData method");

System.out.println("ChildClass num = " + num1);

class ChildClass extends ParentClass{

int num2 = 20;

void showData() {

System.out.println("\nInside the ChildClass showData method");

System.out.println("ChildClass num = " + num2);

super.showData();

public class SuperKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

obj.showData();

//super.showData(); // 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 it's
own. But, the parameterized constructor of parent class must be called explicitly using the super keyword
inside the child class constructor.

Example

class ParentClass{

int num1;

ParentClass(){

System.out.println("\nInside the ParentClass default constructor");

num1 = 10;

System.out.println("\nnum1= "+num1);

ParentClass(int value){

System.out.println("\nInside the ParentClass parameterized constructor");

num1 = value;

System.out.println("\nnum1= "+num1);

class ChildClass extends ParentClass{

int num2;

ChildClass(){

super(100);

System.out.println("\nInside the ChildClass constructor");

num2 = 200;

System.out.println("\nnum2= "+num1);

System.out.println("\nFrom Parent Class num1= "+super.num1);

}
}

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.

USING FINAL WITH INHERITANCE

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)

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.

Example

public class FinalVariableExample {

public static void main(String[] args) {

final int a = 10;

System.out.println("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 can not 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.

Example

class ParentClass{

int num = 10;

final 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 FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


obj.showData();

}}

final with class

When a class defined with final keyword, it can not be extended by any other class.

Example

final class ParentClass{

int num = 10;

void showData() {

System.out.println("Inside ParentClass showData() method");

System.out.println("num = " + num);

class ChildClass extends ParentClass{

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

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

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

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.

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

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();

obj.showData();

obj = new ChildClass();

obj.showData();

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.

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

public class PurePolymorphism {

public static void main(String[] args) {

ParentClass obj = new ParentClass();

obj.showData();

obj = new ChildClass();

obj.showData();

}
}

10 Rules for method overriding

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

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

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>{

...

Example

import java.util.*;
abstract class Shape {

int length, breadth, radius;

Scanner input = new Scanner(System.in);

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

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();

}
An abstract class can not be instantiated but can be referenced. That means we can not 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.

Example

public static void main(String[] args) {

Shape obj = new Rectangle(); //Base class reference to Child class instance

obj.printArea();

obj = new Triangle();

obj.printArea();

obj = new Cricle();

obj.printArea();

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 can not be overridden.
 An abstract class may contain static methods, but the abstract method can not 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 can not be instantiated but can be referenced.

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
super class 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 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
causes the current thread to wait for the specified milliseconds and
wait(long,int) void
nanoseconds, until another thread notifies.
It is invoked by the garbage collector before an object is being
finalize() void
garbage collected.

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

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.

BENEFITS AND COSTS OF INHERITANCE


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.

You might also like