MI 0032-57568118-MI0032-Solved

download MI 0032-57568118-MI0032-Solved

of 54

Transcript of MI 0032-57568118-MI0032-Solved

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    1/54

    MI0032-Java and Web Design

    SET-1

    Q.1 Explain different types of control statements.

    Ans:- 2.4 Control Flow Statements

    Following statements are used to control the flow of execution in a program.

    1. Decision Making Statements

    If-else statement

    Switch case statement

    2. Looping Statement

    For loop

    While loop

    Do-while loop

    3. Other statement

    Break

    Continue

    Label

    (1) If-else statement

    The statement is Javas conditional branch statement. It can be used to route program executionthrough two different paths. Here is the general form of the statement:

    if (condition) statement1;

    else, statement2;

    Here, each statement may be a single statement or a compound statement enclosed in curlybraces (that is, a block). The condition is any expression that returns a boolean value. The else

    clause is optional.

    The works like this: If the condition is true, then statement1 is executed. Otherwise, statement2 (ifit exists) is executed. In no case will both statements be executed. For example, consider thefollowing:

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    2/54

    MI0032-Java and Web Design

    Figure 2.6

    Most often, the expression used to control the will involve the relational operators. However, thisis not technically necessary. It is possible to control the using a single boolean variable, asshown in this code fragment:

    boolean dataAvailable;

    //

    if (dataAvailable)

    ProcessData();

    else

    waitForMoreData();

    Remember, only one statement can appear directly after the ifor the else. If you want to includemore statements, youll need to create a block, as in this fragment:

    int bytesAvailable;

    //

    if (bytesAvailable > 0) {

    ProcessData();

    bytesAvailable -= n;

    } else

    waitForMoreData();

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image01237.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    3/54

    MI0032-Java and Web Design

    Here, both statements within the ifblock will execute ifbytesAvailable is greater than zero.Some programmers find it convenient to include the curly braces when using the even when thereis only one statement in each clause. This makes it easy to add another statement at a later date,and you dont have to worry about forgetting the braces. In fact, forgetting to define a block whenone is needed is a common cause of errors. For example, consider the following code fragment:

    int bytesAvailable;

    //

    if (bytesAvailable > 0) {

    ProcessData();

    bytesAvailable -= n;

    } else

    waitForMoreData();

    bytesAvailable = n;

    It seems clear that the statement bytesAvailable = n; was intended to be executed inside theelseclause, because of the indentation level. However, as you recall, whitespace is insignificantto Java, and there is no way for the compiler to know what was intended. This code will compilewithout complaint, but it will behave incorrectly when run.

    The preceding example is fixed in the code that follows:

    Int bytesAvailable;

    //

    If (bytesAvailable > 0) {

    ProcessData ();

    BytesAvailable -= n;

    }

    else {

    WaitForMoreData ();

    BytesAvailable = n;

    }

    The if-else-if Ladder

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    4/54

    MI0032-Java and Web Design

    A common programming construct that is based upon a sequence of nested ifs is the ifelse-

    ladder. It looks like this:

    if(condition)

    statement;

    else if(condition)

    statement;

    else if(condition)

    statement;

    .

    .

    .

    else

    statement;

    The statements are executed from the top down. As soon as one of the conditions controlling theifis true, the statement associated with that ifis executed, and the rest of the ladder is bypassed.If none of the conditions is true, then the final statement will be executed. The final else acts as adefault condition; that is, if all other conditional tests fail, then the last else statement is

    performed. If there is no final and all other conditions are false, then no action will take place.

    Here is a program that uses an if-else-ifladder to determine which season a particular month isin.

    // 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)

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    5/54

    MI0032-Java and Web Design

    season = "Spring";

    else if(month == 6 || month == 7 || month ==

    season = "Summer";

    else if(month == 9 || month == 10 || month == 11)

    season = "Autumn";

    else

    season = "Bogus Month";

    System.out.println("April is in the " + season + ".");

    }

    }

    Here is the output produced by the program:

    April is in the Spring.

    You might want to experiment with this program before moving on. As you will find, no matterwhat value you give month, one and only one assignment statement within the ladder will beexecuted.

    (2) Switch Statement

    The switch statement is Javas multiway branch statement. It provides an easy way to dispatchexecution to different parts of your code based on the value of an expression. As such, it oftenprovides a better alternative than a large series ofif-else-ifstatements.

    Here is the general form of a switch statement:

    switch (expression) {

    case value1:

    // statement sequence

    break;

    case value2:

    // statement sequence

    break;

    .

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    6/54

    MI0032-Java and Web Design

    .

    .

    case valueN:

    // statement sequence

    break;

    default:

    // default statement sequence

    }

    The expression must be of type byte, short, int, orchar; each of the values specified in the casestatements must be of a type compatible with the expression. Each case value must be a unique

    literal (that is, it must be a constant, not a variable). Duplicate case values are not allowed.

    The switch statement works like this: The value of the expression is compared with each of theliteral values in the case statements. If a match is found, the code sequence following that casestatement is executed. If none of the constants matches the value of the expression, then thedefault statement is executed. However, the default statement is optional. If no case matchesand no default is present, then no further action is taken.

    The break statement is used inside the switch to terminate a statement sequence. When abreak statement is encountered, execution branches to the first line of code that follows the entireswitch statement. This has the effect of "jumping out" of the switch.

    Example

    Figure 2.7

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image01433.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    7/54

    MI0032-Java and Web Design

    The break statement is optional. If you omit the break, execution will continue on into the nextcase. It is sometimes desirable to have multiple cases without break statements between them.For example, consider the following program:

    // In a switch, break statements are optional.

    class MissingBreak {

    public static void main(String args[]) {

    for (int i=0; i

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    8/54

    MI0032-Java and Web Design

    This program generates the following output:

    i is less than 5

    i is less than 5

    i is less than 5

    i is less than 5

    i is less than 5

    i is less than 10

    i is less than 10

    i is less than 10

    i is less than 10

    i is less than 10

    i is 10 or more

    i is 10 or more

    Nested switch Statements

    You can use a switch as part of the statement sequence of an outerswitch. This is called anestedswitch. Since a switch statement defines its own block, no conflicts arise between the

    case constants in the innerswitch and those in the outerswitch. For Example, the followingfragment is perfectly valid:

    switch (count) {

    case 1:

    switch (target) {// nested switch

    case 0:

    System.out.println ("target is zero");

    break;

    case 1: // no conflicts with outer switch

    System.out.println ("target is one");

    break;

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    9/54

    MI0032-Java and Web Design

    }

    break;

    case 2: //

    Here, the case 1: statement in the inner switch does not conflict with the case 1:

    Statement in the outer switch. The count variable is only compared with the list of cases at theouter level. Ifcount is 1, then target is compared with the inner list cases. In summary, there arethree important features of the switch statement to note:

    The switch differs from the ifin that switch can only test for equality, whereas ifcan evaluateany type of Boolean expression. That is, the switch looks only for a match between the value ofthe expression and one of its case constants.

    No two case constants in the same switch can have identical values. Of course, a Switchstatement enclosed by an outerswitch can have case constants in common.

    A switch statement is usually more efficient than a set of nested ifs.

    The last point is particularly interesting because it gives insight into how the Java compiler works.When it compiles a switch statement, the Java compiler will inspect each of the case constantsand create a "jump table" that it will use for selecting the path of execution depending on thevalue of the expression. Therefore, if you need to select among a large group of values, a switchstatement will run much faster than the equivalent logic coded using a sequence ofif-else. Thecompiler can do this because it knows that the case constants are all the same type and simplymust be compared for equality with the switch expression. The compiler has no such knowledgeof a long list ofifexpressions.

    (3) For Loop

    The usage of for loop is as follows

    for (initial statement; termination condition; increment instruction)

    Statement;

    When multiple statements are to be included in the for loop, the statements are included insideflower braces.

    for (initial statement; termination condition; increment instruction)

    {

    statement1;

    statement2;

    }

    The example below prints numbers from 1 to 10

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    10/54

    MI0032-Java and Web Design

    Figure 2.8

    The results of the above program is shown below

    Figure 2.9

    Like all other programming languages, Java allows loops to be nested. That is, one loop may beinside another. For example, here is a program that nests forloops:

    // Loops may be nested.

    class Nested {

    public static void main (String args []) {

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image01821.jpghttp://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image01629.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    11/54

    MI0032-Java and Web Design

    int i, j;

    for (i=0; i

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    12/54

    MI0032-Java and Web Design

    Figure 2.10

    (5) do.while statement

    As you just saw, if the conditional expression controlling a while loop is initially false, then thebody of the loop will not be executed at all. However, sometimes it is desirable to execute thebody of a while loop at least once, even if the conditional expression is false to begin with. Inother words, there are times when you would like to test the termination expression at the end ofthe loop rather than at the beginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop always executes its body at least once, because its conditionalexpression is at the bottom of the loop. Its general form is

    do {

    // body of loop

    } while (condition);

    Each iteration of the do-while loop first executes the body of the loop and then evaluates theconditional expression. If this expression is true, the loop will repeat. Otherwise, the loopterminates. As with all of Javas loops, condition must be a boolean expression.

    Example

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image02023.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    13/54

    MI0032-Java and Web Design

    Figure 2.11

    The do-while loop is especially useful when you process a menu selection, because you willusually want the body of a menu loop to execute at least once. Consider the following programwhich implements a very simple help system for Javas selection and iteration statements:

    // 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");

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image02217.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    14/54

    MI0032-Java and Web Design

    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");

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    15/54

    MI0032-Java and Web Design

    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;

    }" end of switch

    }

    }

    Here is a sample run produced by this program:

    Help on:

    1. if

    2. switch

    3. while

    4. do-while

    5. for

    Choose one:

    The do-while:

    do {

    statement;

    } while (condition);

    In the program, the do-while loop is used to verify that the user has entered a valid choice. If not,then the user is reprompted. Since the menu must be displayed at least once, the do-while is theperfect loop to accomplish this.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    16/54

    MI0032-Java and Web Design

    A few other points about this example: Notice that characters are read from the keyboard bycalling System.in.read( ). This is one of Javas console input functions. Although Javas consoleI/O methods wont be discussed in detail until System.in.read( ) is used here to obtain the userschoice. It reads characters from standard input (returned as integers, which is why the returnvalue was cast to char). By default, standard input is line buffered, so you must press ENTERbefore any characters that you type will be sent to your program.

    Javas console input is quite limited and awkward to work with. Further, most real-world Javaprograms and applets will be graphical and window-based. For these reasons, not much use ofconsole input has been made in this book. However, it is useful in this context. One other point:Because System.in.read( ) is being used, the program must specify the throws

    java.io.IOException clause. This line is necessary to handle input errors.

    (6) Break statement

    By using break, you can force immediate termination of a loop, bypassing the conditionalexpression and any remaining codfse in the body of the loop. When a break statement isencountered inside a loop, the loop is terminated and program control resumes at the nextstatement following the loop. Here is a simple example:

    // Using break to exit a loop.

    class BreakLoop {

    public static void main(String args[]) {

    for(int i=0; i

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    17/54

    MI0032-Java and Web Design

    i: 5

    i: 6

    i: 7

    i: 8

    i: 9

    Loop complete.

    As you can see, although the forloop is designed to run from 0 to 99, the break statementcauses it to terminate early, when i equal 10.

    (7) Continue Statement

    Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue

    running the loop, but stop processing the remainder of the code in its body for this particulariteration. This is, in effect, a goto just past the body of the loop, to the loops end. The continuestatement performs such an action. In while and do-while loops, a continue statement causescontrol to be transferred directly to the conditional expression that controls the loop. In a forloop,control goes first to the iteration portion of the forstatement and then to the conditionalexpression. For all three loops, any intermediate code is bypassed.

    Here is an example program that uses continue to cause two numbers to be printed on eachline:

    // Demonstrate continue.

    class Continue {

    public static void main (String args[]) {

    for (int i=0; i

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    18/54

    MI0032-Java and Web Design

    0 1

    2 3

    4 5

    6 7

    8 9

    As with the break statement, continue may specify a label to describe which enclosing loops tocontinue. Here is an example program that uses continue to print a triangular multiplication tablefor 0 through 9.

    Q.2 a. What is the difference between errors and exceptions?

    Ans :- (a)

    Errors Exceptions

    Error mens system doesn't handle.Forexample: Overflow, Outof memory.

    Exception means When a method encountersan abnormalcondition (an exception condition) that it can'thandleitself, it may throw an exception.

    Error : Something goes wrong in ourapplication/program ,that leads to crash your output/logic is calledas error.the error may be of syntatic error or error whichcaneasily identify the programmer.

    Exception : during the execution(runtime) ofourapplication/program, the system leads tosomething wrongstatements like 'system out of memory' 'out ofarguments'called Exception.

    Error is the one which is of runtime exceptiontype, thatwhat we cann't declare in throws clause.

    Exception is an abnormal condition occurred atruntime.

    Error is uncoverable Exception is coverable

    Error is the compile time error not runtime andit is notcovered it is only fixed by a programer.

    NoteWhen Error occur then our programe stops anddonot run

    Exceptio is an run time error when an abnormalcondition isoccurred the jvm detect it and make the objectof that

    abnormal condition and throws it to its ownclass and thatobject is catched by catched block and catchblock handled it.but If exception occur then nothing happiningonly try blockwill be suspended and after that if any code iswritten thatwill be executed properly means our system or

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    19/54

    MI0032-Java and Web Design

    programe workproperly.

    Error: Any departure from the expectedbehavior of thesystem or program, which stops the working of

    the system isan error.

    Exception: Any error or problem which one canhandle and continue to work normally.An Exception can be caught and recovered:

    Error : Something goes wrong in ourapplication/program ,that leads to crash your output/logic is calledas error.the error may be of syntatic error or error whichcaneasily identify the programmer.

    Exception:its unwanted and unexpeceted eventits disturb thenormal flow of program execution.

    Exception is an object it occurs at runtime itgives system error message and then convertsystem errormessage into user friendly messages

    Errors are the problems which we cant hadle,like stackoverflow and memory out of bounds like that...

    Exceptions are also kind of errors which wecan hadle atboth compile time and run time by using try andcatchblocks.These are two types: Compile time andruntime.Sql and IO operations are come under compiletime arrayindex out of bounds and null pointer these arecome underruntime exceptions

    Java has several predefined exceptions. The most common exceptions that you may encounter

    are described below :

    Arithmetic Exception: this is thrown when an exceptional arithmetic condition has

    occurred. For example, a division by zero generates such an exception.

    NullPointer Exception: This is thrown when an application attempts to user null where an

    object is required. The situations are given below :

    o Using an object without allocating memory for it.

    o Calling the methods of a null object.

    o Accessing or modifying the attributes of a null object.

    ArrayIndexOutOfBounds exception: This exception is thrown when an attempt is made to

    access an array element beyond the index of the array thats has only ten elements, the

    exception will be thrown.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    20/54

    MI0032-Java and Web Design

    b. Explain different types of error handling techniques with a suitable example.

    Ans: Exception Handling Techniques

    When an unexpected error occurs in a method, Java creates an object of the appropriate

    exception class. After creating the exception objects, Java passes it to the program, by an actioncalled throwing an exception. The exception object contains information about the type of errorand the state of the program when the exception occurred. You need to handle the exceptionusing exception-handler and process the exception.

    You can implement exception-handling in your program by using following keywords:

    try

    catch

    finally

    The tryBlock

    You need to guard the statements that may throw an exception in the try block. The followingskeletal code illustrates the use of the try block

    try

    {

    // statement that may cause an exception

    }

    The try block governs the statements that are enclosed within it and defines the scope of theexception handlers associated with it. In other words, if an exception occurs within try block, theappropriate exception-handler that is associated with the try block handles the exception. A tryblock must have at least one catch block that follow it immediately.

    Nested try Statements

    The try statement can be nested. That is, a try statement can be inside the block of anothertry.Each time a try statement is entered, the context of that exception is pushed on the stack. If aninnertry statement does not have a catch handler for a particular exception, the stack isunwound and the next try statements catch handlers are inspected for a match. This continues

    until one of the catch statements succeeds, or until all of the nested try statements areexhausted. If no catch statement matches, then the Java run-time system will handle theexception. Here is an example that uses nested try

    statements:

    // An example of nested try statements.

    class NestTry {

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    21/54

    MI0032-Java and Web Design

    public static void main(String args[]) {

    try {

    int a = args.length;

    /* If no command-line args are present,

    the following statement will generate

    a divide-by-zero exception. */

    int b = 42 / a;

    System.out.println("a = " + a);

    try { // nested try block

    /* If one command-line arg is used,

    then a divide-by-zero exception

    will be generated by the following code. */

    if(a==1) a = a/(a-a); // division by zero

    /* If two command-line args are used,

    then generate an out-of-bounds exception. */

    if(a==2) {

    int c[ ] = { 1 };

    c[42] = 99; // generate an out-of-bounds exception

    }

    } catch(ArrayIndexOutOfBoundsException e) {

    }

    } catch(ArithmeticException e) {

    System.out.println("Divide by 0: " + e);

    }

    }

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    22/54

    MI0032-Java and Web Design

    }

    As you can see, this program nests one try block within another. The program works as follows.When you execute the program with no command-line arguments, a divide-by zero exception isgenerated by the outertry block. Execution of the program by one command-line argumentgenerates a divide-by-zero exception from within the nested try block. Since the inner block does

    not catch this exception, it is passed on to the outertry block, where it is handled. If you executethe program with two command-line arguments, an array boundary exception is generated fromwithin the innertry block. Here are sample runs that illustrate each case:

    C:>java NestTry

    Divide by 0: java.lang.ArithmeticException: / by zero

    C:>java NestTry One

    a = 1

    Divide by 0: java.lang.ArithmeticException: / by zero

    C:>java NestTry One Two

    a = 2

    Array index out-of-bounds:

    java.lang.ArrayIndexOutOfBoundsException: 42

    Nesting oftry statements can occur in less obvious ways when method calls are involved. Forexample, you can enclose a call to a method within a try block. Inside that method is anothertrystatement. In this case, the try within the method is still nested inside the outertry block, whichcalls the method. Here is the previous program recoded so that the nested try block is movedinside the method nesttry( ):

    /* Try statements can be implicitly nested via

    calls to methods. */

    class MethNestTry {

    static void nesttry(int a) {

    try { // nested try block

    /* If one command-line arg is used,

    then a divide-by-zero exception

    will be generated by the following code. */

    if(a==1) a = a/(a-a); // division by zero

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    23/54

    MI0032-Java and Web Design

    /* If two command-line args are used,

    then generate an out-of-bounds exception. */

    if(a==2) {

    int c[ ] = { 1 };

    c[42] = 99; // generate an out-of-bounds exception

    }

    } catch(ArrayIndexOutOfBoundsException e) {

    System.out.println("Array index out-of-bounds: " + e);

    }

    }

    public static void main(String args[]) {

    try {

    int a = args.length;

    /* If no command-line args are present,

    the following statement will generate

    a divide-by-zero exception. */

    int b = 42 / a;

    System.out.println("a = " + a);

    nesttry(a);

    } catch(ArithmeticException e) {

    System.out.println("Divide by 0: " + e);

    }

    }

    }

    The output of this program is identical to that of the preceding example.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    24/54

    MI0032-Java and Web Design

    The catch Block

    You associate an exception-handler with the try block by providing one or more catch handlersimmediately after try block. The following skeletal code illustrates the use of the catch block.

    try

    {

    //statements that may cause an exception

    }

    catch ()

    {

    // error handling code

    }

    The catch statement takes an object of an exception class as a parameter. If an exception isthrown, the statements in the catch block are executed. The scope of the catch block is restrictedto the statements in the preceding try block only.

    The finallyBlock

    When an exception is raised, the rest of the statements in the try block are ignored. Sometimes, itis necessary to process certain statements irrespective of whether an exception is raised or not.The finally block is used for this purpose.

    try

    {

    openFile();

    writeFile(); //may cause an exception

    }

    catch ()

    {

    //process the exception

    }

    In the above example, the file has to be closed irrespective of whether an exception is raised ornot. You can place the code to close the file in both the try and catch blocks. To avoid duplication

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    25/54

    MI0032-Java and Web Design

    of code, you can place the code in the finally block. The code in the finally block is executedregardless of whether an exception is thrown or not. The finally block follows the catch blocks.You have only one finally block for an exception-handler. However, it is not mandatory to have afinally block.

    finally

    {

    closeFile ();

    }

    Q.3 What is InterThread communication in Java? Explain with an example.

    Ans: Interthread Communication

    The preceding examples unconditionally blocked other threads from asynchronous access tocertain methods. This use of the implicit monitors in Java objects is powerful, but you can achievea more subtle level of control through interprocess communication.

    As discussed earlier, multithreading replaces event loop programming by dividing your tasks intodiscrete and logical units. Threads also provide a secondary benefit: they do away with polling.Polling is usually implemented by a loop that is used to check some condition repeatedly. Oncethe condition is true, appropriate action is taken. This wastes CPU time. For example, considerthe classic queuing problem, where one thread is producing some data and another is consumingit. To make the problem more interesting, suppose that the producer has to wait until theconsumer is finished before it generates more data. In a polling system, the consumer wouldwaste many CPU cycles while it waited for the producer to produce. Once the producer wasfinished, it would start polling, wasting more CPU cycles waiting for the consumer to finish, and so

    on. Clearly, thissituation is undesirable.

    To avoid polling, Java includes an elegant interprocess communication mechanism via thewait( ), notify( ), and notifyAll( ) methods. These methods are implemented as final methods inObject, so all classes have them. All three methods can be called only from within asynchronized method. Although conceptually advanced from a computer science perspective,the rules for using these methods are actually quite simple:

    wait( ) tells the calling thread to give up the monitor and go to sleep until some other threadenters the same monitor and calls notify( ).

    notify( ) wakes up the first thread that called wait( ) on the same object.

    notifyAll( ) wakes up all the threads that called wait( ) on the same object. The highest prioritythread will run first.

    These methods are declared within Object, as shown here:

    final void wait( ) throws InterruptedException

    final void notify( )

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    26/54

    MI0032-Java and Web Design

    final void notifyAll( )

    Additional forms ofwait( ) exist that allow you to specify a period of time to wait. The followingsample program incorrectly implements a simple form of the producer/consumer problem. Itconsists of four classes: Q, the queue that youre trying to synchronize; Producer, the threadedobject that is producing queue entries; Consumer, the threaded object that is consuming queue

    entries; and PC, the tiny class that creates the single Q, Producer, and Consumer.

    // An incorrect implementation of a producer and consumer.

    class Q {

    int n;

    synchronized int get() {

    System.out.println("Got: " + n);

    return n;

    }

    synchronized void put(int n) {

    this.n = n;

    System.out.println("Put: " + n);

    }

    }

    class Producer implements Runnable {

    Q q;

    Producer(Q q) {

    this.q = q;

    new Thread(this, "Producer").start();

    }

    public void run() {

    int i = 0;

    while(true) {

    q.put(i++);

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    27/54

    MI0032-Java and Web Design

    }

    }

    }

    class Consumer implements Runnable {

    Q q;

    Consumer(Q q) {

    this.q = q;

    new Thread(this, "Consumer").start();

    }

    public void run() {

    while(true) {

    q.get();

    }

    }

    }

    class PC {

    public static void main(String args[]) {

    Q q = new Q();

    new Producer(q);

    new Consumer(q);

    System.out.println("Press Control-C to stop.");

    }

    }

    Although the put( ) and get( ) methods on Q are synchronized, nothing stops the producer fromoverrunning the consumer, nor will anything stop the consumer from consuming the same queuevalue twice. Thus, you get the erroneous output shown here (the exact output will vary withprocessor speed and task load):

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    28/54

    MI0032-Java and Web Design

    Put: 1

    Got: 1

    Got: 1

    Got: 1

    Got: 1

    Got: 1

    Put: 2

    Put: 3

    Put: 4

    Put: 5

    Put: 6

    Put: 7

    Got: 7

    As you can see, after the producer put 1, the consumer started and got the same 1 five times in arow. Then, the producer resumed and produced 2 through 7 without letting the consumer have achance to consume them.

    The proper way to write this program in Java is to use wait( ) and notify( ) to signal in bothdirections, as shown here:

    // A correct implementation of a producer and consumer.

    class Q {

    int n;

    boolean valueSet = false;

    synchronized int get() {

    if(!valueSet)

    try {

    wait();

    } catch(InterruptedException e) {

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    29/54

    MI0032-Java and Web Design

    System.out.println("InterruptedException caught");

    }

    System.out.println("Got: " + n);

    valueSet = false;

    notify();

    return n;

    }

    synchronized void put(int n) {

    if(valueSet)

    try {

    wait();

    } catch(InterruptedException e) {

    System.out.println("InterruptedException caught");

    }

    this.n = n;

    valueSet = true;

    System.out.println("Put: " + n);

    notify();

    }

    }

    class Producer implements Runnable {

    Q q;

    Producer(Q q) {

    this.q = q;

    new Thread(this, "Producer").start();

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    30/54

    MI0032-Java and Web Design

    }

    public void run() {

    int i = 0;

    while(true) {

    q.put(i++);

    }

    }

    }

    class Consumer implements Runnable {

    Q q;

    Consumer(Q q) {

    this.q = q;

    new Thread(this, "Consumer").start();

    }

    public void run() {

    while(true) {

    q.get();

    }

    }

    }

    class PCFixed {

    public static void main(String args[]) {

    Q q = new Q();

    new Producer(q);

    new Consumer(q);

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    31/54

    MI0032-Java and Web Design

    System.out.println("Press Control-C to stop.");

    }

    }

    Inside get( ), wait( ) is called. This causes its execution to suspend until the Producernotifiesyou that some data is ready. When this happens, execution inside get( ) resumes. After the datahas been obtained, get( ) calls notify( ). This tells Producerthat it is okay to put more data in thequeue. Inside put( ), wait( ) suspends execution until the Consumerhas removed the item fromthe queue. When execution resumes, the next item of data is put in the queue, and notify( ) iscalled. This tells the Consumerthat it should now remove it. Here is some output from thisprogram, which shows the clean synchronous behavior:

    Put: 1

    Got: 1

    Put: 2

    Got: 2

    Put: 3

    Got: 3

    Put: 4

    Got: 4

    Put: 5

    Got: 5

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    32/54

    MI0032-Java and Web Design

    Set II

    Q.1 What are various parameters of an applet tag.

    Ans- The Applet tag is used to embed an applet in an HTML document the Applet tag takes zeroor more parameters.

    The Applet Tag

    The Applet tag is written the Body tag of an HTML document.

    Syntax

    ..

    The most commonly used attributes of the Applet tag are CODE, HEIGHT, WIDTH, CODEBASE

    and ALT. You can send parameters to the applet using the PARAM tag. The PARAM tag must bewritten between and

    Example

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    33/54

    MI0032-Java and Web Design

    Height = 200

    Width = 200 >

    Life Cycle of an Applet

    You can describe the life cycle of an applet through four methods. These methods are:

    The init () method.

    The start () method.

    The stop () method.

    The destroy () method.

    The init ( ) method

    The init () method is called the first time an applet is loaded into the memory of a computer. Youcan initialize variables, and add components like buttons and check boxes to the applet in the init() method.

    The start ( ) method

    The start () method is called immediately after the init () method and every time the appletreceives focus as a result of scrolling in the active window. You can use this method when youwant to restart a process, such as thread animation, every time the applet receives the focus.

    The stop ( ) method

    The stop () method is called every time the applet loses the focus. You can use this method toreset variables and stop the threads that are running.

    The destroy ( ) method

    The destroy ( ) method is called by the browser when the user moves to another page. You canuse this method to perform clean-up operations like closing a file.

    The following diagram depicts the life cycle of an applet.

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image002188.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    34/54

    MI0032-Java and Web Design

    It is not mandatory to use any or all the methods of the applet. These methods are calledautomatically by the Java environment, and hence, must be declared public. None of the methodsaccept parameters. For example,

    public void init ()

    {

    }

    All but the most trivial applets override a set of methods that provides the basic mechanism bywhich the browser or applet viewer interfaces to the applet and controls its execution. Four ofthese methodsinit( ), start( ), stop( ), and destroy( )are defined by Applet. Another, paint( ),is defined by the AWT Component class. Default implementations for all of these methods areprovided. Applets do not need to override those methods they do not use. However, only verysimple applets will not need to define all of them. These five methods can be assembled into theskeleton shown here:

    // An Applet skeleton.

    import java.awt.*;

    import java.applet.*;

    /*

    */

    public class AppletSkel extends Applet {

    // Called first.

    public void init() {

    // initialization

    }

    /* Called second, after init(). Also called whenever

    the applet is restarted. */

    public void start() {

    // start or resume execution

    }

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    35/54

    MI0032-Java and Web Design

    // Called when the applet is stopped.

    public void stop() {

    // suspends execution

    }

    /* Called when applet is terminated. This is the last

    method executed. */

    public void destroy() {

    // perform shutdown activities

    Q.2 Write a short note on following topic:

    a. Knock Knock Protocolb. Datagram

    Ans(a): The Knock Knock Protocol

    The KnockKnockProtocolclass implements the protocol that the client and server use tocommunicate. This class keeps track of where the client and the server are in their conversationand serves up the servers response to the clients statements. The KnockKnockServer objectcontains the text of all the jokes and makes sure that the client gives the proper response to theservers statements. It wouldnt do to have the client say "Dexter who?" when the server says"Knock! Knock!"

    All client/server pairs must have some protocol by which they speak to each other; otherwise, thedata that passes back and forth would be meaningless. The protocol that your own clients andservers use depends entirely on the communication required by them to accomplish the task.

    The Knock Knock Client

    The KnockKnockClient class implements the client program that speaks to theKnockKnockServer. KnockKnockClient is based on the EchoClient program in the previoussection, Reading from and Writing to a Socket and should be somewhat familiar to you. But wellgo over the program anyway and look at whats happening in the client in the context of whatsgoing on in the server.

    When you start the client program, the server should already be running and listening to the port,waiting for a client to request a connection. So, the first thing the client program does is to open asocket that is connected to the server running on the hostname and port specified:

    kkSocket = new Socket("taranis", 4444);out = new PrintWriter(kkSocket.getOutputStream(), true);in = new BufferedReader(new InputStreamReader(

    kkSocket.getInputStream()));

    http://java.sun.com/docs/books/tutorial/networking/sockets/examples/KnockKnockProtocol.javahttp://java.sun.com/docs/books/tutorial/networking/sockets/examples/KnockKnockProtocol.javahttp://java.sun.com/docs/books/tutorial/networking/sockets/examples/KnockKnockClient.javahttp://java.sun.com/docs/books/tutorial/networking/sockets/examples/KnockKnockClient.javahttp://java.sun.com/docs/books/tutorial/networking/sockets/examples/KnockKnockProtocol.java
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    36/54

    MI0032-Java and Web Design

    When creating its socket, KnockKnockClient uses the host name taranis, the name of ahypothetical machine on our network. When you type in and run this program, change the hostname to the name of a machine on your network. This is the machine on which you will run theKnockKnockServer.

    The KnockKnockClient program also specifies the port number 4444 when creating its socket.

    This is a remote port numberthe number of a port on the server machineand is the port towhich KnockKnockServer is listening. The clients socket is bound to any available local portaport on the client machine. Remember that the server gets a new socket as well. That socket isbound to local port number 4444 on its machine. The servers socket and the clients socket areconnected.

    Next comes the while loop that implements the communication between the client and the server.The server speaks first, so the client must listen first. The client does this by reading from theinput stream attached to the socket. If the server does speak, it says "Bye." and the client exitsthe loop. Otherwise, the client displays the text to the standard output and then reads theresponse from the user, who types into the standard input. After the user types a carriage return,the client sends the text to the server through the output stream attached to the socket.

    while ((fromServer = in.readLine()) != null) {System.out.println("Server: " + fromServer);if (fromServer.equals("Bye."))

    break;fromUser = stdIn.readLine();if (fromUser != null) {

    System.out.println("Client: " + fromUser);out.println(fromUser);

    }}

    The communication ends when the server asks if the client wishes to hear another joke, the clientsays no, and the server says "Bye."

    In the interest of good housekeeping, the client closes its input and output streams and thesocket:

    out.close();in.close();stdIn.close();kkSocket.close();

    Running the Programs

    You must start the server program first. To do this, run the server program using the Javainterpreter, just as you would any other Java application. Remember to run the server on themachine that the client program specifies when it creates the socket.

    Next, run the client program. Note that you can run the client on any machine on your network; itdoes not have to run on the same machine as the server.

    If you are too quick, you might start the client before the server has a chance to initialize itself andbegin listening on the port. If this happens, you will see a stack trace from the client. If thishappens, just restart the client.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    37/54

    MI0032-Java and Web Design

    If you forget to change the host name in the source code for the KnockKnockClient program, youwill see the following error message:

    Don't know about host: taranis

    To fix this, modify the KnockKnockClient program and provide a valid host name for your network.

    Recompile the client program and try again.

    If you try to start a second client while the first client is connected to the server, the second clientjust hangs. The next section, Supporting Multiple Clients, talks about supporting multiple clients.

    When you successfully get a connection between the client and server, you will see the followingtext displayed on your screen:

    Server: Knock! Knock!

    Now, you must respond with:

    Who's there?

    The client echoes what you type and sends the text to the server. The server responds with thefirst line of one of the many Knock Knock jokes in its repertoire. Now your screen should containthis (the text you typed is in bold):

    Server: Knock! Knock!Who's there?Client: Who's there?Server: Turnip

    Now, you respond with:

    Turnip who?"

    Again, the client echoes what you type and sends the text to the server. The server responds withthe punch line. Now your screen should contain this:

    Server: Knock! Knock!Who's there?Client: Who's there?Server: TurnipTurnip who?Client: Turnip who?Server: Turnip the heat, it's cold in here! Want another? (y/n)

    If you want to hear another joke, type y; if not, type n. If you type y, the server begins again with"Knock! Knock!" If you type n, the server says "Bye." thus causing both the client and the serverto exit.

    If at any point you make a typing mistake, the KnockKnockServer object catches it and the serverresponds with a message similar to this:

    Server: You're supposed to say "Who's there?"!

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    38/54

    MI0032-Java and Web Design

    The server then starts the joke over again:

    Server: Try again. Knock! Knock!

    Note that the KnockKnockProtocol object is particular about spelling and punctuation but notabout capitalization.

    Supporting Multiple Clients

    To keep the KnockKnockServer example simple, we designed it to listen for and handle a singleconnection request. However, multiple client requests can come into the same port and,consequently, into the same ServerSocket. Client connection requests are queued at the port, sothe server must accept the connections sequentially. However, the server can service themsimultaneously through the use of threads one thread per each client connection.

    The basic flow of logic in such a server is this:

    while (true) {accept a connection ;create a thread to deal with the client ;

    end while

    The thread reads from and writes to the client connection as necessary.

    Ans(b): Datagram

    Clients and servers that communicate via a reliable channel, such as a TCP socket, have adedicated point-to-point channel between themselves, or at least the illusion of one. To

    communicate, they establish a connection, transmit the data, and then close the connection. Alldata sent over the channel is received in the same order in which it was sent. This is guaranteedby the channel.

    In contrast, applications that communicate via datagrams send and receive completelyindependent packets of information. These clients and servers do not have and do not need adedicated point-to-point channel. The delivery of datagrams to their destinations is notguaranteed. Nor is the order of their arrival.

    Definition: A datagram is an independent, self-contained message sent over the network whosearrival, arrival time, and content are not guaranteed.

    The java.net package contains three classes to help you write Java programs that use datagramsto send and receive packets over the network: DatagramSocket, DatagramPacket, andMulticastSocketAn application can send and receive DatagramPackets through aDatagramSocket. In addition, DatagramPackets can be broadcast to multiple recipients alllistening to a MulticastSocket.

    8.3.2 Writing a Datagram Client and Server

    The example featured in this section consists of two applications: a client and a server. Theserver continuously receives datagram packets over a datagram socket. Each datagram packet

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    39/54

    MI0032-Java and Web Design

    received by the server indicates a client request for a quotation. When the server receives adatagram, it replies by sending a datagram packet that contains a one-line "quote of the moment"back to the client.

    The client application in this example is fairly simple. It sends a single datagram packet to theserver indicating that the client would like to receive a quote of the moment. The client then waits

    for the server to send a datagram packet in response.

    Two classes implement the server application: QuoteServer and QuoteServerThread. A singleclass implements the client application: QuoteClient.

    Lets investigate these classes, starting with the class that contains the main method for theserver application. Working with a Server-Side Application contains an applet version of theQuoteClient class.

    The QuoteServer Class

    The QuoteServer class, shown here in its entirety, contains a single method: the main method forthe quote server application. The main method simply creates a new QuoteServerThread object

    and starts it:

    import java.io.*;public class QuoteServer {

    public static void main(String[] args) throws IOException {new QuoteServerThread().start();

    }}

    The QuoteServerThread class implements the main logic of the quote server.

    The QuoteServerThread Class

    When created, the QuoteServerThread creates a DatagramSocket on port 4445 (arbitrarilychosen). This is the DatagramSocket through which the server communicates with all of itsclients.

    public QuoteServerThread() throws IOException {this("QuoteServer");

    }public QuoteServerThread(String name) throws IOException {

    super(name);socket = new DatagramSocket(4445);

    try {

    in = new BufferedReader(new FileReader("one-liners.txt"));

    } catch (FileNotFoundException e)System.err.println("Couldn't open quote file. " +

    "Serving time instead.");}

    }

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    40/54

    MI0032-Java and Web Design

    Remember that certain ports are dedicated to well-known services and you cannot use them. Ifyou specify a port that is in use, the creation of the DatagramSocket will fail.

    The constructor also opens a BufferedReader on a file named one-liners.txt which contains a listof quotes. Each quote in the file is on a line by itself.

    Now for the interesting part of the QuoteServerThread: its run method. The run method overridesrun in the Thread class and provides the implementation for the thread. For information aboutthreads, see Defining and Starting a Thread.

    The run method contains a while loop that continues as long as there are more quotes in the file.During each iteration of the loop, the thread waits for a DatagramPacket to arrive over theDatagramSocket. The packet indicates a request from a client. In response to the clients request,the QuoteServerThread gets a quote from the file, puts it in a DatagramPacket and sends it overthe DatagramSocket to the client that asked for it.

    Lets look first at the section that receives the requests from clients:

    byte[] buf = new byte[256];

    DatagramPacket packet = new DatagramPacket(buf, buf.length);socket.receive(packet);

    The first statement creates an array of bytes which is then used to create a DatagramPacket. TheDatagramPacket will be used to receive a datagram from the socket because of the constructorused to create it. This constructor requires only two arguments: a byte array that contains client-specific data and the length of the byte array. When constructing a DatagramPacket to send overthe DatagramSocket, you also must supply the Internet address and port number of the packetsdestination. Youll see this later when we discuss how the server responds to a client request.

    The last statement in the previous code snippet receives a datagram from the socket (theinformation received from the client gets copied into the packet). The receive method waitsforever until a packet is received. If no packet is received, the server makes no further progressand just waits.

    Now assume that, the server has received a request from a client for a quote. Now the servermust respond. This section of code in the run method constructs the response:

    String dString = null;if (in == null)

    dString = new Date().toString();else

    dString = getNextQuote();buf = dString.getBytes();

    If the quote file did not get opened for some reason, then in equals null. If this is the case, thequote server serves up the time of day instead. Otherwise, the quote server gets the next quotefrom the already opened file. Finally, the code converts the string to an array of bytes.

    Now, the run method sends the response to the client over the DatagramSocket with this code:

    InetAddress address = packet.getAddress();int port = packet.getPort();packet = new DatagramPacket(buf, buf.length, address, port);

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    41/54

    MI0032-Java and Web Design

    socket.send(packet);

    The first two statements in this code segment get the Internet address and the port number,respectively, from the datagram packet received from the client. The Internet address and portnumber indicate where the datagram packet came from. This is where the server must send itsresponse. In this example, the byte array of the datagram packet contains no relevant

    information. The arrival of the packet itself indicates a request from a client that can be found atthe Internet address and port number indicated in the datagram packet.

    The third statement creates a new DatagramPacket object intended for sending a datagrammessage over the datagram socket. You can tell that the new DatagramPacket is intended tosend data over the socket because of the constructor used to create it. This constructor requiresfour arguments. The first two arguments are the same required by the constructor used to createreceiving datagrams: a byte array containing the message from the sender to the receiver and thelength of this array. The next two arguments are different: an Internet address and a port number.These two arguments are the complete address of the destination of the datagram packet andmust be supplied by the sender of the datagram. The last line of code sends the DatagramPacketon its way.

    When the server has read all the quotes from the quote file, the while loop terminates and the runmethod cleans up:

    socket.close();

    The QuoteClient Class

    The QuoteClient class implements a client application for the QuoteServer. This applicationsends a request to the QuoteServer, waits for the response, and, when the response is received,displays it to the standard output. Lets look at the code in detail.

    The QuoteClient class contains one method, the main method for the client application. The topof the main method declares several local variables for its use:

    int port;InetAddress address;DatagramSocket socket = null;DatagramPacket packet;byte[] sendBuf = new byte[256];

    First, the main method processes the command-line arguments used to invoke the QuoteClientapplication:

    if (args.length != 1) {System.out.println("Usage: java QuoteClient ");

    return;}

    The QuoteClient application requires one command-line arguments: the name of the machine onwhich the QuoteServer is running.

    Next, the main method creates a DatagramSocket:

    DatagramSocket socket = new DatagramSocket();

    http://java.sun.com/docs/books/tutorial/networking/datagrams/examples/QuoteClient.javahttp://java.sun.com/docs/books/tutorial/networking/datagrams/examples/QuoteClient.java
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    42/54

    MI0032-Java and Web Design

    The client uses a constructor that does not require a port number. This constructor just binds theDatagramSocket to any available local port. It doesnt matter what port the client is bound tobecause the DatagramPackets contain the addressing information. The server gets the portnumber from the DatagramPackets and send its response to that port.

    Next, the QuoteClient program sends a request to the server:

    byte[ ] buf = new byte[256];InetAddress address = InetAddress.getByName(args[0]);DatagramPacket packet = new DatagramPacket(buf, buf.length,

    address, 4445);socket.send(packet);

    The code segment gets the Internet address for the host named on the command line(presumably the name of the machine on which the server is running). This InetAddress and theport number 4445 (the port number that the server used to create its DatagramSocket) are thenused to create DatagramPacket destined for that Internet address and port number. Therefore theDatagramPacket will be delivered to the quote server.

    Note that the code creates a DatagramPacket with an empty byte array. The byte array is emptybecause this datagram packet is simply a request to the server for information. All the serverneeds to know to send a responsethe address and port number to which replyis automaticallypart of the packet.

    Next, the client gets a response from the server and displays it:

    packet = new DatagramPacket(buf, buf.length);socket.receive(packet);String received = new String(packet.getData(), 0, packet.getLength());System.out.println("Quote of the Moment: " + received);

    To get a response from the server, the client creates a "receive" packet and uses theDatagramSocket receive method to receive the reply from the server. The receive method waitsuntil a datagram packet destined for the client comes through the socket. Note that if the serversreply is somehow lost, the client will wait forever because of the no-guarantee policy of thedatagram model. Normally, a client sets a timer so that it doesnt wait forever for a reply; if noreply arrives, the timer goes off and the client retransmits.

    When the client receives a reply from the server, the client uses the getData method to retrievethat data from the packet. The client then converts the data to a string and displays it.

    Running the Server and Client

    After youve successfully compiled the server and the client programs, you run them. You have to

    run the server program first. Just use the Java interpreter and specify the QuoteServer classname.

    Once the server has started, you can run the client program. Remember to run the client programwith one command-line argument: the name of the host on which the QuoteServer is running.

    After the client sends a request and receives a response from the server, you should see outputsimilar to this:

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    43/54

    MI0032-Java and Web Design

    Quote of the Moment:Good programming is 99% sweat and 1% coffee.

    Q.3 What are the different access specifiers in Java? How can we call a superclassconstructor? Explain with a suitable example.

    Ans:Access Specifiers

    An access specifier determines which features of a class (the class itself, the data members, andthe methods) may be used by other classes. Java supports three access specifiers.

    public.

    private.

    protected.

    ThepublicAccess Specifiers

    All classes except inner class (class within classes) can have the public access specifier. You canuse a public class, a data member, or a method from any object in any Java program.

    Example

    public class publicclass

    {

    public int publicvaraible;

    public void publicmethod ()

    {

    }

    }

    Theprivate Access Specifier

    Only objects of the same class can access a private variable or method. You can declare onlyvariables, methods, and inner classes as private.

    Example

    private int privatevariable;

    TheprotectedAccess Specifier

    The variables, methods, and inner classes that are declared protected are accessible to thesubclasses of the class in which they are declared.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    44/54

    MI0032-Java and Web Design

    Example

    protected int protectedvariable;

    Default Access

    If you do not specify any of the above access specifiers, the scope is friendly. A class, variable, ormethod that has friendly access is accessible to all the classes of a package.

    Consider the following set of classes. Class Y and Z inherit from class X. Class Z belongs to apackage different than that of classes X and Y

    A method accessMe () has been declared in class X. The following table shows you theaccessibility of the method accessMe () from classes Y and Z

    Access Specifier Class Y Class Z

    accessME ( ) isdeclared as protected

    Accessible, as Y is asubclass

    Accessible, as Z is a subclass(event if it is in anotherpackage)

    accessMe ( ) isdeclared without an

    access specifier(friendly)

    Accessible, as it is in thesame package

    Not accessible, as it is not inthe same package

    You can access a non-private variable or method using an object of the class as shown below:

    Someclass classobject = new someclass ();

    classobject.publicvariable;

    classobject.protectedmethod ();

    Although a subclass includes all of the members of its superclass, it cannot access those

    members of the superclass that have been declared as private. For example, consider thefollowing simple class hierarchy:

    /* In a class hierarchy, private members remain

    private to their class.

    This program contains an error and will not

    http://resources.smude.edu.in/slm/wp-content/uploads/2009/06/clip-image00858.jpg
  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    45/54

    MI0032-Java and Web Design

    compile.

    */

    // Create a superclass.

    class A {

    int i; // public by default

    private int j; // private to A

    void setij(int x, int y) {

    i = x;

    j = y;

    }

    }

    // As j is not accessible here.

    class B extends A {

    int total;

    void sum() {

    total = i + j; // ERROR, j is not accessible here

    }

    }

    class Access {

    public static void main(String args[]) {

    B subOb = new B();

    subOb.setij(10, 12);

    subOb.sum();

    System.out.println("Total is " + subOb.total);

    }

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    46/54

    MI0032-Java and Web Design

    }

    This program will not compile because the reference toj inside the sum( ) method ofB causesan access violation. Sincej is declared as private, it is only accessible by other members of itsown class. Subclasses have no access to it.

    Note: A class member that has been declared as private will remain private to its class. It is notaccessibl e by any code outside its class, including subclasses.

    A Superclass Variable Can Reference a Subclass Object

    A reference variable of a superclass can be assigned a reference to any subclass derived fromthat superclass. You will find this aspect of inheritance quite useful in a variety of situations. Forexample, consider the following:

    class Ref Demo {

    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);

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    47/54

    MI0032-Java and Web Design

    }

    }

    Here, weightbox is a reference to BoxWeight objects, and plainbox is a reference to Boxobjects. Since BoxWeight is a subclass ofBox, it is permissible to assign plainbox a reference

    to the weightbox object.

    It is important to understand that it is the type of the reference variable not the type of the objectthat it refers to that determines what members can be accessed. That is, when a reference to asubclass object is assigned to a superclass reference variable, you will have access only to thoseparts of the object defined by the superclass. This is why plainbox cant access weight evenwhen it refers to a BoxWeight object. If you think about it, this makes sense, because thesuperclass has no knowledge of what a subclass adds to it. This is why the last line of code in thepreceding fragment is commented out. It is not possible for a Box reference to access the weightfield, because it does not define one.

    Although the preceding may seem a bit esoteric, it has some important practical applications two of which are discussed later in this chapter.

    Using super

    In the preceding examples, classes derived from Box were not implemented as efficiently or asrobustly as they could have been. For example, the constructor forBoxWeight explicitlyinitializes the width, height, and depth fields ofBox( ). Not only does this duplicate code foundin its superclass, which is inefficient, but it implies that a subclass must be granted access tothese members. However, there will be times when you will want to create a superclass thatkeeps the details of its implementation to itself (that is, that keeps its data members private). Inthis case, there would be no way for a subclass to directly access or initialize these variables onits own. Since encapsulation is a primary attribute of OOP, it is not surprising that Java provides asolution to this problem. Whenever a subclass needs to refer to its immediate superclass, it cando so by use of the keyword super.

    superhas two general forms. The first calls the superclass constructor. The second is used toaccess a member of the superclass that has been hidden by a member of a subclass. Each useis examined here.

    Using super to Call Superclass Constructors

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

    super(parameter-list);

    Here,parameter-listspecifies any parameters needed by the constructor in the superclass.super( ) must always be the first statement executed inside a subclass constructor. To see howsuper( ) is used, consider this improved version of the BoxWeight( ) class:

    // BoxWeight now uses super to initialize its Box attributes.

    class BoxWeight extends Box {

    double weight; // weight of box

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    48/54

    MI0032-Java and Web Design

    // initialize width, height, and depth using super()

    BoxWeight(double w, double h, double d, double m) {

    super(w, h, d); // call superclass constructor

    weight = m;

    }

    }

    Here, BoxWeight( ) calls super( ) with the parameters w, h, and d. This causes the Box( )constructor to be called, which initializes width, height, and depth using these values.BoxWeight no longer initializes these values itself. It only needs to initialize the value unique to it:weight. This leaves Box free to make these values private if desired.

    In the preceding example, super( ) was called with three arguments. Since constructors can be

    overloaded, super( ) can be called using any form defined by the superclass. The constructorexecuted will be the one that matches the arguments. For example, here is a completeimplementation ofBoxWeight that provides constructors for the various ways that a box can beconstructed. In each case, super( ) is called using the appropriate arguments. Notice that width,height, and depth have been made private within Box.

    // 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;

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    49/54

    MI0032-Java and Web Design

    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;

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    50/54

    MI0032-Java and Web Design

    }

    // 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;

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    51/54

    MI0032-Java and Web Design

    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

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    52/54

    MI0032-Java and Web Design

    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

    Pay special attention to this constructor in BoxWeight( ):

    // construct clone of an object

    BoxWeight(BoxWeight ob) { // pass object to constructor

    super(ob);

    weight = ob.weight;

    }

    Notice that super( ) is called with an object of type BoxWeight not of type Box. This stillinvokes the constructorBox(Box ob). As mentioned earlier, a superclass variable can be used to

    reference any object derived from that class. Thus, we are able to pass a BoxWeight object tothe Box constructor. Of course, Box only has knowledge of its own members.

    Lets review the key concepts behind super( ). When a subclass calls super( ), it is calling theconstructor of its immediate superclass. Thus, super( ) always refers to the superclassimmediately above the calling class. This is true even in a multileveled hierarchy. Also, super( )must always be the first statement executed inside a subclass constructor.

    A Second Use for super

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

    super.member

    Here, membercan be either a method or an instance variable.

    This second form ofsuperis most applicable to situations in which member names of a subclasshide members by the same name in the superclass. Consider this simple class hierarchy:

    // Using super to overcome name hiding.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    53/54

    MI0032-Java and Web Design

    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();

    }

    }

    This program displays the following:

    i in superclass: 1

    i in subclass: 2

    Although the instance variable i in B hides the i in A, superallows access to the i defined in thesuperclass. As you will see, supercan also be used to call methods that are hidden by asubclass.

  • 8/6/2019 MI 0032-57568118-MI0032-Solved

    54/54

    MI0032-Java and Web Design