Java Notes
Java Notes
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
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.
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.
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 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:
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:
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:
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:
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;
}
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:
For example:
The methods are the set of instructions that we want to perform. These instructions execute at runtime and
perform the specified task. For example:
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
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
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.
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.
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.
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.
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.
5. Can contain alphabets, character, and digits if the other conditions are met.
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.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
The Boolean data type specifies one bit of information, but its "size" can't be defined precisely.
Example:
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:
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:
The int data type is generally used as a default data type for integral values unless if there is no
problem about memory.
Example:
Example:
Example:
1. float f1 = 234.5f
1. double d1 = 12.3
Example:
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.
Arithmetic multiplicative * / %
additive + -
equality == !=
bitwise exclusive OR ^
bitwise inclusive OR |
logical OR ||
Ternary ternary ? :
Output:
10
12
12
10
Output:
22
21
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.
Output:
15
5
50
2
0
Output:
21
Output:
40
80
80
240
Output:
2
5
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.
Output:
false
false
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.
Output:
true
true
true
10
true
11
Output:
2
Another Example:
Output:
5
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
Output:
Output:
20
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.
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.
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
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
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
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
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
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
Syntax:
//block of statements
}
Calculation.java
Output:
The sum of first 10 natural numbers is 55
Syntax:
Calculation.java
Output:
Java
C
C++
Python
JavaScript
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
Output:
0
2
4
6
8
10
Syntax
do
{
//statements
} while (condition);
The flow chart of the do-while loop is given in the following image.
Example
Calculation.java
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.
The break statement cannot be used independently in the Java program, i.e., it can only be written
inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
Output:
0
1
2
3
break statement example with labeled for loop
Calculation.java
Output:
0
1
2
3
4
5
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”.
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
// Instance Variables
String name;
String breed;
int age;
String color;
this.name = name;
this.breed = breed;
this.age = age;
this.color = color;
// method 1
return name;
// method 2
return breed;
// method 3
return age;
// method 4
public String getColor()
return color;
@Override
this.getBreed()+"," + this.getAge()+
","+ this.getColor());
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).
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.
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
geekName = newName;
}
// set method for roll to access
obj.setName("Harsh");
obj.setAge(19);
obj.setRoll(51);
// due to encapsulation
// 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.
// concept of Abstraction
String color;
double radius;
super(color);
this.radius = radius;
double width;
double width)
super(color);
this.length = length;
this.width = width;
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.
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.
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.
In java programming, multiple and hybrid inheritance is supported through interface only. We will
learn about interfaces later.
When one class inherits multiple classes, it is known as multiple inheritance. For Example:
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. . .
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. . .
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. . .
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
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
// Class 1
// Helper class
class Helper {
return a * b;
// Method 2
{
// Returns product of double numbers
return a * b;
// Class 2
// Main class
class GFG {
// 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
// Class 1
// Helper class
class Helper {
// Method 1
// Multiplication of 2 numbers
// Return product
return a * b;
// Method 2
// // Multiplication of 3 numbers
// Return product
return a * b * c;
// Class 2
// Main class
class GFG {
// input as in arguments
System.out.println(Helper.Multiply(2, 4));
System.out.println(Helper.Multiply(2, 7, 3));
Output:
8
42
// Class 1
// Helper class
class Parent {
void Print()
// Print statement
System.out.println("parent class");
// Class 2
// Helper class
// Class 3
// Helper class
// Method
void Print()
// Print statement
System.out.println("subclass2");
// Class 4
// Main class
class GFG {
Parent a;
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");
}
}
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;
try {
while (true) {
putMessage();
sleep(1000);
catch (InterruptedException e) {
throws InterruptedException
wait();
messages.addElement(new java.util.Date().toString());
notify();
}
public synchronized String getMessage()
throws InterruptedException
notify();
while (messages.size() == 0)
wait();
messages.removeElement(message);
return message;
Producer producer;
Consumer(Producer p)
producer = p;
@Override
try {
while (true) {
sleep(2000);
catch (InterruptedException e) {
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).
// variable in java
import java.io.*;
class Demo {
int x = 10;
int display()
return 0;
class Main {
System.out.println(D1); // point 2
System.out.println(D1.display()); // point 3
Output
Demo@214c265e
x = 10
0
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()
return 0;
class Main {
// create instance
System.out.println(D1.x);
// point 3
D1.display();
}}
Output
10
x = 10
import java.io.*;
class Demo {
int x = 10;
int display()
return 0;
class Main {
// create instances
import java.io.*;
class Demo {
int x = 10;
int display()
return 0;
class Main {
// create instance
Demo G1 = D1;
Demo Q1 = M1;
// 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
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.
Example:
import java.io.*;
class Demo {
int x = 10;
int y = 20;
A.x = 95;
return 0;
class Main {
{
Demo C = new Demo();
// variable
D.y = 55;
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.
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.
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.