Java Classes In Patna

Java Training Classes In Patna
RUPEES 2999
170 SEATS

Course Description

Java was conceived by James Gosling, Patrick Naughton, Chris Warth, Ed Frank, and Mike Sheridan at Sun Microsystems, Inc. in 1991. It took 18 months to develop the first working version. This language was initially called “Oak,” but was renamed “Java” in 1995. Between the initial implementation of Oak in the fall of 1992 and the public announcement of Java in the spring of 1995.

Why learn Java ?

Java was designed to have the look and feel of the C++ language, but it is simpler to use than C++ and enforces an object-oriented programming model. Java can be used to create complete applications that may run on a single computer or be distributed among servers and clients in a network. Java runs on a variety of platforms, such as Windows, Mac OS, and the various versions of UNIX.

The Creation of Java

Somewhat surprisingly, the original impetus for Java was not the Internet! Instead, the primary motivation was the need for a platform-independent (that is, architecture-neutral) language that could be used to create software to be embedded in various consumer electronic devices, such as microwave ovens and remote controls.

JAVA TRAINING

  • Java Chapter 1 - Overview
  • Overview

    Java related to C++ ,which is a direct descendent of c. By the end of the 1980s and early 1990s, object oriented programming using C++ took hold. within a few years , the world wide web and the internet would reach critical mass. This event would precipitate another revolution in programming.

    Java Applets: An applet is a special kind of Java program that is designed to be transmitted over the Internet and automatically executed by a Java-compatible web browser. the applet is a dynamic, self-executing program. As desirable as dynamic, networked programs are, they also present serious problems in the areas of security and portability. Java solved these problems in an effective and elegant way.

    Security:Java to enable applets to be downloaded and executed on the client computer safely. Java achieved this protection by confining an applet to the Java execution environment and not allowing it access to other parts of the computer.

    Portability: Portability is a major aspect of the Internet because there are many different types of computers and operating systems connected to it. If a Java program were to be run on virtually any computer connected to the Internet, there needed to be some way to enable that program to execute on different systems. The same code must work on all computers. The same mechanism that helps ensure security also helps create portability.

    Java’s Magic: The Bytecode

    The key that allows Java to solve both the security and the portability problems just described is that the output of a Java compiler is not executable code. Rather, it is bytecode. Bytecode is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). JVM was designed as an interpreter for bytecode.

    Translating a Java program into bytecode makes it much easier to run a program in a wide variety of environments because only the JVM needs to be implemented for each platform. Once the run-time package exists for a given system, any Java program can run on it. Remember, although the details of the JVM will differ from platform to platform, all understand the same Java bytecode.

    The fact that a Java program is executed by the JVM also helps to make it secure. Because the JVM is in control, it can contain the program and prevent it from generating side effects outside of the system.

    The Java Buzzwords

    the fundamental forces that necessitated the invention of Java are portability and security, other factors also played an important role in molding the final form of the language.

    • Simple:
    • If you already understand the basic concepts of object-oriented programming, learning Java will be even easier. Best of all, if you are an experienced C++ programmer, moving to Java will require very little effort. Because Java inherits the C/C++ syntax and many of the object-oriented features of C++, most programmers have little trouble learning Java.

    • Secure:
    • Java is best known for its security. With Java, we can develop virus-free systems. Java is secured because:No explicit pointer, Java Programs run inside a virtual machine sandbox, Classloader, Bytecode Verifier, Security Manager.

    • Portable:
    • Java facilitates you to execute the Java bytecode to any platform, different architecture and operating systems. Bytecode is executed by Java run-time system, which is called the Java Virtual Machine (JVM).

    • Object-oriented:
    • Java manages to strike a balance between the purist’s “everything is an object” paradigm and the pragmatist’s “stay out of my way” model. The object model in Java is simple and easy to extend, while primitive types, such as integers, are kept as high-performance nonobjects.

    • Robust:
    • Java is a strictly typed language, it checks your code at compile time. However, it also checks your code at run time. Many hard-to-track-down bugs that often turn up in hard-to-reproduce run-time situations are simply impossible to create in Java. To better understand how Java is robust, consider two of the main reasons for program failure: memory management mistakes and mishandled exceptional conditions .

    • Multithreaded:
    • Java supports multithreaded programming, which allows that do many things simultaneously. The Java run-time system comes with an elegant yet sophisticated solution for multiprocess synchronization that enables you to construct smoothly running interactive systems.

    • Architecture-neutral:
    • The Java designers made several hard decisions in the Java language and the Java Virtual Machine in an attempt to alter this situation. Their goal was "write once; run anywhere, any time, forever."

    • Interpreted & High performance:
    • Java enables the creation of cross-platform programs by compiling into an intermediate representation called Java bytecode. the Java bytecode was carefully designed so that it would be easy to translate directly into native machine code for very high performance by using a just-in-time compiler.

    • Distributed:
    • Java is designed for the distributed environment of the Internet because it handles TCP/IP protocols. Java also supports Remote Method Invocation (RMI). This feature enables a program to invoke methods across a network.

    • Dynamic:
    • Java programs carry with them substantial amounts of run-time type information that is used to verify and resolve accesses to objects at run time.

  • Java Chapter 2 - Basic Syntax
  • Basic Syntax

    A First Simple Program

    /* This is a simple Java program. 
    Call this file "Example.java". */ 
    class Example { 
    // Your program begins with a call to main(). 
    	public static void main(String args[]) { 
    		System.out.println("This is a simple Java program."); 
    	}
     }
    

    COMPILE PROGRAM BY FOLLOWIG COMMAND: javac Example.java

    RUN PROGRAM BY FOLLOWIG COMMAND: java Example

    Whitespace: In Java, whitespace is a space, tab, or newline.

    Identifiers: Identifiers are used for class names, method names, and variable names. An identifier may be any descriptive sequence of uppercase and lowercase letters, numbers, or the underscore and dollar-sign characters.

    Literals: A constant value in Java is created by using a literal representation of it.Example: 100 98.6 'X' "This is a test"

    Comments: There are three types of comments defined by Java. You have already seen two: single-line and multiline. The third type is called a documentation comment. This type of comment is used to produce an HTML file that documents your program. The documentation comment begins with a /** and ends with a */.

    Separators: In Java, there are a few characters that are used as separators. The most commonly used separator in Java is the semicolon.

    The Java Keywords: There are 50 keywords currently defined in the Java language. These keywords, combined with the syntax of the operators and separators, form the foundation of the Java language. These keywords cannot be used as names for a variable, class, or method.

    abstractcontinueswitchassertdefaultgotopackagesynchronizedbooleando
    doublewhileimplementsprotectedthrowbyteelseimportpublicthrows
    catch extends int short try char final interface static void
    const float native super ifprivatecase enum class finally
    long transient strictfp volatileinstanceof returnthisbreakfornew

    Data Types

    Java Is a Strongly Typed Language

    Java’s safety and robustness comes from this fact. Let’s see what this means. First, every variable has a type, every expression has a type, and every type is strictly defined. Second, all assignments, whether explicit or via parameter passing in method calls, are checked for type compatibility. There are no automatic coercions or conversions of conflicting types as in some languages. The Java compiler checks all expressions and parameters to ensure that the types are compatible. Any type mismatches are errors that must be corrected before the compiler will finish compiling the class.

    The Primitive Types

    Java defines eight primitive types of data: byte, short, int, long, char, float, double, and boolean. The primitive types represent single values—not complex objects.

    Category Types Size (bits)Range Example
    Character char16 0 To 216-1 OR All Unicode characterschar c = 'A';char c = 65;
    Integer byte8 -28 To 28-1 OR From +127 to -128 byte b = 65;
    Integer short 16 -215 To 215-1 OR From +32,767 to -32,768 short s = 65;
    Integer int 32 -231 To 231-1 OR From +2,147,483,647 to -2,147,483,648 int i = 65;
    Integer long64 -263 To 263-1 OR From +9,223,372,036,854,775,807 to -9,223,372,036,854,775,808 long l = 65L;
    Floating-point float 32 approximately ±3.40282347E+38F float f = 65f;
    Floating-point double64 approximately ±1.79769313486231570E+308 double d = 65.55;
    -- boolean-- -- -- false, true boolean b = true;
    -- void

    Variables

    The variable is the basic unit of storage in a Java program. A variable is defined by the combination of an identifier, a type, and an optional initializer.

    type identifier [ = value][, identifier [= value] ...] ;

    example: int a=2,b=7,c;

    The Scope and Lifetime of Variables

    Many other computer languages define two general categories of scopes: global and local. The scope defined by a method begins with its opening curly brace. As a general rule, variables declared inside a scope are not visible (that is, accessible) to code that is defined outside that scope. Thus, when you declare a variable within a scope, you are localizing that variable and protecting it from unauthorized access and/or modification. Indeed, the scope rules provide the foundation for encapsulation.

    // Demonstrate block scope.
     class Scope { 
        public static void main(String args[]) {
            int x;
            x = 10;
            if(x == 10) {  // start new scope 
                int y = 20;
                System.out.println("x and y: " + x + " " + y);
                x = y * 2;
            }
            // y = 100; // Error! y not known here
            System.out.println("x is " + x);
        }
     } 

    Type Conversion and Casting

    to assign a value of one type to a variable of another type. If the two types are compatible Or The destination type is larger than the source type, then Java will perform the conversion automatically.

    Casting Incompatible Types

    To create a conversion between two incompatible types, you must use a cast. A cast is simply an explicit type conversion. It has this general form:

    (target-type) value

    int a; 
    byte b;
     // ...
     b = (byte) a;

    The Type Promotion Rules

    Java defines several type promotion rules that apply to expressions. They are as follows: First, all byte, short, and char values are promoted to int, as just described. Then, if one operand is a long, the whole expression is promoted to long. If one operand is a float, the entire expression is promoted to float. If any of the operands is double, the result is double.

    User Input-Scanner Class

    The Scanner class is used to get user input, and it is found in the java.util package.

    Syntax:
    import java.util.Scanner;
    Scanner Object = new Scanner(System.in);
    Object.inputfunction();
    
    Input Types MethodDescription
    nextBoolean() Reads a boolean value from the user
    nextByte() Reads a byte value from the user
    nextDouble() Reads a double value from the user
    nextFloat() Reads a float value from the user
    nextInt() Reads a int value from the user
    nextLine() Reads a String value from the user
    nextLong() Reads a long value from the user
    nextShort() Reads a short value from the user
    next().charAt(0) Reads a char value from the user
    Example
        
    
    import java.util.Scanner;  // Import the Scanner class
    
    class MyClass {
      public static void main(String[] args) {
        Scanner myObj = new Scanner(System.in);  // Create a Scanner object
        System.out.println("Enter username");
    
        String userName = myObj.nextLine();  // Read user input
        System.out.println("Username is: " + userName);  // Output user input 
      }
    }
    
  • Java Chapter 3- Arrays
  • Arrays

    An array is a group of like-typed variables that are referred to by a common name. Arrays of any type can be created and may have one or more dimensions. A specific element in an array is accessed by its index.

    One-Dimensional Arrays: The general form of a one-dimensional array declaration is

        Syntax: type var-name[ ];
        array-var = new type[size];
        Example: 	int month_days[];
        month_days = new int[12];
                    OR
        int month_days[] = new int[12];
    	
    // Demonstrate a one-dimensional array.
     
     class Array {
        public static void main(String args[]) {
            int month_days[]; 
            month_days = new int[12];
            month_days[0] = 31;
            month_days[1] = 28; 
            month_days[2] = 31;
            month_days[3] = 30;
            month_days[4] = 31;
            month_days[5] = 30;
            month_days[6] = 31;
            month_days[7] = 31;
            month_days[8] = 30;
            month_days[9] = 31;
            month_days[10] = 30;
            month_days[11] = 31;
            System.out.println("April has " + month_days[3] + " days.");
        }
     }
     
     // An improved version of the previous program.
     
     class AutoArray {
     public static void main(String args[]) {
     int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; 
    System.out.println("April has " + month_days[3] + " days.");
     }
     }
     
    // Average an array of values. 
     
    class Average {
     public static void main(String args[]) {
     double nums[] = {10.1, 11.2, 12.3, 13.4, 14.5}; double result = 0; 
    int i;
     for(i=0; i <5;i++)
    result = result + nums[i]; System.out.println("Average is " + result / 5); 
    }
     }
     
    
     
    

    Multidimensional Arrays:-In Java, multidimensional arrays are actually arrays of arrays

    Syntax:-int twoD[][] = new int[4][5];

    This allocates a 4 by 5 array and assigns it to twoD. Internally this matrix is implemented as an array of arrays of int.

  • Java Chapter 4- Operator
  • Operator

    java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups −

    • Arithmetic Operators
    • Relational Operators
    • Bitwise Operators
    • Logical Operators
    • Assignment Operators
    • Misc Operators

    The Arithmetic Operators:-Arithmetic operators are used in mathematical expressions in the same way that they are used in algebra. The following table lists the arithmetic operators −

    OperatorDescriptionExample here A=10 & B=20
    + (Addition) Adds values on either side of the operator. A + B will give 30
    - (Subtraction) Subtracts right-hand operand from left-hand operand. A - B will give -10
    * (Multiplication) Multiplies values on either side of the operator. A * B will give 200
    / (Division) Divides left-hand operand by right-hand operand. B / A will give 2
    % (Modulus) Divides left-hand operand by right-hand operand and returns remainder. B % A will give 0
    ++ (Increment) Increases the value of operand by 1. B++ gives 21
    -- (Decrement) Decreases the value of operand by 1. B-- gives 19

    The Relational Operators:-There are following relational operators supported by Java language.

    OperatorDescriptionExample here A=10 & B=20
    == (equal to)Checks if the values of two operands are equal or not, if yes then condition becomes true.(A == B) is not true.
    != (not equal to)Checks if the values of two operands are equal or not, if values are not equal then condition becomes true.(A != B) is true.
    > (greater than)Checks if the value of left operand is greater than the value of right operand, if yes then condition becomes true.(A > B) is not true.
    < (less than)Checks if the value of left operand is less than the value of right operand, if yes then condition becomes true. (A < B) is true.
    >= (greater than or equal to)Checks if the value of left operand is greater than or equal to the value of right operand, if yes then condition becomes true.(A >= B) is not true.
    <= (less than or equal to)Checks if the value of left operand is less than or equal to the value of right operand, if yes then condition becomes true.(A <= B) is true.

    The Bitwise Operators:-Java defines several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte.Bitwise operator works on bits and performs bit-by-bit operation. Assume if a = 60 and b = 13; now in binary format they will be as follows −

    a = 0011 1100
    b = 0000 1101
    -----------------
    a&b = 0000 1100
    a|b = 0011 1101
    a^b = 0011 0001
    ~a  = 1100 0011
    
    The following table lists the bitwise operators −
    OperatorDescriptionExample here A=60 & B=13
    & (bitwise and)Binary AND Operator copies a bit to the result if it exists in both operands.(A & B) will give 12 which is 0000 1100
    | (bitwise or)Binary OR Operator copies a bit if it exists in either operand.(A | B) will give 61 which is 0011 1101
    ^ (bitwise XOR)Binary XOR Operator copies the bit if it is set in one operand but not both.(A ^ B) will give 49 which is 0011 0001
    ~ (bitwise compliment)Binary Ones Complement Operator is unary and has the effect of 'flipping' bits. (~A ) will give -61 which is 1100 0011 in 2's complement form due to a signed binary number.
    << (left shift)Binary Left Shift Operator. The left operands value is moved left by the number of bits specified by the right operand.A << 2 will give 240 which is 1111 0000
    >> (right shift)Binary Right Shift Operator. The left operands value is moved right by the number of bits specified by the right operand.A >> 2 will give 15 which is 1111
    >>> (zero fill right shift)Shift right zero fill operator. The left operands value is moved right by the number of bits specified by the right operand and shifted values are filled up with zeros.A >>>2 will give 15 which is 0000 1111
  • Java Chapter 5- Control Statements
  • Control Statements

    A programming language uses control statements to handle the flow of execution. Java’s program control statements can be put into the following categories: selection, iteration, and jump. Selection statements allow your program to choose different paths of execution based upon the outcome of an expression or the state of a variable. Iteration statements enable program execution to repeat one or more statements (that is, iteration statements form loops). Jump statements allow your program to execute in a nonlinear fashion.

    The if-else : Java’s Selection Statements Java supports two selection statements: if and switch. These statements allow you to control the flow of your program’s execution based upon conditions known only during run time.

    if (condition) statement1;
    else statement2;

    The if-else-if Ladder: A common programming construct that is based upon a sequence of nested ifs is the if-else-if ladder. It looks like this:

    if(condition) statement;
    else if(condition) statement;
    else if(condition) statement;
    .
    .
    .
    else statement;
    
    // Demonstrate if-else-if statements.
      
    class IfElse {
     public static void main(String args[]) {
     int month = 4; // April
     String season;
     if(month == 12 || month == 1 || month == 2)
     season = "Winter";
     else if(month == 3 || month == 4 || month == 5) 
    season = "Spring";
     else if(month == 6 || month == 7 || month == 8)
     season = "Summer"; 
    else if(month == 9 || month == 10 || month == 11)
     season = "Autumn"; 
    else season = "Bogus Month";
     System.out.println("April is in the " + season + ".");
     }
     }
    
    switch

    The switch statement is Java’s multiway branch statement. It provides an easy way to dispatch execution to different parts of your code based on the value of an expression.

    switch (expression) {
     case value1:
     // statement sequence 
    break;
     case value2:
     // statement sequence
     break;
     .
     .
     .
     case valueN:
    // statement sequence
     break; 
    default:
     // default statement sequence 
    }
     

    The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression

    // A simple example of the switch. 
     
    class SampleSwitch { 
    public static void main(String args[]) {
     for(int i=0; i<6;i++)
    switch(i) { 
    case 0: 	System.out.println("i is zero.");
     break;
     case 1:	System.out.println("i is one.");
     break; 
    case 2:	 System.out.println("i is two.");
     break;
     case 3:	 System.out.println("i is three.");
     break;
     default:   System.out.println("i is greater than 3.");
     } 	}	 }
     
     The output produced by this program is shown here:
     
    i is zero.
    i is one.
    i is two.
    i is three.
    i is greater than 3.
    i is greater than 3.
     
    // An improved version of the season program. 
     
    class Switch { 
    public static void main(String args[]) {
     int month = 4; 
    String season;
     switch (month) {
     case 12:
     case 1:
     case 2:
     season = "Winter";
     break;
     case 3:
     case 4:
     case 5:
     season = "Spring";
     break;
     case 6:
     case 7:
     case 8:
     season = "Summer"; 
    break;
     case 9: 
    case 10:
     case 11:
     season = "Autumn"; 
    break; 
    default:
     season = "Bogus Month";
     }
     System.out.println("April is in the " + season + ".");
     }
     }
     
        

    Iteration Statements

    while

    The while loop is Java’s most fundamental loop statement. It repeats a statement or block while its controlling expression is true. Here is its general form:

    while(condition) {
    // body of loop
    }
    // Demonstrate the while loop. 
     
    class While {
     public static void main(String args[]) {
     int n = 10;
     while(n > 0) {
     System.out.println("tick " + n);
     n--; 	}	 }	 }
     
    // The target of a loop can be empty. 
     
    class NoBody {
     public static void main(String args[]) { 
    int i, j;
     i = 100;
     j = 200;
     // find midpoint between i and j 
    while(++i < --j) ; // no body in this loop 
    System.out.println("Midpoint is " + i);
     }
     } 
    This program finds the midpoint between i and j. It generates the following output: 
    Midpoint is 150
    

    do-while

    The do-while loop always executes its body at least once, because its conditional expression is at the bottom of the loop.

    do {
     // body of loop 
    } while (condition);
    
    // Using a do-while to process a menu selection
      
    class Menu {
     public static void main(String args[]) throws java.io.IOException {
     char choice;
     do {
     System.out.println("Help on:");
     System.out.println(" 1. if");
     System.out.println(" 2. switch");
     System.out.println(" 3. while");
     System.out.println(" 4. do-while");
     System.out.println(" 5. for\n");
     System.out.println("Choose one:");
     choice = (char) System.in.read();
     } while( choice < '1' || choice > '5');
     System.out.println("\n"); 
    switch(choice) {
     case '1':
     System.out.println("The if:\n");
     System.out.println("if(condition) statement;"); 
    System.out.println("else statement;");
     break;
     case '2':
     System.out.println("The switch:\n");
     System.out.println("switch(expression) {");
     System.out.println(" case constant:");
     System.out.println(" statement sequence"); 
    System.out.println(" break;");
     System.out.println(" // ...");
     System.out.println("}");
     break; 
    case '3':
     System.out.println("The while:\n");
     System.out.println("while(condition) statement;");
     break; 
    case '4':
     System.out.println("The do-while:\n"); 
    System.out.println("do {");
     System.out.println(" statement;");
     System.out.println("} while (condition);");
     break; 
    case '5':
     System.out.println("The for:\n");
     System.out.print("for(init; condition; iteration)");
     System.out.println(" statement;"); 
    break; 
    }	 }	}
     
    Here is a sample run produced by this program:
     Help on: 
    1. if 
    2. switch
     3. while
     4. do-while
     5. for
     Choose one: 
    4
     The do-while:
     do {
    	 statement; 
    } while (condition);
    

    for

    for(initialization; condition; iteration) {
     // body
     }
     
    // Declare a loop control variable inside the for. 
     
    class ForTick {
     public static void main(String args[]) {
     // here, n is declared inside of the for loop
     for(int n=10; n>0; n--)
     System.out.println("tick " + n); 
    }
     }
     
    // Test for primes.
     class FindPrime { 
    	public static void main(String args[]) {
     	int num; 
    	boolean isPrime = true; 
    	num = 14; 
    	for(int i=2; i <= num/i; i++) {
     		if((num % i) == 0) {
     			isPrime = false;
     			break;
     		}
     	}
     	if(isPrime)	System.out.println("Prime");
     	else 	System.out.println("Not Prime");
     	}
     }
     

    The For-Each

    A foreach style loop is designed to cycle through a collection of objects, such as an array, in strictly sequential fashion, from start to finish. The general form of the for-each version of the for is shown here:

    for(type itr-var : collection) statement-block

    // Use a for-each style for loop.
     class ForEach {
    	 public static void main(String args[]) { 
    	int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
     	int sum = 0; 
    	// use for-each style for to display and sum the values
     	for(int x : nums) {
     		System.out.println("Value is: " + x);
    		 sum += x; 
    	}
     	System.out.println("Summation: " + sum);
     	}
     }

    Jump Statements

    Java supports three jump statements: break, continue, and return. These statements transfer control to another part of your program. Using break In Java, the break statement has three uses. First, as you have seen, it terminates a statement sequence in a switch statement. Second, it can be used to exit a loop. Third, it can be used as a “civilized” form of goto. The last two uses are explained here. The general form of the labeled break statement is shown here:

    break label;

    // Using break as a civilized form of goto. 
     
    class Break {
     public static void main(String args[]) {
     boolean t = true;
     first: {
       second: {
         third: {
           System.out.println("Before the break."); 
           if(t) break second; // break out of second block
           System.out.println("This won't execute");
        }
        System.out.println("This won't execute");
       }
       System.out.println("This is after second block.");
      }
     }	
     }
     
    Running this program generates the following output: 
    Before the break.
    This is after second block
    

    Using continue

    Sometimes it is useful to force an early iteration of a loop.

    // Demonstrate continue.
     
     class Continue { 
    public static void main(String args[]) {
     for(int i=0; i<10;i++){
    System.out.print(i + " ");
     if (i%2 == 0) continue;
     System.out.println(""); 
    }
     }
     }
     

    return

    The last control statement is return. The return statement is used to explicitly return from a method. That is, it causes program control to transfer back to the caller of the method.

    // Demonstrate return.
     
     class Return {
     	public static void main(String args[]) {
    	boolean t = true;
     	System.out.println("Before the return.");
     	if(t) return; // return to caller
     	System.out.println("This won't execute."); 
    	}
     }
    
        
  • Java Chapter 6- Object Oriented Programming & Introducing Classes
  • Object Oriented Programming & Introducing Classes

    Object-oriented programming (OOP) is at the core of Java.

    Two Paradigms

    All computer programs consist of two elements: code and data. These are the two paradigms that govern how a program is constructed. The first way is called the process-oriented model. This approach characterizes a program as a series of linear steps (that is, code). The process-oriented model can be thought of as code acting on data. Procedural languages such as C employ this model to considerable success.

    To manage increasing complexity, the second approach, called object-oriented programming, was conceived. Object-oriented programming organizes a program around its data (that is, objects) and a set of well-defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.

    Abstraction

    An essential element of object-oriented programming is abstraction. Humans manage complexity through abstraction.The data from a traditional process-oriented program can be transformed by abstraction into its component objects.

    The Three OOP Principles

    All object-oriented programming languages provide mechanisms that help you implement the object-oriented model. They are encapsulation, inheritance, and polymorphism.

    Encapsulation: Encapsulation is the mechanism that binds together code and the data it manipulates, and keeps both safe from outside interference and misuse. Access to the code and data inside the wrapper is tightly controlled through a well-defined interface. objects are sometimes referred to as instances of a class. Thus, a class is a logical construct; an object has physical reality. When you create a class, you will specify the code and data that constitute that class. Collectively, these elements are called members of the class. Specifically, the data defined by the class are referred to as member variables or instance variables. The code that operates on that data is referred to as member methods or just methods. Each method or variable in a class may be marked private or public. The public interface of a class represents everything that external users of the class need to know, or may know. The private methods and data can only be accessed by code that is a member of the class.

    Inheritance: Inheritance is the process by which one object acquires the properties of another object. This is important because it supports the concept of hierarchical classification. . However, by use of inheritance, an object need only define those qualities that make it unique within its class. It can inherit its general attributes from its parent.

    Polymorphism: Polymorphism (from Greek, meaning “many forms”) is a feature that allows one interface to be used for a general class of actions. the concept of polymorphism is often expressed by the phrase “one interface, multiple methods.” This means that it is possible to design a generic interface to a group of related activities. This helps reduce complexity by allowing the same interface to be used to specify a general class of action. It is the compiler’s job to select the specific action (that is, method) as it applies to each situation. You, the programmer, do not need to make this selection manually. You need only remember and utilize the general interface.

    The class is at the core of Java. Thus, a class is a template for an object, and an object is an instance of a class. class is that it defines a new data type. Once defined, this new type can be used to create objects of that type. A class is declared by use of the class keyword. A class is declared by use of the class keyword.

    Syntax:
     
    class classname {
     type instance-variable1;
     type instance-variable2;
    // ... 
    type instance-variableN; 
    type methodname1(parameter-list) {
     // body of method
     }
     type methodname2(parameter-list) {
     // body of method 
    }
     // ...
     type methodnameN(parameter-list) {
     // body of method 
    }
     }
     

    The data, or variables, defined within a class are called instance variables. The code is contained within methods. Collectively, the methods and variables defined within a class are called members of the class.

    Example:
     
    class Box {
     double width;
     double height;
     double depth;
     }
    Box mybox = new Box(); // create a Box object called mybox
     
    After this statement executes, mybox will be an instance of Box.
    
    /* A program that uses the Box class. Call this file BoxDemo.java */
      
    class Box { double width, height, depth; }
      class BoxDemo {
     public static void main(String args[]) {
     Box mybox = new Box();
    double vol;
    mybox.width = 10; mybox.height = 20;mybox.depth = 15;
    vol = mybox.width * mybox.height * mybox.depth; 
     System.out.println("Volume is " + vol);
     }
     }
     

    Declaring Objects

    when you create a class, you are creating a new data type. You can use this type to declare objects of that type. However, obtaining objects of a class is a two-step process. First, you must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. Second, you must acquire an actual, physical copy of the object and assign it to that variable. You can do this using the new operator. The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns a reference to it.

    Box mybox = new Box();
    OR
    Box mybox; // declare reference to object 
    mybox = new Box(); // allocate a Box object
    
    Assigning Object Reference Variables
    
    Box b1 = new Box(); 
    Box b2 = b1;
    

    Introducing Methods

    type name(parameter-list) {
     // body of method
     }
    // This program includes a method inside the box class.
     
      
    class Box {
    	 double width;
     	double height;
     	double depth;
     	// display volume of a box 
    	void volume() {
     		System.out.print("Volume is ");
     		System.out.println(width * height * depth);
     	}
     }
    class BoxDemo3 { 
    	public static void main(String args[]) {
     	Box mybox1 = new Box();
     	Box mybox2 = new Box();
     // assign values to mybox1's instance variables
     mybox1.width = 10;
     mybox1.height = 20;
     mybox1.depth = 15; 
    /* assign different values to mybox2's instance variables */
     mybox2.width = 3;
     mybox2.height = 6;
     mybox2.depth = 9;
     // display volume of first box
     mybox1.volume(); 
    // display volume of second box
     mybox2.volume(); 
    }	}
    
     
    This program generates the following output, which is the same as the previous version. 
    Volume is 3000.0
     Volume is 162.0
     

    Returning a Value

    // Now, volume() returns the volume of a box. 
    class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } } class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // assign values to mybox1's instance variables mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; /* assign different values to mybox2's instance variables */ mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol);
    // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
    // This program uses a parameterized method. 
    class Box { double width; double height; double depth; // compute and return volume double volume() { return width * height * depth; } // sets dimensions of box void setDim(double w, double h, double d) { width = w;
    height = h; depth = d; } } class BoxDemo5 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // initialize each box mybox1.setDim(10, 20, 15); mybox2.setDim(3, 6, 9); // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

    Constructors

    Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the use of a constructor. A constructor initializes an object immediately upon creation. It has the same name as the class in which it resides and is syntactically similar to a method. Constructors look a little strange because they have no return type, not even void.

    /* Here, Box uses a constructor to initialize the dimensions of a box. */ 
    class Box { double width; double height; double depth; // This is the constructor for Box. Box() { System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } // compute and return volume double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }

    The default constructor automatically initializes all instance variables to zero.

    Parameterized Constructors

    /* Here, Box uses a parameterized constructor to initialize the dimensions of a box. */ 
    class Box { double width; double height; double depth; // This is the constructor for Box. Box(double w, double h, double d) { width = w; height = h; depth = d; } // compute and return volume double volume() { return width * height * depth; } }
    class BoxDemo7 { public static void main(String args[]) { // declare, allocate, and initialize Box objects Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume is " + vol); } }
    The output from this program is shown here: 
    Volume is 3000.0 
    Volume is 162.0

    The this Keyword

    Java defines the this keyword. this can be used inside any method to refer to the current object.

    // A redundant use of this.
    Box(double w, double h, double d) {
     this.width = w;
     this.height = h;
     this.depth = d; 
    }

    Garbage Collection

    In some languages, such as C++, dynamically allocated objects must be manually released by use of a delete operator. Java takes a different approach; it handles deallocation for you automatically. The technique that accomplishes this is called garbage collection. It works like this: when no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed.

    The finalize( ) Method

    Sometimes an object will need to perform some action when it is destroyed. For example, if an object is holding some non-Java resource such as a file handle or character font, then you might want to make sure these resources are freed before an object is destroyed. To handle such situations, Java provides a mechanism called finalization. By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector.

    Syntax:
    protected void finalize( ) { 
    // finalization code here
     }

    A Stack Class

    // This class defines an integer stack that can hold 10 values.
     class Stack { int stck[] = new int[10]; int tos; // Initialize top-of-stack Stack() { tos = -1; } // Push an item onto the stack void push(int item) { if(tos==9) System.out.println("Stack is full."); else stck[++tos] = item; } // Pop an item from the stack int pop() { if(tos < 0) { System.out.println("Stack underflow."); return 0; } else return stck[tos--]; } }
    class TestStack { public static void main(String args[]) { Stack mystack1 = new Stack(); Stack mystack2 = new Stack();
    // push some numbers onto the stack
     for(int i=0; i <10;i++)mystack1.push(i);
    for(int i=10; i<20;i++) mystack2.push(i);
    // pop those numbers off the stack 
    System.out.println("Stack in mystack1:"); 
    for(int i=0; i<10;i++)
    System.out.println(mystack1.pop());
    System.out.println("Stack in mystack2:");
    for(int i=0; i <10;i++)
    System.out.println(mystack2.pop()); } }
    Overloading Methods
    In Java it is possible to define two or more methods within the same class that share the same name, as long as their parameter declarations are different. When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. Method overloading is one of the ways that Java supports polymorphism.
    // Demonstrate method overloading. 
    class OverloadDemo { void test() { System.out.println("No parameters"); } // Overload test for one integer parameter. void test(int a) { System.out.println("a: " + a); }
    // Overload test for two integer parameters. 
    void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } // overload test for a double parameter double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; // call all versions of test() ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } }
     This program generates the following output:
     No parameters a: 10
     a and b: 10 20 
    double a: 123.25 
    Result of ob.test(123.25): 15190.5625
    

    Overloading Constructors

    /* Here, Box defines three constructors to initialize the dimensions of a box various ways. */
     class Box { double width; double height; double depth; // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } class OverloadCons { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol;
    // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); } }
     The output produced by this program is shown here:
     Volume of mybox1 is 3000.0
     Volume of mybox2 is -1.0
     Volume of mycube is 343.0
     

    Using Objects as Parameters

    // Objects may be passed to methods. 
    class Test { int a, b; Test(int i, int j) { a = i; b = j; } // return true if o is equal to the invoking object boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2));System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } }
     This program generates the following output:		
     ob1 == ob2: true
    ob1 == ob3: false
    // Here, Box allows one object to initialize another. 
    class Box { double width; double height; double depth; // Notice this constructor. It takes an object of type Box. Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; }
    // compute and return volume double volume() { return width * height * depth; } } class OverloadCons2 { public static void main(String args[]) { // create boxes using the various constructors Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); Box myclone = new Box(mybox1); // create copy of mybox1 double vol; // get volume of first box vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); // get volume of second box vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); // get volume of cube vol = mycube.volume(); System.out.println("Volume of cube is " + vol); // get volume of clone vol = myclone.volume(); System.out.println("Volume of clone is " + vol); } }

    A Closer Look at Argument Passing

    there are two ways that a computer language can pass an argument to a subroutine.The first way is call-by-value. This approach copies the value of an argument into the formal parameter of the subroutine. Therefore, changes made to the parameter of the subroutine have no effect on the argument. The second way an argument can be passed is call-by-reference. In this approach, a reference to an argument (not the value of the argument) is passed to the parameter. Inside the subroutine, this reference is used to access the actual argument specified in the call. This means that changes made to the parameter will affect the argument used to call the subroutine.

    // Primitive types are passed by value.
     class Test { void meth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } }
     The output from this program is shown here:
     a and b before call: 15 20
     a and b after call: 15 20
    // Objects are passed by reference. class Test { int a, b; Test(int i, int j) { a = i; b = j; } // pass an object void meth(Test o) { o.a *= 2;
    o.b /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " + ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b); } } This program generates the following output: ob.a and ob.b before call: 15 20 ob.a and ob.b after call: 30 10

    Returning Objects

    // Returning an object. class Test { int a; Test(int i) { a = i; } Test incrByTen() { Test temp = new Test(a+10); return temp; }
    } class RetOb { public static void main(String args[]) { Test ob1 = new Test(2); Test ob2; ob2 = ob1.incrByTen(); System.out.println("ob1.a: " + ob1.a); System.out.println("ob2.a: " + ob2.a); ob2 = ob2.incrByTen(); System.out.println("ob2.a after second increase: " + ob2.a); } } The output generated by this program is shown here: ob1.a: 2 ob2.a: 12 ob2.a after second increase: 22

    Recursion

    recursion is the attribute that allows a method to call itself. A method that calls itself is said to be recursive

    //A simple example of recursion.
     class Factorial { // this is a recursive method int fact(int n) { int result; if(n==1) return 1; result = fact(n-1) * n; return result;}
    } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } } The output from this program is shown here: Factorial of 3 is 6 Factorial of 4 is 24 Factorial of 5 is 120

    Introducing Access Control

    encapsulation links data with the code that manipulates it. However, encapsulation provides another important attribute: access control. Through encapsulation, you can control what parts of a program can access the members of a class. By controlling access, you can prevent misuse. How a member can be accessed is determined by the access specifier that modifies its declaration. Java supplies a rich set of access specifiers. Some aspects of access control are related mostly to inheritance or packages. Java’s access specifiers are public, private, and protected. Java also defines a default access level. protected applies only when inheritance is involved. 1. Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class. 2. Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default. 3. Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package. 4. Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

    Access Modifier	within class	within package	subclass only	outside package
    Private	Y	N	N	N
    Default	Y	Y	N	N
    Protected	Y	Y	Y	N
    Public	Y	Y	Y	Y
    

    Understanding static

    When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. You can declare both methods and variables to be static. The most common example of a static member is main( ). main( ) is declared as static because it must be called before any objects exist. Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. Methods declared as static have several restrictions: • They can only call other static methods. • They must only access static data. • They cannot refer to this or super in any way.

    // Demonstrate static variables, methods, and blocks.
     
     class UseStatic {
     static int a = 3;
     static int b;
     static void meth(int x) {
    System.out.println("x = " + x);
     System.out.println("a = " + a);
     System.out.println("b = " + b);
     }
     static {
     System.out.println("Static block initialized.");
     b = a * 4;
     }
     public static void main(String args[]) {
     meth(42); 
    }
     }
     
    Here is the output of the program:
     Static block initialized. x = 42 a = 3 b = 12
     
    if you wish to call a static method from outside its class, you can do so using the following general form: classname.method( ) class StaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } } Here is the output of this program: a = 42 b = 99

    Introducing final

    A variable can be declared as final. Doing so prevents its contents from being modified. This means that you must initialize a final variable when it is declared. A final variable is essentially a constant.

    For example: final int FILE_NEW = 1; final int FILE_OPEN = 2; final int FILE_SAVE = 3; final int FILE_SAVEAS = 4; final int FILE_QUIT = 5;

    length - the size of an array—All arrays have length instance variable.It will always hold the size of the array.

    // This program demonstrates the length array member.
     class Length { public static void main(String args[]) { int a1[] = new int[10]; int a2[] = {3, 5, 7, 1, 8, 99, 44, -10}; int a3[] = {4, 3, 2, 1};
    System.out.println("length of a1 is " + a1.length); System.out.println("length of a2 is " + a2.length); System.out.println("length of a3 is " + a3.length); } }

    Introducing Nested and Inner Classes

    It is possible to define a class within another class; such classes are known as nested classes. The scope of a nested class is bounded by the scope of its enclosing class. Thus, if class B is defined within class A, then B does not exist independently of A. A nested class has access to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. A nested class that is declared directly within its enclosing class scope is a member of its enclosing class. It is also possible to declare a nested class that is local to a block. There are two types of nested classes: static and non-static. A static nested class is one that has the static modifier applied. Because it is static, it must access the members of its enclosing class through an object. That is, it cannot refer to members of its enclosing class directly. Because of this restriction, static nested classes are seldom used. The most important type of nested class is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.

    // Demonstrate an inner class.
     class Outer { int outer_x = 100; void test() { Inner inner = new Inner(); inner.display(); } // this is an inner class
    class Inner { void display() { System.out.println("display: outer_x = " + outer_x); } } } class InnerClassDemo { public static void main(String args[]) { Outer outer = new Outer(); outer.test(); } }
     Output from this application is shown here: display: outer_x = 100

    Using Command-Line Arguments

    A command-line argument is the information that directly follows the program’s name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy— they are stored as strings in a String array passed to the args parameter of main( ). The first command-line argument is stored at args[0], the second at args[1], and so on.

    // Display all command-line arguments. class CommandLine { public static void main(String args[]) {
     for(int i=0; i<args.length;i++)
    System.out.println("args[" + i + "]: " + args[i]); } }
    Try executing this program, as shown here:
     java CommandLine this is a test 100 -1 
    When you do, you will see the following output:
     args[0]: this args[1]: is args[2]: a args[3]: test args[4]: 100 args[5]: -1
     
    

    Varargs: Variable-Length Arguments

    A method that takes a variable number of arguments is called a variable-arity method, or simply a varargs method.

    A variable-length argument is specified by three periods (...).

    For example, here is how vaTest( ) is written using a vararg:
     static void vaTest(int ... v) {
    // Demonstrate variable-length arguments. 
    class VarArgs { // vaTest() now uses a vararg. static void vaTest(int ... v) { System.out.print("Number of args: " + v.length + " Contents: "); for(int x : v) System.out.print(x + " "); System.out.println(); } public static void main(String args[]) {
    vaTest(10); vaTest(1, 2, 3); vaTest();} }
    The output from the program is shown here: 
    Number of args: 1 Contents: 10 
    Number of args: 3 Contents: 1 2 3
     Number of args: 0 Contents:
    
  • Java Chapter 7- Inheritance
  • Inheritance

    Inheritance is one of the cornerstones of object-oriented programming because it allows the creation of hierarchical classifications. Using inheritance, you can create a general class that defines traits common to a set of related items. This class can then be inherited by other, more specific classes, each adding those things that are unique to it. In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. Therefore, a subclass is a specialized version of a superclass. It inherits all of the instance variables and methods defined by the superclass and adds its own, unique elements

    Inheritance Basics

    To inherit a class, you simply incorporate the definition of one class into another by using the extends keyword.

    The general form of a class declaration that inherits a superclass is shown here:

    class subclass-name extends superclass-name 
    { // body of class }
    // A simple example of inheritance.
     // Create a superclass.
     class A { 
    int i, j;
     void showij() {
     System.out.println("i and j: " + i + " " + j);
     }
     }
     
    // Create a subclass by extending class A.
     class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } }
    class SimpleInheritance { public static void main(String args[]) { A superOb = new A(); B subOb = new B(); // The superclass may be used by itself. superOb.i = 10; superOb.j = 20; System.out.println("Contents of superOb: "); superOb.showij(); System.out.println(); /* The subclass has access to all public members of its superclass. */ subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } }
    The output from this program is shown here: 
    Contents of superOb: i and j: 10 20 Contents of subOb: i and j: 7 8 k: 9 Sum of i, j and k in subOb: i+j+k: 24
    // This program uses inheritance to extend Box.
     class Box { double width; double height; double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // Here, Box is extended to include weight. class BoxWeight extends Box { double weight; // weight of box
    // constructor for BoxWeight BoxWeight(double w, double h, double d, double m) { width = w; height = h; depth = d; weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); } }
    The output from this program is shown here: 
    Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076
    // Here, Box is extended to include color. 
    class ColorBox extends Box { int color; // color of box ColorBox(double w, double h, double d, int c) { width = w; height = h; depth = d; color = c; } }

    A Superclass Variable Can Reference a Subclass Object

    A reference variable of a superclass can be assigned a reference to any subclass derived from that superclass.

    class RefDemo { public static void main(String args[]) { BoxWeight weightbox = new BoxWeight(3, 5, 7, 8.37); Box plainbox = new Box(); double vol; vol = weightbox.volume(); System.out.println("Volume of weightbox is " + vol); System.out.println("Weight of weightbox is " + weightbox.weight); System.out.println(); // assign BoxWeight reference to Box reference plainbox = weightbox; vol = plainbox.volume(); // OK, volume() defined in Box System.out.println("Volume of plainbox is " + vol); /* The following statement is invalid because plainbox does not define a weight member. */ // System.out.println("Weight of plainbox is " + plainbox.weight); } }

    Using super to Call Superclass Constructors

    A subclass can call a constructor defined by its superclass by use of the following form of super:

    super(arg-list);

    // A complete implementation of BoxWeight. class Box { private double width; private double height; private double depth; // construct clone of an object Box(Box ob) { // pass object to constructor width = ob.width; height = ob.height; depth = ob.depth; } // constructor used when all dimensions specified Box(double w, double h, double d) { width = w; height = h; depth = d; } // constructor used when no dimensions specified Box() { width = -1; // use -1 to indicate height = -1; // an uninitialized depth = -1; // box } // constructor used when cube is created Box(double len) { width = height = depth = len; } // compute and return volume double volume() { return width * height * depth; } } // BoxWeight now fully implements all constructors. class BoxWeight extends Box { double weight; // weight of box // construct clone of an object BoxWeight(BoxWeight ob) { // pass object to constructor super(ob); weight = ob.weight; } // constructor when all parameters are specified BoxWeight(double w, double h, double d, double m) {
    super(w, h, d); // call superclass constructor weight = m; } // default constructor BoxWeight() { super(); weight = -1; } // constructor used when cube is created BoxWeight(double len, double m) { super(len); weight = m; } } class DemoSuper { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); BoxWeight mybox2 = new BoxWeight(2, 3, 4, 0.076); BoxWeight mybox3 = new BoxWeight(); // default BoxWeight mycube = new BoxWeight(3, 2); BoxWeight myclone = new BoxWeight(mybox1); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); System.out.println("Weight of mybox1 is " + mybox1.weight); System.out.println(); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); System.out.println("Weight of mybox2 is " + mybox2.weight); System.out.println(); vol = mybox3.volume(); System.out.println("Volume of mybox3 is " + vol); System.out.println("Weight of mybox3 is " + mybox3.weight); System.out.println(); vol = myclone.volume(); System.out.println("Volume of myclone is " + vol); System.out.println("Weight of myclone is " + myclone.weight); System.out.println(); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); System.out.println("Weight of mycube is " + mycube.weight); System.out.println(); } }

    This program generates the following output:

    Volume of mybox1 is 3000.0 Weight of mybox1 is 34.3 Volume of mybox2 is 24.0 Weight of mybox2 is 0.076 Volume of mybox3 is -1.0 Weight of mybox3 is -1.0 Volume of myclone is 3000.0 Weight of myclone is 34.3 Volume of mycube is 27.0 Weight of mycube is 2.0

    A Second Use for super

    The second form of super acts somewhat like this, except that it always refers to the superclass of the subclass in which it is used. This usage has the following general form:

    super.member

    // Using super to overcome name hiding.
     class A { int i; }
    // Create a subclass by extending class A. class B extends A { int i; // this i hides the i in A B(int a, int b) { super.i = a; // i in A i = b; // i in B } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } }

    When Constructors Are Called

    // Demonstrate when constructors are called. 
    // Create a super class.
     class A { A() { System.out.println("Inside A's constructor."); } }
    // Create a subclass by extending class A. 
    class B extends A { B() { System.out.println("Inside B's constructor."); } } // Create another subclass by extending B. class C extends B { C() { System.out.println("Inside C's constructor."); } } class CallingCons { public static void main(String args[]) { C c = new C(); } }
     The output from this program is shown here:
     Inside A’s constructor
     Inside B’s constructor 
    Inside C’s constructor

    Method Overriding

    In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass.

    // Method overriding.
     class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } }
    class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // display k – this overrides show() in A void show() { System.out.println("k: " + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls show() in B } }
     The output produced by this program is shown here:
     k: 3

    If you wish to access the superclass version of an overridden method, you can do so by using super

    class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } }
     If you substitute this version of A into the previous program, you will see the following output: 
    i and j: 1 2
     k: 3

    Dynamic Method Dispatch

    Method overriding forms the basis for one of Java’s most powerful concepts: dynamic method dispatch. Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. Dynamic method dispatch is important because this is how Java implements run-time polymorphism.

    It is the type of the object being referred to (not the type of the reference variable) that determines which version of an overridden method will be executed.

    Overridden methods are another way that Java implements the “one interface, multiple methods” aspect of polymorphism.

    // Dynamic Method Dispatch
     class A { void callme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A
    r = a; // r refers to an A object r.callme(); // calls A's version of callme r = b; // r refers to a B object r.callme(); // calls B's version of callme r = c; // r refers to a C object r.callme(); // calls C's version of callme } } 
    The output from the program is shown here:
     Inside A’s callme method 	Inside B’s callme method Inside		 C’s callme method

    Abstract Classes

    Syntax: abstract type name(parameter-list);

    Any class that contains one or more abstract methods must also be declared abstract. To declare a class abstract, you simply use the abstract keyword in front of the class keyword at the beginning of the class declaration. There can be no objects of an abstract class. That is, an abstract class cannot be directly instantiated with the new operator. Also, you cannot declare abstract constructors, or abstract static methods. Any subclass of an abstract class must either implement all of the abstract methods in the superclass, or be itself declared abstract.

    // A Simple demonstration of abstract.
     abstract class A { abstract void callme();
     // concrete methods are still allowed in abstract classes 
    void callmetoo() { System.out.println("This is a concrete method."); } }
     class B extends A {
     void callme() { System.out.println("B's implementation of callme."); } }
     class AbstractDemo { 
    public static void main(String args[]) {
     B b = new B();
     b.callme();
     b.callmetoo(); } }

    Using final to Prevent Inheritance

    class A { 
    final void meth(){
     System.out.println("This is a final method."); } }
     class B extends A {
     void meth() { // ERROR! Can't override. System.out.println("Illegal!"); } }

    Inlining is only an option with final methods. Normally, Java resolves calls to methods dynamically, at run time. This is called late binding. However, since final methods cannot be overridden, a call to one can be resolved at compile time. This is called early binding.

    Sometimes you will want to prevent a class from being inherited. To do this, precede the class declaration with final.

    final class A { // ... }
     // The following class is illegal.
     class B extends A { // ERROR! Can't subclass A // ... }

    As the comments imply, it is illegal for B to inherit A since A is declared as final

    The Object Class

    There is one special class, Object, defined by Java. All other classes are subclasses of Object. That is, Object is a superclass of all other classes. This means that a reference variable of type Object can refer to an object of any other class. Also, since arrays are implemented as classes, a variable of type Object can also refer to any array. Object defines the following methods, which means that they are available in every object.

    Method			 Purpose
     Object clone( )		 			Creates a new object that is the same as the object being cloned.
     boolean equals(Object object)		 	Determines whether one object is equal to another.
     void finalize( ) 					Called before an unused object is recycled.
     Class getClass( ) 				Obtains the class of an object at run time.
     int hashCode( ) 				Returns the hash code associated with the invoking object. 
    void notify( ) 					Resumes execution of a thread waiting on the invoking object.
     void notifyAll( ) 				Resumes execution of all threads waiting on the invoking object. 
    String toString( ) 				Returns a string that describes the object. 
    void wait( ) 	
    void wait(long milliseconds)			Waits on another thread of execution.
     void wait(long milliseconds, int nanoseconds)
    
  • Java Chapter 8- Exception Handling
  • Exception Handling

    An exception is an abnormal condition that arises in a code sequence at run time. In other words, an exception is a run-time error. Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. This is the general form of an exception-handling block:

     
    try { // block of code to monitor for errors }
    catch (ExceptionType1 exOb) { // exception handler for ExceptionType1 } 
    catch (ExceptionType2 exOb) { // exception handler for ExceptionType2 } 
    // ...
    // ...
     finally { // block of code to be executed after try block ends }
     
    Example:
    class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } }

    throws: This is the general form of a method declaration that includes a throws clause:

    type method-name(parameter-list) throws exception-list { // body of method }

    throw: To throw an exception explicitly, using the throw statement. Syntax: throw ThrowableInstance;

    1.	public class TestThrow1{  
    2.	   static void validate(int age){  
    3.	     if(age<18)  
    4.	      throw new ArithmeticException("not valid");
    5.	     else  
    6.	      System.out.println("welcome to vote");     }  
    7.	   public static void main(String args[]){  
    8.	      validate(13);  
    9.	      System.out.println("rest of the code...");    }
    10.	} 
     

    The Finally Block: The finally block follows a try block or a catch block. A finally block of code always executes.Using a finally block allows you to run any cleanup-type statements that you want to execute.Syntax:

    try {
       // Protected code
    } catch (ExceptionType1 e1) {
       // Catch block
    } catch (ExceptionType2 e2) {
       // Catch block
    } catch (ExceptionType3 e3) {
       // Catch block
    }finally {
       // The finally block always executes.
    }
     
    1.	public class TestFinallyBlock2{  
    2.	  public static void main(String args[]){  
    3.	  try{  
    4.	   int data=25/0;  
    5.	   System.out.println(data);  
    6.	  }  
    7.	  catch(ArithmeticException e){System.out.println(e);}  
    8.	  finally{System.out.println("finally block is always executed");}  
    9.	  System.out.println("rest of the code...");  
    10.	  }  
    11.	}
     

    Java - Built-in Exceptions

    Java defines several exception classes inside the standard package java.lang.

    Following is the list of Java Unchecked RuntimeException.

    Sr.No.	Exception & Description
    1	ArithmeticException: Arithmetic error, such as divide-by-zero.
    2	ArrayIndexOutOfBoundsException: Array index is out-of-bounds.
    3	ArrayStoreException: Assignment to an array element of an incompatible type.
    4	ClassCastException: Invalid cast.
    5	IllegalArgumentException: Illegal argument used to invoke a method.
    6	IllegalMonitorStateException: Illegal monitor operation, such as waiting on an unlocked thread.
    7	IllegalStateException: Environment or application is in incorrect state.
    8	IllegalThreadStateException: Requested operation not compatible with the current thread state.
    9	IndexOutOfBoundsException: Some type of index is out-of-bounds.
    10	NegativeArraySizeException: Array created with a negative size.
    11	NullPointerException: Invalid use of a null reference.
    12	NumberFormatException: Invalid conversion of a string to a numeric format.
    13	SecurityException: Attempt to violate security.
    14	StringIndexOutOfBounds: Attempt to index outside the bounds of a string.
    15	UnsupportedOperationException: An unsupported operation was encountered.
    Following is the list of Java Checked Exceptions Defined in java.lang.
    Sr.No.	Exception & Description
    1	ClassNotFoundException: Class not found.
    2	CloneNotSupportedException: Attempt to clone an object that does not implement the Cloneable interface.
    
    3 IllegalAccessException: Access to a class is denied. 4 InstantiationException: Attempt to create an object of an abstract class or interface. 5 InterruptedException: One thread has been interrupted by another thread. 6 NoSuchFieldException: A requested field does not exist. 7 NoSuchMethodException: A requested method does not exist.
  • Java Chapter 9- Packages and Interfaces
  • Packages & Interfaces

    Packages

    Packages are containers for classes that are used to keep the class name space compartmentalized. Packages are stored in a hierarchical manner and are explicitly imported into new class definitions.

    A unique name had to be used for each class to avoid name collisions. Thankfully, Java provides a mechanism for partitioning the class name space into more manageable chunks. This mechanism is the package. The package is both a naming and a visibility control mechanism. You can define classes inside a package that are not accessible by code outside that package. You can also define class members that are only exposed to other members of the same package. This allows your classes to have intimate knowledge of each other, but not expose that knowledge to the rest of the world.

    Defining a Package

    To create a package is quite easy: simply include a package command as the first statement in a Java source file. Any classes declared within that file will belong to the specified package. The package statement defines a name space in which classes are stored. If you omit the package statement, the class names are put into the default package, which has no name.

    Syntax: package pkg;

    Example: package MyPackage;

    Java uses file system directories to store packages.

    The general form of a multileveled package statement is shown here: package pkg1[.pkg2[.pkg3]];

    Example: package java.awt.image;

    needs to be stored in java\awt\image in a Windows environment. Be sure to choose your package names carefully.

    Finding Packages and CLASSPATH

    packages are mirrored by directories. This raises an important question: How does the Java run-time system know where to look for packages that you create? The answer has three parts. First, by default, the Java run-time system uses the current working directory as its starting point. Thus, if your package is in a subdirectory of the current directory, it will be found. Second, you can specify a directory path or paths by setting the CLASSPATH environmental variable. Third, you can use the -classpath option with java and javac to specify the path to your classes.

    A Short Package Example 
     
    package MyPack;
     class Balance {
     String name;
     double bal;
     Balance(String n, double b) { 
    name = n; bal = b;
     } 
    void show() { 
    if(bal<0)
    System.out.print("--> "); 
    System.out.println(name + ": $" + bal);
     }
     }
     class AccountBalance {
     public static void main(String args[]) {
     Balance current[] = new Balance[3];
    current[0] = new Balance("K. J. Fielding", 123.23);
     current[1] = new Balance("Will Tell", 157.02);
     current[2] = new Balance("Tom Jackson", -12.33);
     for(int i=0; i<3; i++) current[i].show(); 
    }
    }
     

    Call this file AccountBalance.java and put it in a directory called MyPack

    Next, compile the file. Make sure that the resulting .class file is also in the MyPack directory. Then, try executing the AccountBalance class, using the following command line: java MyPack.AccountBalance

    Access Protection

    Classes and packages are both means of encapsulating and containing the name space 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. Because of the interplay between classes and packages, Java addresses four categories of visibility for class members:

    • Subclasses in the same package 
    • Non-subclasses in the same package
     • Subclasses in different packages
     • Classes that are neither in the same package nor subclasses

    Anything declared public can be accessed from anywhere. Anything declared private cannot be seen outside of its class. When a member does not have an explicit access specification, it is visible to subclasses as well as to other classes in the same package. This is the default access. If you want to allow an element to be seen outside your current package, but only to classes that subclass your class directly, then declare that element protected.

    Private	No Modifier	Protected	Public
    Same class	YES	YES	YES	YES
    Same package subclass	NO	YES	YES	YES
    Same package non-subclass	NO	YES	YES	YES
    Different package subclass	NO	NO	YES	YES
    Different package non-subclass	NO	NO	NO	YES

    Importing Packages

    Java includes the import statement to bring certain classes, or entire packages, into visibility. Once imported, a class can be referred to directly, using only its name. The import statement is a convenience to the programmer and is not technically needed to write a complete Java program.

    This is the general form of the import statement: import pkg1[.pkg2].(classname|*);

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

    All of the standard Java classes included with Java are stored in a package called java. The basic language functions are stored in a package inside of the java package called java.lang. Normally, you have to import every package or class that you want to use, but since Java is useless without much of the functionality in java.lang, it is implicitly imported by the compiler for all programs. This is equivalent to the following line being at the top of all of your programs:

    import java.lang.*;

    If a class with the same name exists in two different packages that you import using the star form, the compiler will remain silent, unless you try to use one of the classes. In that case, you will get a compile-time error and have to explicitly name the class specifying its package.

    import statement is optional. Any place you use a class name with its fully qualified name, which includes its full package hierarchy. For example:

    import java.util.*;
     class MyDate extends Date { }

    The same example without the import statement looks like this:

    class MyDate extends java.util.Date { }

    EXAMPLE:
    package MyPack;
    public class Balance {
        String name;
        double bal;
        public Balance(String n, double b) {
            name = n;
            bal = b;
        }
        public void show() {
            if(bal<0)
            System.out.print("--> "); 
            System.out.println(name + ": $" + bal);
        }
     }
    
    import MyPack.*; 
    class TestBalance {
        public static void main(String args[]) {
        Balance test = new Balance("J. J. Jaspers", 99.88);
        test.show();
        }
     }
     
    

    Interfaces

    Interfaces are syntactically similar to classes, but they lack instance variables, and their methods are declared without any body. Any number of classes can implement an interface & Also one class can implement any number of interfaces. Defining an Interface An interface is defined much like a class.

    Syntax of an interface:
     access interface name {
     	return-type method-name1(parameter-list);
     	return-type method-name2(parameter-list);
     	type final-varname1 = value; 
    	type final-varname2 = value;
     	// ... 
    	return-type method-nameN(parameter-list);
     	type final-varnameN = value;
     }
     
    Example:
    interface Callback {
    	 void callback(int param); 
    }
    

    Implementing Interfaces

    To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface.

    Syntax:
    class classname [extends superclass] [implements interface [,interface...]] {
    	 // class-body
     }
     

    The methods that implement an interface must be declared public. Also, the type signature of the implementing method must match exactly the type signature specified in the interface definition.

    Here is a small example class that implements the Callback interface shown earlier
    class Client implements Callback {
    	 // Implement Callback's interface
     	public void callback(int p) {
     		System.out.println("callback called with " + p);
     	}
     }
     

    Notice that callback( ) is declared using the public access specifier.

    class Client implements Callback { 
    	// Implement Callback's interface
     	public void callback(int p) {
    		 System.out.println("callback called with " + p);
     	}
     	void nonIfaceMeth() {
    		 System.out.println("Classes that implement interfaces " + "may also define other members, too.");
     	}
     }
     

    The following example calls the callback( ) method via an interface reference variable:

    class TestIface {
        public static void main(String args[]) {
        Callback c = new Client();
        c.callback(42);
        }
     }
     

    The output of this program is shown here:

    callback called with 42

    Example:
    // Another implementation of Callback.
     class AnotherClient implements Callback {
    	 // Implement Callbacks interface 
    	public void callback(int p) {
     		System.out.println("Another version of callback");
     		System.out.println("p squared is " + (p*p));
     	}
     }
     

    Now, try the following class:

    class TestIface2 {
        public static void main(String args[]) {
            Callback c = new Client();
            AnotherClient ob = new AnotherClient();
            c.callback(42);
            c = ob;
            // c now refers to AnotherClient object
            c.callback(42); 
        }
     }
     
    The output from this program is shown here:
    callback called with 42 
    Another version of callback p squared is 1764
     

    Partial Implementations

    If a class includes an interface but does not fully implement the methods defined by that interface, then that class must be declared as abstract. For example:

    abstract class Incomplete implements Callback {
        int a, b;
        void show() { 
            System.out.println(a + " " + b);
        }
        // ...
     }
     

    First, here is the interface that defines an integer stack. Put this in a file called IntStack.java. This interface will be used by both stack implementations.

    interface IntStack { 
        void push(int item); 
        int pop();
    }
    // An implementation of IntStack that uses fixed storage. 
    class FixedStack implements IntStack {
        private int stck[];
        private int tos;
        // allocate and initialize stack 
        FixedStack(int size) {
            stck = new int[size];
            tos = -1;
        }
        // Push an item onto the stack 
        public void push(int item) {
            if(tos==stck.length-1) // use length member 
                System.out.println("Stack is full.");
            else
                stck[++tos] = item;
        }
        // Pop an item from the stack
        public int pop() {
            if(tos < 0) {
                System.out.println("Stack underflow.");
                return 0;
            }
            else
                return  stck[tos--]; 
        }	 
    }
     class IFTest {
            public static void main(String args[]) { 
                FixedStack mystack1 = new FixedStack(5); 
                FixedStack mystack2 = new FixedStack(8);
                // push some numbers onto the stack
                for(int i=0; i<5;i++)
                    mystack1.push(i);
                for(int i=0; i<8;i++)
                    mystack2.push(i);
                // pop those numbers off the stack
                 System.out.println("Stack in mystack1:");
                for(int i=0; i<5;i++)
                    System.out.println(mystack1.pop());
                System.out.println("Stack in mystack2:");
                for(int i=0; i<8;i++)
                    System.out.println(mystack2.pop());
            }
    }
     
    Following is another implementation of IntStack that creates a dynamic stack by use of the same interface definition.
    // Implement a "growable" stack.
     class DynStack implements IntStack {
            private int stck[];
            private int tos;
            DynStack(int size) {
                stck = new int[size];
                tos = -1;
            }
            public void push(int item) {
                if(tos==stck.length-1) {
                    int temp[] = new int[stck.length * 2]; // double size
                    for(int i=0; i<stack.length;i++) 
                        temp[i]=stck[i];
                    stck = temp;
                    stck[++tos] = item; 
                }
                else
                    stck[++tos] = item;
            }
            public int pop() {
                if(tos < 0) {
                    System.out.println("Stack underflow.");
                    return 0;
                }
                else
                    return stck[tos--]; 
                }
            }
    class IFTest2 {
        public static void main(String args[]) {
            DynStack mystack1 = new DynStack(5);
            DynStack mystack2 = new DynStack(8); 
            for(int i=0;i<12;i++) 
                mystack1.push(i);
            for(int i=0;i<20;i++)
                mystack2.push(i);
            for(int i=0;i<12;i++)
                System.out.println(mystack1.pop());
            for(int i=0;i<20;i++)
                System.out.println(mystack2.pop());
        }
    }
     

    Interfaces Can Be Extended

    One interface can inherit another by use of the keyword extends.

    // One interface can extend another.
     interface A {
    	 void meth1(); 
    	void meth2();
     }
     interface B extends A {
     	void meth3();
     }
     class MyClass implements B {
     	public void meth1() { 
    	System.out.println("Implement meth1().");
     }
     public void meth2() {
    	 System.out.println("Implement meth2().");
     }
     public void meth3() {	
    System.out.println("Implement meth3().");
     	}
     }
     class IFExtend {
     public static void main(String arg[]) {
     	MyClass ob = new MyClass();
    	 ob.meth1();
     	ob.meth2(); 
    	ob.meth3(); 
    	}
     }
     
    
  • Java Chapter 10- Enumerations & Type Wrappers
  • Enumerations & Type Wrappers

    Enumerations

    An enumeration is a list of named constants.Enumeration Fundamentals An enumeration is created using the enum keyword.

    For example:
     enum Indian {   varsha, nikita, ramika, sikha, barun   }
    

    The identifiers varsha, nikita, ramika and so on, are called enumeration constants. Each is implicitly declared as a public, static final member of Indian.

    For example,
    Indian ap;
    ap = Indian.ramika;
    
    For example,
    // An enumeration of apple varieties.
      
    enum Indian {   varsha, nikita, ramika, sikha, barun   }
    class EnumDemo {
         public static void main(String args[]) {
        Indian ap;
        ap = Indian.ramika;
        // Output an enum value.
        System.out.println("Value of ap: " + ap);
        System.out.println();
        ap = Indian.sikha;
        // Compare two enum values.
        if(ap == Indian.sikha) 
        System.out.println("ap contains sikha.\n");
        // Use an enum to control a switch statement. 
        switch(ap) {
            case varsha: System.out.println("varsha is brilliant."); break;
            case nikita: System.out.println("nikita  is smart."); break;
            case ramika: System.out.println("ramika is sharp."); break;
            case sikha: System.out.println("sikha is clever."); break; 
            case barun: System.out.println("barun is master."); break;
            }
        }
     }
     
    The output from the program is shown here:
    Value of ap: ramika
     ap contains sikha.
     sikha is clever.
    
    The values( ) and valueOf( ) Methods

    All enumerations automatically contain two predefined methods: values( ) and valueOf( ). Their general forms are shown here:

    public static enum-type[ ] values( )

    public static enum-type valueOf(String str)

    // An enumeration of apple varieties.
         enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland }
     class EnumDemo2 {
        public static void main(String args[]) {
            Apple ap;
            System.out.println("Here are all Apple constants:"); 
            // use values()
            Apple allapples[] = Apple.values();
            for(Apple a : allapples)
                System.out.println(a);
                System.out.println();
            // use valueOf()
            ap = Apple.valueOf("Winesap"); 
            System.out.println("ap contains " + ap);
        }
     }
     
    The output from the program is shown here:
    Here are all Apple constants:
     Jonathan
     GoldenDel
     RedDel
     Winesap
     Cortland
     ap contains Winesap
     

    Type Wrappers

    Java provides type wrappers, which are classes that encapsulate a primitive type within an object.The type wrappers are Double, Float, Long, Integer, Short, Byte, Character, and Boolean. These classes offer a wide array of methods that allow you to fully integrate the primitive types into Java’s object hierarchy.

    Number

    The abstract class Number defines a superclass that is implemented by the classes that wrap the numeric types byte, short, int, long, float, and double. Number has abstract methods that return the value of the object in each of the different number formats.

    byte byteValue( ) 
    double doubleValue( )
    float floatValue( )
    int intValue( )
    long longValue( )
    short shortValue( )
    

    The values returned by these methods can be rounded. Number has six concrete subclasses that hold explicit values of each numeric type: Double, Float, Byte, Short, Integer, and Long.

    // Demonstrate a type wrapper. 
    class Wrap {
        public static void main(String args[]) {
            Integer iOb = new Integer(100);
            int i = iOb.intValue();
            System.out.println(i + " " + iOb); // displays 100 100
        }
     }    
    

    All of the numeric type wrappers define constructors that allow an object to be constructed from a given value, or a string representation of that value. For example, here are the constructors defined for Integer: Integer(int num) or Integer(String str)

    If str does not contain a valid numeric value, then a NumberFormatException is thrown

    All of the type wrappers override toString( ). It returns the human-readable form of the value contained within the wrapper. This allows you to output the value by passing a type wrapper object to println( ), for example, without having to convert it into its primitive type.

    Byte, Short, Integer, and Long

    The Byte, Short, Integer, and Long classes are wrappers for byte, short, int, and long integer types, respectively. Their constructors are shown here:

     Byte(byte num)
     Byte(String str) throws NumberFormatException 
     Short(short num)
     Short(String str) throws NumberFormatException 
     Integer(int num)
     Integer(String str) throws NumberFormatException
     Long(long num) 
     Long(String str) throws NumberFormatException
     
     /* This program sums a list of numbers entered by the user. It converts the string representation of each number into an int using parseInt().*/
    import java.io.*;
    class ParseDemo {
        public static void main(String args[]) throws IOException
        {
            // create a BufferedReader using System.in
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String str;
            int i;
            int sum=0;
            System.out.println("Enter numbers, 0 to quit.");
            do {
                str = br.readLine();
                try 
                {
                    i = Integer.parseInt(str);
                } 
                catch(NumberFormatException e)
                {
                    System.out.println("Invalid format");
                    i = 0;
                }
                sum += i;
                System.out.println("Current sum is: " + sum);
            } while(i != 0);
        }
    }
    
    
    
    /* Convert an integer into binary, hexadecimal, and octal. */
    class StringConversions {
        public static void main(String args[]) {
            int num = 19648;
            System.out.println(num + " in binary: " + Integer.toBinaryString(num));
            System.out.println(num + " in octal: " + Integer.toOctalString(num));
            System.out.println(num + " in hexadecimal: " + Integer.toHexString(num));
        }
    }
    The output of this program is shown here:
    19648 in binary: 100110011000000
    19648 in octal: 46300
    19648 in hexadecimal: 4cc0
    

    Double and Float

    Double and Float are wrappers for floating-point values of type double and float, respectively.

    The constructors for Float are shown here:
    Float(double num) 
    Float(float num) 
    Float(String str) throws NumberFormatException
    The constructors for Double are shown here:
    Double(double num)
    Double(String str) throws NumberFormatException
    
        
    //Compare two double number
    class DoubleDemo {
        public static void main(String args[]) {
            Double d1 = new Double(3.14159);
            Double d2 = new Double("314159E-5");
            System.out.println(d1 + " = " + d2 + " -> " + d1.equals(d2));
        }
    }
        
    
    // Demonstrate isInfinite() and isNaN()
    class InfNaN {
        public static void main(String args[]) {
            Double d1 = new Double(1/0.);
            Double d2 = new Double(0/0.);
            System.out.println(d1 + ": " + d1.isInfinite() + ", " + d1.isNaN());
            System.out.println(d2 + ": " + d2.isInfinite() + ", " + d2.isNaN());
        }
    }
    output:
    This program generates the following output: 
    Infinity: true, false 
    NaN: false, true
    

    Character

    Character is a wrapper around a char. The constructor for Character is Character(char ch)

    To obtain the char value contained in a Character object, call charValue( ), shown here: char charValue( )

    // Demonstrate several Is... methods. 
    class IsDemo {
        public static void main(String args[]) {
            char a[] = {'a', 'b', '5', '?', 'A', ' '};
            for(int i=0; i a.length; i++) {
                if(Character.isDigit(a[i]))
                    System.out.println(a[i] + " is a digit.");
                if(Character.isLetter(a[i]))
                    System.out.println(a[i] + " is a letter.");
                if(Character.isWhitespace(a[i]))
                    System.out.println(a[i] + " is whitespace.");
                if(Character.isUpperCase(a[i]))
                    System.out.println(a[i] + " is uppercase.");
                if(Character.isLowerCase(a[i]))
                    System.out.println(a[i] + " is lowercase.");
            }
        }
    }
    The output from this program is shown here:
    a is a letter.
    a is lowercase.
    b is a letter.
    b is lowercase.
    5 is a digit.
    A is a letter.
    A is uppercase.
    is whitespace.
        
    

    Boolean

    Boolean is a wrapper around boolean values. It defines these constructors: Boolean(boolean boolValue) or Boolean(String boolString)

    To obtain a boolean value from a Boolean object, use booleanValue( ), shown here: boolean booleanValue( )

    Void

    The Void class has one field, TYPE, which holds a reference to the Class object for type void. You do not create instances of this class

    Autoboxing

    Autoboxing is the process by which a primitive type is automatically encapsulated (boxed) into its equivalent type wrapper whenever an object of that type is needed. There is no need to explicitly construct an object.

    auto-unboxing

    Auto-unboxing is the process by which the value of a boxed object is automatically extracted (unboxed) from a type wrapper when its value is needed. There is no need to call a method such as intValue( ) or doubleValue( ).

        
    // Demonstrate autoboxing/unboxing.
     class AutoBox { 
        public static void main(String args[]) {
            Integer iOb = 100; // autobox an int
            int i = iOb; // auto-unbox
            System.out.println(i + " " + iOb); // displays 100 100 
        }
    }
    

    Process

    The abstract Process class encapsulates a process—that is, an executing program. It is used primarily as a superclass for the type of objects created by exec( ) in the Runtime class, or by start( ) in the ProcessBuilder class.

    Runtime

    The Runtime class encapsulates the run-time environment. You cannot instantiate a Runtime object. However, you can get a reference to the current Runtime object by calling the static method Runtime.getRuntime( ). Once you obtain a reference to the current Runtime object, you can call several methods that control the state and behavior of the Java Virtual Machine.

    
    // Demonstrate totalMemory(), freeMemory() and gc().
    class MemoryDemo {
        public static void main(String args[]) {
            Runtime r = Runtime.getRuntime();
            long mem1, mem2;
            Integer someints[] = new Integer[1000];
            System.out.println("Total memory is: " +r.totalMemory());
            mem1 = r.freeMemory();
            System.out.println("Initial free memory: " + mem1);
            r.gc();
            mem1 = r.freeMemory();
            System.out.println("Free memory after garbage collection: "+ mem1);
            for(int i=0; i< 1000; i++)
                someints[i] = new Integer(i); // allocate integers
            mem2 = r.freeMemory();
            System.out.println("Free memory after allocation: "+ mem2);
            System.out.println("Memory used by allocation: "+ (mem1-mem2));
            // discard Integers
            for(int i=0; i < 1000; i++)
                someints[i] = null;
            r.gc(); // request garbage collection
            mem2 = r.freeMemory();
            System.out.println("Free memory after collecting" +" discarded Integers: " + mem2);
        }
    }
    Sample output from this program is shown here (of course, your actual results may vary):
    Total memory is: 1048568
    Initial free memory: 751392
    Free memory after garbage collection: 841424
    Free memory after allocation: 824000
    Memory used by allocation: 17424
    Free memory after collecting discarded Integers: 842640
    
    
    
    
    // Demonstrate exec().
    class ExecDemo {
        public static void main(String args[]) {
            Runtime r = Runtime.getRuntime();
            Process p = null;
            try {
                p = r.exec("notepad");
            } catch (Exception e) {
                System.out.println("Error executing notepad.");
            }
        }
    }
    
    
    
    // Wait until notepad is terminated.
    class ExecDemoFini {
        public static void main(String args[]) {
            Runtime r = Runtime.getRuntime();
            Process p = null;
            try
            {
                p = r.exec("notepad");
                p.waitFor();
            } 
            catch (Exception e)
            {
                System.out.println("Error executing notepad.");
            }
            System.out.println("Notepad returned " + p.exitValue());
        }
    }
        
    

    ProcessBuilder

    ProcessBuilder provides another way to start and manage processes (that is, programs). ProcessBuilder offers more control over the processes. For example, you can set the current working directory and change environmental parameters. ProcessBuilder defines these constructors: ProcessBuilder(List args)

    ProccessBuilder(String ... args)

    //Execute Notepad
    class PBDemo {
        public static void main(String args[]) {
            try {
                ProcessBuilder proc = new ProcessBuilder("notepad.exe", "testfile");
                proc.start();
            }
            catch (Exception e) {
                System.out.println("Error executing notepad.");
            }
        }
    }
    

    System

    The System class holds a collection of static methods and variables. The standard input, output, and error output of the Java run time are stored in the in, out, and err variables.

    // Timing program execution.
    class Elapsed {
        public static void main(String args[]) {
            long start, end;
            System.out.println("Timing a for loop from 0 to 1,000,000");
            // time a for loop from 0 to 1,000,000
            start = System.currentTimeMillis(); // get starting time
            for(int i=0; i < 1000000; i++) ;
                end = System.currentTimeMillis(); // get ending time
            System.out.println("Elapsed time: " + (end-start));
        }
    }
    

    Math

    The Math class contains all the floating-point functions that are used for geometry and trigonometry, as well as several general-purpose methods. Math defines two double constants: E (approximately 2.72) and PI (approximately 3.14).

    // Demonstrate toDegrees() and toRadians().
    class Angles {
    public static void main(String args[]) {
    double theta = 120.0;
    System.out.println(theta + " degrees is " +
    Math.toRadians(theta) + " radians.");
    theta = 1.312;
    System.out.println(theta + " radians is " +
    Math.toDegrees(theta) + " degrees.");
    }
    }
    The output is shown here:
    120.0 degrees is 2.0943951023931953 radians.
    1.312 radians is 75.17206272116401 degrees.
    
        
    
  • Java Chapter 11- I/O & FILE HANDLING
  • I/O & FILE HANDLING

    Streams: Java programs perform I/O through streams. A stream is an abstraction that either produces or consumes information. A stream is linked to a physical device by the Java I/O system. This means that an input stream can abstract many different kinds of input: from a disk file, a keyboard, or a network socket. Likewise, an output stream may refer to the console, a disk file, or a network connection. Java implements streams within class hierarchies defined in the java.io package.

    Byte Streams and Character Streams: Java defines two types of streams: byte and character. Byte streams provide a convenient means for handling input and output of bytes. Byte streams are used, for example, when reading or writing binary data. Character streams provide a convenient means for handling input and output of characters. They use Unicode.

    The Byte Stream Classes: Byte streams are defined by using two class hierarchies. At the top are two abstract classes: InputStream and OutputStream. Each of these abstract classes has several concrete subclasses that handle the differences between various devices, such as disk files, network connections, and even memory buffers. to use the stream classes, you must import java.io. The abstract classes InputStream and OutputStream define several key methods that the other stream classes implement. Two of the most important are read( ) and write( ), which, respectively, read and write bytes of data.

    The Character Stream Classes: Character streams are defined by using two class hierarchies. At the top are two abstract classes, Reader and Writer. These abstract classes handle Unicode character streams. The abstract classes Reader and Writer define several key methods that the other stream classes implement. Two of the most important methods are read( ) and write( ), which read and write characters of data, respectively.

    The Predefined Streams: All Java programs automatically import the java.lang package. This package defines a class called System, which encapsulates several aspects of the run-time environment. System also contains three predefined stream variables: in, out, and err. System.out refers to the standard output stream. By default, this is the console. System.in refers to standard input, which is the keyboard by default. System.err refers to the standard error stream, which also is the console by default. System.in is an object of type InputStream; System.out and System.err are objects of type PrintStream.

    Reading Console Input: BufferedReader supports a buffered input stream.

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

    Reading Characters: To read a character from a BufferedReader, use read( ).

    int read( ) throws IOException

    Example:
    // Use a BufferedReader to read characters from the console.
     import java.io.*;
     class BRRead {
        public static void main(String args[]) throws IOException { 
        char c;
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        System.out.println("Enter characters, 'q' to quit.");
        // read characters 
        do {
            c = (char) br.read();
            System.out.println(c);
            } while(c != 'q');
        }
     }
     

    Reading Strings: To read a string from the keyboard, use the version of readLine( ) that is a member of the BufferedReader class.

    Syntax: String readLine( ) throws IOException

    Example:
      
    import java.io.*;
     class BRReadLines { 
        public static void main(String args[]) throws IOException { 
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        String str;
        System.out.println("Enter lines of text.");
        System.out.println("Enter 'stop' to quit.");
        do {
            str = br.readLine();
            System.out.println(str);
            } while(!str.equals("stop"));
        }
     }
     
    
    The next example creates a tiny text editor.
    import java.io.*;
     class TinyEdit {
        public static void main(String args[]) throws IOException {
            BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
            String str[] = new String[100];
            System.out.println("Enter lines of text. Enter 'stop' to quit.");
            for(int i=0; i 100;i++){
    	        str[i] = br.readLine(); 
    	        if(str[i].equals("stop"))
     	            break;
     	      }
            System.out.println("\nHere is your file:");
            for(int i=0; i 100;i++){
                if(str[i].equals("stop")) 
                    break;
                System.out.println(str[i]);
            }
        }	 
    }
    

    File:- A File object is used to obtain or manipulate the information associated with a disk file, such as the permissions, time, date, and directory path, and to navigate subdirectory hierarchies. A directory in Java is treated simply as a File with one additional property—a list of filenames that can be examined by the list( ) method.

    constructors can be used to create File objects:
    File(String directoryPath) 
    File(String directoryPath, String filename)
    File(File dirObj, String filename)
    File(URI uriObj)
     
    Example:
     File f1 = new File("/");
     File f2 = new File("/","autoexec.bat");
     File f3 = new File(f1,"autoexec.bat");
    
    // Demonstrate File.
    import java.io.File;
    class FileDemo {
        static void p(String s)
        {
            System.out.println(s);
        }
        public static void main(String args[])
        {
            File f1 = new File("/java/COPYRIGHT");
            p("File Name: " + f1.getName());
            p("Path: " + f1.getPath());
            p("Abs Path: " + f1.getAbsolutePath());
            p("Parent: " + f1.getParent());
            p(f1.exists() ? "exists" : "does not exist");
            p(f1.canWrite() ? "is writeable" : "is not writeable");
            p(f1.canRead() ? "is readable" : "is not readable");
            p("is " + (f1.isDirectory() ? "" : "not" + " a directory"));
            p(f1.isFile() ? "is normal file" : "might be a named pipe");
            p(f1.isAbsolute() ? "is absolute" : "is not absolute");
            p("File last modified: " + f1.lastModified());
            p("File size: " + f1.length() + " Bytes");
        }
    }
    
    Output:
    File Name: COPYRIGHT
    Path: /java/COPYRIGHT
    Abs Path: /java/COPYRIGHT
    Parent: /java
    exists
    is writeable
    is readable
    is not a directory
    is normal file
    is absolute
    File last modified: 812465204000
    File size: 695 Bytes
    

    Directories:- A directory is a File that contains a list of other files and directories. When you create a File object and it is a directory, the isDirectory( ) method will return true. In this case, you can call list( ) on that object to extract the list of other files and directories inside. It has two forms. The first is shown here: String[ ] list( )

    // Using directories.
    import java.io.File;
    class DirList {
        public static void main(String args[])
        {
            String dirname = "/java";
            File f1 = new File(dirname);
            if (f1.isDirectory())
            {
                System.out.println("Directory of " + dirname);
                String s[] = f1.list();
                for (int i=0; i < s.length; i++)
                {
                    File f = new File(dirname + "/" + s[i]);
                    if (f.isDirectory())
                    {
                        System.out.println(s[i] + " is a directory");
                    }
                    else
                    {
                        System.out.println(s[i] + " is a file");
                    }
                }
            }
            else
            {
                System.out.println(dirname + " is not a directory");
            }
        }
    }
    

    FileInputStream:- The FileInputStream class creates an InputStream that you can use to read bytes from a file. Either can throw a FileNotFoundException. Its two most common constructors are shown here:

        FileInputStream(String filepath) 
        FileInputStream(File fileObj)
        
    

    When you are done with a file, you should close it by calling close( ). It is defined by both FileInputStream and FileOutputStream, as shown here: void close( ) throws IOException

    To read from a file: use a read( ) that is defined within FileInputStream. Syntax: int read( ) throws IOException

    import java.io.*;
     class ShowFile
     {
        public static void main(String args[]) throws IOException
        {
            int i;
            FileInputStream fin; 
            try { 
                fin = new FileInputStream(args[0]);
            }
            catch(FileNotFoundException e) {
                System.out.println("File Not Found");
                return;
            }
            catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("Usage: ShowFile File");
                return;
            }
            // read characters until EOF is encountered
            do {
                i = fin.read();
    	        if(i != -1)
    	            System.out.print((char) i);
            } while(i != -1);
             fin.close();
        }
    }
     
    // Demonstrate FileInputStream.
    import java.io.*;
    class FileInputStreamDemo {
        public static void main(String args[]) throws IOException {
            int size;
            InputStream f = new FileInputStream("FileInputStreamDemo.java");
            System.out.println("Total Available Bytes: " +(size = f.available()));
            int n = size/40;
            System.out.println("First " + n +" bytes of the file one read() at a time");
            for (int i=0; i < n; i++)
            {
                System.out.print((char) f.read());
            }
            System.out.println("\nStill Available: " + f.available());
            System.out.println("Reading the next " + n +" with one read(b[])");
            byte b[] = new byte[n];
            if (f.read(b) != n)
            {
                System.err.println("couldn't read " + n + " bytes.");
            }
            System.out.println(new String(b, 0, n));
            System.out.println("\nStill Available: " + (size = f.available()));
            System.out.println("Skipping half of remaining bytes with skip()");
            f.skip(size/2);
            System.out.println("Still Available: " + f.available());
            System.out.println("Reading " + n/2 + " into the end of array");
            if (f.read(b, n/2, n/2) != n/2)
            {
                System.err.println("couldn't read " + n/2 + " bytes.");
            }
            System.out.println(new String(b, 0, b.length));
            System.out.println("\nStill Available: " + f.available());
            f.close();
        }
    }
    
    OUTPUT:
    Total Available Bytes: 1433
    First 35 bytes of the file one read() at a time
    // Demonstrate FileInputStream.
    im
    Still Available: 1398
    Reading the next 35 with one read(b[])
    port java.io.*;
    class FileInputS
    Still Available: 1363
    Skipping half of remaining bytes with skip()
    Still Available: 682
    Reading 17 into the end of array
    port java.io.*;
    read(b) != n) {
    S
    Still Available: 665
    

    FileOutputStream:- FileOutputStream creates an OutputStream that you can use to write bytes to a file. Its most commonly used constructors are shown here:

    FileOutputStream(String filePath)
    FileOutputStream(File fileObj)
    FileOutputStream(String filePath, boolean append) 
    FileOutputStream(File fileObj, boolean append)
    

    To write to a file: you can use the write( ) method defined by FileOutputStream. Its simplest form is shown here: void write(int byteval) throws IOException

    import java.io.*;
     class CopyFile { 
        public static void main(String args[]) throws IOException {
            int i;
            FileInputStream fin;
            FileOutputStream fout;
            try { 
                try {
                    // open input file
                    fin = new FileInputStream(args[0]); 
                }
                catch(FileNotFoundException e) {
                    System.out.println("Input File Not Found"); 
                    return;
                }
                try {
                    // open output file
                    fout = new FileOutputStream(args[1]);
                }
                catch(FileNotFoundException e) {
                    System.out.println("Error Opening Output File");
                    return;
                }
            }
            catch(ArrayIndexOutOfBoundsException e) {
                System.out.println("Usage: CopyFile From To");
                return;
            }
        
        try {
            do { 
    	            i = fin.read();
     	            if(i != -1) fout.write(i);
            } while(i != -1);
        }
        catch(IOException e) { 
    	    System.out.println("File Error");
    	}
        fin.close();
        fout.close();
        }
     }
     
    // Demonstrate FileOutputStream.
    import java.io.*;
    class FileOutputStreamDemo {
        public static void main(String args[]) throws IOException
        {
            String source = "Now is the time for all good men\n"+ " to come to the aid of their country\n"+ " and pay their due taxes.";
            byte buf[] = source.getBytes();
            OutputStream f0 = new FileOutputStream("file1.txt");
            for (int i=0; i < buf.length; i += 2)
            {
                f0.write(buf[i]);
            }
            f0.close();
            OutputStream f1 = new FileOutputStream("file2.txt");
            f1.write(buf);
            f1.close();
            OutputStream f2 = new FileOutputStream("file3.txt");
            f2.write(buf,buf.length-buf.length/4,buf.length/4);
            f2.close();
        }
    }
    

    The Character Streams

    FileReader:- The FileReader class creates a Reader that you can use to read the contents of a file. Either can throw a FileNotFoundException. Its two most commonly used constructors are shown here:

        FileReader(String filePath)
        FileReader(File fileObj)
     
    
    // Demonstrate FileReader.
    import java.io.*;
    class FileReaderDemo
    {
        public static void main(String args[]) throws IOException
        {
            FileReader fr = new FileReader("FileReaderDemo.java");
            BufferedReader br = new BufferedReader(fr);
            String s;
            while((s = br.readLine()) != null) 
            {
                System.out.println(s);
            }
            fr.close();
        }
    }
    

    FileWriter:- FileWriter creates a Writer that you can use to write to a file. Its most commonly used constructors are shown here:

        FileWriter(String filePath)
        FileWriter(String filePath, boolean append)
        FileWriter(File fileObj)
        FileWriter(File fileObj, boolean append)
     

    They can throw an IOException. Here, filePath is the full path name of a file, and fileObj is a File object that describes the file. If append is true, then output is appended to the end of the file.

    // Demonstrate FileWriter.
    import java.io.*;
    class FileWriterDemo {
        public static void main(String args[]) throws IOException
        {
            String source = "Now is the time for all good men\n"+ " to come to the aid of their country\n"+ " and pay their due taxes.";
            char buffer[] = new char[source.length()];
            source.getChars(0, source.length(), buffer, 0);
            FileWriter f0 = new FileWriter("file1.txt");
            for (int i=0; i < buffer.length; i += 2)
            {
                f0.write(buffer[i]);
            }
            f0.close();
            FileWriter f1 = new FileWriter("file2.txt");
            f1.write(buffer);
            f1.close();
            FileWriter f2 = new FileWriter("file3.txt");
            f2.write(buffer,buffer.length-buffer.length/4,buffer.length/4);
            f2.close();
        }
    } 
    
  • Java Chapter 12- String Handling
  • String Handling

    Java implements strings as objects of type String. when you create a String object, you are creating a string that cannot be changed. For those cases in which a modifiable string is desired, Java provides two options: StringBuffer and StringBuilder. Both hold strings that can be modified after they are created. The String, StringBuffer, and StringBuilder classes are defined in java.lang.

    The String Constructors

    String():- To create an empty String, you call the default constructor. For example, String s = new String();

    String(char chars[ ]):- To create a String initialized by an array of characters.

    String(char chars[ ], int startIndex, int numChars):- You can specify a subrange of a character array.

    String(byte asciiChars[ ]):- To convert byte array to string.

    String(byte asciiChars[ ], int startIndex, int numChars):- You can specify a subrange of a byte array.

    Here, startIndex specifies the index at which the subrange begins, and numChars specifies the number of characters to use.

    Example Program:
    // Construct string from subset of char array. 
    class SubStringCons {
        public static void main(String args[])
        {
            byte ascii[] = {65, 66, 67, 68, 69, 70 };//char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
            String s1 = new String(ascii);
            System.out.println(s1); 
            String s2 = new String(ascii, 2, 3);
            System.out.println(s2);
        }
     } 
     
    This program generates the following output:
        ABCDEF
        CDE
     

    String(String strObj):- Construct a String object that contains the same character sequence as another String object using this constructor.

    // Construct one String from another.
     class MakeString 
     {
        public static void main(String args[]) 
        { 
            char c[] = {'J', 'a', 'v', 'a'};
            String s1 = new String(c);
            String s2 = new String(s1);
            System.out.println(s1);
            System.out.println(s2);
        }
     }
     

    The output from this program is as follows: Java Java

    The String Method

      1) Length():- The length of a string is the number of characters that it contains. To obtain this value, call the length( ) method, Syntax:int length( )

      2)String Concatenation:- + operator, which concatenates two strings, producing a String object as the result.

      Example
          String age = "9"; 
          String s = "He is " + age + " years old.";
          System.out.println(s);
          This displays the string “He is 9 years old.”
      

      3)String Conversion and toString( ):- To implement toString( ), simply return a String object that contains the human-readable string that appropriately describes an object of your class.

      // Override toString() for Box class.
       class Box
       {
          double width;
          double height;
          double depth;
          Box(double w, double h, double d) 
          {
              width = w; height = h; depth = d;
          }
          public String toString()
          {
              return "Dimensions are " + width + " by " + depth + " by " + height + ".";
          }
       }
       class toStringDemo
       {
          public static void main(String args[])
          {
              Box b = new Box(10, 12, 14);
              String s = "Box b: " + b; 
              // concatenate Box object 
              System.out.println(b); 
              // convert Box to string 
              System.out.println(s);
          }
       }
       The output of this program is shown here: 
       Dimensions are 10.0 by 14.0 by 12.0 
       Box b: Dimensions are 10.0 by 14.0 by 12.0
       

      4)charAt( ): To extract a single character from a String.

      Syntax:- char charAt(int where)

          Example:-
          char ch;
          ch = "abc".charAt(1);
          Output:- assigns the value “b” to ch.
      

    5)getChars( ):- If you need to extract more than one character at a time, you can use the getChars( ) method.

    Syntax:- void getChars(int sourceStart, int sourceEnd, char target[ ], int targetStart)

    Example:-
    class getCharsDemo { 
        public static void main(String args[])
        {
            String s = "This is a demo of the getChars method.";
            int start = 10;
            int end = 14;
            char buf[] = new char[end - start];
            s.getChars(start, end, buf, 0);
            System.out.println(buf); 
        } 
    }
     Here is the output of this program: demo
     

    6) getBytes( ):- There is an alternative to getChars( ) that stores the characters in an array of bytes.

    Syntax:- byte[ ] getBytes( )

    7) toCharArray( ) :- To convert all the characters in a String object into a character array.

    Syntax:- char[ ] toCharArray( )

    8) equals( ) and equalsIgnoreCase( ):- To compare two strings for equality, use equals( ). It has this general form: boolean equals(Object str) . To perform a comparison that ignores case differences, call equalsIgnoreCase( ). When it compares two strings, it considers A-Z to be the same as a-z. It has this general form:boolean equalsIgnoreCase(String str)

    // Demonstrate equals() and equalsIgnoreCase().
     class equalsDemo
     { 
        public static void main(String args[])
        {
            String s1 = "Hello";
            String s2 = "Hello"; 
            String s3 = "Good-bye"; 
            String s4 = "HELLO";
            System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
            System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
            System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4)); 
            System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " + s1.equalsIgnoreCase(s4));
        }
     }
     The output from the program is shown here: 
        Hello equals Hello -> true 
        Hello equals Good-bye -> false
        Hello equals HELLO -> false
        Hello equalsIgnoreCase HELLO -> true
     

    9) regionMatches( ):- The regionMatches( ) method compares a specific region inside a string with another specific region in another string.

    boolean regionMatches(int startIndex, String str2, int str2StartIndex, int numChars)

    boolean regionMatches(boolean ignoreCase, int startIndex, String str2, int str2StartIndex, int numChars)

    10)startsWith( ) and endsWith( ):- The startsWith( ) method determines whether a given String begins with a specified string. Conversely, endsWith( ) determines whether the String in question ends with a specified string.

    Syntax:- boolean startsWith(String str) or boolean endsWith(String str)

    Example:- "Foobar".endsWith("bar") and "Foobar".startsWith("Foo") are both true.

    11)compareTo( ):- A string is less than another if it comes before the other in dictionary order. A string is greater than another if it comes after the other in dictionary order. The String method compareTo( ) serves this purpose.

    Syntax:- int compareTo(String str)

     Value 					    Meaning
     Less than zero				    The invoking string is less than str.
     Greater than zero			    The invoking string is greater than str.
     Zero 					        The two strings are equal.
     
    // A bubble sort for Strings. 
    class SortString {
        static String arr[] = { "Now", "is", "the", "time", "for", "all", "good", "men", "to", "come", "to", "the", "aid", "of", "their", "country" };
    	public static void main(String args[]) { 
    	    for(int j = 0; j < arr.length; j++) {
     		    for(int i = j + 1; i < arr.length; i++) {
     			    if(arr[i].compareTo(arr[j]) < 0) {
     				    String t = arr[j];
     				    arr[j] = arr[i];
     				    arr[i] = t;
     				}
     			}
     		    System.out.println(arr[j]);
     		}
     	}
     }
     

    12)indexOf( ):- Searches for the first occurrence of a character or substring.

    Syntax:- int indexOf(int ch) or int indexOf(String str) or int indexOf(int ch, int startIndex) or int indexOf(String str, int startIndex)

    13) lastIndexOf( ):- Searches for the last occurrence of a character or substring.

    Syntax:- int int lastIndexOf(int ch) or int lastIndexOf(String str) or int lastIndexOf(int ch, int startIndex) or int lastIndexOf(String str, int startIndex)

    // Demonstrate indexOf() and lastIndexOf(). 
    class indexOfDemo
    {
        public static void main(String args[])
        {
            String s = "Now is the time for all good men to come to the aid of their country."; 
            System.out.println(s);
            System.out.println("indexOf(t) = " + s.indexOf('t')); 
            System.out.println("lastIndexOf(t) = " + s.lastIndexOf('t'));
            System.out.println("indexOf(the) = " + s.indexOf("the")); 
            System.out.println("lastIndexOf(the) = " + s.lastIndexOf("the"));
            System.out.println("indexOf(t, 10) = " + s.indexOf('t', 10));
            System.out.println("lastIndexOf(t, 60) = " + s.lastIndexOf('t', 60)); 
            System.out.println("indexOf(the, 10) = " + s.indexOf("the", 10));
            System.out.println("lastIndexOf(the, 60) = " + s.lastIndexOf("the", 60));
        }	
    }
    OUTPUT :
    Now is the time for all good men to come to the aid of their country. 
    indexOf(t) = 7
    lastIndexOf(t) = 65
    indexOf(the) = 7
    lastIndexOf(the) = 55
    indexOf(t, 10) = 11 
    lastIndexOf(t, 60) = 55
    indexOf(the, 10) = 44
    lastIndexOf(the, 60) = 55
     

    14)substring( ):- You can extract a substring using substring( ). It has two forms: String substring(int startIndex) or String substring(int startIndex, int endIndex)

    15) concat( ):- You can concatenate two strings using concat( ). It has forms: String concat(String str)

    16) replace( ):- The replace( ) method has two forms. The first replaces all occurrences of one character in the invoking string with another character.

    Syntax: String replace(char original, char replacement)

    Example:- String s = "Hello".replace('l', 'w');

    The second form of replace( ) replaces one character sequence with another. It has this general form: String replace(CharSequence original, CharSequence replacement)

    17) trim( ):- The trim( ) method returns a copy of the invoking string from which any leading and trailing whitespace has been removed.

    Syntax:- String trim( )

    Example:- String s = " Hello World ".trim();

    18) String toLowerCase( ) or String toUpperCase( ):- To convert upper case and lower case letter string.

      // Demonstrate toUpperCase() and toLowerCase(). 
    class ChangeCase
    {
        public static void main(String args[])
        {
            String s = "This is a test.";
            System.out.println("Original: " + s);
            String upper = s.toUpperCase(); 
            String lower = s.toLowerCase();
            System.out.println("Uppercase: " + upper); 
            System.out.println("Lowercase: " + lower); 
        }
    }  
    

    StringBuffer

    StringBuffer represents growable and writeable character sequences. StringBuffer may have characters and substrings inserted in the middle or appended to the end.

    1)insert( ):- The insert( ) method inserts one string into another.

    Syntax:-
    StringBuffer insert(int index, String str) 
    StringBuffer insert(int index, char ch)
    StringBuffer insert(int index, Object obj)
    
    // Demonstrate insert().
    class insertDemo 
    {
        public static void main(String args[])
        {
            StringBuffer sb = new StringBuffer("I Java!");
            sb.insert(2, "like ");
            System.out.println(sb);
        }
    }
    The output of this example is shown here:
    I like Java! 
    

    2)reverse( ):- You can reverse the characters within a StringBuffer object using reverse( ), shown here:

    Syntax:- StringBuffer reverse( )

    // Using reverse() to reverse a StringBuffer.
    class ReverseDemo {
        public static void main(String args[]) {
            StringBuffer s = new StringBuffer("abcdef");
            System.out.println(s);
            s.reverse();
            System.out.println(s);
        }
    }
        
    

    3)delete( ) and deleteCharAt( ):- You can delete characters within a StringBuffer by using the methods delete( ) and deleteCharAt( ). These methods are shown here: StringBuffer delete(int startIndex, int endIndex) or StringBuffer deleteCharAt(int loc)

    // Demonstrate delete() and deleteCharAt()
    class deleteDemo {
        public static void main(String args[]) {
            StringBuffer sb = new StringBuffer("This is a test.");
            sb.delete(4, 7);
            System.out.println("After delete: " + sb);
            sb.deleteCharAt(0);
            System.out.println("After deleteCharAt: " + sb);
        }
    }
    

    4)replace( ):-You can replace one set of characters with another set inside a StringBuffer object by calling replace( ). Its signature is shown here: StringBuffer replace(int startIndex, int endIndex, String str)

    // Demonstrate replace()
    class replaceDemo {
        public static void main(String args[]) {
            StringBuffer sb = new StringBuffer("This is a test.");
            sb.replace(5, 7, "was");
            System.out.println("After replace: " + sb);
        }
    }
    
  • Java Chapter 13- Java.util: Collection
  • Collections Overview

    The Java Collections Framework standardizes the way in which groups of objects are handled by your programs. Java provided ad hoc classes such as Dictionary, Vector, Stack, and Properties to store and manipulate groups of objects.

    The ArrayList Class

    The ArrayList class extends AbstractList and implements the List interface. ArrayList is a generic class that has this declaration:class ArrayList<E> Here, E specifies the type of objects that the list will hold

    An ArrayList is a variable-length array of object references. That is, an ArrayList can dynamically increase or decrease in size. Array lists are created with an initial size. When this size is exceeded, the collection is automatically enlarged. When objects are removed, the array can be shrunk. ArrayList has the constructors shown here:

    ArrayList( ):- builds an empty array list.

    ArrayList(Collection<? extends E> c):- builds an array list that is initialized with the elements of the collection c.

    ArrayList(int capacity):- builds an array list that has the specified initial capacity. The capacity is the size of the underlying array that is used to store the elements. The capacity grows automatically as elements are added to an array list.

    
    // Demonstrate ArrayList.
    import java.util.*;
    class ArrayListDemo {
        public static void main(String args[]) {
            // Create an array list.
            ArrayList al = new ArrayList();
            System.out.println("Initial size of al: " +al.size());
            // Add elements to the array list.
            al.add("C");
            al.add("A");
            al.add("E");
            al.add("B");
            al.add("D");
            al.add("F");
            al.add(1, "A2");
            System.out.println("Size of al after additions: " +al.size());
            // Display the array list.
            System.out.println("Contents of al: " + al);
            // Remove elements from the array list.
            al.remove("F");
            al.remove(2);
            System.out.println("Size of al after deletions: " +al.size());
            System.out.println("Contents of al: " + al);
        }
    }
        The output from this program is shown here:
        Initial size of al: 0
        Size of al after additions: 7
        Contents of al: [C, A2, A, E, B, D, F]
        Size of al after deletions: 5
        Contents of al: [C, A2, E, B, D]
    
    
    
    // Convert an ArrayList into an array.
    import java.util.*;
    class ArrayListToArray {
        public static void main(String args[]) {
            // Create an array list.
            ArrayList al = new ArrayList();
            // Add elements to the array list.
            al.add(1);
            al.add(2);
            al.add(3);
            al.add(4);
            System.out.println("Contents of al: " + al);
            // Get the array.
            Integer ia[] = new Integer[al.size()];
            ia = al.toArray(ia);
            int sum = 0;
            // Sum the array.
            for(int i : ia) sum += i;
                System.out.println("Sum is: " + sum);
        }
    }
    The output from the program is shown here:
    Contents of al: [1, 2, 3, 4]
    Sum is: 10
    
        
    

    The LinkedList Class

    The LinkedList class extends AbstractSequentialList and implements the List, Deque, and Queue interfaces. It provides a linked-list data structure. LinkedList is a generic class that has this declaration: class LinkedList<E> Here, E specifies the type of objects that the list will hold.

    LinkedList has the two constructors shown here:

    LinkedList( ) :- builds an empty linked list.

    LinkedList(Collection c):- linked list that is initialized with the elements of the collection c.

    
    // Demonstrate LinkedList.
    import java.util.*;
    class LinkedListDemo {
        public static void main(String args[]) {
            // Create a linked list.
            LinkedList ll = new LinkedList();
            // Add elements to the linked list.
            ll.add("F");
            ll.add("B");
            ll.add("D");
            ll.add("E");
            ll.add("C");
            ll.addLast("Z");
            ll.addFirst("A");
            ll.add(1, "A2");
            System.out.println("Original contents of ll: " + ll);
            // Remove elements from the linked list.
            ll.remove("F");
            ll.remove(2);
            System.out.println("Contents of ll after deletion: "+ ll);
            // Remove first and last elements.
            ll.removeFirst();
            ll.removeLast();
            System.out.println("ll after deleting first and last: "+ ll);
            // Get and set a value.
            String val = ll.get(2);
            ll.set(2, val + " Changed");
            System.out.println("ll after change: " + ll);
        }
    }
    The output from this program is shown here:
    Original contents of ll: [A, A2, F, B, D, E, C, Z]
    Contents of ll after deletion: [A, A2, D, E, C, Z]
    ll after deleting first and last: [A2, D, E, C]
    ll after change: [A2, D, E Changed, C]
    
    

    The HashSet Class

    HashSet extends AbstractSet and implements the Set interface. It creates a collection that uses a hash table for storage. HashSet is a generic class that has this declaration: class HashSet<E> Here, E specifies the type of objects that the set will hold.

    As most readers likely know, a hash table stores information by using a mechanism called hashing. In hashing, the informational content of a key is used to determine a unique value, called its hash code. The hash code is then used as the index at which the data associated with the key is stored. The transformation of the key into its hash code is performed automatically— you never see the hash code itself. Also, your code can’t directly index the hash table. The advantage of hashing is that it allows the execution time of add( ), contains( ), remove( ), and size( ) to remain constant even for large sets. The following constructors are defined:

    HashSet( )
    HashSet(Collection<? extends E> c) 
    HashSet(int capacity) 
    HashSet(int capacity, float fillRatio)
    
    // Demonstrate HashSet.
    import java.util.*;
    class HashSetDemo {
        public static void main(String args[]) {
            HashSet hs = new HashSet();
            hs.add("B");	hs.add("A");
            hs.add("D");	hs.add("E");
            hs.add("C");	hs.add("F");
            System.out.println(hs);
        }
    }
    The following is the output from this program:
    [D, A, F, C, B, E]
    

    The TreeSet Class

    TreeSet extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a tree for storage. Objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. TreeSet is a generic class that has this declaration: class TreeSet<E> Here, E specifies the type of objects that the set will hold.

     
    TreeSet has the following constructors:
     TreeSet( )
     TreeSet(Collection c) 
     TreeSet(Comparator comp) 
     TreeSet(SortedSet ss)
    
    // Demonstrate TreeSet.
    import java.util.*;
    class TreeSetDemo {
        public static void main(String args[]) {
            // Create a tree set.
            TreeSet ts = new TreeSet();
            ts.add("C");
            ts.add("A");
            ts.add("B");
            ts.add("E");
            ts.add("F");
            ts.add("D");
            System.out.println(ts);
        }
    }
    The output from this program is shown here:
    [A, B, C, D, E, F]
    

    The ArrayDeque Class

    The ArrayDeque class, which extends AbstractCollection and implements the Deque interface. It adds no methods of its own. ArrayDeque creates a dynamic array and has no capacity restrictions.

        class ArrayDeque<E>   Here, E specifies the type of objects stored in the collection. 
    ArrayDeque defines the following constructors: 
    ArrayDeque( ) 
    ArrayDeque(int size)
     ArrayDeque(Collection c)
    
    
    // Demonstrate ArrayDeque.
    import java.util.*;
    class ArrayDequeDemo {
        public static void main(String args[]) {
            ArrayDeque adq = new ArrayDeque();
            adq.push("A");
            adq.push("B");
            adq.push("D");
            adq.push("E");
            adq.push("F");
            System.out.print("Popping the stack: ");
            while(adq.peek() != null)
                System.out.print(adq.pop() + " ");
            System.out.println();
        }
    }
    The output is shown here:
    Popping the stack: F E D B A
    

    Accessing a Collection via an Iterator

    To cycle through the elements in a collection. For example, you might want to display each element. One way to do this is to employ an iterator, which is an object that implements either the Iterator or the ListIterator interface. Iterator enables you to cycle through a collection, obtaining or removing elements. ListIterator extends Iterator to allowbidirectional traversal of a list, and the modification of elements. Iterator and ListIterator are generic interfaces which are declared as shown here: interface ListIterator <E> Here, E specifies the type of objects being iterated

    
    // Demonstrate iterators.
    import java.util.*;
    class IteratorDemo {
        public static void main(String args[]) {
            // Create an array list.
            ArrayList al = new ArrayList();
            // Add elements to the array list.
            al.add("C");
            al.add("A");
            al.add("E");
            al.add("B");
            al.add("D");
            al.add("F");
            // Use iterator to display contents of al.
            System.out.print("Original contents of al: ");
            Iterator itr = al.iterator();
            while(itr.hasNext())
            {
                String element = itr.next();
                System.out.print(element + " ");
            }
            System.out.println();
            // Modify objects being iterated.
            ListIterator litr = al.listIterator();
            while(litr.hasNext()) {
            String element = litr.next();
            litr.set(element + "+");		}
            System.out.print("Modified contents of al: ");
            itr = al.iterator();
            while(itr.hasNext())
            {
                String element = itr.next();
                System.out.print(element + " ");	
            }
                System.out.println();
                // Now, display the list backwards.
                System.out.print("Modified list backwards: ");
            while(litr.hasPrevious())
            {
                String element = litr.previous();
                System.out.print(element + " ");
            }
            System.out.println();
        }
    }
    The output is shown here:
    Original contents of al: C A E B D F
    Modified contents of al: C+ A+ E+ B+ D+ F+
    Modified list backwards: F+ D+ B+ E+ A+ C+
    
    
    
    // Use the for-each for loop to cycle through a collection.
    import java.util.*;
    class ForEachDemo {
        public static void main(String args[])
        {
            ArrayList vals = new ArrayList();
            vals.add(1);
            vals.add(2);
            vals.add(3);
            vals.add(4);
            vals.add(5);
            // Use for loop to display the values.
            System.out.print("Original contents of vals: ");
            for(int v : vals)
                System.out.print(v + " ");
            System.out.println();
            // Now, sum the values by using a for loop.
            int sum = 0;
            for(int v : vals)
                sum += v;
            System.out.println("Sum of values: " + sum);
        }
    }
    The output from the program is shown here:
    Original contents of vals: 1 2 3 4 5
    Sum of values: 15
    
    Storing User-Defined Classes in Collections
    // A simple mailing list example.
    import java.util.*;
    class Address {
        private String name;
        private String street;
        private String city;
        private String state;
        private String code;
        Address(String n, String s, String c, String st, String cd)
        {
            name = n;	street = s;	city = c;	state = st;	code = cd;	
        }
        public String toString()
        {
            return name + "\n" + street + "\n" + city + " " + state + " " + code;	}
        }
    class MailList {
        public static void main(String args[]) 
        {
            LinkedList
    ml = new LinkedList
    (); // Add elements to the linked list. ml.add(new Address("J.W. West", "11 Oak Ave", "Urbana", "IL", "61801")); ml.add(new Address("Ralph Baker", "1142 Maple Lane", "Mahomet", "IL", "61853")); ml.add(new Address("Tom Carlton", "867 Elm St", "Champaign", "IL", "61820")); // Display the mailing list. for(Address element : ml) System.out.println(element + "\n"); System.out.println(); } } The output from the program is shown here: J.W. West 11 Oak Ave Urbana IL 61801 Ralph Baker 1142 Maple Lane Mahomet IL 61853 Tom Carlton 867 Elm St Champaign IL 61820

    Working with Maps

    A map is an object that stores associations between keys and values, or key/value pairs. Given a key, you can find its value. Both keys and values are objects. The keys must be unique, but the values may be duplicated. don’t implement the Iterable interface. This means that you cannot cycle through a map using a for-each style for loop.

    Map Interface 	Description
    Map				    Maps unique keys to values. 
    Map.Entry		 	Describes an element (a key/value pair) in a map. This is an inner class of Map. 
    NavigableMap 		Extends SortedMap to handle the retrieval of entries based on closest-match searches. 					(Added by Java SE 6.) 
    SortedMap 			Extends Map so that the keys are maintained in ascending order.
    

    The HashMap Class

    The HashMap class extends AbstractMap and implements the Map interface. It uses a hash table to store the map. This allows the execution time of get( ) and put( ) to remain constant even for large sets. HashMap is a generic class that has this declaration: class HashMap<K, V> Here, K specifies the type of keys, and V specifies the type of values.

        The following constructors are defined: 
    HashMap( )
    HashMap(Map m)
    HashMap(int capacity)
    HashMap(int capacity, float fillRatio)
    
    
    //MAP EXAMPLE
    import java.util.*;
    class HashMapDemo {
        public static void main(String args[]) {
            // Create a hash map.
            HashMap hm = new HashMap();
            // Put elements to the map
            hm.put("John Doe", new Double(3434.34));
            hm.put("Tom Smith", new Double(123.22));
            hm.put("Jane Baker", new Double(1378.00));
            hm.put("Tod Hall", new Double(99.22));
            hm.put("Ralph Smith", new Double(-19.08));
            // Get a set of the entries.
            Set<Map.Entry<String, Double>> set = hm.entrySet();
            // Display the set.
            for(Map.Entry me : set)
            {
                System.out.print(me.getKey() + ": ");
                System.out.println(me.getValue());
            }
            System.out.println();
            // Deposit 1000 into John Doe's account.
            double balance = hm.get("John Doe");
            hm.put("John Doe", balance + 1000);
            System.out.println("John Doe's new balance: " +
            hm.get("John Doe"));
        }
    }
    Output from this program is shown here (the precise order may vary):
    Ralph Smith: -19.08
    Tom Smith: 123.22
    John Doe: 3434.34
    Tod Hall: 99.22
    Jane Baker: 1378.0
    John Doe’s new balance: 4434.34
    
    

    Vector

    Vector implements a dynamic array. It is similar to ArrayList, but with two differences: Vector is synchronized, and it contains many legacy methods that are not part of the other Collections class class Vector<E>

    Here are the Vector constructors: 
    Vector( )
    Vector(int size)
    Vector(int size, int incr)
    Vector(Collection <?extends>c)
    
    
    // Demonstrate various Vector operations.
    import java.util.*;
    class VectorDemo {
        public static void main(String args[]) {
            // initial size is 3, increment is 2 
            Vector v = new Vector(3, 2);
            System.out.println("Initial size: " + v.size());
            System.out.println("Initial capacity: " +v.capacity());
            v.addElement(1);
            v.addElement(2);
            v.addElement(3);
            v.addElement(4);
            System.out.println("Capacity after four additions: " +v.capacity());
            v.addElement(5);
            System.out.println("Current capacity: " +v.capacity());
            v.addElement(6);
            v.addElement(7);
            System.out.println("Current capacity: " +v.capacity());
            v.addElement(9);
            v.addElement(10);
            System.out.println("Current capacity: " +v.capacity());
            v.addElement(11);
            v.addElement(12);
            System.out.println("First element: " + v.firstElement());
            System.out.println("Last element: " + v.lastElement());
            if(v.contains(3))
                System.out.println("Vector contains 3.");
            // Enumerate the elements in the vector.
            Enumeration vEnum = v.elements();
            System.out.println("\nElements in vector:");
            while(vEnum.hasMoreElements())
                System.out.print(vEnum.nextElement() + " ");
        }
    }
    The output from this program is shown here:
    Initial size: 0
    Initial capacity: 3
    Capacity after four additions: 5
    Current capacity: 5
    Current capacity: 7
    Current capacity: 9
    First element: 1
    Last element: 12
    Vector contains 3.
    Elements in vector:
    1 2 3 4 5 6 7 9 10 11 12
    
    // Use an iterator to display contents.
    Iterator vItr = v.iterator();
    System.out.println("\nElements in vector:");
    while(vItr.hasNext())
    System.out.print(vItr.next() + " ");
    System.out.println();
    You can also use a for-each for loop to cycle through a Vector, the following code shows:
    // Use an enhanced for loop to display contents.
    System.out.println("\nElements in vector:");
    for(int i : v)
    System.out.print(i + " ");
    System.out.println();
    
    

    Stack

    Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. With the release of JDK 5, Stack was retrofitted for generics and is declared as shown here:class Stack<E>

    // Demonstrate the Stack class.
    import java.util.*;
    class StackDemo {
        static void showpush(Stack st, int a) {
            st.push(a);
            System.out.println("push(" + a + ")");
            System.out.println("stack: " + st);
        }
        static void showpop(Stack st) {
            System.out.print("pop -> ");
            Integer a = st.pop();
            System.out.println(a);
            System.out.println("stack: " + st);
        }
        public static void main(String args[]) {
            Stack st = new Stack();
            System.out.println("stack: " + st);
            showpush(st, 42);
            showpush(st, 66);
            showpush(st, 99);
            showpop(st);
            showpop(st);
            showpop(st);
            try {
                showpop(st);
            }
            catch (EmptyStackException e) {
                System.out.println("empty stack");
            }
        }
    }
        
    

    Hashtable

    Like HashMap, Hashtable stores key/value pairs in a hash table. However, neither keys nor values can be null. When using a Hashtable, you specify an object that is used as a key, and the value that you want linked to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table.class Hashtable Here, K specifies the type of keys, and V specifies the type of values.

        The Hashtable constructors are shown here:
    Hashtable( )
    Hashtable(int size) 
    Hashtable(int size, float fillRatio)
    
    
    // Demonstrate a Hashtable.
    import java.util.*;
    class HTDemo {	
        public static void main(String args[]) {
            Hashtable balance = new Hashtable();
            Enumeration names;		
            String str;
            double bal;
            balance.put("John Doe", 3434.34);
            balance.put("Tom Smith", 123.22);
            balance.put("Jane Baker", 1378.00);
            balance.put("Tod Hall", 99.22);
            balance.put("Ralph Smith", -19.08);	
            names = balance.keys();
            while(names.hasMoreElements()) {	
                str = names.nextElement();
                System.out.println(str + ": " +balance.get(str));
            }
            bal = balance.get("John Doe");
            balance.put("John Doe", bal+1000);
            System.out.println("John Doe's new balance: " +balance.get("John Doe"));
        }
    }
    The output from this program is shown here:
    Todd Hall: 99.22
    Ralph Smith: -19.08
    John Doe: 3434.34
    Jane Baker: 1378.0
    Tom Smith: 123.22
    John Doe’s new balance: 4434.34
    
    
    
    // Use iterators with a Hashtable.
    import java.util.*;
    class HTDemo2 {
        public static void main(String args[]) {
            Hashtable balance =
            new Hashtable();
            String str;
            double bal;
            balance.put("John Doe", 3434.34);
            balance.put("Tom Smith", 123.22);
            balance.put("Jane Baker", 1378.00);
            balance.put("Tod Hall", 99.22);
            balance.put("Ralph Smith", -19.08);
            // Show all balances in hashtable.
            // First, get a set view of the keys.
            Set set = balance.keySet();
            // Get an iterator.
            Iterator itr = set.iterator();
            while(itr.hasNext()) {
                str = itr.next();
                System.out.println(str + ": " +	balance.get(str));
            }
            System.out.println();
            // Deposit 1,000 into John Doe's account.
            bal = balance.get("John Doe");
            balance.put("John Doe", bal+1000);
            System.out.println("John Doe's new balance: " +balance.get("John Doe"));
        }
    }
    

    Properties

    Properties is a subclass of Hashtable. It is used to maintain lists of values in which the key is a String and the value is also a String. The Properties class is used by many other Java classes. For example, it is the type of object returned by System.getProperties( ) when obtaining environmental values. Although the Properties class, itself, is not generic, several of its methods are. Properties defines the following instance variable: Properties defaults;

    This variable holds a default property list associated with a Properties object. Properties defines these constructors: Properties( ) Properties(Properties propDefault)

    // Demonstrate a Property list.
    import java.util.*;
    class PropDemo {
        public static void main(String args[]) {
            Properties capitals = new Properties();
            capitals.put("Illinois", "Springfield");
            capitals.put("Missouri", "Jefferson City");
            capitals.put("Washington", "Olympia");
            capitals.put("California", "Sacramento");
            capitals.put("Indiana", "Indianapolis");
            // Get a set-view of the keys.
            Set states = capitals.keySet();
            // Show all of the states and capitals.
            for(Object name : states)
                System.out.println("The capital of " +name + " is " +capitals.getProperty((String)name)+ ".");
            System.out.println();	
        }
    }
    The output from this program is shown here:
    The capital of Missouri is Jefferson City.
    The capital of Illinois is Springfield.
    The capital of Indiana is Indianapolis.
    The capital of California is Sacramento.
    The capital of Washington is Olympia.
    

    Using store( ) and load( )

    One of the most useful aspects of Properties is that the information contained in a Properties object can be easily stored to or loaded from disk with the store( ) and load( ) methods. At any time, you can write a Properties object to a stream or read it back. This makes property lists especially convenient for implementing simple databases.

    /* A simple telephone number database that uses a property list. */
    import java.io.*;
    import java.util.*;
    class Phonebook {
        public static void main(String args[]) throws IOException
        {
            Properties ht = new Properties();
            BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
            String name, number;
            FileInputStream fin = null;
            boolean changed = false;
            // Try to open phonebook.dat file.
            try {
                fin = new FileInputStream("phonebook.dat");
            }
            catch(FileNotFoundException e) {
                // ignore missing file
            }
            /* If phonebook file already exists, load existing telephone numbers. */
            try {
                if(fin != null) {
                    ht.load(fin);
                    fin.close();
                }
            }
            catch(IOException e) {
                System.out.println("Error reading file.");
            }
            // Let user enter new names and numbers.
            do {
                System.out.println("Enter new name" +" ('quit' to stop): ");
                name = br.readLine();
                if(name.equals("quit")) 
                    continue;
                System.out.println("Enter number: ");
                number = br.readLine();
                ht.put(name, number);
                changed = true;
               } 
            while(!name.equals("quit"));
            // If phone book data has changed, save it.
                if(changed)
                {
                    FileOutputStream fout = new FileOutputStream("phonebook.dat");
                    ht.store(fout, "Telephone Book");
                    fout.close();
                }
            do {
                    System.out.println("Enter name to find" +" ('quit' to quit): ");
                    name = br.readLine();
                    if(name.equals("quit"))
                        continue;
                    number = (String) ht.get(name);
                    System.out.println(number);
            } while(!name.equals("quit"));
        }
    }
        
    
  • Java Chapter 14- Java.util: StringTokenizer Date & Random
  • StringTokenizer Date & Random

    This chapter continues our discussion of java.util by examining those classes and interfaces that are not part of the Collections Framework.

    StringTokenizer

    The processing of text often consists of parsing a formatted input string. Parsing is the division of text into a set of discrete parts, or tokens, which in a certain sequence can convey a semantic meaning. To use StringTokenizer, you specify an input string and a string that contains delimiters. Delimiters are characters that separate tokens. Each character in the delimiters string is considered a valid delimiter—for example, “,;:” sets the delimiters to a comma, semicolon, and colon. The default set of delimiters consists of the whitespace characters: space, tab, newline, and carriage return.

    The StringTokenizer constructors are shown here: 
    StringTokenizer(String str)
    StringTokenizer(String str, String delimiters)
    StringTokenizer(String str, String delimiters, boolean delimAsToken)
    
    // Demonstrate StringTokenizer.
    import java.util.StringTokenizer;
    class STDemo {
        static String in = "title=Java: The Complete Reference;" +"author=Schildt;" +"publisher=Osborne/McGraw-Hill;" +"copyright=2007";
        public static void main(String args[]) {
            StringTokenizer st = new StringTokenizer(in, "=;");
            while(st.hasMoreTokens())
            {
                String key = st.nextToken();
                String val = st.nextToken();
                System.out.println(key + "\t" + val);
            }
        }
    }
    The output from this program is shown here:
    title Java: The Complete Reference
    author Schildt
    publisher Osborne/McGraw-Hill
    copyright 2007
    

    Date

    The Date class encapsulates the current date and time.

    Date supports the following constructors:

    Date( ):- initializes the object with the current date and time

    Date(long millisec):- accepts one argument that equals the number of milliseconds that have elapsed since midnight, January 1, 1970.

    // Show date and time using only Date methods.
    import java.util.Date;
    class DateDemo {
        public static void main(String args[])
        {
            Date date = new Date();// Instantiate a Date object
            System.out.println(date); // display time and date using toString()
            long msec = date.getTime();// Display number of milliseconds since midnight, January 1, 1970 GMT
            System.out.println("Milliseconds since Jan. 1, 1970 GMT = " + msec);
        }
    }
    Sample output is shown here:
     Mon Jan 01 16:28:16 CST 2007 
    Milliseconds since Jan. 1, 1970 GMT = 1167690496023
    

    Calendar

    The abstract Calendar class provides a set of methods that allows you to convert a time in milliseconds to a number of useful components. Some examples of the type of information that can be provided are year, month, day, hour, minute, and second.

    // Demonstrate Calendar
    import java.util.Calendar;
    class CalendarDemo {
        public static void main(String args[])
        {
            String months[] = {"Jan", "Feb", "Mar", "Apr","May", "Jun", "Jul", "Aug","Sep", "Oct", "Nov", "Dec"};
            Calendar calendar = Calendar.getInstance();//  a calendar with current date and time in default locale and timezone.
            // Display current time and date information.
            System.out.print("Date: ");
            System.out.print(months[calendar.get(Calendar.MONTH)]);
            System.out.print(" " + calendar.get(Calendar.DATE) + " ");
            System.out.println(calendar.get(Calendar.YEAR));
            System.out.print("Time: "+calendar.get(Calendar.HOUR) + ":");
            System.out.print(calendar.get(Calendar.MINUTE) + ":");
            System.out.println(calendar.get(Calendar.SECOND));
            // Set the time and date information and display it.
            calendar.set(Calendar.HOUR, 10);
            calendar.set(Calendar.MINUTE, 29);
            calendar.set(Calendar.SECOND, 22);
            System.out.print("Updated time: "+calendar.get(Calendar.HOUR) + ":");
            System.out.print(calendar.get(Calendar.MINUTE) + ":");
            System.out.println(calendar.get(Calendar.SECOND));
        }
    }
    Sample output is shown here:
    Date: Jan 1 2007
    Time: 11:24:25
    Updated time: 10:29:22 
    
    

    Random

    The Random class is a generator of pseudorandom numbers. These are called pseudorandom numbers because they are simply uniformly distributed sequences.

    Random defines the following constructors:

    Random( ):- creates a random number generator that uses the current time as the starting.

    Random(long seed):-creates a random number generator that uses the seed value.

        Method 						Description
    boolean nextBoolean( ) 		    Returns the next boolean random number.
    void 	nextBytes(byte vals[ ])     Fills vals with randomly generated values.
    double 	nextDouble( ) 		    Returns the next double random number.
    float 	nextFloat( ) 		    Returns the next float random number.
    double 	nextGaussian( )	 	    returns a double value centered at 0.0 with a standard deviation of 1.0. (bell curve)
    int nextInt( ) 			    Returns the next int random number.
    int nextInt(int n) 		    Returns the next int random number within the range zero to n.
    long nextLong( ) 		    Returns the next long random number.
    void setSeed(long newSeed) 	    Sets the seed value  to that specified by newSeed
    
    
    // Demonstrate random Gaussian values.
    import java.util.Random;
    class RandDemo {
        public static void main(String args[])
        {
            Random r = new Random();
            double val;
            double sum = 0;
            for(int i=0; i<100; i++)
            {
                val = r.nextGaussian();
                sum += val;	
            }
            System.out.println("Average of values: " +(sum/100));
        }
    }
    
  • Java Chapter 15- Applet
  • The Applet Class

    Applets are small applications that are accessed on an Internet server, transported over the Internet, automatically installed, and run as part of a web document. After an applet arrives on the client, it has limited access to resources so that it can produce a graphical user interface and run complex computations without introducing the risk of viruses or breaching data integrity.

    All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand-alone programs. Instead, they run within either a web browser or an applet viewer. Execution of an applet does not begin at main( ).

    /∗ <applet code="MyApplet" width="200 " height="60"></applet>∗/ This comment contains an APPLET tag that will run an applet called MyApplet in a window that is 200 pixels wide and 60 pixels high. Because the inclusion of an APPLET command makes testing applets easier.

    An Applet Skeleton

    All but the most trivial applets override a set of methods that provides the basic mechanism by which the browser or applet viewer interfaces to the applet and controls its execution. Four of these methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet. AWT-based applets will also override the paint( ) method, which is defined by the AWT Component class. This method is called when the applet’s output must be redisplayed.

    // An Applet skeleton.
    import java.awt.*;
    import java.applet.*;
    /∗ <applet code="MyApplet" width="200 " height="60"></applet>∗/
    public class AppletSkel extends Applet {
        // Called first.
        public void init() {
            // initialization
        }
        /* Called second, after init(). Also called whenever the applet is restarted. */
        public void start() {
            // start or resume execution
        }
        // Called when the applet is stopped.
        public void stop() {
            // suspends execution
        }
        /* Called when applet is terminated. This is the last method executed. */
        public void destroy() {
            // perform shutdown activities
        }
        // Called when an applet's window must be restored.
        public void paint(Graphics g) {
            // redisplay contents of window
        }
    }
        
    
        //EXAMPLE PROGRAM OF APPLET
    import java.awt.*;
    import java.applet.*;
    /*<applet code="SimpleApplet" width=200 height=60> 	</applet>*/
    public class SimpleApplet extends Applet {
        public void paint(Graphics g) {
            g.drawString("A Simple Applet", 20, 20);
        }
    }
    

    After you enter the source code for SimpleApplet, compile in the same way that you have been compiling programs. However, running SimpleApplet involves a different process. In fact, there are two ways in which you can run an applet:

    A)Executing the applet within a Java-compatible web browser

    B) Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes your applet in a window. This is generally the fastest and easiest way to test your applet.

    To execute an applet in a web browser, you need to write a short HTML text file that contains a tag that loads the applet. Here is the HTML file that executes SimpleApplet:

    /*<applet code="SimpleApplet" width=200 height=60> </applet>*/
    With this approach, you can quickly iterate through applet development by using these three steps:

    1. Edit a Java source file.

    2. Compile your program.

    3. Execute the applet viewer, specifying the name of your applet’s source file. The applet viewer will encounter the APPLET tag within the comment and execute your applet.

    Applet Initialization and Termination

    It is important to understand the order in which the various methods shown in the skeleton are called. When an applet begins, the following methods are called, in this sequence:

    1. init( ):- This is where you should initialize variables. This method is called only once during the run time of your applet.

    2. start( ):- The start( ) method is called after init( ). It is also called to restart an applet after it has been stopped. start( ) is called each time an applet’s HTML document is displayed onscreen. So, if a user leaves a web page and comes back, the applet resumes execution at start( ).

    3. paint( ):- The paint( ) method is called each time your applet’s output must be redrawn. The paint( ) method has one parameter of type Graphics. This parameter will contain the graphics context, which describes the graphics environment in which the applet is running.

    When an applet is terminated, the following sequence of method calls takes place:

    1. stop( ):- The stop( ) method is called when a web browser leaves the HTML document containing the applet—when it goes to another page

    2. destroy( ):- The destroy( ) method is called when the environment determines that your applet needs to be removed completely from memory.

        /* A simple applet that sets the foreground and background colors and outputs a string. */
    import java.awt.*;
    import java.applet.*;
    /*<applet code="SimpleApplet" width=200 height=60> 	</applet>*/
    public class Sample extends Applet{
        String msg;
        // set the foreground and background colors.
        public void init() {
            setBackground(Color.cyan);
            setForeground(Color.red);
            msg = "Inside init( ) --";
        }
        // Initialize the string to be displayed.
        public void start() {
            msg += " Inside start( ) --";
        }
        // Display msg in applet window.
        public void paint(Graphics g) {
            msg += " Inside paint( ).";
            g.drawString(msg, 10, 30);
        }
    }
    
    
    // Using the Status Window.
    import java.awt.*;
    import java.applet.*;
    /*<applet code="SimpleApplet" width=200 height=60> 	</applet>*/
    public class StatusWindow extends Applet{
        public void init() {
            setBackground(Color.cyan);
        }
        // Display msg in applet window.
        public void paint(Graphics g) {
            g.drawString("This is in the applet window.", 10, 20);
            showStatus("This is shown in the status window.");
        }
    }
    
    
  • Java Chapter 16- Introducing the AWT: Working with Windows, Graphics, and Text
  • Introducing the AWT: Working with Windows, Graphics, and Text

    The AWT classes are contained in the java.awt package. It is one of Java’s largest packages.

    Window Fundamentals

    The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level. The two most common windows are those derived from Panel, which is used by applets, and those derived from Frame, which creates a standard application window.

    Component

    At the top of the AWT hierarchy is the Component class. Component is an abstract class that encapsulates all of the attributes of a visual component. All user interface elements that are displayed on the screen and that interact with the user are subclasses of Component. It defines over a hundred public methods that are responsible for managing events, such as mouse and keyboard input, positioning and sizing the window, and repainting. A Component object is responsible for remembering the current foreground and background colors and the currently selected text font.

    Container

    The Container class is a subclass of Component. It has additional methods that allow other Component objects to be nested within it. Other Container objects can be stored inside of a Container (since they are themselves instances of Component). This makes for a multileveled containment system. A container is responsible for laying out (that is, positioning) any components that it contains. It does this through the use of various layout managers.

    Panel

    The Panel class is a concrete subclass of Container. It doesn’t add any new methods; it simply implements Container. A Panel may be thought of as a recursively nestable, concrete screen component. Panel is the superclass for Applet. a Panel is a window that does not contain a title bar, menu bar, or border. Other components can be added to a Panel object by its add( ) method (inherited from Container). Once these components have been added, you can position and resize them manually using the setLocation( ), setSize( ), setPreferredSize( ), or setBounds( ) methods defined by Component.

    Window

    The Window class creates a top-level window. A top-level window is not contained within any other object; it sits directly on the desktop. Generally, you won’t create Window objects directly. Instead, you will use a subclass of Window called Frame, described next.

    Frame

    Frame encapsulates what is commonly thought of as a “window.” It is a subclass of Window and has a title bar, menu bar, borders, and resizing corners. When a Frame window is created by a stand-alone application rather than an applet, a normal window is created.

    Canvas

    Although it is not part of the hierarchy for applet or frame windows, there is one other type of window that you will find valuable: Canvas. Canvas encapsulates a blank window upon which you can draw. You will see an example of Canvas later.

    Working with Frame Windows

    it will create top-level or child windows for stand-alone applications.

    Here are two of Frame’s constructors:
    Frame( )
    Frame(String title)
     
    Setting the Window’s Dimensions

    The setSize( ) method is used to set the dimensions of the window. Its signature is shown here:

    void setSize(int newWidth, int newHeight)

    void setSize(Dimension newSize)

    Hiding and Showing a Window

    After a frame window has been created, it will not be visible until you call setVisible( ). Its signature is shown here: void setVisible(boolean visibleFlag)

    //using extends Frame
    import java.awt.*;  
    class win extends Frame{  
        win()
        {  
            setSize(300,300);//frame size 300 width and 300 height  
            setVisible(true);//now frame will be visible, by default not visible
        }  
        public static void main(String args[]){  
            win f=new win();  
        }
    }  
        
    //using Frame Object
    import java.awt.*;  
    class win2 {  
        win2(){  
    	    Frame f=new frame();
    	    f.setSize(300,300);//frame size 300 width and 300 height  
    	    f.setVisible(true);//now frame will be visible, by default not visible  
    	   }  
    	public static void main(String args[]){  
    	    win2 f=new win2();  
        }
    }  
    
    
    

    Control Fundamentals

    The AWT supports the following types of controls:

    • Labels • Push buttons • Check boxes • Choice lists • Lists • Scroll bars • Text editing

    These controls are subclasses of Component.

    Adding and Removing Controls

    To include a control in a window, you must add it to the window. To do this, you must first create an instance of the desired control and then add it to a window by calling add( ), which is defined by Container.

    Component add(Component compObj)

    Sometimes you will want to remove a control from a window when the control is no longer needed. To do this, call remove( ). This method is also defined by Container.

    void remove(Component obj)

    removeAll( )

    Labels

    The easiest control to use is a label. A label is an object of type Label, and it contains a string, which it displays. Labels are passive controls that do not support any interaction with the user.

    Constructor

    Label( ) throws HeadlessException :- creates a blank label

    Label(String str) throws HeadlessException :- creates a label that contains the string specified by str. This string is left-justified.

    Label(String str, int how) throws HeadlessException:- creates a label that contains the string specified by str using the alignment specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or Label.CENTER.

    Method

    void setText(String str) :- set or change the text in a label by using the setText( ) method.

    String getText( ):- obtain the current label by calling getText( ).

    void setAlignment(int how):- set the alignment of the string within the label by calling setAlignment( ).

    int getAlignment( ):- To obtain the current alignment

     //use Label as default Layout
    import java.awt.*;  
    class showlebel extends Frame{  
        showlebel (){  
            Label one = new Label("One"); 
            Label two = new Label("Two"); 
            Label three = new Label("Three"); 
            // add labels to window 
            add(one); 
            add(two); 
            add(three); 
            setSize(600,600);//frame size 300 width and 300 height  
            setVisible(true);//now frame will be visible, by default not visible  
        }  
        public static void main(String args[]){  
            showlebel f=new showlebel ();  
        }
    }  
    
    
    //use Label as null Layout
    import java.awt.*;  
    class showlebel extends Frame{  
        showlebel (){  
            Label one = new Label("One"); 
            Label two = new Label("Two"); 
            Label three = new Label("Three"); 
            one.setBounds(30,100,80,30);
            two.setBounds(130,100,80,30);
            three.setBounds(270,100,80,30);
            add(one); 
            add(two); 
            add(three); 
            setSize(600,600);//frame size 300 width and 300 height 
            setLayout(null); //set layout null
            setVisible(true);//now frame will be visible, by default not visible  
        }  
        public static void main(String args[]){  
            showlebel f=new showlebel ();  
        }
    }     
     

    Using Buttons

    A push button is a component that contains a label and that generates an event when it is pressed. Push buttons are objects of type Button

    constructors

    Button( ) throws HeadlessException

    Button(String str) throws HeadlessException

    Method

    void setLabel(String str):- set its label by calling setLabel( )

    String getLabel( ):- retrieve its label by calling getLabel( )

    import java.awt.*;  
    class First extends Frame{  
        First(){  
            Button b=new Button("click me");  
            b.setBounds(30,100,80,30);// setting button position  
        	add(b);//adding button into frame  
        	setSize(300,300);//frame size 300 width and 300 height  
        	setLayout(null);//no layout manager  
        	setVisible(true);//now frame will be visible, by default not visible  
        }  
    	public static void main(String args[]){  
        	First f=new First();  
    	}
    }  
    

    Applying Check Boxes

    A check box is a control that is used to turn an option on or off. It consists of a small box that can either contain a check mark or not. There is a label associated with each check box that describes what option the box represents. You change the state of a check box by clicking on it. Check boxes can be used individually or as part of a group.

    Checkbox supports these constructors:
     Checkbox( ) throws HeadlessException
     Checkbox(String str) throws HeadlessException
     Checkbox(String str, boolean on) throws HeadlessException
     Checkbox(String str, boolean on, CheckboxGroup cbGroup) throws HeadlessException
     Checkbox(String str, CheckboxGroup cbGroup, boolean on) throws HeadlessException
     
    Method
    boolean getState( )
    void setState(boolean on)
    String getLabel( )
    void setLabel(String str)    
    

    CheckboxGroup

    It is possible to create a set of mutually exclusive check boxes in which one and only one check box in the group can be checked at any one time. These check boxes are often called radio buttons.

    Constructor

    CheckboxGroup();

    Methods

    Checkbox getSelectedCheckbox( ):- You can determine which check box in a group is currently selected by calling getSelectedCheckbox( ).

    void setSelectedCheckbox(Checkbox which):-You can set a check box by calling setSelectedCheckbox( ).

    Choice Controls

    The Choice class is used to create a pop-up list of items from which the user may choose. Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only enough space to show the currently selected item. When the user clicks on it, the whole list of choices pops up, and a new selection can be made. Each item in the list is a string that appears as a left-justified label in the order it is added to the Choice object.

    Constructor

    Choice()

    Method

    void add(String name):- To add a selection Item to the list.

    String getSelectedItem( ) & int getSelectedIndex( ):- To determine which item is currently selected

    int getItemCount( ):- To obtain the number of items in the list

    void select(int index) & void select(String name):- set the currently selected item with either a zero-based integer index or a string that will match a name in the list.

    String getItem(int index):- obtain the name associated with the item at that index.

    Using Lists

    The List class provides a compact, multiple-choice, scrolling selection list. Unlike the Choice object, which shows only the single selected item in the menu, a List object can be constructed to show any number of choices in the visible window. It can also be created to allow multiple selections.

    List provides these constructors:

    List( ) throws HeadlessException

    List(int numRows) throws HeadlessException

    List(int numRows, boolean multipleSelect) throws HeadlessException

    Method

    void add(String name) & void add(String name, int index):- To add a selection to the list.

    String getSelectedItem( ) & int getSelectedIndex( ):- For lists that allow only single selection, you can determine which item is currently selected.

    String[ ] getSelectedItems( ) & int[ ] getSelectedIndexes( ):- For lists that allow multiple selection, you must use either getSelectedItems( ) or getSelectedIndexes( ), shown here, to determine the current selections.

    int getItemCount( ):- To obtain the number of items in the list

    void select(int index):- set the currently selected item by using the select( ) method with a zero-based integer index.

    String getItem(int index):- obtain the name associated with the item at that index.

    Managing Scroll Bars

    Scroll bars are used to select continuous values between a specified minimum and maximum. Scroll bars may be oriented horizontally or vertically. The slider box can be dragged by the user to a new position. The scroll bar will then reflect this value.

    Contructor

    Scrollbar( ) throws HeadlessException:- creates a vertical scroll bar.

    Scrollbar(int style) throws HeadlessException:- to specify the orientation of the scroll bar. If style is Scrollbar.VERTICAL, a vertical scroll bar is created. If style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.

    Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws HeadlessException:- the initial value of the scroll bar is passed in initialValue. The number of units represented by the height of the thumb is passed in thumbSize. The minimum and maximum values for the scroll bar are specified by min and max.

    Method

    void setValues(int initialValue, int thumbSize, int min, int max):-set initial value,thum size,min and max

    int getValue( ):- To obtain the current value of the scroll bar

    void setValue(int newValue):- To set the current value

    int getMinimum( ) & int getMaximum( ):-To retrieve the minimum and maximum values.

    void setUnitIncrement(int newIncr):- By default, 1 is the increment added to or subtracted from the scroll bar each time it is scrolled up or down one line. You can change this increment by calling setUnitIncrement( ).

    void setBlockIncrement(int newIncr):- By default, page-up and page-down increments are 10. You can change this value by calling setBlockIncrement( ).

    Using a TextField

    The TextField class implements a single-line text-entry area, usually called an edit control. Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and paste keys, and mouse selections. TextField is a subclass of TextComponent.

    Constructor

    TextField( ) throws HeadlessException

    TextField(int numChars) throws HeadlessException

    TextField(String str) throws HeadlessException

    TextField(String str, int numChars) throws HeadlessException

    Method

    String getText( ):- To obtain the string currently contained in the text field

    void setText(String str):- To set the text

    String g

    etSelectedText( ):- The user can select a portion of the text in a text field. obtain the currently selected text.

    void select(int startIndex, int endIndex):- select a portion of text under program control by using select( ).

    boolean isEditable( ):-To know text field editable or not

    void setEditable(boolean canEdit):-to make text field editable or only readable.

    void setEchoChar(char ch):- want the user to enter text that is not displayed, such as a password. You can disable the echoing of the characters as they are typed.

    boolean echoCharIsSet( ):-to check echo character is set or not.

    char getEchoChar( ):- retrieve the echo character

    Using a TextArea

    Sometimes a single line of text input is not enough for a given task. To handle these situations, the AWT includes a simple multiline editor called TextArea.

    Constructor

    TextArea( ) throws HeadlessException

    TextArea(int numLines, int numChars) throws HeadlessException

    TextArea(String str) throws HeadlessException

    TextArea(String str, int numLines, int numChars) throws HeadlessExcepti on

    TextArea(String str, int numLines, int numChars, int sBars) throws HeadlessException:-sBars must be one of these values: SCROLLBARS_BOTH, SCROLLBARS_NONE, SCROLLBARS_HORIZONTAL_ONLY , SCROLLBARS_VERTICAL_ONLY

    TextArea is a subclass of TextComponent. Therefore, it supports the getText( ), setText( ), getSelectedText( ), select( ), isEditable( ), and setEditable( ) methods.

    void append(String str):- d appends the string specified by str to the end of the current text.

    void insert(String str, int index):- inserts the string passed in str at the specified index

    void replaceRange(String str, int startIndex, int endIndex):- It replaces the characters from startIndex to endIndex–1, with the replacement text passed in str.

        // Demonstrate TextArea.
    import java.awt.*;
    public class TextAreaDemo extends Frame {
        public void TextAreaDemo () {
            String val =    "Java SE 6 is the latest version of";
            TextArea text = new TextArea(val, 10, 30);
            add(text);
        }
        public static void main(String args[])
        {
    	    TextAreaDemo te=new TextAreaDemo();
        }
    }
    
  • Java Chapter 17- Understanding Layout Managers
  • Understanding Layout Managers

    Each Container object has a layout manager associated with it. A layout manager is an instance of any class that implements the LayoutManager interface. The layout manager is set by the setLayout( ) method. If no call to setLayout( ) is made, then the default layout manager is used. Whenever a container is resized (or sized for the first time), the layout manager is used to position each of the components within it. The setLayout( ) method has the following general form: void setLayout(LayoutManager layoutObj)

    Here, layoutObj is a reference to the desired layout manager. If you wish to disable the layout manager and position components manually, pass null for layoutObj. If you do this, you will need to determine the shape and position of each component manually, using the setBounds( ) method defined by Component.

    FlowLayout

    FlowLayout is the default layout manager. FlowLayout implements a simple layout style, which is similar to how words flow in a text editor. A small space is left between each component, above and below, as well as left and right.

    constructors:-

    FlowLayout( ):- creates the default layout, which centers components and leaves five pixels of space between each component.

    FlowLayout(int how):- lets you specify how each line is aligned. Valid values for how are as follows: FlowLayout.LEFT, FlowLayout.CENTER, FlowLayout.RIGHT, FlowLayout.LEADING, FlowLayout.TRAILING.

    FlowLayout(int how, int horz, int vert):- allows you to specify alignment as well the horizontal and vertical space left between components in horz and vert, respectively.

    Example

    // Use left-aligned flow layout.
    import java.awt.*;
    public class FlowLayoutDemo extends Frame {
        Checkbox winXP, winVista, solaris, mac;
        public  FlowLayoutDemo() {
            // set left-aligned flow layout
            setLayout(new FlowLayout(FlowLayout.LEFT));
            winXP = new Checkbox("Windows XP", null, true);
            winVista = new Checkbox("Windows Vista");
            solaris = new Checkbox("Solaris");
            mac = new Checkbox("Mac OS");
            add(winXP);
            add(winVista);
            add(solaris);
            add(mac);
            setSize(500,600);
            setVisible(true);
        }
        public static void main(String args[]) {
    	    FlowLayoutDemo fl=new FlowLayoutDemo();
        }
    }
    
    
    

    BorderLayout

    The BorderLayout class implements a common layout style for top-level windows. It has four narrow, fixed-width components at the edges and one large area in the center. The four sides are referred to as north, south, east, and west. The middle area is called the center.

    Constructor

    BorderLayout( ):- creates a default border layout.

    BorderLayout(int horz, int vert):- allows you to specify the horizontal and vertical space left between components in horz and vert, respectively. BorderLayout defines the following constants that specify the regions: BorderLayout.CENTER, BorderLayout.SOUTH BorderLayout.EAST, BorderLayout.WEST, BorderLayout.NORTH.

    Adding Components

    void add(Component compObj, Object region) Here, compObj is the component to be added, and region specifies where the component will be added.

    Example:

    // Demonstrate BorderLayout.
    import java.awt.*;
    import java.util.*;
    public class BorderLayoutDemo extends Frame {
        public BorderLayoutDemo() {
            setLayout(new BorderLayout());
            add(new Button("This is across the top."),BorderLayout.NORTH);
            add(new Label("The footer message might go here."),BorderLayout.SOUTH);
            add(new Button("Right"), BorderLayout.EAST);
            add(new Button("Left"), BorderLayout.WEST);
            String msg = "The reasonable man adapts " +"himself to the world;\n" +the unreasonable one persists in " +"trying to adapt the world to himself.\n" +"Therefore all progress depends " +"on the unreasonable man.\n\n" +" - George Bernard Shaw\n\n";
            add(new TextArea(msg), BorderLayout.CENTER);
            setSize(600,600);
            setVisible(true);
        }
        public static void main(String args[]) {
    	    BorderLayoutDemo fl=new BorderLayoutDemo();
        }
    }    
    

    GridLayout

    GridLayout lays out components in a two-dimensional grid. When you instantiate a GridLayout, you define the number of rows and columns.

    constructors

    GridLayout( ):- creates a single-column grid layout.

    GridLayout(int numRows, int numColumns):- creates a grid layout with the specified number of rows and columns.

    GridLayout(int numRows, int numColumns, int horz, int vert):- to specify the horizontal and vertical space left between components in horz and vert, respectively.

    Example:

    // Demonstrate GridLayout
    import java.awt.*;
    public class GridLayoutDemo extends Frame {
        static final int n = 4;
        public  GridLayoutDemo () {
            setLayout(new GridLayout(n, n));
            setFont(new Font("SansSerif", Font.BOLD, 24));
            for(int i = 0; i < n; i++) {
    	        for(int j = 0; j < n; j++) {
    		        int k = i * n + j;
    		        if(k > 0)
    		            add(new Button("" + k));
    		    }
    	    }
        }
        public static void main(String args[])
        {
            GridLayoutDemo g=new GridLayoutDemo();
        }
    }
        
    

    CardLayout

    The CardLayout stores several different layouts. Each layout can be thought of as being on a separate index card in a deck that can be shuffled so that any card is on top at a given time. This can be useful for user interfaces with optional components that can be dynamically enabled and disabled upon user input. You can prepare the other layouts and have them hidden, ready to be activated when needed.

    CardLayout provides these two constructors:

    1)CardLayout( ):- creates a default card layout.

    2)CardLayout(int horz, int vert):- to specify the horizontal and vertical space left between components in horz and vert, respectively.

    Use of a card layout requires a bit more work than the other layouts. The cards are typically held in an object of type Panel. This panel must have CardLayout selected as its layout manager. The cards that form the deck are also typically objects of type Panel. Thus, you must create a panel that contains the deck and a panel for each card in the deck. Next, you add to the appropriate panel the components that form each card. You then add these panels to the panel for which CardLayout is the layout manager. Finally, you add this panel to the window. Once these steps are complete, you must provide some way for the user to select between cards. One common approach is to include one push button for each card in the deck.

    When card panels are added to a panel, they are usually given a name. Thus, most of the time, you will use this form of add( ) when adding cards to a panel: void add(Component panelObj, Object name) Here, name is a string that specifies the name of the card whose panel is specified by panelObj.

    After you have created a deck, your program activates a card by calling one of the following methods defined by CardLayout:

    void first(Container deck) 
    void last(Container deck) 
    void next(Container deck) 
    void previous(Container deck) 
    void show(Container deck, String cardName)
    
    // Demonstrate CardLayout.
    import java.awt.*;
    import java.awt.event.*;
    public class CardLayoutDemo extends Frame implements ActionListener, MouseListener {
        Checkbox winXP, winVista, solaris, mac;
        Panel osCards;
        CardLayout cardLO;
        Button Win, Other;
        public CardLayoutDemo() {
            Win = new Button("Windows");
            Other = new Button("Other");
            add(Win);
            add(Other);
            cardLO = new CardLayout();
            osCards = new Panel();
            osCards.setLayout(cardLO); // set panel layout to card layout
            winXP = new Checkbox("Windows XP", null, true);
            winVista = new Checkbox("Windows Vista");
            solaris = new Checkbox("Solaris");
            mac = new Checkbox("Mac OS");
            // add Windows check boxes to a panel
            Panel winPan = new Panel();
            winPan.add(winXP);
            winPan.add(winVista);
            // add other OS check boxes to a panel
            Panel otherPan = new Panel();
            otherPan.add(solaris);
            otherPan.add(mac);
            // add panels to card deck panel
            osCards.add(winPan, "Windows");
            osCards.add(otherPan, "Other");
            // add cards to main window panel
            add(osCards);
            // register to receive action events
            Win.addActionListener(this);
            Other.addActionListener(this);
            // register mouse events
            addMouseListener(this);
        }
        // Cycle through panels.
        public void mousePressed(MouseEvent me) {
            cardLO.next(osCards);
        }
        // Provide empty implementations for the other MouseListener methods.
        public void mouseClicked(MouseEvent me) {
        }
        public void mouseEntered(MouseEvent me) {
        }
        public void mouseExited(MouseEvent me) {
        }
        public void mouseReleased(MouseEvent me) {
        }
        public void actionPerformed(ActionEvent ae) {
            if(ae.getSource() == Win) {
                cardLO.show(osCards, "Windows");
            }
            else {
                cardLO.show(osCards, "Other");
            }
        }
        public static void main(String args[])
        {
    	    CardLayoutDemo cd=new CardLayoutDemo();	
        }
    }
    
    

    GridBagLayout

    specify the relative placement of components by specifying their positions within cells inside a grid. The key to the grid bag is that each component can be a different size, and each row in the grid can have a different number of columns. This is why the layout is called a grid bag. It’s a collection of small grids joined together.

    The location and size of each component in a grid bag are determined by a set of constraints linked to it. The constraints are contained in an object of type GridBagConstraints. Constraints include the height and width of a cell, and the placement of a component, its alignment, and its anchor point within the cell.

    GridBagLayout defines only one constructor

    GridBagLayout( )

    GridBagLayout defines several methods, of which many are protected and not for general use. There is one method, however, that you must use: setConstraints( ). It is shown here: void setConstraints(Component comp, GridBagConstraints cons)

    // Use GridBagLayout.
    import java.awt.*;
    public class GridBagDemo extends Applet implements ItemListener {
        Checkbox winXP, winVista, solaris, mac;
        public GridBagDemo () {
            GridBagLayout gbag = new GridBagLayout();
            GridBagConstraints gbc = new GridBagConstraints();
            setLayout(gbag);
            // Define check boxes.
            winXP = new Checkbox("Windows XP ", null, true);
            winVista = new Checkbox("Windows Vista");
            solaris = new Checkbox("Solaris");
            mac = new Checkbox("Mac OS");
            // Define the grid bag.
            // Use default row weight of 0 for first row.
            gbc.weightx = 1.0; // use a column weight of 1
            gbc.ipadx = 200; // pad by 200 units
            gbc.insets = new Insets(4, 4, 0, 0); // inset slightly from top left
            gbc.anchor = GridBagConstraints.NORTHEAST;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            gbag.setConstraints(winXP, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbag.setConstraints(winVista, gbc);
            // Give second row a weight of 1.
            gbc.weighty = 1.0;
            gbc.gridwidth = GridBagConstraints.RELATIVE;
            gbag.setConstraints(solaris, gbc);
            gbc.gridwidth = GridBagConstraints.REMAINDER;
            gbag.setConstraints(mac, gbc);
            // Add the components.
            add(winXP);
            add(winVista);
            add(solaris);
            add(mac);
        }
        public static void main(String args[])
        {
            GridBagDemo g=new GridBagDemo();
        }
    }
    
  • Java Chapter 18- EVENT HANDLING
  • EVENT HANDLING

    There are several types of events, including those generated by the mouse, the keyboard, and various GUI controls, such as a push button, scroll bar, or check box.

    The Delegation Event Model

    It is modern approach to handling events, which defines standard and consistent mechanisms to generate and process events. Its concept is quite simple: a source generates an event and sends it to one or more listeners. Here listener simply waits until it receives an event. Once an event is received, the listener processes the event and then returns.

    Event Sources

    A source is an object that generates an event. Sources may generate more than one type of event.

    Events

    In the delegation model, an event is an object that describes a state change in a source. It can be generated as a consequence of a person interacting with the elements in a graphical user interface. Some of the activities that cause events to be generated are pressing a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse.

    Event Listeners

    A listener is an object that is notified when an event occurs. It has two major requirements. First, it must have been registered with one or more sources to receive notifications about specific types of events. The general form of such a method is this:public void addTypeListener(TypeListener el)

    For example

    The method that registers a keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called addMouseMotionListener( ).

    Second, it must implement methods to receive and process these notifications. The methods that receive and process events are defined in a set of interfaces found in java.awt.event. For Example MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or moved.

    A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general form of such a method is this: public void removeTypeListener(TypeListener el)

    Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard listener, you would call removeKeyListener( ).

    Event Classes

    At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass for all events.

    constructor

    EventObject(Object src) Here, src is the object that generates this event.

    EventObject contains two methods:

    Object getSource( ):- Returns the source of the event.

    toString( ):- Returns the string equivalent of the event.

    AWTEvent Class

    class AWTEvent defined within the java.awt package, is a subclass of EventObject. It is the superclass (either directly or indirectly) of all AWT-based events used by the delegation event model.

    AWTEvent Method

    int getID( ):- getID( ) method can be used to determine the type of the event.

    The ActionEvent Class

    An ActionEvent is generated when a button is pressed, a list item is double-clicked, or a menu item is selected.

    ActionEvent has these three constructors:

    ActionEvent(Object src, int type, String cmd)

    ActionEvent(Object src, int type, String cmd, int modifiers)

    ActionEvent(Object src, int type, String cmd, long when, int modifiers)

    Here, src is a reference to the object that generated this event. The type of the event is specified by type, and its command string is cmd. The argument modifiers indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated. The when parameter specifies when the event occurred.

    Method

    String getActionCommand( ):- obtain the command name for the invoking ActionEvent object. For example, when a button is pressed, an action event is generated that has a command name equal to the label on that button.

    int getModifiers( ):- Method returns a value that indicates which modifier keys (ALT, CTRL, META, and/or SHIFT) were pressed when the event was generated.

    long getWhen( ):- Returns the time at which the event took place. This is called the event’s timestamp.

    ActionListener Interface

    This interface defines the actionPerformed( ) method that is invoked when an action event occurs. ActionEvent Class is handled and processed by following method: public void actionPerformed(ActionEvent ae)

    Example Program
    // Demonstrate Buttons
    import java.awt.*;
    import java.awt.event.*;
    public class ButtonDemo extends Frame implements ActionListener {
        Label lmsg;
        Button yes, no, maybe;
        public ButtonDemo() {
            setLayout(new GridLayout(4, 1));
            lmsg=new Label("MSG:");
            yes = new Button("Yes");
            no = new Button("No");
            maybe = new Button("Undecided");
            add(lmsg);
            add(yes);
            add(no);
            add(maybe);
            yes.addActionListener(this);
            no.addActionListener(this);
            maybe.addActionListener(this);
            setSize(600,600);
            setVisible(true);
        }
        public void actionPerformed(ActionEvent ae) {
            String str = ae.getActionCommand();
            if(str.equals("Yes")) {
    	    lmsg.setText("You pressed Yes.");
            }
            else if(str.equals("No")) {
    	        lmsg.setText("You pressed No.");
            }
            else {
    	        lmsg.setText("You pressed Undecided.");
            }
        }
        public static void main(String args[]) {
            ButtonDemo bd=new ButtonDemo();
        }
    }
    
    

    The AdjustmentEvent Class

    An AdjustmentEvent is generated by a scroll bar. There are five types of adjustment events.

    BLOCK_DECREMENT:- The user clicked inside the scroll bar to decrease its value.

    BLOCK_INCREMENT:- The user clicked inside the scroll bar to increase its value.

    TRACK:- The slider was dragged.

    UNIT_DECREMENT:- The button at the end of the scroll bar was clicked to decrease its value.

    UNIT_INCREMENT:- The button at the end of the scroll bar was clicked to increase its value.

    AdjustmentEvent constructor

    AdjustmentEvent(Adjustable src, int id, int type, int data) Here, src is a reference to the object that generated this event. The id specifies the event. The type of the adjustment is specified by type, and its associated data is data.

    AdjustmentEvent Method

    Adjustable getAdjustable( ):- getAdjustable( ) method returns the object that generated the event.

    int getAdjustmentType( ):- The type of the adjustment event may be obtained by the getAdjustmentType( ) method. It returns one of the constants defined by AdjustmentEvent.

    int getValue( ) :- The amount of the adjustment can be obtained from the getValue( ) method For example, when a scroll bar is manipulated, this method returns the value represented by that change.

    AdjustmentListener Interface

    This interface defines the method that is invoked when an adjustment event occurs.

    AdjustmentListener Method

    void adjustmentValueChanged(AdjustmentEvent ae)

    AdjustmentListener Example

    import java.awt.*;
    import java.awt.event.*;
    public class ScrollEx2 implements AdjustmentListener{
        Frame jf;
        Panel jp, jp2; 
        Label frameLabel1;
        ScrollEx2(){
            jf = new Frame("Scrollbar");
            //Creating the first JPanel and adding two JLabels to it
            jp = new Panel();
            //Creating a Label 
            Label panelLabel1 = new Label("Handling a Scrollbar drag event", Label.CENTER);
            jp = new Panel(new BorderLayout());
            jp.add(panelLabel1,BorderLayout.NORTH); //Adding the Label to NORTH of the Panel
            Scrollbar scrollBHorizontal = new Scrollbar(Scrollbar.HORIZONTAL, 10, 40, 0, 100); //Creating the horizontal Scrollbar
            Scrollbar scrollBVertical = new Scrollbar(Scrollbar.VERTICAL, 10, 60, 0, 100); //Creating the vertical Scrollbar
            jp.add(scrollBHorizontal,BorderLayout.SOUTH); //Adding the horizontal Scrollbar to SOUTH of Panel
            jp.add(scrollBVertical, BorderLayout.EAST); //Adding the vetical Scrollbar to EAST of JPanel
            Integer i = scrollBHorizontal.getValue();//Getting the current position value of horizontal scrollbar
            //Creating a JLabel and setting its value to the current position value of horizontal scrollbar.
            frameLabel1 = new Label(i.toString());
            //Adding this JLabel to SOUTH of the JFrame
            jf.add(frameLabel1, BorderLayout.SOUTH);
            //Adding the first JPanel to the CENTER of JFrame
            jf.add(jp,BorderLayout.CENTER);
            //Registering the scrollbar adjustment events 
            scrollBHorizontal.addAdjustmentListener(this);
            scrollBVertical.addAdjustmentListener(this);
            jf.setSize(350,270);
            jf.setVisible(true);
        }
        public void adjustmentValueChanged(AdjustmentEvent e){
            Integer i =e.getValue();
            frameLabel1.setText(i.toString());
        }
        public static void main(String... ar){
            new ScrollEx2();
        }
    }
       
       

    The ComponentEvent Class

    A ComponentEvent is generated when the size, position, or visibility of a component is changed. ComponentEvent is the superclass either directly or indirectly of ContainerEvent, FocusEvent, KeyEvent, MouseEvent, and WindowEvent. There are four types of component events which are resized, moved, shown, or hidden.

    ComponentEvent Constructor:

    ComponentEvent(Component src, int type) Here, src is a reference to the object that generated this event. The type is the event type. There are four types of component events. which are COMPONENT_HIDDEN, COMPONENT_MOVED, COMPONENT_RESIZED, COMPONENT_SHOWN.

    ComponentEvent Method:

    Component getComponent( ):- Method returns the component that generated the event.

    The ComponentListener Interface

    This interface defines four methods that are invoked when a component is resized, moved, shown, or hidden. Their general forms are shown here:

    void componentResized(ComponentEvent ce) :- Invoked when component was resized.

    void componentMoved(ComponentEvent ce) :- Invoked when component was moved.

    void componentShown(ComponentEvent ce) :- Invoked when component was visible.

    void componentHidden(ComponentEvent ce):- Invoked when component was hidden.

    Example Program

       //Component Listner
    import java.awt.*;
    import java.awt.event.*;
    public class ComponentEventEx {
    public static void main(String[] args) {
    Frame frame = new Frame("ComponentEventExample");
    frame.setSize(300,300);
     frame.setVisible(true);
        ComponentListener componentListener = new ComponentListener(){
    	public void componentShown(ComponentEvent evt) {
        		System.out.println("componentShown");
      	}
    	public void componentHidden(ComponentEvent evt) {
        		System.out.println("componentHidden");
      	}
    	public void componentMoved(ComponentEvent evt) {
        		System.out.println("componentMoved");
      	}
    	public void componentResized(ComponentEvent evt) {
        		System.out.println("componentResized");
      	}};
        frame.addComponentListener(componentListener);
      }
    }
     
    

    The ContainerEvent Class

    A ContainerEvent is generated when a component is added to or removed from a container. There are two types of container events: COMPONENT_ADDED and COMPONENT_REMOVED. ContainerEvent is a subclass of ComponentEvent.

    ContainerEvent Constructor

    ContainerEvent(Component src, int type, Component comp) Here,src is a reference to the container that generated this event. The type of the event is specified by type, and the component that has been added to or removed from the container is comp.

    ContainerEvent Method

    Container getContainer( ):- You can obtain a container that generated this event.

    Component getChild( ):- Method returns a component that was added to or removed from the container.

    The ContainerListener Interface

    This interface contains two methods. Their general forms are shown here:

    void componentAdded(ContainerEvent ce):- Invoked When a component is added to a container

    void componentRemoved(ContainerEvent ce):- Invoked When a component is removed from a container

    Example Program

    //Component Listner
    import java.awt.*;
    import java.awt.event.*;
    public class ContainerEventEx extends Frame implements ContainerListener {
    private Label headerLabel, statusLabel;
      ContainerEventEx(){
    	    super("MYWindow");
    	    setSize(400,400);
            setLayout(new GridLayout(3, 1));
            statusLabel = new Label();        
            statusLabel.setAlignment(Label.CENTER);
            statusLabel.setSize(350,100);
            addContainerListener(this);
            add(statusLabel);
            setVisible(true);	
        }
    public void componentAdded(ContainerEvent e) {
             statusLabel.setText(statusLabel.getText() 
             + ((Frame)e.getContainer()).getTitle() + " IN "+e.getChild( ) .getClass().getSimpleName()+" added. ");
          }
          public void componentRemoved(ContainerEvent e) {
             statusLabel.setText(statusLabel.getText()          + e.getComponent().getClass().getSimpleName() + " removed. ");
          }
        public static void main(String[] args) {
            ContainerEventEx ex=new ContainerEventEx();
      }
    }
    
    

    The FocusEvent Class

    A FocusEvent is generated when a component gains or loses input focus. These events are identified by the integer constants FOCUS_GAINED and FOCUS_LOST. FocusEvent is a subclass of ComponentEvent.

    Constructors

    FocusEvent(Component src, int type) Here, src is a reference to the component that generated this event. The type of the event is specified by type.

    FocusEvent(Component src, int type, boolean temporaryFlag)

    FocusEvent(Component src, int type, boolean temporaryFlag, Component other) Here, The argument temporaryFlag is set to true if the focus event is temporary. Otherwise, it is set to false. (A temporary focus event occurs as a result of another user interface operation. For example, assume that the focus is in a text field. If the user moves the mouse to adjust a scroll bar, the focus is temporarily lost.) The other component involved in the focus change, called the opposite component, is passed in other.

    Method

    Component getOppositeComponent( ):- Therefore, if a FOCUS_GAINED event occurred, other will refer to the component that lost focus. Conversely, if a FOCUS_LOST event occurred, other will refer to the component that gains focus. You can determine the other component by calling getOppositeComponent( ). The opposite component is returned.

    boolean isTemporary( ):- The isTemporary( ) method indicates if this focus change is temporary. The method returns true if the change is temporary. Otherwise, it returns false.

    The FocusListener Interface

    This interface defines two methods.

    void focusGained(FocusEvent fe)

    void focusLost(FocusEvent fe)

    Example Program

    import java.awt.*;
    import java.awt.event.*;
    public class FocusListenertest extends Frame implements FocusListener{
         Button b1,b2;
         public FocusListenertest(){
             add(b1=new Button ("First"),"South");
             add(b2=new Button ("Second"),"North");
             b1.addFocusListener(this);
             b2.addFocusListener(this);
             setSize(200,200);
         }
         public void focusGained(FocusEvent fe){	 //method of focuslistener
             if(fe.getSource()==b1)
                System.out.println(b1.getLabel()+"gained");
             if(fe.getSource()==b2)
                System.out.println(b2.getLabel()+"gained");
             if(fe.isTemporary())
                System.out.println("Temporary Focus");
         }
         public void focusLost(FocusEvent fe)         {	//in focusevent "getID()"is a method
             if(fe.getSource()==b1)
                System.out.println(b1.getLabel()+"lost");
             if(fe.getSource()==b2)
                System.out.println(b2.getLabel()+"lost");
         }
         public static void main(String a[])         {
             new FocusListenertest().setVisible(true);
         }
    }
    

    The ItemEvent Class

    An ItemEvent is generated when a check box or a list item is clicked or Choice item is clicked or when a checkable menu item is selected or deselected. There are two types of item events integer constants : DESELECTED The user deselected an item. SELECTED The user selected an item. In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED, that signifies a change of state.

    ItemEvent constructor:

    ItemEvent(ItemSelectable src, int type, Object entry, int state) Here, src is a reference to the component that generated this event. For example, this might be a list or choice element. The type of the event is specified by type. The specific item that generated the item event is passed in entry. The current state of that item is in state.

    Method

    Object getItem( ):- The getItem( ) method can be used to obtain a reference to the item that generated an event. ItemSelectable getItemSelectable( ):- To obtain a reference to the ItemSelectable object that generated an event.

    int getStateChange( ):- Method returns the state change (that is, SELECTED or DESELECTED) for the event.

    The ItemListener Interface

    This interface defines the method that is invoked when the state of an item changes. Its general form is shown here: void itemStateChanged(ItemEvent ie)

    Example Program

    import java.awt.*;    
    import java.awt.event.*;    
    public class ItemListenerExample implements ItemListener{    
        Checkbox checkBox1,checkBox2;  
        Label label;  
        ItemListenerExample(){    
            Frame f= new Frame("CheckBox Example");    
            label = new Label();            
            label.setAlignment(Label.CENTER);    
            label.setSize(400,100);    
            checkBox1 = new Checkbox("C++");    
            checkBox1.setBounds(100,100, 50,50);    
            checkBox2 = new Checkbox("Java");    
            checkBox2.setBounds(100,150, 50,50);    
            f.add(checkBox1); f.add(checkBox2); f.add(label);    
            checkBox1.addItemListener(this);
            checkBox2.addItemListener(this);    
            f.setSize(400,400);    
            f.setLayout(null);    
            f.setVisible(true);    
         }    
        public void itemStateChanged(ItemEvent e) {      
            if(e.getSource()==checkBox1)
            	label.setText("C++ Checkbox: " + (e.getStateChange()==1?"checked":"unchecked"));   
            if(e.getSource()==checkBox2)  
      	        label.setText("Java Checkbox: "  + (e.getStateChange()==1?"checked":"unchecked"));    
         }  
        public static void main(String args[])    {    
            new ItemListenerExample();    
        }    
    }    
    
    

    The InputEvent Class

    The abstract class InputEvent is a subclass of ComponentEvent. Its subclasses are KeyEvent and MouseEvent. InputEvent defines several integer constants that represent any modifiers, i.e control key being pressed, that might be associated with the event. Such as: ALT_MASK, BUTTON2_MASK, META_MASK, ALT_GRAPH_MASK, BUTTON3_MASK, SHIFT_MASK, BUTTON1_MASK, CTRL_MASK

    However, because of possible conflicts between the modifiers used by keyboard events and mouse events, and other issues, the following extended modifier values were added: ALT_DOWN_MASK, BUTTON2_DOWN_MASK, META_DOWN_MASK, ALT_GRAPH_DOWN_MASK, BUTTON3_DOWN_MASK, SHIFT_DOWN_MASK, BUTTON1_DOWN_MASK, CTRL_DOWN_MASK.

    When writing new code, it is recommended that you use the new, extended modifiers rather than the original modifiers. To test if a modifier was pressed at the time an event is generated, The forms of these methods are shown here:

     boolean isAltDown( )
     boolean isAltGraphDown( )
     boolean isControlDown( )
     boolean isMetaDown( )
     boolean isShiftDown( ) 
     

    int getModifiers( ):- Obtain a value that contains all of the original modifier flags by calling the method.

    int getModifiersEx( ):- obtain a value that contains all of the extended modifiers flags by calling the method.

    The KeyEvent Class

    A KeyEvent is generated when keyboard input occurs. KeyEvent is a subclass of InputEvent. There are three types of key events, which are identified by these integer constants: KEY_PRESSED, KEY_RELEASED, and KEY_TYPED.

    The first two events are generated when any key is pressed or released. The last event occurs only when a character is generated.

    There are many other integer constants that are defined by KeyEvent. VK_0 to VK_9 and VK_A to VK_Z define the ASCII equivalents of the numbers and letters.

    Here are some others: VK_ALT, VK_DOWN, VK_LEFT, VK_RIGHT, VK_CANCEL, VK_ENTER, VK_PAGE_DOWN, VK_SHIFT, VK_CONTROL, VK_ESCAPE, VK_PAGE_UP, VK_UP. The VK constants specify virtual key codes and are independent of any modifiers, such as control, shift, or alt.

    constructors:

    KeyEvent(Component src, int type, long when, int modifiers, int code, char ch) Here, src is a component that generated the event. The type of the event is specified by type. The system time at which the key was pressed is passed in when. The modifiers argument indicates which modifiers were pressed when this key event occurred. The virtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The character equivalent (if one exists) is passed in ch. If no valid character exists, then ch contains CHAR_UNDEFINED. For KEY_TYPED events, code will contain VK_UNDEFINED.

    The KeyEvent class defines several methods

    char getKeyChar( ):- Returns the character that was entered. If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.

    int getKeyCode( ):-, which returns the key code. When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.

    The KeyListener Interface

    This interface defines three methods.

    void keyPressed(KeyEvent ke) : method is invoked when a key has been press.

    void keyReleased(KeyEvent ke):- method is invoked when a key has been release.

    void keyTyped(KeyEvent ke):- The keyTyped( ) method is invoked when a character has been entered.

    For example, if a user presses and releases the A key, three events are generated in sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key events are generated in sequence: key pressed and released.

    //Key Listner Example
    import java.awt.*;  
    import java.awt.event.*;  
    public class KeyListenerExample extends Frame implements KeyListener{  
        Label l;    TextArea area;  
        KeyListenerExample(){  
          l=new Label(); 
             l.setBounds(20,50,500,20);  
            area=new TextArea();    
          area.setBounds(20,80,300, 300);  
            area.addKeyListener(this);  
              add(l);add(area);  
            setSize(400,400);     
       setLayout(null);       
     setVisible(true);  
        }  
        public void keyPressed(KeyEvent e) {  
            l.setText(" Key Pressed");  
        }  
        public void keyReleased(KeyEvent e) {  
        	 String text=area.getText();    
          String words[]=text.split("\\s");  
            l.setText(" Key Released          Words: "+words.length+" Characters:"+text.length());   
        }  
        public void keyTyped(KeyEvent e) {  
            l.setText(" Key Typed");  
        }  
          public static void main(String[] args) {  
            new KeyListenerExample();  
        }  
    }  
    

    The MouseEvent

    MouseEvent is a subclass of InputEvent. Class There are eight types of mouse events. The MouseEvent class defines the following integer constants that can be used to identify them:

     MOUSE_CLICKED 	The user clicked the mouse.
     MOUSE_DRAGGED 	The user dragged the mouse.
     MOUSE_ENTERED 	The mouse entered a component.
     MOUSE_EXITED 	The mouse exited from a component.
     MOUSE_MOVED 	The mouse moved.
     MOUSE_PRESSED 	The mouse was pressed.
     MOUSE_RELEASED 	The mouse was released.
     MOUSE_WHEEL 	The mouse wheel was moved.
     

    constructors:

    MouseEvent(Component src, int type, long when, int modifiers, int x, int y, int clicks, boolean triggersPopup) Here, src is a reference to the component that generated the event. The type of the event is specified by type. The system time at which the mouse event occurred is passed in when. The modifiers argument indicates which modifiers were pressed when a mouse event occurred. The coordinates of the mouse are passed in x and y. The click count is passed in clicks. The triggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.

    MouseEvent Methods:

    int getX( ):- Return X coordinates of mouse within component when event occured.

    int getY( ):- Return X coordinates of mouse within component when event occured.

    Point getPoint( ):- Obtain the coordinates of the mouse. It returns a Point object that contains the X,Y coordinates.

    void translatePoint(int x, int y ):- Changes the location of the event.

    int getClickCount( ):- Obtains the number of mouse clicks for this event.

    boolean isPopupTrigger( ):- Method tests if this event causes a pop-up menu to appear on this platform.

    int getButton( ):- It returns a value that represents the button that caused the event. The return value will be one of these constants defined by MouseEvent: NOBUTTON, BUTTON1, BUTTON2, BUTTON3 The NOBUTTON value indicates that no button was pressed or released.

    Java SE 6 added to that obtain the coordinates of the mouse relative to the screen rather than the component:

    Point getLocationOnScreen( ):- returns a Point object that contains both the X and Y coordinate of screen.

    int getXOnScreen( ):- Return X coordinate of screen when event occured.

    int getYOnScreen( ):- Return Y coordinate of screen when event occured.

    The MouseListener Interface

    This interface defines five methods. The general forms of these methods are:

    void mouseClicked(MouseEvent me):- Methods are invoked If the mouse is pressed and released at the same point.

    void mouseEntered(MouseEvent me) :- Methods are invoked When the mouse enters a component.

    void mouseExited(MouseEvent me):- Methods are invoked When it leaves a component.

    void mousePressed(MouseEvent me):- Methods are invoked when the mouse is pressed.

    void mouseReleased(MouseEvent me):- Methods are invoked when the mouse is released.

    The MouseMotionListener Interface

    This interface defines two methods. Their general forms are shown here:

    void mouseDragged(MouseEvent me):- method is called multiple times as the mouse is dragged.

    void mouseMoved(MouseEvent me):- method is called multiple times as the mouse is moved.

    import java.awt.*;  
    import java.awt.event.*;  
    public class MouseListenerExample extends Frame implements MouseListener, MouseMotionListener {  
        Label l;  
        MouseListenerExample(){  
            addMouseListener(this);  
    	l=new Label();  
            l.setBounds(20,50,500,20);  
            add(l);  
            setSize(300,300);  
            setLayout(null);  
            setVisible(true);  
        }  
        public void mouseClicked(MouseEvent e) {  
            l.setText("Mouse Clicked at ["+e.getX()+" "+e.getY()+"]"); 
    	Graphics g=getGraphics();  
            g.setColor(Color.BLUE);  
            g.fillOval(e.getX(),e.getY(),30,30); 
        } 
    public void mouseEntered(MouseEvent e) {  
            l.setText("Mouse Entered at ["+e.getX()+" "+e.getY()+"]");  
        }  
        public void mouseExited(MouseEvent e) {  
            l.setText("Mouse Exited at ["+e.getX()+" "+e.getY()+"]");  
        }  
        public void mousePressed(MouseEvent e) {  
            l.setText("Mouse Pressed at ["+e.getX()+" "+e.getY()+"]");  
        }  
        public void mouseReleased(MouseEvent e) {  
            l.setText("Mouse Released at ["+e.getX()+" "+e.getY()+"]");  
        } 
    	public void mouseDragged(MouseEvent e) {
    		l.setText("Mouse Dragged at ["+e.getX()+" "+e.getY()+"]");
    	}
    	public void mouseMoved(MouseEvent e) {
    		l.setText("Mouse Moved at ["+e.getX()+" "+e.getY()+"]");
    	}
    	public static void main(String[] args) {  
       	 	new MouseListenerExample();  
    	}  
    }  
    
    

    The TextEvent Class

    Instances of this class describe text events. These are generated by text fields and text areas when characters are entered by a user or program. TextEvent defines the integer constant TEXT_VALUE_CHANGED.

    constructor for TextEvent Class

    TextEvent(Object src, int type) Here, src is a reference to the object that generated this event. The type of the event is specified by type.

    The TextListener Interface

    This interface defines the textChanged( ) method that is invoked when a change occurs in a text area or text field. Its general form is shown here: void textChanged(TextEvent te)

    import java.awt.*;  
    import java.awt.event.*;  
    public class TextListenerExample extends Frame implements TextListener{  
        Label l;  
        TextArea area;  
        TextListenerExample(){  
            l=new Label(); l.setBounds(20,50,500,20);  
            area=new TextArea();  
            area.setBounds(20,80,300, 300);  
            area.addTextListener(this);  
            add(l);
    	add(area);  
            setSize(400,400); setLayout(null);  setVisible(true);  
        }  
        public void textValueChanged(TextEvent e) {
             l.setText("text: " + area.getText());               
          } 
        public static void main(String[] args) {  
            new TextListenerExample();  
        }  
    }  
    
    

    The WindowEvent Class

    WindowEvent is a subclass of ComponentEvent. There are ten types of window events. The WindowEvent class defines integer constants that can be used to identify them. The constants and their meanings are shown here:

    WINDOW_ACTIVATED The window was activated. 
    WINDOW_CLOSED The window has been closed. 
    WINDOW_CLOSING The user requested that the window be closed. 
    WINDOW_DEACTIVATED The window was deactivated. 
    WINDOW_DEICONIFIED The window was deiconified. 
    WINDOW_GAINED_FOCUS The window gained input focus. 
    WINDOW_ICONIFIED The window was iconified.
     WINDOW_LOST_FOCUS The window lost input focus. 
    WINDOW_OPENED The window was opened. 
    WINDOW_STATE_CHANGED The state of the window changed.
    

    Constructors of WindowEvent Class:

    WindowEvent(Window src, int type) Here, src is a reference to the object that generated this event. The type of the event is type.

    WindowEvent(Window src, int type, Window other)

    WindowEvent(Window src, int type, int fromState, int toState)

    WindowEvent(Window src, int type, Window other, int fromState, int toState) Here, other specifies the opposite window when a focus or activation event occurs. The fromState specifies the prior state of the window, and toState specifies the new state that the window will have when a window state change occurs.

    Method

    Window getWindow( ):- It returns the Window object that generated the event.

    Window getOppositeWindow( ):- return the opposite window (when a focus or activation event has occurred)

    int getOldState( ):- previous window state

    int getNewState( ):- current window state

    The WindowListener Interface

    This interface defines seven methods.

    void windowActivated(WindowEvent we):- invoked when a window is activated

    void windowDeactivated(WindowEvent we):- invoked when a window is deactivated

    void windowOpened(WindowEvent we):- When a window is opened or closed

    void windowClosed(WindowEvent we):- When a window is opened or closed

    void windowClosing(WindowEvent we):- method is called when a window is being closed.

    void windowIconified(WindowEvent we):- Invoked If a window is iconified

    void windowDeiconified(WindowEvent we):-Invoked When a window is deiconified

    import java.awt.*;  
    import java.awt.event.WindowEvent;  
    import java.awt.event.WindowListener;  
    public class WindowExample extends Frame implements WindowListener{  
        WindowExample(){  
            addWindowListener(this);  
              
            setSize(400,400);  
            setLayout(null);  
            setVisible(true);  
        }  
          
    public static void main(String[] args) {  
        new WindowExample();  
    }  
    public void windowActivated(WindowEvent arg0) {  
        System.out.println("activated");  
    }  
    public void windowClosed(WindowEvent arg0) {  
        System.out.println("closed");  
    }  
    public void windowClosing(WindowEvent arg0) {  
        System.out.println("closing");  
        dispose();  
    }  
    public void windowDeactivated(WindowEvent arg0) {  
        System.out.println("deactivated");  
    }  
    public void windowDeiconified(WindowEvent arg0) {  
        System.out.println("deiconified");  
    }  
    public void windowIconified(WindowEvent arg0) {  
        System.out.println("iconified");  
    }  
    public void windowOpened(WindowEvent arg0) {  
        System.out.println("opened");  
    }  
    }  
    

    Adapter Classes

    Java provides a special feature, called an adapter class, that can simplify the creation of event handlers in certain situations. An adapter class provides an empty implementation of all methods in an event listener interface. Adapter classes are useful when you want to receive and process only some of the events that are handled by a particular event listener interface. You can define a new class to act as an event listener by extending one of the adapter classes and implementing only those events in which you are interested.

    Adapter class Listener interface
    WindowAdapter WindowListener
    KeyAdapter KeyListener
    MouseAdapter MouseListener
    MouseMotionAdapter MouseMotionListener
    FocusAdapter FocusListener
    ComponentAdapter ComponentListener
    ContainerAdapter ContainerListener

    Java WindowAdapter Example

    1.	import java.awt.*;  
    2.	import java.awt.event.*;  
    3.	public class AdapterExample{  
    4.	    Frame f;  
    5.	    AdapterExample(){  
    6.	        f=new Frame("Window Adapter");  
    7.	        f.addWindowListener(new WindowAdapter(){  
    8.	            public void windowClosing(WindowEvent e) {  
    9.	                f.dispose();  
    10.	            }  
    11.	        });  
    12.	        f.setSize(400,400);  
    13.	        f.setLayout(null);  
    14.	        f.setVisible(true);  
    15.	    }  
    16.	public static void main(String[] args) {  
    17.	    new AdapterExample();  
    18.	}  
    19.	}
    

    Java MouseAdapter Example

    1.	import java.awt.*;  
    2.	import java.awt.event.*;  
    3.	public class MouseAdapterExample extends MouseAdapter{  
    4.	    Frame f;  
    5.	    MouseAdapterExample(){  
    6.	        f=new Frame("Mouse Adapter");  
    7.	        f.addMouseListener(this);  
    8.	          
    9.	        f.setSize(300,300);  
    10.	        f.setLayout(null);  
    11.	        f.setVisible(true);  
    12.	    }  
    13.	    public void mouseClicked(MouseEvent e) {  
    14.	        Graphics g=f.getGraphics();  
    15.	        g.setColor(Color.BLUE);  
    16.	        g.fillOval(e.getX(),e.getY(),30,30);  
    17.	    }  
    18.	      
    19.	public static void main(String[] args) {  
    20.	    new MouseAdapterExample();  
    21.	}  
    22.	}
    

    Java MouseMotionAdapter Example

    1.	import java.awt.*;  
    2.	import java.awt.event.*;  
    3.	public class MouseMotionAdapterExample extends MouseMotionAdapter{  
    4.	    Frame f;  
    5.	    MouseMotionAdapterExample(){  
    6.	        f=new Frame("Mouse Motion Adapter");  
    7.	        f.addMouseMotionListener(this);  
    8.	          
    9.	        f.setSize(300,300);  
    10.	        f.setLayout(null);  
    11.	        f.setVisible(true);  
    12.	    }  
    13.	public void mouseDragged(MouseEvent e) {  
    14.	    Graphics g=f.getGraphics();  
    15.	    g.setColor(Color.ORANGE);  
    16.	    g.fillOval(e.getX(),e.getY(),20,20);  
    17.	}  
    18.	public static void main(String[] args) {  
    19.	    new MouseMotionAdapterExample();  
    20.	}  
    21.	}
    

    Java KeyAdapter Example

    1.	import java.awt.*;  
    2.	import java.awt.event.*;  
    3.	public class KeyAdapterExample extends KeyAdapter{  
    4.	    Label l;  
    5.	    TextArea area;  
    6.	    Frame f;  
    7.	    KeyAdapterExample(){  
    8.	        f=new Frame("Key Adapter");  
    9.	        l=new Label();  
    10.	        l.setBounds(20,50,200,20);  
    11.	        area=new TextArea();  
    12.	        area.setBounds(20,80,300, 300);  
    13.	        area.addKeyListener(this);  
    14.	          
    15.	        f.add(l);f.add(area);  
    16.	        f.setSize(400,400);  
    17.	        f.setLayout(null);  
    18.	        f.setVisible(true);  
    19.	    }  
    20.	    public void keyReleased(KeyEvent e) {  
    21.	        String text=area.getText();  
    22.	        String words[]=text.split("\\s");  
    23.	        l.setText("Words: "+words.length+" Characters:"+text.length());  
    24.	    }  
    25.	  
    26.	    public static void main(String[] args) {  
    27.	        new KeyAdapterExample();  
    28.	    }  
    29.	}  
      
    

Student Reviews

Considering primary motivation for the generation of narratives is a useful concept