+ All Categories
Home > Documents > A Basic Java Course Material

A Basic Java Course Material

Date post: 08-Apr-2018
Category:
Upload: harikumarmpl
View: 221 times
Download: 0 times
Share this document with a friend

of 176

Transcript
  • 8/7/2019 A Basic Java Course Material

    1/176

    .

    Basic Java Material

    Contents:1. Introduction to Java and OOC

    2. The Language Package3. The Utilities Package

    4. I/O Package5. Multithreading6. GUI and Applet Programming

    7. Networking8. JDBC

    1

  • 8/7/2019 A Basic Java Course Material

    2/176

    .

    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

    2

  • 8/7/2019 A Basic Java Course Material

    3/176

    .

    3

    Introduction to Java and

    Object Oriented Concepts

  • 8/7/2019 A Basic Java Course Material

    4/176

    .

    CHAPTER-1: INTRODUCTION TO JAVA

    Java, a Web programming technology, had altered the course of softwaredevelopment, especially in regard to the Internet. Java sports all features necessaryfor 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 theWeb 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 makesJava unique is that it is the first programming language that can be used for writinggeneral-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 thedevelopment of large software, the concept of package is used. The major differencewas the removal of the direct use of pointers. Java automatically handlesreferencing and dereferencing of language objects. Other difference includes theremoval of support for data structures like struct, union. Its in-built classesprovide this. Also, the concepts ofoperator overloading and multiple-inheritancein 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 notpossible to write a Java program that does something meaningful without using the

    class construct. Java language comes with very powerful set of pre-defined classeswith a hierarchy level.

    DISTRIBUTED NATURE

    Java provides the network capabilities by a pre-defined package java.net. Thispackage has many classes that simplify the network communication. Accessing toany 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 .exefile. Instead the compiler produces an intermediate code called as 'byte code'. Javabyte code is an architecturally neutral representation of the program, that is, it isindependent of any processor type or machine architecture. These byte codes areread by the Java interpreter and the same is executed using an internal model of anabstract machine. The Java Interpreter and the implementation of this abstractmachine are called the JAVA VIRTUAL MACHINE.

    SECURE LANGUAGE

    Before any Java program is interpreted, the Java runtime system performs a byte-code 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 localclasses. This prevents any other program to affect the system classes.

    4

  • 8/7/2019 A Basic Java Course Material

    5/176

    .

    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 World!!");}

    }

    Create the file

    Save this into a file called HelloWorld.java using any text editor. It is very important tocall the file HelloWorld.java, because the compiler expects the file name to match theclass 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.javafile. Inside this file (HelloWorld.class) is text known as bytecodes which can be run bythe Java interpreter.

    Run the program

    Now that you have compiled the program, you can run it by typing at the commandprompt:

    Promtpt> java HelloWorld

    The input to the interpreter is nothing but the name of the class that has the mainmethod.

    After you do this, the 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 firstline of the HelloWorld application:

    public class HelloWorld {

    5

  • 8/7/2019 A Basic Java Course Material

    6/176

    .

    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 isalso a closing brace (}). The braces tell the compiler where your class will begin andend. 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 mini-programs. 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 theplace that all Java applications start. For instance, when you run java HelloWorld, theJava 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 youwould like.

    The System.out line is run because, when the application starts up, the interpreterlooks at the first line of code (namely the printout) and executes it. If you place anyother code there, it runs that code instead.

    The System.out.println serves approximately the same purpose as the writeln inPascal. 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("HelloWorld!!"). The difference between println and print is that print does not add acarriage 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 torestrict access to the method. Regardless of what the access specifier is, though, themethod is accessible from any other method in the same class.

    public

    The public modifier is the most relaxed modifier possible for a method. By specifyinga method as public it becomes accessible to all classes regardless of their lineage ortheir package. In other words, a public method is not restricted in any way.

    6

  • 8/7/2019 A Basic Java Course Material

    7/176

    .protected

    The second possible access modifier is protected. Protected methods can beaccessed by any class within the current package, but are inaccessible to any classoutside the package.

    defaultThe next access modifier that can be applied to a class is that of default. Defaultmethods 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 privatemethod is only accessible by those methods in the same class. Even classes thatextend 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 willbe 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 itcommon to all object references of that class. While non-static methods can alsooperate with static variables, static methods can only deal with static variables andstatic methods.

    abstract

    Abstract methods are simply methods that are declared, but are not implemented inthe current class. The responsibility of defining the body of the method is left tosubclasses of the current class.

    final

    By placing the keyword final in front of the method declaration, you prevent anysubclasses of the current class from overriding the given method. This abilityenhances the degree of insulation of your classes, you can ensure that thefunctionality 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 soprevents 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 benefitssuch as faster execution time. Like abstract methods, they are declared simply byplacing the modifier native in front of the method declaration and by substituting asemicolon for the method body.

    synchronized

    By placing the keyword synchronized in front of a method declaration, you canprevent data corruption that may result when two methods attempt to access thesame piece of data at the same time. While this may not be a concern for simpleprograms, once you begin to use threads in your programs, this may become aserious problem.

    7

  • 8/7/2019 A Basic Java Course Material

    8/176

    .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 methodand 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 toallocate memory for an instance of the class and points variable to the new section ofmemory. In the process of doing this, the compiler also calls the class's constructormethod and passes the appropriate 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 membervalue 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 toprint 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

    8

  • 8/7/2019 A Basic Java Course Material

    9/176

    .{

    public static void main (String args[]{

    int inChar =0;System.out.println("Enter a Character:");

    try{

    inChar = System.in.read();System.out.println("You entered " + inChar);

    }catch (IOException e){

    System.out.println("Error reading from user");}

    }}

    You've probably already noticed that there is a lot more to this code than there wasto the last one. Lets first compile the program.

    Enter a Character:AYou 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 amethod is then able to be used in an expression. In the case of ReadHello, a variablecalled inChar is set to the value which is returned by the System.in.read() method.

    In the next line, the value of the inChar variable is added to the System.out string. Byadding the variable into the string, you can see the results of your work. It's notactually necessary to use a variable. If you prefer, you can print it out directly in thesecond System.out line, by changing it to

    System.out.println("You entered "+ System.in.read());

    Now, notice that the program displays a number instead of a character for what youentered. This is because the read() method of System.in returns an integer, not anactual character. The number corresponds to what is known as the ASCII characterset.

    Converting integer to character

    To convert the number that is returned from System.in into a character, you need todo what is known as a cast. Casting effectively converts a given data type to anotherone.

    ---

    inChar =(char) System.in.read();---

    9

  • 8/7/2019 A Basic Java Course Material

    10/176

    .Notice the characters before System.in.read().The (char) causes the integer to bechanged into a character.

    The Rest of the Extra Codetry, 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 isno way for you as a programmer to catch it and deal with the problem. In somelanguages, it's a bit complicated. In Java, most problems cause what are known asExceptions.

    When a method states that it will throw an exception, it is your responsibility to onlytry to perform that method, and if it throws the exception, you need to catch it. Seethe line of code right after the catch phase. If there is an error while reading, anexception called an IOException is thrown. When that happens, the code in the catchblock is called.

    JAVA LANGUAGE FUNDAMENTALS

    KEYWORDS

    The following is a list of the 56 keywords you can use in Java.

    abstract boolean Break Bytecase cast Catch Char class const Continue Defaultdo double Else Extendsfinal finally Float for future generic Goto if

    implements import Inner instanceof int interface Long nativenew null Operator outer package private Protected publicrest return Short staticsuper switch Synchronized thisthrow throws Transient tryvar void Volatile while

    EXTENDING OBJECTS THROUGH INHERITANCE

    Inheritance is a feature of OOP programming that enables us inherit all the commonfeatures of a parent class onto a child class, it's not necessary to reinvent the objectevery time. When new classes inherit the properties of another class, they arereferred to as child classes or subclasses. The class from which they are derived isthen called a parent or super class.

    A Simple Inheritance Program

    class BaseClass{public BaseClass(){System.out.println("Base Class Constructor Called");}

    10

  • 8/7/2019 A Basic Java Course Material

    11/176

    .}

    /*DerivedClass extends or inherits the propertyof the BaseClass

    */class DerivedClass extends BaseClass{public DerivedClass(){System.out.println("Derived 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, theparent class constructor is invoked first.

    INTERFACES

    Interfaces are Java's substitute for C++'s feature of multiple inheritance, the practiceof allowing a class to have several super classes. While it is often desirable to have aclass inherit several sets of properties, for several reasons the creators of Javadecided not to allow multiple inheritance. Java classes, however, can implementseveral 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 thatnone ofthe methods in your interface may have a body.

    An Interface Example

    public interface Product{

    public int getPrice(int id);}

    public class Shoe implements Product

    11

  • 8/7/2019 A Basic Java Course Material

    12/176

    .{

    public int getPrice(int id){if (id == 1)

    return(5);

    elsereturn(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 InterfacesBy 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 givenpackage to implement it as well.

    The rules for an interface name are identical to those for classes.

    Extending Other Interfaces

    In keeping with the OOP practice of inheritance, Java interfaces may also extendother interfaces as a means of building larger interfaces upon previously developedcode.

    e.g public interface NameOfInterface extends AnotherInterface

    Interfaces cannot extend classes. There are a number of reasons for this, butprobably the easiest to understand is that any class, which the interface would beextending would have its method bodies defined. This violates the "prime directive" ofinterfaces.

    The Interface Body

    The main purposes of interfaces are to declare abstract methods that will be definedin 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

    12

  • 8/7/2019 A Basic Java Course Material

    13/176

    .this process is not overly complicated, there is one important difference that shouldbe 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);

    Note that unlike normal method declarations in classes, declarations in interfaces areimmediately followed by a semicolon.

    All methods in interfaces are public by default, regardless of the presence or absenceof 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 (includingnative, 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 ofmethods, you may also define variables within them. Because you cannot place anycode within the bodies of the methods, all variables declared in an interface must beglobal to the class. Furthermore, regardless of the modifiers used when declaring thefield, 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 explicitlystate 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 classmust override the getPrice(int) method.

    Overriding Methods

    Declaring a method in an interface is a good practice. However, the method cannotbe 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 characteristicof encapsulationthe ability to isolate and insulate information effectively from therest of your program.

    POLYMORPHISM

    Finally, the allure of the OOP approach to creating self-sustaining modules is furtherenhanced 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 performthe same operation on different types of classes as long as they share a common

    13

  • 8/7/2019 A Basic Java Course Material

    14/176

    .trait. While the behavior of each class might be different, you know that the class willbe able to perform the same operation as its parent because it is of the same familytree

    Example of Function Overload

    class Sample {public Sample() {

    System.out.println("Sample Constructor Called"); }public void overloadMe() {

    System.out.println("Overload 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 onits invocation. This is termed as method overloading.

    JAVA DATA TYPES

    Java has Two Types of Data TypesIn Java, there are really two different categories in which data types have beendivided:

    Primitive typesReference 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

    14

  • 8/7/2019 A Basic Java Course Material

    15/176

    .

    short - 16-bit 2s-compliment integer with values between -2^15 and 2^15-1 (-32,768 to 32,767)

    char 16-bit Unicode characters. For alpha-numerics, these are the same as

    ASCII with the high byte set to 0. The numerical values are unsigned 16-bitvalues are between 0 and 65535.

    int 32-bit 2s-compliment integer with values between -231 and 231-1 (-2,147,483,648 to 2,147,483,647)

    long 64-bit 2s-compliment integer with values between -263 and 263-1 (-9223372036854775808 to 9223372036854775807)

    float 32-bit single precision floating point numbers using the IEEE 754-1985standard (+/- about 1039)

    double 64-bit double precision floating point numbers using the IEEE 754-1985standard. (+/- 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;

    IdentifiersThe 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 subsequentcharacters can be letters or numerals. The underscore (_) and the dollar sign ($) maybe used as any character in an identifier, including the first one. Identifiers are case-sensitive and language-sensitive.

    Examples of Legal Identifiers

    HelloWorldcounterHotJava$

    ioc_Queue3

    15

  • 8/7/2019 A Basic Java Course Material

    16/176

    .

    Examples of Illegal Identifiers

    9HelloWorldcount&add

    Hot Java65536

    OPERATORS

    Operators are used to change the value of a particular object. They are describedhere in several related categories.

    UNARY LOGICAL OPERATORS

    Description Operator

    Increment ++

    Decrement --Negation -

    Bitwise complement ~

    Example for Increment and Decrement Operatorsclass 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);

    }}

    Outputx = 8y = 13++x = 9y++ = 13x = 9y = 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

    16

  • 8/7/2019 A Basic Java Course Material

    17/176

    .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 >

    Zero-Fill Right Shift >>>

    Shift Operators

    The left-shift, right-shift, and zero-fill-right-shift operators (, and >>>) shift theindividual bits of an integer by a specified integer amount. The following are someexamples of how these operators are used:

    x > 7;z >>> 2;

    Example for Shift Operators

    class Shift {public static void main (String args[]) {

    int x = 7;

    System.out.println(x = + x);System.out.println(x >> 2 = + (x >> 2));System.out.println(x > 1 = + (x >>> 1));

    }}

    The output of Shift follows:x = 7x >> 2 = 1x >> 1 = 3

    17

  • 8/7/2019 A Basic Java Course Material

    18/176

    .Relational Operators

    The last group of integer operators is the relational operators, which all operate onintegers but return a type boolean.

    Description Operator

    Less Than Less 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 onthe right.

    = assignment operator

    The arithmetic assignment operators provide a shortcut for assigning a value. Whenthe previous value of a variable is a factor in determining the value that you want toassign, 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

    18

  • 8/7/2019 A Basic Java Course Material

    19/176

    .

    It takes the following form:

    expression1 ? expression2 : expression3

    In this syntax, expression1 must produce a Boolean value. If this value is true, thenexpression2 is evaluated, and its result is the value of the conditional. If expression1is false, then expression3 is evaluated, and its result is the value of the conditional.

    Example for Conditional Operatorclass 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, programswould not be able to do anything more than several sequential operations.

    IF STATEMENTS

    if (expression)if_statement;elseelse_statement;

    ITERATION STATEMENTS

    Programmers use iteration statements to control sequences of statements that arerepeated according to runtime conditions.

    Java supports five types of iteration statements:

    whiledoforcontinuebreak

    WHILE STATEMENTS

    while (expression)

    19

  • 8/7/2019 A Basic Java Course Material

    20/176

    .statement;

    DO WHILE LOOP

    dostatement;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 byusing the break statement.

    RETURN STATEMENTS

    A return statement passes control to the caller of the method, constructor, or staticinitializer containing the return statement. If the return statement is in a method that isnot 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};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 otherlanguages, 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, orplace brackets after the identifier name.

    int MyIntArray[];int[] MyIntArray;

    20

  • 8/7/2019 A Basic Java Course Material

    21/176

    .

    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 isMyArray[0], not MyArray[1].

    COMMENTS

    Java supports three styles of comments:

    TraditionalC++ stylejavadoc

    Traditional Comments

    A traditional comment is a C-style comment that begins with a slash-star (/*) andends with a star-slash (*/).

    C++ Style Comments

    The second style of comment begins with a slash-slash (//) and ends when thecurrent source code line ends. These comments are especially useful for describingthe 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 propertiesmentioned previously, but the contents of the comment may be used in automaticallygenerated 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:

    BooleanCharacterFloating-pointIntegerStringInteger Literal

    Example

    int j=0;

    21

  • 8/7/2019 A Basic Java Course Material

    22/176

    .long GrainOfSandOnTheBeachNum=1L;short Mask1=0x007f;String FirstName = "Ernest";char TibetanNine = '\u1049'boolean 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 \rcharacters 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 anexecution stack list. The Exception class is derived from Throwable and provides thebase 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 alsoderived from Throwable, but it is used for handling abnormal errors that arentexpected to occur. Very few Java programs worry with the Error class; most use theException 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 indexis " +get);} catch(Exception err) {System.out.println("Requested Index Not found");}finally {System.out.println("--------End---------");}

    }}

    22

  • 8/7/2019 A Basic Java Course Material

    23/176

    .

    In the above example, the array size is 5, but we are trying to access the 6 th element.As this is a runtime error, an exception is caught and the 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 afteropening it, or something similar. In exception handling, the finally block is executedno 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 Javalanguage. 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 throwstatement. Similarly, only this class or one of its subclasses can be the argumenttype in a catch clause. A Throwable class contains a snapshot of the execution stackof its thread at the time it was created. It can also contain a message string that givesmore information about the error.

    THE EXCEPTION CLASS

    The class Exception and its subclasses are a form of Throwable that indicatesconditions 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 an index value");

    try {do {

    input = (char)System.in.read();data = data + input;

    }while(input!='\n');}catch(Exception err) {

    System.out.println("Unable to obtain system input");}

    23

  • 8/7/2019 A Basic Java Course Material

    24/176

    .try {

    index = Integer.parseInt(data.trim());

    System.out.println("The value in the requested index :"+values[index]);

    }catch(NumberFormatException err) {

    System.out.println("Invalid Index");}catch(ArrayIndexOutOfBoundsException err) {

    System.out.println("Requested 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 gotas a String. It is then parsed into an int data type. The value in the array for this indexis 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 andArrayIndexOutOfBoundsException respectively. So the try block encapsulating theparsing of the input and searching of the index has two catch blocks to handle theseexceptions 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.

    24

  • 8/7/2019 A Basic Java Course Material

    25/176

    .

    Packages:

    Java provides a mechanism for partitioning the classname into more manageablechunks. This mechanism is thepackage.The package is both a naming and avisibility comttrol mechanism. Classes can be defined inside a package that are not

    accessible by code outside the package. Class members can also be defined thatare only exposed to other members of the same package. This is achieved with thehelp of package and access protection.

    Access Protection:

    Java provides many levels of protection to allow fine-grained control over thevisibility 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 thenamespace and scope of variables and methods. Packages act as containers for

    classes and other subordinate packages. Classes act as containers for data andcode. The class is Javas smallest unit of abstraction.

    Java addresses four categories of visibility for class members.

    1. Sub classes in the same package2. Non Subclasses in the same package3. Subclasses in different packages4. Classes are neither in the same package nor subclasses

    The three access specifiers, private, public and protected provide a variety of waysto produce tha many levels of access required by these categories.

    public - Anything declared public can be accessed from anywhere

    private Anything declared private cannot be seen outsideof its class.

    default When a member doesnot have an access specification, it is visible tosubclasses as well as other classes in the same package.

    protected If an element has to be seen outside the current package but only toclasses that subclass your class directly.

    Defining Package:

    Creating a package in Java is quite easy. This is achieved by simply including apackage command as the first statement in a Java Source file. Any classes that aredeclared with in that file belong to the specified package. The package statementdefines 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.

    25

  • 8/7/2019 A Basic Java Course Material

    26/176

    .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 folderUse import keyword for using the classes in different package.

    Example for Package mechanism:

    package com.first.one;

    public class BaseClass{

    int x=6; // default accessprivate int x_pri=2; // private accessprotected int x_pro=3; //protected accesspublic int x_pub=4; //public access

    public BaseClass(){System.out.println("Inside Constructor of Base Class"); }public void display(){

    System.out.println("Value of x(default) is "+x);System.out.println("Value of x(private) is

    "+x_pri);System.out.println("Value of x(protected) is

    "+x_pro);System.out.println("Value of x(public) is "+x_pub);

    }}

    package com.first.one;

    class Derived extends BaseClass{

    Derived(){

    System.out.println("Inside Derived ClassConstrcutor\n");

    System.out.println("Value of x(default) is "+x);

    // Not available to derived class also because it isprivate (Class only)// System.out.println("Value of x(private) is

    "+x_pri);System.out.println("Value of x(protected) is

    "+x_pro);System.out.println("Value of x(public) is "+x_pub);

    }public static void main(String arg[]){

    Derived deri=new Derived();}

    }

    26

  • 8/7/2019 A Basic Java Course Material

    27/176

    .package com.first.one;

    public class TestBaseClass{

    public TestBaseClass()

    {System.out.println("Inside TestBaseClass

    constructor");BaseClass bc1=new BaseClass();System.out.println("Value of x(default) is

    "+bc1.x);

    // Not accessible because private - access is for Class only// System.out.println("Value of x(private) is"+bc1.x_pri);

    System.out.println("Value of x(protected) is"+bc1.x_pro);

    System.out.println("Value 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 of Base class inanother package");

    //Not accessible because it is default - for packageonly

    //System.out.println("Value of x(default) is"+x);

    // Not accessible becuase it is private - for Classonly

    //System.out.println("Value of x(private) is"+x_pri);

    System.out.println("Value of x(protected) is"+x_pro);

    System.out.println("Value of x(public) is "+x_pub);

    }

    27

  • 8/7/2019 A Basic Java Course Material

    28/176

    .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 Constructor ofSomeClass");

    BaseClass bc=new BaseClass();

    // Only for package//System.out.println("Value of x(default) is

    "+bc.x);

    // Only for Class//System.out.println("Value of x(private) is

    "+bc.x_pri);// Only for Class, subClass & package//System.out.println("Value of x(protected) is

    "+bc.x_pro);System.out.println("Value of x(public) is

    "+bc.x_pub);

    }

    public static void main(String arg[]){

    SomeClass sc=new SomeClass();}

    }

    28

  • 8/7/2019 A Basic Java Course Material

    29/176

    .

    29

    The Language

    Package - java.lang

  • 8/7/2019 A Basic Java Course Material

    30/176

    .

    CHAPTER-2: THE LANGUAGE PACKAGE java.lang

    The Java language package, which is also known as java.lang, provides classes thatmake 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 allclasses are derived from, is located in the language package.Its impossible to write a Java program without dealing with at least a few of theelements of the language package. The most important classes contained in thelanguage 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 arederived from Object, the methods defined in Object are shared by all classes. Theseresults 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 implementedas classes. Many times it is useful, however, to know more information about afundamental types than just its value. By implementing class wrappers for thefundamental types, additional information can be maintained, as well as methodsdefined that act on the types. The data type wrapper classes serve as class versionsof the fundamental data types, and are named similarly to the types they wrap. Forexample, 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 Javas utility classes require classes

    as parameters, not simple types. Type wrappers and simple types are notinterchangeable.

    30

  • 8/7/2019 A Basic Java Course Material

    31/176

    .

    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 Mathclass itself is final. This means you cant derive new classes from Math. Additionally,you cant instantiate the Math class. Its best to think of the Math class as just aconglomeration of methods and constants for performing mathematicalcomputations.The Math class includes the E and PI constants, methods for determining theabsolute value of a number, methods for calculating trigonometric functions, andminimum 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 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.exit(0);}

    double d_data = data.doubleValue();

    System.out.println("Printing Math values......");System.out.println("Sin : " + (Math.sin(d_data)));System.out.println("Cos : " + (Math.cos(d_data)));System.out.println("Tan : " + (Math.tan(d_data)));System.out.println("asin : " + (Math.asin(d_data)));System.out.println("acos : " + (Math.acos(d_data)));System.out.println("atan : " + (Math.atan(d_data)));System.out.println("Abs : " + (Math.abs(d_data)));System.out.println("Exp : " + (Math.exp(d_data)));System.out.println("Log : " + (Math.log(d_data)));System.out.println("Sqrt : " + (Math.sqrt(d_data)));

    System.out.println("Ceil : " + (Math.ceil(d_data)));System.out.println("Floor : " + (Math.floor(d_data)));

    31

  • 8/7/2019 A Basic Java Course Material

    32/176

    .System.out.println("rint : " + (Math.rint(d_data)));System.out.println("round : " + (Math.round(d_data)));System.out.println("Random Number : " + (Math.random()));}

    }

    STRING CLASSES

    For various reasons (mostly security related), Java implements text strings asclasses, rather than forcing the programmer to use character arrays. The two Javaclasses that represent strings are String and StringBuffer. The String class is usefulfor working with constant strings that cant change in value or length. TheStringBuffer 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; theirvalues cannot be changed after they are created. String buffers support mutablestrings. 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 thesequence, for comparing strings, for searching strings, for extracting substrings, andfor creating a copy of a string with all characters translated to uppercase or tolowercase. The Java language provides special support for the string concatenationoperator ( + ), and for conversion of other objects to strings. String concatenation isimplemented through the StringBuffer class and its append method. Stringconversions are implemented through the method toString(), defined by Object andinherited 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 of data : "+length);

    32

  • 8/7/2019 A Basic Java Course Material

    33/176

    .System.out.println("Extracting character...");for(int index=0;index

  • 8/7/2019 A Basic Java Course Material

    34/176

    .

    String s = new String("Hello");/** Constructors1. Empty Constructor will create with initial capacity of16 characters.

    2. Constructor with specified characters as the initialcapacity

    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 of StringBuffer = " + sb1);

    //Appending a charactersb1.append('c');System.out.println("Value of StringBuffer = " + sb1);

    //Appending a character arraychar c[] = {'H','e','l','l','o'};sb1.append(c);

    System.out.println("Value of StringBuffer = " + sb1);sb1.append(c,2,3);

    System.out.println("Value of StringBuffer = " + sb1);double d = 12.141354;sb1.append(d);

    System.out.println("Value of StringBuffer = " + sb1);float f = (float)15.1;sb1.append(f);

    System.out.println("Value of StringBuffer = " + sb1);int i = 1;sb1.append(i);System.out.println("Value of StringBuffer = " + sb1);

    long l = 1000000;sb1.append(l);System.out.println("Value of StringBuffer = " + sb1);sb1.append(s);System.out.println("Value of StringBuffer = " + sb1);System.out.println("Capacity = " + sb2.capacity());System.out.println("Character at 5th position = " +sb1.charAt(5));sb1.getChars(0,4,c,0);System.out.println("Chars extracted from Sb1 = " + c);

    //Insert the boolean value at the 5th position

    sb1.insert(5,true);

    34

  • 8/7/2019 A Basic Java Course Material

    35/176

    .

    //Insert the character value at the 9th positionsb1.insert(9,'M');System.out.println("Length of the string buffer = " +sb1.length());

    sb1.reverse();System.out.println("Reverse of the String Buffer = " +sb1);sb1.setCharAt(5, 'Y');System.out.println("Value of String Buffer = " + sb1);}

    }

    THE SYSTEM AND RUNTIME CLASSES

    The System and Runtime classes provide a means for your programs to accesssystem and runtime environment resources. Like the Math class, the System class is

    final and is entirely composed of static variables and methods. The System classbasically provides a system-independent programming interface to systemresources. Examples of system resources include the standard input and outputstreams, System.in and System.out, which typically model the keyboard and monitor.

    The Runtime class provides direct access to the runtime environment. An example ofa run-time routine is the freeMemory method, which returns the amount of freesystem 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 " +err.getMessage());

    }}}

    THREAD CLASSES

    Java is a multithreaded environment and provides various classes for managing andworking with threads. Following are the classes and interfaces used in conjunctionwith multithreaded programs:

    Thread

    ThreadDeath

    ThreadGroup Runnable

    35

  • 8/7/2019 A Basic Java Course Material

    36/176

    .The Thread class is used to create a thread of execution in a program. TheThreadDeath class is used to clean up after a thread has finished execution. As itsname implies, the ThreadGroup class is useful for organizing a group of threads.Finally, the Runnable interface provides an alternate means of creating a threadwithout subclassing the Thread class.

    CLASS CLASSES

    Java provides two classes for working with classes: Class and ClassLoader. TheClass class provides runtime information for a class, such as the name, type, andparent superclass. Class is useful for querying a class for runtime information, suchas the class name. The ClassLoader class provides a means to load classes into theruntime environment. ClassLoader is useful for loading classes from a file or forloading 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());}

    36

  • 8/7/2019 A Basic Java Course Material

    37/176

    .

    37

    The Utilities Package

    java.util

  • 8/7/2019 A Basic Java Course Material

    38/176

    .

    CHAPTER- 3: THE UTILITIES PACKAGE java.util

    The Java utilities, package, which is also known as java.util, provides variousclasses that perform different utility functions. The utilities package includes a

    class for working with dates, a set of data structure classes, a class forgenerating random numbers, and a string tokenizer class, among others. Themost 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-independentfashion. The Date class provides methods for retrieving the current date andtime as well as computing days of the week and month.

    EXAMPLE FOR DATE CLASS

    import java.util.Date;public class DateExample { public static void main(Stringargs[]) {

    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 Date : " +(sys_date.toString()));

    System.out.println("Specified Date : " +(date.toString()));

    int day = date.getDay();System.out.println("The day forthe specified date : " +days[day]);System.out.println("Does the specified dateprecede 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 ofinteger 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 forinformation about the Date class.)

    38

  • 8/7/2019 A Basic Java Course Material

    39/176

    .Subclasses of Calendar interpret a Date according to the rules of a specific calendarsystem. The JDK provides one concrete subclass of Calendar: GregorianCalendar.Future subclasses could represent the various types of lunar calendars in use inmany 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 methodreturns a GregorianCalendar object whose time fields have been initialized with thecurrent date and time:

    EXAMPLE FOR CALENDAR CLASS

    import java.util.Calendar;

    public class CalendarExample{public static void main(String args[]){

    Calendar calendar = Calendar.getInstance();int date = calendar.get(Calendar.DATE);int month = calendar.get(Calendar.MONTH);int year = calendar.get(Calendar.YEAR);

    System.out.println("Date : " + date + "/" + (month+1) +"/" +year);

    calendar.add(Calendar.DATE,50);

    date = calendar.get(Calendar.DATE);month = calendar.get(Calendar.MONTH);year = calendar.get(Calendar.YEAR);

    System.out.println("Latest date : " + date + "/" +(month+1) + "/" +year);

    }}

    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 somedegree of randomness. Java provides randomness by way of the Randomclass. The Random class implements a random-number generator by

    39

  • 8/7/2019 A Basic Java Course Material

    40/176

    .

    providing a stream of pseudo-random numbers. A slot machine program is agood example of one that would make use of the Random class.

    EXAMPLE FOR RANDOM CLASS

    import java.util.*;public class RandomExample {public static void main(String args[]) {Random random = new Random();

    System.out.println("Random number(int):" +(random.nextInt()));

    System.out.println("Random number(float): " +(random.nextFloat()));

    System.out.println("Random number(double): " +(random.nextDouble()));

    System.out.println("Random number(gaussian): " +(random.nextGaussian()));

    Date date = new Date();

    Random seed_random = new Random(date.getTime());

    System.out.println("Random number with seed(int): " +(seed_random.nextInt()));

    System.out.println("Random number with seed(float): " +(seed_random.nextFloat()));

    System.out.println("Random number with seed(double): " +(seed_random.nextDouble()));

    System.out.println("Random number with seed(gaussian) : " +(seed_random.nextGaussian()));

    }}

    THE STRINGTOKENIZER CLASS

    The StringTokenizer class provides a means of converting text strings into individualtokens. By specifying a set of delimiters, you can parse text strings into tokens usingthe 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. Thetokenization 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

    40

  • 8/7/2019 A Basic Java Course Material

    41/176

    .(the characters that separate tokens) may be specified either at creation time or on aper-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 trueor false:

    If the flag is false, delimiter characters serve to separate tokens. A token is amaximal sequence of consecutive characters that are not delimiters.

    If the flag is true, delimiter characters are considered to be tokens. A token iseither one delimiter character, or a maximal sequence of consecutivecharacters 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:

    thisisatest

    EXAMPLE FOR STRINGTOKENIZER

    import java.util.StringTokenizer;

    public class TokenizerExample {public static void main(String args[]) {char temp = (char)-1;

    String input = "";

    System.out.println("Enter 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 tokens...");StringTokenizer tokenizer = new StringTokenizer(input);

    System.out.println("Number of tokens : "+(tokenizer.countTokens()));

    41

  • 8/7/2019 A Basic Java Course Material

    42/176

    .

    while(tokenizer.hasMoreTokens()){System.out.println(tokenizer.nextToken());}

    }}

    THE HASHTABLE CLASS

    This class implements a hashtable, which maps keys to values. Any non-null objectcan be used as a key or as a value. To successfully store and retrieve objects from ahashtable, the objects used as keys must implement the hashCode method and theequals method. An instance of Hashtable has two parameters that affect itsefficiency: its capacity and its load factor. The load factor should be between 0.0 and1.0. When the number of entries in the hashtable exceeds the product of the loadfactor and the current capacity, the capacity is increased by calling the rehashmethod. Larger load factors use memory more efficiently, at the expense of largerexpected time per lookup. If many entries are to be made into a Hashtable, creating itwith a sufficiently large capacity may allow the entries to be inserted more efficientlythan letting it perform automatic rehashing as needed to grow the table. Thisexample creates a hashtable of numbers. It uses the names of the numbers as keys:

    Hashtable numbers = new Hashtable();numbers.put("one", new Integer(1));numbers.put("two", new Integer(2));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"};

    for(int index=0;index

  • 8/7/2019 A Basic Java Course Material

    43/176

    .

    Date date = new Date();int day = date.getDay();

    Integer pos = new Integer(day);

    System.out.println("Day : " + (hash.get(pos).toString()));}}

    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 = newStringTokenizer(date.toString());System.out.println("tokens : "+tokenizer.countTokens());while (tokenizer.hasMoreTokens()){stack.push(tokenizer.nextToken());}

    Object obj = stack.peek();

    System.out.println("First element in stack - by peek : " +(obj.toString()));

    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 containscomponents that can be accessed using an integer index. However, the size of aVector can grow or shrink as needed to accommodate adding and removing itemsafter the Vector has been created.

    Each vector tries to optimize storage management by maintaining a capacity and acapacityIncrement. The capacity is always at least as large as the vector size; it isusually larger because as components are added to the vector, the vector's storage

    43

  • 8/7/2019 A Basic Java Course Material

    44/176

    .increases in chunks the size of capacityIncrement. An application can increase thecapacity of a vector before inserting a large number of components; this reduces theamount 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 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()) {store.addElement(tokenizer.nextToken());}System.out.println("Size of the Vector : "+store.size());

    System.out.println("Capacity of the Vector :

    "+store.capacity());

    System.out.println("First Element : "+store.firstElement());

    System.out.println("Last 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()));

    }}

    44

  • 8/7/2019 A Basic Java Course Material

    45/176

    .

    The Collections Framework

    The collections framework is a unified architecture for representing and manipulatingcollections, allowing them to be manipulated independently of the details of theirrepresentation. It reduces programming effort while increasing performance. It allows

    for interoperability among unrelated APIs, reduces effort in designing and learningnew APIs, and fosters software reuse. The framework is based on six collectioninterfaces. It includes implementations of these interfaces, and algorithms tomanipulate them.

    IntroductionThe 1.2 release of the Java platform includes a new collections framework. Acollection is an object that represents a group of objects. A collections framework is aunified architecture for representing and manipulating collections, allowing them to bemanipulated independently of the details of their representation.

    The primary advantages of a collections framework are that it:

    Reduces programming effort by providing useful data structures andalgorithms so you don't have to write them yourself.

    Increases performance by providing high-performance implementations ofuseful data structures and algorithms. Because the various implementationsof each interface are interchangeable, programs can be easily tuned byswitching implementations.

    Provides interoperability between unrelated APIs by establishing acommon 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 andalgorithms 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 Implementations - Primary implementations of thecollection interfaces.

    Legacy Implementations - The collection classes from earlier releases,Vector and Hashtable, have been retrofitted to implement the collectioninterfaces.

    Wrapper Implementations - Add functionality, such as synchronization, toother implementations.

    Convenience Implementations - High-performance "mini-implementations"of the collection interfaces.

    Abstract Implementations - Partial implementations of the collectioninterfaces to facilitate custom implementations.

    45

  • 8/7/2019 A Basic Java Course Material

    46/176

    . Algorithms - Static methods that perform useful functions on collections,

    such as sorting a list.

    Infrastructure - Interfaces that provide essential support for the collectioninterfaces.

    Array Utilities - Utility functions for arrays of primitives and reference objects.Not, strictly speaking, a part of the Collections Framework, this functionality isbeing added to the Java platform at the same time and relies on some of thesame infrastructure.

    Collection Interfaces

    There are six collection interfaces. The most basic interface is Collection. Threeinterfaces extend Collection: Set, List, and SortedSet. The other two collectioninterfaces, Map and SortedMap, do not extend Collection, as they representmappings rather than true collections. However, these interfaces contain collection-viewoperations, 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. SomeCollection implementations allow duplicate elements and others donot. Some are ordered and others unordered. The JDK doesn'tprovide any direct implementations of this interface: It providesimplementations of more specific subinterfaces like Set and List. Thisinterface is the least common denominator that all collectionsimplement. Collection is used to pass collections around andmanipulate them when maximum generality is desired.

    Set

    A Set is a collection that cannot contain duplicate elements. As youmight expect, this interface models the mathematical setabstraction. It

    is used to represent sets like the cards comprising a poker hand, the

    46

  • 8/7/2019 A Basic Java Course Material

    47/176

    .courses making up a student's schedule, or the processes running ona machine.

    List

    A List is an ordered collection (sometimes called a sequence). Lists

    can contain duplicate elements. The user of a List generally hasprecise control over where in the List each element is inserted. Theuser can access elements by their integer index (position). If you'veused Vector, you're already familiar with the general flavor of List.

    Map

    A Map is an object that maps keys to values. Maps cannot containduplicate keys: Each key can map to at most one value. If you've usedHashtable, you're already familiar with the general flavor of Map.

    The last two core collection interfaces (SortedSet and SortedMap) are merely sortedversions of Set and Map

    Object Ordering

    There are two ways to order objects: The Comparable interfaceprovides automatic natural orderon classes that implement it, whilethe Comparator interface gives the programmer complete control overobject ordering. Note that these are notcore collection interfaces, butunderlying infrastructure.

    The last two core collection interfaces:

    SortedSet

    A SortedSet is a Set that maintains its elements in ascending order.Several additional operations are provided to take advantage of theordering. The SortedSet interface is used for things like word lists andmembership rolls.

    SortedMap

    A SortedMap is a Map that maintains its mappings in ascending keyorder. It is the Map analogue of SortedSet. The SortedMap interface isused for apps like dictionaries and telephone directories.

    All of the modification methods in the collection interfaces are labeled optional. Someimplementations may not perform one or more of these operations, throwing aruntime exception (UnsupportedOperationException) if they are attempted.

    Implementations must specify in their documentation which optional operations theysupport. 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 notunmodifiable are referred to modifiable.

    Collections that additionally guarantee that no change in the Collection objectwill ever be visible are referred to as immutable. Collections that are notimmutable 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 fixed-size are referred to as variable-size.

    47

  • 8/7/2019 A Basic Java Course Material

    48/176

    .Some implementations may restrict what elements (or in the case of Maps, keys andvalues) 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 ina runtime exception, typically a ClassCastException, an IllegalArgumentException ora NullPointerException. Attempting to remove or test for the presence of an elementthat violates an implementation's restrictions may result in an exception, thoughsome "restricted collections" may permit this usage.

    Collection Implementations

    Class that implement the collection interfaces typically have names of the form. The general-purpose implementations aresummarized in the table below:

    Implementations

    Hash Table Resizable Array Balanced Tree Linked List

    Interfaces

    Set HashSet TreeSet

    List ArrayList LinkedList

    Map HashMap TreeMap

    The general-purpose implementations support all of the optional operations in thecollection interfaces, and have no restrictions on the elements they may contain.

    The AbstractCollection, AbstractSet, AbstractList, AbstractSequentialList andAbstractMap classes provide skeletal implementations of the core collectioninterfaces, to minimize the effort required to implement them. The API documentationfor these classes describes precisely how each method is implemented so theimplementer knows which methods should be overridden, given the performance ofthe "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 functionalitynot 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 be powerfulenough to provide all the advantages described above.

    To keep the number of core interfaces small, the interfaces do not attempt to capturesuch subtle distinctions as mutability, modifiability, resizability. Instead, certain callsin the core interfaces are optional, allowing implementations to throw anUnsupportedOperationException to indicate that they do not support a specifiedoptional operation. Of course, collection implementers must clearly document whichoptional operations are supported by an implementation.

    To keep the number of methods in each core interface small, an interface contains amethod only if either:

    48

  • 8/7/2019 A Basic Java Course Material

    49/176

    .

    1. It is a truly fundamental operation: a basic operations in terms of which otherscould be reasonably defined,

    2. There is a compelling performance reason why an important implementationwould want to override it.

    It was critical that all reasonable representations of collections interoperate well. Thisincluded arrays, which cannot be made to implement the Collection interface directlywithout changing the language. Thus, the framework includes methods to allowcollections to be dumped into arrays, arrays to be viewed as collections, and maps tobe viewed as collections.

    49

  • 8/7/2019 A Basic Java Course Material

    50/176

    .

    50

    Input/Output package

    java.io

  • 8/7/2019 A Basic Java Course Material

    51/176

    .

    CHAPTER 4 : THE I/O PACKAGE - java.io

    The Java I/O package, also known as java.io, provides classes with support forreading and writing data to and from different input and output devices, including

    files. The I/O package includes classes for inputting streams of data, outputtingstreams of data, working with files, and tokenizing streams of data. The mostimportant 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. Javasupports files with two different classes: File and RandomAccessFile. The File classprovides 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 isstored and how it can be accessed. The File class has no methods for reading andwriting data to and from a file; it is only useful for querying and modifying theattributes of a file. In actuality, you can think of the File class data as representing afilename, and the class methods as representing operating system commands thatact on filenames.

    The RandomAccessFile class provides a variety of methods for reading and writingdata to and from a file. RandomAccessFile contains many different methods forreading 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 filesystem. A file is specified by a pathname, which can either be an absolute pathnameor a pathname relative to the current working directory. The pathname must followthe 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-independentfashion.Note that whenever a filename or path is used it is assumed that the host's filenaming conventions are used.

    Example for File

    import java.io.*;import java.util.Date;

    public class FileExample{public static void main(String args[]){

    51

  • 8/7/2019 A Basic Java Course Material

    52/176

    .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 Exists : "+file.exists());

    Date date = new Date(file.lastModified());System.out.println("Last Modified : "+date.toString());System.out.println("Absolute Path :

    "+file.getAbsolutePath());System.out.println("Length of file : "+file.length());

    System.out.println("Parent : "+file.getParent());}catch(Exception err){System.out.println("Exception in accessing file");}}}

    THE RANDOMACCESSFILE CLASS

    Instances of this class support both reading and writing to a random access file. Anapplication 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 modeaccesses 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("java 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(destfile,"rw");

    52

  • 8/7/2019 A Basic Java Course Material

    53/176

    .

    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 theresult");} catch(Exception err) {}}}

    INPUT STREAM CLASSES

    Java uses input streams to handle reading data from an input source. An inputsource can be a file, a string, memory, or anything else that contains data. The inputstream 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 inputstreams. The InputStream class defines an interface for reading streamed bytes ofdata, 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 forreading data from different types of input devices.

    OUTPUT STREAM CLASSES

    Output streams are the counterpart to input streams and handle writing data to anoutput source. Similar to input sources, output sources include files, strings, memory,and anything else that can contain data. The output stream classes defined in java.iofollow:

    OutputStream

    BufferedOutputStream

    ByteArrayOutputStream

    DataOutputStream

    53

  • 8/7/2019 A Basic Java Course Material

    54/176

    .

    FileOutputStream

    FilterOutputStream

    PipedOutputStream

    PrintStream

    The OutputStream class is an abstract class that serves as the base class for alloutput streams. OutputStream defines an interface for writing streamed bytes of datato an output source. All the other output streams provide support for writing data todifferent output devices. Data written by an output stream is formatted to be read byan 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 theunderlying 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

    import java.io.*;class BufferedExample {public static void main (String args[]) {

    BufferedInputStream in = newBufferedInputStream(System.in);

    byte buf[] = new byte[10];try {

    in.read(buf, 0, 10);}catch (Exception e) {System.out.println(Error: + e.toString()); }

    String s = new String(buf, 0); System.out.println(s);} }

    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 necessarilycausing 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 Class

    import java.io.*;class WriteStuff{public static void main (String args[]){// Copy the string into a byte arrayString s = new String(Dance, spider!\n);

    byte[] buf = new byte[64];

    54

  • 8/7/2019 A Basic Java Course Material

    55/176

    .s.getBytes(0, s.length(), buf, 0);

    // Output the byte array (buffered)BufferedOutputStream out = newBufferedOutputStream(System.out); try

    {out.write(buf, 0, 64);out.flush();

    }catch (Exception e){System.out.println(Error: + e.toString());}}}

    THE DATAINPUTSTREAM CLASS

    A data input stream lets an application read primitive Java data types from anunderlying input stream in a machine-independent way. An application uses a dataoutput 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 formatthat 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-5Characters 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 thefollowing:

    The null byte '\u0000' is encoded in 2-byte format rather than 1-byte, so that theencoded strings never have embedded nulls.

    Only the 1-byte, 2-byte, and 3-byte formats are used.

    Example for DataInputStream and DataOutputStream

    import java.io.DataInputStream;import java.io.DataOutputStream;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.File;

    import java.io.IOException;

    55

  • 8/7/2019 A Basic Java Course Material

    56/176

    .

    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()+" bytes were written");outStream.close();outFile.close();FileInputStream inFile = new 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 aFileDescriptor.

    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: + e.toString());}String s = new String(buf, 0);System.out.println(s);}}

    56

  • 8/7/2019 A Basic Java Course Material

    57/176

    .THE FILEOUTPUTSTREAM CLASS

    A file output stream is an output stream for writing data to a File or to aFileDescriptor.

    Example for FileOutputStreamimport 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: + e.toString());}// Output the data to a filetry{FileOutputStream out = new FileOutputStream(Output.txt);out.write(buf);}catch (Exception e){System.out.println(Error: + e.toString());

    }}}

    THE BYTEARRAYINPUTSTREAM CLASS

    This class allows an application to create an input stream in which the bytes read aresupplied by the contents of a byte array. Applications can also read bytes from astring by using a StringBufferInputStream.

    Example for Byte Array input/output stream

    import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.IOException;

    public class ByteArrayIOApp{public static void main(String args[]) throws IOException{

    ByteArrayOutputStream outStream = newByteArrayOutputStream();String s = "This is a test.";for(int i=0;i

  • 8/7/2019 A Basic Java Course Material

    58/176

    .System.out.println("size: "+outStream.size());ByteArrayInputStream inStream;

    inStream = newByteArrayInputStream(outStream.toByteArray());int inBytes = inStream.available();

    System.out.println("inStream has "+inBytes+" availablebytes");byte inBuf[] = new byte[inBytes]


Recommended