Java Notes Important
Java Notes Important
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a
methodology or paradigm to design a program using classes and objects. It simplifies the software
development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation
Object
Any entity that has state and behavior is known as an object. For example: chair, pen, table,
keyboard, bike etc. It can be physical and logical.
Class
Collection of objects is called class. It is a logical entity.
Inheritance
When one object acquires all the properties and behaviours of parent object i.e. known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.
Polymorphism
When one task is performed by different ways i.e. known as polymorphism. For example: to
convense the customer differently, to draw something e.g. shape or rectangle etc.
In java, we use method overloading and method overriding to achieve polymorphism.
Another example can be to speak something e.g. cat speaks meaw, dog barks woof etc.
Abstraction
Hiding internal details and showing functionality is known as abstraction. For example: phone
call, we don't know the internal processing.
In java, we use abstract class and interface to achieve abstraction.
Encapsulation
Binding (or wrapping) code and data together into a single unit is known as
encapsulation. For example: capsule, it is wrapped with different medicines.
A java class is the example of encapsulation. Java bean is the fully encapsulated class because all
the data members are private here.
3)OOPs provides ability to simulate real-world event much more effectively. We can provide the
solution of real word problem if we are using the Object-Oriented Programming language.
What is difference between object-oriented programming language and objectbased programming language?
Object based programming language follows all the features of OOPs except Inheritance.
JavaScript and VBScript are examples of object based programming languages.
Object in Java
An entity that has state and behavior is known as an object e.g. chair, bike, marker, pen, table, car
etc. It can be physical or logical (tengible and intengible). The example of integible object is banking
system.
An object has three characteristics:
For Example: Pen is an object. Its name is Reynolds, color is white etc. known as its state. It is
used to write, so writing is its behavior.
Object is an instance of a class. Class is a template or blueprint from which objects are
created. So object is the instance(result) of a class.
Class in Java
A class is a group of objects that has common properties. It is a template or blueprint from which
objects are created.
A class in java can contain:
data member
method
1.
2.
3.
4.
constructor
block
class and interface
class <class_name>{
data member;
method;
}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Student{
int id;//data member (also instance variable)
String name;//data member(also instance variable)
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.id+" "+s1.name);
}
}
Output:0 null
Method in Java
In java, a method is like function i.e. used to expose behaviour of an object.
Advantage of Method
Code Reusability
Code Optimization
new keyword
The new keyword is used to allocate memory at runtime.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}//method
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}
Output:111 Karan
222 Aryan
As you see in the above figure, object gets the memory in Heap area and reference variable
refers to the object allocated in the Heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.
20.
21.
22.
r2.calculateArea();
}
}
Output:55
45
are
By
By
By
By
Annonymous object
Annonymous simply means nameless.An object that have no reference is known as annonymous
object.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
If you have to use an object only once, annonymous object is a good approach.
class Calculation{
void fact(int n){
int fact=1;
for(int i=1;i<=n;i++){
fact=fact*i;
}
System.out.println("factorial is "+fact);
}
public static void main(String args[]){
new Calculation().fact(5);//calling method with annonymous object
}
}
Output:Factorial is 120
17.
18.
19.
20.
21.
r1.calculateArea();
r2.calculateArea();
}
}
Output:55
45
In java, Methood Overloading is not possible by changing the return type of the method.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(int a,int b,int c){System.out.println(a+b+c);}
public static void main(String args[]){
6.
7.
8.
9.
10.
11.
class Calculation{
void sum(int a,int b){System.out.println(a+b);}
void sum(double a,double b){System.out.println(a+b);}
public static void main(String args[]){
Calculation obj=new Calculation();
obj.sum(10.5,10.5);
obj.sum(20,20);
}
}
Output:21.0
40
Que) Why Method Overloaing is not possible by changing the return type of method?
In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:
because there was problem:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class Calculation{
int sum(int a,int b){System.out.println(a+b);}
double sum(int a,int b){System.out.println(a+b);}
public static void main(String args[]){
Calculation obj=new Calculation();
int result=obj.sum(20,20); //Compile Time Error
}
}
int result=obj.sum(20,20); //Here how can java determine which sum() method should be called
class Simple{
public static void main(int a){
System.out.println(a);
}
Constructor in Java
Constructor is a special type of method that is used to initialize the object.
Constructor is invoked at the time of object creation. It constructs the values i.e. provides data
for the object that is why it is known as constructor.
Types of constructors
There are two types of constructors:
1. default constructor (no-arg constructor)
2. parameterized constructor
1) Default Constructor
A constructor that have no parameter is known as default constructor.
<class_name>(){}
1.
2.
3.
4.
5.
6.
7.
8.
class Student{
int id;
String name;
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.display();
s2.display();
}
}
Output:0 null
0 null
Explanation:In the above class,you are not creating any constructor so compiler provides you a
default constructor.Here 0 and null values are provided by default constructor.
Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Constructor Overloading
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by taking
into account the number of parameters in the list and their type.
class Student{
int id;
String name;
int age;
Student(int i,String n){
id = i;
name = n;
}
Student(int i,String n,int a){
id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan",25);
s1.display();
s2.display();
}
}
Output:111 Karan 0
222 Aryan 25
Method
object.
behaviour of an object.
in any case.
name.
By constructor
By assigning the values of one object into another
By clone() method of Object class
In this example, we are going to copy the values of one object into another using constructor.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
class Student{
int id;
String name;
Student(int i,String n){
id = i;
name = n;
}
Student(Student s){
id = s.id;
name =s.name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(s1);
s1.display();
s2.display();
}
21.
}
Output:111 Karan
111 Karan
The static keyword is used in java mainly for memory management. We may apply static keyword
with variables, methods, blocks and nested class. The static keyword belongs to the class than
instance of the class.
The static can be:
1.
2.
3.
4.
1) static variable
If you declare any variable as static, it is known static variable.
The static variable can be used to refer the common property of all objects (that is not
unique for each object) e.g. company name of employees,college name of students etc.
The static variable gets memory only once in class area at the time of class loading.
class Student{
int rollno;
String name;
String college="ITS";
}
Suppose there are 500 students in my college, now all instance data members will get memory each
time when object is created.All student have its unique rollno and name so instance data member is
good.Here, college refers to the common property of all objects.If we make it static,this field will get
memory only once.
class Counter{
int count=0;//will get memory when instance is created
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
}}
Output:1
1
1
changes the value of the static variable, it will retain its value.
class Counter{
static int count=0;//will get memory only once and retain its value
Counter(){
count++;
System.out.println(count);
}
public static void main(String args[]){
Counter c1=new Counter();
Counter c2=new Counter();
Counter c3=new Counter();
15.
}}
Output:1
2
3
2) static method
If you apply static keyword with any method, it is known as static method
s1.display();
s2.display();
s3.display();
}
7.
8.
9.
10.
11.
12.
1.
2.
3.
4.
5.
6.
7.
There are two main restrictions for the static method. They are:
1. The static method can not use non static data member or call non-static method directly.
2. this and super cannot be used in static context.
class A{
int a=40;//non static
public static void main(String args[]){
System.out.println(a);
}
}
Output:Compile Time Error
3)static block
class A{
static{System.out.println("static block is invoked");}
Ans)Yes, one of the way is static block but in previous version of JDK not in JDK 1.7.
class A{
static{
System.out.println("static block is invoked");
System.exit(0);
}
}
Output:static block is invoked (if not JDK7)
this keyword
There can be a lot of usage of this keyword. In java, this is a reference variable that refers to
the current object.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
Let's understand the problem if we don't use this keyword by the example given below:
class student{
int id;
String name;
student(int id,String name){
id = id;
name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
student s1 = new student(111,"Karan");
student s2 = new student(321,"Aryan");
s1.display();
s2.display();
}
}
Output:0 null
0 null
In the above example, parameter (formal arguments) and instance variables are same that is
why we are using this keyword to distinguish between local variable and instance variable.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
class Student{
int id;
String name;
}
}
Output111 Karan
222 Aryan
If local variables(formal arguments) and instance variables are different, there is no need to use
this keyword like in the following program:
class Student{
int id;
String name;
}
}
Output:111 Karan
222 Aryan
20.
21.
22.
e2.display();
}
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
id = id;
name = name;
this ();//must be the first statement
}
void display(){System.out.println(id+" "+name);}
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
class S{
void m(){
System.out.println("method is invoked");
}
void n(){
this.m();//no need because compiler does it for you.
}
void p(){
n();//complier will add this to invoke n() method as this.n()
}
11.
12.
13.
14.
15.
Output:method is invoked
Output:method is invoked
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
return_type method_name(){
return this;
}
are printing the reference variable and this, output of both variables are same.
class A{
void m(){
System.out.println(this);//prints same reference ID
}
public static void main(String args[]){
A obj=new A();
System.out.println(obj);//prints the reference ID
obj.m();
}
}
Output:A@13d9c02
A@13d9c02
Inheritance in Java
Inheritance is a mechanism in which one object acquires all the properties and behaviours of
parent object.
The idea behind inheritance is that you can create new classes that are built upon existing classes.
When you inherit from an existing class, you reuse (or inherit) methods and fields, and you add new
methods and fields to adapt your new class to new situations.
Inheritance represents the IS-A relationship.
1.
2.
3.
4.
Syntax of Inheritance
The keyword extends indicates that you are making a new class that derives from an existing
class. In the terminology of Java, a class that is inherited is called a superclass. The new class is
called a subclass.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a
type of Employee.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
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);
}
}
Output: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
On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical.
Multiple and Hybrid is supported through interface only. We will learn about interfaces later.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
To reduce the complexity and simplify the language, multiple inheritance is not supported in
java. For example:
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?
}
}
If subclass (child class) has the same method as declared in the parent class, it is known as method
overriding.
In other words, If subclass provides the specific implementation of the method that has been
provided by one of its parent class, it is known as Method Overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why
we use method overriding.
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
class Bike extends Vehicle{
void run(){System.out.println("Bike is running safely");}
public static void main(String args[]){
8.
9.
10.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
Method Overriding
program.
super class.
within a class.
relationship.
super keyword
The super is a reference variable that is used to refer immediate parent class object.
Whenever you create the instance of subclass, an instance of parent class is created implicitly i.e.
referred by super reference variable.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
class Vehicle{
int speed=50;
}
class Bike extends Vehicle{
int speed=100;
void display(){
System.out.println(speed);//will print speed of Bike
}
public static void main(String args[]){
Bike b=new Bike();
b.display();
}
}
Output:100
In the above example Vehicle and Bike both class have a common property speed. Instance
variable of current class is refered by instance bydefault, but I have to refer parent class instance
variable that is why we use super keyword to distinguish between parent class instance variable
and current class instance variable.
Solution by super keyword
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
Bike(){
super();//will invoke parent class constructor
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike b=new Bike();
12.
13.
14.
}
}
Output:Vehicle is created
Bike is created
As we know well that default constructor is provided by compiler automatically but it also adds
super() for the first statement.If you are creating your own constructor and you don't have either
this() or super() as the first statement, compiler will provide super() as the first statement of the
constructor.
Another example of super keyword where super() is provided by the compiler implicitly.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
class Vehicle{
Vehicle(){System.out.println("Vehicle is created");}
}
class Bike extends Vehicle{
int speed;
Bike(int speed){
this.speed=speed;
System.out.println(speed);
}
public static void main(String args[]){
Bike b=new Bike(10);
}
}
Output:Vehicle is created
10
class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void message(){System.out.println("welcome to java");}
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
void display(){
message();//will invoke current class message() method
super.message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}
Output:welcome to java
welcome
In the above example Student and Person both classes have message() method if we call
message() method from Student class, it will call the message() method of Student class not of
Person class because priority is given to local.
In case there is no method in subclass as parent, there is no need to use super. In the example
given below message() method is invoked from Student class but Student class does not have
message() method, so you can directly call message() method.
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
class Person{
void message(){System.out.println("welcome");}
}
class Student extends Person{
void display(){
message();//will invoke parent class message() method
}
public static void main(String args[]){
Student s=new Student();
s.display();
}
}
Output: welcome
The final keyword can be applied with the variables, a final variable that have no value it is called
blank final variable or uninitialized final variable. It can be initialized in the constructor only. The
blank final variable can be static also which will be initialized in the static block only. We will have
detailed learning of these. Let's first learn the basics of final keyword.
1) final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
class Bike{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike obj=new Bike();
obj.run();
}
}//end of class
Output:Compile Time Error
2) final method
If you make any method as final, you cannot override it.
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error
3) final class
If you make any class as final, you cannot extend it.
class Bike{
final void run(){System.out.println("running...");}
}
class Honda extends Bike{
public static void main(String args[]){
new Honda().run();
}
}
Output:running...
class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
class Bike{
final int speedlimit;//blank final variable
4.
5.
6.
7.
8.
9.
10.
11.
12.
Bike(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike();
}
}
Output:70
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
class Bike{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike b=new Bike();
b.cube(5);
}
}
Output:Compile Time Error
Upcasting
When reference variable of Parent class refers to the object of Child class, it is known as upcasting.
For example:
1.
2.
1.
class A{}
class B extends A{}
A a=new B();//upcasting
class Bike{
void run(){System.out.println("running");}
}
class Splender extends Bike{
void run(){System.out.println("running safely with 60km");}
class Bank{
int getRateOfInterest(){return 0;}
}
class SBI extends Bank{
int getRateOfInterest(){return 8;}
}
class ICICI extends Bank{
int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
class Test{
public static void main(String args[]){
Bank b1=new SBI();
Bank b2=new ICICI();
Bank b3=new AXIS();
System.out.println("SBI Rate of Interest: "+b1.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+b2.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+b3.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
class Bike{
int speedlimit=90;
}
class Honda extends Bike{
int speedlimit=150;
public static void main(String args[]){
Bike obj=new Honda();
System.out.println(obj.speedlimit);//90
}
Output:90
class Animal{
void eat(){System.out.println("eating");}
}
class Dog extends Animal{
void eat(){System.out.println("eating fruits");}
}
class BabyDog extends Dog{
void eat(){System.out.println("drinking milk");}
public static void main(String args[]){
Animal a1,a2,a3;
a1=new Animal();
a2=new Dog();
a3=new BabyDog();
a1.eat();
a2.eat();
a3.eat();
}
}
Output: eating
eating fruits
drinking Milk
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
class Animal{
void eat(){System.out.println("animal is eating...");}
}
class Dog extends Animal{
void eat(){System.out.println("dog is eating...");}
}
class BabyDog extends Dog{
public static void main(String args[]){
Animal a=new BabyDog();
a.eat();
}}