CH 2
CH 2
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);
2
Access Specifies (Public, Private, Protected, 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);
}
}
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.
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:-
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:-
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 override_test
{
public static void main(String[] args)
{
xyz p1 = new xyz(100,200);
p1.display();
}
}
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();
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();
}
}
FinalBlankVarialbeConstructor
{
speedlimit=70;
System.out.println(speedlimit);
}
17
Abstract Class:-
}
}
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.
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.
static import can be defined and static member fields can not
refere any class name and use directly without classname.
24
out is static field in java.lang.System class and E is static member
variable for java.lang.Math class.
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.
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.
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.
System.out.println(x);
System.out.println(c);
System.out.println(a);
System.out.println(b);
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.
}
}
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
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);
}
}
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).
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
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
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);
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.
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.
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.
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