Академический Документы
Профессиональный Документы
Культура Документы
in
data_type instance_variablen;
data_type method_name(parameter_list)
.
{
//code
ac
}
tu
}
.v
When multiple objects are created, each object has its own copy of members i.e. data of one
object is different from data of other objects.
w
in
• Different types of constructors are
• Zero parameterized constructors
.
•
•
Parameterized constructors
Copy Constructors
ac
Zero parameterized constructors
tu
It does not receive any arguments at the time of calling constructor.
Example
.v
zeroConstructor()
{
System.out.println("Zero Parameter Constructuor Called");
w
a = 10;
System.out.println("Data member a is initialized to " +a);
w
}
public static void main(String[] args) {
zeroConstructor z = new zeroConstructor();
}
}
Output:
Parameterized constructors
In these method constructors receives one or more parameters.
public class parameterConstructor {
int a;
parameterConstructor(int x)
{
System.out.println("Parameterized Constructuor Called");
a = x;
System.out.println("Data member a is initialized to " +a);
}
public static void main(String[] args) {
parameterConstructor z = new parameterConstructor(20);
}
}
Output:
this pointer
in
this is a reference to object of the class.
this can be used to refer current class instance variable.
.
ac
this can be used to invoke current class method .
public class parameterConstructor {
int a, b;
tu
parameterConstructor(int a, int b)
{
System.out.println("Parameterized Constructor Called");
.v
this.a = a;
this.b = b;
w
}
public static void main(String[] args) {
parameterConstructor z = new parameterConstructor(30, 40);
w
}
}
Output:
Parameterized Constructor Called
Data member a is initialized to 30
Data member a is initialized to 40
Instance Variable Hiding
If there is a local variable in method with same name as instance variable, then
the local variable hides the instance variable.
public class instanceVariable {
int a = 10;
void display()
{
int a = 20;
System.out.println("Value of Instance Variable is "
+this.a);
System.out.println("Value of Local Variable is " +a);
}
public static void main(String[] args) {
instanceVariable i = new instanceVariable();
i.display();
}
}
Output:
Value of Instance Variable is 10
Value of Local Variable is 20
Garbage Collection
in
When an object is dereferenced, the memory allocated to the object will be
reclaimed automatically. This mechanism is called garbage collection.
.
ac
Garbage collector removes the unreferenced objects automatically from the heap
memory.
Garbage collector is a part of JVM.
tu
How Garbage collector works
1. STUDENT s = new STUDENT( ); Memory allocated to object s.
.v
s = null; Object is dereferenced, Now garbage collector frees the memory allocated
to members of object automatically.
w
Finalize Method
If an object is required to perform some task before it is deleted, the task should
be written in final method.
The final method is executed just before collecting the garbage.
Specify the actions to be performed by object before destroying in final method.
The general form of final method is
protected void finalize( )
{
//Actions to be performed
}
Example:
public class finalGarbage {
int a = 10;
protected void finalize()
{
System.out.println("From Final Method");
}
public static void main(String[] args) {
finalGarbage fG = new finalGarbage();
finalGarbage fG1 = new finalGarbage();
fG = fG1;
System.out.println("Program Terminated");
System.gc();
}
in
}
Output:
.
Program Terminated
From Final Method
ac
Inheritance
tu
It is a mechanism that allows one class to inherit property of another class.
The class that is inherited is called super class (Parent class).
.v
The class that inherits the properties of other class is called sub class (Child class).
The keyword “extends” is used to inherit the properties.
w
of parent class.
The access specifiers determine whether a field or method in a class, can be used or invoked
w
in
System.out.println("Name:" +name);
System.out.println("Mileage:" +mileage);
.
System.out.println("Price:" + price);
}
}
ac
public class singleInheritance {
public static void main(String[] args) {
tu
CAR c1 = new CAR();
c1.display();
.v
}
}
Output:
w
Car Details
Name: Swift
w
Mileage: 20.5
Price: 805000.0
w
BIKE
String Make
String Make
void display( )
Example:
class Vehicle
{
int vehicle_speed = 100;
}
public class Bike extends Vehicle {
int bike_speed = 200;
public static void main(String[] args)
{
Bike b = new Bike();
System.out.println("Speed of a vehicle is " + b.vehicle_speed);
System.out.println("Speed of a vehicle is " + b.bike_speed);
in
}
}
.
Output: Speed of a vehicle is 100
Speed of a vehicle is 200
ac
In the above example, Bike object can access the field of own class as well as of Vehicle class i.e.
code re usability.
tu
Multi-Level Inheritance
Here, sub class created by inheriting super class and new class is created by
inheriting sub class.
.v
A
w
w
B
w
Example 1:
class A
{
A()
{
System.out.println("Class A constructor");
}
}
class B extends A
{
B()
{
System.out.println("Class B constructor");
}
}
}
Output:
Class A constructor
Class B constructor
Class C constructor
in
In the above example,
◦ First class A's constructors are called
.
◦ Secondly class B's constructors are called
ac
◦ Lastly class C's constructors are called
Example 2:
class Animal{
tu
void eat()
{
.v
System.out.println("eating...");
}
}
w
{
System.out.println("barking...");
w
}
}
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:
Hybrid Inheritance
Here two or more sub classes are inherited from one super class.
class Animal{
void eat()
{
System.out.println("eating...");
}
in
}
class Dog extends Animal{
void bark()
.
{ ac
System.out.println("barking...");
}
}
tu
class Cat extends Animal{
void meow()
.v
{
System.out.println("meowing...");
}
w
}
class TestInheritance3{
w
c.meow();
c.eat();
}
}
Output:
Interface
An interface in java is a blueprint of a class. It has static constants and abstract methods only. The
interface in java is a mechanism to achieve fully abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve fully abstraction and multiple
inheritances in Java.
Simple example of Java interface
In this example, Printable interface have only one method, its implementation is provided in the
class.
interface printable
{
void print();
}
class Example_Interface implements printable
{
public void print()
in
{
System.out.println("Hello");
.
}
public static void main(String args[])
{
ac
Example_Interface obj = new Example_Interface();
tu
obj.print();
}
}
.v
Multiple Inheritance
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
w
multiple inheritance.
Example of simple interface
w
interface Printable
{
w
void print();
}
interface Showable
{
void show();
}
class Multiple_Inheritance implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
in
Method in super class and sub class has same name and parameters.
The implementation details of method in sub class are different from its parent
.
class. ac
When method is called from sub class object, then sub class method is executed.
Example
tu
class VEHICLE1
{
double mileage;
.v
double price;
VEHICLE1()
w
{
mileage = 20.5;
w
price = 20500;
}
void display()
w
{
System.out.println("Name:" +price);
System.out.println("Mileage:" +mileage);
}
}
class CAR1 extends VEHICLE1
{
String name = "Swift";
void display()
{
System.out.println("Car Details");
System.out.println("Price:" + name);
}
}
public class singleInheritance {
public static void main(String[] args) {
CAR1 c1 = new CAR1();
c1.display();
}
}
Output:
Car Details
Price: Swift
Super Class
A super class is a class that has been extended by another class. It allows the extending class
in
to inherit its state and behaviors.
It is also called as base class or parent class.
.
The super keyword in java is a reference variable that is used to refer immediate parent
ac
class object.
Whenever you create the instance of subclass, an instance of parent class is created
implicitly i.e. referred by super reference variable.
tu
Usage of java super Keyword
.v
class Vehicle
w
{
int speed = 100;
}
public class Bike extends Vehicle {
int speed = 200;
void display()
{
System.out.println("Speed of a vehicle is " +speed);
//refers to local variable
System.out.println("Speed of a vehicle is "
+super.speed); // refers to super class variable
}
public static void main(String[] args) {
Bike b = new Bike();
b.display();
}
}
Output:
Speed of a vehicle is 200
Speed of a vehicle is 100
class College{
College()
{
System.out.println("Presently I Am in Parent Class
Constructor");
}
in
}
public class SuperParentConstructor extends College{
.
SuperParentConstructor()
{
super();
ac
System.out.println("Presently I Am in Extended Class
Constructor");
tu
}
public static void main(String[] args) {
.v
}
w
}
Output:
w
w
Example 1:
abstract class Bank
{
abstract void ROI();
void Info()
{
System.out.println("All Banks Must Adhere to the Rules and
Regulations of RBI");
}
in
}
class SBI extends Bank
{
.
void ROI( ) ac
{
System.out.println("Rate of Interest at SBI is 8.5%");
}
}
tu
class CANARA extends Bank
{
.v
void ROI( )
{
System.out.println("Rate of Interest at SBI is 8.8%");
w
}
}
w
in
{
System.out.println("drawing circle");
.
} ac
}
class Testabstraction1
{
tu
public static void main(String args[])
{
Rectangle s = new Rectangle();
.v
s.draw();
}
w
}
Output: drawing rectangle
w
Final
w
}
public class finalExample {
public static void main(String[] args){
in
cat c = new cat();
c.display();
.
}
}
Output:
ac
Error
Final can be used to prevent Inheritance
tu
o The class being inherited can be avoided by using final.
.v
o When a class is defined as final, such classes cannot be inherited by any sub
class.
w
Example:
final class animal
w
{
final void display()
w
{
System.out.println("I am in animal class");
}
}
class cat extends animal
{
void display(){
System.out.println("I am in animal class");
}
}
public class finalExample {
public static void main(String[] args){
cat c = new cat();
c.display();
}
}
Output:
Cannot inherit from final class
Object class
o By default, object class is a top most class of all objects in java.
o The objects of Object class can reference to any objects of sub class.
o The methods of this class are
Method Purpose
Object clone( ) Creates new object that is same as object being cloned
boolean equals(Object obj) Determines whether one object is equal to other
in
void finalize( ) Invoked before garbage collector frees the memory
.
Class getClass( ) Obtains the class of an object at run time
int hashCode( )
ac
Returns the hashcode associated with the invoking object
Classes
tu
It is also called as nested classes.
Here, one class is declared inside another class.
.v
Inner classes are used to logically group classes so that program is easy to read and
maintain.
Syntax of inner class
w
class Java_Outer_Class
w
{
//code
w
class Java_Inner_Class
{
//Code
}
}
Advantages of inner classes
There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.
Access Modifiers
Access Modifiers Default private protected Public
Accessible within the subclass inside the same package Yes No Yes Yes
Method Overriding
in
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in java.
.
Usage of Java Method Overriding
ac
Method overriding is used to provide specific implementation of a method that is already
provided by its super class.
Method overriding is used for runtime polymorphism
tu
Rules for Java Method Overriding
1. method must have same name as in the parent class
.v
class Vehicle
{
w
void run()
{
w
System.out.println("Vehicle is running");
}
}
class Bike extends Vehicle
{
void run()
{
System.out.println("Bike is running");
}
public static void main(String args[])
{
Bike obj = new Bike();
obj.run();
}
}
Output: Bike is running
Overloading
If a class has multiple methods by same name but different parameters, it is known as
Method Overloading.
Method overloading increases the readability of the program.
in
In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.
Example:
.
class Calculation
{
ac
void sum(int a, int b)
tu
{
System.out.println(a+b);
}
.v
{
System.out.println(a+b+c);
}
w
{
Calculation obj=new Calculation();
obj.sum(10,10,10);
obj.sum(20,20);
}
}
Output:
2. Method Overloading by changing data type of arguments
In this example, we have created two overloaded methods that differs in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.
class Calculation
{
void sum(int a, int b)
{
System.out.println(a+b);
}
void sum(double a,double b)
{
System.out.println(a+b+c);
}
public static void main(String args[])
{
in
Calculation obj=new Calculation();
obj.sum(10,20);
.
obj.sum(5.5, 6.5); ac
}
}
tu
Method Overloading Method Overriding
.v
Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that is
already provided by its super class.
w
Method overloading is performed within class. Method overriding occurs in two classes that
w
In case of method overloading, parameter must In case of method overriding, parameter must be
w
be different. same.
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.
In java, method overloading can't be performed Return type must be same in method overriding.
by changing return type of the method only.
Return type can be same or different in method
overloading. But you must have to change the
parameter.
Exception Handling
The exception handling in java is one of the powerful mechanisms to handle the runtime errors so
that normal flow of the application can be maintained.
What is exception?
Dictionary Meaning: Exception is an abnormal condition.
In java, exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
What is exception handling
Exception Handling is a mechanism to handle runtime errors such as ClassNotFound, IO, SQL,
Remote etc.
Advantage of Exception Handling
The core advantage of exception handling is to maintain the normal flow of the application.
Exception normally disrupts the normal flow of the application that is why we use exception
handling. Let's take a scenario:
in
statement1;
statement2;
.
statement3;
statement4;
ac
statement5;
tu
statement6; //exception occurs
statement7;
.v
statement8;
statement9;
w
statement10;
Suppose there are 10 statements in a program and there occurs an exception at statement 6, rest of
w
the code will not be executed i.e. statement 7 to 10 will not run. If we perform exception handling,
rest of the code will be executed. That is why we use exception handling in java.
1) Checked Exception (Compile Time Exception)
w
The classes that extend Throwable class except RuntimeException and Error are known as
checked exceptions.
These exceptions are checked at compile time.
Example: IOException, SQLException etc. Checked exceptions are checked at compile-
time.
2) Unchecked Exception (Run Time Exceptions)
The classes that extend RuntimeException are known as unchecked exceptions.
These exceptions are not checked at compile time.
Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException
etc. Unchecked exceptions are not checked at compile-time rather they are checked at
runtime.
3) Error
Error is irrecoverable e.g. OutOfMemoryError, VirtualMachineError, AssertionError etc.
These are not exceptions at all, but problems that arise beyond the control of the user or the
programmer. Errors are typically ignored in your code because you can rarely do anything
about an error. For example, if a stack overflow occurs, an error will arise. They are also
ignored at the time of compilation.
Common scenarios where exceptions may occur
There are given some scenarios where unchecked exceptions can occur. They are as follows:
Scenario 1: where ArithmeticException occurs
If we divide any number by zero, there occurs an ArithmeticException.
1. int a=50/0; //ArithmeticException
in
If we have null value in any variable, performing any operation by the variable occur a
NullPointerException.
1. String s=null;
.
ac
2. System.out.println(s.length()); // NullPointerException
1. String s="abc";
2. int i=Integer.parseInt(s); //NumberFormatException
w
If you are inserting any value in the wrong index, it would result
ArrayIndexOutOfBoundsException as shown below:
w
in
{
int data=50/0; //may throw exception
.
}
ac
System.out.println("After Exception");
}
tu
Output: Exception in thread main java.lang.ArithmeticException:/ by zero
As displayed in the above example, “After Exception” is not executed
.v
try
{
w
int data=50/0;
}
catch(ArithmeticException e)
{
System.out.println(e);
}
System.out.println("rest of the code...");
}
}
The JVM firstly checks whether the exception is handled or not. If exception is not handled, JVM
provides a default exception handler that performs the following tasks:
Prints out exception description.
Prints the stack trace (Hierarchy of methods where the exception occurred).
Causes the program to terminate.
But if exception is handled by the application programmer, normal flow of the application is
maintained i.e. rest of the code is executed.
Multiple catch block
If you have to perform different tasks at the occurrence of different Exceptions, use java multi catch
block.
Example:
public class TestMultipleCatchBlock
{
public static void main(String args[])
{
try
{
in
int a[ ]=new int[5];
a[5]=30/0;
.
} ac
catch(ArithmeticException e)
{
System.out.println("task1 is completed");
tu
}
catch(ArrayIndexOutOfBoundsException e)
{
.v
System.out.println("task 2 completed");
}
w
}
w
in
public static void main(String args[])
{
try
.
{ ac
try
{
System.out.println("going to divide");
tu
int b =39/0;
}
.v
catch(ArithmeticException e)
{
System.out.println(e);
w
}
try
w
{
int a[]=new int[5];
w
a[5]=4;
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println(e);
}
System.out.println("other statement);
}
catch(Exception e){System.out.println("handled");}
System.out.println("normal flow..");
}
}
Finally Block
It is a block that is used to execute important code such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or not.
Java finally block must be followed by try or catch block.
For each try block there can be zero or more catch blocks, but only one finally block.
The finally block will not be executed if program exits (either by calling System.exit() or by
causing a fatal error that causes the process to abort).
Example 1: In the below example, divide by zero is not handled.
class TestFinallyBlock1
{
public static void main(String args[])
{
try
in
{
int data=25/0;
.
}
System.out.println(data); ac
catch(NullPointerException e)
tu
{
System.out.println(e);
.v
}
finally
w
{
System.out.println("finally block is always executed");
w
}
System.out.println("rest of the code...");
w
}
}
Output:
finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at TestFinallyBlock1.main(TestFinallyBlock1.java:7)
Example 2: In the below example, Arithmetic exception is handled.
public class TestFinallyBlock2
{
public static void main(String args[])
{
try
{
int data=25/0;
System.out.println(data);
}
catch(ArithmeticException e)
{
System.out.println(e);
}
finally
in
{
System.out.println("finally block is always executed");
.
} ac
System.out.println("rest of the code...");
}
}
tu
Output:
java.lang.ArithmeticException: / by zero
.v
throw keyword
w
throw exception;
In the below example, we have created the validate method that takes age as a parameter. If the age
is less than 35, we are throwing the ArithmeticException otherwise print a message You are
eligible.
public class TestThrow1
{
static void validate(int age)
{
if(age<18)
throw new ArithmeticException("Not Eligible to vote");
else
System.out.println("Eligible to vote");
}
public static void main(String args[])
{
validate(13);
System.out.println("rest of the code...");
}
}
Output: Exception in thread "main" java.lang.ArithmeticException: You Are Failed
throws
The Java throws keyword is used to declare an exception.
The calling function must handle an exception thrown by called function.
Using throws, we can declare
unchecked Exception: under your control so correct your code.
in
error: beyond your control e.g. you are unable to do anything if there occurs
VirtualMachineError or StackOverflowError.
Example:
.
class Test1
{
ac
static void check() throws ArithmeticException
tu
{
System.out.println("Inside check function");
int a = 25 / 0;
.v
}
w
in
Exception from main() caught ArithmeticException java.lang.ArithmeticException: / by zero
Inside len function
.
ac
Exception from main() caught NullPointerException java.lang.NullPointerException
Rest of the code
Difference between throw and throws in Java
tu
Sl. No. Throw Throws
.v
Java throw keyword is used to explicitly Java throws keyword is used to declare an
1
throw an exception. exception.
w
4 Throw is used within the method. Throws is used with the method signature.
void m()
void m() throws ArithmeticException
{
{
6 throw new ArithmeticException("sorry");
//method code
}
}
Finally
The finally block always executes when the try block exits.
This ensures that the finally block is executed even if an unexpected exception occurs.
If exception is handled or not, finally block can be used.
Example:
class FinallyExample
{
public static void main(String[] args)
{
try
{
int x = 300/0;
}
catch(ArithmeticException e)
in
{
System.out.println("Caught " +e);
.
} ac
finally
{
System.out.println("finally block is executed");
tu
}
}
}
.v
Output:
Caught java.lang.ArithmeticException: / by zero
w
Abstract class can have abstract and non-abstract Interface can have only abstract methods.
methods.
Abstract class can have final, non-final, static Interface has only static and final variables.
and non-static variables.
Abstract class can have static methods, main Interface can't have static methods, main method
method and constructor. or constructor.
Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
The abstract keyword is used to declare abstract The interface keyword is used to declare
class. interface.
Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Packages
A java package is a group of similar types of classes, interfaces and sub-packages.
Package in java can be categorized in two form, built-in package and user-defined package.
There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
Advantage of Java Package
in
Java package is used to categorize the classes and interfaces so that they can be easily
maintained.
.
Java package provides access protection. ac
Java package removes naming collision.
tu
.v
w
w
w
/* First.java */
package first;
in
public class Message{
public void msg(){
.
ac
System.out.println("In Package “first”");
}
}
tu
/* Second.java */
package second;
.v
import first.*;
public class Display{
w
m.msg();
}
w
}
Output:
In Package “first”
2. import package.classname;
In this case, particular class of package is imported.
Only imported class has accessibility in the new program.
/* First.java */
package first;
public class Airtel{
public void Airtel(){
System.out.println("Airtel Function");}
}
in
public class Display{
public static void main(String [] args){
.
Airtel a = new Airtel();
}
}
ac
Output:
tu
Airtel Function
3. Fully qualified name.
.v
When fully qualified name is used then, importing package is not required.
A class can be used by writing “packagename.class” in another program.
w
Example:
/* First.java */
w
package first;
public class Airtel{
public void Airtel(){
w
System.out.println("Airtel Function");}
}
/* Second.java */
package second;
. in
ac
tu
.v
w
w
w
4.
w
w
w
.v
tu
ac
. in