0% found this document useful (0 votes)
14 views85 pages

Understanding Object-Oriented Programming

The document explains object-oriented programming (OOP) concepts using a food delivery example, illustrating how agents (like Zomato) and communities (like hotels) interact to solve problems. It covers key OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's features and data types. Additionally, it details the history of Java, its execution process, and the distinction 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)
14 views85 pages

Understanding Object-Oriented Programming

The document explains object-oriented programming (OOP) concepts using a food delivery example, illustrating how agents (like Zomato) and communities (like hotels) interact to solve problems. It covers key OOP principles such as encapsulation, inheritance, polymorphism, and abstraction, along with Java's features and data types. Additionally, it details the history of Java, its execution process, and the distinction 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

UNIT I

A way of viewing world


A way of viewing the world is an idea to illustrate the object-oriented programming concept with an
example of a real-world situation.

Let us consider a situation, I am at my office and I wish to get food to my family members who are
at my home from a hotel. Because of the distance from my office to home, there is no possibility of
getting food from a hotel myself. So, how do we solve the issue?

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

Agents and Communities


To solve my food delivery problem, I used a solution by finding an appropriate agent (Zomato) and
pass a message containing my request. It is the responsibility of the agent (Zomato) to satisfy my
request. Here, the agent uses some method to 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


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

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 esential functionality. In the abstraction
concept, we do not show the actual implemention to the end user, instead we provide only esential
things. For example, if we want to drive a car, we does not need to know about the internal
functionality like how wheel system works? how brake system works? how music system works?
etc.

Java Buzz Words


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

 Simple
 Secure
 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).

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


Meaning Range
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
-9,223,372,036,854,775,808 to
long Whole numbers 8 bytes 0L
+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)
Let's look at the following example java program to illustrate primitive data types in java and their
default values.

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

[Link]("i = " + obj.i + ", j = " + obj.j + ", k = " +


obj.k + ", l = " + obj.l);
[Link]("m = " + obj.m + ", n = " + obj.n);
[Link]("ch = " + [Link]);
[Link]("p = " + obj.p);

}
}

When we run the above example code, it produces the following 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();

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

//using addition method


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

When we run the above example code, it produces the following 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

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.

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

Let's look at the following example java program to illustrate local variable in java.

Example
public class LocalVariables {

public void show() {


int a = 10;
//static int x = 100;
[Link]("Inside show method, a = " + a);
}
public void display() {
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]();
}
}

When we run the above example code, it produces the following 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.

Let's look at the following example java program to illustrate instance variable in java.

Example
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();
[Link]();
[Link]();
}
}

When we run the above example code, it produces the following 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.

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();
StaticVariablesExample.z = 1000;
obj_2.show();
}
}

When we run the above example code, it produces the following 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.

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

When we run the above example code, it produces the following output.

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.

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

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

When we run the above example code, it produces the following 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.

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

When we run the above example code, it produces the following 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.

Look at the following example program.

Example
public class ArrayExample {

public static void main(String[] args) {

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

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

When we run the above example code, it produces the following 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 [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);

When we run the above example code, it produces the following 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.

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 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--
Let's look at the following example program.

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

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

When we run the above example code, it produces the following 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 TRUE
returns FALSE
Returns TRUE if the first value is smaller than or equal to second value 10 <= 5 is
<=
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

Look at the following example program.

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

When we run the above example code, it produces the following 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 =>
^
returns TRUE false
Logical NOT - Returns TRUE if condition is FLASE and returns FALSE
! !false => true
if it is TRUE
short-circuit AND - Similar to Logical AND (&), but once a decision is false & true =>
&&
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
Look at the following example program.

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;


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

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


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

When we run the above example code, it produces the following 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 side
+= A += 10
variable
Subtract right-hand side value from left-hand side variable value and store the
-= A -= B
result into left-hand side variable
Multiply right-hand side value with left-hand side variable value and store the
*= A *= B
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 -

Look at the following example program.

Example
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;
[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);
}
}

When we run the above example code, it produces the following 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 specified
<< ⇒ 100
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)

Look at the following example program.

Example
public class BitwiseOperators {

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


}

When we run the above example code, it produces the following 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;
Look at the following example program.

Example
public class ConditionalOperator {

public static void main(String[] args) {

int a = 10, b = 20, c;

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

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


}

When we run the above example code, it produces the following output.

Java Expressions
Java 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

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

 if statement
 if-else statement
 if-elif statement
 nested if statement
 switch statement
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 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.

Java Program

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

When we run this code, it produce the following 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.

Let's look at the following example java code.

Java Program

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

}
When we run this code, it produce the following 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;
...
}
...
}

Let's look at the following example java code.

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

When we run this code, it produce the following 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;
...
}

Let's look at the following example java code.

Java Program

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

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

When we run this code, it produce the following 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.
Let's look at the following example java code.

Java Program

import [Link];

public class SwitchStatementTest {

public static void main(String[] args) {

Scanner read = new Scanner([Link]);


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

int value = [Link]();

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

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


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

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.

Java Program

ipublic class WhileTest {

public static void main(String[] args) {

int num = 1;

while(num <= 10) {


[Link](num);
num++;
}

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

When we run this code, it produce the following 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.

Let's look at the following example java code.

Java Program

public class DoWhileTest {

public static void main(String[] args) {


int num = 1;

do {
[Link](num);
num++;
}while(num <= 10);

[Link]("Statement after do-while!");

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

for statement in java


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

Let's look at the following example java code.

Java Program

public class ForTest {

public static void main(String[] args) {

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


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

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


}

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

for-each statement in java


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

The for-each statement has the following syntax and execution flow diagram.
Let's look at the following example java code.

Java Program

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


}

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

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

The floowing picture depictes the execution flow of the break statement.

Let's look at the following example java code.

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;
[Link](i);
}

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

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.

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;
[Link](i);
}

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


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.

Let's look at the following example java code.

Java Program

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

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

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.

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.

Java Program

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

}
}

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


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.

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

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

Let's look at the following example java code.

Example

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

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

Example

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

}Output:
Constructor
A constructor is a special method of a class that has the same name as the class name. The
constructor gets executes automatically on object creation. It does not require the explicit method
call. A constructor may have parameters and access specifiers too. In java, if you do not provide any
constructor the compiler automatically creates a default constructor.

Let's look at the following example java code.

Example

public class ConstructorExample {

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

ConstructorExample obj1 = new ConstructorExample();


ConstructorExample obj2 = new ConstructorExample();
}

Output:
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 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] = '-';
[Link](name);

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.

Example

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

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


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

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

startsWith(String) Checks whether a string starts with the specified string boolean

endsWith(String) Checks whether a string ends with the specified string boolean

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 string int

lastIndexOf(String) Finds the last index of argument string in object string int

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

substring(int, int) Extracts a sub-string from specified start and end index values String

toLowerCase() Converts a string to lower case letters String

toUpperCase() Converts a string to upper case letters String


Method Description Return Value

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.

Java Program

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));
[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]());
}

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


Java Inheritance Basics
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.

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.

Example

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 {

public static void main(String[] args) {

ChildClass obj = new ChildClass();


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

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


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() {
[Link]("Value of a is " + a);
}
}
class ChildChildClass extends ChildClass{
void display() {
[Link]("Inside ChildChildClass!");
}
}
public class MultipleInheritance {

public static void main(String[] args) {

ChildChildClass obj = new ChildChildClass();


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

}
}

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

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() {
[Link]("Inside ChildClass!");
[Link]("Value of a is " + a);
}
}
class ChildClassToo extends ParentClass{
void display() {
[Link]("Inside ChildClassToo!");
[Link]("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();

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

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

Example

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.

Let's look at the following example java code.

Example

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

void showData() {
[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]();

}
}

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

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.

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

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

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

Let's look at the following example java code.


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

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

The parameterized constructor of parent class must be called explicitly using the super keyword.
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.

Example

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 {

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

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

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.

Example

class ParentClass{

int num1 = 10;

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

class ChildClass extends ParentClass{

int num2 = 20;

void showData() {
[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

}
}

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

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.

Let's look at the following example java code.

Example

class ParentClass{

int num1;

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

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

class ChildClass extends ParentClass{

int num2;

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

public class SuperKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

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

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

Example

public class FinalVariableExample {

public static void main(String[] args) {

final int a = 10;

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

a = 100; // Can't be modified

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


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


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

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

}
}When we run this code, it produce the following output.
final with class
When a class defined with final keyword, it can not be extended by any other class.

Let's look at the following example java code.

Example

final class ParentClass{

int num = 10;

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

class ChildClass extends ParentClass{

public class FinalKeywordExample {

public static void main(String[] args) {

ChildClass obj = new ChildClass();

}
}when we run this code, it produce the following output.
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
The ad hoc polymorphism is a technique used to define the same method with different
implementations and different arguments. In a java programming language, ad hoc polymorphism
carried out with a method overloading concept.

In ad hoc polymorphism the method binding happens at the time of compilation. Ad hoc
polymorphism is also known as compile-time polymorphism. Every function call binded with the
respective overloaded method based on the arguments.

The ad hoc polymorphism implemented within the class only.

Let's look at the following example java code.

Example
import [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
}
}

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


Pure polymorphism
The pure polymorphism is a technique used to define the same method with the same arguments but
different implementations. In a java programming language, pure polymorphism carried out with a
method overriding concept.

In pure polymorphism, the method binding happens at run time. Pure polymorphism is also known as
run-time polymorphism. Every function call binding with the respective overridden method based on
the object reference.

When a child class has a definition for a member function of the parent class, the parent class
function is said to be overridden.

The pure polymorphism implemented in the inheritance concept only.

Let's look at the following example java code.

Example
class ParentClass{

int num = 10;


void showData() {
[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]();

}
}When we run this code, it produce the following output.
Java Method Overriding
The method overriding is the process of re-defining a method in a child class that is already defined
in the parent class. When both parent and child classes have the same method, then that method is
said to be the overriding method.

The method overriding enables the child class to change the implementation of the method which
aquired from parent class according to its requirement.

In the case of the method overriding, the method binding happens at run time. The method binding
which happens at run time is known as late binding. So, the method overriding follows late binding.

The method overriding is also known as dynamic method dispatch or run time polymorphism or pure
polymorphism.

Let's look at the following example java code.

Example

class ParentClass{

int num = 10;

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

}
}

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


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

 Static methods can not be overridden.


 Final methods can not be overridden.
 Private methods can not be overridden.
 Constructor can not be overridden.
 An abstract method must be overridden.
 Use super keyword to invoke overridden method from child class.
 The return type of the overriding method must be same as the parent has it.
 The access specifier of the overriding method can be changed, but the visibility must increase but
not decrease. For example, a protected method in the parent class can be made public, but not
private, in the child class.
 If the overridden method does not throw an exception in the parent class, then the child class
overriding method can only throw the unchecked exception, throwing a checked exception is not
allowed.
 If the parent class overridden method does throw an exception, then the child class overriding
method can only throw the same, or subclass exception, or it may not throw any exception.
Java Abstract Class
An abstract class is a class that created using abstract keyword. In other words, a class prefixed with
abstract keyword is known as an abstract class.

In java, an abstract class may contain abstract methods (methods without implementation) and also
non-abstract methods (methods with implementation).

We use the following syntax to create an abstract class.

Syntax

abstract class <ClassName>{


...
}

Let's look at the following example java code.

Example

import [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 ***");
[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]();

Cricle cri = new Cricle();


[Link]();
}
}

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


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

You might also like