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 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 - Object Oriented Programming
  • 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.

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

  • Java - 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 - 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 - User Input Using 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 - 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 - Introducing Classes
  • 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; iVarargs: 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 - 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 - 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 - Packages and Interfaces
  • 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. It must be emphasized that the import statement is optional. Any place you use a class name, you can use its fully qualified name, which includes its full package hierarchy. For example, this fragment uses an import statement: import java.util.*; class MyDate extends Date { } The same example without the import statement looks like this: class MyDate extends java.util.Date { } In this version, Date is fully-qualified. 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. In practice, this means that you can define interfaces that don’t make assumptions about how they are implemented. Once it is defined, 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. This is the general form 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 Once an interface has been defined, one or more classes can implement that interface. To implement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: 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); } // ... } Here, the class Incomplete does not implement callback( ) and must be declared as abstract. Any class that inherits Incomplete must implement callback( ) or be declared abstract itself. 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 - Enumerations
  • an enumeration is a list of named constants.Enumeration Fundamentals An enumeration is created using the enum keyword. For example: enum Apple { 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 Apple. For example, Apple ap; ap = Apple.ramika; // An enumeration of apple varieties. enum Apple { Jonathan, GoldenDel, RedDel, Winesap, Cortland } class EnumDemo { public static void main(String args[]) { Apple ap; ap = Apple.RedDel; // Output an enum value. System.out.println("Value of ap: " + ap); System.out.println(); ap = Apple.GoldenDel; // Compare two enum values. if(ap == Apple.GoldenDel) System.out.println("ap contains GoldenDel.\n"); // Use an enum to control a switch statement. switch(ap) { case Jonathan: System.out.println("Jonathan is red."); break; case GoldenDel: System.out.println("Golden Delicious is yellow."); break; case RedDel: System.out.println("Red Delicious is red."); break; case Winesap: System.out.println("Winesap is red."); break; case Cortland: System.out.println("Cortland is red."); break; } } } The output from the program is shown here: Value of ap: RedDel ap contains GoldenDel. Golden Delicious is yellow. _________________________________________________________________________________________________ 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. 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( ) Boolean Boolean is a wrapper around boolean values. It defines these constructors: Boolean(boolean boolValue) Boolean(String boolString) To obtain a boolean value from a Boolean object, use booleanValue( ), shown here: boolean booleanValue( ) The Numeric Type Wrappers These are Byte, Short, Integer, Long, Float, and Double. All of the numeric type wrappers inherit the abstract class Number. Number declares methods that return the value of an object in each of the different number formats. These methods are shown here: byte byteValue( ) double doubleValue( ) float floatValue( ) int intValue( ) long longValue( ) short shortValue( ) // 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) 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. 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 } }
  • Java - I/O, Applets, and Other Topics
  • 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]); } } } Reading and Writing Files Two of the most often-used stream classes are FileInputStream and FileOutputStream, which create byte streams linked to files. Syntax: FileInputStream(String fileName) throws FileNotFoundException FileOutputStream(String fileName) throws FileNotFoundException Here, fileName specifies the name of the file that you want to open. 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(); } } To write to a file, you can use the write( ) method defined by FileOutputStream. Its simplest form is shown here: Syntax: 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(); } } ______________________________________________________________________________________________ 1)Enter no and print sum of 1 to no(Summation of no) example 10-->1+2+3+4+5+6+7+8+9+10=? 2)enter no and calculate factorial no no ex 5->1*2*3*4*5=? 3)enter no and count no of digit 25->2 348->3 1278->4 1785689->7 4)enter no and sum of digit 25->7 348->15 5) WAP to input basic salary and DA is 40% of basic salary. HRA is 20% of basic salary and It is 10% of basic salary so calculate gross salary. 1000->1500 6)enter distance in km and conver in meter 8)enter tempratur in fahrenheit and calculate in centigrade 9)enter radius of circle and calculate area and perimeter 10) enter length and width of rectangle and calculate area and perimeter Applet Fundamentals 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. import java.awt.*; import java.applet.*; public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } there are two ways in which you can run an applet: •Executing the applet within a Java-compatible web browser. • 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. Here is the HTML file that executes SimpleApplet: To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example, if the preceding HTML file is called RunApp.html, then the following command line will run SimpleApplet: C:\>appletviewer RunApp.html a more convenient method exists that you can use to speed up testing. Simply include a comment at the head of your Java source code file that contains the APPLET tag. import java.awt.*; import java.applet.*; /* */ public class SimpleApplet extends Applet { public void paint(Graphics g) { g.drawString("A Simple Applet", 20, 20); } } Using assert Another relatively new addition to Java is the keyword assert. It is used during program development to create an assertion, which is a condition that should be true during the execution of the program. However, if the condition is false, then an AssertionError is thrown The assert keyword has two forms. The first is shown here: assert condition; // Demonstrate assert. class AssertDemo { static int val = 3; // Return an integer. static int getnum() { return val--; } public static void main(String args[]) { int n; for(int i=0; i < 10; i++) { n = getnum(); assert n > 0; // will fail when n is 0 System.out.println("n is " + n); } } } The second form of assert is shown here: assert condition : expr; As explained, you can specify the message displayed when an assertion fails. For example, if you substitute assert n > 0 : "n is negative!"; Static Import By following import with the keyword static, an import statement can be used to import the static members of a class or interface. When using static import, it is possible to refer to static members directly by their names, without having to qualify them with the name of their class. This simplifies and shortens the syntax required to use a static member. // Compute the hypotenuse of a right triangle. class Hypot { public static void main(String args[]) { double side1, side2; double hypot; side1 = 3.0; side2 = 4.0; // Notice how sqrt() and pow() must be qualified by // their class name, which is Math. hypot = Math.sqrt(Math.pow(side1, 2) + Math.pow(side2, 2)); System.out.println("Given sides of lengths " + side1 + " and " + side2 + " the hypotenuse is " + hypot); } } Because pow( ) and sqrt( ) are static methods, they must be called through the use of their class’ name, Math. Invoking Overloaded Constructors Through this( ) When working with overloaded constructors, it is sometimes useful for one constructor to invoke another. In Java, this is accomplished by using another form of the this keyword. The general form is shown here: this(arg-list) First, consider the following class that does not use this( ): class MyClass { int a; int b; // initialize a and b individually MyClass(int i, int j) { a = i; b = j; } // initialize a and b to the same value MyClass(int i) { a = i; b = i; } // give a and b default values of 0 MyClass( ) { a = 0; b = 0; } } By using this( ), it is possible to rewrite MyClass as shown here: class MyClass { int a; int b; // initialize a and b individually MyClass(int i, int j) { a = i; b = j; } // initialize a and b to the same value MyClass(int i) { this(i, i); // invokes MyClass(i, i) } // give a and b default values of 0 MyClass( ) { this(0); // invokes MyClass(0) } } Generics What Are Generics? At its core, the term generics means parameterized types. Parameterized types are important because they enable you to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter. Using generics, it is possible to create a single class. // A simple generic class. // Here, T is a type parameter that // will be replaced by a real type // when an object of type Gen is created. class Gen { T ob; // declare an object of type T // Pass the constructor a reference to // an object of type T. Gen(T o) { ob = o; } // Return ob. T getob() { return ob; } // Show type of T. void showType() { System.out.println("Type of T is " + ob.getClass().getName()); } } // Demonstrate the generic class. class GenDemo { public static void main(String args[]) { // Create a Gen reference for Integers. Gen iOb; // Create a Gen object and assign its // reference to iOb. Notice the use of autoboxing // to encapsulate the value 88 within an Integer object. iOb = new Gen(88); // Show the type of data used by iOb. iOb.showType(); // Get the value in iOb. Notice that // no cast is needed. int v = iOb.getob(); System.out.println("value: " + v); System.out.println(); // Create a Gen object for Strings. Gen strOb = new Gen("Generics Test"); // Show the type of data used by strOb. strOb.showType(); // Get the value of strOb. Again, notice // that no cast is needed. String str = strOb.getob(); System.out.println("value: " + str); } } The output produced by the program is shown here: Type of T is java.lang.Integer value: 88 Type of T is java.lang.String value: Generics Test
  • Java - Constructors
  • Java - Basic Datatypes
  • Java - Variable Types
  • Java - Modifier Types
  • Java - Basic Operators
  • Java - Loop Control
  • Java - Decision Making
  • Java - Numbers
  • Java - Characters
  • Java - Strings
  • Java - Arrays
  • Java - Date & Time
  • Java - Regular Expressions
  • Java - Methods
  • Java - Files and I/O
  • Java - Exceptions
  • Java - Inner classes
  • Java Object Oriented
  • Java - Inheritance
  • Java - Overriding
  • Java - Polymorphism
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java Advanced
  • Java - Data Structures
  • Java - Collections
  • Java - Generics
  • Java - Serialization
  • Java - Networking
  • Java - Sending Email
  • Java - Multithreading
  • Java - Applet Basics

Student Reviews

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