Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
21 views

Java Notes

Uploaded by

Shagun Dhiman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

Java Notes

Uploaded by

Shagun Dhiman
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 78

Comparing Procedural and Object Oriented:

Characteristics:
The characteristics of OOP are:
Class – Basic building blocks OOP and a single entity which has data and operations on
data together

Objects – The instances of a class which are used in real functionality – its variables and
operations

Abstraction – Specifying what to do but not how to do ; a flexible feature for having a
overall view of an object’s functionality.

Encapsulation – Binding data and operations of data together in a single unit – A class
adhere this feature

Inheritance – Reusability and extension of existing classes

Polymorphism – Multiple definitions for a single name - functions with same name with
different functionality; saves time in investing many function names Operator and
Function overloading

Message passing – Objects communicates through invoking methods and sending data to
them. This feature of sending and receiving information among objects through function
parameters is known as Message Passing.

Object-oriented programing language:


They support programming using the classes and objects paradigm.

Five of the most popular object-oriented languages include:

1. Java
2. Python
3. C++
4. Ruby
5. C#

History of Java:
 Java was developed by James Gosling, who is known as the father of Java, in 1995.
 It is initiated the Java language project in June 1991.
 The small team of sun engineers called Green Team.
 After that, it was called Oak and was developed as a part of the Green project.
 Java is an island in Indonesia where the first coffee was produced (called Java coffee). It is a kind of
espresso bean. Java name was chosen by James Gosling while having a cup of coffee nearby his office.

How Java Works:


Java is compiled into the bytecode and then it is interpreted to machine code.

Source Compiled Byte Interpreted Machine


Code Code Code

Structure of Java Program:


A typical structure of a Java

program contains the following elements:


o Documentation Section
o Package Declaration
o Import Statements
o Interface Section
o Class Definition
o Class Variables and Variables
o Main Method Class
o Methods and Behaviors

Documentation Section

The documentation section is optional for a Java program. It includes basic information about a Java program.
It improves the readability of the program and includes the program name, company name, and description of
the program. Whatever we write in the documentation section, the Java compiler ignores the statements
during the execution of the program. To write the statements in the documentation section, we use comments.
The comments may be single-line, multi-line, and documentation comments.

o Single-line Comment: It starts with a pair of forwarding slash (//).

For example: //First Java Program

o Multi-line Comment: It starts with a /* and ends with */. We write between these two
symbols.

For example:

/*It is an example of

multiline comment*/

o Documentation Comment: It starts with the delimiter (/**) and ends with */. For example:

/**It is an example of documentation comment*/

Package Declaration:

The package declaration is optional. It is placed just after the documentation section. In this section,
we declare the package name in which the class is placed. Note that there can be only one
package statement in a Java program. It must be defined before any class and interface declaration. It
is necessary because a Java class can be placed in different packages and directories based on the
module they are used. For all these classes package belongs to a single parent directory. We use the
keyword package to declare the package name. For example:

package javatpoint; //where javatpoint is the package name


package com.javatpoint; //where com is the root directory and javatpoint is the subdirectory

Import Statements:

The package contains the many predefined classes and interfaces. If we want to use any class of a
particular package, we need to import that class. The import statement represents the class stored in
the other package. We use the import keyword to import the class. It is written before the class
declaration and after the package statement. We use the import statement in two ways, either import
a specific class or import all classes of a particular package. In a Java program, we can use multiple
import statements. For example:

import java.util.Scanner; //it imports the Scanner class only


import java.util.*; //it imports all the class of the java.util package
Interface Section

It is an optional section. We can create an interface in this section if required. We use the interface keyword to
create an interface. An interface is a slightly different from the class. It contains
only constants and method declarations. Another difference is that it cannot be instantiated. We can use
interface in classes by using the implements keyword. An interface can also be used with other interfaces by
using the extends keyword.

For example:

interface car {
void start();
void stop();
}

Class Definition:

In this section, we define the class. It is vital part of a Java program. Without the class, we cannot create any
Java program. A Java program may conation more than one class definition. We use the class keyword to define
the class. The class is a blueprint of a Java program. It contains information about user-defined methods,
variables, and constants. Every Java program has at least one class that contains the main() method.

For example:

class Student //class definition


{
}

Class Variables and Constants:

Variables and constants that are to be used later in the program. In a Java program, the variables and constants
are defined just after the class definition. The variables and constants store values of the parameters. It is used
during the execution of the program. We can also decide and define the scope of variables by using the
modifiers. It defines the life of the variables.
For example:
class Student //class definition
{
String sname; //variable
int id;
double percentage;
}

Main Method Class:

In this section, we define the main() method. It is essential for all Java programs. Because the execution of all
Java programs starts from the main() method. In other words, it is an entry point of the class. It must be inside
the class. Inside the main method, we create objects and call the methods. We use the following statement to
define the main() method:

public static void main(String args[])


{
}

For example:

public class Student //class definition

public static void main(String args[])


{
//statements
}
}

Methods and behavior:

The methods are the set of instructions that we want to perform. These instructions execute at runtime and
perform the specified task. For example:

public class Demo //class definition


{
public static void main(String args[])
{
void display()
{
System.out.println("Welcome to javatpoint");
}
//statements
}
}

Features of Java:
The primary objective of Java programming language creation was to make it portable, simple and
secure programming language. Apart from this, there are also some excellent features which play an
important role in the popularity of this language. The features of Java are also known as Java
buzzwords.

A list of the most important features of the Java language is given below.
1. Simple
2. Object-Oriented
3. Portable
4. Platform independent
5. Secured
6. Robust
7. Architecture neutral
8. Interpreted
9. High Performance
10. Multithreaded

1. Simple

Java is very easy to learn, and its syntax is simple, clean and easy to understand. According to Sun
Microsystem, Java language is a simple programming language because:

o Java syntax is based on C++ (so easier for programmers to learn it after C++).
o Java has removed many complicated and rarely-used features, for example, explicit pointers, operator
overloading, etc.
o There is no need to remove unreferenced objects because there is an Automatic Garbage Collection in
Java.

2. Object-oriented

Java is an object-oriented programming language. Everything in Java is an object. Object-oriented


means we organize our software as a combination of different types of objects that incorporate both
data and behavior.

Object-oriented programming (OOPs) is a methodology that simplifies software development and


maintenance by providing some rules.

Basic concepts of OOPs are:

1. Object
2. Class
3. Inheritance
4. Polymorphism
5. Abstraction
6. Encapsulation
3. Platform Independent

Java is platform independent because it is different from other languages like C, C++, etc. which are
compiled into platform specific machines while Java is a write once, run anywhere language. A
platform is the hardware or software environment in which a program runs.

There are two types of platforms software-based and hardware-based. Java provides a software-
based platform.

The Java platform differs from most other platforms in the sense that it is a software-based platform
that runs on top of other hardware-based platforms. It has two components:

1. Runtime Environment
2. API (Application Programming Interface)

Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris, Mac/OS,
etc. Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e., Write Once and Run Anywhere
(WORA).

4. Secured

Java is best known for its security. With Java, we can develop virus-free systems. Java is secured
because:

o No explicit pointer
o Java Programs run inside a virtual machine sandbox

o Classloader: Classloader in Java is a part of the Java Runtime Environment (JRE) which is used to load
Java classes into the Java Virtual Machine dynamically. It adds security by separating the package for
the classes of the local file system from those that are imported from network sources.
o Bytecode Verifier: It checks the code fragments for illegal code that can violate access rights to
objects.
o Security Manager: It determines what resources a class can access such as reading and writing to the
local disk.

Java language provides these securities by default. Some security can also be provided by an
application developer explicitly through SSL, JAAS, Cryptography, etc.

5. Robust

The English mining of Robust is strong. Java is robust because:


o It uses strong memory management.
o There is a lack of pointers that avoids security problems.
o Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects
which are not being used by a Java application anymore.
o There are exception handling and the type checking mechanism in Java. All these points make Java
robust.

6. Architecture-neutral

Java is architecture neutral because there are no implementation dependent features, for example, the
size of primitive types is fixed.

In C programming, int data type occupies 2 bytes of memory for 32-bit architecture and 4 bytes of
memory for 64-bit architecture. However, it occupies 4 bytes of memory for both 32 and 64-bit
architectures in Java.

7. Portable

Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require
any implementation.

8. High-performance

Java is faster than other traditional interpreted programming languages because Java bytecode is
"close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an
interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.

9. Distributed

Java is distributed because it facilitates users to create distributed applications in Java. RMI and EJB
are used for creating distributed applications. This feature of Java makes us able to access files by
calling the methods from any machine on the internet.

10. Multi-threaded

A thread is like a separate program, executing concurrently. We can write Java programs that deal
with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it
doesn't occupy memory for each thread. It shares a common memory area. Threads are important for
multi-media, Web applications, etc.

JVM:
JVM is the specification for a software program that executes code and provides the runtime
environment for that code.
JVM Architecture
Let's understand the internal architecture of JVM. It contains classloader, memory area, execution
engine etc.

1) Classloader
Classloader is a subsystem of JVM which is used to load class files. Whenever we run the java program, it is
loaded first by the classloader. There are three built-in classloaders in Java.

1. Bootstrap ClassLoader: This is the first classloader which is the super class of Extension classloader. It loads
the rt.jar file which contains all class files of Java Standard Edition like java.lang package classes, java.net
package classes, java.util package classes, java.io package classes, java.sql package classes etc.
2. Extension ClassLoader: This is the child classloader of Bootstrap and parent classloader of System classloader.
It loades the jar files located inside $JAVA_HOME/jre/lib/ext directory.
3. System/Application ClassLoader: This is the child classloader of Extension classloader. It loads the classfiles
from classpath. By default, classpath is set to current directory. You can change the classpath using "-cp" or "-
classpath" switch. It is also known as Application classloader.

4. These are the internal classloaders provided by Java. If you want to create your own classloader, you
need to extend the ClassLoader class.
2) Class(Method) Area
Class(Method) Area stores per-class structures such as the runtime constant pool, field and method data, the
code for methods.

3) Heap
It is the runtime data area in which objects are allocated.

4) Stack
Java Stack stores frames. It holds local variables and partial results, and plays a part in method invocation and
return.

Each thread has a private JVM stack, created at the same time as thread.

A new frame is created each time a method is invoked. A frame is destroyed when its method invocation
completes.

5) Program Counter Register


PC (program counter) register contains the address of the Java virtual machine instruction currently being
executed.

6) Native Method Stack


It contains all the native methods used in the application.

7) Execution Engine
It contains:

1. A virtual processor
2. Interpreter: Read bytecode stream then execute the instructions.
3. Just-In-Time(JIT) compiler: It is used to improve the performance. JIT compiles parts of the byte code that
have similar functionality at the same time, and hence reduces the amount of time needed for compilation. Here,
the term "compiler" refers to a translator from the instruction set of a Java virtual machine (JVM) to the
instruction set of a specific CPU.

8) Java Native Interface


Java Native Interface (JNI) is a framework which provides an interface to communicate with another
application written in another language like C, C++, Assembly etc. Java uses JNI framework to send output to
the Console or interact with OS libraries.
What is a Class file?
A Class file in Java is the compiled output of .java class that is actually executed by a Java Virtual Machine
(JVM). Class files can be executed individually as well as can be a part of a JAR file as a bundle along with other
package files. These can be created using the javac command from the command line interface. Some Java
IDEs like Eclipse and NetBeans provide create .class output files from the project’s Java files.

Class File Format


A Java class file comprises of bytecode that is intermediate code to be run by JVM. A class file consists of a
stream of 8-bit bytes and multibyte data items are always stored in big-endian order.

Components of Java Instrumentation:

 Agent – is a jar file containing agent and transformer class files.


 Agent Class – A java class file, containing a method named ‘premain’.
 Manifest – manifest.mf file containing the “premain-class” property.
 Transformer – A Java class file implementing the interface ClassFileTransformer.

Java Keywords:
Java keywords are also known as reserved words. Keywords are particular words that act as a key to a
code. These are predefined words by Java so they cannot be used as a variable or object name or
class name.

Java Constant:
A constant is a data item whose value cannot change during the program’s execution. Thus, as its
name implies – the value is constant.

Java Variable:
A variable is a container which holds the value while the Java program is executed. A variable is
assigned with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and
static.

There are two types of data types in Java: primitive and non-primitive.

int data=50;//Here data is variable


1) Local Variable

A variable declared inside the body of the method is called local variable. You can use this variable
only within that method and the other methods in the class aren't even aware that the variable exists.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

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

It is called an instance variable because its value is instance-specific and is not shared among
instances.

3) Static variable

A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for
static variables happens only once when the class is loaded in the memory.

Rules for declaring a variable name:


We can choose a name while declaring a Java variable if the following rules are followed:

1. Must not begin with a digit

2. Name is case sensitive

3. Should not be a keyword

4. White space not allowed

5. Can contain alphabets, character, and digits if the other conditions are met.

Data Types in Java


Data types specify the different sizes and values that can be stored in the variable. There are two
types of data types in Java:

1. Primitive data types: The primitive data types include boolean, char, byte, short, int, long, float and
double.
2. Non-primitive data types: The non-primitive data types include Classes, Interfaces, and Arrays.
Java Primitive Data Types
In Java language, primitive data types are the building blocks of data manipulation. These are the
most basic data types available in Java language.

There are 8 types of primitive data types:

o boolean data type


o byte data type
o char data type
o short data type
o int data type
o long data type
o float data type
o double data type

Data Type Default Value Default size

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte
int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

Boolean Data Type:


The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.

The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.

Example:

1. Boolean one = false

Byte Data Type:


The byte data type is an example of primitive data type. It isan 8-bit signed two's complement integer.
Its value-range lies between -128 to 127 (inclusive). Its minimum value is -128 and maximum value is
127. Its default value is 0.

The byte data type is used to save memory in large arrays where the memory savings is most
required. It saves space because a byte is 4 times smaller than an integer. It can also be used in place
of "int" data type.

Example:

1. byte a = 10, byte b = -20

Short Data Type


The short data type is a 16-bit signed two's complement integer. Its value-range lies between -32,768
to 32,767 (inclusive). Its minimum value is -32,768 and maximum value is 32,767. Its default value is 0.

The short data type can also be used to save memory just like byte data type. A short data type is 2
times smaller than an integer.
Example:

1. short s = 10000, short r = -5000

Int Data Type:


The int data type is a 32-bit signed two's complement integer. Its value-range lies between -
2,147,483,648 (-2^31) to 2,147,483,647 (2^31 -1) (inclusive). Its minimum value is - 2,147,483,648and
maximum value is 2,147,483,647. Its default value is 0.

The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.

Example:

1. int a = 100000, int b = -200000

Long Data Type:


The long data type is a 64-bit two's complement integer. Its value-range lies between -
9,223,372,036,854,775,808(-2^63) to 9,223,372,036,854,775,807(2^63 -1)(inclusive). Its minimum value
is - 9,223,372,036,854,775,808and maximum value is 9,223,372,036,854,775,807. Its default value is 0.
The long data type is used when you need a range of values more than those provided by int.

Example:

1. long a = 100000L, long b = -200000L

Float Data Type:


The float data type is a single-precision 32-bit IEEE 754 floating point.Its value range is unlimited. It is
recommended to use a float (instead of double) if you need to save memory in large arrays of floating
point numbers. The float data type should never be used for precise values, such as currency. Its
default value is 0.0F.

Example:

1. float f1 = 234.5f

Double Data Type:


The double data type is a double-precision 64-bit IEEE 754 floating point. Its value range is unlimited.
The double data type is generally used for decimal values just like float. The double data type also
should never be used for precise values, such as currency. Its default value is 0.0d.
Example:

1. double d1 = 12.3

Char Data Type:


The char data type is a single 16-bit Unicode character. Its value-range lies between '\u0000' (or 0) to
'\uffff' (or 65,535 inclusive).The char data type is used to store characters.

Example:

1. char letterA = 'A'


Why char uses 2 bytes in java and what is \u0000?
It is because java uses Unicode system not ASCII code system. The \u0000 is the lowest range of
Unicode system. To get detail explanation about Unicode visit next page.

Operators in Java:
Operator in Java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in Java which are given below:

o Unary Operator,
o Arithmetic Operator,
o Shift Operator,
o Relational Operator,
o Bitwise Operator,
o Logical Operator,
o Ternary Operator and
o Assignment Operator.

Java Operator Precedence:

Operator Type Category Precedence

Unary postfix expr++ expr--

prefix ++expr --expr +expr -expr ~ !

Arithmetic multiplicative * / %
additive + -

Shift shift << >> >>>

Relational comparison < > <= >= instanceof

equality == !=

Bitwise bitwise AND &

bitwise exclusive OR ^

bitwise inclusive OR |

Logical logical AND &&

logical OR ||

Ternary ternary ? :

Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator:


The Java unary operators require only one operand. Unary operators are used to perform various
operations i.e.:Competitive questions on Structures

o incrementing/decrementing a value by one


o negating an expression
o inverting the value of a boolean

Java Unary Operator Example: ++ and --:


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

Output:

10
12
12
10

Java Unary Operator Example 2: ++ and --:


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

Output:
22
21

Java Unary Operator Example: ~ and !:


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a);//-11 (minus of total positive value which starts from 0)
System.out.println(~b);//9 (positive of total minus, positive starts from 0)
System.out.println(!c);//false (opposite of boolean value)
System.out.println(!d);//true
}}

Output:
-11
9
false
true
Java Arithmetic Operators:
Java arithmetic operators are used to perform addition, subtraction, multiplication, and division. They
act as basic mathematical operations.

Java Arithmetic Operator Example:


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

Output:
15
5
50
2
0

Java Arithmetic Operator Example: Expression


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

Output:
21

Java Left Shift Operator


The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified
number of times.

Java Left Shift Operator Example


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

Output:
40
80
80
240

Java Right Shift Operator


The Java right shift operator >> is used to move the value of the left operand to right by the number
of bits specified by the right operand.

Java Right Shift Operator Example


public OperatorExample{
public static void main(String args[]){
System.out.println(10>>2);//10/2^2=10/4=2
System.out.println(20>>2);//20/2^2=20/4=5
System.out.println(20>>3);//20/2^3=20/8=2
}}

Output:
2
5
2

Java Shift Operator Example: >> vs >>>


public class OperatorExample{
public static void main(String args[]){
//For positive number, >> and >>> works same
System.out.println(20>>2);
System.out.println(20>>>2);
//For negative number, >>> changes parity bit (MSB) to 0
System.out.println(-20>>2);
System.out.println(-20>>>2);
}}

Output:
5
5
-5
Java AND Operator
1073741819 Example: Logical && and Bitwise &
The logical && operator doesn't check the second condition if the first condition is false. It checks the
second condition only if the first one is true.

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

public class OperatorExample{


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

Output:
false
false

Java AND Operator Example: Logical && vs Bitwise &


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

Output:

false
10
false
11
Java OR Operator Example: Logical || and Bitwise |
The logical || operator doesn't check the second condition if the first condition is true. It checks the
second condition only if the first one is false.

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

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int c=20;
System.out.println(a>b||a<c);//true || true = true
System.out.println(a>b|a<c);//true | true = true
//|| vs |
System.out.println(a>b||a++<c);//true || true = true
System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked
}}

Output:
true
true
true
10
true
11

Java Ternary Operator


Java Ternary operator is used as one line replacement for if-then-else statement and used a lot in Java
programming. It is the only conditional operator which takes three operands.

Java Ternary Operator Example


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

Output:
2

Another Example:

public class OperatorExample{


public static void main(String args[]){
int a=10;
int b=5;
int min=(a<b)?a:b;
System.out.println(min);
}}

Output:
5

Java Assignment Operator


Java assignment operator is one of the most common operators. It is used to assign the value on its
right to the operand on its left.

Java Assignment Operator Example


public class OperatorExample{
public static void main(String args[]){
int a=10;
int b=20;
a+=4;//a=a+4 (a=10+4)
b-=4;//b=b-4 (b=20-4)
System.out.println(a);
System.out.println(b);
}}

Output:
14
16
Java Assignment Operator Example
public class OperatorExample{
public static void main(String[] args){
int a=10;
a+=3;//10+3
System.out.println(a);
a-=4;//13-4
System.out.println(a);
a*=2;//9*2
System.out.println(a);
a/=2;//18/2
System.out.println(a);
}}

Output:
13
9
18
9

Java Assignment Operator Example: Adding short


public class OperatorExample{
public static void main(String args[]){
short a=10;
short b=10;
//a+=b;//a=a+b internally so fine
a=a+b;//Compile time error because 10+10=20 now int
System.out.println(a);
}}

Output:

Compile time error

After type cast:

public class OperatorExample{


public static void main(String args[]){
short a=10;
short b=10;
a=(short)(a+b);//20 which is int now converted to short
System.out.println(a);
}}

Output:
20

Java Control Statements | Control Flow in Java


Java compiler executes the code from top to bottom. The statements in the code are executed
according to the order in which they appear. However, Java

provides statements that can be used to control the flow of Java code. Such statements are called control flow
statements. It is one of the fundamental features of Java, which provides a smooth flow of program.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value, either
true or false. In Java, there are four types of if-statements given below. Stay

1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement

1) Simple if statement:

It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.

Syntax of if statement is given below.

if(condition) {
statement 1; //executes when condition is true
}

Consider the following example in which we have used the if statement in the java code.

Student.java

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y > 20) {
System.out.println("x + y is greater than 20");
}
}
}

Output:

x + y is greater than 20
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e., else block. The
else block is executed if the condition of the if-block is evaluated as false.

Syntax:

if(condition) {
statement 1; //executes when condition is true
}
else{
statement 2; //executes when condition is false
}

Example:

Student.java

public class Student {


public static void main(String[] args) {
int x = 10;
int y = 12;
if(x+y < 10) {
System.out.println("x + y is less than 10");
} else {
System.out.println("x + y is greater than 20");
}
}
}

Output:
x + y is greater than 20

3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.

Syntax:

if(condition 1) {
statement 1; //executes when condition 1 is true
}
else if(condition 2) {
statement 2; //executes when condition 2 is true
}
else {
statement 2; //executes when all the conditions are false
}

Example

Student.java

public class Student {


public static void main(String[] args) {
String city = "Delhi";
if(city == "Meerut") {
System.out.println("city is meerut");
}else if (city == "Noida") {
System.out.println("city is noida");
}else if(city == "Agra") {
System.out.println("city is agra");
}else {
System.out.println(city);
}
}
}

Output:
Delhi

4. Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or else-
if statement.

Syntax :
if(condition 1) {
statement 1; //executes when condition 1 is true
if(condition 2) {
statement 2; //executes when condition 2 is true
}
else{
statement 2; //executes when condition 2 is false
}
}

Example.

Student.java

public class Student {


public static void main(String[] args) {
String address = "Delhi, India";
if(address.endsWith("India")) {
if(address.contains("Meerut")) {
System.out.println("Your city is Meerut");
}else if(address.contains("Noida")) {
System.out.println("Your city is Noida");
}else {
System.out.println(address.split(",")[0]);
}
}else {
System.out.println("You are not living in India");
}
}
}

Output:
Delhi

Switch Statement:
In Java, Switch statement are similar to if-else-if statements. The switch statement contains multiple blocks of
code called cases and a single case is executed based on the variable which is being switched. The switch
statement is easier to use instead of if-else-if statements. It also enhances the readability of the program.
Points to be noted about switch statement:

o The case variables can be int, short, byte, char, or enumeration. String type is also supported since
version 7 of Java
o Cases cannot be duplicate
o Default statement is executed when any of the case doesn't match the value of expression. It is optional.
o Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
o While using switch statements, we must notice that the case expression will be of the same type as the
variable. However, it will also be a constant value.

Syntax:

switch (expression){
case value1:
statement1;
break;
.
.
.
case valueN:
statementN;
break;
default:
default statement;
}

Example:

Student.java

public class Student implements Cloneable {


public static void main(String[] args) {
int num = 2;
switch (num){
case 0:
System.out.println("number is 0");
break;
case 1:
System.out.println("number is 1");
break;
default:
System.out.println(num);
}
}
}

Output:
2

While using switch statements, we must notice that the case expression will be of the same type as
the variable. However, it will also be a constant value. The switch permits only int, string, and Enum
type variables to be used.

Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true. However, loop statements are used to execute the set of instructions in a repeated
order. The execution of the set of instructions depends upon a particular condition.

In Java, we have three types of loops that execute similarly. However, there are differences in their
syntax and condition checking time.

1. for loop
2. while loop
3. do-while loop

Java for loop


It enables us to initialize the loop variable, check the condition, and increment/decrement in a single line of
code. We use the for loop only when we exactly know the number of times, we want to execute the block of
code.

Syntax:

for(initialization, condition, increment/decrement) {

//block of statements
}

The flow chart for the for-loop is given below.


Example:

Calculation.java

public class Calculattion {


public static void main(String[] args) {
// TODO Auto-generated method stub
int sum = 0;
for(int j = 1; j<=10; j++) {
sum = sum + j;
}
System.out.println("The sum of first 10 natural numbers is " + sum);
}
}

Output:
The sum of first 10 natural numbers is 55

Java for-each loop


Java provides an enhanced for loop to traverse the data structures like array or collection. In the for-
each loop, we don't need to update the loop variable. The syntax to use the for-each loop in java is
given below.

Syntax:

for(data_type var : array_name/collection_name){


//statements
}
Example:

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
String[] names = {"Java","C","C++","Python","JavaScript"};
System.out.println("Printing the content of the array names:\n");
for(String name:names) {
System.out.println(name);
}
}
}

Output:

Printing the content of the array names:

Java
C
C++
Python
JavaScript

Java while loop


The while loop is also used to iterate over the number of statements multiple times. However, if we don't know
the number of iterations in advance, it is recommended to use a while loop. Unlike for loop, the initialization
and increment/decrement doesn't take place inside the loop statement in while loop.

It is also known as the entry-controlled loop since the condition is checked at the start of the loop. If
the condition is true, then the loop body will be executed; otherwise, the statements after the loop
will be executed.

Syntax

while(condition){
//looping statements
}

The flow chart for the while loop is given in the following image.
Example.

Calculation .java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
while(i<=10) {
System.out.println(i);
i = i + 2;
}
}
}

Output:

Printing the list of first 10 even numbers

0
2
4
6
8
10

Java do-while loop


The do-while loop checks the condition at the end of the loop after executing the loop statements. When the
number of iteration is not known and we have to execute the loop at least once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance.

Syntax

do
{
//statements
} while (condition);

The flow chart of the do-while loop is given in the following image.

Example

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
int i = 0;
System.out.println("Printing the list of first 10 even numbers \n");
do {
System.out.println(i);
i = i + 2;
}while(i<=10);
}
}

Output:
Printing the list of first 10 even numbers

0
2
4
Jump
6 Statements
8
Jump
10 statements are used to transfer the control of the program to the specific statements. In other
words, jump statements transfer the execution control to the other part of the program. There are two
types of jump statements in Java, i.e., break and continue.

Java break statement


Break statement is used to break the current flow of the program and transfer the control to the next statement outside
a loop or switch statement. However, it breaks only the inner loop in the case of the nested loop.

The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.

The break statement example with for loop

Consider the following example in which we have used the break statement with the for loop.

BreakExample.java

public class BreakExample {


public static void main(String[] args) {
// TODO Auto-generated method stub
for(int i = 0; i<= 10; i++) {
System.out.println(i);
if(i==6) {
break;
}
}
}
}

Output:

0
1
2
3
break statement example with labeled for loop

Calculation.java

public class Calculation {


public static void main(String[] args) {
// TODO Auto-generated method stub
a:
for(int i = 0; i<= 10; i++) {
b:
for(int j = 0; j<=15;j++) {
c:
for (int k = 0; k<=20; k++) {
System.out.println(k);
if(k==5) {
break a;
}
}
}
}
}
}

Output:
0
1
2
3
4
5

Java continue statement


Continue Statement doesn't break the loop, whereas, it skips the specific part of the loop and jumps to the next iteration
of the loop immediately.
Example

public class ContinueExample {

public static void main(String[] args) {

// TODO Auto-generated method stub

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


for (int j = i; j<=5; j++) {
if(j == 4) {
continue;
}
System.out.println(j);
}
}
}
}

Output:
0
1
2
3
5
1
2
3
5
2
3
5
Classes and Objects in Java
Classes and Objects are basic concepts of Object Oriented Programming which revolve around the real
life entities.

Class

A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:
1. Modifiers: A class can be public or has default access (Refer this for details).
2. class keyword: class keyword is used to create a class.
3. Class name: The name should begin with an initial letter (capitalized by convention).
4. Super-class (if any): The name of the class’s parent (superclass), if any, preceded by the
keyword extends. A class can only extend (subclass) one parent.
5. Interfaces (if any): A comma-separated list of interfaces implemented by the class, if any,
preceded by the keyword implements. A class can implement more than one interface.
6. Body: The class body surrounded by braces, { }.
Constructors are used for initializing new objects. Fields are variables that provides the state of the
class and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested
classes, anonymous classes, lambda expressions.

Object

It is a basic unit of Object-Oriented Programming and represents the real-life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists
of:
1. State: It is represented by attributes of an object. It also reflects the properties of an object.
2. Behavior: It is represented by methods of an object. It also reflects the response of an object
with other objects.
3. Identity: It gives a unique name to an object and enables one object to interact with other
objects.
Example of an object: dog

Objects correspond to things found in the real world. For example, a graphics program may have
objects such as “circle”, “square”, “menu”. An online shopping system might have objects such as
“shopping cart”, “customer”, and “product”.

Declaring Objects (Also called instantiating a class)

When an object of a class is created, the class is said to be instantiated. All the instances share the
attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for
each object. A single class may have any number of instances.
Example:

As we declare variables like (type name;). This notifies the compiler that we will use name to refer to
data whose type is type. With a primitive variable, this declaration also reserves the proper amount of
memory for the variable. So for reference variable, type must be strictly a concrete class name. In
general, we can’t create objects of an abstract class or an interface.
Dog tuffy;
If we declare reference variable(tuffy) like this, its value will be undetermined(null) until an object is
actually created and assigned to it. Simply declaring a reference variable does not create an object.

Initializing an object

The new operator instantiates a class by allocating memory for a new object and returning a reference
to that memory. The new operator also invokes the class constructor.

// Class Declaration

public class Dog

// Instance Variables

String name;

String breed;

int age;
String color;

// Constructor Declaration of Class

public Dog(String name, String breed,

int age, String color)

this.name = name;

this.breed = breed;

this.age = age;

this.color = color;

// method 1

public String getName()

return name;

// method 2

public String getBreed()

return breed;

// method 3

public int getAge()

return age;

// method 4
public String getColor()

return color;

@Override

public String toString()

return("Hi my name is "+ this.getName()+

".\nMy breed,age and color are " +

this.getBreed()+"," + this.getAge()+

","+ this.getColor());

public static void main(String[] args)

Dog tuffy = new Dog("tuffy","papillon", 5, "white");

System.out.println(tuffy.toString());

Output:
Hi my name is tuffy.
My breed,age and color are papillon,5,white
 This class contains a single constructor. We can recognize a constructor because its
declaration uses the same name as the class and it has no return type. The Java compiler
differentiates the constructors based on the number and the type of the arguments. The
constructor in the Dog class takes four arguments. The following statement provides
“tuffy”,”papillon”,5,”white” as values for those arguments:
Dog tuffy = new Dog("tuffy","papillon",5, "white");
 The result of executing this statement can be illustrated as :
Note : All classes have at least one constructor. If a class does not explicitly declare any, the Java
compiler automatically provides a no-argument constructor, also called the default constructor. This
default constructor calls the class parent’s no-argument constructor (as it contain only one statement i.e
super();), or the Object class constructor if the class has no other parent (as Object class is parent of all
classes either directly or indirectly).

Ways to create object of a class

There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
 Using new keyword: It is the most common and general way to create object in
java. Example:
// creating object of class Test
Test t = new Test();
 Using Class.forName(String className) method: There is a pre-defined class in java.lang
package with name Class. The forName(String className) method returns the Class object
associated with the class with the given string name.We have to give the fully qualified name
for a class. On calling new Instance() method on this Class object returns new instance of the
class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test)Class.forName("com.p1.Test").newInstance();
 Using clone() method: clone() method is present in Object class. It creates and returns a
copy of the object.

// creating object of class Test


Test t1 = new Test();

// creating clone of above object


Test t2 = (Test)t1.clone();
 Deserialization: De-serialization is technique of reading an object from the saved state in a
file. Refer Serialization/De-Serialization in java

FileInputStream file = new FileInputStream(filename);


ObjectInputStream in = new ObjectInputStream(file);
Object obj = in.readObject();

Creating multiple objects by one type only (A good practice)

 In real-time, we need different objects of a class in different methods. Creating a number of


references for storing them is not a good practice and therefore we declare a static reference
variable and use it whenever required. In this case, wastage of memory is less. The objects
that are not referenced anymore will be destroyed by Garbage Collector of java. Example:

Test test = new Test();


test = new Test();
 In inheritance system, we use parent class reference variable to store a sub-class object. In
this case, we can switch into different subclass objects using same referenced variable.
Example:
class Animal {}

class Dog extends Animal {}


class Cat extends Animal {}

public class Test


{
// using Dog object
Animal obj = new Dog();
// using Cat object
obj = new Cat();
}

Anonymous objects

Anonymous objects are the objects that are instantiated but are not stored in a reference variable.
 They are used for immediate method calling.
 They will be destroyed after method calling.
 They are widely used in different libraries. For example, in AWT libraries, they are used to
perform some action on capturing an event(eg a key press).
 In the example below, when a key is button(referred by the btn) is pressed, we are simply
creating anonymous object of EventHandler class for just calling handle method.
btn.setOnAction(new EventHandler()
{
public void handle(ActionEvent event)
{
System.out.println("Hello World!");
}
});

Encapsulation in Java
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism that binds
together code and the data it manipulates. Another way to think about encapsulation is, it is a protective
shield that prevents the data from being accessed by the code outside this shield.

 Technically in encapsulation, the variables or data of a class is hidden from any other class
and can be accessed only through any member function of its own class in which it is
declared.
 As in encapsulation, the data in a class is hidden from other classes using the data hiding
concept which is achieved by making the members or methods of a class private, and the
class is exposed to the end-user or the world without providing any details behind
implementation using the abstraction concept, so it is also known as a combination of data-
hiding and abstraction.
 Encapsulation can be achieved by Declaring all the variables in the class as private and
writing public methods in the class to set and get the values of variables

The program to access variables of the class EncapsulateDemo is shown below:

// Java program to demonstrate encapsulation


class Encapsulate {

// private variables declared

// these can only be accessed by

// public methods of class

private String geekName;

private int geekRoll;

private int geekAge;

// get method for age to access

// private variable geekAge

public int getAge() { return geekAge; }

// get method for name to access

// private variable geekName

public String getName() { return geekName; }

// get method for roll to access

// private variable geekRoll

public int getRoll() { return geekRoll; }

// set method for age to access

// private variable geekage

public void setAge(int newAge) { geekAge = newAge; }

// set method for name to access

// private variable geekName

public void setName(String newName)

geekName = newName;

}
// set method for roll to access

// private variable geekRoll

public void setRoll(int newRoll) { geekRoll = newRoll; }

public class TestEncapsulation {

public static void main(String[] args)

Encapsulate obj = new Encapsulate();

// setting values of the variables

obj.setName("Harsh");

obj.setAge(19);

obj.setRoll(51);

// Displaying values of the variables

System.out.println("Geek's name: " + obj.getName());

System.out.println("Geek's age: " + obj.getAge());

System.out.println("Geek's roll: " + obj.getRoll());

// Direct access of geekRoll is not possible

// due to encapsulation

// System.out.println("Geek's roll: " +

// obj.geekName);

Output
Geek's name: Harsh
Geek's age: 19
Geek's roll: 51
In the above program, the class Encapsulate is encapsulated as the variables are declared as private.
The get methods like getAge() , getName() , getRoll() are set as public, these methods are used to
access these variables. The setter methods like setName(), setAge(), setRoll() are also declared as
public and are used to set the values of the variables.
Advantages of Encapsulation:
 Data Hiding: The user will have no idea about the inner implementation of the class. It will
not be visible to the user how the class is storing values in the variables. The user will only
know that we are passing the values to a setter method and variables are getting initialized
with that value.
 Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirement. If we wish to make the variables read-only then we have to
omit the setter methods like setName(), setAge(), etc. from the above program or if we wish
to make the variables as write-only then we have to omit the get methods like getName(),
getAge(), etc. from the above program
 Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
 Testing code is easy: Encapsulated code is easy to test for unit testing.

Abstraction in Java
Data Abstraction is the property by virtue of which only the essential details are displayed to the user.
The trivial or the non-essentials units are not displayed to the user. Ex: A car is viewed as a car rather
than its individual components.
Data Abstraction may also be defined as the process of identifying only the required characteristics of
an object ignoring the irrelevant details. The properties and behaviours of an object differentiate it from
other objects of similar type and also help in classifying/grouping the objects.
Consider a real-life example of a man driving a car. The man only knows that pressing the accelerators
will increase the speed of a car or applying brakes will stop the car, but he does not know about how on
pressing the accelerator the speed is actually increasing, he does not know about the inner mechanism
of the car or the implementation of the accelerator, brakes, etc in the car. This is what abstraction is.
In java, abstraction is achieved by interfaces and abstract classes. We can achieve 100% abstraction
using interfaces.
Abstract classes and Abstract methods :
1. An abstract class is a class that is declared with an abstract keyword.
2. An abstract method is a method that is declared without implementation.
3. An abstract class may or may not have all abstract methods. Some of them can be concrete
methods
4. A method defined abstract must always be redefined in the subclass, thus
making overriding compulsory OR either make the subclass itself abstract.
5. Any class that contains one or more abstract methods must also be declared with an abstract
keyword.
6. There can be no object of an abstract class. That is, an abstract class can not be directly
instantiated with the new operator.
7. An abstract class can have parameterized constructors and the default constructor is always
present in an abstract class.
When to use abstract classes and abstract methods with an example
There are situations in which we will want to define a superclass that declares the structure of a given
abstraction without providing a complete implementation of every method. That is, sometimes we will
want to create a superclass that only defines a generalization form that will be shared by all of its
subclasses, leaving it to each subclass to fill in the details.
Consider a classic “shape” example, perhaps used in a computer-aided design system or game
simulation. The base type is “shape” and each shape has a color, size, and so on. From this, specific
types of shapes are derived(inherited)-circle, square, triangle, and so on — each of which may have
additional characteristics and behaviors. For example, certain shapes can be flipped. Some behaviors
may be different, such as when you want to calculate the area of a shape. The type hierarchy embodies
both the similarities and differences between the shapes.

// Java program to illustrate the

// concept of Abstraction

abstract class Shape {

String color;

// these are abstract methods

abstract double area();

public abstract String toString();

// abstract class can have the constructor

public Shape(String color)

System.out.println("Shape constructor called");


this.color = color;

// this is a concrete method

public String getColor() { return color; }

class Circle extends Shape {

double radius;

public Circle(String color, double radius)

// calling Shape constructor

super(color);

System.out.println("Circle constructor called");

this.radius = radius;

@Override double area()

return Math.PI * Math.pow(radius, 2);

@Override public String toString()

return "Circle color is " + super.getColor()

+ "and area is : " + area();

class Rectangle extends Shape {


double length;

double width;

public Rectangle(String color, double length,

double width)

// calling Shape constructor

super(color);

System.out.println("Rectangle constructor called");

this.length = length;

this.width = width;

@Override double area() { return length * width; }

@Override public String toString()

return "Rectangle color is " + super.getColor()

+ "and area is : " + area();

public class Test {

public static void main(String[] args)

Shape s1 = new Circle("Red", 2.2);

Shape s2 = new Rectangle("Yellow", 2, 4);

System.out.println(s1.toString());

System.out.println(s2.toString());

}
Output
Shape constructor called
Circle constructor called
Shape constructor called
Rectangle constructor called
Circle color is Redand area is : 15.205308443374602
Rectangle color is Yellowand area is : 8.0
Encapsulation vs Data Abstraction
1. Encapsulation is data hiding(information hiding) while Abstraction is detailed
hiding(implementation hiding).
2. While encapsulation groups together data and methods that act upon the data, data
abstraction deal with exposing the interface to the user and hiding the details of
implementation.
Advantages of Abstraction
1. It reduces the complexity of viewing the things.
2. Avoids code duplication and increases reusability.
3. Helps to increase the security of an application or program as only important details are
provided to the user.

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

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

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Why use inheritance in java


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

Terms used in Inheritance


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

The syntax of Java Inheritance


class Subclass-name extends Superclass-name
{
//methods and fields
}

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

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

Java Inheritance Example

As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a
type of Employee.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is: 40000.0
Bonus of programmer is: 10000

In the above example, Programmer object can access the field of own class as well as of Employee
class i.e. code reusability.

Types of inheritance in java


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

In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.

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

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class TestInheritance{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}}

Output:

barking. . .
eating. . .

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the
example given below, BabyDog class inherits the Dog class which again inherits the Animal class, so
there is a multilevel inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class BabyDog extends Dog{
void weep(){System.out.println("weeping...");}
}
class TestInheritance2{
public static void main(String args[]){
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}}

Output:
Weeping. . .
barking. . .
eating. . .

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:
meowing. . .
eating. . .

Q) Why multiple inheritance is not supported in


java?
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If A and B
classes have the same method and you call it from child class object, there will be ambiguity to call
the method of A or B class.

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

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Compile Time Error

Polymorphism in Java
The word polymorphism means having many forms. In simple words, we can define polymorphism as
the ability of a message to be displayed in more than one form.
Real-life Illustration: Polymorphism
A person at the same time can have different characteristics. Like a man at the same time is a father, a
husband, an employee. So the same person possesses different behavior in different situations. This is
called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.
Types of polymorphism
In Java polymorphism is mainly divided into two types:
 Compile-time Polymorphism
 Runtime Polymorphism
Type 1: Compile-time polymorphism
It is also known as static polymorphism. This type of polymorphism is achieved by function
overloading or operator overloading.
Note: But Java doesn’t support the Operator Overloading.
Method Overloading: When there are multiple functions with the same name but different parameters
then these functions are said to be overloaded. Functions can be overloaded by change in the number
of arguments or/and a change in the type of arguments.
Example 1
// Java Program for Method overloading

// By using Different Types of Arguments

// Class 1

// Helper class

class Helper {

// Method with 2 integer parameters

static int Multiply(int a, int b)

// Returns product of integer numbers

return a * b;

// Method 2

// With same name but with 2 double parameters

static double Multiply(double a, double b)

{
// Returns product of double numbers

return a * b;

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Calling method by passing

// input as in arguments

System.out.println(Helper.Multiply(2, 4));

System.out.println(Helper.Multiply(5.5, 6.3));

Output:
8
34.65

Example 2
// Java program for Method Overloading

// by Using Different Numbers of Arguments

// Class 1

// Helper class

class Helper {
// Method 1

// Multiplication of 2 numbers

static int Multiply(int a, int b)

// Return product

return a * b;

// Method 2

// // Multiplication of 3 numbers

static int Multiply(int a, int b, int c)

// Return product

return a * b * c;

// Class 2

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Calling method by passing

// input as in arguments

System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(2, 7, 3));

Output:
8
42

Type 2: Runtime polymorphism


It is also known as Dynamic Method Dispatch. It is a process in which a function call to the overridden
method is resolved at Runtime. This type of polymorphism is achieved by Method Overriding. Method
overriding, on the other hand, occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
Example
// Java Program for Method Overriding

// Class 1

// Helper class

class Parent {

// Method of parent class

void Print()

// Print statement

System.out.println("parent class");

// Class 2

// Helper class

class subclass1 extends Parent {


// Method

void Print() { System.out.println("subclass1"); }

// Class 3

// Helper class

class subclass2 extends Parent {

// Method

void Print()

// Print statement

System.out.println("subclass2");

// Class 4

// Main class

class GFG {

// Main driver method

public static void main(String[] args)

// Creating object of class 1

Parent a;

// Now we will be calling print methods

// inside main() method


a = new subclass1();

a.Print();

a = new subclass2();

a.Print();

Output:
subclass1
subclass2

Output explanation:
Here in this program, When an object of child class is created, then the method inside the child class is
called. This is because The method in the parent class is overridden by the child class. Since The
method is overridden, This method has more priority than the parent method inside the child class. So,
the body inside the child class is executed.
Dynamic Binding:
In dynamic binding, the method call is bonded to the method body at runtime. This is also known as
late binding. This is done using instance methods.

Example
class Super {
public void sample() {
System.out.println("This is the method of super class");
}
}

Public class extends Super {


Public static void sample() {
System.out.println("This is the method of sub class");
}

Public static void main(String args[]) {


new Sub().sample()
}}
Output
This is the method of sub class

Message Passing in Java


What is message passing and why it is used?
Message Passing in terms of computers is communication between processes. It is a form of
communication used in object-oriented programming as well as parallel programming. Message
passing in Java is like sending an object i.e. message from one thread to another thread. It is used when
threads do not have shared memory and are unable to share monitors or semaphores or any other shared
variables to communicate. Suppose we consider an example of producer and consumer, likewise what
producer will produce, the consumer will be able to consume that only. We mostly use Queue to
implement communication between threads.

In the example explained below, we will be using vector(queue) to store the messages, 7 at a time and
after that producer will wait for the consumer until the queue is empty.
In Producer there are two synchronized methods putMessage() which will call form run() method of
Producer and add message in Vector whereas getMessage() extracts the message from the queue for
the consumer.
Using message passing simplifies the producer-consumer problem as they don’t have to reference each
other directly but only communicate via a queue.
Example:
import java.util.Vector;

class Producer extends Thread {

// initialization of queue size

static final int MAX = 7;

private Vector messages = new Vector();


@Override

public void run()

try {

while (true) {

// producing a message to send to the consumer

putMessage();

// producer goes to sleep when the queue is full

sleep(1000);

catch (InterruptedException e) {

private synchronized void putMessage()

throws InterruptedException

// checks whether the queue is full or not

while (messages.size() == MAX)

// waits for the queue to get empty

wait();

// then again adds element or messages

messages.addElement(new java.util.Date().toString());

notify();

}
public synchronized String getMessage()

throws InterruptedException

notify();

while (messages.size() == 0)

wait();

String message = (String)messages.firstElement();

// extracts the message from the queue

messages.removeElement(message);

return message;

class Consumer extends Thread {

Producer producer;

Consumer(Producer p)

producer = p;

@Override

public void run()

try {

while (true) {

String message = producer.getMessage();

// sends a reply to producer got a message


System.out.println("Got message: " + message);

sleep(2000);

catch (InterruptedException e) {

public static void main(String args[])

Producer producer = new Producer();

producer.start();

new Consumer(producer).start();

Output:
Got message: Thu May 09 06:57:53 UTC 2019
Got message: Thu May 09 06:57:54 UTC 2019
Got message: Thu May 09 06:57:55 UTC 2019
Got message: Thu May 09 06:57:56 UTC 2019
Got message: Thu May 09 06:57:57 UTC 2019
Got message: Thu May 09 06:57:58 UTC 2019
Got message: Thu May 09 06:57:59 UTC 2019
Got message: Thu May 09 06:58:00 UTC 2019
Reference Variable in Java
Before We Started with the Reference variable we should know about the following facts.
1. When we create an object (instance) of class then space is reserved in heap memory. Let’s
understand with the help of an example.
Demo D1 = new Demo();

Now, The space in the heap Memory is created but the question is how to access that space?.
Then, We create a Pointing element or simply called Reference variable which simply points out the
Object(the created space in a Heap Memory).

Understanding Reference variable


1. Reference variable is used to point object/values.
2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference
variables hold the objects/values of reference types in Java.
3. Reference variable can also store null value. By default, if no object is passed to a reference variable
then it will store a null value.
4. You can access object members using a reference variable using dot syntax.
<reference variable name >.<instance variable_name / method_name>
Example:
// Java program to demonstrate reference

// variable in java

import java.io.*;

class Demo {

int x = 10;

int display()

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

return 0;

class Main {

public static void main(String[] args)

Demo D1 = new Demo(); // point 1

System.out.println(D1); // point 2

System.out.println(D1.display()); // point 3

Output
Demo@214c265e
x = 10
0

Let us see what is actually happening step by step.

1. When we create an object of demo class new DEMO();, the default constructor is called and returns
a reference of the object, and simply this reference will be stored to the reference variable D1 (As we
know that associativity is Right-hand side to left-hand side).
2. The value of a reference variable is a reference. When we attempt to print the value of a reference
variable, the output contains the type of the variable and the hash code created for it by Java: the
string Demo@214c265e tells us that the given variable is of type Name and its hexadecimal format of
hash code is 214c265e.

3. At this point we will access the methods display() of the class demo using our custom reference
variable that we created.

BINDING UP : The constructor call returns a value that is a reference to the newly-created object.
The equality sign tells the program that the value of the right-hand side expression is to be copied as
the value of the variable on the left-hand side. The reference to the newly-created object, returned by
the constructor call, is copied as the value of the variable.

import java.io.*;

class Demo {

int x = 10;

int display()

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

return 0;

class Main {

public static void main(String[] args)

// create instance

Demo D1 = new Demo();

// accessing instance(object) variable

System.out.println(D1.x);

// point 3

// accessing instance(object) method

D1.display();

}}
Output
10
x = 10

// Accessing instance methods

import java.io.*;

class Demo {

int x = 10;

int display()

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

return 0;

class Main {

public static void main(String[] args)

// create instances

Demo D1 = new Demo();

Demo M1 = new Demo();


Demo Q1 = new Demo();

// Pointing to same instance memory

import java.io.*;

class Demo {

int x = 10;

int display()

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

return 0;

class Main {

public static void main(String[] args)

// create instance

Demo D1 = new Demo();


// point to same reference

Demo G1 = D1;

Demo M1 = new Demo();

Demo Q1 = M1;

// updating the value of x using G!

// reference variable

G1.x = 25;

System.out.println(G1.x); // Point 1

System.out.println(D1.x); // Point 2

Output
25
25

Note:
Here we pass G1 and Q1 reference variable point out the same object respectively. Secondly At Point
1 we try to get the value of the object with G1 reference variable which shows it as 25 and At Point
2 we try to get the value of an object with D1 reference variable which shows it as 25 as well. This will
prove that the modification in the object can be done by using any reference variable but the condition
is it should hold the same reference.
More on Reference Variable

1. Reference Variable as Method Parameters:

As the value of a primitive variable is directly stored in the variable, whereas the value of a reference
variable holds a reference to an object. We also mentioned that assigning a value with the equality sign
copies the value (possibly of some variable) on the right-hand side and stores it as the value of the left-
hand-side variable. A similar kind of copying occurs during a method call. Regardless of whether the
variable is primitive or reference type, a copy of the value is passed to the method’s argument and
copied to that argument.

Note: Java only supports pass by value.


But we know that the reference variable holds the reference of an instance(OBJECT) so a copy of the
reference is passed to the method’s argument.

Example:

// Pass by reference and value

import java.io.*;

class Demo {

int x = 10;

int y = 20;

int display(Demo A, Demo B)

// Updating value using argument

A.x = 95;

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

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

return 0;

class Main {

public static void main(String[] args)

{
Demo C = new Demo();

Demo D = new Demo();

// updating value using primary reference

// variable

D.y = 55;

C.display(C, D); // POINT 1

D.display(C, D); // POINT 2

Output
x = 95
y = 20
x = 10
y = 55

SCENE 1 :
SCENE 2:

Now, What is going on here, when we pass the reference to the method it will copy to the reference
variable defined in the method signature and After that, they also have access to the object members.
Here, We defined two instances named C and D. Afterwards we pass C and D to the method which
further gives reference to A and B

At Point 1: A will update the value of x from 10 to 95, hence C.display() will show 95 20 but in
another object D we update the value of x through D only from y =20 to 55, hence D, display() will
show 10 and 55.

Note: Any Object Updation will not affect the other object’s member.
2. What if we swap the reference variables with the help of the Swap Method?

The fact is if we try to swap the reference variable, then they just swap their Pointing element there is
no effect on the address of reference variable and object(Instance) Space. Let’s Understand It with the
help of an example:
Note: There is no swapping between Variables, They only change their References.
3. What if we pass arrays to the method will it be able to update the Actual Array’s values, even
we know that a copy of the array is a pass to the formal Array?
The answer is YES, the values will be updated by Formal parameter, The Fact is, When we create an
Array, a memory is assigned to the array of the desired size, and it returns the reference of the first
array’s element that is the base address that will store to the Formal Array(Method argument). As we
learned earlier every pointing reference variable can change or update the object.

4. this and super keywords are also Pointing Elements.

this keyword. In java, this is a reference variable that refers to the current object.

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

5. null value of a reference variable.


Demo obj = null ;
A. The null reference can be set as the value of any reference type variable.

B. The object whose name is obj is referred to by nobody. In other words, the object has
become garbage. In the Java programming language, the programmer need not worry about the
program’s memory use. From time to time, the automatic garbage collector of the Java language cleans
up the objects that have become garbage. If the garbage collection did not happen, the garbage objects
would reserve a memory location until the end of the program execution.

You might also like