Professional Documents
Culture Documents
A class is a group of objects which have common properties. It is a template or blueprint from which
objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
fields
methods
constructors
blocks
nested class and interface
Syntax to declare a class:
class <class_name>{
field;
method;
}
Instance variable in Java
A variable which is created inside the class but outside the method, is known as instance variable. Instance
variable doesn't get memory at compile time. It gets memory at run time when object(instance) is created.
That is why, it is known as instance variable.
1. By reference variable
2. By method
3. By constructor
1
Object and Class Example-initialization through reference variables:outside main class
In real time development, we create classes and use it from another class. It is a better approach than
previous one. Let's see a simple example, where we are having main() method in another class.
We can have multiple classes in different java files or single java file. If you define multiple classes in a
single java source file, it is a good idea to save the file name with the class name which has main() method.
package basics;
class Student{
int id;
String name;
}
}
}
o/p
101
Ram
The new keyword is used to allocate memory at run time. All objects get memory in Heap memory area.
Output:
111 Karan
222 Aryan
class Student{
int id;
String name;
// constructor
Student(int i, String n)
{
id=i;
name=n;
}
public void Display()
{
System.out.println("Empno "+id);
System.out.println("Ename "+name);
}
}
public class MainOutClass {
public static void main(String args[]){
Student s1=new Student(101,"Ram");
s1.Display();
}
}
o/p
Empno 101
Ename Ram
Within an instance method or a constructor, this is a reference to the current object — the object whose
method or constructor is being called. You can refer to any member of the current object from within an
instance method or a constructor by using this.
Using this with a Field
3
The most common reason for using the this keyword is because a field is shadowed by a method or
constructor parameter.
For example, the Point class was written like this
public class Point {
public int x = 0;
public int y = 0;
//constructor
public Point(int a, int b) {
x = a;
y = b;
}
}
but it could have been written like this:
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
}
Memory Management
Java Memory Management, with its built-in garbage collection, is one of the language’s finest
achievements. It allows developers to create new objects without worrying explicitly about memory
allocation and deallocation, because the garbage collector automatically reclaims memory for reuse. This
enables faster development with less boilerplate code, while eliminating memory leaks and other memory-
related problems. At least in theory.
Ironically, Java garbage collection seems to work too well, creating and removing too many objects. Most
memory-management issues are solved, but often at the cost of creating serious performance problems.
Making garbage collection adaptable to all kinds of situations has led to a complex and hard-to-optimize
system. In order to wrap your head around garbage collection, you need first to understand how memory
management works in a Java Virtual Machine (JVM).
How Garbage Collection Really Works
Many people think garbage collection collects and discards dead objects. In reality, Java garbage collection
is doing the opposite! Live objects are tracked and everything else designated garbage. As you’ll see, this
fundamental misunderstanding can lead to many performance problems.
Let’s start with the heap, which is the area of memory used for dynamic allocation. In most configurations
the operating system allocates the heap in advance to be managed by the JVM while the program is
running. This has a couple of important ramifications:
Object creation is faster because global synchronization with the operating system is not needed for
every single object. An allocation simply claims some portion of a memory array and moves the
offset pointer forward (see Figure 2.1). The next allocation starts at this offset and claims the next
portion of the array.
When an object is no longer used, the garbage collector reclaims the underlying memory and reuses
it for future object allocation. This means there is no explicit deletion and no memory is given back
to the operating system.
Figure 2.1: New objects are simply allocated at the end of the used heap.
All objects are allocated on the heap area managed by the JVM. Every item that the developer uses is
treated this way, including class objects, static variables, and even the code itself. As long as an object is
being referenced, the JVM considers it alive. Once an object is no longer referenced and therefore is not
reachable by the application code, the garbage collector removes it and reclaims the unused memory. As
simple as this sounds, it raises a question: what is the first reference in the tree?
Garbage-Collection Roots—The Source of All Object Trees
6
Every object tree must have one or more root objects. As long as the application can reach those roots, the
whole tree is reachable. But when are those root objects considered reachable? Special objects called
garbage-collection roots (GC roots; see Figure 2.2) are always reachable and so is any object that has a
garbage-collection root at its own root.
There are four kinds of GC roots in Java:
Local variables are kept alive by the stack of a thread. This is not a real object virtual reference and
thus is not visible. For all intents and purposes, local variables are GC roots.
Active Java threads are always considered live objects and are therefore GC roots. This is
especially important for thread local variables.
Static variables are referenced by their classes. This fact makes them de facto GC roots. Classes
themselves can be garbage-collected, which would remove all referenced static variables. This is of
special importance when we use application servers, OSGi containers or class loaders in general.
We will discuss the related problems in the Problem Patterns section.
JNI References are Java objects that the native code has created as part of a JNI call. Objects thus
created are treated specially because the JVM does not know if it is being referenced by the native
code or not. Such objects represent a very special form of GC root, which we will examine in more
detail in the Problem Patterns section below.
Java Garbage Collection
In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words,
it is a way to destroy the unused objects.
To do so, we were using free() function in C language and delete() in C++. But, in java it is performed
automatically. So, java provides better memory management.
Advantage of Garbage Collection
It makes java memory efficient because garbage collector removes the unreferenced objects from
heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra
efforts.
How can an object be unreferenced?
There are many ways:
By nulling the reference
By assigning a reference to another
By annonymous object etc.
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By annonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can
be used to perform cleanup processing. This method is defined in Object class as:
1. protected void finalize(){}
Note: The Garbage collector of JVM collects only those objects that are created by new keyword.
So if you have created any object without new, you can use finalize method to perform cleanup
processing (destroying remaining objects).
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is
found in System and Runtime classes.
1. public static void gc(){}
7
Note: Garbage collection is performed by a daemon thread called Garbage Collector(GC). This
thread calls the finalize() method before object is garbage collected.
example program
package basics;
public class GarbageCollection {
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String args[]){
GarbageCollection s1=new GarbageCollection();
GarbageCollection s2=new GarbageCollection();
s1=null;
s2=null;
System.gc(); //performs garbage collection
System.out.println("hello");
}
}
o/p
hello
object is garbage collected
object is garbage collected
Inheritance in Java
Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent
object.
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 parent class, and you can add
new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.
Why use inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Syntax of Java Inheritance
1. class Subclass-name extends Superclass-name
2. {
3. //methods and fields
4. }
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 parent or super class and the new class is
called child or subclass
8
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.
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.
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
When a class extends multiple classes i.e. known as multiple inheritance. For Example:
9
Single Inheritance Example
File: TestInheritance.java
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...
Super keyword
1) super is used to refer immediate parent class instance variable.
We can use super keyword to access the data member or field of parent class. It is used if parent class and
child class have same fields.
class Animal{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color);//prints color of Dog class
System.out.println(super.color);//prints color of Animal class
}
}
class TestSuper1{
public static void main(String args[]){
Dog d=new Dog();
d.printColor();
}
}
Output:
black
white
This second form of super is most applicable to situations in which member names of
a subclass hide members by the same name in the superclass. Consider this simple class
hierarchy:
class Animal{
void eat()
{
System.out.println("eating...");}
}
class Dog extends Animal{
void eat()
{
System.out.println("eating bread...");
}
void bark()
{
System.out.println("barking...");
}
void work()
{
super.eat();
bark();
}
}
class TestSuper2{
public static void main(String args[]){
Dog d=new Dog();
d.work();
12
}
}
Output:
eating...
barking...
class Dog extends Animal
{
Dog()
{
super();
System.out.println("dog is created");
}
}
class TestSuper3{
public static void main(String args[])
{
Dog d=new Dog();
}
}
o/p
animal is created
dog is created
class TestSuper5{
public static void main(String[] args){
Emp e1=new Emp(1,"ankit",45000f);
e1.display();
}
}
Output:
1 ankit 45000
since super( ) must be the first statement executed in a subclass’ constructor, this order is the same whether
or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each super
class will be executed. The following program illustrates when constructors are executed:
// Demonstrate when constructors are called.
// Create a super class.
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
// Create a subclass by extending class A.
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
// Create another subclass by extending B.
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
The output from this program is shown here:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
package basics;
class Overload {
14
double volume(float l, float w, float h) {
return l * w * h;
}
double volume(float l) {
return l * l * l;
}
o/p
Method Overriding
In a class hierarchy, when a method in a subclass has the same name and type signature as
a method in its superclass, then the method in the subclass is said to override the method in
the superclass. When an overridden method is called from within a subclass, it will always
refer to the version of that method defined by the subclass. The version of the method defined
by the superclass will be hidden. Consider the following:
// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
15
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B
is used. That is, the version of show( ) inside B overrides the version declared in A.
If you wish to access the superclass version of an overridden method, you can do so by
using super. For example, in this version of B, the superclass version of show( ) is invoked
within the subclass’ version.
This allows all instance variables to be displayed.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
output:
i and j: 1 2
k: 3
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
16
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
The version of show( ) in B takes a string parameter. This makes its type signature
different from the one in A, which takes no parameters. Therefore, no overriding (or name
hiding) takes place. Instead, the version of show( ) in B simply overloads the version of
show( ) in A.
DivideByZero exception
NullPointerException
ArithmeticException
ArrayIndexOutOfBoundsException
Types of exceptions
There are two types of exceptions
1)Checked exceptions
2)Unchecked exceptions
Checked exceptions
All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during
compilation to see whether the programmer has handled them or not. If these exceptions are not handled/declared in
the program, it will give compilation error.
Unchecked Exceptions
Runtime Exceptions are also known as Unchecked Exceptions as the compiler do not check whether the programmer
has handled them or not but it’s the duty of the programmer to handle these exceptions and provide a safe exit.
These exceptions need not be included in any method’s throws list because compiler does not check to see if a
method handles or throws these exceptions.
18
NullPointerException
NegativeArraySizeException etc.
Exception hierarchy
a = input.nextInt();
b = input.nextInt();
// try block
try {
result = a / b;
System.out.println("Result = " + result);
}
// catch block
catch (ArithmeticException e) {
System.out.println("Divide by zero Exception caught: Don't divide by zero. "+e);
}
}
}
19
o/p
Input two integers
3
0
Divide by zero Exception caught: Don't divide by zero. java.lang.ArithmeticException: / by zero
Java Package
Package are used in Java, in-order to avoid name conflicts and to control access of class, interface and enumeration etc. A
package can be defined as a group of similar types of classes, interface, enumeration and sub-package. Using package it becomes
easier to locate the related classes.
Creating a package
Creating a package in java is quite easy. Simply include a package command followed by name of the package as the first
statement in java source file.
package mypack;
public class employee
{
...statement;
}
class test
{
public static void main(String[] args)
{
Book bk = new Book("java","Herbert");
bk.show();
}
}
To run this program :
create a directory under your current working development directory(i.e. JDK directory), name it as mypack.
compile the source file
Put the class file into the directory you have created.
Execute the program from development directory.
NOTE : Development directory is the directory where your JDK is install.
20
Package is a way to organize files in java, it is used when a project consists of multiple modules. It also helps resolve naming
conflicts. Package's access level also allows you to protect data from being used by the non-authorized classes.
import keyword
import keyword is used to import built-in and user-defined packages into your java source file. So that your class can refer to a
class that is in another package by directly using its name.
There are 3 different ways to refer to class that is present in different package
1. Using fully qualified name (But this is not a good practice.)
Example :
class MyDate extends java.util.Date
{
//statement;
}
2. import the only class you want to use.
Example :
import java.util.Date;
class MyDate extends Date
{
//statement.
}
3. import all the classes from the particular package
Example :
import java.util.*;
class MyDate extends Date
{
//statement;
}
Static import
static import is a feature that expands the capabilities of import keyword. It is used to import static member of a class. We all
know that static member are referred in association with its class name outside the class. Using static import, it is possible to
refer to the static member directly without its class name. There are two general form of static import statement.
The first form of static import statement, import only a single static member of a class
Syntax
import static package.class-name.static-member-name;
Example
import static java.lang.Math.sqrt; //importing static method sqrt of Math class
The second form of static import statement,imports all the static member of a class
Syntax
import static package.class-type-name.*;
Example
import static java.lang.Math.*; //importing all static member of Math class
22
private
protected
provides a variety of ways to produce many levels of access required by these categories. The upcoming table sums up the
interaction
While the access control mechanism of Java may seem complicated, we can simplify it as follows.
Anything declared as public can be accessed from anywhere.
Anything declared as private can't be seen outside of its class.
subclasses as well as to the other classes in the same package. This is the default access. And If you want to allow an element to
be seen outside your current package, but only to the classes that subclass your class directly, then declare that element
protected.
Private Protected Public No Modifier
Same class Yes Yes Yes Yes
Same package subclass No Yes Yes Yes
Same package non-subclass No Yes Yes Yes
Different package subclass No Yes Yes No
Different package non-subclass No No Yes No
This table applies only to the members of classes. A non-nested class has only two possible access levels i.e., default and
public.
When a class is declared as public, then it is accessible by any other code. If a class has default access, then it can only be
accessed by the other code within its same package. When a class is public, it must be only the public class declared in the file
that must have the same name as the class.
Java Access Protection Example
Here the upcoming example allows all the combinations of access control modifiers. This example has two packages and five
classes.
Always remember that the classes for the two different packages need to be stored in directories after their respective packages
(in this case pkg1 and pkg2).
The source for the first package defines the three classes i.e., Protection, Derived, and SamePackage. The first class defines the
four variables of type int in each of the legal protection modes. The variable n declared with the default protection, the variables
n_priv, n_prot, and n_publ is private, protected, and public respectively.
Each subsequent class in the following example will try to access the variables in an instance of this class. The lines that will not
compile due to the access restrictions are commented out. Before each of these lines is a comment that listing the places from
which this level of protection would allow access.
The second class named Derived, is a subclass of Protection in the same package, pkg1. This grants Derived access to every
variable in the class Protection except for n_priv, the private one. The third class named SamePackage, is not a subclass of the
class Protection, but is in the same package and also has access to all but not n_priv.
This is Protection.java file:
package pkg1;
public Protection()
{
System.out.println("base constructor");
System.out.println("n = " + n);
System.out.println("n_priv = " + n_priv);
System.out.println("n_prot = " + n_prot);
System.out.println("n_publ = " + n_publ);
}
}
This is Derived.java file:
package pkg1;
/* class only
* System.out.println("n_priv = "4 + n_priv); */
class SamePackage
{
SamePackage()
{
Protection pro = new Protection();
System.out.println("same package constructor");
System.out.println("n = " + pro.n);
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
/* class only
* System.out.println("n_priv = " + n_priv); */
class OtherPackage
{
OtherPackage()
{
pkg1.Protection pro = new pkg1.Protection();
24
/* class or package only
* System.out.println("n = " + pro.n); */
/* class only
* System.out.println("n_priv = " + pro.n_priv); */
package pkg1;
package pkg2;
Interface
Interface looks like class but it is not a class. An interface can have methods and variables just like the class but the methods
declared in interface are by default abstract (only method signature, no body). Also, the variables declared in an interface are
public, static & final by default.
interface Area
{
float compute(float x, float y);
}
area = tri;
System.out.println("Area Of Triangle = "+ area.compute(10,2));
}
}
/* * OUTPUT **
26