0% found this document useful (0 votes)
15 views

CH 2

The document discusses the Object class in Java and its universal role as the superclass of all classes. It describes several important methods in the Object class like hashCode(), equals(), clone(), and toString(). It also provides examples of using these methods.

Uploaded by

yashsayani1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

CH 2

The document discusses the Object class in Java and its universal role as the superclass of all classes. It describes several important methods in the Object class like hashCode(), equals(), clone(), and toString(). It also provides examples of using these methods.

Uploaded by

yashsayani1234
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 49

R.P.

Bhalodia BCA College

CH 2
Universal Class (Object Class)
 The Object Class is known as universal super class of Java.
 This is so because Every class you create in Java automatically inherits the
Object class.
 The Object class is super class of all the classes in Java either directly or
Indirectly. You don't need to extend it manually. All the properties of
Object class are already in your class.
 You can find the definition of the Object class in java.lang package And
there are a few useful methods in this class which you can override in your
class. Following program shows a few method with the examples.
Method Description
public final Class getClass() returns the Class class object of this object. The
Class class can further be used to get the metadata
of this class.
public int hashCode() returns the hashcode number for this object.
public boolean equals(Object compares the given object to this object.
obj)
protected Object clone() creates and returns the exact copy (clone) of this
throws object.
CloneNotSupportedExceptio
n
public String toString() returns the string representation of this object.

public final void notify() wakes up single thread, waiting on this object's
monitor.
public final void notifyAll() wakes up all the threads, waiting on this object's
monitor.
public final void wait(long causes the current thread to wait for the specified
timeout)throws milliseconds, until another thread notifies
InterruptedException (invokes notify() or notifyAll() method).

1
public final void wait(long causes the current thread to wait for the specified
timeout,int nanos)throws milliseconds and nanoseconds, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
public final void wait()throws causes the current thread to wait, until another
InterruptedException thread notifies (invokes notify() or notifyAll()
method).
protected void is invoked by the garbage collector before object
finalize()throws Throwable is being garbage collected.

class ObjectClass
{
public static void main(String[] args)
{
Object oc = new Object();
System.out.println("The Hash Code:-"+oc.hashCode());
System.out.println("To String"+oc.toString());
System.out.println("The GetClass Method"+oc.getClass());
Class cls1 = oc.wait(1000);
System.out.println(cls1);

Object oc1 = new Object();


System.out.println(oc.equals(oc1));
System.out.println(oc1.hashCode());
System.out.println(oc1.toString());
/*ObjectClass oc2 = new ObjectClass();
System.out.println(oc.equals(oc2));
System.out.println(oc2.hashCode());
System.out.println(oc2.toString());*/

Integer obj = new Integer(10);


Class cls = obj.getClass();
System.out.println("The Obj Direct Use getClass() :-
"+obj.getClass());
System.out.println("The CLS Object is :-"+cls);
System.out.println(obj.toString());
System.out.println(obj.hashCode());
}
}

2
Access Specifies (Public, Private, Protected, Default)

Access specifies are the important concept in Object-oriented language. These


specify are control the visibility of variable and method. So that, here some
protection of variable and method.
Java provides a number of access modifiers to set access levels for classes,
variables, methods, and constructors. The four access levels are −
 Visible to the package, the default. No modifiers are needed.
 Visible to the class only (private).
 Visible to the world (public).
 Visible to the package and all subclasses (protected).

Default Access Modifier – No Keyword Needed:-


 These modifiers cannot need any keyword to use in variable, method and
constructors.
 A variable and method use this access modifier is available to any class in
the same package.
 The fields in an interface are implicitly public static final and the
methods in an interface are by default public.
class Default
{
int a, b;
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}
class DefaultMain
{
public static void main(String[] args)
{
Default df = new Default();

df.a = 10;
df.b = 20;
df.display();
}
}
Private Access Modifiers – Private
 If we want to access the variable method and constructors with in the class
it is declared as private.
 Private modifier is the most restrictive access level.
 Class and interface cannot be declared as private.
3
 Private variable and method use outside the class by use of public getter
method.
 It is use for the data hides from the outside world.
class PrivateKey
{
private int a, b;

PrivateKey(int x, int y)
{
a = x;
b = y;
}
PrivateKey(){}

double area()
{
return a * b;
}
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}
class PrivateMain
{
public static void main(String[] args)
{
PrivateKey pk = new PrivateKey();
PrivateKey pk2 = new PrivateKey(10,15);
pk.display();
pk2.display();
System.out.println("The Value of A outside the class is :-"
+pk2.a);
System.out.println("The Value of B outside the class is :-"
+pk2.b);
}
}
Public Access Modifier – Public
 This access modifier is the universal access modifier in java.
 Its use any class and same package in java. But we want to access in
different package need to be imported.
 The security level is very low when declare as public.

4
class PublicKey
{
public int a, b;

PublicKey(int x, int y)
{
a = x;
b = y;
}
PublicKey(){}

double area()
{
return a * b;
}
void display()
{
System.out.println("The Value of A:-" +a);
System.out.println("The Value of B:-" +b);
}
}
class PublicMain
{
public static void main(String[] args)
{
PublicKey publick = new PublicKey();
PublicKey publick2 = new PublicKey(10,15);
publick.display();
publick2.display();
System.out.println("The Value of A outside the class is :-"
+publick2.a);
System.out.println("The Value of B outside the class is :-"
+publick2.b);
}
}

Protected Access Modifier - Protected


 Variables, methods, and constructors, which are declared protected in a
superclass can be accessed only by the subclasses in other package or any
class within the package of the protected members' class.
 The protected access modifier cannot be applied to class and interfaces.
Methods, fields can be declared protected, however methods and fields in a
interface cannot be declared protected.

5
 Protected access gives the subclass a chance to use the helper method or
variable, while preventing a nonrelated class from trying to use it.

Doing Inheritance
 Inheritance supports the concept of hierarchical classification. With the use
of inheritance, one can create a general class that defines a set of related
item which means that each are class is adding those things that are
unique to it.
 A class that is inherited is called a SUPERCLASS. The class that does the
inheriting is called a SUBCLASS. A subclass inherits all instance
variables and methods from its superclass and also has its own variable
and methods. One can inherit the class using the EXTEND keyword.
 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:-
Class subclass-name extends superclass-name
{
Body of class.
}
 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.

Types of inheritance in java


 On the basis of class, there can be three types of inheritance in java: single,
multilevel and hierarchical.

6
Example of Single level Inheritance:-
//Simple Example of Inheritance
//Create a superclass
class A
{
int x,y;
void showxy()
{
System.out.println("x:->"+x);
System.out.println("y:->"+y);
}
}
class B extends A
{
int z;
void showz()
{
System.out.println("c:->"+z);
}
void sum()
{
System.out.print("sum:->"+(x+y+z));
}
}
class single
{
public static void main(String args[])
{
A a=new A();
B b=new B();
a.x=10;
7
a.y=20;
a.showxy();

b.x=5;
b.y=6;
b.z=7;
b.showxy();
b.showz();
b.sum();
}
}

2) Multilevel Inheritance:
When a class extends a class, which extends another class then this is
called Multilevel Inheritance.
For example Class C extends class B and class B extends class A then this
type of Inheritance is Known as Multilevel Inheritance.

Class Car
{
Public Car()
{
System.out.println(“Class Car”);
}
Public void vehicleType()
{
System.out.println(“Class Car”);
}
}
Class Maruti extends Car
{
Public Maruti()
{
System.out.println(“Class Maruti”);
}
Public void brand()
{
System.out.println(“Brand: Maruti”);
}
Public void speed()
{
System.out.println(“Max: 90Kmph”);
}
8
}
Public class Maruti800 extends Maruti
{
Public Maruti800()
{
System.out.println(“Maruti Model: 800”);
}
Public void speed()
{
System.out.println(“Max:80Kmph”);
}
Public static void main(String arg[])
{
Maruti800 Obj = new Maruti800();
Obj.vehicleType();
Obj.brand();
Obj.speed();
}
}
Output:-

3) Hierarchical Inheritance:-
When More than one classes inherit a same class then this is called
hierarchical inheritance.
Class A
{
Public void methodA()
{
System.out.println(“Method of class A..”);
}
}
Class B extends A
{
Public void methodB()
{
System.out.println(“Method of class B”);
}
}
Class C extends A
{
Public void methodC()
{
System.out.println(“Method of class C”);
9
}
}
Class Demo
{
Public static void main(String arg[])
{
B Obj1 = new B();
C Obj2 = new C();
Obj1.methodA();
Obj2.methodB();

}
}

 Super Keyword:-

 The super keyword in java is a reference variable which is used to


refer immediate parent class object.
 Whenever you create the instance of subclass, an instance of parent class is
created implicitly which is referred by super reference variable.

Usage of java super Keyword


 super can be used to refer immediate parent class instance variable.
 super can be used to invoke immediate parent class method.
 super() can be used to invoke immediate parent class constructor.

“super” can be used for two purposes:-


1) Access the hidden data variables of the super class:-

class A
{
int a;
float b;
void show()
{
System.out.println("A in Super class");
}
}
class B extends A
{
int a;
float b;
B(int p,float z)
{
10
a=p;
super.b=z;
}
void show()
{
super.show();
System.out.println("B in super class:"+super.b);
System.out.println("A in Sub class:"+a);
}
public static void main(String arg[])
{
B obj = new B(10,15);
obj.show();
}
}

Output:-

2) Use of super to call super class Constructor or Method


OR (Constructor inheritance)

class A
{
int a,b,c;
A(int p,int q,int r)
{
a=p;
b=q;
c=r;
}
}
class B extends A
{
int d;
B(int m,int n,int s,int t)
{
super(m,n,s);
d=t;
}
void show()
{
11
System.out.println("A=="+a);
System.out.println("B=="+b);
System.out.println("C=="+c);
System.out.println("D=="+d);
}
public static void main(String arg[])
{
B b = new B(10,20,30,40);
b.show();
}
}

Method Overriding
 We know that method defined in a base class will be inherited by the
derived class and cam be used by the objects created by the derived class.
 But there may be the occasion when we have the method in a base class
and the same name method in derived class.
 Now the object of the derived class will always call the method defined in
the derived class. This is known as overriding of the method.
 Remember that here the method of the base class will never be called and
the object will always call from the derived class.

class abc
{
int x;
abc(int x)
{
this.x = x;
}
void display()
{
System.out.println("Out Put from Base Class x:-" +x);
}
}

class xyz extends abc


{
int y;
xyz(int x, int y)
{
super(x);//call the base class constructor
this.y = y;
}
void display()
12
{
System.out.println("Output from Deriveed Class x:-" + x + " The
Value of Y:- " +y);
}
}

class override_test
{
public static void main(String[] args)
{
xyz p1 = new xyz(100,200);
p1.display();
}
}

Difference between Method Overloading VS Method Overriding


Method Overloading Method Overriding
Method overloading is used to Method overriding is used to provide
increase the readability of the the specific implementation of the
program. method that is already provided by its
super class.
Method overloading is Method overriding occurs in two
performed within class. classes that have IS-A (inheritance)
relationship.
In case of method In case of method
overloading, parameter must be overriding, parameter must be same.
different.
Method overloading is the example Method overriding is the example
of compile time polymorphism. of run time polymorphism.
In java, method overloading can't be Return type must be same or covariant
performed by changing return type of in method overriding.
the method only. Return type can be
same or different in method
overloading. But you must have to
change the parameter.

Dynamic Method Dispatch :-


If a superclass contains a method that is overridden by a subclass ,then
when different types of objects are referred through a superclass reference
variable, different versions of the method are executed. It is called Dynamic
Method Dispatch.

13
class A
{
void callme()
{
System.out.println("Inside A's Call Me Method");
}
}
class B extends A
{
void callme()
{
System.out.println("Inside B's Call Me Method");
}
}
class C extends A
{
void callme()
{
System.out.println("Inside C's Call Me Method");
}
}

class Dispatch
{
public static void main(String args[])
{
A a1 =new A();
B b1 = new B();
C c1 = new C();
A r; //obtain reference of type A
r = a1; //r regers to an A object
r.callme();

r = b1; //r regers to an A object


r.callme();

r = c1; //r regers to an A object


r.callme();
}
}

14
Abstract and Final Keyword
Final keyword:-
The final keyword in java is used to restrict the user. The java final keyword
can be used in many contexts. Final can be:
1. variable
2. method
3. class
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) Java final variable
 If you make any variable as final, you cannot change the value of final
variable (It will be constant).
 Example of final variable
 There is a final variable speedlimit, we are going to change the value of
this variable, but It can't be changed because final variable once assigned a
value can never be changed.
class FinalVariable
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
FinalVariable obj=new FinalVariable();
obj.run();
}
}
2) Java final method
If you make any method as final, you cannot override it.
class FinalMethod
{
final void run()
{
System.out.println("running");
}
}
class FinalMethodMain extends FinalMethod
{
15
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
FinalMethodMain fmm= new FinalMethodMain();
fmm.run();
}
}

3) Java final class


If you make any class as final, you cannot extend it.
final class FinalClass
{
}
class FinalClassMain extends FinalClass
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
FinalClassMain fcm= new FinalClassMain();
fcm.run();
}
}

4) Is final method inherited?


Yes, final method is inherited but you cannot override it.
class FinalMethodInherit
{
final void run()
{
System.out.println("running...");
}
}
class FinalMethodInheritance extends FinalMethodInherit
{
public static void main(String args[])
{
new FinalMethodInheritance().run();
}
16
}
5) What is blank or uninitialized final variable?
 A final variable that is not initialized at the time of declaration is known as
blank final variable.
 If you want to create a variable that is initialized at the time of creating
object and once initialized may not be changed, it is useful. For example
PAN CARD number of an employee.
 It can be initialized only in constructor.
class FinalBlankVarialbeConstructor
{
final int speedlimit;//blank final variable

FinalBlankVarialbeConstructor
{
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[])


{
FinalBlankVarialbeConstructor fbvc = new
FinalBlankVarialbeConstructor();
}
}
6) static blank final variable
 A static final variable that is not initialized at the time of declaration is
known as static blank final variable. It can be initialized only in static
block.

7) What is final parameter?


 If you declare any parameter as final, you cannot change the value of it.

8) Can we declare a constructor final?


 No, because constructor is never inherited.

17
Abstract Class:-

A class which contains the abstract keyword in its declaration is known as


abstract class.
 Abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )
 But, if a class has at least one abstract method, then the class must be
declared abstract.
 If a class is declared abstract, it cannot be instantiated.
 To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
 If you inherit an abstract class, you have to provide implementations to all
the abstract methods in it.
With Simple Example
abstract class Salary
{
int basic ,da;
Salary(int b,int d)
{
basic=b;
da=basic*d/100;
}
//Abstract Method does not have body
abstract void computeSalary();
}
class GrossSalary extends Salary
{
int hra;
GrossSalary(int b,int d,int h)
{
super(b,d);
hra=basic*h/100;
}
void computeSalary()
{
System.out.println("Gross Salary From
subclass:="+(basic+da+hra));

}
}

18
class Basic
{
public static void main(String args[])
{
//Salary e=new Salary(5000,10);
GrossSalary e1=new GrossSalary(5000,10,20);
//Salary e;
e = e1;
e.computeSalary();

}
}
Output:-

Interface:-
 We know that java does not support multiple inheritance means that we are
not allow to write like
class a extends b, c
 Even though the developer of JAVA knows that there is much importance
of multiple inheritance of JAVA.
 So they have given a new approach called INERFACE.

How to define Interface:-


 An Interface is basically a class which contains variables any method but
there is major difference.
 The difference is the INTERFACE DEFINES ONLY ABSTRACT
METHOD AND FINAL FIELDS.
 It means that the any codes for any method defines in the interface are
always constant variable.
 You can define interface in following way:-
interface item
{
static final int code = 101;
void display()
{
……
……
}
}

How to extends Interface:-


19
 Special note for Interface:-
INTERFACE TO INTERFACE = EXTENDS
CLASS TO INTERFACE = IMPLIMENTS
 Like classes we can extends interfaces also that new interface will behave
like sub class.
 We can do this when we declare all the constants in one interface and all
methods to other interface.
 For example:-
interface itemconstants
{
static final int code = 101;
static final string name = “computer”;
}
interface item extends itemconstants
{
void display()
}
 Java has given us the concept of multiple inheritances in interface means
that we can extends more than one interface in single interface.
Simple Interface
interface Drawable
{
void draw();
}

//Implementation: by second user


class Rectangle implements Drawable
{
public void draw()
{
System.out.println("drawing rectangle");
}
}
class Circle implements Drawable
{
public void draw()
{
System.out.println("drawing circle");
}
}
//Using interface: by third user
class InterfaceDemo
{
public static void main(String args[])
20
{
Drawable d=new Circle();//In real scenario, object is provided by method
e.g. getDrawable()
d.draw();
Drawable d1=new Rectangle();
d1.draw();
}
}
Simple Interface with Inheritance
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class MultipleInheritnace implements Printable,Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
MultipleInheritnace obj = new MultipleInheritnace();
obj.print();
obj.show();
}
}

Simple Interface with interface


interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
21
}
class InterfaceToInterface implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}

public static void main(String args[])


{
InterfaceToInterface obj = new InterfaceToInterface();
obj.print();
obj.show();
}
}

 Inner Class:-
Java Inner class or nested class is a class which is declared inside the class
or interface.
Advantages:-
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.
Example:-
class Outer
{
private int data=30;

class Inner
{
void display()
{
System.out.println("Data Is:-"+data);
}
}

22
public static void main(String arg[])
{
Outer obj = new Outer();
Outer.Inner in = obj.new Inner();
in.display();
}
}

Output:-

23
JAVA Packages
 Normal import & static import
 Normally in java coding, if we want to use the any static member
variables or a method of a class in our code,
 we have to first import that class using normal import keyword,
after that we have to use variables/methods with class name in
the code (Math.E)).
 We can see in below example.

import java.lang.*;
class xyz
{
public static void main(String args[])
{
System.out.println("without using static import functionality" + Math.E);
}
}

 In the above program, we have used System and Math classes are
used from java.lang package.

 In java program, we don't need to import any java.lang package as


default package imported is java.lang package for every program.

 The basic difference between normal import and static import is


normal import can call the member variables with class name in
the package.

 static import can be defined and static member fields can not
refere any class name and use directly without classname.

we can see example for static import

import static java.lang.System.*;


import static java.lang.Math.*;
class xyz
{ public static void main(String args[])
{
out.println("without using static import functionality" + E);
}
}

24
 out is static field in java.lang.System class and E is static member
variable for java.lang.Math class.

 For using static member variable E in Math class in java.lang Package,


we have coded by adding static import something like import static
java.lang.Math.*; or java.lang.Math.E.

 It will always good idea to define for each static member(Math.E)


instead of all static members(Math.*) in static import declaration

Advantages of Static import feature:-

To call the static members without using class name in our code. By
making static import code statements makes all the static members of
that class are available to declared java class
Static import can be used for static member variables as well as static
members without referring class name in java code.

 It simplifies the code readability for the constants.

Disadvantages of Static import feature:-

if we are importing the two same static constants from different classes
in the same class.
 There is possibility of ambiguity for the compiler to throw error.

 Introduction to java API packages & implment classes.


java.lang This is the language package. It contains String,
StringBuffer, System, Math,Thread etc classes
java.util This is utility package. It contains the utility classes
such as Vector, Random, HashTable, Date, Calender
etc.
java.io Provides for system input and output through data
streams, serialization and the file system.
java.net Provides the classes for implementing networking
applications.
java.awt This is an Abstract Window Toolkit package.
It contains the classes to implement a GUI(Graphical
User Interface). Some of its classes are : font, graphics,
color, Button etc

25
java.awt.event Provides interfaces and classes for dealing with
different types of events fired by AWT components.
java.applet Provides the classes necessary to create an applet and
the classes an applet uses to communicate with its
applet context.
javax.swing Provides a set of "lightweight" (all-Java language)
components that, to the maximum degree possible,
work the same on all platforms.

 Java.lang Package
Math Class
Math
The java.lang.Math class contains methods for performing basic numeric
operations such as the elementary exponential, logarithm, square root, and
trigonometric functions. Math.methodName()
Method Math Class
Method Description
static double abs(double a) This method returns the absolute value
of a double value.
static double ceil(double a) This method returns the smallest
(closest to negative infinity) double
value that is greater than or equal to the
argument and is equal to a
mathematical integer.
static double log(double a) This method returns the natural
logarithm (base e) of a double value.
static double log10(double a) This method returns the base 10
logarithm of a double value.
static float max(float a, float b) This method returns the greater of two
float values.
static double random() This method returns a double value
with a positive sign, greater than or
equal to 0.0 and less than 1.0.
static double sqrt(double a) This method returns the correctly
rounded positive square root of a
double value.
26
import java.lang.Math;
class MathDemo
{
public static void main(String[] args)
{
// get some doubles to find their absolute values
double x = 4876.1874d;
double y = -0.0d;
// get and print their absolute values
System.out.println("Math.abs(" + x + ")=" + Math.abs(x));//static
method
System.out.println("Math.abs(" + y + ")=" + Math.abs(y));//static
method
System.out.println("Math.abs(-9999.555d)=" + Math.abs(-
9999.555d));//static method
System.out.println("************** Use of Ceil Method
***********************");
System.out.println("Math.ceil(" + x + ")=" + Math.ceil(x));
System.out.println("Math.ceil(" + y + ")=" + Math.ceil(y));
System.out.println("Math.ceil(-0.65)=" + Math.ceil(-0.65));
System.out.println("************** Use of Natural Log
***********************");
System.out.println("Math.log(" + x + ")=" + Math.log(x));
System.out.println("Math.log(" + y + ")=" + Math.log(y));
System.out.println("Math.log(1)=" +Math.log(1));
System.out.println("************** Use of Natural Log Base 10
***********************");
System.out.println("Math.log10(" + x + ")=" + Math.log10(x));
System.out.println("Math.log10(" + y + ")=" + Math.log10(y));
System.out.println("Math.log(1)=" +Math.log10(1));
System.out.println("************** Use of Max Method
***********************");
System.out.println("Math.max(" + x + "," + y + ")=" + Math.max(x,
y));
System.out.println("************** Use of Random Method
***********************");
System.out.println("The Random Number is :-" +Math.random());
System.out.println("************** Use of SQRT Method
***********************");
System.out.println("Math.sqrt(100)=" + Math.sqrt(100));
System.out.println("Math.sqrt(625)=" + Math.sqrt(625));
}
}
27
Wrapper Class
What is need to Wrapper Class in JAVA?
 Java is an object-oriented language and can view everything as an object.
 The primitive data types are not objects; they do not belong to any class;
they are defined in the language itself. Sometimes, it is required to convert
data types into objects in Java language.

What are Wrapper classes?


 As the name says, a wrapper class wraps (encloses) around a data type and
gives it an object appearance. Wherever, the data type is required as an
object, this object can be used.
 Wrapper classes include methods to unwrap the object and give back the
data type. It can be compared with a chocolate. The manufacturer wraps
the chocolate with some foil or paper to prevent from pollution. The user
takes the chocolate, removes and throws the wrapper and eats it.
 Since J2SE 5.0, autoboxing and unboxing feature converts primitive into
object and object into primitive automatically. The automatic conversion
of primitive into object is known as autoboxing and vice-versa unboxing.
 The eight classes of java.lang package are known as wrapper classes in
java. The list of eight wrapper classes are given below:
Primitive Type Wrapper class
Boolean Boolean
Char Character
Byte Byte
Short Short
Int Integer
Long Long
Float Float
Double Double

Method of Wrapper Class:-


Method Description
valueOf() Returns an Integer object holding
the value of the specified primitive.
toString() Returns a String object representing
the value of a specified int or Integer.
parseInt() This method is used to get the
primitive data type of a certain String.
String toBinaryString(long l) Returns a binary representation of l
String toHexString(long l) Returns a Hex representation of l
String toOctalString(long l) Returns a Octal representation of l
//Primitiv to Wrapper Class
//Primitiv to Wrapper Class
28
class PrimitivtoWrapper
{
public static void main(String args[])
{
System.out.println("********************* Method of valueOf()
**************************************");
Integer x =Integer.valueOf(9);
Double c = Double.valueOf(5);
Float a = Float.valueOf("80");
Integer b = Integer.valueOf("444",16);

System.out.println(x);
System.out.println(c);
System.out.println(a);
System.out.println(b);

System.out.println("********************* Method of toString()


**************************************");
System.out.println(x.toString());
System.out.println(Integer.toString(12));

System.out.println("********************* Method of parseInt()


**************************************");
x =Integer.parseInt("9");
c = Double.parseDouble("5");
b = Integer.parseInt("444",16);

System.out.println(x);
System.out.println(c);
System.out.println(b);
System.out.println("The Value of Boolean B-
"+Integer.toBinaryString(20));
System.out.println("The Value of Boolean B-
"+Integer.toHexString(20));
System.out.println("The Value of Boolean B-
"+Integer.toOctalString(20));
long i=10;
long srt = Long.parseLong(Long.toBinaryString(i));
System.out.println("The Value of Boolean B-"+srt);
}
}

29
String
 In c and c++ string was array of characters but in C and C++ we are not
able to perform some operation like sorting of names.
 The java.lang.String class provides a lot of methods to work on string.
 By the help of these methods, we can perform operations on string such as
trimming, concatenating, converting, comparing, replacing strings etc.
 Java String is a powerful concept because everything is treated as a string
if you submit any form in window based, web based or mobile application.
 For example:-
String str;
Str = new String(Your String);
 In above example syntax str is name of the object and we have to allocate
the memory using new keyword.
String s1;
s1 = new String(“Welcome to Java”);
 Here in the object s1 the String “Welcome to Java” will be stored now you
can use this object for various purposes.
String s2;
s2 = new String(“ “);
s2 =s1;
System.out.println(“s1”);
System.out.println(“s2”);
 In above example we have used our string object for output as well as for
copying the data from one object to another object.
 Now java String object behaves like a regular variable.

Method of String Class


Method Description
s2=s1.toLowerCase() Convert the string s1 into lower case
and then store in s2 object.
s2=s1.toUpperCase() Convert the string s1 into uppercase
and then store in s2 object.
s2=s1.replace(„x‟,‟y‟) Replace all the content of x from s1
with y and store in s2.
s2=s1.trim() Removes leading and trailing space
from s1 and store to s2.
s1.equals(s2) Return true if s1 equals to s2.
s1.equalsIgnoreCase(s2) Return true if s1 and s2 are equal
without matching the cases
s1.length() Return length of s1.
s1.charAt(n) Return nth character from s1.
s1.compareTo(s2) Return negative if s1 < s2. Return
positive if s1>s2. Return 0 if s1 =s2.
30
String concat(String str) Returns concat string.
s1.substing(n) Return substring from nth character.
s1.substring(n,m) Return substring from nth character to
mth character.
s1.indexOf(„x‟) Gives us first accurate position of x.
class A
{
public static void main(String args[])
{
char c1[]={'a','b','c','d','e'};
char c2[];
String s1=new String();
s1="nilesh";
String s2=new String();
s2="jayesh";
String s3=new String();
s3=" parmar";
System.out.println("charAt :->"+s1.charAt(2));
System.out.println("equal :->"+s1.equals(s2));
System.out.println("startwith :->"+s1.startsWith("n"));
System.out.println("endwith :->"+s1.endsWith("h"));
System.out.println("concate :->"+s1.concat(s3));
System.out.println("replace :->"+s1.replace('n','j'));
System.out.println("trim :->"+s3.trim());
System.out.println("tolowercase :->"+s1.toLowerCase());
System.out.println("toupercase :->"+s1.toUpperCase());
System.out.println("indexof :->"+s1.indexOf('l'));

}
}

31
String Buffer
 The java.lang.StringBuffer class is a thread-safe, mutable (changeable)
sequence of characters. Following are the important points about
StringBuffer −
o A string buffer is like a String, but can be modified.
o It contains some particular sequence of characters, but the length and
content of the sequence can be changed through certain method calls.
o They are safe for use by multiple threads.
 Important Constructors of StringBuffer class
Constructor Description

StringBuffer() creates an empty string buffer with the initial capacity


of 16.
StringBuffer(String str) creates a string buffer with the specified string.

StringBuffer(int creates an empty string buffer with the specified


capacity) capacity as length.

Difference between String and StringBuffer


String StringBuffer
String class is immutable. StringBuffer class is mutable.
String is slow and consumes more StringBuffer is fast and consumes less
memory when you concat too many memory when you cancat strings.
strings because every time it creates
new instance.
String class overrides the equals() StringBuffer class doesn't override the
method of Object class. So you can equals() method of Object class.
compare the contents of two strings by
equals() method.

Method of String Buffer:-


Method Description
public StringBuffer append(String s) Updates the value of the object that
invoked the method. The method takes
boolean, char, int, long, Strings, etc.
public StringBuffer reverse() The method reverses the value of the
StringBuffer object that invoked the
method.
public delete(int start, int end) Deletes the string starting from the
start index until the end index.
32
public insert(int offset, int i) This method inserts a string s at the
position mentioned by the offset.
replace(int start, int end, String str) This method replaces the characters in
a substring of this StringBuffer with
characters in the specified String.
import java.lang.*;

public class StringBufferDemo


{

public static void main(String[] args)


{
StringBuffer sb = new StringBuffer("Test");
sb.append(" String Buffer");

System.out.println("\n\nThe Use of Append Method:- "+sb);

sb.delete(3, 7);
System.out.println("\n\nThe Use of Delete Method:- "+sb);

sb.insert(3, "123");
System.out.println("\n\nThe Use of Insert Method:- " +sb);

sb.replace(3, 8, "ZARA");
System.out.println("\n\nThe Use of replace Mathod:- " +sb);

sb.reverse();
System.out.println("\n\nThe Use of Reverse Method:- "+sb);
}
}

java.util Package Classes


Random
 The random class allows you to generate random double, float, int and
long numbers.
 These random numbers are very useful when we are developing simulation
to the real world system because we are needed random number is input.
 The constructor of the random number are:-
o Random():-This creates a new random number generator.
o Random(long seed):-This creates a new random number generator
using a single long seed.

33
Method of Random number
Method Description
double nextDouble() Return a random double value
float nextFloat() Return a random float value
int nextInt() Return a random integer value
long nextLong() Retrun a random long number
import java.util.*;
class RandomNumber
{
public static void main(String args[])
{
Random ran = new Random();
System.out.println("The Random number is:-" +ran);//retunr package
name class

int a = ran.nextInt();
System.out.println("The Random Integer Value is:- " +a);

float b = ran.nextFloat();
System.out.println("The Random Float Value is:- " +b);

double c = ran.nextDouble();
System.out.println("The Random Double Value is:- " +c);

long d = ran.nextLong();
System.out.println("The Random Long Value is:- " +d);
}
}

Date
 Java library also provide Date ckass in java.util package.
 Date class encapsulate both date and time and represent the value using
milliseconds precision.
 Date class support the following constructor.
o Date():- this constructor initializes the object with the current date
and time.
o Date(long millisec):- this constructor accept one argument that
equals the number of milliseconds that have elapsed since midnight,
January 1, 1970.
 The epoch is midnight on January 1,1970 GMT(Greenwich Mean Time).

Method of Date class


34
Method Description
boolean after(Date d) Return true if the d is after the current
date
boolean before(Date d) Return true if the d is before the current
date.
boolean equals(Date d) If the d is current date then return true
else return false.
long getTime() Return the number of milliseconds
since epoch
void setTime(long msec) Set the date and time of current object
to represent milliseconds since epoch
String toString() Return the string equivalent of the date.
import java.util.Date;

class DateDemo
{
public static void main(String args[])
{
Date date = new Date();
java.util.Date date2 = new java.util.Date();
Date x = new Date(0); //pass the args 0 the output is 1 jan 1970

System.out.println("The output of Object 1 :-"+date);//display


current system date and time with time zone
System.out.println("The output of Object 2 :-"+date2);
System.out.println("The output of Object X :-"+x);

long msec = date.getTime();


System.out.println("Milliseconds since 1 Jan,1970 GMT:- " +msec);
date.setTime(msec + 10000000);
System.out.println("Date and time after add 1 crore milliseconds:-
"+date.toString());

Date d = new Date(63, 0, 16); // January 16, 1963


System.out.println("Day of the week: " + d.getDay());
}
}

35
GregorianCalendar

Calendar:-
 Like date class, Calendar class is also provided in java.util package.
 This class can be sued to extract detailed calendar information llike year,
month, date, hour, minute and second.
 Here, we will see the use of GregorianCalendar subclass of Calendar class.
 Calendar class has no public constructor.

GregorianCalendar

The java.util.GregorianCalendar class is a concrete subclass of Calendar and


provides the standard calendar system used by most of the world.
Class constructors
GregorianCalendar() This constructs a default
GregorianCalendar using the current
time in the default time zone with the
default locale.
GregorianCalendar(int year, int month, This constructs a GregorianCalendar
int dayOfMonth) with the given date set in the default
time zone with the default locale.
GregorianCalendar(int year, int month, This constructs a GregorianCalendar
int dayOfMonth, int hourOfDay, int with the given date and time set for
minute) the default time zone with the default
locale.
GregorianCalendar(int year, int month, This constructs a GregorianCalendar
int dayOfMonth, int hourOfDay, int with the given date and time set for
minute, int second) the default time zone with the default
locale.
GregorianCalendar(TimeZone zone) This constructs a GregorianCalendar
based on the current time in the given
time zone with the default locale.

36
import java.util.*;
class MonthCalendar
{
static String dayName[] = {"Sun","Mon","Tue","Wed","Thu","Fri","Sat"};
static String monthName[] =
{"January","Feruary","March","April","May","June","July","August","Septembe
r","October","November","December"};
static int dayInMonth[]= {31,28,31,30,31,30,31,31,30,31,30,31};

}
class GregorianCal
{
public static void main(String args[])
{
GregorianCalendar gc = new GregorianCalendar();
int year = gc.get(Calendar.YEAR);
int month = gc.get(Calendar.MONTH);
int date = gc.get(Calendar.DATE);
int dow = gc.get(Calendar.DAY_OF_WEEK);
System.out.println("The Year is :"+year);
System.out.println("The Month is
:"+MonthCalendar.monthName[month]);
System.out.println("The Day is :"+date);
System.out.println("The Day_Of_Week is :"+dow);
//handle leap year
MonthCalendar.dayInMonth[1] += gc.isLeapYear(year) ? 1 : 0;
//change to the first day of month
gc.add(Calendar.DATE, -date + 1);
//Determine the day of week
int fdow = gc.get(Calendar.DAY_OF_WEEK);

//Compute the variable dom


int dom = 2 - fdow;
//display column headings
for(int i=0;i<7;i++)
{
String s = MonthCalendar.dayName[i];
System.out.print(s + " ");
}
System.out.println(" ");
//display date

37
for(int row=0;row<6;row++)
{
for(int col=0;col<7;col++)
{
if(dom >MonthCalendar.dayInMonth[month] )
{
break;
}
if(dom > 0)
{
//display date in the fird cell
if(dom < 10 )
{
System.out.print(" " +dom+" " );
}
else
{
System.out.print(" " +dom+" " );
}
}
else
{
System.out.print(" ");
}
++dom;
}
System.out.println(" ");
}
}
}

38
Vector
Vector implements a dynamic array. It is similar to ArrayList, but with two
differences −
 Vector is synchronized.
 Vector contains many legacy methods that are not part of the collections
framework.
Vector proves to be very useful if you don't know the size of the array in
advance or you just need one that can change sizes over the lifetime of a
program.
Following is the list of constructors provided by the vector class.
Constructor & Description
Vector( )
This constructor creates a default vector, which has an initial size of 10.
Vector(int size)
This constructor accepts an argument that equals to the required size, and creates a
vector whose initial capacity is specified by size.
Vector(int size, int incr)
This constructor creates a vector whose initial capacity is specified by size and whose
increment is specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward.
Vector(Collection c)
This constructor creates a vector that contains the elements of collection c.

Method of Vector Class


Method Description
addElement() It will add the specified item at the end
of vector
elementAt() It will gives us data at the nth elelment
Size() Return the size of vector.
removeElement() It will remove element with the name
e
removeElementAt() Remove nth element from the vector.
removeAllElements() Remove all the element of vector
copyInto() Copies all the items into the array
insertElementAt() Insert the item at nth position

39
import java.util.*;

class VectorDemo
{
public static void main(String args[])
{
Vector v1 = new Vector();
int length = args.length;
for(int i =0; i<length;i++)
{
v1.addElement(args[i]);
}
v1.insertElementAt("Cobol",2);
int size = v1.size();
String str1[] = new String[size];
v1.copyInto(str1);
System.out.println("List of Language");
for(int i=0;i<size;i++)
{
System.out.println(str1[i]);
}
}
}

ArrayList Vector
1) ArrayList is not synchronized. Vector is synchronized.
2) ArrayList increments 50% of current Vector increments 100% means doubles the
array size if number of element exceeds array size if total number of element
from its capacity. exceeds than its capacity.
3) ArrayList is not a legacy class, it is Vector is a legacy class.
introduced in JDK 1.2.
4) ArrayList is fast because it is non- Vector is slow because it is synchronized
synchronized. i.e. in multithreading environment, it will
hold the other threads in runnable or non-
runnable state until current thread releases
the lock of object.

40
HashTable
 HashTable class is very much useful in java programming. It allows us to
easily store and retrieve the object.
 Each entry in the HashTable contains a key and the values are objects. The
keys must be unique and to retrieve elements from the HashTable.
 Another name of this type of data structure is associative array. This class
has a constructor which allows us to initialize its object.
 Constructor as follows:-
o Hashtable( ):-This is the default constructor of the hash table it
instantiates the Hashtable class.
o Hashtable(int size):-This constructor accepts an integer parameter
and creates a hash table that has an initial size specified by integer
value size.
o Hashtable(int size, float fillRatio):-This creates a hash table that has
an initial size specified by size and a fill ratio specified by fillRatio.
This ratio must be between 0.0 and 1.0, and it determines how full
the hash table can be before it is resized upward.
o Hashtable(Map < ? extends K, ? extends V > t):-This constructs a
Hashtable with the given mappings.
Method of Hash Table
Method Description
Boolean contains(Object o) Return true if the Hash Table contains
obj as one of its values.
Boolean containsKey(Object obj) Return true if the hash table contains
obj as one of its keys otherwise return
false.
Boolean containsValue(Object obj) Return true if the hash table contains
obj as one of its value otherwise false.
Enumeration e() Return an enumeration of elements.
Object get(Object x) Return the value associated with the
key x.
Boolean isEmpty() Return true if the hash table is empty
otherwise false
Enumeration keys() Return an enumeration key.
Object put(object k, object v) Puts a key and value pair in the hash
table where k is the key and v is the
value
Object remove(object k) Removes the key and value pair form
the hash table which key=k
Int size() Return number of keys in the hash
table

41
import java.util.*;
class HashTableClass
{
public static void main(String args[])
{
Hashtable hs = new Hashtable();

hs.put("Apple","Red");
hs.put("Grapes","Green");
hs.put("Mango","Orange");

Enumeration e = hs.keys();
while(e.hasMoreElements())
{
Object k = e.nextElement();
Object v = hs.get(k);
System.out.println("The Value of Key is:- "+k);
System.out.println("The Value of Value is:- "+v);
}
System.out.println("The Color of Apple is:-");
Object x = hs.get("Apple");
System.out.println(x);
}
}

42
StringTokenizer
 The string tokenizer class allows you to convert your string into words or
tokens.
 We have to specify the delimiter character.
 This functionality is very much useful when you need to develop a
program which process the formatted file.
 This class gives you a constructor in which you have to pass string and the
delimiter character.
 It doesn't provide the facility to differentiate numbers, quoted strings,
identifiers etc. like StreamTokenizer class.
 The constructor of the class are as below.
o StringTokenizer(String str):-creates StringTokenizer with specified
string.
o StringTokenizer(String str, String delim):-creates StringTokenizer
with specified string and delimeter.
o StringTokenizer(String str, String delim, boolean returnValue):-
creates StringTokenizer with specified string, delimeter and
returnValue. If return value is true, delimiter characters are
considered to be tokens. If it is false, delimiter characters serve to
separate tokens.
Method of Stringtokenizer Class:-
Method Description
Int countTokens() Return the number of tokens in the
string
Boolean hasMoreTokens() Returns true if there are more tokens in
the string otherwise false.
String nextToken() Return the next token.
import java.util.*;
class StringTokenizerClass
{
public static void main(String args[])
{
String str = "123/45.3/-11.2./-90.10/100/99.99/-50/20";
StringTokenizer st = new StringTokenizer(str,"/");
while(st.hasMoreElements())
{
String s = st.nextToken();
System.out.println(s);
}
}
}

43
Creating and Using User Defined package and sub-package
Packages
• Packages are container for classes that are used to keep the class name
space compartmentalized.
• Packages are stored in a hierarchical manner and are explicitly imported
into new class definition.
• Java provides a mechanism for partitioning the classname space into more
manageable chunk. This mechanism is the package.
• The package is both a naming and a visibility control mechanism. You can
define classes inside a package that are not accessible by code outside that
package. You can also define class member that are only exposed to other
members of the same package. This allows your classes to have intimate
knowledge of each-other but not expose that knowledge to the rest of the
world.
Defining a Package
 To create a package, simply include a package command as the first
statement in java source file.
 Any classes declared within that file will belong to the specified package.
 The package statement defines a name space in which classes are stored.
 If you omit the package statement, the class names are put into the default
package, which has no name.
• General form of package statement:
Package pkg;
 Where, pkg is the name of the package. For example following statement
creates a package called MyPackage must be stored in directory called
MyPackage. The directory name must match the package name exactly.
 More than one file can include the same package statement.
 You can create a hierarchy of packages. To do so, simply separate each
package name from the one above it by use of a period. The general form
of multileveled package statement:
Package pkg1[.pkg2[.pkg3]];
For example:
Package java.awt.image;
 This package needs to be stored in java/awt/image, java\awt\image or
java:awt:image on your system.

44
 You can not rename a package without renaming the directory in which
the classes are stored.
Finding Packages and CLASSPATH
 How dose the java run-time system know where to look for packages that
you create? – the answer has two parts:
1. by default, the java run-time system uses the current working directories as
its starting point. Thus, if your package is in the current directory, or a
subdirectory of the current directory, it will be found.
2. you can specify a directory path or paths by setting the CLASSPATH
environmental variable.
 For example, consider the following package specification:
Package MyPack;
 In order for a program to find MyPack, one of two things must be true.
Either the program is executed form a directory immediately above
MyPack or CLASSPATH must be set to MyPack.
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name=n;
bal=b;
}
void show()
{
if (bal>0)
System.out.println("Name is:"+name +":$" +bal);
}
}
class AccountBalance
{
public static void main(String args[])
{
Balance current[]=new Balance[3];

current[0]=new Balance("K.J.Fielding",123.23);
current[1]=new Balance("will tell",157.02);
current[2]=new Balance("Tom",-12.33);
45
for(int i=0;i<3;i++)
{
current[i].show();
}
}
}
 Compilation of program:
C:\javaprogs\MyPack>javac AccountBalance.java
C:\javaprogs>java MyPack.AccountBalance
 You will need to be in the directory above MyPack when you execute this
command, or your CLASSPATH environment variable set appropriately.
C:\javaprogs>javac p\*.java
C:\javaprogs>java p.PackageDemo
Javac –d . P\*.java

Package
• Package is a very important concept of java.
• Simply saying a package is just a container or collection of classes.
• So it is a directory or folder which contains the source files & its class
files.
• Generally you have to take care about duplicate class names.
• But using package you can have more than one class of same name.
• That is you can have same name of class in different packages.
• You can define class & members that can not be accessed by other
classes or packages.

How to define a package?


• To create a package keyword is used as the first statement of your
program after package keyword you have to give the package name.
• In this package.
• I.e. directory your class files & source files will be stored and if you do
not specify any package as we did earlier, the files will be stored in
the default package.
• But it is good define a package for your classes.
46
• As we can shown in bellow.
package packagename
Ex: package mypack;
• Here your class files must be in the directory named mypack. You can
also create a hierarchy of packages. It can be done as follow.
Package p1.p2.p3;
• Here the hierarchy shows that p1 is the main package, p2 is its sub
package & p3 is sub package of p2. So the p3 directory should be in
p2 & p2 should be in p1. The path of your class files should be like
this..
• p1/p2/p3/class file & you can not rename any of these directory
names without changing the package name.
• If your program contains a package statement, it must be the first
statement of the program.

• Access control for package

Specified Private Default Protected Public

Same class Yes Yes Yes Yes


Same package No Yes Yes Yes
Different package,subclasses No No Yes yes
Different package, no-sub class No No No Yes

Private : any private member can be accessed by the member of


its class only. Private member can not be accessed from outside
the class.

47
Default(No specifier) : The default members are accessed by the
members of the current package only. So the members of other
class but same package can be accessed.

Protected : if a member is defined as protected, it can be


accessed from other class & other packages but only the subclass
in the case of different package. So when you want to allow a
member to be accessed from other package.
• But only those members which belong to the subclass of this
class, use protected specifier.

Public :
• The public members can be accessed from anywhere, means any
class & any package.
• Remember that these access specifiers can be applied to any
members of classes but a class can have only public or default
access.
How to import package?
• After creating a package, you can use its classes in other java
files.
• To do this you have to import that package in which the class is
resided.
• Importing a package is similar to including header file in C or
C++.
• Syntax :import pack1 [.pack2].classname/*;
• Here pack1 is the name of main package or directory. Pack2 is
the sub package of package pack1.
• You can have as many sub packages as you want . After the
package name you have to specify the class name that you want
to use.

48
You can import whole package
• Example:
• Import java.awt.*;
• Import java.util.Vector;
• As we can shown bellow…..
• …………….
• …………..

***********************************************************************

49

You might also like