.
Basic J ava Material Contents: 1. Introduction to Java and OOC 2. The Language Package 3. The Utilities Pack age 4. I / O P a c k ag ag e 5. Multithreading 6. GUI and Applet Programming 7. Networking 8. JDBC
.
Table of Contents
1. Introduction to Java and OOC ………………………. 4
2. The language package
……………………………………....29
3. The Utilities package ………………………………………...37
4. The I/O Package
………………………………………………………….50
5. GUI and Applet Programming ……………………………….72
6. Multithreading ……………………………………………………………..115
7. Networking in Java …………………………………………………..127
8. Java Database Connectivity ……………………………….139
.
I ntroduction to Java and Object Oriented Concepts
.
CHAPTER-1: INTRODUCTION TO JAVA Java, a Web programming technology, had altered the course of software development, especially in regard to the Internet. Java sports all features necessary for extending the Web in ways previously impossible. Java was designed with issues such as portability and reliability in mind. Because of Java, the entire concept of the Web and what it can do is being redefined. Java is a simple, distributed, interpreted, secure, architecturally neutral, portable, high-performance, multithreaded and dynamic language. But what exactly makes Java unique is that it is the first programming language that can be used for writing general-purpose general-purpose applications, as well as programs designed for the Internet. Java Buzzwords: SIMPLICITY
Java was designed to be a powerful language but simple. To support the development of large software, the concept of package is used. The major difference was the removal of the direct use of pointers . Java automatically handles referencing and dereferencing of language objects. Other difference includes the removal of support for data structures like struct, union . Its in-built classes provide this. Also, the concepts of operator overloading and multiple-inheritance in the form of classes have been removed. OBJECT-ORIENTED NATURE
The notion of object in Java is implemented by its class construct. In fact, it is not possible to write a Java program that does something meaningful without using the class construct. Java language comes with very powerful set of pre-defined classes with a hierarchy level. DISTRIBUTED NATURE
Java provides the network capabilities by a pre-defined package java.net. This package has many classes that simplify the network communication. Accessing to any remote object is also possible in Java via the java.rmi package. ARCHITECTURALLY NEUTRAL
The Java Compiler does not produce the machine language instructions that make up the executable Java Program. The Java Compiler DOES NOT generate a .exe file. Instead the compiler produces an intermediate code called as 'byte code' . Java byte code is an architecturally neutral representation of the program, that is, it is independent of any processor type or machine architecture. These byte codes are read by the Java interpreter and the same is executed using an internal model of an abstract machine. The Java Interpreter and the implementation of this abstract machine are called the JAVA VIRTUAL MACHINE. SECURE LANGUAGE
Before any Java program is interpreted, the Java runtime system performs a bytecode verification to ensure that the program is not violating the system integrity. Also, programs loaded from the net are loaded in a separate name space than the local classes. This prevents any other program to affect the system classes.
. MULTITHREADED LANGUAGE
Java supports multitasking in the form of multithreading within itself. First Java Application HelloWorld Application public class HelloWorld { public static void main(String args[]) { System.out.println("Hello System.out.println("Hell o World!!"); } }
Create the file
Save this into a file called HelloWorld.java using any text editor. It is very important to call the file HelloWorld.java, because the compiler expects the file name to match the class identifier. Compile the code
Type Prompt> javac HelloWorld.java at a command prompt. The javac program creates a file called HelloWorld.class from the HelloWorld.java file. Inside this file (HelloWorld.class) is text known as bytecodes which can be run by the Java interpreter. Run the program
Now that you have compiled the program, you can run it by typing at the command prompt: Promtpt> java HelloWorld
The input to the interpreter is nothing but the name of the class that has the main method. After you do this, the t he computer should print to the screen Hello World!! Understanding HelloWorld Declaring a class
The first task when creating any Java program is to create a class. Look at the first line of the HelloWorld application: public class HelloWorld {
. This declares a class called HelloWorld. To create any class, simply write a line that looks like: public class ClassName Here, ClassName is the name of the program you are writing. In addition, ClassName must correspond to the file name. Next, notice the little curly brace ({) that is located after the class declaration. If you look at the end of the class, there is also a closing brace (}). The braces tell the compiler where your class will begin and end. Any code between those two braces is considered to be in the HelloWorld class. public static void main(String args[]){ This line declares what is known as the main method. Methods are essentially miniprograms. Each method performs some of the tasks of a complete program. The main method is the most important one with respect to applications, because it is the place that all Java applications start. For instance, when you run java HelloWorld, the Java interpreter starts at the first line of the main method. Writing to the Screen
The text Hello World!! appears on the screen through System.out.println("Hello World!!"); You can replace any of the text within the quotation marks ("") with any text that you would like. The System.out line is run because, when the application starts up, the interpreter looks at the first line of code (namely the printout) and executes it. If you place any other code there, it runs that code instead. The System.out.println serves approximately the same purpose as the writeln in Pascal. In C, the function is printf, and in C++, cout. println Versus print
There is one minor variation on println which is also readily used: print("Hello World!!"). The difference between println and print is that print does not add a carriage return at the end of the line, so any subsequent printouts are on the same line. Access Specifiers :
The first option for a method is the access specifier. Access specifiers are used to restrict access to the method. Regardless of what the access specifier is, though, the method is accessible from any other method in the same class. public
The public modifier is the most relaxed modifier possible for a method. By specifying a method as public it becomes accessible to all classes regardless of their lineage or their package. In other words, a public method is not restricted in any way.
. protected
The second possible access modifier is protected. Protected methods can be accessed by any class within the current package, but are inaccessible to any class outside the package. default
The next access modifier that can be applied to a class is that of default. Default methods are accessible only to the current class and any classes that extend from it. If you fail to specify an access modifier, the method is considered default. private
private is the highest degree of protection that can be applied to a method. A private method is only accessible by those methods in the same class. Even classes that extend from the current class do not have access to a private class. Method Modifiers
Method modifiers enable you to set properties for the method, such as where it will be visible and how subclasses of the current class will interact with it. static
Placing the static modifier in front of a method or variable declaration makes it common to all object references of that class. While non-static methods methods can also operate with static variables, static methods can only deal with static variables and static methods. abstract
Abstract methods are simply methods that are declared, but are not implemented in the current class. The responsibility of defining the body of the method is left to subclasses of the current class . final
By placing the keyword final in front of the method declaration, you prevent any subclasses of the current class from overriding the given method. This ability enhances the degree of insulation of your classes, you can ensure that the functionality defined in this method will never be altered in any way. Note: Neither static methods nor class constructors can be declared to be abstract. Furthermore, you should not make abstract methods final, because doing so prevents you from overriding the method. native
Native methods are methods that you want to use, but do not want to write in Java. Native methods are most commonly written in C++, and can provide several benefits such as faster execution time. Like abstract methods, they are declared simply by placing the modifier native in front of the method declaration and by substituting a semicolon for the method body. synchronized
By placing the keyword synchronized in front of a method declaration, you can prevent data corruption that may result when two methods attempt to access the same piece of data at the same time. While this may not be a concern for simple programs, once you begin to use threads in your programs, this may become a serious problem.
. Modified HelloWorld
In the above HelloWorld program, the print method was called inside the same class. The following example creates a separate PrintWorld object that has a print method and any other class can invoke this method to print the necessary result. class PrintWorld { String data_member; public PrintWorld(String line) { data_member = new String(line); } public void printMe() { System.out.println(data_member); } } public class ObjectWorld { public static void main(String args[]) { PrintWorld p_world = new PrintWorld("Hello World"); p_world.printMe(); } }
In the above program, PrintWorld p_world = new PrintWorld("Hello World"); is used to construct the class PrintWorld. Quite simply, the line tells the compiler to allocate memory for an instance of the class and points variable to the new section of memory. In the process of doing this, the compiler also calls the class's constructor method and passes the appropriate parameters parameters to it p_world is the object to the class PrintWorld. This class has a data member, data_member and a method printMe(). In the construction phase of the class, the argument of the constructor is assigned to the data member. And later when the printMe() method is called, this data member value is retrieved and printed. Getting information from the user with System.in
System.out has a convenient partner called System.in. While System.out is used to print information to the screen, System.in is used to get information into the program. Requesting input from the user
Let's use System.in.read() to get a character from the user. ReadHello.java public class ReadHello
. { public static void main (String args[] { int inChar =’0’; System.out.println("Enter System.out.println("Ente r a Character:"); try { inChar = System.in.read(); System.out.println("You entered " + inChar); } catch (IOException e) { System.out.println("Error System.out.println("Err or reading from user"); } } }
You've probably already noticed that there is a lot more to this code than there was to the last one. one. Let’s first compile the program. program. Enter a Character: A You entered 65 The code we are most interested in is the line, which reads: inChar = System.in.read(); System.in.read() is a method that takes a look at the character that the user enters. It then performs what is known as a return on the value. A value that is returned by a method is then able to be used in an expression. In the case of ReadHello, a variable called inChar is set to the value which is returned by the System.in.read() method. method. In the next line, the value of the inChar variable is added to the System.out string. By adding the variable into the string, you can see the results of your work. It's not actually necessary to use a variable. If you prefer, you can print it out directly in the second System.out line, by changing it to System.out.println("You entered "+ System.in.read()); System.in.read()); Now, notice that the program displays a number instead of a character for what you entered. This is because the read() method of System.in returns an integer, not an actual character. The number corresponds to what is known as the ASCII character set. Converting integer to character To convert the number that is returned from System.in into a character, you need to do what is known as a cast. Casting effectively converts a given data type to another one. --inChar =(char) Syst em.in.read(); em.in.read(); ---
. Notice the characters before System.in.read().The (char) causes the integer to be changed into a character. The Rest of the Extra Code—try, catch
In this code, there is a sequence there called a try-catch block. In some programming languages, when a problem occurs during execution, there is no way for you as a programmer to catch it and deal with the problem. In some languages, it's a bit complicated. In Java, most problems cause what are known as Exceptions. When a method states that it will throw an exception, it is your responsibility to only try to perform that method, and if it throws the exception, you need to catch it. See the line of code right after the catch phase. If there is an error while reading, an exception called an IOException is thrown. When that happens, the code in the catch block is called. JAVA LANGUAGE FUNDAMENTALS KEYWORDS
The following is a list of the 56 keywords you can use in Java. abstract case class do final future implements int new package rest super throw var
boolean cast const double finally generic import interface null private return switch throws void
Break Catch Continue Else Float Goto Inner Long Operator Protected Short Synchronized Transient Volatile
Byte Char Default Extends for if instanceof native outer public static this try while
EXTENDING OBJECTS THROUGH INHERITANCE
Inheritance is a feature of OOP programming that enables us inherit all the common features of a parent class onto a child class, it's not necessary to reinvent the object every time. When new classes inherit the properties of another class, they are referred to as child classes or subclasses. The class from which they are derived is then called a parent or super class. A Simple Inheritance Program class BaseClass { public BaseClass() { System.out.println("Base Class Constructor Called"); }
. } /* DerivedClass extends or inherits the property of the BaseClass */ class DerivedClass extends BaseClass { public DerivedClass() { System.out.println("Derived System.out.println("Deri ved Class Constructed"); } } public class Inheritance { public static void main(String args[]) { BaseClass base = new BaseClass(); System.out.println("------------"); DerivedClass derived = new DerivedClass(); } }
The output is: Base Class Constructor Called -----------Base Class Constructor Called Derived class Constructed By looking at the output, you can find that, when the child class is constructed, the parent class constructor is invoked first. INTERFACES
Interfaces are Java's substitute for C++'s feature of multiple inheritance, the practice of allowing a class to have several super classes. While it is often desirable to have a class inherit several sets of properties, for several reasons the creators of Java decided not to allow multiple inheritance. Java classes, however, can implement several interfaces, thereby enabling you to create classes that build upon other objects without the problems created by multiple inheritance. The syntax for creating an interface is extremely similar to that for creating a class. However, there are a few exceptions. The most significant difference is that none of the methods in your interface may have a body. An Interface Example public interface Product { public int getPrice(int id); } public class Shoe implements Product
. { public int getPrice(int id) { if (id == 1) return(5); else return(10); } } public class Store { public static void main(String argv[]) { Shoe some = new Shoe(); int x = Some.getPrice(3); System.out.println(“the price : “+x); } }
The Declaration
Interface declarations have the syntax public interface NameofInterface Public Interfaces By default, interfaces may be implemented by all classes in the same package. But if you make your interface public, you allow classes and objects outside of the given package to implement it as well. The rules for an interface name are identical to those t hose for classes.
Extending Other Interfaces
In keeping with the OOP practice of inheritance, Java interfaces may also extend other interfaces as a means of building larger interfaces upon previously developed code. e.g public interface NameOfInterface extends AnotherInterface Interfaces cannot extend classes. There are a number of reasons for this, but probably the easiest to understand is that any class, which the interface would be extending would have its method bodies defined. This violates the "prime directive" of interfaces. The Interface Body
The main purposes of interfaces are to declare abstract methods that will be defined in other classes. As a result, if you are dealing with a class that implements an interface, you can be assured that these methods will be defined in the class. While
. this process is not overly complicated, there is one important difference that should be noticed. An interface method consists of only a declaration. Methods in Interface
Method declarations in interfaces have the following syntax: public return_value nameofmethod (parameters); (parameters); Note that unlike normal method declarations in classes, declarations in interfaces are immediately followed by a semicolon. All methods in interfaces are public by default, regardless of the presence or absence of the public modifier. This is in contrast to class methods which default to friendly. It's actually illegal to use any of the other standard method modifiers (including native, static, synchronized, final, private, protected, or private protected) when declaring a method in an interface. Variables in Interfaces
Although interfaces are generally employed to provide abstract implementation of methods, you may also define variables within them. Because you cannot place any code within the bodies of the methods, all variables declared in an interface must be global to the class. Furthermore, regardless regardless of the modifiers used when declaring the field, all fields declared in an interface are always public, final, and static. While all fields will be created as public, final, and static, you do not need to explicitly state this in the field declaration. All fields default to public, static and final regardless of the presence of these modifiers. It is, however, a good practice to explicitly define all fields in interfaces as public, final, and static to remind yourself (and other programmers) of this fact. Implementing an interface.
In order to fulfill the requirements of implementing the Product interface, the class must override the getPrice(int) method. Overriding Methods
Declaring a method in an interface is a good practice. However, the method cannot be used until a class implements the interface and overrides the given method . ENCAPSULATION
Another benefit of enclosing data and methods in classes is the OOP characteristic of encapsulation—the ability to isolate and insulate information effectively from the rest of your program . POLYMORPHISM
Finally, the allure of the OOP approach to creating self-sustaining modules is further enhanced by the fact that children of a given class are still considered to be of the same "type" as the parent. This feature, called polymorphism, enables you to perform the same operation on different types of classes as long as they share a common
. trait. While the behavior of each class might be different, you know that the class will be able to perform the same operation as its parent because it is of the same family tree Example of Function Overload class Sample { public Sample() { System.out.println("Sample System.out.println("Samp le Constructor Called"); } public void overloadMe() { System.out.println("Overload System.out.println("Over load Method Invoked"); } public void overloadMe(String str) { System.out.println(str); } } public class Overload { public static void main(String args[]) { Sample samp = new Sample(); System.out.println("-------------"); samp.overloadMe(); System.out.println("-------------"); samp.overloadMe("Hi! I am not the old one"); } }
Output:
Sample Constructor Called ------------Overload Method Invoked ------------Hi! I am not the old one Here, though the method overloadMe is the same, it throws different ouput based on its invocation. This is termed as method overloading.
JAVA DATA TYPES
Java has Two Types of Data Types In Java, there are really two different categories in which data types have been divided: Primitive types Reference types
Reference types enclose things such as arrays, classes, and interfaces. Java has eight primitive types, each with its own purpose and use: Type Description boolean - These have values of either true or false.
byte - 8-bit 2s-compliment integer with values between -128 to 127
.
short - 16-bit 2s-compliment integer with values between -2^15 and 2^15-1 (32,768 to 32,767) char 16-bit Unicode Unicode characters. For alpha-numerics, alpha-numerics, these these are the the same as ASCII with the high byte set to 0. The numerical values are unsigned 16-bit values are between 0 and 65535. int 32-bit 2s-compliment 2s-compliment integer with values between -231 -231 and and 231-1 231-1 (2,147,483,648 to 2,147,483,647) long 64-bit 2s-compliment 2s-compliment integer integer with values values between -263 and 263-1 ((9223372036854775808 to 9223372036854775807) float 32-bit single precision floating floating point numbers numbers using the IEEE 754-1985 754-1985 standard (+/- about 1039) double 64-bit double precision precision floating point point numbers using the IEEE 754-1985 754-1985 standard. (+/- about 10317)
VARIABLES
You can create any variable in Java in the same way as was just shown:
State the data type that you will be using
State the name the variable will be called
Assign the variable a value
As with every other line of code in Java, terminate the line with a semicolon
example: int number = 0; boolean value = false; Identifiers—The Naming of a Variable
There are several rules that must be obeyed when creating an identifier: The first character of an identifier must be a letter. After that, all subsequent characters can be letters or numerals. The underscore (_) and the dollar sign ($) may be used as any character in an identifier, including the first one. Identifiers are casesensitive and language-sensitive. language-sensitive. Examples of Legal Identifiers
HelloWorld counter HotJava$ ioc_Queue3
. Examples of Illegal Identifiers
9HelloWorld count&add Hot Java 65536 OPERATORS
Operators are used to change the value of a particular object. They are described here in several related categories. UNARY LOGICAL OPERATORS Description
Operator
Increment Decrement Negation Bitwise complement
++ -~
Example for Increment and Decrement Operators class IncDec { public static void main (String args[]) { int x = 8, y = 13; System.out.println(“x = “ + x); System.out.println(“y = “ + y); System.out.println(“++x = “ + ++x); System.out.println(“y++ = “ + y++); System.out.println(“x = “ + x); System.out.println(“y = “ + y); } }
Output x=8 y = 13 ++x = 9 y++ = 13 x=9 y = 14 Example for negation operator class Negation { public static void main (String args[]) { int x = 8; System.out.println(“x = “ + x); int y = -x; System.out.println(“y = “ + y); } }
Example for Bitwise complement operator
. class BitwiseComplement { public static void main (String args[]) { int x = 8; System.out.println(“x = “ + x); int y = ~x; System.out.println(“y = “ + y); } }
ARITHMETIC OPERATORS
Arithmetic operators act on pairs of integers. Description
Operator
Addition Subtraction Multiplication Division Modulus Bitwise AND Bitwise OR Bitwise XOR Left Shift Right Shift Zero-Fill Right Shift
+ * / % & | ^ << >> >>>
Shift Operators
The left-shift, right-shift, and zero-fill-right-shift operators (<<, >>, and >>>) shift the individual bits of an integer by a specified integer amount. The following are some examples of how these operators are used: x << 3; y >> 7; z >>> 2; Example for Shift Operators class Shift { public static void main int x = 7; System.out.println(“x System.out.println(“x System.out.println(“x System.out.println(“x } }
The output of Shift follows: x=7 x >> 2 = 1 x << 1 = 14 x >>> 1 = 3
(String args[]) { = “ + x); >> 2 = “ + (x >> 2)); << 1 = “ + (x << 1)); >>> 1 = “ + (x >>> 1));
.
Relational Operators
The last group of integer operators is the relational operators, which all operate on integers but return a type boolean. Description
Operator
Less Than Greater Than Less Than Or Equal To Greater Than Or Equal To Equal To Not Equal To
< > <= >= == !=
ASSIGNMENT OPERATORS
The simplest assignment operator is the standard assignment operator. This operator is often known as the gets operator, because the value on the left gets the value on the right. = assignment operator The arithmetic assignment operators provide a shortcut for assigning a value. When the previous value of a variable is a factor in determining the value that you want to assign, the arithmetic assignment operators are often more efficient: Description
Operator
Simple Addition Subtraction Multiplication Division Modulus AND OR XOR
= += -= *= /= %= &= |= ^=
BOOLEAN OPERATORS
Boolean operators act on Boolean types and return a Boolean result. The Boolean operators are listed Description
Operator
Evaluation AND Evaluation OR Evaluation XOR Logical AND Logical OR D="I228" NAME="I228"> Negation
& | ^ && || !
. Equal To Not Equal To Conditional
== != ?:
CONDITIONAL OPERATOR
It takes the following f ollowing form: expression1 ? expression2 : expression3 In this syntax, expression1 must produce a Boolean value. If this value is true, then expression2 is evaluated, and its result is the value of the conditional. If expression1 is false, then expression3 is evaluated, and its result is the value of the conditional. Example for Conditional Operator class Conditional { public static void main (String args[]) { int x = 0; boolean isEven = false; System.out.println(“x = “ + x); x = isEven ? 4 : 7; System.out.println(“x = “ + x); } }
The results of the Conditional program follow: x=0 x=7 CONTROL FLOW
Control flow is the heart of any program. Control flow is the ability to adjust (control) the way that a program progresses (flows). By adjusting the direction that a computer takes, the programs that you build become dynamic. Without control flow, programs would not be able to do anything more than several sequential operations. IF STATEMENTS
if (expression) if_statement; else else_statement; ITERATION STATEMENTS
Programmers use iteration statements to control sequences of statements that are repeated according to runtime conditions. Java supports five types of iteration statements: while do for
. continue break WHILE STATEMENTS
while (expression) statement; DO WHILE LOOP
do statement; while (expression) FOR LOOP
for (initialization, expression , step ) statement; SWITCH STATEMENTS
switch (expression){ case V1: statement1; break; case V2: statement2; break; default: statementD; } BREAK STATEMENTS
The sub-statement blocks of loops and switch statements can be broken out of by using the break statement. RETURN STATEMENTS
A return statement passes control to the caller of the method, constructor, or static initializer containing the return statement. If the return statement is in a method that is not declared void, it may have a parameter of the same type as the method. ARRAYS
An array is simply a way to have several items in a row. If you have data that can be easily indexed, arrays are the perfect means to represent them. int IQ[] = {123,109,156,142,131}; {123,109,156,142,131}; The next line shows an example of accessing the IQ of the third individual: int ThirdPerson = IQ[3]; Arrays in Java are somewhat tricky. This is mostly because, unlike most other languages, there are really three steps to filling out an array, rather than one:
. There are two ways to do this: place a pair of brackets after the variable type, or place brackets after the identifier name. int MyIntArray[]; int[] MyIntArray; Examples of declaring arrays.
long Primes[] = new long[1000000]; // declare an array and assign // some memory to hold it. long[] EvenPrimes = new long[1]; // Either way, it's an array. EvenPrimes[0] = 2; // populate the array. There are several additional points about arrays you need to know: Indexing of arrays starts with 0. In other words, the first element of an array is MyArray[0], not MyArray[1]. COMMENTS
Java supports three styles of comments: Traditional C++ style javadoc Traditional Comments
A traditional comment is a C-style comment that begins with a slash-star (/*) and ends with a star-slash (*/). C++ Style Comments
The second style of comment begins with a slash-slash (//) and ends when the current source code line ends. These comments are especially useful for describing the intended meaning of the current line of code. javadoc Comments
The final style of comment in Java is a special case of the first. It has the properties mentioned previously, but the contents of the comment may be used in automatically generated documentation by the javadoc tool. javadoc comments are opened with /**, and they are closed with */. By using these comments in an appropriate manner, you will be able to use JavaDoc to automatically create documentation pages LITERALS
There are several different types of literal. In fact, there are five major types of literal, in the Java language: Boolean Character Floating-point Integer
. String Integer Literal Example
int j=0; long GrainOfSandOnTheBeachNum=1 GrainOfSandOnTheBeachNum=1L; L; short Mask1=0x007f; String FirstName = "Ernest"; char TibetanNine = '\u1049' boolean UniverseWillExpandForever UniverseWillExpandForever = true; ESCAPE CHARACTERS
Escape Literal Meaning '\b' \u0008 backspace '\t' \u0009 horizontal tab '\n' \u000a linefeed '\f' \u000c form feed '\r' \u000d carriage return '\"' \u0022 double quote '\'' \u0027 single quote '\\' \u005c backslash Don't use the \u format to express an end-of-line character. Use the \n or \r characters instead. ERROR-HANDLING CLASSES
Runtime error handling is a very important facility in any programming environment. Java provides the following classes for dealing with runtime errors: Throwable Exception Error The Throwable class provides low-level error-handling capabilities such as an execution stack list. The Exception class is derived from Throwable and provides the base level of functionality for all the exception classes defined in the Java system. The Exception class is used for handling normal errors. The Error class is also derived from Throwable, but it is used for handling abnormal errors that aren’t expected to occur. Very few Java programs worry with the Error class; most use the Exception class to handle runtime errors.
Example for Exception Handling public class ExceptionHandling { public static void main(String args[]) { int values[] = {5,6,3,5,2}; int index = 6; try { int get = values[index]; System.out.println("The value in the requested index is " +get); } catch(Exception err) { System.out.println("Requested System.out.println("Req uested Index Not found");
. } finally { System.out.println("--------End---------"); } } }
In the above example, the array size is 5, but we are trying to access the 6th element. As this is a runtime error, an exception is caught and the t he catch block is executed. Use of finally clause
Suppose there is some action that you absolutely must do, no matter what happens. Usually, this is to free some external resource after acquiring it, to close a file after opening it, or something similar. In exception handling, the finally block is executed no matter whether an exception is thrown or not. Output: Requested Index Not found --------End--------THE THROWABLE CLASS
The Throwable class is the superclass of all errors and exceptions in the Java language. Only objects that are instances of this class (or of one of its subclasses) are thrown by the Java Virtual Machine or can be thrown by the Java throw statement. Similarly, only this class or one of its subclasses can be the argument type in a catch clause. A Throwable class contains a snapshot of the execution stack of its thread at the time it was created. It can also contain a message string that gives more information about the error. THE EXCEPTION CLASS
The class Exception and its subclasses are a form of Throwable that indicates conditions that a reasonable application might want to catch.
EXAMPLE FOR MULTIPLE EXCEPTION HANDLING public class MultipleExceptions { public static void main(String args[]) { int values[] = {5,6,2,3,5}; int index; char input = (char)-1; String data = ""; System.out.println("Enter System.out.println("E nter an index value"); try { do { input = (char)System.in.read(); data = data + input;
. }while(input!='\n'); } catch(Exception err) { System.out.println("Unable System.out.println("Unab le to obtain system input"); } try { index = Integer.parseInt(data.tr Integer.parseInt(data.trim()); im()); System.out.println("The value in the requested index : System.out.println("The "+values[index]); } catch(NumberFormatException catch(NumberFormatExc eption err) { System.out.println("Invalid System.out.println("Inva lid Index"); } catch(ArrayIndexOutOfBoundsException catch(ArrayIndexOutOf BoundsException err) { System.out.println("Requested System.out.println("Requ ested Index Not Found"); } finally { System.out.println("--------End---------"); } } }
In the above program, there is a pre-defined array of length 5. The user input is got as a String. It is then parsed into an int data type. The value in the t he array for this index is given as ouput. Here, the exceptions may be thrown
While getting an input While trying to convert the input to an int data type While trying to access that index in the array
The exception classes for the last two exceptions are NumberFormatException and ArrayIndexOutOfBoundsException respectively. So the try block encapsulating the parsing of the input and searching of the index has two catch blocks to handle these exceptions in their own different way. If input is not an integer, then output is Invalid Index --------End--------If input is an integer, but index is out of range in the array, then output is Requested Index Not Found --------End--------Note that in both the cases, the finally block is executed.
. Packages:
Java provides a mechanism for f or partitioning the classname into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility comttrol mechanism. Classes can be defined inside a package that are not accessible by code outside the package. Class members can also be defined that are only exposed to other members of the same package. This is achieved with the help of package and access protection. Access Protection: Java provides many levels of protection to allow fine-grained control control over the visibility of the variables and methods within classes, subclasses and packages. Packages add another dimension to access control. Classes and packages are both means of encapsulating and containing the namespace and scope of variables and methods. Packages act as containers for classes and other subordinate packages. Classes act as containers for data and code. The class is Java’s smallest unit of abstraction. Java addresses four categories of visibility for class members. 1. 2. 3. 4.
Sub classes in the same package package Non Subclasses in the the same same package package Subclasses in different packages Classes are neither in in the same package package nor subclasses
The three access specifiers, private, public and protected provide a variety of ways to produce tha many levels of access required by these categories. public - Anything declared declared public can be accessed from anywhere anywhere private – Anything declared private cannot be seen outsideof its class. default – When a member doesnot have an access specification, it is visible to subclasses as well as other classes in the same package. protected – If an element has to be seen outside the current package but only to classes that subclass your class directly. Defining Package:
Creating a package in Java is quite easy. This is achieved by simply including a package command as the first statement in a Java Source file. Any classes that are declared with in that file belong to the specified package. The package statement defines a namepsace in which classes are stored. If you omit the package statement, the classes are put into the default package that has no name. Syntax for package statement: package mypackage;
Use package keyword as the first line in the file.
. E.g. package com.first The classes under this package are in com/first namespace. The classes under this package must be stored inside the com/first folder Use import keyword for using the classes in different package. Example for Package mechanism: package com.first.one; public class BaseClass { int x=6; // default access private int x_pri=2; // private access protected int x_pro=3; //protected access public int x_pub=4; //public access public BaseClass() { System.out.println("Inside System.out.println("I nside Constructor of Base Class"); } public void display() { System.out.println("Value System.out.println("Valu e of x(default) is "+x); System.out.println("Value System.out.println("Valu e of x(private) is "+x_pri); System.out.println("Value System.out.println("Valu e of x(protected) is "+x_pro); System.out.println("Value System.out.println("Valu e of x(public) is "+x_pub); } } package com.first.one; class Derived extends BaseClass { Derived() { System.out.println("Inside System.out.println("Insi de Derived Class Constrcutor\n"); System.out.println("Value System.out.println("Valu e of x(default) is "+x); // Not available to derived class also because it is private (Class only) // System.out.println("Value System.out.println("Valu e of x(private) is "+x_pri); System.out.println("Value System.out.println("Valu e of x(protected) is "+x_pro); System.out.println("Value System.out.println("Valu e of x(public) is "+x_pub); } public static void main(String arg[]) { Derived deri=new Derived(); } }
. package com.first.one; public class TestBaseClass { public TestBaseClass() { System.out.println("Inside System.out.println("Insi de TestBaseClass constructor"); BaseClass bc1=new BaseClass(); System.out.println("Value System.out.println("Valu e of x(default) is "+bc1.x); // Not accessible because private - access is for Class only // System.out.println("Value System.out.println("Valu e of x(private) is "+bc1.x_pri); System.out.println("Value System.out.println("Valu e of x(protected) is "+bc1.x_pro); System.out.println("Value System.out.println("Valu e of x(public) is "+bc1.x_pub); } public static void main(String arg[]) { BaseClass bc=new BaseClass(); bc.display(); System.out.println("\n****************TestBaseClass* **************\n"); TestBaseClass test=new TestBaseClass(); } } package com.first.two; import com.first.one.BaseClass; class BaseClassNew extends BaseClass { BaseClassNew() { System.out.println("Constrcutor System.out.println("Cons trcutor of Base class in another package"); //Not accessible because it is default - for package only //System.out.println("Value //System.out.println("Va lue of x(default) is"+x); // Not accessible becuase it is private - for Class only //System.out.println("Value //System.out.println("Va lue of x(private) is "+x_pri); System.out.println("Value System.out.println("Valu e of x(protected) is "+x_pro); System.out.println("Value System.out.println("Valu e of x(public) is "+x_pub); } public static void main(String arg[]) {
. BaseClassNew bcn=new BaseClassNew(); } } package com.first.two; import com.first.one.*; public class SomeClass { SomeClass() { System.out.println("Inside System.out.println("Insi de Constructor of SomeClass"); BaseClass bc=new BaseClass(); // Only for package //System.out.println("Value //System.out.println("Va lue of x(default) is "+bc.x); // Only for Class //System.out.println("Value //System.out.println("Va lue of x(private) is "+bc.x_pri); // Only for Class, subClass & package //System.out.println("Value //System.out.println("Va lue of x(protected) is "+bc.x_pro); System.out.println("Value System.out.println("Valu e of x(public) is "+bc.x_pub); } public static void main(String arg[]) { SomeClass sc=new SomeClass(); } }
.
The Language P ackage ackag e - java.lang java.lang
.
CHAPTER-2: THE LANGUAGE PACKAGE – java.lang The Java language package, which is also known as java.lang, provides classes that make up the core of the Java language. The language package contains classes at the lowest level of the Java class libraries. For example, the Object class, which all classes are derived from, is located in the language package. It’s impossible to write a Java program without dealing with at least a few of the elements of the language package. The most important classes contained in the language package follow:
The Object Class Data Type Wrapper Classes The Math Class String Classes System and Runtime Classes Thread Classes Class Classes Exception Handling Classes Process Classes
THE OBJECT CLASS
The Object class is the super class for all classes in Java. Because all classes are derived from Object, the methods defined in Object are shared by all classes. These results in a core set of methods that all Java classes are guaranteed to support. Object includes methods for making copies of an object, testing objects for equality, and converting the value of an object to a string.
DATA TYPE WRAPPER CLASSES
The fundamental data types (int, char, float, and so on) in Java are not implemented as classes. Many times it is useful, however, to know more information about a fundamental types than just its value. By implementing class wrappers for the fundamental types, additional information can be maintained, as well as methods defined that act on the types. The data type wrapper classes serve as class versions of the fundamental data types, and are named similarly to the types they wrap. For example, the type wrapper for int is the Integer class. Following are the Java data type wrapper classes:
Boolean Character Double Float Integer Long Number
Type wrappers are also useful because many of Java’s utility classes require classes as parameters, not simple types. Type wrappers and simple types are not interchangeable.
. THE MATH CLASS
The Math class serves as a grouping of mathematical functions and constants. It is interesting to note that all the variables and methods in Math are static, and the Math class itself is final. This means you can’t derive new classes from Math. Additionally, you can’t instantiate the Math class. It’s best to think of the Math class as just a conglomeration of methods and constants for performing mathematical computations. The Math class includes the E and PI constants, methods for determining the absolute value of a number, methods for calculating trigonometric functions, and minimum and maximum methods, among others. EXAMPLE FOR MATH CLASS public class MathExample { public static void main(String args[]) { char temp = (char)-1; String input = ""; Double data = null; System.out.println("Enter System.out.println("E nter any number"); /** Gets the user input**/ try { do { temp = (char)System.in.read(); input = input + temp; }while(temp != '\n'); data = new Double(input); } catch(Exception err) { System.out.println("Exception System.out.println("E xception ..."); System.exit(0); } double d_data = data.doubleValue(); System.out.println("Printing Math values......"); System.out.println("Printing System.out.println("Sin System.out.println("S in : " + (Math.sin(d_data))); System.out.println("Cos System.out.println("C os : " + (Math.cos(d_data))); System.out.println("Tan System.out.println("T an : " + (Math.tan(d_data))); System.out.println("asin System.out.println("a sin : " + (Math.asin(d_data))); System.out.println("acos System.out.println("a cos : " + (Math.acos(d_data))); System.out.println("atan System.out.println("a tan : " + (Math.atan(d_data))); System.out.println("Abs System.out.println("A bs : " + (Math.abs(d_data))); System.out.println("Exp System.out.println("E xp : " + (Math.exp(d_data))); System.out.println("Log System.out.println("L og : " + (Math.log(d_data))); System.out.println("Sqrt System.out.println("S qrt : " + (Math.sqrt(d_data))); System.out.println("Ceil System.out.println("C eil : " + (Math.ceil(d_data))); System.out.println("Floor System.out.println("F loor : " + (Math.floor(d_data))); System.out.println("rint System.out.println("r int : " + (Math.rint(d_data)));
. System.out.println("round : " + (Math.round(d_data))) System.out.println("round (Math.round(d_data))); ; System.out.println("Random System.out.println("R andom Number : " + (Math.random())); } }
STRING CLASSES
For various reasons (mostly security related), Java implements text strings as classes, rather than forcing the programmer to use character arrays. The two Java classes that represent strings are String and StringBuffer. The String class is useful for working with constant strings that can’t change in value or length. The StringBuffer class is used to work with strings of varying value and length. THE STRING CLASS
The String class represents character strings. All string literal in Java programs, such as "abc", are implemented as instances of this class. Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example: String str = "abc"; is equivalent to: char data[] = {'a', 'b', 'c'}; String str = new String(data); Here are some more examples of how strings can be used: System.out.println("abc"); String cde = "cde"; System.out.println("abc" + cde); String c = "abc".substring(2,3); The class String includes methods for examining individual characters of the sequence, for comparing strings, for searching strings, for extracting substrings, and for creating a copy of a string with all characters translated to uppercase or to lowercase. The Java language provides special support for the string concatenation operator ( + ), and for conversion of other objects to strings. String concatenation is implemented through the StringBuffer class and its append method. String conversions are implemented through the method toString(), defined by Object and inherited by all classes in Java.
EXAMPLE FOR STRING CLASS public class StringExample { public static void main(String args[]) { String str = new String("Java World"); int length = str.length(); System.out.println("Length System.out.println("L ength of data : "+length); System.out.println("Extracting System.out.println("E xtracting character...");
. for(int index=0;index
THE STRINGBUFFER CLASS
A string buffer implements a mutable sequence of characters. String buffers are safe for use by multiple threads. The methods are synchronized where necessary so that all the operations on any particular instance behave as if they occur in some serial order. String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code: x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").appe StringBuffer().append("a").append(4).append nd(4).append("c").toString() ("c").toString() The principal operations on a StringBuffer are the append and insert methods, which are overloaded so as to accept data of any type. Each effectively converts a given datum to a string and then appends or inserts the characters of that string to the string buffer. The append method always adds these characters at the end of the buffer; the insert method adds the characters at a specified point. For example, if z refers to a string buffer object whose current contents are "start", then the method call z.append("le") would cause the string buffer to contain "startle", whereas z.insert(4, "le") would alter the string buffer to contain "starlet". Every string buffer has a capacity. As long as the length of the character sequence contained in the string buffer does not exceed the capacity, it is not necessary to allocate a new internal buffer array. If the internal buffer overflows, it is automatically made larger. EXAMPLE FOR STRINGBUFFER public class SBExample { public static void main(String args[]) {
. String s = new String("Hello"); /** Constructors 1. Empty Constructor will create with initial capacity of 16 characters. 2. Constructor with specified characters as the initial capacity 3. Constructor with specified string as the initial value */ StringBuffer sb1 = new StringBuffer(); StringBuffer sb2 = new StringBuffer(40); StringBuffer sb3 = new StringBuffer(s); //Appending a boolean value sb1.append(true); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); //Appending a character sb1.append('c'); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); //Appending a character array char c[] = {'H','e','l','l','o'}; sb1.append(c); System.out.println("Value of StringBuffer = " + sb1); System.out.println("Value sb1.append(c,2,3); System.out.println("Value of StringBuffer = " + sb1); System.out.println("Value double d = 12.141354; sb1.append(d); System.out.println("Value of StringBuffer = " + sb1); System.out.println("Value float f = (float)15.1; sb1.append(f); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); int i = 1; sb1.append(i); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); long l = 1000000; sb1.append(l); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); sb1.append(s); System.out.println("Value System.out.println("V alue of StringBuffer = " + sb1); System.out.println("Capacity System.out.println("C apacity = " + sb2.capacity()); System.out.println("Character System.out.println("C haracter at 5th position = " + sb1.charAt(5)); sb1.getChars(0,4,c,0); System.out.println("Chars System.out.println("C hars extracted from Sb1 = " + c); //Insert the boolean value at the 5th position sb1.insert(5,true);
. //Insert the character value at the 9th position sb1.insert(9,'M'); System.out.println("Length System.out.println("L ength of the string buffer = " + sb1.length()); sb1.reverse(); System.out.println("Reverse System.out.println("R everse of the String Buffer = " + sb1); sb1.setCharAt(5, 'Y'); System.out.println("Value System.out.println("V alue of String Buffer = " + sb1); } }
THE SYSTEM AND RUNTIME CLASSES
The System and Runtime classes provide a means for your programs to access system and runtime environment resources. Like the Math class, the System class is final and is entirely composed of static variables and methods. The System class basically provides a system-independent programming interface to system resources. Examples of system resources include the standard input and output streams, System.in and System.out, which typically model the keyboard and monitor. The Runtime class provides direct access to the runtime environment. An example of a run-time routine is the freeMemory method, which returns the amount of free system memory available. EXAMPLE FOR RUNTIME public class RuntimeExample { public static void main(String args[]) { try { Runtime run = Runtime.getRuntime(); run.exec("notepad.exe"); } catch(Exception err) { System.out.println("Exception System.out.println("E xception " +err.getMessage()); } } }
THREAD CLASSES
Java is a multithreaded environment and provides various classes for managing and working with threads. Following are the classes and interfaces used in conjunction with multithreaded programs: Thread ThreadDeath ThreadGroup Runnable
. The Thread class is used to create a thread of execution in a program. The ThreadDeath class is used to clean up after a thread has finished execution. As its name implies, the ThreadGroup class is useful for organizing a group of threads. Finally, the Runnable interface provides an alternate means of creating a thread without subclassing the Thread class. CLASS CLASSES
Java provides two classes for working with classes: Class and ClassLoader. The Class class provides runtime information for a class, such as the name, type, and parent superclass. Class is useful for querying a class for runtime information, such as the class name. The ClassLoader class provides a means to load classes into the runtime environment. ClassLoader is useful for loading classes from a file or for loading distributed classes across a network connection. Example to print the class name of an object:
void printClassName(Object obj) { System.out.println("The class of " + obj + " is " + obj.getClass().getName()); obj.getClass().getName()); }
.
The Utilities Utilitie s P ackage – java.util
.
CHAPTER- 3: THE UTILITIES PACKAGE – java.util
The Java utilities, package, which is also known as java.util, provides various classes that perform different utility functions. The utilities package includes a class for working with dates, a set of data structure classes, a class for generating random numbers, and a string tokenizer class, among others. The most important classes contained in the utilities package follow:
The Date Class Data Structure Classes The Random Class The StringTokenizer Class The Properties Class The Observer Interface The Enumeration Interface
THE DATE CLASS
The Date class represents a calendar date and time in a system-independent fashion. The Date class provides methods for retrieving the current date and time as well as computing days of the week and month. EXAMPLE FOR DATE CLASS import java.util.Date; public class DateExample { public static void args[]) { String days[] {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; Date sys_date = new Date(); Date date = new Date(101,8,3); System.out.println("System (sys_date.toString())); System.out.println("Specified (date.toString()));
Date Date
:
main(String =
" :
"
+ +
int day = date.getDay();System.out.println("The day for the specified date : " + days[day]);System.out.println("Does the specified date precede the system date ? ");System.out.println(date.before(sys_date)); }}
THE CALENDAR CLASS Calendar is an abstract base class for converting between a Date object and a set of integer fields such as YEAR, MONTH, DAY, HOUR, and so on. (A Date object represents a specific instant in time with millisecond precision. See java.util.Date for information about the Date class.)
. Subclasses of Calendar interpret a Date according to the rules of a specific calendar system. The JDK provides one concrete subclass of Calendar: GregorianCalendar. Future subclasses could represent the various types of lunar calendars in use in many parts of the world. Like other locale-sensitive classes, Calendar provides a class method, getInstance, for getting a generally useful object of this type. Calendar's getInstance method returns a GregorianCalendar object whose time fields have been initialized with the current date and time:
EXAMPLE FOR CALENDAR CLASS import java.util.Calendar; public class CalendarExample { public static void main(String args[]) { Calendar calendar = Calendar.getInstance Calendar.getInstance(); (); int date = calendar.get(Calendar calendar.get(Calendar.DATE); .DATE); int month = calendar.get(Calendar calendar.get(Calendar.MONTH); .MONTH); int year = calendar.get(Calendar. calendar.get(Calendar.YEAR); YEAR); System.out.println("Date : " + date + "/" + (month+1) + "/" +year); calendar.add(Calendar.DATE,50); date = calendar.get(Calendar. calendar.get(Calendar.DATE); DATE); month = calendar.get(Calendar calendar.get(Calendar.MONTH); .MONTH); year = calendar.get(Calendar. calendar.get(Calendar.YEAR); YEAR); System.out.println("Latest (month+1) + "/" +year);
date
:
"
+
date
+
"/"
+
} }
Data Structure Classes The Java data structure classes and interfaces implement popular data structures for storing data. The data structure classes and interfaces are as follows: Dictionary Hashtable Vector Stack Enumeration Random
THE RANDOM CLASS
Many programs, especially programs that model the real world, require some degree of randomness. Java provides randomness by way of the Random class. The Random class implements a random-number generator by
.
providing a stream of pseudo-random numbers. A slot machine program is a good example of one that would make use of the Random class. EXAMPLE FOR RANDOM CLASS import public public Random
java.util.*; class RandomExample { static void main(String args[]) { random = new Random();
System.out.println("Random (random.nextInt())); System.out.println("Random (random.nextFloat()));
number(int):"
number(float):
+
"
+
System.out.println("Random number(double): " System.out.println("Random +(random.nextDouble())); System.out.println("Random number(gaussian): " System.out.println("Random +(random.nextGaussian())); Date date = new Date(); Random seed_random = new Random(date.getTime()) Random(date.getTime()); ; System.out.println("Random number with seed(int): " System.out.println("Random +(seed_random.nextInt())); System.out.println("Random number with seed(float): " System.out.println("Random +(seed_random.nextFloat())); System.out.println("Random number with seed(double): " + System.out.println("Random (seed_random.nextDouble())); System.out.println("Random number with seed(gaussian) : " System.out.println("Random +(seed_random.nextGaussian())); } }
THE STRINGTOKENIZER CLASS The StringTokenizer class provides a means of converting text strings into individual tokens. By specifying a set of delimiters, you can parse text strings into tokens using the StringTokenizer class. String tokenization is useful in a wide variety of programs, from compilers to text-based adventure games. public class StringTokenizer extends Object implements Enumeration 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. An instance of StringTokenizer behaves in one of two ways, depending on whether it was created with the returnTokens flag having the value true or false:
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 considered to be tokens. A token is either one delimiter character, or a maximal sequence of consecutive characters that are not delimiters.
The following is one example of the use of the tokenizer. The code: StringTokenizer st = new StringTokenizer("this is a test"); while (st.hasMoreTokens()) { println(st.nextToken()); } prints the following output: this is a test
EXAMPLE FOR STRINGTOKENIZER STRINGTOKENIZER import java.util.StringTokenizer java.util.StringTokenizer; ; public class TokenizerExample { public static void main(String args[]) { char temp = (char)-1; String input = ""; System.out.println("Enter System.out.println("Ente r a string "); try { do { temp = (char)System.in.read(); input = input + temp; }while(temp != '\n'); } catch(Exception err){} input = input.trim(); System.out.println("Printing System.out.println("Prin ting tokens..."); StringTokenizer tokenizer = new StringTokenizer(input); System.out.println("Number of tokens "+(tokenizer.countTokens()));
:
. while(tokenizer.hasMoreTokens()) { System.out.println(tokenizer.nextToken()); } } }
THE HASHTABLE CLASS This class implements a hashtable, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. An instance of Hashtable has two parameters that affect its efficiency: its capacity and its load factor. The load factor should be between 0.0 and 1.0. When the number of entries in the hashtable exceeds the product of the load factor and the current capacity, the capacity is increased by calling the rehash method. Larger load factors use memory more efficiently, at the expense of larger expected time per lookup. If many entries are to be made into a Hashtable, creating it with a sufficiently large capacity may allow the entries to be inserted more efficiently than letting it perform automatic rehashing as needed to grow the table. This example creates a hashtable of numbers. It uses the names of the numbers as keys: Hashtable numbers = new Hashtable(); numbers.put("one", numbers.put("one", new Integer(1)); Integer(1)); numbers.put("two", new Integer(2)); numbers.put("three", numbers.put("three", new Integer(3));
To retrieve a number, use the following code: Integer n = (Integer)numbers.get("two"); if (n != null) { System.out.println("two = " + n); } EXAMPLE FOR HASHTABLE CLASS import java.util.*; public class HashtableExample { public static void main(String args[]) { Hashtable hash = new Hashtable(); String days[] = {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; {"Sun","Mon","Tue","Wed","Thur","Fri","Sat"}; for(int index=0;index
. Date date = new Date(); int day = date.getDay(); Integer pos = new Integer(day); System.out.println("Day : " + (hash.get(pos).toStri (hash.get(pos).toString())); ng())); } }
THE STACK CLASS
The Stack class represents a last-in-first-out (LIFO) stack of objects. EXAMPLE FOR STACK CLASS import java.util.*; public class StackExample { public static void main(String args[]) { Stack stack = new Stack(); Date date = new Date(); StringTokenizer tokenizer = StringTokenizer(date.toString()); System.out.println("tokens System.out.println("toke ns : "+tokenizer.countToken "+tokenizer.countTokens()); s()); while (tokenizer.hasMoreTokens() (tokenizer.hasMoreTokens()) ) { stack.push(tokenizer.nextToken()); }
new
Object obj = stack.peek(); System.out.println("First System.out.println("First (obj.toString()));
element element in
stack stack
-
by peek :
" +
System.out.println("Pop out the elements in stack "); while(!stack.empty()) { obj = stack.pop(); System.out.println(obj.toString()); } } }
THE VECTOR CLASS
The Vector class implements a growable array of objects. Like an array, it contains components that can be accessed using an integer index. However, the size of a Vector can grow or shrink as needed to accommodate adding and removing items after the Vector has been created. Each vector tries to optimize storage management by maintaining a capacity and a capacityIncrement. The capacity is always at least as large as the vector size; it is usually larger because as components are added to the vector, the vector's storage
. increases in chunks the size of capacityIncrement. An application can increase the capacity of a vector before inserting a large number of components; this reduces the amount of incremental reallocation. EXAMPLE FOR VECTOR CLASS import java.util.*; public class VectorExample { public static void main(String args[]) { Vector store = new Vector(); String input = ""; char temp = (char)-1; System.out.println("Enter System.out.println("Ente r a string "); try { do { temp = (char)System.in.read(); input = input+temp; }while(temp != '\n'); input = input.trim(); }catch(Exception err){} StringTokenizer tokenizer = new StringTokenizer(input); while(tokenizer.hasMoreTokens()) while(tokenizer.hasMoreT okens()) { store.addElement(tokenizer.nextToken()); } System.out.println("Size of the Vector : "+store.size()); System.out.println("Capacity "+store.capacity());
of
the
Vector
:
System.out.println("First System.out.println("Firs t Element : "+store.firstElement()); System.out.println("Last System.out.println("Las t Element : "+store.lastElement()); Enumeration enum = store.elements(); while(enum.hasMoreElements()) { System.out.println(enum.nextElement().toString()); } store.trimToSize(); System.out.println("Capacity of the vector after trimming : " + (store.capacity())); } }
.
The Collections Framework The collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently of the details of their representation. representation. It reduces programming effort while increasing performance. It allows for interoperability among unrelated APIs, reduces effort in designing and learning new APIs, and fosters software s oftware reuse. The framework is based on six collection interfaces. It includes implementations of these interfaces, and algorithms to manipulate them. Introduction The 1.2 release of the Java platform includes a new collections framework . A collection is an object that represents a group of objects. A collections framework is a unified architecture for representing and manipulating collections, allowing them to be manipulated independently independently of the t he details of their representation.
The primary advantages of a collections framework are that it:
Reduces programming effort by providing useful data structures and algorithms so you don't have to write them yourself. Increases performance by providing high-performance implementations of useful data structures and algorithms. Because the various implementations of each interface are interchangeable, interchangeable, programs can be easily tuned by switching implementations. Provides interoperability between unrelated APIs by establishing a common language to pass collections back and forth. Reduces the effort required to learn APIs by eliminating the need to learn multiple ad hoc collection APIs. Reduces the effort required to design and implement APIs by eliminating the need to produce ad hoc collections APIs. Fosters software reuse by providing a standard interface for collections and algorithms to manipulate them.
The collections framework consists of:
Collection Interfaces - Represent different types of collections, such as sets, lists and maps. These interfaces form the basis of the framework. General-purpose General-purpose Implementations - Primary implementations of the collection interfaces. Legacy Implementations - The collection classes from earlier releases, Vector and Hashtable, have been retrofitted to implement the collection interfaces. Wrapper Implementations - Add functionality, such as synchronization, to other implementations. Convenience Implementations - High-performance High-performance "mini-implemen " mini-implementations" tations" of the collection interfaces. Abstract Implementations - Partial implementations of the collection interfaces to facilitate custom implementations.
.
Algorithms - Static methods that perform useful functions on collections, such as sorting a list. Infrastructure - Interfaces that provide essential support for the collection interfaces. Array Utilities - Utility functions for arrays of primitives and reference objects. Not, strictly speaking, a part of the Collections Framework, this functionality is being added to the Java platform at the same time and relies on some of the t he same infrastructure.
Collection Interfaces
There are six collection interfaces . The most basic interface is Collection. Three interfaces extend Collection: Set, List, and SortedSet. The other two collection interfaces, Map and SortedMap, do not extend Collection, as they represent mappings rather than true collections. However, these interfaces contain collection- view operations, which allow them to be manipulated as collections.
Collection
The Collection interface is the root of the collection hierarchy. A Collection represents a group of objects, known as its elements . Some Collection implementations allow duplicate elements and others do not. Some are ordered and others unordered. The JDK doesn't provide any direct implementations of this interface: It provides implementations implementations of more specific subinterfaces like Set and List. This interface is the least common denominator that all collections implement. Collection is used to pass collections around and manipulate them when maximum generality is desired. Set
A Set is a collection that cannot contain duplicate elements. As you might expect, this interface models the mathematical set abstraction. It is used to represent sets like the cards comprising a poker hand, the
. courses making up a student's schedule, or the processes running on a machine.
List A List is an ordered collection (sometimes called a sequence ). ). Lists can contain duplicate elements. The user of a List generally has precise control over where in the List each element is inserted. The user can access elements by their integer index (position). If you've used Vector, you're already familiar with the general flavor of List.
Map A Map is an object that maps keys to values. Maps cannot contain duplicate keys: Each key can map to at most one value. If you've used Hashtable, you're already familiar with the general flavor of Map. The last two core collection interfaces (SortedSet and SortedMap) are merely sorted versions of Set and Map Object Ordering
There are two ways to order objects: The Comparable interface provides automatic natural order on classes that implement it, while the Comparator interface gives the programmer complete control over object ordering. Note that these are not core collection interfaces, but underlying infrastructure. The last two core collection interfaces: SortedSet
A SortedSet is a Set that t hat maintains its elements in ascending order. Several additional operations are provided to take advantage of the ordering. The SortedSet interface is used for things like word lists and membership rolls. SortedMap
A SortedMap is a Map that maintains its mappings in ascending key order. It is the Map analogue of SortedSet. The SortedMap interface is used for apps like dictionaries and telephone directories. All of the modification methods in the collection interfaces are labeled optional . Some implementations may not perform one or more of these operations, throwing a runtime exception (UnsupportedOperationException) (UnsupportedOperationException) if they are attempted. Implementations must specify in their documentation which optional operations they support. Several terms are introduced to aid in this specification:
Collections that do not support any modification operations (such as add, remove and clear) are referred to as unmodifiable . Collections that are not unmodifiable are referred to modifiable. Collections that additionally guarantee that no change in the Collection object will ever be visible are referred to as immutable . Collections that are not immutable are referred to as mutable . Lists that guarantee that their size remains constant even though the elements may change are referred to as fixed-size . Lists that are not fixedsize are referred to as variable-size .
. Some implementations may restrict what elements (or in the case of Maps, keys and values) may be stored. Possible restrictions include requiring elements to:
Be of a particular type.
Be non-null.
Obey some arbitrary predicate.
Attempting to add an element that violates an implementation's restrictions results in a runtime exception, typically a ClassCastException, an IllegalArgumentException IllegalArgumentException or a NullPointerException. Attempting to remove or test for the presence of an element that violates an implementation's restrictions may result in an exception, though some "restricted collections" may permit this usage. Collection Implementations
Class that implement the collection interfaces typically have names of the form
< >. >. The general-purpose general-purpose implementations are summarized in the table below: Implementations Hash Has h Table Table Res Resiza izable ble Arra Array y Bal Balanc anced ed Tree Tree Linked Linked List List Set HashSet Interfaces List Map HashMap
TreeSet ArrayList
LinkedList TreeMap
The general-purpose general-purpose implementations support all of the optional operations in the collection interfaces, and have no restrictions on the elements they may contain. The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList and AbstractMap classes provide skeletal implementations of the core collection interfaces, to minimize the effort required to implement them. The API documentation for these classes describes precisely how each method is implemented so the implementer knows which methods should be overridden, given the performance of the "basic operations" of a specific implementation. Design Goals
The main design goal was to produce an API that was reasonably small, both in size, and, more importantly, in "conceptual weight." It was critical that the new functionality not seem alien to current Java programmers; it had to augment current facilities, rather than replacing them. At the same time, the new API had to t o be powerful enough to provide all the advantages described above. To keep the number of core interfaces small, the interfaces do not attempt to capture such subtle distinctions as mutability, modifiability, resizability. Instead, certain c alls in the core interfaces are optional , allowing implementations to throw an UnsupportedOperationException UnsupportedOperationException to indicate that they t hey do not support a specified optional operation. Of course, collection implementers must clearly document which optional operations are supported by an implementation. To keep the number of methods in each core interface small, an interface contains a method only if either:
. 1. It is a truly fundamental operation : a basic operations in terms of which others could be reasonably defined, 2. There is a compelling performance performance reason reason why an important important implementation implementation would want to override it. It was critical that t hat all reasonable representations representations of collections interoperate well. This included arrays, which cannot be made to implement the Collection interface directly without changing the language. Thus, the framework includes methods to allow collections to be dumped into arrays, arrays to be viewed as collections, and maps to be viewed as collections.
.
I nput/ Output Out put package pac kage – java.io
.
CHAPTER – 4 :THE I/O PACKAGE - java.io The Java I/O package, also known as java.io, provides classes with support for reading and writing data to and from different input and output devices, including files. The I/O package includes classes for inputting streams of data, outputting streams of data, working with files, and tokenizing streams of data. The most important classes contained in the I/O package follows:
Input Stream Classes Output Stream Classes File Classes The StreamTokenizer Class
FILE CLASSES
Files are the most widely used method of data storage in computer systems. Java supports files with two different classes: File and RandomAccessFile. The File class provides an abstraction for files that takes into account system-dependent features. The File class keeps up with information about a file including the location where it is stored and how it can be accessed. The File class has no methods for reading and writing data to and from a file; it is only useful for querying and modifying the attributes of a file. In actuality, you can think of the File class data as representing a filename, and the class methods as representing operating system commands that act on filenames. The RandomAccessFile class provides a variety of methods for reading and writing data to and from a file. RandomAccessFile contains many different methods for reading and writing different types of information, namely the data type wrappers.
THE FILE CLASS
Instances of this class represent the name of a file or directory on the host file system. A file is specified by a pathname, which can either be an absolute pathname or a pathname relative to the current working directory. The pathname must follow the naming conventions of the host platform. The File class is intended to provide an abstraction that deals with most of the machine dependent complexities of files and pathnames in a machine-independent fashion. Note that whenever a filename or path is used it is assumed that the host's file naming conventions are used. Example for File import java.io.*; import java.util.Date; public class FileExample { public static void main(String args[]) {
. if(args.length == 0) { System.out.println("Usage : java FileExample "); System.exit(0); } String filename = args[0]; try { File file = new File(filename); System.out.println("File System.out.println("F ile Exists : "+file.exists()); Date date = new Date(file.lastModified()); System.out.println("Last System.out.println("L ast Modified : "+date.toString()); System.out.println("Absolute Path : "+file.getAbsolutePath()); System.out.println("Length System.out.println("L ength of file : "+file.length()); System.out.println("Parent System.out.println("P arent : "+file.getParent()); } catch(Exception err) { System.out.println("Exception System.out.println("Exce ption in accessing file"); } } }
THE RANDOMACCESSFILE CLASS
Instances of this class support both reading and writing to a random access file. An application can modify the position in the file at which the next read or write occurs. This class provides a sense of security by offering methods that allow specified mode accesses of read-only or read-write to files. Example for RandomAccessFile import java.io.*; public class RandomAccessExample { public static void main(String args[]) { if(args.length != 2) { System.out.println("Usage System.out.println("U sage : "); System.out.println("java System.out.println("j ava RandomAccessExample "); System.exit(0); } String sourcefile = args[0]; String destinfile = args[1]; String data = ""; try { File srcfile = new File(sourcefile); File destfile = new File(destinfile); RandomAccessFile srcrdm = new RandomAccessFile(srcfile,"r"); RandomAccessFile dstrdm =new RandomAccessFile(destf RandomAccessFile(destfile,"rw"); ile,"rw");
. System.out.println("The size of the file "+srcrdm.length()); System.out.println("The file pointer is at "+srcrdm.getFilePointer()); data = srcrdm.readLine(); while(!data.equals("")) { dstrdm.writeBytes(data); data = srcrdm.readLine(); } System.out.println("File successfully copied"); System.out.println("Open the destination file to view the result"); } catch(Exception err) { } }}
INPUT STREAM CLASSES
Java uses input streams to handle reading data from an input source. An input source can be a file, a string, memory, or anything else that contains data. The input stream classes follow:
InputStream BufferedInputStream ByteArrayInputStream DataInputStream FileInputStream FilterInputStream LineNumberInputStream PipedInputStream PushbackInputStream SequenceInputStream StringBufferInputStream
The InputStream class is an abstract class that serves as the base class for all input streams. The InputStream class defines an interface for reading streamed bytes of data, finding out the number of bytes available for reading, and moving the stream position pointer, among other things. All the other input streams provide support for reading data from different types of input devices. OUTPUT STREAM CLASSES
Output streams are the counterpart to input streams and handle writing data to an output source. Similar to input sources, output sources s ources include files, strings, memory, and anything else that can contain data. The output stream classes defined in java.io follow:
OutputStream BufferedOutputStream ByteArrayOutputStream DataOutputStream
.
FileOutputStream FilterOutputStream PipedOutputStream PrintStream
The OutputStream class is an abstract class that serves as the base class for all output streams. OutputStream defines an interface for writing streamed bytes of data to an output source. All the other output streams provide support for writing data to different output devices. Data written by an output stream is formatted to be read by an input stream. THE BUFFEREDINPUTSTREAM CLASS
The class implements a buffered input stream. By setting up such an input stream, an application can read bytes from a stream without necessarily causing a call to the underlying system for each byte read. The data is read by blocks into a buffer; subsequent reads can access the data directly from the buffer. Example for BufferedInputStream BufferedInputStream import java.io.*; class BufferedExample { public static void main (String args[]) { BufferedInputStream in = BufferedInputStream(System.in); byte buf[] = new byte[10]; try { in.read(buf, 0, 10); } catch (Exception e) { System.out.println(“Error: System.out.println(“Erro r: “ + e.toString()); } String s = new String(buf, 0); System.out.println(s); } }
new
THE BUFFEREDOUTPUTSTREAM CLASS
The class implements a buffered output stream. By setting up such an output stream, an application can write bytes to the underlying output stream without necessarily causing a call to the underlying system for each byte written. The data is written into a buffer, and then written to the underlying stream if the buffer reaches its capacity, the buffer output stream is closed, or the buffer output stream is explicity flushed. Example for BufferedOutputStream BufferedOutputStream Class import java.io.*; class WriteStuff { public static void main (String args[]) { // Copy the string into a byte array String s = new String(“Dance, spider!\n”); byte[] buf = new byte[64];
. s.getBytes(0, s.length(), buf, 0); // Output the byte array (buffered) BufferedOutputStream out BufferedOutputStream(System.out); BufferedOutputStream(Sys tem.out); try { out.write(buf, 0, 64); out.flush(); } catch (Exception e) { System.out.println(“Error: System.out.println(“Erro r: “ + e.toString()); } } }
=
new
THE DATAINPUTSTREAM CLASS
A data input stream lets an application read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream. Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. All characters in the range '\u0001' to '\u007F' are represented by a single byte: 0bits 0-7 The null character '\u0000' and characters in the range '\u0080' to '\u07FF' are represented by a pair of bytes: 110bits 6-1010bits 0-5 Characters in the range '\u0800' to '\uFFFF' are represented by three bytes: 1110bits 12-1510bits 6-1110bits 0-5
The two differences between this format and the "standard" UTF-8 format are the following:
The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that the encoded strings never have embedded nulls. Only the 1-byte, 2-byte, and 3-byte formats are used.
Example for DataInputStream DataInputStream and DataOutputStream DataOutputStream import import import import import import
java.io.DataInputStream; java.io.DataOutputStream; java.io.FileInputStream; java.io.FileOutputStream; java.io.File; java.io.IOException;
. public class DataIOApp { public static void main(String args[]) throws IOException { File file = new File("test.txt"); FileOutputStream outFile = new FileOutputStream(file); DataOutputStream outStream = new DataOutputStream(outFile); outStream.writeBoolean(true); outStream.writeInt(123456); outStream.writeChar('j'); outStream.writeDouble(1234.56); System.out.println(outStream.size()+" System.out.println(outStr eam.size()+" bytes were written"); outStream.close(); outFile.close(); FileInputStream inFile = new FileInputStream(file FileInputStream(file); ); DataInputStream inStream = new DataInputStream(inFile); System.out.println(inStream.readBoolean()); System.out.println(inStream.readInt()); System.out.println(inStream.readChar()); System.out.println(inStream.readDouble()); inStream.close(); inFile.close(); file.delete(); } }
THE FILEINPUTSTREAM CLASS
A file input stream is an input stream for reading data from a File or from a FileDescriptor. Example for FileInputStream import java.io.*; class ReadFile { public static void main (String args[]) { byte buf[] = new byte[64]; try { FileInputStream in = new FileInputStream(“Grocery.txt”); in.read(buf, 0, 64); } catch (Exception e) { System.out.println(“Error: System.out.println(“Erro r: “ + e.toString()); } String s = new String(buf, 0); System.out.println(s); }}
. THE FILEOUTPUTSTREAM CLASS
A file output stream is an output stream for writing data to a File or to a FileDescriptor. Example for FileOutputStream import java.io.*; class WriteFile { public static void main (String args[]) { // Read the user input byte buf[] = new byte[64]; try { System.in.read(buf, 0, 64); } catch (Exception e) { System.out.println(“Error: System.out.println(“Erro r: “ + e.toString()); } // Output the data to a file try { FileOutputStream out = new FileOutputStream(“Output.txt”); out.write(buf); } catch (Exception e) { System.out.println(“Error: System.out.println(“Erro r: “ + e.toString()); } } }
THE BYTEARRAYINPUTSTREAM CLASS
This class allows an application to create an input stream in which the bytes read are supplied by the contents of a byte array. Applications can also read bytes from a string by using a StringBufferInputStream. Example for Byte Array input/output stream import java.io.ByteArrayInputStr java.io.ByteArrayInputStream; eam; import java.io.ByteArrayOutputSt java.io.ByteArrayOutputStream; ream; import java.io.IOException; public class ByteArrayIOApp { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream = ByteArrayOutputStream(); String s = "This is a test."; for(int i=0;i
new
. System.out.println("size: "+outStream.size()); ByteArrayInputStream inStream; inStream = new ByteArrayInputStream(outStream.toByteArray()); int inBytes = inStream.available(); System.out.println("inStream has "+inBytes+" available bytes"); byte inBuf[] = new byte[inBytes]; int bytesRead = inStream.read(inBuf,0 inStream.read(inBuf,0,inBytes); ,inBytes); System.out.println(bytesRead+" System.out.println(bytesRe ad+" bytes were read"); System.out.println("They are: "+new String(inBuf)); } }
THE BYTEARRAYOUTPUTSTREAM CLASS
This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it. The data can be retrieved using toByteArray() and toString(). t oString(). THE CHARARRAYREADER CLASS
This class implements a character buffer that can be used as a character-input stream. Example for CharArrayReader and Writer import java.io.CharArrayReader; import java.io.CharArrayWriter; import java.io.IOException; public class CharArrayIOApp { public static void main(String args[]) throws IOException { CharArrayWriter outStream = new CharArrayWriter(); String s = "This is a test."; for(int i=0;i
. THE LINENUMBERREADER CLASS
A buffered character-input stream that keeps track of line numbers. A line is considered to be terminated by any one of a line feed ('\n'), a carriage return ('\r'), or a carriage return followed immediately by a linefeed. Example for LineNumberReader LineNumberReader import import import import
java.io.LineNumberReader; java.io.FileReader; java.io.BufferedWriter; java.io.IOException;
public class LineNumberIOApp { public static void main(String args[]) throws IOException { FileReader inFile = new FileReader("LineNumberIOApp.java"); FileReader("LineNumberIOApp.java"); LineNumberReader inLines = new LineNumberReader(inFile); String inputLine; while ((inputLine=inLines.readLine()) != null) { System.out.println(inLines.getLineNumber()+". System.out.println(inLine s.getLineNumber()+". "+inputLine); } } }
THE PUSHBACKINPUTSTREAM CLASS
This class is an input stream filter that provides a buffer into which data can be "unread." An application may unread data at any time by pushing it back into the buffer, as long as the buffer has sufficient room. Subsequent reads will read all of the pushed-back data in the buffer before reading from the underlying input stream. This functionality is useful when a fragment of code should read an indefinite number of data bytes that are delimited by particular byte values. After reading the terminating byte the code fragment can push it back, so that the next read operation on the input stream will re-read that byte. Example PushbackInputStream and OutputStream Classes import import import import
java.io.PushbackInputStream; java.io.PushbackInputStream; java.io.ByteArrayInputStream; java.io.ByteArrayInputStr eam; java.io.ByteArrayOutputStream; java.io.ByteArrayOutputSt ream; java.io.IOException;
public class PushbackIOApp { public static void main(String args[]) throws IOException { ByteArrayOutputStream outStream = ByteArrayOutputStream(); String s = "This is a test."; for(int i=0;i
new
. System.out.println("outstream: "+outStream); System.out.println("outstream: System.out.println("size: "+outStream.size()); ByteArrayInputStream inByteArray; inByteArray = ByteArrayInputStream(outStream.toByteArray());
new
PushbackInputStream inStream; inStream = new PushbackInputStream(inByteArray); char ch = (char) inStream.read(); System.out.println("First character of inStream is "+ch); inStream.unread((int) 't'); int inBytes = inStream.available(); System.out.println("inStream has bytes"); byte inBuf[] = new byte[inBytes];
"+inBytes+"
available
for(int i=0;i
THE SEQUENCEINPUTSTREAM CLASS
The sequence input stream class allows an application to combine several input streams serially and make them appear as if they were a single input stream. Each input stream is read from, in turn, until it reaches the end of the stream. The sequence input stream class then closes that stream and automatically switches to the next input stream. Example for SequenceInputStream SequenceInputStream import java.io.FileInputStream; import java.io.SequenceInputStre java.io.SequenceInputStream; am; import java.io.IOException; public class SequenceIOApp { public static void main(String args[]) throws IOException { SequenceInputStream inStream; FileInputStream f1 = new FileInputStream("ByteArrayIOApp.java"); FileInputStream f2 = new FileInputStream("FileIOApp.java"); FileInputStream("FileIOApp.java"); inStream = new SequenceInputStream(f1,f2); boolean eof = false; int byteCount = 0; while (!eof) {
. int c = inStream.read(); if(c == -1) eof = true; else { System.out.print((char) c); ++byteCount; } } System.out.println(byteCount+" System.out.println(byteCou nt+" bytes were read"); inStream.close(); f1.close(); f2.close(); } }
THE STREAMTOKENIZER CLASS
The StreamTokenizer class takes an input stream and parses it into "tokens", allowing the tokens to be read one at a time. The parsing process is controlled by a table and a number of flags that can be set to various states. The stream tokenizer can recognize identifiers, numbers, quoted strings, and various comment styles. Each byte read from the input stream is regarded as a character in the range '\u0000' through '\u00FF'. The character value is used to look up five possible attributes of t he character: white space, alphabetic, numeric, string quote, and comment character. Each character can have zero or more of these t hese attributes. In addition, an instance has four flags. These flags indicate:
Whether line terminators are to be returned as tokens or treated as white space that merely separates tokens. Whether C-style comments are to be recognized and skipped. Whether C++-style comments are to be recognized and skipped. Whether the characters of identifiers are converted to lowercase.
A typical application first constructs an instance of this class, sets up the syntax tables, and then repeatedly loops calling the nextToken method in each iteration of the loop until it returns the value TT_EOF. Example for StreamTokenizer Class import import import import
java.io.StreamTokenizer; java.io.InputStreamReader; java.io.InputStreamReade r; java.io.BufferedReader; java.io.IOException;
public class StreamTokenApp { public static void main(String args[]) throws IOException { BufferedReader inData = new BufferedReader(new InputStreamReader(System.in));
. StreamTokenizer inStream = new StreamTokenizer(inData); inStream.commentChar('#'); boolean eof = false; do { int token=inStream.nextToken( token=inStream.nextToken(); ); switch(token) { case inStream.TT_EOF: System.out.println("EOF encountered."); eof = true; break; case inStream.TT_EOL: System.out.println("EOL encountered."); break; case inStream.TT_WORD: System.out.println("Word: System.out.println("Word : "+inStream.sval); break; case inStream.TT_NUMBER: System.out.println("Number: System.out.println("Numb er: "+inStream.nval); break; default: System.out.println((char) System.out.println((char ) token+" encountered."); if(token=='!') eof=true; } } while(!eof); } }
. THE PIPEDINPUTSTREAM CLASS
A piped input stream is the receiving end of a communications pipe. Two threads can communicate by having one thread send data through a piped output stream and having the other thread read the data through a piped input stream. Example for Piped Input/Output Operations import java.io.*; public class PipedExample { public static void main(String args[]) { if(args.length == 0) { System.out.println("Usage System.out.println("Usag e : java PipedExample "); System.exit(0); } String filename = args[0]; try { File file = new File(filename); FileInputStream fis = new FileInputStream(file) FileInputStream(file); ; byte store[] = new byte[fis.available()]; byte p_store[] = new byte[fis.available()]; fis.read(store,0,store.length); PipedOutputStream piped_out = new PipedOutputStream(); PipedInputStream piped_in = new PipedInputStream(piped_ PipedInputStream(piped_out); out); piped_out.write(store,0,store.length); piped_in.read(p_store,0,p_store.length); System.out.println("Result stored in file 'output.txt'"); System.out.println("Result FileOutputStream fos = new FileOutputStream("ouput.txt"); fos.write(p_store,0,p_store.length); System.out.println("----------End----------"); } catch(Exception err) { System.out.println("Exception System.out.println("Exc eption in accessing file"); } } }
. THE PRINTSTREAM CLASS
Print values and objects to an output stream, using the platform's default character encoding to convert characters into bytes. If automatic flushing is enabled at creation time, then the stream will be flushed each time a line is terminated or a newline character is written. Methods in this class never throw I/O exceptions. Client code may inquire as to whether any errors have occurred by invoking the checkError method. Note: This class is provided primarily for use in debugging, and for compatibility with existing code; new code should use the PrintWriter class. THE SERIALIZABLE INTERFACE
Serializability of a class is enabled by the class implementing the java.io.Serializable interface. Classes that do not implement this interface will not have any of their state serialized or deserialized. All subtypes of a serializable class are themselves serializable. The serialization interface has no methods or fields and serves only to identify the semantics of being serializable. To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype'spublic, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable in this case. The error will be detected at runtime. During deserialization, the fields of non-serializable classes will be initialized using thepublic or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream. When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object. Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void writeObject(java.io.Obje writeObject(java.io.ObjectOutputStream ctOutputStream out) throws IOException private void readObject(java.io.ObjectInputStream readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException; The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The default mechanism for saving the Object's fields can be invoked by calling out.defaultWriteObject. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.
. The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput. THE EXTENALIZABLE INTERFACE
Externalization allows a class to specify the methods to be used to write the object's contents to a stream and to read them back. The Externalizable interface's writeExternal and readExternal methods are implemented by a class to give the class complete control over the format and contents of the stream for an object and its supertypes. These methods must explicitly coordinate with the supertype to save its state. Object Serialization uses the Serializable and Externalizable interfaces. Object persistence mechanisms may use them also. Each object to be stored is tested for the Externalizable interface. If the object supports it, the writeExternal method is called. If the object does not support Externalizable and does implement Serializable the object should be saved using ObjectOutputStream. When an Externalizable object is to be reconstructed, an instance is created using thepublic no-arg constructor and the readExternal method called. Serializable objects are restored by reading them from an ObjectInputStream. THE OBJECTINPUTSTREAM CLASS
An ObjectInputStream deserializes primitive data and objects previously written using an ObjectOutputStream. ObjectOutputStream and ObjectInputStream can provide an application with persistent storage for graphs of objects when used with a FileOutputStream and FileInputStream respectively. ObjectInputStream is used to recover those objects previously serialized. Other uses include passing objects between hosts using a socket stream or for marshaling and unmarshaling arguments and parameters in a remote communication system. ObjectInputStream ensures that the types of all objects in the graph created from the stream match the classes present in the Java Virtual Machine. Classes are loaded as required using the standard mechanisms. Only objects that support the java.io.Serializable or java.io.Externalizable interface can be read from streams. The method readObject is used to read an object from the stream. Java's safe casting should be used to get the desired type. In Java, strings and arrays are objects and are treated as objects during serialization. When read they need to be cast to the expected type. Primitive data types can be read from the stream using the appropriate method on DataInput. The default deserialization mechanism for objects restores the contents of each field to the value and type it had when it was written. Fields declared as transient or static are ignored by the deserialization process. References to other objects cause those
. objects to be read from the stream as necessary. Graphs of objects are restored correctly using a reference sharing mechanism. New objects are always allocated when deserializing, which prevents existing objects from being overwritten. Reading an object is analogous to running the constructors of a new object. Memory is allocated for the object and initialized to zero (NULL). No-arg constructors are invoked for the non-serializable classes and then the fields of the serializable classes are restored from the stream starting with the serializable class closest to java.lang.object and finishing with the object's most specifiec class. For example to read from a stream as written by the example in ObjectOutputStream: FileInputStream istream = new FileInputStream("t.tmp") FileInputStream("t.tmp");; ObjectInputStream p = new ObjectInputStream(istream); ObjectInputStream(istream); int i = p.readInt(); String today = (String)p.readObject(); (String)p.readObject(); Date date = (Date)p.readObject(); istream.close(); Classes control how they are serialized by java.io.Serializable or java.io.Externalizable interfaces.
implementing
either
the
Implementing the Serializable interface allows object serialization to save and restore the entire state of the object and it allows classes to evolve between the time the stream is written and the time it is read. It automatically traverses references between objects, saving and restoring entire graphs. Serializable classes that require special handling during the serialization and deserialization process should implement both of these methods: private void writeObject(java.io.Obje writeObject(java.io.ObjectOutputStream ctOutputStream stream) throws IOException; private void readObject(java.io.ObjectInputStream readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; The readObject method is responsible for reading and restoring the state of the object for its particular class using data written to the stream by the corresponding writeObject method. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is restored by reading data from the ObjectInputStream for the individual fields and making assignments to the appropriate fields of the object. Reading primitive data types is supported by DataInput. Serialization does not read or assign values to the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state. Any exception that occurs while deserializing an object will be caught by the ObjectInputStream and abort the reading process.
. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs. Example for ObjectInput and Output Streams import import import import import import import import
java.io.ObjectInputStream; java.io.ObjectInputStream; java.io.ObjectOutputStream; java.io.ObjectOutputStrea m; java.io.Serializable; java.io.FileInputStream; java.io.FileOutputStream; java.io.File; java.io.IOException; java.util.Date;
public class ObjectIOApp { public static void main(String args[]) throws IOException, ClassNotFoundException { File file = new File("test.txt"); FileOutputStream outFile = new FileOutputStream(file); ObjectOutputStream outStream = new ObjectOutputStream(outFile); TestClass1 t1 = new TestClass1(true,9,'A',0.0001,"java"); TestClass1(true,9,'A',0.0001,"java"); TestClass2 t2 = new TestClass2(); String t3 = "This is a test."; Date t4 = new Date(); outStream.writeObject(t1); outStream.writeObject(t2); outStream.writeObject(t3); outStream.writeObject(t4); outStream.close(); outFile.close(); FileInputStream inFile = new FileInputStream(file FileInputStream(file); ); ObjectInputStream inStream = new ObjectInputStream(inFile); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); System.out.println(inStream.readObject()); inStream.close(); inFile.close(); file.delete(); } }
. class TestClass1 implements Serializable { boolean b; int i; char c; double d; String s; TestClass1(boolean b,int i,char c,double d,String s) { this.b = b; this.i = i; this.c = c; this.d = d; this.s = s; } public String toString() { String r = String.valueOf(b)+" "; r += String.valueOf(i)+" "; r += String.valueOf(c)+" "; r += String.valueOf(d)+" "; r += String.valueOf(s); return r; } }
class TestClass2 implements Serializable { int i; TestClass1 tc1; TestClass1 tc2; TestClass2() { i=0; tc1 = new TestClass1(true,2,'j',1.234,"Java"); TestClass1(true,2,'j',1.234,"Java"); tc2 = new TestClass1(false,7,'J',2.468,"JAVA"); TestClass1(false,7,'J',2.468,"JAVA"); } public String toString() { String r = String.valueOf(i)+" "; r += tc1.toString()+" "; r += tc2.toString(); return r; } }
THE OBJECTOUTPUTSTREAM CLASS
An ObjectOutputStream writes primitive data types and graphs of Java objects to an OutputStream. The objects can be read (reconstituted) using an ObjectInputStream. Persistent storage of objects can be accomplished by using a file for the stream. If the stream is a network socket stream, the objects can be reconsituted on another host or in another process.
. Only objects that support the java.io.Serializable interface can be written to streams. The class of each serializable object is encoded including the class name and signature of the class, the values of the object's fields and arrays, and the closure of any other objects referenced from the initial objects. The method writeObject is used to write an object to the stream. Any object, including Strings and arrays, is written with writeObject. Multiple objects or primitives can be written to the stream. The objects must be read back from the corresponding ObjectInputstream with the same types and in the same order as they were written. Primitive data types can also be written to the stream using the appropriate methods from DataOutput. Strings can also be written using t he writeUTF method. The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graph of objects can be restored to the same shape as when the original was written. For example to write an object that can be read by the example in ObjectInputStream: FileOutputStream FileOutputStream ostream = new FileOutputStream("t.tmp"); FileOutputStream("t.tmp"); ObjectOutputStream ObjectOutputStream p = new ObjectOutputStream(ostream); ObjectOutputStream(ostream); p.writeInt(12345); p.writeObject("Today"); p.writeObject(new Date()); p.flush(); ostream.close(); Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures: private void readObject(java.io.ObjectInputStream readObject(java.io.ObjectInputStream stream) throws IOException, ClassNotFoundException; private void writeObject(java.io.Obje writeObject(java.io.ObjectOutputStream ctOutputStream stream) throws IOException The writeObject method is responsible for writing the state of the object for its particular class so that the corresponding readObject method can restore it. The method does not need to concern itself with the state belonging to the object's superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput. Serialization does not write out the fields of any object that does not implement the java.io.Serializable interface. Subclasses of Objects that are not serializable can be serializable. In this case the non-serializable class must have a no-arg constructor to allow its fields to be initialized. In this case it is the responsibility of the subclass to save and restore the state of the non-serializable class. It is frequently the case that
. the fields of that class are accessible (public, package, or protected) or that there are get and set methods that can be used to restore the state. Serialization of an object can be prevented by implementing writeObject and readObject methods that throw the NotSerializableException. The exception will be caught by the ObjectOutputStream and abort the serialization process. Implementing the Externalizable interface allows the object to assume complete control over the contents and format of the object's serialized form. The methods of the Externalizable interface, writeExternal and readExternal, are called to save and restore the objects state. When implemented by a class they can write and read their own state using all of the methods of ObjectOutput and ObjectInput. It is the responsibility of the objects to handle any versioning that occurs. THE INPUTSTREAMREADER CLASS
An InputStreamReader is a bridge from byte streams to character streams: It reads bytes and translates them into characters according to a specified character encoding. The encoding that it uses may be specified by name, or the platform's default encoding may be accepted. Each invocation of one of an InputStreamReader's InputStreamReader's read() methods may cause one or more bytes to be read from the underlying byte-input stream. For top efficiency, consider wrapping an InputStreamReader within a BufferedReader; for example, BufferedReader in = new BufferedReader(new BufferedReader(new InputStreamReader(System.in)); Example for InputStreamReader InputStreamReader import java.io.InputStreamReader java.io.InputStreamReader; ; import java.io.BufferedReader; import java.io.IOException; public class InputConversionApp { public static void main(String args[]) throws IOException { InputStreamReader in = new InputStreamReader(System.in); BufferedReader inStream = new BufferedReader(in); System.out.println("Encoding: System.out.println("Encodi ng: "+in.getEncoding()); String inputLine; do { System.out.print(">"); System.out.flush(); inputLine=inStream.readLine(); System.out.println(inputLine); } while (inputLine.length() != 0); } }
. THE OUTPUTSTREAMWRITER CLASS
Write characters to an output stream, translating characters into bytes according to a specified character encoding. Each OutputStreamWriter incorporates its own CharToByteConverter, CharToByteConverter, and is thus a bridge from character streams to byte streams. The encoding used by an OutputStreamWriter may be specified by name, by providing a CharToByteConverter, or by accepting the default encoding, which is defined by the system sy stem property file.encoding. Each invocation of a write() method causes the encoding converter to be invoked on the given character(s). The resulting bytes are accumulated in a buffer before being written to the underlying output stream. The size of this buffer may be specified, but by default it is large enough for most purposes. Note that the characters passed to the write() methods are not buffered. For top efficiency, consider wrapping an OutputStreamWriter within a BufferedWriter so as to avoid frequent converter invocations. For example, Writer out
= new BufferedWriter(new BufferedWriter(new OutputStreamWriter(System.out)); OutputStreamWriter(System.out));
.
G UI and Applet Programming
.
CHAPTER – 5: APPLET PROGRAMMING An applet is a small program that is intended not to be run on its own, but rather to be embedded inside another application. The Applet class must be the superclass of any applet that is to be embedded in a Web page or viewed by the Java Applet Viewer. The Applet class provides a standard interface between applets and their environment. HelloWorld Applet
Applets can be run in a browser such as Netscape Navigator, Internet Explorer. Several differences exist between applets and applications. The most important of these is that Java applet classes extend an existing class. This class is called java.applet.Applet. You have to extend Applet in order for a class to be usable as such. One of the simplest applets is the HelloWorld applet, the source code for which is shown below. Right away you should see that the applet HelloWorld is quite different from the HelloWorld application. HelloApplet.java import java.applet.Applet; import java.awt.Graphics; public class HelloApplet extends Applet { public void paint (Graphics g) { g.drawString ("Hello World!",0,50); } }
Creating HTML file
When you created the HelloWorld application , you ran them using the Java interpreter. Applets, however, don't run from the command line; they are executed within a browser. To get the applet into the browser, you need to embed what are known as HTML tags into an HTML file. The HTML file can then be read into a browser. The simplest HTML file for the HelloApplet class is shown.