Corejava 2
Corejava 2
java.lang
java.lang package : The java.lang package is indispensable when programming in Java. It is
automatically imported into every source file at compile time. The package contains the Object class that
is the mother of all classes, and the wrapper classes (Boolean, Character, Byte, Short, Integer, Long,
Float, Double) used to handle primitive values as objects. It provides classes essential for interacting with
the JVMR (untime), for security (SecurityManager), for loading classes (ClassLoader), for dealing with
threads (Thread), and for exceptions (Throwable). The java.lang package also contains classes that
provide the standard input, output, and error streams (System), string handling (String, StringBuffer), and
mathematical functions (Math).
Skarifahmed@gmail.com
2
Java.lang.Object Class: The Object class is always at the top of the class hierarchy tree in the Java
development environment. The Object class defines the basic state and behavior that all objects must
have, such as the ability to compare one to another object, to convert to a string, to wait on a condition
variable, to notify other objects that a condition variable has changed, and to return the object's class. All
Java classes derive from the Object base class directly or indirectly. These is true even though you don't
explicitly include the "extends Object" in your class definition. For example,
Skarifahmed@gmail.com
3
...
is equivalent to
...
This means that all Java classes are of the Object type.
Some of the important methods defined in the Object class are given below. These methods are
available to all Java classes.
>>public boolean equals(Object obj)-The equals() method is usually overridden to provide the
semantics of object value equality, as is the case for the wrapper classes and the String class. Some classes
like String and Boolean overload this method.
Consider this code that tests two Integers, one and anotherOne, for equality:
Integer one = new Integer(1), anotherOne = new Integer(1);
if (one.equals(anotherOne))
System.out.println("objects are equal");
This code will display objects are equal even though one and anotherOne reference two different, distinct
objects. They are considered equal because they contain the same integer value.
>>public int hashCode()-Returns a hash code value for the object. This method is supported for the
benefit of hashtables such as those provided by java.util.Hashtable.
*Whenever it is invoked on the same object more than once during an execution of a Java
application, the hashCode method must consistently return the same integer, provided no information
used in equals comparisons on the object is modified. This integer need not remain consistent from one
execution of an application to another execution of the same application.
Skarifahmed@gmail.com
4
*If two objects are equal according to the equals(Object) method, then calling the hashCode
method on each of the two objects must produce the same integer result.
*It is not required that if two objects are unequal according to the equals(java.lang.Object)
method, then calling the hashCode method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing distinct integer results for unequal
objects may improve the performance of hashtables.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct
integers for distinct objects. (This is typically implemented by converting the internal address of the
object into an integer, but this implementation technique is not required by the JavaTM programming
language.)
>>protected Object clone() throws CloneNotSupportedException- New objects that are exactly the
same (i.e., have identical states) as the current object can be created by using the clone() method, that is,
primitive values and reference values are copied. This is called shallow copying. A class can override this
method to provide its own notion of cloning.
>>public String toString()-The function is used to convert objects to String. If a subclass does not
override this method, the method returns a textual representation of the object, which has the following
format : <name of the class>@<hash code value of the object>".
For example, you could display a String representation of the current Thread like this:
System.out.println(Thread.currentThread().toString());
The String representation for an object is entirely dependent on the object. The String representation of an
Integer object is the integer value displayed as text. The String representation of a Thread object contains
various attributes about the thread, such as its name and priority.
Thread[main,5,main]
>>protected void finalize() throws Throwable- Called by the garbage collector on an object when
garbage collector determines that there are no more references to the object. A subclass overrides the
Skarifahmed@gmail.com
5
finalize method to dispose of system resources or to perform other cleanup. The finalize method is never
invoked more than once by a Java virtual machine for any given object.
>>public final Class getClass()-Returns the runtime class of the object, which is represented by an
object of the class java.lang.Class at runtime.
The following methods related to threads are also defined in Object class
>>notify () - Called by a thread that owns an object's lock to tell a waiting thread, as arbitrarily chosen by
the VM, that the lock is now available.
>>notifyAll () -Similar to notify() but wakes all waiting threads and then they compete as usual for the
lock.
>>wait () - The thread that owns the lock on a object will release the lock and then wait for a notify() or
notifyAll() to get the lock back.
>>wait (long msecs) throws InteruptedException-Same as wait() but if a notify fails to come within the
specified time, it wakes up and starts competing for the lock on this object.
>>wait (long msecs, int nanosecs) throws InteruptedException-Same as wait(long msecs) but
specified to the nanosec.
Wrapper class: Wrapper class is wrapper around a primitive data type. Primitive values in Java are not
Objects. An instance of a wrapper class contains, or wraps, a primitive value of the corresponding type.
Wrapper Classes are public final i.e. cannot be extended. Wrapper Classes allow objects to be created
from primitive types. The objects of all wrapper classes that can be instantiated are immutable, that is,
their state cannot be changed.
Skarifahmed@gmail.com
6
1>A constructor that takes the primitive type and creates an object eg Character(char),
Integer(int)
The Character class has only one public constructor, taking a primitive value as parameter. The
Character class does not have a constructor that takes a String argument.
A constructor that takes a primitive value can be used to create wrapper objects.
Skarifahmed@gmail.com
7
A constructor that takes a String object representing the primitive value, can also be used to create
wrapper objects. The constructors for the numeric wrapper types throw an unchecked
NumberFormatException if the String parameter does not parse to a valid number.
All wrapper classes except Character, have a valueOf(String s) method which is equivalent to new
Type(String s) . This method for the numeric wrapper types also throws a NumberFormatException if the
String parameter is not a valid number.
Each wrapper class overrides the toString() method from the Object class. The overriding method returns
a String object containing the string representation of the primitive value in the wrapper object.
Skarifahmed@gmail.com
8
Skarifahmed@gmail.com
9
Each wrapper class defines a static method toString(type v) that returns the string corresponding to the
primitive value of type passed as argument.
For integer primitive types, the base is assumed to be 10. For floating-point numbers, the textual
representation (decimal form or scientific notation) depends on the sign and the magnitude (absolute
value) of the number. The NaN value, positive infinity and negative infinity will result in the strings
"NaN", "Infinity", and "-Infinity", respectively.
In addition, the wrapper classes Integer and Long define overloaded toString() methods for converting
integers to string representation in decimal, binary, octal, and hexadecimal notation.
Each wrapper class defines a typeValue() method which returns the primitive value in the wrapper object
In addition, each numeric wrapper class defines typeValue() methods for converting the primitive value in
the wrapper object to a value of any numeric primitive data type. These methods are discussed below.
The numeric wrapper classes Byte, Short, Integer, Long, Float, and Double are all subclasses of the
abstract class Number
Skarifahmed@gmail.com
10
Each numeric wrapper class defines an assortment of constants, including the minimum and maximum
value of the corresponding primitive data type:
The following code retrieves the minimum and maximum values of various numeric types:
Each numeric wrapper class defines the following set of typeValue() methods for converting the primitive
value in the wrapper object to a value of any numeric primitive type:
byte byteValue()
short shortValue()
int intValue()
long longValue()
float floatValue()
double doubleValue()
The following code shows converting of values in numeric wrapper objects to any numeric primitive
type.
Skarifahmed@gmail.com
11
Notice the potential for loss of information at (1) and (2) above, when the primitive value in a wrapper
object is converted to a narrower primitive data type.
Each numeric wrapper class defines a static method parseType(String s), which returns the primitive
numeric value represented by the String object passed as argument. The Type in the method name
parseType stands for the name of a numeric wrapper class, except for the name of the Integer class which
is abbreviated to Int. These methods throw a NumberFormatException if the String parameter is not a
valid argument.
The wrapper classes Integer and Long provide static methods for converting integers to string
representation in decimal, binary, octal, and hexadecimal notation. Some of these methods from the
Integer class are listed here, but analogous methods are also defined in the Long class.
These three methods return a string representation of the integer argument as an unsigned integer in base
2, 16, and 8,
Skarifahmed@gmail.com
12
The first method returns the minus sign '-' as the first character if the integer i is negative. In all cases, it
returns the string representation of the magnitude of the integer i in the specified base.
Character
The Character class defines a myriad of constants, including the following which represent the minimum
and the maximum value of the char type.
Character.MIN_VALUE
Character.MAX_VALUE
The Character class also defines a plethora of static methods for handling various attributes of a character,
and case issues relating to characters, as defined by Unicode:
Skarifahmed@gmail.com
13
Boolean
The Boolean class defines the following wrapper objects to represent the primitive values true and false,
respectively:
Boolean.TRUE
Boolean.FALSE
Void
Although the Void class is considered a wrapper class, it does not wrap any primitive value and is not
instantiable (i.e., has nopublic constructors). It just denotes the Class object representing the keyword
void. The constructors and methods described above do NOT exist for the Void class although it does
have the TYPE field.
java.lang.Math: The final class Math defines a set of static methods to support common mathematical
functions, including functions for rounding numbers, performing trigonometry, generating pseudo random
numbers, finding maximum and minimum of two numbers, calculating logarithms and exponentiation.
The Math class cannot be instantiated. In Math class all methods are static. Only the class name Math can
be used to invoke the static methods.
Skarifahmed@gmail.com
14
Static double E: 2.718281828459045 The double value that is closer than any other to e,
the base of the natural logarithms.
Static double PI: 3.141592653589793 The double value that is closer than any other to
pi, the ratio of the circumference of a circle to its
diameter.
Math Methods
Math.abs(-0.0): 0.0
Math.abs(Float.NEGATIVE_INFINITY): Infinity
Math.abs(Float.NaN): NaN
• EXCEPT if the value is equal to Integer.MIN_VALUE, in which case, it returns the value as a
negative .
Math.abs(Integer.MIN_VALUE): -2147483648
Skarifahmed@gmail.com
15
• returns the smallest double value not less than the argument and equal to an integer (counts
up)
• if the argument is already an integer, returns the argument
• if the argument is NaN or infinity, returns the argument
• if the argument is between -1.0 and 0, returns 0
Math.ceil( 9.01): 10.0 // counts up (away from zero)
Math.ceil(10): 10.0
Math.ceil(-0.03): -0.0
Math.ceil(Double.NaN): NaN
• returns the largest double value not greater than the argument and equal to an integer (counts
down)
• if the argument is an integer, returns the argument
• if the argument is NaN, infinity, negative or positive zero, returns the argument
• if the argument is between -0 and 0, returns -0
Math.floor( 9.01): 9.0 // counts down (towards zero)
Math.floor(10): 10.0
Math.floor(-0.03): -1.0
Math.floor(Double.NaN): NaN
Skarifahmed@gmail.com
16
Math.min(Float.NaN,Float.POSITIVE_INFINITY); NaN
Math.round( 1.5): 2
Math.round(-1.5): -1
Skarifahmed@gmail.com
17
Math.round(Float.NaN): 0
Math.round(Float.NEGATIVE_INFINITY): -2147483648
Math.round(Double.POSITIVE_INFINITY): 9223372036854775807
Math.round(Float.MAX_VALUE): 2147483647
(Float.MAX_VALUE is 3.4028235E38)
Math.rint(-5.5): -6.0
Math.rint(-5.49): -5.0
Math.sqrt(-45): NaN
• returns the first argument raised to the power of the second argument
Math.pow(2,2): 4.0
Trigometric functions
Skarifahmed@gmail.com
18
Skarifahmed@gmail.com
19
Math.sin(90): 0.8939966636005579
Math.cos(90): -0.4480736161291701
Math.tan(90): -1.995200412208242
Math.asin(-0): 0.0
Math.acos(-0): 1.5707963267948966
Math.atan(90): 1.5596856728972892
Math.toRadians(90) 1.5707963267948966
Math.toDegrees(Math.PI/2): 90.0
Logarithms
Math.log(-10): NaN
Math.log(0.0): -Infinity
Skarifahmed@gmail.com
20
Math.exp(Float.NaN): NaN
Math.exp(Float.POSITIVE_INFINITY): Infinity
Math.exp(Float.NEGATIVE_INFINITY): 0.0
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the
same reference. A java.lang.String class is final which implies no class can extend it.
String methods
char charAt(int index)Returns the character at the specified index. An index ranges from 0 to length()
- 1. The first character of the sequence is at index 0, the next at index 1, and so on, as for array indexing.
int length()Returns the length of this string. The length is equal to the number of 16-bit Unicode
characters in the string.
boolean equals(Object anObject)Compares this string to the specified object. The result is true if and
only if the argument is not null and is a String object that represents the same sequence of characters as
this object.
Skarifahmed@gmail.com
21
String toUpperCase() Converts all of the characters in this String to upper case using the rules
of the default locale.
String toLowerCase() Converts all of the characters in this String to upper case using the rules
of the default locale.
String concat(String str)Concatenates the specified string to the end of this string. If the length of the
argument string is 0, then this String object is returned. Otherwise, a new String object is created,
representing a character sequence that is the concatenation of the character sequence represented by this
String object and the character sequence represented by the argument string.
indexOf(int ch) Returns the index within this string of the first occurrence of the specified
character.
indexOf(int ch, int fromIndex) Returns the index within this string of the first occurrence of the
specified character, starting the search at the specified index.
indexOf(String str) Returns the index within this string of the first occurrence of the specified
substring.
indexOf(String str, int fromIndex) Returns the index within this string of the first occurrence of
the specified substring, starting at the specified index.
lastIndexOf(int ch) Returns the index within this string of the last occurrence of the specified
character.
lastIndexOf(int ch, int fromIndex) Returns the index within this string of the last occurrence of the
specified character, searching backward starting at the specified index.
lastIndexOf(String str) Returns the index within this string of the rightmost occurrence of the
specified substring.
lastIndexOf(String str, int fromIndex) Returns the index within this string of the last occurrence
of the specified substring, searching backward starting at the specified index.
Skarifahmed@gmail.com
22
substring(int beginIndex, int endIndex) Returns a new string that is a substring of this string. The
index position is start from 0, so the index of the last character of the string is (length of the string-1).
replace(char oldChar, char newChar) Returns a new string resulting from replacing all
occurrences of oldChar in this string with newChar.
trim() Returns a copy of the string, with leading and trailing whitespace omitted.
Skarifahmed@gmail.com
23
} else {
System.out.print(str3 + " equals " + str4);
}
System.out.println();
System.out.print("Equals Test");
System.out.println("str3.equalsIgnoreCase(5) : " + str3.equalsIgnoreCase(str5));
System.out.println("str3.equals(6) : " + str3.equals(str6));
System.out.println("str1.equals(3) : " + str1.equals(str3));
str5.toUpperCase(); //Strings are immutable
System.out.println("str5 : " + str5);
String temp = str5.toUpperCase();
System.out.println("str5 Uppercase: " + temp);
temp = str1.toLowerCase();
System.out.println("str1 Lowercase: " + temp);
System.out.println("str1.concat(str4): " + str1.concat(str4));
String str7temp = " \t\n Now for some Search and Replace Examples ";
String str7 = str7temp.trim();
System.out.println("str7 : " + str7);
String newStr = str7.replace('s', 'T');
System.out.println("newStr : " + newStr);
System.out.println("indexof Operations on Strings");
System.out.println("Index of p in " + str7 + " : "+ str7.indexOf('p'));
System.out.println("Index of for in " + str7 + " : "+ str7.indexOf("for"));
System.out.println("str7.indexOf(for, 30) : "+ str7.indexOf("for", 30));
System.out.println("str7.indexOf('p', 30) : "+ str7.indexOf('p', 30));
System.out.println("str7.lastIndexOf('p') : "+ str7.lastIndexOf('p'));
System.out.println("str7.lastIndexOf('p', 4) : "+ str7.lastIndexOf('p', 4));
System.out.print("SubString Operations on Strings");
String str8 = "SubString Example";
String sub5 = str8.substring(5); // "ring Example"
String sub3_6 = str8.substring(3, 6); // "Str"
System.out.println("str8 : " + str8);
System.out.println("str8.substring(5) : " + sub5);
Skarifahmed@gmail.com
24
Character at position 3 is : n
str3.equals(6) : true
str1.equals(3) : false
str5 : BoB
str7.indexOf(for, 30) : -1
str7.indexOf('p', 30) : 36
str7.lastIndexOf('p') : 36
Skarifahmed@gmail.com
25
str7.lastIndexOf('p', 4) : -1
str8.substring(3,6) : Str
StringBuilder and StringBuffer are much more efficient when building up a string from many strings.
Character has many useful static methods for working with single characters.
Pattern and Matcher provide full regular expression processing.
CharSequence interface is implemented by String, StringBuilder and others. Defines length(),
charAt(pos), subSequence(beg, upto), and toString().
StringTokenizer divides strings into tokens, but String.split(regex) and other regular expression methods
are more useful.
StringCharacterIterator and CharacterIterator don't seem to be especially useful.
The String class implements immutable character strings, which are read-only once the string has been
created and initialized, whereas the StringBuffer class implements dynamic character strings. Strings are
immutable (can't be changed), so manipulating strings often causes many temporary string objects to be
created, which can be quite inefficient. StringBuilder (or StringBuffer) are better choices in these cases.
Their toString() method can be used get a String value. It isn't necessary to create them with a specific
size, it will expand as necessary. Many StringBuilder methods return the same StringBuilder so that the
call chaining style of programming can be used.
StringBuilder is basically identical to the older StringBuffer, but is slightly faster because it isn't
synchronized.
Example :
Skarifahmed@gmail.com
26
output += i;
return output;
The above code would build 99 new String objects, of which 98 would be thrown away immediately.
Creating new objects is not
efficient.
output.append(“Some text”);
output.append(i);
return output.toString();
The above code creates only two new objects, the StringBuffer and the final String that is returned.
StringBuffer expands as needed, which is costly however, so it would be better to initialize the
StringBuffer with the correct size from the start as shown.
Constructors of StringBuffer
StringBuffer(String s) Constructs a string buffer so that it represents the same sequence of characters as
the string argument; in other words, the initial contents of the string buffer is a copy of the argument
string.
Skarifahmed@gmail.com
27
StringBuffer method:
int length()The length of the sequence of characters currently represented by this string buffer.
int capacity()Returns the current capacity of the String buffer. The capacity is the amount of storage
available for newly inserted characters; beyond which an allocation will occur.
char charAt(int index)The specified character of the sequence currently represented by the string
buffer, as indicated by the index argument, is returned. The first character of a string buffer is at index 0,
the next at index 1, and so on, for array indexing. The index argument must be greater than or equal to 0,
and less than the length of this string buffer.
void setCharAt(int index,char ch)The character at the specified index of this string buffer is set to
ch. The string buffer is altered to represent a new character sequence that is identical to the old character
sequence, except that it contains the character ch at position index. The index argument must be greater
than or equal to 0, and less than the length of this string buffer.
StringBuffer append(Object obj)Appends the string representation of the Object argument to this
string buffer. The argument is converted to a string as if by the method String. valueOf, and the characters
of that string are then appended to this string buffer.
StringBuffer delete(int start,int end)Removes the characters in a substring of this StringBuffer. The
substring begins at the specified start and extends to the character at index end - 1 or to the end of the
StringBuffer if no such character exists. If start is equal to end, no changes are made.
StringBuffer insert(int offset, String str)Inserts the string into this character sequence. The
characters of the String argument are inserted, in order, into this sequence at the indicated offset, moving
Skarifahmed@gmail.com
28
up any characters originally above that position and increasing the length of this sequence by the length of
the argument. If str is null, then the four characters "null" are inserted into this sequence.
• the character at index k in the old character sequence, if k is less than offset
• the character at index k-offset in the argument str, if k is not less than offset but is less than
offset+str.length()
• the character at index k-str.length() in the old character sequence, if k is not less than
offset+str.length()
The offset argument must be greater than or equal to 0, and less than or equal to the length of this
sequence.
String substring(int start)Returns a new String that contains a subsequence of characters currently
contained in this character sequence. The substring begins at the specified index and extends to the end of
this sequence.
Skarifahmed@gmail.com
29
Thread
Ans.Multitasking is the ability to execute more than one task (*program) at the same time.
*What is a program?
Skarifahmed@gmail.com
30
1.Process-based multitasking
2.Thread-based multitasking
Process-based Multitasking
A process is a program that is being executed by the processor. The process-based
multitasking feature of Java enables you to switch from one program to another so
quickly that it appears as if the programs are executing at the same time.
Example: process-based multitasking enables you to run the Java compiler and use the text editor at
the same time. The process-based multitasking feature enables a computer to execute two or more
processes (For Single CPU) simultaneously. Processes are the tasks that require separate address
space in the computer memory.
Thread-based Multitasking
A single program can contain two or more threads and therefore, perform two or more tasks
simultaneously.
Example: a text editor can perform writing to a file and print a document simultaneously with separate
threads performing the writing and printing actions. Also, in a text-editor, you can format text in a
document and print the document at the same time. Threads are called lightweight process because
there are fewer overloads when the processor switches from one thread to another. On the other
hand, when the processor switches from one process to another process the overload increases.
Ans:
Skarifahmed@gmail.com
31
The Runnable interface is more advantageous, as it does not require your object to inherit a thread
because when you need multiple inheritance, only interfaces can help you. In the above example we had
to extend the Base class so implementing Runnable interface is an obvious choice. Also note how the
threads are started in each of the different cases as shown in the code sample. By implementing a
Runnable interface instead of extending the Thread class,if a class needs,it can inherit other features
provided by other classes or interfaces of different packages.
Skarifahmed@gmail.com
32
Skarifahmed@gmail.com
33
A thread must acquire the object lock associated with a shared resource,
before it can enter the shared resource. The runtime system ensures that no
other thread can enter a shared resource if another thread already holds the
object lock associated with the shared resource. If a thread cannot
immediately acquire the object lock, it is blocked, that is, it must wait for the
lock to become available.
When a thread exits a shared resource, the runtime system ensures that the
object lock is also relinquished. If another thread is waiting for this object
lock, it can proceed to acquire the lock in order to gain access to the shared
resource.
Classes also have a class-specific lock that is analogous to the object lock.
Such a lock is actually a lock on the java.lang.Class object associated with
the class. Given a class A, the reference A.class denotes this unique Class
object. The class lock can be used in much the same way as an object lock
to implement mutual exclusion.
1.synchronized methods:-
Synchronized Methods
If the methods of an object should only be executed by one thread at a time, then the
declaration of all such methods should be specified with the keyword synchronized. A
thread wishing to execute a synchronized method must first obtain the object's lock (i.e.,
hold the lock) before it can enter the object to execute the method. This is simply
achieved by calling the method. If the lock is already held by another thread, the calling
thread waits. No particular action on the part of the program is necessary. A thread
relinquishes the lock simply by returning from the synchronized method, allowing the
next thread waiting for this lock to proceed.
Example:-
public class CubbyHole {
private int contents;
Skarifahmed@gmail.com
34
Skarifahmed@gmail.com
35
System.out.println("first statement");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println("Error " + e);
}
System.out.println("second statement");
}
}
class Thread2 extends Thread
{
Thread1 t;
public Thread2(Thread1 t)
{
this.t = t;
}
public void run()
{
synchronized(t) //synchronized statements
{
t.call();
}
}
}
public class SynchronizedBlock
{
public static void main(String args[])
{
Thread1 obj1 = new Thread1();
Thread2 obja = new Thread2(obj1);
Thread2 objb = new Thread2(obj1);
obja.start();
objb.start();
}
}
Output:-
Skarifahmed@gmail.com
36
Skarifahmed@gmail.com
37
New: A new thread is one that has been created, i.e. using the new
operator, but has not yet been started.
Runnable (ready state to Run): A thread becomes runnable once its
start() method has been invoked, which means that the code in the run()
method can execute whenever the thread receives CPU time from the
operating system. A Thread that had been set to sleep and the time interval
has expired, a thread which was waiting and has been notified, a thread that
had been suspended and it has been resumed, and a thread that had been
blocked by an I/O request and the I/O has been completed are also in a
runnable state.
Running sate
The thread code is being actively executed by the processor. It runs until it is
swapped out, becomes blocked, or voluntarily give up its turn with this static
method
Skarifahmed@gmail.com
38
Thread.yield();
Please note that yield() is a static method. Even if it is called on any thread
object, it causes the currently executing thread to give up the CPU.
Not Runnable (blocked state): A thread can become not runnable if: the
thread's sleep() method is invoked (in which case, the thread remains
blocked for a specified number of milliseconds, giving a chance to lower-
priority threads to run); the thread's suspend() method is invoked (in which
case, the thread remains blocked until its resume() method is invoked); the
thread calls the wait() method of an object (in which case, the thread
remains blocked until either the object's notify() method or its notifyAll()
method is called from another thread); the thread has blocked on an I/O
operation (in which case the thread remains blocked until the I/O operation
has been completed)
Dead: A thread can die either because the run() method has finished
executing, i.e. has terminated, or because the thread's stop() method has
been called. The latter should be avoided because it throws
a ThreadDeath which is a subclass of Error.
Example:
class MyRunnableClass implements Runnable
{
String name;
MyRunnableClass(String str)
{
name = str;
}
Skarifahmed@gmail.com
39
class ThreadExample3
{
public static void main(String args[])
{
MyRunnableClass r1 = new MyRunnableClass("Thread-1");
MyRunnableClass r2 = new MyRunnableClass("Thread-2");
MyRunnableClass r3 = new MyRunnableClass("Thread-3");
th3.start();
th1.start();
th2.start();
}
}
Output:
th1 priority: 5
th2 priority: 10
th3 priority: 1
Thread: Thread-2
Thread: Thread-2
Thread: Thread-2
Thread: Thread-2
Skarifahmed@gmail.com
40
Thread: Thread-2
Thread: Thread-1
Thread: Thread-1
Thread: Thread-1
Thread: Thread-3
Thread: Thread-1
Thread: Thread-1
Thread: Thread-3
Thread: Thread-3
Thread: Thread-3
Thread: Thread-3
• the wait() method causes a thread to release the lock it is holding on an object;
allowing another thread to run
• the wait() method is defined in the Object class
• wait() can only be invoked from within synchronized code
• it should always be wrapped in a try block as it throws IOExceptions
• there are actually three wait() methods
1. wait()
2. wait(long timeout)
3. wait(long timeout, int nanos)
• the timeout is measured in milliseconds
• nanos is measured in nanoseconds
• wait() can only invoked by the thread that own's the lock on the object
• when wait() is called, the thread becomes disabled for scheduling and lies dormant until
one of four things occur:
1. another thread invokes the notify() method for this object and the scheduler
arbitrarily chooses to run the thread
2. another thread invokes the notifyAll() method for this object
3. another thread interrupts this thread
4. the specified wait() time elapses
• when one of the above occurs, the thread becomes re-available to the Thread scheduler
and competes for a lock on the object
• once it regains the lock on the object, everything resumes as if no suspension had
occurred
• if the thread was interrupted by another thread, an InterruptedException is thrown
BUT not until after the thread regains it's lock on the object
Skarifahmed@gmail.com
41
Example:
Skarifahmed@gmail.com
42
• the notify() and notifyAll() methods are defined in the Object class
• they can only be used within synchronized code
• notify() wakes up a single thread which is waiting on the object's lock
• if there is more than one thread waiting, the choice is arbitrary ie there is no way to
specify which waiting thread should be re-awakened
• notifyAll() wakes up ALL waiting threads; the scheduler decides which one will run
Example:
iv)join():
Skarifahmed@gmail.com
43
A thread can invoke the overloaded method join() on another thread in order to wait for the other
thread to complete its execution before continuing, that is, the first thread waits for the second thread
to join it after completion. A running thread t1 invokes the method join() on a thread t2. The join()
call has no effect if thread t2 has already completed. If thread t2 is still alive, then thread t1 transits
to the Blocked-for-join-completion state. Thread t1 waits in this state until one of these events occur
Thread t2 completes. In this case thread t1 is enabled and when it gets to run, it will continue
normally after the join() method call. Thread t1 is timed out. The time specified in the argument in the
join() method call has elapsed, without thread t2 completing. In this case as well,
thread t1 is enabled. When it gets to run, it will continue normally after the join() method call.
Thread t1 is interrupted. Some thread interrupted thread t1 while thread t1 was waiting for join
completion. Thread t1 is enabled, but when it gets to execute, it will now throw an
InterruptedException.
Example:
Skarifahmed@gmail.com
44
Skarifahmed@gmail.com
45
Output:
Skarifahmed@gmail.com
46
v)yeild():
• Java does not time-slice ie it will not preempt a currently executing thread to allow
another thread of the same priority to run
• the operating system may use time-slicing but you should not rely on time-slicing when
creating threads
• a well behaved thread will use the yield() method to voluntarily yield to the CPU, giving
it a chance to run another thread of the same priority.
• if no threads of the same priority are available, execution of the yielding thread
continues.
• Note: lower priority threads are ignored.
• the yield() method only hints to the JVM that if there are other thread which is in the
ready to run state the scheduler should run one in place of the current thread. The JVM
may interpret this hint any way it likes ie how the yield is handled is dependent on the
JVM implementation for the operating system
Example:
public void run() {
try {
while (!done()) {
sum();
Thread.yield(); // Current thread yields
}
} catch (InterruptedException e) {
doCleaningUp();
}
}
Skarifahmed@gmail.com
47
vi)sleep():
The static method 'sleep' makes the current thread stop execution for the
amount of time specified in its input parameter. The unit of time used is
milliseconds (a millisecond is 1/1000 of a second). A checked exception
called 'InterruptedException' is thrown by the sleep() method if another
process attempts to interrupt the thread before the specified time-interval is
over. This Exception should be handled when the sleep method is used.
Example:
(new HelloWorldThread()).start();
try {
Skarifahmed@gmail.com
48
System.out.println(ie.getMessage());
Output:
g)What is deadlock?
Ans.
Deadlock:
A deadlock is a situation where a thread is waiting for an object lock that
another thread holds, and this second thread is waiting for an object lock
that the first thread holds. Since each thread is waiting for the other thread
to relinquish a lock, they both remain waiting forever in the Blocked-for-lock-
acquisition state. The threads are said to be deadlocked.
Thread t1 has a lock on object o1, but cannot acquire the lock on object o2. Thread t2
has a lock on object o2, but cannot acquire the lock on object o1. They can only
Skarifahmed@gmail.com
49
proceed if one of them relinquishes a lock the other one wants, which is never going to
happen.
Example of Deadlock
public class DeadLockDanger {
String o1 = "Lock " ; // (1)
String o2 = "Step "; // (2)
Thread t1 = (new Thread("Printer1") { // (3)
public void run() {
while(true) {
synchronized(o1) { // (4)
synchronized(o2) { // (5)
System.out.println(o1 + o2);
}
}
}
}
});
Thread t2 = (new Thread("Printer2") { // (6)
public void run() {
while(true) {
synchronized(o2) { // (7)
synchronized(o1) { // (8)
System.out.println(o2 + o1);
}
}
}
}
});
public static void main(String[] args) {
DeadLockDanger dld = new DeadLockDanger();
dld.t1.start();
dld.t2.start();
}
}
Possible output from the program:
...
Step Lock
Step Lock
Lock Step
Lock Step
Lock Step
Thread t1 at (3) tries to synchronize at (4) and (5), first on string o1 at (1) then on string o2 at (2), respectively. The thread t2 at (6)
does the opposite. It synchronizes at (7) and (8), first on stringo 2 then on string o1, respectively. A deadlock can occur as explained
previously. However, the potential of deadlock in the situation in the above code is easy to fix. If the two threads acquire the locks on
the objects in the same order, then mutual lock dependency is avoided and a deadlock can never occur. This means having the
same locking order at (4) and (5) as at (7) and (8). In general, the cause of a deadlock is not always easy to discover, let alone easy
to fix.
Skarifahmed@gmail.com
50
Ans:-
The Java Run-time Environment executes threads based on their priority.
• A CPU can execute only one thread at a time. Therefore, the threads,
which are ready for execution, queue up for their turn to get executed by the
processor.
• A thread with higher priority runs before threads with low priority.
• Defining Thread Priority
• Thread priorities are the integers in the range of 1 to 10 that specify the
priority of one thread with respect to the priority of another thread.
•Priorities are integer values from 1 (lowest priority given by the constant
Thread. MIN_PRIORITY) to 10 (highest priority given by the
constant Thread.MAX_PRIORITY). The default priority is 5
(Thread.NORM_PRIORITY).
Example:-
Skarifahmed@gmail.com
51
{
try
{
for(int i=1;i<=5;i++)
{
System.out.println(t + "loop :" + i);
Thread.sleep(500);
}
}
catch( InterruptedException obj)
{
System.out.println("Thread :" + t + "interrupted");}
}
}
class PriorityDemo
{
public static void main(String args[])
{
ChildThread obj1 = new ChildThread(Thread.NORM_PRIORITY - 2);//setting The priority
ChildThread obj2 = new ChildThread(Thread.NORM_PRIORITY + 2);
ChildThread obj3 = new ChildThread(Thread.NORM_PRIORITY + 3);
//Starting the threads with different priority
obj1.t.start();
obj2.t.start();
obj3.t.start();
try
{
System.out.println("Main thread waiting for child
thread to finish");
obj1.t.join();
obj2.t.join();
obj3.t.join();
}
catch(InterruptedException e)
{
Skarifahmed@gmail.com
52
Output:
Skarifahmed@gmail.com
53
Garbage Collection
a) What is garbage collection? What is reachable reference and unreachable reference?
What is reachable and unreachable object?
Answer: Garbage collection is the feature of Java that helps to automatically destroy the
objects created and release their memory for future reallocation. When no reference to an
object exists and the object is assumed to be no longer required, the memory occupied by that
object can be released and used by another object. The various activities involved in garbage
collection are:
• Monitoring the objects used by a program and determining when they are not in use
• Destroying objects that are no more in use and reclaiming their resources, such as
memory space.
The Java Virtual machine (JVM) acts as the garbage collector that keeps a track of the memory
allocated to various objects and the objects being referenced. The JVM performs garbage
collection when it needs more memory to continue execution of programs.
The various methods of the Runtime class used in memory management are:
• static Runtime getRuntime(): Returns the current runtime object.
• void gc(): Invokes garbage collection.
• long totalMemory(): Returns the total number of bytes of memory available in JVM.
• long freeMemory(): Returns the amount of memory free in the JVM.
To run the garbage collector explicitly, you need to perform two steps:
1. Create an object of the Java Runtime class. The following syntax shows how to create
an object of the Java Runtime class:
Runtime r = Runtime.getRuntime();
2. Invoke the gc() method of the Runtime() class to request the garbage collection. The
following syntax shows how to invoke the garbage collector:
r.gc();
In order to understand how the automatic garbage collector finds objects whose storage
should be reclaimed, we need to look at the activity going on in the JVM. Java provides thread-
based multitasking, meaning there can be several threads executing in the JVM, each doing its
own task. A thread is alive if it has not completed its execution. Each live thread has its own
runtime stack; the runtime stack contains activation records of methods that are currently active.
Skarifahmed@gmail.com
54
Local references declared in a method can always be found in the method's activation record,
on the runtime stack associated with the thread in which the method is called. Objects, on the
other hand, are always created in the heap. If an object has a field reference, then the field is to
be found inside the object in the heap, and the object denoted by the field reference is also to
be found in the heap.
The following figure shows two live threads (t1 and t2) and their respective runtime stacks with
the activation records. The diagram shows which objects in the heap are referenced by local
references in the method activation records. The diagram also shows field references in objects,
which denote other objects in the heap. Some objects have several aliases.
Skarifahmed@gmail.com
55
Run-Time Stack HEAP
An object in the heap is said to be reachable if it is denoted by any local reference in a runtime
stack. Additionally, any object that is denoted by a reference in a reachable object is also said to
be reachable. Reachability is a transitive relation. Thus, a reachable object has at least one
chain of reachable references from the runtime stack. Any reference that makes an object
reachable is called a reachable reference. An object that is not reachable is said to be
unreachable. A reachable object is alive. It is accessible by the live thread that owns the runtime
stack. Note that an object can be accessible by more than one thread. Any object that is not
accessible by a live thread is a candidate for garbage collection. When an object becomes
unreachable and is waiting for its memory to be reclaimed, it is said to be eligible for garbage
collection. An object is eligible for garbage collection if all references denoting it are in eligible
objects. Eligible objects do not affect the future course of program execution. When the garbage
collector runs, it finds and reclaims the storage of eligible objects. However, garbage collection
does not necessarily occur as soon as an object becomes unreachable. From the figure we see
Skarifahmed@gmail.com
56
that objects o4, o5, o11, o12, o14, and o15 all have reachable references. Objects o13 and
o16 have no reachable references and are, therefore, eligible for garbage collection.
So, we can conclude that if a composite object becomes unreachable, then its constituent
objects also become unreachable, barring any reachable references to the constituent objects.
Although objects o1, o2, and o3 form a circular list, they do not have any reachable references.
Thus, these objects are all eligible. On the other hand, objects o5, o6, and o7 form a linear list,
but they are all reachable, as the first object in the list, 05, is reachable. Objects o8, o10, o11,
and o9 also form a linear list (in that order), but not all objects in the list are reachable. Only
objects o9 and o11 are reachable, as object o11 has a reachable reference. Objects o8 and
o10 are eligible for garbage collection.
b) What are the ways to make an object eligible for garbage collection?
Answer:
• Nulling a Reference:
An object becomes eligible for garbage collection when there are no more reachable
references to it. Obviously, if there are no reachable references, it doesn't matter what
happens to the object. For our purposes it is just floating in space, unused, inaccessible,
and no longer needed.
The first way to remove a reference to an object is to set the reference variable that refers
to the object to null. Examine the following code:
The StringBuffer object with the value hello is assigned to the reference variable sb in the
third line. To make the object eligible (for GC), we set the reference variable sb to null,
Skarifahmed@gmail.com
57
which removes the single reference that existed to the StringBuffer object. Once line 6
has run, our happy little hello StringBuffer object is doomed, eligible for garbage
collection.
We can also decouple a reference variable from an object by setting the reference variable
to refer to another object. Examine the following code:
class GarbageTruck {
public static void main(String [] args) {
StringBuffer s1 = new StringBuffer("hello");
StringBuffer s2 = new StringBuffer("goodbye");
System.out.println(s1);
// At this point the StringBuffer "hello" is not eligible
s1 = s2; // Redirects s1 to refer to the "goodbye" object
// Now the StringBuffer "hello" is eligible for collection
}
}
Objects that are created in a method also need to be considered. When a method is
invoked, any local variables created exist only for the duration of the method. Once the
method has returned, the objects created in the method are eligible for garbage collection.
There is an obvious exception, however. If an object is returned from the method, its
reference might be assigned to a reference variable in the method that called it; hence, it
will not be eligible for collection. Examine the following code:
import java.util.Date;
public class GarbageFactory {
public static void main(String [] args) {
Date d = getDate();
doComplicatedStuff();
System.out.println("d = " + d) ;
}
Skarifahmed@gmail.com
58
return d2;
}
}
In the preceding example, we created a method called getDate() that returns a Date
object. This method creates two objects: a Date and a StringBuffer containing the date
information. Since the method returns the Date object, it will not be eligible for collection
even after the method has completed. The StringBuffer object, though, will be eligible,
even though we didn't explicitly set the now variable to null.
• Isolating a Reference
There is another way in which objects can become eligible for garbage collection, even if
they still have valid references! We call this scenario "islands of isolation."
A simple example is a class that has an instance variable that is a reference variable to
another instance of the same class. Now imagine that two such instances exist and that
they refer to each other. If all other references to these two objects are removed, then
even though each object still has a valid reference, there will be no way for any live
thread to access either object. When the garbage collector runs, it can usually discover
any such islands of objects and remove them. As you can imagine, such islands can
become quite large, theoretically containing hundreds of objects. Examine the following
code:
i2.i = i3 // i2 refers to i3
i3.i = i4 // i3 refers to i4
i4.i = i2 // i4 refers to i2
i2 = null
i3 = null
Skarifahmed@gmail.com
59
i4 = null
When the code reaches // do complicated, the three Island objects (previously known as
i2,i3, and i4) have instance variables so that they refer to each other, but their links to the
outside world (i2, i3, and i4) have been nulled. These three objects are eligible for
garbage collection.
This covers everything you will need to know about making objects eligible for garbage
collection. The following figure discusses the concepts of objects without references and
islands of isolation.
Skarifahmed@gmail.com
60
Answer: The job of freeing up the memory allocated to objects is that of a garbage
collector. When the garbage collector determines that an object is no longer referenced it
automatically runs a special destructor function called “Finalize”. However we have no way
to determine when the garbage collector will call the Finalize method. We can only be sure
that it will be called at some time after the last reference to the object is released.
• any exception thrown by finalize() during garbage collection halts the finalization but is
otherwise ignored
• finalize() is never run more than once on any object
Skarifahmed@gmail.com
61
java.io
a) What is the difference between File class and RandomAccessFile class?
The File class can only provide File properties. But cannot actually read or write those
files. RandomAccessFile provides methods to read and write to files.
File Class
The File class in the java.io package provides various methods to access the properties
of a file or a directory, such as file permissions, date and time of creation, and path of a
directory.
Constructors to create an instance of the File class
• File(File dirObj, String filename): Creates a new instance of the File class. The dirObj
argument is a File object that specifies a directory. The filename argument specifies
the name of the file.
• File(String directoryPath): Creates a new instance of the File class. The
directoryPath argument specifies the path of the file. • File(String directoryPath,
String filename): Creates a new instance of the File class. The argument
directoryPath specifies the path of the file, and the filename argument specifies the
name of the file.
Methods of the File class
• String getName():Retrieves the name of the specified file.
• String getParent():Retrieves the name of the parent directory.
• String getPath():Retrieves the path of the specified file.
• String[] list():Displays the list of files and directories inside the specified directory.
Accessing File Properties
Skarifahmed@gmail.com
62
• boolean delete(): The delete() method is used to delete a specified file. The delete()
method returns true, if it successfully deletes the file otherwise false.
• boolean renameTo(File newName):The renameTo() method is used to rename a
specified file. the renameTo() method returns true, if it successfully renames the file
otherwise false.
RandomAccessFile Class
You access the random files in Java by using the RandomAccessFile class. The
constructor throws FileNotFoundException, if the RandomAccessFile class is unable to retrieve
the name of the file to be created.
Constructors to create an instance of the RandomAccessFile class:
• RandomAccessFile(File fileObj, String mode):Creates an instance of the random
access file.
• RandomAccessFile(String name, String mode):Creates an instance of the random
access file.
Methods of the RandomAccessFile class:
• void close() throws IOException: Closes the random access file and releases the
system resources, such as streams and file pointers associated with the file.
• long getFilePointer() throws IOException:Retrieves the current position of the file
pointer in the specified file.
• int skipBytes(int n) throws IOException: Ignores the number of bytes from a file
specified by the n argument.
• long length() throws IOException: Retrieves the length of the specified file.
• void seek(long position) throws IOException: Sets the current location of the file
pointer at the specified position.
• int read() : Reads a byte of data from this file.
• int read(byte[] b): Reads up to b.length bytes of data from this file into an array of
bytes.
• int read(byte[] b, int off, int len): Reads up to len bytes of data from this file into an
array of bytes.
• xxx readxxx(): Reads a xxx type data from this file.[xxx is the primitive data type ex:
int readInt()]
• void write(byte[] b) : Writes b.length bytes from the specified byte array to this file,
starting at the current file pointer.
• void write(byte[] b, int off, int len) : Writes len bytes from the specified byte array
starting at offset off to this file.
• void write(int b) : Writes the specified byte to this file.
Skarifahmed@gmail.com
63
• void writexxx(xxx v) : Writes a xxx type data to the file. [xxx is the primitive data type
ex: void writeInt(int x)]
b) What is stream in java? How many types of streams are there in java? Define them.
Give Example of each.
Answer: Stream is something by which a java program can read data from source
and write data in the destination. In other words a stream is a sequence of data of
undetermined length. It may be a local files or data that is coming from other computers on
the network or any external device. Java has a concept of working with so-called streams of
data. After physical data storage is mapped to a logical stream, a Java program reads/writes
data from/to this stream serially - byte after byte, character after character. There
are two types of stream
• byte streams (InputStream, OutputStream)
• character streams (Reader and Writer).
Classes that work with streams are located in the package java.io.
Here's the sequence of steps needed to work with a stream:
1. Open a stream that points at a specific data source: a file, a socket, URL, etc.
2. Read or write data from/to this stream.
3. Close the stream.
Byte stream
The byte stream classes provide a rich environment for handling byte-oriented I/O. A byte stream can be
used with any type of object, including binary data. This versatility makes byte streams important to many
types of programs. The byte stream classes are topped by InputStream and OutputStream. ByteStream
read or Write one byte at a time.
Skarifahmed@gmail.com
64
Character Stream
While the byte stream classes provide sufficient functionality to handle any type of I/O operation, they
cannot work directly with Unicode characters. Since one of the main purposes of Java is to support the
"write once, run anywhere" philosophy, it was necessary to include direct I/O support for characters. The
top of the character stream hierarchies are the Reader and Writer abstract classes. Character Stream
Read or Write two byte at a time(in Unicode Charcter format).
Skarifahmed@gmail.com
65
vii. FileReader
viii. FileWriter
ix. BufferedReader
x. BufferedWriter
xi. ByteArrayInputStream
xii. ByteArrayOutputStream
Answer:
i. FileInputStream: The FileInputStream class creates an InputStream that you can use to
read bytes from a file. Its two most common constructors are shown here:
• FileInputStream(String filepath)
• FileInputStream(File fileObj)
Either can throw a FileNotFoundException. Here, filepath is the full path name of a file,
and fileObj is a File object that describes the file. The following example creates two
FileInputStreams that use the same disk file and each of the two constructors:
Although the first constructor is probably more commonly used, the second allows us to closely
examine the file using the File methods, before we attach it to an input stream.
When a FileInputStream is created, it is also opened for reading. FileInputStream overrides six
of the methods in the abstract class InputStream. The mark( ) and reset( ) methods are not
overridden, and any attempt to use reset( ) on a FileInputStream will generate an IOException.
The next example shows how to read a single byte, an array of bytes, and a subrange
array of bytes. It also illustrates how to use available( ) to determine the number of bytes
remaining, and how to use the skip( ) method to skip over unwanted bytes. The program reads
its own source file, which must be in the current directory.
// Demonstrate FileInputStream.
import java.io.*;
class FileInputStreamDemo {
public static void main(String args[]) throws Exception {
int size;
InputStream f = new
FileInputStream("FileInputStreamDemo.java");
Skarifahmed@gmail.com
66
Skarifahmed@gmail.com
67
ii. DataInputStream: An input stream that contains methods for reading the Java
standard data types. If you are expecting to work with a stream of a known data
structure, i.e. two integers, three floats and a double, use the DataInputStream. A
method call readInt() will read the whole integer number (4 bytes ) at once, and the
readLong() will get you a long number (8 bytes).
The DataInput stream is just a filter. We are building a "pipe" from the following
fragments:
try {
int num1 = data.readInt();
int num2 = data.readInt();
float num2 = data.readFloat();
float num3 = data.readFloat();
float num4 = data.readFloat();
Skarifahmed@gmail.com
68
The following example contrives a situation where we can use mark( ) to remember
where we are in an input stream and later use reset( ) to get back there. This example is parsing
a stream for the HTML entity reference for the copyright symbol. Such a reference begins with an
ampersand (&) and ends with a semicolon (;) without any intervening whitespace. The sample
input has two ampersands to show the case where the reset( ) happens and where it does not.
Skarifahmed@gmail.com
69
Skarifahmed@gmail.com
70
Use of mark( ) is restricted to access within the buffer. This means that you can only specify a parameter
to mark( ) that is smaller than the buffer size of the stream.
iv. FileOutputStream: FileOutputStream creates an OutputStream that you can use to write
bytes to a file. Its most commonly used constructors are shown here:
• FileOutputStream(String filePath)
• FileOutputStream(File fileObj)
• FileOutputStream(String filePath, boolean append)
They can throw an IOException or a SecurityException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, the file is opened in
append mode.
Creation of a FileOutputStream is not dependent on the file already existing. FileOutputStream
will create the file before opening it for output when you create the object. In the case where you
attempt to open a read-only file, an IOException will be thrown.
The following example creates a sample buffer of bytes by first making a String and then using
the getBytes( ) method to extract the byte array equivalent. It then creates three files. The first,
file1.txt, will contain every other byte from the sample. The second, file2.txt, will contain the
entire set of bytes. The third and last, file3.txt, will contain only the last quarter. Unlike the
FileInputStream methods, all of the FileOutputStream methods have a return type of void. In
the case of an error, these methods will throw an IOException.
// Demonstrate FileOutputStream.
import java.io.*;
class FileOutputStreamDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\\n"
+ " to come to the aid of their country\\n"
+ " and pay their due taxes.";
byte buf[] = source.getBytes();
OutputStream f0 = new FileOutputStream("file1.txt");
for (int i=0; i < buf.length; i += 2) {
f0.write(buf[i]);
}
f0.close();
OutputStream f1 = new FileOutputStream("file2.txt");
f1.write(buf);
f1.close();
OutputStream f2 = new FileOutputStream("file3.txt");
Skarifahmed@gmail.com
71
f2.write(buf,(buf.length)-(buf.length/4),buf.length/4);
f2.close();
}
}
Here are the contents of each file after running this program.
First,
file1.txt:
Nwi h iefralgo e
t oet h i ftercuty n a hi u ae.
Next, file2.txt:
Now is the time for all good men
to come to the aid of their country
and pay their due taxes.
Finally, file3.txt:
nd pay their due taxes.
v. DataOutputStream: An output stream that contains methods for writing the Java standard
data types. DataOutputStream give us the power to write primitive data type to a media
such as file. This class have the corresponding method to write primitive data.
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
Skarifahmed@gmail.com
72
int cityIdB = 2;
String cityNameB = "Salt Lake City";
int cityPopulationB = 250000;
float cityTempB = 10.45f;
try {
/*
Create an instance of FileOutputStream with cities.dat
as the file name to be created. Then we pass the input
stream object in the DataOutputStream constructor.
*/
FileOutputStream fos = new FileOutputStream("cities.dat");
DataOutputStream dos = new DataOutputStream(fos);
/* Below we write some data to the cities.dat.
DataOutputStream class have various method that allow
us to write primitive type data and string. There are
method called writeInt(), writeFloat(), writeUTF(),
etc.
*/
dos.writeInt(cityIdA);
dos.writeUTF(cityNameA);
dos.writeInt(cityPopulationA);
dos.writeFloat(cityTempA);
dos.writeInt(cityIdB);
dos.writeUTF(cityNameB);
dos.writeInt(cityPopulationB);
dos.writeFloat(cityTempB);
dos.flush();
dos.close();
/*
Now we have a cities.dat file with some data in it. Next
you'll see how easily we can read back this data and
display it. Just like the DataOutputStream the
DataInputStream class have the corresponding read methods
to read data from the file. Some of the method names are
readInt(), readFloat(), readUTF(), etc.
*/
FileInputStream fis = new FileInputStream("cities.dat");
Skarifahmed@gmail.com
73
vii. FileReader : The FileReader class creates a Reader that you can use to read the contents of
a file. Its two most commonly used constructors are shown here:
• FileReader(String filePath)
• FileReader(File fileObj)
Either can throw a FileNotFoundException. Here, filePath is the full path name of a file, and fileObj is a
File object that describes the file.
Skarifahmed@gmail.com
74
List of Methods
Method Description
abstract void close( ) Closes the output stream. Further write attempts
will generate an IOException.
abstract void flush( ) Finalizes the output state so that any buffers are
cleared. That is, it flushes the output buffers
Writes a single character to the invoking output
void write(int ch) stream. Note that the parameter is an int, which
allows you to call write with expressions without
having to cast them back to char.
void write(char buffer[ ]) Writes a complete array of characters to the
invoking output stream
Writes a subrange of numChars characters from the
abstract void write(char buffer[ ], int offset, int array buffer, beginning at buffer[offset] to the
numChars) invoking
output stream.
.
.
The following example shows how to read lines from a file and print these to the standard output stream.
It reads its own source file, which must be in the current directory.
// Demonstrate FileReader.
import java.io.*;
class FileReaderDemo {
public static void main(String args[]) throws Exception {
FileReader fr = new FileReader("FileReaderDemo.java");
BufferedReader br = new BufferedReader(fr);
String s;
while((s = br.readLine()) != null) {
System.out.println(s);
}
fr.close();
}
Skarifahmed@gmail.com
75
viii. FileWriter: FileWriter creates a Writer that you can use to write to a file. Its most commonly
used constructors are shown here:
• FileWriter(String filePath)
• FileWriter(String filePath, boolean append)
• FileWriter(File fileObj)
They can throw an IOException or a SecurityException. Here, filePath is the full path name of a
file, and fileObj is a File object that describes the file. If append is true, then output is appended
to the end of the file. Creation of a FileWriter is not dependent on the file already existing.
FileWriter will create the file before opening it for output when you create the object. In the case
where you attempt to open a read-only file, an IOException will be thrown. The following
example is a character stream version of an example shown earlier when FileOutputStream was
discussed. This version creates a sample buffer of characters by first making a String and then
using the getChars( ) method to extract the character array equivalent. It then creates three files.
The first, file1.txt, will contain every other character from the sample. The second, file2.txt, will
contain the entire set of characters. Finally, the third, file3.txt, will contain only the last quarter.
// Demonstrate FileWriter.
import java.io.*;
class FileWriterDemo {
public static void main(String args[]) throws Exception {
String source = "Now is the time for all good men\\n"
+ " to come to the aid of their country\\n"
+ " and pay their due taxes.";
char buffer[] = new char[source.length()];
source.getChars(0, source.length(), buffer, 0);
FileWriter f0 = new FileWriter("file1.txt");
for (int i=0; i < buffer.length; i += 2) {
f0.write(buffer[i]);
}
f0.close();
FileWriter f1 = new FileWriter("file2.txt");
f1.write(buffer);
f1.close();
FileWriter f2 = new FileWriter("file3.txt");
f2.write(buffer,buffer.lengthbuffer.length/4,buffer.length/4);
f2.close();
}
}
Skarifahmed@gmail.com
76
Skarifahmed@gmail.com
77
} else
System.out.print((char) c);
break;
case ' ':
if (marked) {
marked = false;
f.reset();
System.out.print("&");
} else
System.out.print((char) c);
break;
default:
if (!marked)
System.out.print((char) c);
break;
}
}
}
}
Skarifahmed@gmail.com
78
class ByteArrayInputStreamDemo {
public static void main(String args[]) throws IOException {
String tmp = "abcdefghijklmnopqrstuvwxyz";
byte b[] = tmp.getBytes();
ByteArrayInputStream input1 = new ByteArrayInputStream(b);
ByteArrayInputStream input2 = new ByteArrayInputStream(b,
0,3);
}
}
The input1 object contains the entire lowercase alphabet, while input2 contains only the first
three letters. A ByteArrayInputStream implements both mark( ) and reset( ). However, if mark( )
has not been called, then reset( ) sets the stream pointer to the start of the stream-which in this
case is the start of the byte array passed to the constructor. The next example shows how to use
the reset( ) method to read the same input twice. In this case, we read and print the letters "abc"
once in lowercase and then again in uppercase.
import java.io.*;
class ByteArrayInputStreamReset {
public static void main(String args[]) throws IOException {
String tmp = "abc";
byte b[] = tmp.getBytes();
ByteArrayInputStream in = new ByteArrayInputStream(b);
for (int i=0; i<2; i++) {
int c;
while ((c = in.read()) != -1) {
if (i == 0) {
System.out.print((char) c);
} else {
System.out.print(Character.toUpperCase((char) c));
}
}
System.out.println();
in.reset();
}
}
}
This example first reads each character from the stream and prints it as is, in lowercase. It then
resets the stream and begins reading again, this time converting each character to uppercase
before printing.
Here's the output:
abc
Skarifahmed@gmail.com
79
ABC
Skarifahmed@gmail.com
80
Answer:
in: The "standard" input stream. This stream is already open and ready to supply input
data. Typically this stream corresponds to keyboard input or another input source specified
by the host environment or user. It is an object of InputStream class which is declared in System
class having modifier final and static.
out: The "standard" output stream. This stream is already open and ready to accept output
data. Typically this stream corresponds to display output or another output destination
specified by the host environment or user. It is an object of PrintStream class which is declared in
System class having modifier final and static.
For simple stand-alone Java applications, a typical way to write a line of output data is:
System.out.println(data)
Skarifahmed@gmail.com
81
Collection Framework
A collection allows a group of objects to be treated as a single unit. Arbitrary objects can be
stored, retrieved, and manipulated as elements of collections. Program design often requires
handling of groups of objects. The collections framework presents a set of standard utility
Skarifahmed@gmail.com
82
classes for managing such collections. This framework is provided in the java.util package and
comprises three main parts:
• The core interfaces: It allows collections to be manipulated independently of their
implementation. These interfaces define the common functionality exhibited by
collections and facilitate data exchange between collections.
• Concrete classes: These are specific implementations of the core interfaces,
providing data structures that a program can use readily.
• utility methods: An assortment of static utility methods that can be used to perform
various operations on collections, such as sorting and searching, or creating customized
collections.
Skarifahmed@gmail.com
83
SortedSet The SortedSet interface extends the Set interface to provide the required functionality for TreeSet
maintaining a set in which the elements are stored in some sorted order.
List The List interface extends the Collection interface to maintain a sequence of elements that ArrayList
need not be unique. Vector
LinkedList
Map A basic interface that defines operations for maintaining mappings of keys to values. HashMap
Hashtable
LinkedHashMap
SortedMap Extends the Map interface for maps that maintain their mappings sorted in key order. TreeMap
The elements in a Set must be unique, that is, no two elements in the set can be equal.
The order of elements in a List is retained, and individual elements can be accessed according
to their position in the list.
Map interface does not extend the Collection interface because conceptually, a map is
not a collection. A map does not contain elements. It contains mappings (also called entries)
from a set of key objects to a set of value objects. A key can, at most, be associated with one
value. As the name implies, the SortedMap interface extends the Map interface to maintain its
mappings sorted in key order.
None of the concrete implementations inherit directly from the Collection interface. The
abstract classes provide the basis on which concrete classes are implemented. All the concrete
classes implement the Serializable and the Cloneable interfaces; therefore, the objects of these
classes can be serialized and also cloned.
Utility Methods:
The Collection interface is used to represent any group of objects, or elements. Here is a list
of the public methods of the Collection Interface.
Skarifahmed@gmail.com
84
operation).
void clear()
Removes all of the elements from this collection (optional operation).
boolean contains(Object o)
Returns true if this collection contains the specified element.
boolean containsAll(Collection c)
Returns true if this collection contains all of the elements in the specified
collection.
boolean equals(Object o)
Compares the specified object with this collection for equality.
boolean isEmpty()
Returns true if this collection contains no elements.
Iterator iterator()
Returns an iterator over the elements in this collection.
boolean remove(Object o)
Removes a single instance of the specified element from this collection, if it is
present (optional operation).
boolean removeAll(Collection c)
Removes all this collection's elements that are also contained in the specified
collection (optional operation).
int size()
Returns the number of elements in this collection.
Iterator Interface:
The iterator() method of the Collection interface returns an Iterator. An Iterator is similar to
the Enumeration interface; Iterators differ from enumerations in two ways:
1.Iterators allow the caller to remove elements from the underlying collection during the
iteration with well-defined semantics.
2. Method names have been improved.
boolean hasNext()
Returns true if the iteration has more elements.
Object next()
Returns the next element in the iteration.
void remove()
Removes from the underlying collection the last element returned by the iterator
(optional operation).
The remove method is optionally suported by the underlying collection. When called and
supported, the element returned by the last next() call is removed.
Skarifahmed@gmail.com
85
List Interface:
This is an ordered collection (also known as a sequence). The List interface extends the
Collection interface to define an ordered collection, permitting duplicates. The user of this
interface has precise control over where in the list each element is inserted. The user can
access elements by their integer index (position in the list), and search for elements in the
list. Some methods are added into List interface for easy to handle i.e.
Unlike sets, lists typically allow duplicate elements. More formally, lists typically allow pairs
Skarifahmed@gmail.com
86
of elements e1 and e2 such that e1.equals(e2), and they typically allow multiple null
elements if they allow null elements at all. It is not inconceivable that someone might wish
to implement a list that prohibits duplicates, by throwing runtime exceptions when the user
attempts to insert them, but we expect this usage to be rare.
The List interface provides four methods for positional (indexed) access to list elements.
Lists (like Java arrays) are zero based. Note that these operations may execute in time
proportional to the index value for some implementations (the LinkedList class, for
example). Thus, iterating over the elements in a list is typically preferable to indexing
through it if the caller does not know the implementation.
The List interface provides a special iterator, called a ListIterator, that allows element
insertion and replacement, and bidirectional access in addition to the normal operations that
the Iterator interface provides. A method is provided to obtain a list iterator that starts at a
specified position in the list.
The List interface provides two methods (indexOf(),lastIndexOf()) to search for a specified
object. From a performance standpoint, these methods should be used with caution. In
many implementations they will perform costly linear searches.
Set Interface:
The set interface extends the Collection interface and, by definition, forbids duplicates within
the collection. All the original methods are present and no new method is introduced. The
concrete Set implementation classes rely on the equals() method of the object added to
check for equality.
SortedSet Interface:
The Collection Framework provides a special Set interface for maintaining elements in a
sorted order called SortedSet.
Comparator comparator()
Returns the comparator associated with this sorted set, or null if it uses its
elements' natural ordering.
Object first()
Returns the first (lowest) element currently in this sorted set.
SortedSet headSet(Object toElement)
Returns a view of the portion of this sorted set whose elements are strictly less
than toElement.
Object last()
Returns the last (highest) element currently in this sorted set.
SortedSet subSet(Object fromElement, Object toElement)
Returns a view of the portion of this sorted set whose elements range from
fromElement, inclusive, to toElement, exclusive.
Skarifahmed@gmail.com
87
The interface provides access methods to the ends of the set as well to subsets of the set.
When working with subsets of the list, changes to the subset are reflected in the source set.
In addition changes to the source set are reflected in the subset. This works because
subsets are identical by elements at the end point, not indices. In addition, if the
formElement is part of the source set, it is part of the subset. However, if the toElement is
part of the source ser, it is not part of the subset. If you would like a particular to-element
to be in the subset, you must find the next element. In the case of a string, the next
element is the same strong with a null character appended (string+”\0”).;
The element added to a SortedSet must either implement Comparable or you must provide
a Comparator to the constructor to its implementation class: TreeSet.
This example uses the reverse order Comprator available from the Collection calss.
Map Interface:
The Map interface is not an extension of Collection interface. Instead the interface starts of
it’s own interface hierarchy, for maintaining key-value associations. The interface describes
a mapping from keys to values, without duplicate keys, by definition.
The Map interface provides three collection views, which allow a map's contents to be
viewed as a set of keys, collection of values, or set of key-value mappings. The order of a
map is defined as the order in which the iterators on the map's collection views return their
elements. Some map implementations, like the TreeMap class, make specific guarantees as
to their order; others, like the HashMap class, do not.
void clear()
Removes all mappings from this map (optional operation).
boolean containsKey(Object key)
Skarifahmed@gmail.com
88
Returns true if this map contains a mapping for the specified key.
boolean equals(Object o)
Compares the specified object with this map for equality.
Object get(Object key)
Returns the value to which this map maps the specified key.
boolean isEmpty()
Returns true if this map contains no key-value mappings.
Set keySet()
Returns a set view of the keys contained in this map.
Object put(Object key, Object value)
Associates the specified value with the specified key in this map (optional
operation).
void putAll(Map t)
Copies all of the mappings from the specified map to this map (optional
operation).
Object remove(Object key)
Removes the mapping for this key from this map if it is present (optional
operation).
int size()
Returns the number of key-value mappings in this map.
Collection values()
Returns a collection view of the values contained in this map.
The interface methods can be broken down into three sets of operations: altering, querying
and providing alternative views
The alteration operation allows you to add and remove key-value pairs from the map. Both
the key and value can be null. However you should not add a Map to itself as a key or value.
Object put(Object key, Object value)
Object remove(Object key)
void putAll(Map t)
void clear()
The query operations allow you to check on the contents of the map
Object get(Object key)
boolean containsKey(Object key)
boolean containsValue(Object value)
int size()
Skarifahmed@gmail.com
89
boolean isEmpty()
The set methods allow you to work with the group ofkeys or values as a collection
Set keySet()
Collection values()
Set entrySet()
SortedMap Interface:
The Collection Framework provides a special Map interface for maintaining elements in a
sorted order called SortedMap.
The interface provides access methods to the ends of the map as well to subsets of the set.
Working with a SortedMap is just like a SortedSet, except the sort is done on the map keys.
The implementation class provided by the Collection Framework is a TreeMap.
Comparator comparator()
Returns the comparator associated with this sorted map, or null if it uses its
keys' natural ordering.
Object firstKey()
Returns the first (lowest) key currently in this sorted map.
SortedMap headMap(Object toKey)
Returns a view of the portion of this sorted map whose keys are strictly less
than toKey.
Object lastKey()
Returns the last (highest) key currently in this sorted map.
SortedMap subMap(Object fromKey, Object toKey)
Returns a view of the portion of this sorted map whose keys range from
fromKey, inclusive, to toKey, exclusive.
There are two general-purpose List implementations in the Collection Framework, ArrayList
and LinkedList, which of the two List implementations you use depends on your specific
needs. If you need to support random access, without inserting or removing elements from
any place to other than the end, then ArrayList offers you the optimal collection, the
LinkedList class provides uniformly named methods to get, remove and insert an element at
the beginning and end of the list.
Skarifahmed@gmail.com
90
Each ArrayList instance has a capacity. The capacity is the size of the array used to store the
elements in the list. It is always at least as large as the list size. As elements are added an
ArrayList, its capacity grows automatically. The details of the growth policy are not specified
beyond the fact that adding an element has constant amortized time cost.
An application can increase the capacity of an ArrayList instance before adding a large
number of elements using the ensureCapacity operation. This may reduce the amount of
incremental reallocation.
Note that these implementation is not synchronized. If multiple threads access a set
concurrently, and at least one of the threads modifies the set, it must be synchronized
externally. This is typically accomplished by synchronizing on some object that naturally
encapsulates the set. If no such object exists, the set should be "wrapped" using the
Collections.synchronizedSet method. This is best done at creation time, to prevent
accidental unsynchronized access to the set:
A Vector is an historical collection class that acts like a growable array, but can store
heterogeneous data elements.
The Stack class represents a last-in-first-out (LIFO) stack of objects. It extends class Vector
with five operations that allow a vector to be treated as a stack. The usual push and pop
operations are provided, as well as a method to peek at the top item on the stack, a method
to test for whether the stack is empty, and a method to search the stack for an item and
discover how far it is from the top.
Skarifahmed@gmail.com
91
Date Class:
The class Date represents a specific instant in time, with millisecond precision. It allowed the
understanding of dates as year, month, day, hour, minute, and second values. It also allowed
the formatting and parsing of date strings. DateFormat class should be used to format and
parse date strings.
In all methods of class Date that accept or return year, month, date, hours, minutes, and
seconds values, the following representations are used:
In all cases, arguments given to methods for these purposes need not fall within the indicated
ranges; for example, a date may be specified as January 32 and is interpreted as meaning
February 1
Constructors
Date()
Allocates a Date object and initializes it so that it represents the time at which it was
allocated, measured to the nearest millisecond.
Date(int year, int month, int date)
Date(int year, int month, int date, int hrs, int min)
Skarifahmed@gmail.com
92
Date(int year, int month, int date, int hrs, int min, int sec)
Date(long date)
Allocates a Date object and initializes it to represent the specified number of milliseconds
since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.
Date(String s)
Skarifahmed@gmail.com
93
Methods Summery
boolean after(Date when)
Tests if this date is after the specified date.
boolean before(Date when)
Tests if this date is before the specified date.
Object clone()
Return a copy of this object.
int compareTo(Date anotherDate)
Compares two Dates for ordering.
int compareTo(Object o)
Compares this Date to another Object.
boolean equals(Object obj)
Compares two dates for equality.
int getDay()Returns the day of the week represented by this date. The
returned value (0 = Sunday, 1 = Monday, 2 = Tuesday, 3 = Wednesday,
4 = Thursday, 5 = Friday, 6 = Saturday) represents the day of the
week that contains or begins with the instant in time represented by
this Date object, as interpreted in the local time zone.
This can be done using Calendar.get(Calendar.DAY_OF_WEEK).
int getHours()Returns the hour represented by this Date object. The
returned value is a number (0 through 23) representing the hour within
the day that contains or begins with the instant in time represented by
this Date object, as interpreted in the local time zone.
This can be done using Calendar.get(Calendar.HOUR_OF_DAY).
int getMinutes()Returns the number of minutes past the hour represented
by this date, as interpreted in the local time zone. The value returned is
between 0 and 59.
This can be done using Calendar.get(Calendar.MINUTE).
int getMonth()Returns a number representing the month that contains or
begins with the instant in time represented by this Date object. The
value returned is between 0 and 11, with the value 0 representing
January
This can be done using Calendar.get(Calendar.MONTH).
int getSeconds()Returns the number of seconds past the minute
represented by this date. The value returned is between 0 and 61. The
Skarifahmed@gmail.com
94
values 60 and 61 can only occur on those Java Virtual Machines that
take leap seconds into account.
This can be done using Calendar.get(Calendar.SECOND).
long getTime()
Returns the number of milliseconds since January 1, 1970,
00:00:00 GMT represented by this Date object.
int getTimezoneOffset()Returns the offset, measured in minutes, for the
local time zone relative to UTC that is appropriate for the time
represented by this Date object.
This can be done using (Calendar.get(Calendar.ZONE_OFFSET)
+ Calendar.get(Calendar.DST_OFFSET)) / (60 * 1000).
int getYear()Returns a value that is the result of subtracting 1900 from
the year that contains or begins with the instant in time represented by
this Date object, as interpreted in the local time zone
This can be done using Calendar.get(Calendar.YEAR) - 1900.
static long parse(String s) parse into long
This can be done using DateFormat.parse(String s).
void setDate(int date) Sets the day of the month of this Date object to the
specified value. This Date object is modified so that it represents a
point in time within the specified day of the month, with the year,
month, hour, minute, and second the same as before, as interpreted in
the local time zone
This can be done using Calendar.set(Calendar.DAY_OF_MONTH,
int date).
void setHours(int hours) Sets the hour of this Date object to the specified
value. This Date object is modified so that it represents a point in time
within the specified hour of the day, with the year, month, date, minute,
and second the same as before, as interpreted in the local time zone.
This can be done using Calendar.set(Calendar.HOUR_OF_DAY, int
hours).
void setMinutes(int minutes) Sets the minutes of this Date object to the
specified value. This Date object is modified so that it represents a
point in time within the specified minute of the hour, with the year,
month, date, hour, and second the same as before, as interpreted in
the local time zone.
This can be done using Calendar.set(Calendar.MINUTE, int
minutes).
void setMonth(int month) Sets the month of this date to the specified
value.
This can be done using Calendar.set(Calendar.MONTH, int
month).
Skarifahmed@gmail.com
95
void setSeconds(int seconds) Sets the seconds of this Date to the specified
value. This Date object is modified so that it represents a point in time
within the specified second of the minute, with the year, month, date,
hour, and minute the same as before, as interpreted in the local time
zone
This can be done using Calendar.set(Calendar.SECOND, int
seconds).
void setTime(long time)
Sets this Date object to represent a point in time that is time
milliseconds after January 1, 1970 00:00:00 GMT.
void setYear(int year) Sets the year of this Date object to be the specified
value plus 1900. This Date object is modified so that it represents a
point in time within the specified year, with the month, date, hour,
minute, and second the same as before, as interpreted in the local time
zone
This can be done using Calendar.set(Calendar.YEAR, year +
1900).
String toGMTString() Creates a string representation of this Date object of
the form: d mon yyyy hh:mm:ss GMT
This can be done using DateFormat.format(Date date), using a
GMT TimeZone.
Properties Class:
The Properties class represents a persistent set of properties. The Properties can be saved to a
stream or loaded from a stream. Each key and its corresponding value in the property list is a
string.
A property list can contain another property list as its "defaults"; this second property list is
searched if the property key is not found in the original property list.
Because Properties inherits from Hashtable, the put and putAll methods can be applied to a
Properties object. Their use is strongly discouraged as they allow the caller to insert entries
whose keys or values are not Strings. The setProperty method should be used instead. If the
Skarifahmed@gmail.com
96
store or save method is called on a "compromised" Properties object that contains a non-String
key or value, the call will fail.
When saving properties to a stream or loading them from a stream, the ISO 8859-1 character
encoding is used. For characters that cannot be directly represented in this encoding, Unicode
escapes are used; however, only a single 'u' character is allowed in an escape sequence.
Constructors
Properties()
Creates an empty property list with no default values.
Properties(Properties defaults)
Creates an empty property list with the specified defaults.
Methods Summery
String getProperty(String key)
Searches for the property with the specified key in this property list.
String getProperty(String key, String defaultValue)
Searches for the property with the specified key in this property list.
void list(PrintStream out)
Reads a property list (key and element pairs) from the input stream.
Enumeration propertyNames()
Skarifahmed@gmail.com
97
Writes this property list (key and element pairs) in this Properties table to
the output stream in a format suitable for loading into a Properties table using
the load method.
StringTokenizer Class:
The string tokenizer class allows an application to break a string into tokens. The tokenization
method is much simpler than the one used by the StreamTokenizer class. The StringTokenizer
methods do not distinguish among identifiers, numbers, and quoted strings, nor do they
recognize and skip comments.
The set of delimiters (the characters that separate tokens) may be specified either at creation
time or on a per-token basis.
• If the flag is false, delimiter characters serve to separate tokens. A token is a maximal
sequence of consecutive characters that are not delimiters.
• If the flag is true, delimiter characters are themselves considered to be tokens. A token is
thus either one delimiter character, or a maximal sequence of consecutive characters
that are not delimiters.
A StringTokenizer object internally maintains a current position within the string to be tokenized.
Some operations advance this current position past the characters processed.
A token is returned by taking a substring of the string that was used to create the
StringTokenizer object.
The following is one example of the use of the StringTokenizer. The code:
import java.util.StringTokenizer;
Skarifahmed@gmail.com
98
}
}
this
is
a
test
StringTokenizer is a legacy class that is retained for compatibility reasons although its use is
discouraged in new code. It is recommended that anyone seeking this functionality use the split
method of String or the java.util.regex package instead.
The following example illustrates how the String.split method can be used to break up a string
into its basic tokens:
this
is
a
test
Skarifahmed@gmail.com
99
Constructors
StringTokenizer(String str)
Constructs a string tokenizer for the specified string.
StringTokenizer(String str, String delim)
Constructs a string tokenizer for the specified string.
Methods Summery
int countTokens()
Calculates the number of times that this tokenizer's nextToken method can be
called before it generates an exception.
boolean hasMoreElements()
Tests if there are more tokens available from this tokenizer's string.
Object nextElement()
Returns the same value as the nextToken method, except that its declared return
value is Object rather than String.
String nextToken()
ListIterator Interface:
An iterator for lists that allows the programmer to traverse the list in either direction, modify the
list during iteration, and obtain the iterator's current position in the list. A ListIterator has no
current element; its cursor position always lies between the element that would be returned by a
call to previous() and the element that would be returned by a call to next(). In a list of length
n, there are n+1 valid index values, from 0 to n, inclusive.
The remove() and set(Object) methods are not defined in terms of the cursor position; they are
defined to operate on the last element returned by a call to next() or previous().
Methods List
void add(Object o)
Returns true if this list iterator has more elements when traversing the list in the
forward direction.
boolean hasPrevious()
Returns true if this list iterator has more elements when traversing the list in the
reverse direction.
Object next()
Returns the index of the element that would be returned by a subsequent call to
next.
Object previous()
Returns the index of the element that would be returned by a subsequent call to
previous.
void remove()
Removes from the list the last element that was returned by next or previous
(optional operation).
void set(Object o)
Replaces the last element returned by next or previous with the specified
Skarifahmed@gmail.com
101
Example 1:
The following example shows how to use LinkedList class of the collection framework. At first
we create an instance of LinkedList. Then we add 4 elments into it and after that we fetch all the
elements from it using Iterator interface. Then we use some methods of the LinkedList class like
size(), addFirst(Object obj), addLast(Object obj), add(int index, Object obj), getFirst(), getLast(),
get(int index), clear(), remove() etc.
import java.util.*;
public class LinkedListExample{
public static void main(String[] args) {
System.out.println("Linked List Example!");
LinkedList <Integer>list = new LinkedList<Integer>();
int num1 = 11, num2 = 22, num3 = 33, num4 = 44;
int size;
Iterator iterator;
//Adding data in the list
list.add(num1);
list.add(num2);
list.add(num3);
list.add(num4);
size = list.size();
System.out.print( "Linked list data: ");
//Create a iterator
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
//Check list empty or not
Skarifahmed@gmail.com
102
if (list.isEmpty()){
System.out.println("Linked list is empty");
}
else{
System.out.println( "Linked list size: " + size);
}
System.out.println("Adding data at 1st location: 55");
//Add at the first place
list.addFirst(55);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at last location: 66");
//Adding last or append
list.addLast(66);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
System.out.println("Adding data at 3rd location: 99");
//Adding data at 3rd position
list.add(2,99);
System.out.print("Now the list contain: ");
iterator = list.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
Skarifahmed@gmail.com
103
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Retrieve first data
System.out.println("First data: " + list.getFirst());
//Retrieve last data
System.out.println("Last data: " + list.getLast());
//Retrieve specific data
System.out.println("Data at 4th position: " + list.get(3));
//Remove first
int first = list.removeFirst();
System.out.println("Data removed from 1st location: " + first);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove last
int last = list.removeLast();
System.out.println("Data removed from last location: " + last);
System.out.print("Now the list contain: ");
iterator = list.iterator();
//After removing data
while (iterator.hasNext()){
System.out.print(iterator.next()+" ");
}
System.out.println();
System.out.println("Now the size of list: " + list.size());
//Remove 2nd data
int second = list.remove(1);
Skarifahmed@gmail.com
104
Output
Linked List Example!
Linked list data: 11 22 33 44
Linked list size: 4
Adding data at 1st location: 55
Now the list contain: 55 11 22 33 44
Now the size of list: 5
Adding data at last location: 66
Now the list contain: 55 11 22 33 44 66
Now the size of list: 6
Adding data at 3rd location: 99
Now the list contain: 55 11 99 22 33 44 66
Now the size of list: 7
Skarifahmed@gmail.com
105
First data: 55
Last data: 66
Data at 4th position: 22
Data removed from 1st location: 55
Now the list contain: 11 99 22 33 44 66
Now the size of list: 6
Data removed from last location: 66
Now the list contain: 11 99 22 33 44
Now the size of list: 5
Data removed from 2nd location: 99
Now the list contain: 11 22 33 44
Now the size of list: 4
Linked list is empty
Example 2:
The following example shows how to use HashMap and TreeMap class of the collection
framework. At first we create an instance of HashMap. Then we put 7 elments into it with key 0-
6 and after that we fetch all the elements from it using Iterator interface. After that we create an
instance of TreeMap from the above Map. Then we use some methods of the TreeMap like
keySet(), values(), firstKey(), remove() etc.
import java.util.*;
Skarifahmed@gmail.com
106
Output
Keys of tree map: [0, 1, 2, 3, 4, 5, 6]
Values of tree map: [Sunday, Monday, Tuesday, Wednesnday, Thursday,
Friday, Saturday]
First key: 0 Value: Sunday
Skarifahmed@gmail.com
107
Example 3:
The example of HashSet
import java.util.*;
public class A {
public static void main(String [] args) {
System.out.println( "Collection Example!\n" );
int size;
// Create a collection
HashSet collection = new HashSet ();
String str1 = "Yellow", str2 = "White", str3 = "Green", str4 =
"Blue";
Iterator iterator;
//Adding data in the collection
collection.add(str1);
collection.add(str2);
collection.add(str3);
collection.add(str4);
System.out.print("Collection data: ");
Skarifahmed@gmail.com
108
//Create a iterator
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
// Get size of a collection
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
System.out.println( "Collection size: " + size);
}
System.out.println();
// Remove specific data
collection.remove(str2);
System.out.println("After removing [" + str2 + "]\n");
System.out.print("Now collection data: ");
iterator = collection.iterator();
while (iterator.hasNext()){
System.out.print(iterator.next() + " ");
}
System.out.println();
size = collection.size();
System.out.println("Collection size: " + size + "\n");
//Collection empty
collection.clear();
size = collection.size();
if (collection.isEmpty()){
System.out.println("Collection is empty");
}
else{
Skarifahmed@gmail.com
109
Collection is empty
Skarifahmed@gmail.com
110
JDBC
i)Describe JDBC Architecture Overview?
Ans.
JDBC Architecture:
Java applications cannot directly communicate with a database to submit data and retrieve the
results of queries. This is because a database can interpret only SQL statements and not Java
language statements. For this reason, you need a mechanism to translate Java statements into
SQL statements. The JDBC architecture provides the mechanism for this kind of translation.
The JDBC architecture can be classified into two layers:
��JDBC application layer: Signifies a Java application that uses the JDBC API to interact with
the JDBC drivers. A JDBC driver is software that a Java application uses to access a database.
The JDBC driver manager of JDBC API connects the Java application to the driver.
��
JDBC driver layer: Acts as an interface between a Java application and a
Skarifahmed@gmail.com
111
database. This layer contains a driver, such as a SQL Server driver or an Oracle driver, which
enables connectivity to a database. A driver sends the request of a Java application to the
database. After processing the request, the database sends the response back to the driver.
The driver translates and sends the response to the JDBC API. The JDBC API forwards it to the
Java application
Skarifahmed@gmail.com
112
Ans.
JDBC Drivers:
When you develop JDBC applications, you need to use JDBC drivers to convert queries into a
form that a particular database can interpret. The JDBC driver also retrieves the result of SQL
statements and converts the result into equivalent JDBC API class objects that the Java
application uses. As the JDBC driver only takes care of interactions with the database, any
change made to the database does not affect the
application.
Ans:
The JDBC-ODBC Bridge driver is called the Type 1 driver. The JDBC-ODBC Bridge driver
converts JDBC calls to Open Database Connectivity (ODBC) calls. ODBC is an open standard
API to communicate with databases. The JDBC-ODBC bridge driver enables a Java application
to use any database that supports ODBC driver. A Java application cannot interact directly with
the ODBC driver. For this reason, the application uses the JDBC-ODBC Bridge driver that works
as an interface between the application and the ODBC driver. To use the JDBC-ODBC Bridge
driver you need to have the ODBC driver installed on the client computer. The JDBC-ODBC
Bridge driver is usually used in stand-alone applications.
Skarifahmed@gmail.com
113
The following figure shows the working of the JDBC-ODBC Bridge driver:
The Native-API Partly-Java driver is called the Type 2 driver. It uses the local native libraries
provided by the database vendors to access databases. The JDBC driver maps the JDBC calls
to the native method calls, which are passed to the local native Call Level Interface (CLI). This
interface consists of functions written in C to access databases. To use the Type 2 driver, CLI
needs to be loaded on the client computer. As opposed to the JDBC-ODBC Bridge driver, the
Native-API Partly-Java driver does not have an ODBC intermediate layer. As a result, this driver
has a better performance than the JDBC-ODBC Bridge driver. This driver is usually used for
network-based applications.
The following figure shows the working of the Native-API Partly-Java
Skarifahmed@gmail.com
114
The JDBC-Net Pure-Java driver is called the Type 3 driver. You can use the JDBC-Net Pure-
Java driver over the Web while connecting applets with databases. The JDBC-Net Pure-Java
driver consists of client and server portions. The client portion contains pure Java functions and
the server portion contains Java and native methods. The Java application sends JDBC calls to
the JDBC-Net Pure-Java driver client portion, which in turn, translates JDBC calls into database
calls. The database calls are sent to the server portion of the JDBC-Net Pure-Java driver that
forwards the request to the database. When you use the JDBC-Net Pure-Java driver, CLI native
libraries are loaded on the server
The following figure shows the working of the JDBC-Net Pure-java Driver
Skarifahmed@gmail.com
115
The Native-Protocol Pure-Java driver is called the Type 4 driver. It is a Java driver that interacts
with the database directly using a vendor-specific network protocol. As opposed to the other
JDBC drivers, you do not require to install any vendor-specific libraries to use the Type 4 driver.
DataDirect Technologies provide Type 4 driver for various databases such as MS SQL Server,
AS/400, and DB2. This driver is usually used for enterprise applications.
Skarifahmed@gmail.com
116
The following figure shows the working of the Native Protocol Pure-Java driver:
v.Write the steps to establish a connection with the database and firing a SQL query and
how is it implemented in java?
Ans.
Here are the JDBC Steps to establish a connection with the database and firing a SQL query
Loading Driver
Skarifahmed@gmail.com
117
• Import Statement
Import all the necessary classes and interface from java.sql package into your program.
ex:
import java.sql.*;
or
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
• Loading Driver
Loading Database driver is very first step towards making JDBC connectivity with the
database. It is necessary to load the JDBC drivers before attempting to connect to the
database. The JDBC drivers automatically register themselves with the JDBC system
when loaded. Here is the code for loading the JDBC driver:
Class.forName(driver).newInstance();
• Establishing Connection
In the above step we have loaded the database driver to be used. Now its time to make
the connection with the database server. In the Establishing Connection step we will
logon to the database with user name and password. Following code we have used to
make the connection with the database:
Skarifahmed@gmail.com
118
• Executing Statements
In the previous step we established the connection with the database, now its time to
execute query against database. You can run any type of query against database to
perform database operations. In this example we will select all the rows from employee
table. Here is the code that actually execute the statements against database:
• Getting Results
In this step we receives the result of execute statement. In this case we will fetch the
employees records from the recordset object and show on the console. Here is the code:
while (res.next()) {
String employeeName = res.getString( " employee_name " );
System.out.println( employeeName );
}
con.close();
(i) Driver Interface: Represents a database driver. All JDBC driver classes must implement the
Driver interface. When a Driver class is loaded, it should create an instance of itself and register
it with the DriverManager. This means that a user can load and register a driver by calling
Class.forName("foo.bah.Driver").
(ii) Connection Interface: Enables you to establish a connection between a Java application
and a database.
Skarifahmed@gmail.com
119
void close()Releases this Connection object's database and JDBC resources immediately
instead of waiting for them to be automatically released. Calling the method close on a
Connection object that is already closed is a no-op.
void close() Releases this Statement object's database and JDBC resources immediately
instead of waiting for this to happen when it is automatically closed.
Boolean execute(String sql) Executes an SQL statement and returns a boolean value.
ResultSet executeQuery(String sql) Executes the given SQL statement, which returns a
single ResultSet object.
Skarifahmed@gmail.com
120
int executeUpdate(String sql) Executes the given SQL statement, which may be an
INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an
SQL DDL statement.
Connection getConnection() Retrieves the Connection object that produced this Statement
object.
ResultSet getGeneratedKeys() Retrieves any auto-generated keys created as a result of
executing this Statement object.
ResultSet getResultSet()Retrieves the current result as a ResultSet object. This method
should be called only once per result.
Skarifahmed@gmail.com
121
CallableStatement can return one ResultSet object or multiple ResultSet objects. Multiple
ResultSet objects are handled using operations inherited from Statement.
This escape syntax has one form that includes a result parameter and one that does not. If
used, the result parameter must be registered as an OUT parameter. The other parameters can
be used for input, output or both. Parameters are referred to sequentially, by number, with the
first parameter being 1.
IN parameter values are set using the set methods inherited from PreparedStatement. The type
of all OUT parameters must be registered prior to executing the stored procedure; their values
are retrieved after execution via the get methods provided here.
Skarifahmed@gmail.com
122
{
String one = rs1.getString("HELLO");
System.out.println(one);
}
//Another way
/*
--create table test(slno int,ques varchar(100),ans text)
--EXECUTE fetchRec 1
create procedure fetchRec
@A int
as
select * from test where slno=@A
*/
Skarifahmed@gmail.com
123
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
ResultSet interface: Represents the information retrieved from a database.After execution of
sql statement retrieved data will be stored in ResultSet. A ResultSet object maintains a cursor
that enables you to move through the rows stored in a ResultSet object.
The various types of ResultSet objects to store the output returned by a database are:
• Read only: Allows you to only read the rows in a ResultSet object.
• Forward only: Moves the result set cursor from first row to last row in forward
direction only.
• Scrollable: Moves the result set cursor forward or backward through the result set.
• Updatable: Allows you to update the result set rows retrieved from a database table.
Various fields of ResultSet interface:
TYPE_SCROLL_SENTITIVE: Specifies that the cursor of the ResultSet object is scrollable and
it reflects the changes in the data made by other users.
TYPE_SCROLL_INSENSITIVE: Specifies that the cursor of the ResultSet object is scrollable
and it does not reflect changes in the data made by other users.
TYPE_FORWARD_ONLY: Specifies that the cursor of the ResultSet object moves in forward
direction only from the first row to the last row.
Skarifahmed@gmail.com
124
CONCUR_READ_ONLY: Specifies the concurrency mode that does not allow you to update
the ResultSet object.
CONCUR_UPDATABLE: Specifies the concurrency mode that allows you to update the
ResultSet object.
HOLD_CURSORS_OVER_COMMIT: Specifies that a ResultSet object should not be closed
after data is committed to the database.
CLOSE_CURSORS_AT_COMMIT: Specifies that a ResultSet object should be closed after
data is committed to the database.
Skarifahmed@gmail.com
125
Skarifahmed@gmail.com
126
Connection getConnection (String <url>) Accepts the JDBC URL of the database, which
you need to access, as a parameter. You can use the following code snippet to connect to a
database using the getConnection() method with a single parameter:
String url = "jdbc:odbc:MyDataSource";
Connection con = DriverManager.getConnection(url);
The syntax for a JDBC URL that is passed as a parameter to the getConnection() method is:
<protocol>:<subprotocol>:<subname>
A JDBC URL has the following three components:
• Protocol name: Indicates the name of the protocol that is used to access a database.
In JDBC, the name of the access protocol is always jdbc.
• Sub-protocol name: Indicates the mechanism to retrieve data from a database. For
example, if you use the JDBC-ODBC Bridge driver to access a database, then the
name of the sub-protocol is odbc.
• Subname: Indicates the Data Source Name (DSN) that contains database
information, such as the name of a database, location of the database server, user
name, and password to access a database server.
Skarifahmed@gmail.com
127
In the preceding code snippet, p is the reference to an object of the Properties class.
The username and password properties are set using the setProperty() method. After
you create a connection, you need to write JDBC statements that are to be executed.
Ans.
The Preparedstatement object are compiled and prepared only once by JDBC. The
Preparedstatement interface is derived from the Statement interface. The
Preparedstatement object allows you to pass runtime parameters to the SQL statements
to query and modify the data in the table. Since the PreparedStatement is compiled only
one time so it is relatively fast from Statement. PreparedStatement is strictly typed so it
prevents SQL injection. In other word, in PreparedStatement special characters are
inserted into SQL statement using escape sequence character.
Statement example:
Skarifahmed@gmail.com
128
PreparedSatement example:
vii) What are the utility of executeQuery, executeUpdate & execute method of statement
interface?
Answer:
ResultSet executeQuery(String str): Executes an SQL statement and returns a single object
of the type, ResultSet. This object provides you with the methods to access the data from a
Skarifahmed@gmail.com
129
result set. The executeQuery() method should be used when you need to retrieve data from a
database table using the SELECT statement. The syntax to use the executeQuery() method is:
In the preceding syntax, stmt is a reference to the object of the Statement interface. The
ecuteQuery() method executes an SQL statement and the result retrieved from a database is
stored in rs, the ResultSet object.
int executeUpdate(String str): Executes the SQL statements and returns the number of data
rows that are affected after processing the SQL statement. When you need to modify data in a
database table using the Data Manipulation Language(DML) statements, INSERT, DELETE,
and UPDATE, you can use the executeUpdate() method. The syntax to use the
executeUpdate() method is:
In the preceding syntax, the executeUpdate() method executes an SQL statement and number
of rows affected in a database is stored in count, the int type variable.
boolean execute(String str): Executes an SQL statement and returns a boolean value. You
can use this method when the type of SQL statement passed as parameter is not known or
when the statement being executed returns a result set or an update count. The execute()
method returns true if the result
of the SQL statement is an object of ResultSet and false if it is an update count. The syntax to
use the execute() methods is:
stmt.execute(<SQL statement>);
Skarifahmed@gmail.com