chavan CH-2
chavan CH-2
1
Contents
2
Introduction
Java is a true OO language and therefore the underlying
structure of all Java programs is classes.
Anything we wish to represent in Java must be encapsulated
in a class that defines the “state” and “behaviour” of the basic
program components known as objects.
Classes create objects and objects use methods to
communicate between them. They provide a convenient
method for packaging a group of logically related data items
and functions that work on them.
A class essentially serves as a template for an object and
behaves like a basic data type “int”. It is therefore important
to understand how the fields and methods are defined in a
class and how they are used to build a Java program that
incorporates the basic OO concepts such as encapsulation,
inheritance, and polymorphism.
3
Classes
Circle
centre
radius
circumference()
area()
4
Classes
Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
6
Adding Methods
A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
Methods are declared inside the body of the
class but immediately after the declaration of
data fields.
The general form of a method declaration is:
7
Adding Methods to Class Circle
public class Circle {
}
}
8
Class of Circle cont.
aCircle bCircle
null null
10
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
P Q P Q
11
Automatic garbage collection
The object Q
does not have a
reference and cannot be used in future.
13
Declaring Objects
Box mybox = new Box();
OR
14
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
15
Constructors
A constructor initializes an object immediately upon creation.
It has the same name as the class in which it resides and is
syntactically similar to a method.
Once defined, the constructor is automatically called
immediately after the object is created, before the new
operator completes.
Constructors look a little strange because they have no return
type, not even void.
It is the constructor’s job to initialize the internal state of an
object so that the code creating an instance will have a fully
initialized, usable object immediately.
16
Rules for creating Java constructor
17
18
19
20
Java Parameterized Constructor
A constructor which has a specific
number of parameters is called a
parameterized constructor.
Why use the parameterized
constructor?
The parameterized constructor is used to
provide different values to distinct objects.
However, you can provide the same values
also.
21
Example of Parameterized constructor
22
Java Copy Constructor
There is no copy constructor in Java. However, we can
copy the values from one object to another like copy
constructor in C++.
There are many ways to copy the values of one object
into another in Java.
They are:
By constructor
By assigning the values of one object into another
By clone() method of Object class
23
Constructor Overloading in Java
In Java, a constructor is just like a method but
without return type. It can also be overloaded
like Java methods.
Constructor overloading in Java is a technique
of having more than one constructor with
different parameter lists.
They are arranged in a way that each
constructor performs a different task. They are
differentiated by the compiler by the number of
parameters in the list and their types.
25
Example of Constructor Overloading
Call by Value
There is only call by value in java, not call by reference.
If we call a method passing a value, it is known as call
by value.
The changes being done in the called method, is not
affected in the calling method.
28
call by reference
In case of call by reference original value is changed if we made
changes in the called method.
If we pass object in place of any primitive value, original value will
be changed. In this example we are passing object as a value.
The this Keyword
this can be used to refer current class instance variable.
this can be used to invoke current class method
(implicitly)
this() can be used to invoke current class constructor.
this can be passed as an argument in the method call.
this can be passed as argument in the constructor call.
this can be used to return the current class instance
from the method.
30
31
32
33
The finalize( ) Method
Sometimes an object will need to perform some
action when it is destroyed.
For example, if an object is holding some non-Java
resource such as a file handle or window character
font, then you might want to make sure these
resources are freed before an object is destroyed.
To handle such situations, Java provides a
mechanism
The finalize( ) method has this general form:
protected void finalize( )
{
// finalization code here
}
34
Java Object finalize() Method
35
36
Garbage Collection
objects are dynamically allocated by using the new operator, you might be
wondering how such objects are destroyed and their memory released for later
reallocation.
In some languages, such as C++, dynamically allocated objects must be manually released
by use of a delete operator.
It handles deallocation for you automatically. The technique that accomplishes this is
called garbage collection.
It works like this: when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be reclaimed. There is no
explicit need to destroy objects as in C++.
Garbage collection only occurs during the execution of your program. It will not occur
simply because one or more objects exist that are no longer used.
66
StringBuffer
StringBuffer is mutable means one can change the value of the
object .
The object created through StringBuffer is stored in the heap .
StringBuffer has the same methods as the StringBuilder , but each
method in StringBuffer is synchronized that is StringBuffer is
thread safe .
67
Constructors of StringBuffer class
68
69
StringBuffer append() method
Hello Java
HJavaello
HJavalo
olleH
74
StringBuilder
StringBuilder is same as the StringBuffer , that is it stores the
object in heap and it can also be modified .
The main difference between the StringBuffer and StringBuilder is
that StringBuilder is also not thread safe.
StringBuilder is fast as it is not thread safe
demo2=new StringBuilder("Bye");
// Above statement is right as it modifies the value which is allowed in the
StringBuilder
75
StringBuilder append() method
Hello Java
HJavaello
HJavalo
Hlo
olleH
80
Access Modifiers in Java
81
The access modifiers in Java specifies the accessibility or scope of
a field, method, constructor, or class.
We can change the access level of fields, constructors, methods,
and class by applying the access modifier on it.
There are four types of Java access modifiers:
Private: The access level of a private modifier is only within
can be accessed from within the class, outside the class, within
the package and outside the package.
82
83
Non-access modifiers
84
Vector
Java Vector class comes under the java.util package.
The vector class implements a growable array of
objects. Like an array, it contains the component that
can be accessed using an integer index.
Vector is very useful if we don't know the size of an
array in advance or we need one that can change the
size over the lifetime of a program.
Vector implements a dynamic array that means it can
grow or shrink as required. It is similar to the ArrayList,
but with two differences-
Vector is synchronized.
The vector contains many legacy methods that are not
the part of a collections framework
85
The data structures provided by the Java utility
package are very powerful and perform a wide range of
functions.
These data structures consist of the following interface
and classes −
Enumeration
BitSet
Vector
Stack
Dictionary
Hashtable
Properties
86
The Enumeration
The Enumeration interface isn't itself a data structure,
but it is very important within the context of other data
structures.
The Enumeration interface defines a means to retrieve
successive elements from a data structure.
For example, Enumeration defines a method called
nextElement that is used to get the next element in a
data structure that contains multiple elements.
87
The BitSet
88
The Vector
The Vector class is similar to a traditional Java
array, except that it can grow as necessary to
accommodate new elements.
Like an array, elements of a Vector object can
be accessed via an index into the vector.
The nice thing about using the Vector class is
that you don't have to worry about setting it to
a specific size upon creation; it shrinks and
grows automatically when necessary.
89
The Hashtable
90
91
The Methods Defined by Vector
92
93
94
95
Vector Array
Vector is similar to array hold multiple Array is homogeneous collection of
objects and the objects can be data types.
retrieved using index value
Size of the vector can be changed Array is fixed size.
Vector automatically grows when they Array never grows when they run out
Run out of allocated space. of allocated space it attempt to do so,
result in overflow.
Vector provides extra method for No methods are provide for adding
adding removing and removing elements in case of
array
Vector is synchronized. Array is not synchronized
96
Wrappers:
Java’s Wrapper Classes for the
Primitives Types
Primitives & Wrappers
Wrapper class in java provides the
mechanism to convert primitive into object
and object into primitive.
autoboxing and unboxing feature
converts primitive into object and object
into primitive automatically.
The automatic conversion of primitive into
object is known and autoboxing and vice-
versa unboxing.
Change the value in Method: Java supports only call by
value. So, if we pass a primitive value, it will not change the
original value. But, if we convert the primitive value in an
object, it will change the original value.
Serialization: We need to convert the objects into streams
to perform the serialization. If we have a primitive value, we
can convert it in objects through the wrapper classes.
Synchronization: Java synchronization works with objects
in Multithreading.
java.util package: The java.util package provides the
utility classes to deal with objects.
Collection Framework: Java collection framework works
with objects only. All classes of the collection framework
(ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects
only. 99
Java has a wrapper class for each of the
eight primitive data types:
Primitive Wrapper Primitive Wrapper
Type Class Type Class
boolean Boolean float Float
byte Byte int Integer
char Character long Long
double Double short Short
100
101
102
103
104
105
106
Java Enums
The Enum in Java is a data type which contains a fixed set
of constants.
It can be used for days of the week (SUNDAY, MONDAY,
TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, and
SATURDAY) , directions (NORTH, SOUTH, EAST, and
WEST), season (SPRING, SUMMER, WINTER, and
AUTUMN or FALL), colors (RED, YELLOW, BLUE,
GREEN, WHITE, and BLACK) etc. According to the Java
naming conventions, we should have all constants in capital
letters. So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed
set of constants (a variable that does not change).
The Java enum constants are static and final implicitly. It is
available since JDK 1.5.
107
Enums are used to create our own data type like classes. The
enum data type (also known as Enumerated Data Type) is
used to define an enum in Java. Unlike C/C++, enum in Java
is more powerful. Here, we can define an enum either inside
the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot
inherit any other class, but it can implement many interfaces.
We can have fields, constructors, methods, and main
methods in Java enum.
108
109
110
111
112
113
114
115
116
HashMap
Java HashMap class implements the Map interface which allows us to
store key and value pair, where keys should be unique.
If you try to insert the duplicate key, it will replace the element of the
corresponding key.
It is easy to perform operations using the key index like updation,
deletion, etc. HashMap class is found in the java.util package.
HashMap in Java is like the legacy Hashtable class, but it is not
synchronized.
It allows us to store the null elements as well, but there should be only
one null key.
Since Java 5, it is denoted as HashMap<K,V>, where K stands for key and
V for value.
It inherits the AbstractMap class and implements the Map interface.
118
Java HashMap contains values based on
the key.
Java HashMap contains only unique keys.
Java HashMap may have one null key and
multiple null values.
Java HashMap is non synchronized.
Java HashMap maintains no order.
120
121
122
124
Java Annotation
Java Annotation is a tag that represents the metadata
i.e. attached with class, interface, methods or fields to
indicate some additional information which can be used
by java compiler and JVM.
Annotations in Java are used to provide additional
information, so it is an alternative option for XML and
Java marker interfaces.
125
Built-In Java Annotations
There are several built-in annotations in Java. Some
annotations are applied to Java code and some to other
annotations.
Built-In Java Annotations used in Java code
@Override
@SuppressWarnings
@Deprecated
Built-In Java Annotations used in other
annotations
@Target
@Retention
@Inherited
@Documented
126