mc0078 set 1 july2011

  • Upload
    killer1

  • View
    219

  • Download
    1

Embed Size (px)

Citation preview

  • 8/3/2019 mc0078 set 1 july2011

    1/42

    July 2011

    Master of Computer Application (MCA) Semester 4MC0078 Java Programming 4 Credits

    (Book ID: B0831 & B0832)

    Assignment Set

    1 (40 Marks)

    1. Write a program to perform the basic arithmetic operations:a) Additionb) Subtractionc) Multiplicationd) DivisionUse 4 different methods for the above and invoke them as necessary from the main()

    method.

    Ans:

    /**

    * Arithmetic Operations

    */

    public class ArithmeticTest { /**

    * Arithmetic Operations

    */

    public class ArithmeticTest {

    public static void main(String[] args) {

    int number1 = 98; // Declare an int variable number1 and initialize it to 98

    int number2 = 5; // Declare an int variable number2 and initialize it to 5

    int sum, difference, product, quotient; // Declare four int variables to hold results

    // Perform arithmetic Operations

  • 8/3/2019 mc0078 set 1 july2011

    2/42

    sum = number1 + number2;

    difference = number1 - number2;

    product = number1 * number2;

    quotient = number1 / number2;

    System.out.print("The sum, difference, product and quotient of "); // Print description

    System.out.print(number1); // Print the value of the variable

    System.out.print(" and ");

    System.out.print(number2);

    System.out.print(" are ");

    System.out.print(sum);

    System.out.print(", ");

    System.out.print(difference);

    System.out.print(", ");

    System.out.print(product);

    System.out.print(", and ");

    System.out.println(quotient);

    }

    }

    Output -

    The sum, difference, product and quotient of 98 and 5 are 103, 93, 490 and 19

  • 8/3/2019 mc0078 set 1 july2011

    3/42

    2. Discuss the following with suitable example programs for each:A) Data Types in JavaB) Variables in Java

    Ans:

    Data Types in Java

    There are two kinds of data types in Java

    Primitives/standard data types.

    Abstract/derived data types.

    Primitives Data Types

    Primitive data types (also know as standard data types) are the data types that are built into the Java

    language. The Java compiler holds details instructions on each operation the data types that are built intothe Java language. The Java compiler holds detailed instructions on each legal operation the data typesupports. There are eight primitive data types in Java.

    The data typesbyte, short, int, long, float and double are numeric data types. The first four of these can

    hold only whole numbers whereas the last two (float and double) can hold decimal values like 5.05. Allthese data types can hold negative values. However, the keyword unsigned can be used to restrict therange of values to positive numbers. Amongst others, boolean can hold only the value true or false andchar can hold only a single character.

    Abstract/Derived Data Types

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00832.jpg
  • 8/3/2019 mc0078 set 1 july2011

    4/42

    Abstract data types are based on primitives data types and have more functionality that the primitive datatypes. For example, String is an abstract data type that can store alphabets, digits and other characters like/, (); :$#. You cannot perform calculations on a variable of the string data type even if the data stored in ithas digits.

    Variables in Java

    When you learned algebraic equations in school, you used x and y to represent values in equations.Unlike pi which has a constant value of 3.14, the values of x and y are not constant in equations. Javaprovides constants and variables to store data in programs.

    Java allocates memory to each variable and constant you use in your program. As in algebra, the values ofvariables may change in a program, but the values of constants, as the name suggests, do not change. Youmust assign unique names to variables and constants. Variable names are used in a program in much thesame way as they are in ordinary Algebra.

    Each variable used in a program must be declared. That is to say, the program must contain a statementspecifying precisely what kind of information (data type) the variable will contain. This applies to every

    variable used in the program, regardless of the type.

    Naming Variables

    A program refers to a variable using its name. Certain rules and conventions govern the naming ofvariables. You must adhere to rules. Conventions help improve the readability of the program, butfollowing them is not mandatory.

    Rules for Naming Variables in Java

    A variable name:

    Must not be a keyword in Java.

    Must not begin with a digit.

    Must not contain embedded spaces.

    Can contain characters from various alphabets, like Japanese, Greek, and Cyrillic.

    Syntax for Defining Variables

    All the attributes of a class are defined as data members. The syntax used to declare a class variable is:

    As the braces { } are used to markthe beginning and end of a class, a semicolon ; is used to mark theend of a statement.

  • 8/3/2019 mc0078 set 1 july2011

    5/42

    3. What are the different types of control statements?

    Ans:

    Control Flow Statements

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

    1. Decision Making Statements

    If-else statement

    Switchcase statement

    2. Looping Statement

    For loop

    While loop

    Do-while loop

    3. Other statement

    Break

    Continue

    Label

    If-else statement

    The ifstatement is Javas conditional branch statement. It can be used to route program execution throughtwo different paths. Here is the general form of the if statement:

    if (condition) statement1;

    else statement2;

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

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

  • 8/3/2019 mc0078 set 1 july2011

    6/42

    Most often, the expression used to control the if will involve the relational operators. However, this is not

    technically necessary. It is possible to control the if using a single boolean variable, as shown in this codefragment:

    boolean dataAvailable;

    //

    if (dataAvailable)

    ProcessData();

    else

    waitForMoreData();

    Remember, only one statement can appear directly after the if or the else. If you want to include morestatements, 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/2010/07/clip-image01226.jpg
  • 8/3/2019 mc0078 set 1 july2011

    7/42

    Here, both statements within the if block will execute if bytesAvailable is greater than zero. Someprogrammers find it convenient to include the curly braces when using the if, even when there is only onestatement in each clause. This makes it easy to add another statement at a later date, and you dont have toworry about forgetting the braces. In fact, forgetting to define a block when one is needed is a commoncause 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 the else clause,because of the indentation level. However, as you recall, whitespace is insignificant to Java, and there isno way for the compiler to know what was intended. This code will compile without complaint, but it willbehave 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/3/2019 mc0078 set 1 july2011

    8/42

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

    if ladder. It looks like this:

    if(condition)

    statement;

    else if(condition)

    statement;

    else if(condition)

    statement;

    .

    .

    .

    else

    statement;

    The if statements are executed from the top down. As soon as one of the conditions controllingthe if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. Ifnone of the conditions is true, then the final else statement will be executed. The final else acts as a

    default condition; that is, if all other conditional tests fail, then the last else statement is performed. Ifthere is no final elseand all other conditions are false, then no action will take place.

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

    // 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/3/2019 mc0078 set 1 july2011

    9/42

    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 matter whatvalue you give month, one and only one assignment statement within the ladder will be executed.

    Switch Statement

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

    As such, it often provides a better alternative than a large series of if-else-if statements.

    Here is the general form of a switch statement:

    switch (expression) {

    case value1:

    // statement sequence

    break;

    case value2:

    // statement sequence

    break;

  • 8/3/2019 mc0078 set 1 july2011

    10/42

    .

    .

    .

    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 statementsmust be of a type compatible with the expression. Each case value must be a unique literal (that is, it mustbe 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 the literalvalues in the case statements. If a match is found, the code sequence following that case statement isexecuted. If none of the constants matches the value of the expression, then thedefault statement isexecuted. However, the default statement is optional. If no case matches and no default is present, then nofurther action is taken.

    The break statement is used inside the switch to terminate a statement sequence. When a break statement

    is encountered, execution branches to the first line of code that follows the entire switch statement. Thishas the effect of "jumping out" of the switch.

    Example

  • 8/3/2019 mc0078 set 1 july2011

    11/42

    The break statement is optional. If you omit the break, execution will continue on into the next case. It issometimes desirable to have multiplecases without break statements between them. For example, considerthe following program:

    // In a switch, break statements are optional.

    class MissingBreak {

    public static void main(String args[ ]) {

    for(int i=0; i

  • 8/3/2019 mc0078 set 1 july2011

    12/42

    case 6:

    case 7:

    case 8:

    case 9:

    System.out.println("i is less than 10");

    break;

    default:

    System.out.println("i is 10 or more");

    }

    }

    }

    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

  • 8/3/2019 mc0078 set 1 july2011

    13/42

    You can use a switch as part of the statement sequence of an outer switch. This is called a nested switch.Since a switch statement defines its own block, no conflicts arise between the case constants in theinner switch and those in the outer switch. For example, the following fragment 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;

    }

    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 the outer level. If count is 1,then target is compared with the inner list cases.

    In summary, there are three important features of the switch statement to note:

    The switch differs from the if in that switch can only test for equality, whereas if can evaluate any type ofBoolean expression. That is, theswitch looks only for a match between the value of the expression andone of its case constants.

    No two case constants in the same switch can have identical values. Of course, a switch statementenclosed by an outer switch can have caseconstants 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. Whenit compiles a switch statement, the Java compiler will inspect each of the case constants and create a"jump table" that it will use for selecting the path of execution depending on the value of the expression.Therefore, if you need to select among a large group of values, a switch statement will run much fasterthan the equivalent logic coded using a sequence of if-elses. The compiler can do this because it knowsthat the case constants are all the same type and simply must be compared for equality withthe switch expression. The compiler has no such knowledge of a long list of if expressions.

  • 8/3/2019 mc0078 set 1 july2011

    14/42

    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 inside flowerbraces. for (initial statement; termination condition; increment instruction)

    {

    statement1;

    statement2;

    }

    The example below prints numbers from 1 to 10

    The results of the above program is shown below

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image01619.jpg
  • 8/3/2019 mc0078 set 1 july2011

    15/42

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

    // Loops may be nested.

    class Nested {

    public static void main(String args[ ]) {

    int i, j;

    for(i=0; i

  • 8/3/2019 mc0078 set 1 july2011

    16/42

    ..

    While Statement

    The while loop is Javas most fundamental looping statement. It repeats a statement or block while itscontrolling expression is true. Here is its general form:

    while (condition) {

    // body of loop

    }

    The condition can be any Boolean expression. The body of the loop will be executed as long as theconditional expression is true. When conditionbecomes false, control passes to the next line of codeimmediately following the loop. The curly braces are unnecessary if only a single statement is beingrepeated.

    Example

    do.while statement

    As you just saw, if the conditional expression controlling a while loop is initially false, then the body ofthe loop will not be executed at all. However, sometimes it is desirable to execute the body ofa while loop at least once, even if the conditional expression is false to begin with. In other words, thereare times when you would like to test the termination expression at the end of the loop rather than at thebeginning. Fortunately, Java supplies a loop that does just that: the do-while. The do-while loop alwaysexecutes its body at least once, because its conditional expression is at the bottom of the loop. Its generalform is

  • 8/3/2019 mc0078 set 1 july2011

    17/42

    do {

    // body of loop

    } while (condition);

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

    Example

    The do-while loop is especially useful when you process a menu selection, because you will usually want

    the body of a menu loop to execute at least once. Consider the following program which implements avery simple help system for Javas selection and iterationstatements:

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

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image02215.jpg
  • 8/3/2019 mc0078 set 1 july2011

    18/42

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

  • 8/3/2019 mc0078 set 1 july2011

    19/42

    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

    The do-while

    do {

  • 8/3/2019 mc0078 set 1 july2011

    20/42

    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 theuser is reprompted. Since the menu must be displayed at least once, the do-while is the perfect loop to

    accomplish this.

    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 console I/Omethods wont be discussed in detail until System.in.read( ) is used here to obtain the users choice. Itreads characters from standard input (returned as integers, which is why the return value was cast to char).By default, standard input is line buffered, so you must press ENTER before any characters that you typewill be sent to your program.

    Javas console input is quite limited and awkward to work with. Further, most real-world Java programsand applets will be graphical and window-based. For these reasons, not much use of console input hasbeen 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 tohandle input errors.

    Break statement

    By using break, you can force immediate termination of a loop, bypassing the conditional expression andany remaining code in the body of the loop. When a break statement is encountered inside a loop, the loopis terminated and program control resumes at the next statement following the loop. Here is a simpleexample:

    // Using break to exit a loop.

    class BreakLoop {

    public static void main(String args[ ]) {

    for(int i=0; i

  • 8/3/2019 mc0078 set 1 july2011

    21/42

    i: 0

    i: 1

    i: 2

    i: 3

    i: 4

    i: 5

    i: 6

    i: 7

    i: 8

    i: 9

    Loop complete.

    As you can see, although the for loop is designed to run from 0 to 99, the break statement causes it toterminate early, when i equal 10.

    Continue Statement

    Sometimes it is useful to force an early iteration of a loop. That is, you might want to continue runningthe loop, but stop processing the remainder of the code in its body for this particular iteration. This is, in

    effect, a goto just past the body of the loop, to the loops end. Thecontinue statement performs such anaction. In while and do-while loops, a continue statement causes control to be transferred directly to theconditional expression that controls the loop. In a for loop, control goes first to the iteration portion ofthe for statement and then to the conditional expression. For all three loops, any intermediate code isbypassed.

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

    // Demonstrate continue.

    class Continue {

    public static void main (String args[]) {

    for (int i=0; i

  • 8/3/2019 mc0078 set 1 july2011

    22/42

    System.out.println ("");

    }

    }

    }

    This code uses the % operator to check if i is even. If it is, the loop continues without printing a newline.Here is the output from this program:

    0 1

    2 3

    4 5

    6 7

    8 9

    As with thebreakstatement,continuemay specify a label to describe which enclosing loops tocontinue. Here is an example program that uses continueto print a triangular multiplication tablefor 0 through 9.

    4. Describe the following with respect to Exception Handling:A) Exception Classes B) Common Exceptions

    Ans:

    (A)Exception Classes:

    The class at the top of the exception classes hierarchy is called Throwable. Two classes are derived from

    the Throwable class- Error and Exception. The Exception class is used from the exceptional conditions

    that have to Be trapped in a program. The Error class defines a condition that does Not occur under

    normal circumstances. In other words, the Error class is used for catastrophic failures such as

    VirtualMachineError. These classes are available in the java.lang package.

    (B)Common Exceptions:

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

    described below.

    Arithmetic Exception

  • 8/3/2019 mc0078 set 1 july2011

    23/42

    This exception is thrown when an exceptional arithmetic condition has occurred. For example, a division

    by zero generates such an exception.

    Null Pointer Exception

    This exception is thrown when an application attempts to use null where an object is required. An

    object that has not been allocated memory holds a null value. The situations in which an exception is

    thrown include:

    ods of a null object.

    ArrayIndexOutOfBounds Exception

    The exception ArrayIndexOutOfBounds Exception is thrown when an attempt is made to access an array

    element beyond the index of the array. For example, if you try to access the eleventh element of an

    array thats has only ten elements, the exception will be thrown.

    5. What is the difference between bound property and constraint property?

    Ans:

    Bound Properties

    Bound propertiessupport the PropertyChangeListener (in the API reference documentation)class.

    Sometimes when a Bean property changes, another object might need to be notified of the change, and

    react to the change.Whenever a bound property changes, notification of the change is sent to interested listeners.

    The accessor methods for a bound property are defined in the same way as those for simple properties.However, you also need to provide the event listener registration methods

    forPropertyChangeListener classes and fire a PropertyChangeEvent (in the API reference

    documentation) event to the PropertyChangeListenerobjects by calling

    their propertyChangemethods

  • 8/3/2019 mc0078 set 1 july2011

    24/42

    The convenience PropertyChangeSupport (in the API reference documentation) class enables yourbean to implement these methods. Your bean can inherit changes from

    the PropertyChangeSupportclass, or use it as an inner class.In order to listen for property changes, an object must be able to add and remove itself from the listenerlist on the bean containing the bound property. It must also be able to respond to the event notificationmethod that signals a property change.

    The PropertyChangeEvent class encapsulates property change information, and is sent from theproperty change event source to each object in the property change listener list with

    the propertyChangemethod.

    Implementing Bound Property Support within a Bean

    To implement a bound property in your application, follow these steps:

    1. Import the java.beans package. This gives you access to the PropertyChangeSupport class.

    2. Instantiate a PropertyChangeSupportobject. This object maintains the property change listenerlist and fires property change events. You can also make your class

    a PropertyChangeSupport subclass.3. Implement methods to maintain the property change listener list. Since

    a PropertyChangeSupport subclass implements these methods, you merely wrap calls to theproperty-change support objects methods.4. Modify a propertys set method to fire a property change event when the property is changed.

    Creating a Bound Property

    To create the title property as a bound property for the MyBean component in the NetBeans GUI Builder,perform the following sequence of operations:

    1. Right-click the Bean Patterns node in the MyBean class hierarchy.

    2. Select Add|Property from the pop-up menu.3. Fill the New Property Pattern form as shown on the following figure and click OK.

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image0252.jpg
  • 8/3/2019 mc0078 set 1 july2011

    25/42

    Fig. 6.6.1

    Note that the title property and the multicast event source pattern PropertyChangeListenerwereadded to the Bean Patterns structure.You can also modify existing code generated in the previous lesson to convert the title and linesproperties to the bound type as follows (where newly added code is shown in bold):

    import java.awt.Graphics;

    import java.beans.PropertyChangeListener;import java.beans.PropertyChangeSupport;import java.io.Serializable;

    import javax.swing.JComponent;

    /**

    * Bean with bound properties.

    */

    public class MyBean

    extends JComponent

    implements Serializable

    {

    private String title;

    private String[] lines = new String[10];

    private final PropertyChangeSupport pcs = new PropertyChangeSupport( this );

    public String getTitle()

    {

    return this.title;

    }

    public void setTitle( String title )

    {String old = this.title;this.title = title;

    this.pcs.firePropertyChange( "title", old, title );}

    public String[] getLines()

    {

    return this.lines.clone();

    }

  • 8/3/2019 mc0078 set 1 july2011

    26/42

    public String getLines( int index )

    {

    return this.lines[index];

    }

    public void setLines( String[] lines )

    {

    String[] old = this.lines;this.lines = lines;

    this.pcs.firePropertyChange( "lines", old, lines );}

    public void setLines( int index, String line ){

    String old = this.lines[index];this.lines[index] = line;this.pcs.fireIndexedPropertyChange( "lines", index, old, lines );

    }public void addPropertyChangeListener( PropertyChangeListener listener )

    {this.pcs.addPropertyChangeListener( listener );

    }public void removePropertyChangeListener( PropertyChangeListener listener )

    {this.pcs.removePropertyChangeListener( listener );

    }

    protected void paintComponent( Graphics g )

    {

    g.setColor( getForeground() );

    int height = g.getFontMetrics().getHeight();

    paintString( g, this.title, height );

    if ( this.lines != null )

    {

    int step = height;

    for ( String line : this.lines )

    paintString( g, line, height += step );

    }

  • 8/3/2019 mc0078 set 1 july2011

    27/42

    }

    private void paintString( Graphics g, String str, int height )

    {

    if ( str != null )

    g.drawString( str, 0, height );

    }

    }

    Constrained Properties

    A bean property is constrainedif the bean supports the Vetoable ChangeListener(in the API

    reference documentation) and Property ChangeEvent(in the API reference documentation) classes,

    and if the set method for this property throws a PropertyVetoException(in the API referencedocumentation).

    Constrained properties are more complicated than bound properties because they also support propertychange listeners which happen to be vetoers.

    The following operations in the setXXXmethod for the constrained property must be implemented inthis order:1. Save the old value in case the change is vetoed.

    2. Notify listeners of the new proposed value, allowing them to veto the change.

    3. If no listener vetoes the change (no exception is thrown), set the property to the new value.

    The accessor methods for a constrained property are defined in the same way as those for simple

    properties, with the addition that the setXXXmethod throws a PropertyVetoException exception.The syntax is as follows:

    public void setPropertyName(PropertyType pt)

    throws PropertyVetoException {code}

    Handling Vetoes

    If a registered listener vetoes a proposed property change by throwing

    a PropertyVetoException exception, the source bean with the constrained property is responsiblefor the following actions: Catching exceptions.

    Reverting to the old value for the property.

    Issuing a new VetoableChangeListener.vetoableChangecall to all listeners to report thereversion.

    The VetoableChangeListener class throws a PropertyVetoException and handles

    the PropertyChangeEvent event fired by the bean with the constrained property.

    The VetoableChangeSupportprovides the following operations:

    Keeping track ofVetoableChangeListenerobjects.

    Issuing the vetoableChangemethod on all registered listeners. Catching any vetoes (exceptions) thrown by listeners.

  • 8/3/2019 mc0078 set 1 july2011

    28/42

    Informing all listeners of a veto by calling vetoableChange again, but with the old property value asthe proposed "new" value.Creating a Constrained Property

    To create a constrained property, set the appropriate option in the New Property Pattern form as shown onthe following figure.

    Fig. 6.7.1

    Note that the Multicast Source Event Pattern vetoableChangeListener was added to the Bean Patternshierarchy.

    You can also modify the existing code generated in the previous lesson to make

    the title and lines properties constrained as follows (where newly added code is shown in bold):import java.io.Serializable;import java.beans.PropertyChangeListener;

    import java.beans.PropertyChangeSupport;

    import java.beans.PropertyVetoException;import java.beans.VetoableChangeListener;import java.beans.VetoableChangeSupport;import java.awt.Graphics;import javax.swing.JComponent;

    /**

    * Bean with constrained properties.

    */

    public class MyBean

    extends JComponent

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image0272.jpg
  • 8/3/2019 mc0078 set 1 july2011

    29/42

    implements Serializable

    {

    private String title;

    private String[] lines = new String[10];

    private final PropertyChangeSupport pcs = new PropertyChangeSupport( this );

    private final VetoableChangeSupport vcs = new VetoableChangeSupport( this );public String getTitle()

    {

    return this.title;

    }

    /**

    * This method was modified to throw the PropertyVetoException

    * if some vetoable listeners reject the new title value

    */

    public void setTitle( String title )

    throws PropertyVetoException{

    String old = this.title;

    this.vcs.fireVetoableChange( "title", old, title );this.title = title;

    this.pcs.firePropertyChange( "title", old, title );

    }

    public String[] getLines()

    {

    return this.lines.clone();

    }

    public String getLines( int index )

    {

    return this.lines[index];

    }

    /**

  • 8/3/2019 mc0078 set 1 july2011

    30/42

    * This method throws the PropertyVetoException

    * if some vetoable listeners reject the new lines value

    */

    public void setLines( String[] lines )

    throws PropertyVetoException{

    String[] old = this.lines;

    this.vcs.fireVetoableChange( "lines", old, lines );this.lines = lines;

    this.pcs.firePropertyChange( "lines", old, lines );

    }

    public void setLines( int index, String line )

    throws PropertyVetoException

    {

    String old = this.lines[index];

    this.vcs.fireVetoableChange( "lines", old, line );this.lines[index] = line;

    this.pcs.fireIndexedPropertyChange( "lines", index, old, line );

    }

    public void addPropertyChangeListener( PropertyChangeListener listener )

    {

    this.pcs.addPropertyChangeListener( listener );

    }

    public void removePropertyChangeListener( PropertyChangeListener listener )

    {

    this.pcs.removePropertyChangeListener( listener );

    }

    /**

    * Registration of the VetoableChangeListener

    */

    public void addVetoableChangeListener( VetoableChangeListener listener ){

  • 8/3/2019 mc0078 set 1 july2011

    31/42

    this.vcs.addVetoableChangeListener( listener );}public void removeVetoableChangeListener( VetoableChangeListener listener ){

    this.vcs.removeVetoableChangeListener( listener );}

    protected void paintComponent( Graphics g )

    {

    g.setColor( getForeground() );

    int height = g.getFontMetrics().getHeight();

    paintString( g, this.title, height );

    if ( this.lines != null )

    {

    int step = height;

    for ( String line : this.lines )

    paintString( g, line, height += step );

    }

    }

    private void paintString( Graphics g, String str, int height )

    {

    if ( str != null )

    g.drawString( str, 0, height );

    }

    }

    6. Define RMI. Define the architecture of RMI invocation

    Ans:

    Remote Method Invocation (RMI)

    Java's native scheme for creating and using remote objects. Java RMI provides the following elements:

  • 8/3/2019 mc0078 set 1 july2011

    32/42

    Remote object implementations Client interfaces, or stubs, to remote objects A remote object registry for finding objects on the network A network protocol for communication between remote objects and their client A facility for automatically creating (activating) remote objects on-demand

    Each of these elements (except the last one) has a Java interface defined for it withinthe java.rmi package and its subpackages, which comprise the RMI API. Using these interfaces, youcan develop remote objects and the clients that use them to create a distributed application that resides onhosts across the network.

    RMI is the distributed object system that is built into the core Java environment. You can think of RMI asa built-in facility for Java that allows you to interact with objects that are actually running in Java virtualmachines on remote hosts on the network. With RMI (and other distributed object APIs we discuss in thisbook), you can get a reference to an object that "lives" in a remote process and invoke methods on it as ifit were a local object running within the same virtual machine as your code (hence the name, "RemoteMethod Invocation API").

    RMI was added to the core Java API in Version 1.1 of the JDK (and enhanced for Version 1.2 of the Java2 platform), in recognition of the critical need for support for distributed objects in distributed-applicationdevelopment. Prior to RMI, writing a distributed application involved basic socket programming, where a"raw" communication channel was used to pass messages and data between two remote processes. Now,with RMI and distributed objects, you can "export" an object as a remote object, so that other remoteprocesses/agents can access it directly as a Java object. So, instead of defining a low-level messageprotocol and data transmission format between processes in your distributed application, you use Javainterfaces as the "protocol" and the exported method arguments become the data transmission format. Thedistributed object system (RMI in this case) handles all the underlying networking needed to make yourremote method calls work.

    Java RMI is a Java-only distributed object scheme; the objects in an RMI-based distributed applicationhave to be implemented in Java. Some other distributed object schemes, most notably CORBA, arelanguage-independent, which means that the objects can be implemented in any language that has adefined binding. With CORBA, for example, bindings exist for C, C++, Java, Smalltalk, and Ada, amongother languages.

    The advantages of RMI primarily revolve around the fact that it is "Java-native." Since RMI is part of thecore Java API and is built to work directly with Java objects within the Java VM, the integration of itsremote object facilities into a Java application is almost seamless. You really can use RMI-enabledobjects as if they live in the local Java environment. And since Java RMI is built on the assumption thatboth the client and server are Java objects, RMI can extend the internal garbage-collection mechanisms ofthe standard Java VM to provide distributed garbage collection of remotely exported objects.

    RMI Architecture

    There are three layers that comprise the basic remote-object communication facilities in RMI:

    The stub/skeleton layer, which provides the interface that client and server application objects useto interact with each other.

  • 8/3/2019 mc0078 set 1 july2011

    33/42

    The remote reference layer, which is the middleware between the stub/skeleton layer and theunderlying transport protocol. This layer handles the creation and management of remote objectreferences.

    The transport protocol layer, which is the binary data protocol that sends remote object requestsover the wire.

    These layers interact with each other as shown in Figure. In this figure, the server is the application thatprovides remotely accessible objects, while the client is any remote application that communicates withthese server objects.

    In a distributed object system, the distinctions between clients and servers can get pretty blurry at times.Consider the case where one process registers a remote-enabled object with the RMI naming service, anda number of remote processes are accessing it. We might be tempted to call the first process the serverand the other processes the clients. But what if one of the clients calls a method on the remote object,passing a reference to an RMI object that's local to the client. Now the server has a reference to and isusing an object exported from the client, which turns the tables somewhat. The "server" is really theserver for one object and the client of another object, and the "client" is a client and a server, too. For thesake of discussion, I'll refer to a process in a distributed application as a server or client if its role in the

    overall system is generally limited to one or the other. In peer-to-peer systems, where there is no clearclient or server, I'll refer to elements of the system in terms of application-specific roles (e.g., chatparticipant, chat facilitator).

  • 8/3/2019 mc0078 set 1 july2011

    34/42

    The RMI architecture

    As you can see in Figure, a client makes a request of a remote object using a client-side stub; the serverobject receives this request from a server-side object skeleton. A client initiates a remote methodinvocation by calling a method on a stub object. The stub maintains an internal reference to the remoteobject it represents and forwards the method invocation request through the remote reference layer

    by marshalling the method arguments into serialized form and asking the remote reference layer toforward the method request and arguments to the appropriate remote object. Marshalling involvesconverting local objects into portable form so that they can be transmitted to a remote process. Eachobject is checked as it is marshaled, to determine whether it implements

    the java.rmi.Remote interface. If it does, its remote reference is used as its marshaled data. If it isn't

    a Remote object, the argument is serialized into bytes that are sent to the remote host and reconstituted

    into a copy of the local object. If the argument is neither Remote norSerializable, the stub throws

    a java.rmi.MarshalExceptionback to the client.

    If the marshalling of method arguments succeeds, the client-side remote reference layer receives theremote reference and marshaled arguments from the stub. This layer converts the client request into low-

    level RMI transport requests according to the type of remote object communication being used. In RMI,remote objects can (potentially) run under several different communication styles, such as point-to-pointobject references, replicated objects, or multicast objects. The remote reference layer is responsible forknowing which communication style is in effect for a given remote object and generating thecorresponding transport-level requests. In the current version of RMI (Version 1.2 of Java 2), the onlycommunication style provided out of the box is point-to-point object references, so this is the only stylewe'll discuss in this chapter. For a point-to-point communication, the remote reference layer constructs asingle network-level request and sends it over the wire to the sole remote object that corresponds to theremote reference passed along with the request.

    On the server, the server-side remote reference layer receives the transport-level request and converts itinto a request for the server skeleton that matches the referenced object. The skeleton converts the remote

    request into the appropriate method call on the actual server object, which involves unmarshalling themethod arguments into the server environment and passing them to the server object. As you mightexpect, unmarshalling is the inverse procedure to the marshalling process on the client. Arguments sent asremote references are converted into local stubs on the server, and arguments sent as serialized objects areconverted into local copies of the originals.

    If the method call generates a return value or an exception, the skeleton marshals the object for transportback to the client and forwards it through the server reference layer. This result is sent back using theappropriate transport protocol, where it passes through the client reference layer and stub, is unmarshaledby the stub, and is finally handed back to the client thread that invoked the remote method.

    7. Define the following terms:A) Socket B) Port C) Datagram

    Ans:

    A) Socket

  • 8/3/2019 mc0078 set 1 july2011

    35/42

    Normally, a server runs on a specific computer and has a socket that is bound to a specific port number.The server just waits, listening to the socket for a client to make a connection request.

    On the client-side: The client knows the hostname of the machine on which the server is running and theport number on which the server is listening. To make a connection request, the client tries to rendezvouswith the server on the servers machine and port. The client also needs to identify itself to the serverso it

    binds to a local port number that it will use during this connection. This is usually assigned by the system.

    If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socketbound to the same local port and also has its remote endpoint set to the address and port of the client. It

    needs a new socket so that it can continue to listen to the original socket for connection requests whiletending to the needs of the connected client.

    On the client side, if the connection is accepted, a socket is successfully created and the client can use the

    socket to communicate with the server.

    The client and server can now communicate by writing to or reading from their sockets.

    Definition

    A socket is one endpoint of a two-way communication link between two programs running on thenetwork. A socket is bound to a port number so that the TCP layer can identify the application that data isdestined to be sent.An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquelyidentified by its two endpoints. That way you can have multiple connections between your host and theserver.

    The java.net package in the Java platform provides a class, Socket, that implements one side of a

    two-way connection between your Java program and another program on the network. The Socket classsits on top of a platform-dependent implementation, hiding the details of any particular system from your

    Java program. By using the java.net.Socket class instead of relying on native code, your Javaprograms can communicate over the network in a platform-independent fashion.

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00839.jpghttp://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00649.jpghttp://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00839.jpghttp://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00649.jpg
  • 8/3/2019 mc0078 set 1 july2011

    36/42

    Additionally, java.net includes the ServerSocket class, which implements a socket that serverscan use to listen for and accept connections to clients. This lesson shows you how to use

    the Socket and ServerSocket classes.

    If you are trying to connect to the Web, the URL class and related classes

    (URLConnection, URLEncoder) are probably more appropriate than the socket classes. In fact,URLs are a relatively high-level connection to the Web and use sockets as part of the underlyingimplementation.

    B) Port

    A computer has a single physical connection to the network. All data destined for a particular computerarrives through that connection. However, the data may be intended for different applications running onthe computer. So how does the computer know to which application to forward the data? Through the useof ports.Data transmitted over the Internet is accompanied by addressing information that identifies the computerand the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses todeliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP andUDP use to deliver the data to the right application.

    In connection-based communication such as TCP, a server application binds a socket to a specific portnumber. This has the effect of registering the server with the system to receive all data destined for thatport. A client can then rendezvous with the server at the servers port, as illustrated here:

    Definition

    The TCP and UDP protocols use ports to map incoming data to a particular process running on acomputer.

    In datagram-based communication such as UDP, the datagram packet contains the port number of itsdestination and UDP routes the packet to the appropriate application, as illustrated in this figure:

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00262.jpg
  • 8/3/2019 mc0078 set 1 july2011

    37/42

    Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbersranging from 01023 are restricted; they are reserved for use by well-known services such as HTTP and

    FTP and other system services. These ports are called well-known ports. Your applications should notattempt to bind to them.

    C) Datagram

    Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicatedpoint-to-point channel between themselves, or at least the illusion of one. To communicate, they establisha connection, transmit the data, and then close the connection. All data sent over the channel is receivedin the same order in which it was sent. This is guaranteed by the channel.

    In contrast, applications that communicate via datagrams send and receive completely independentpackets of information. These clients and servers do not have and do not need a dedicated point-to-point

    channel. The delivery of datagrams to their destinations is not guaranteed. Nor is the order of their arrival.

    Definition

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

    The java.net package contains three classes to help you write Java programs that use datagrams tosend and receive packets over the network: DatagramSocket. DatagramPacket, and MulticastSocket An

    application can send and receive DatagramPackets through a DatagramSocket. In

    addition, DatagramPackets can be broadcast to multiple recipients all listening to

    a MulticastSocket.

    Reading from and Writing to a Socket

    Lets look at a simple example that illustrates how a program can establish a connection to a server

    program using the Socket class and then, how the client can send data to and receive data from theserver through the socket.

    http://resources.smude.edu.in/slm/wp-content/uploads/2010/07/clip-image00452.jpg
  • 8/3/2019 mc0078 set 1 july2011

    38/42

    The example program implements a client, EchoClient, that connects to the Echo server. The Echoserver simply receives data from its client and echoes it back. The Echo server is a well-known servicethat clients can rendezvous with on port 7.

    EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from theuser on the standard input stream, and then forwards that text to the Echo server by writing the text to thesocket. The server echoes the input back through the socket to the client. The client program reads and

    displays the data passed back to it from the server:

    import java.io.*;

    import java.net.*;

    public class EchoClient {

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

    Socket echoSocket = null;

    PrintWriter out = null;

    BufferedReader in = null;

    try {

    echoSocket = new Socket("taranis", 7);

    out = new PrintWriter(echoSocket.getOutputStream(), true);

    in = new BufferedReader(new InputStreamReader(

    echoSocket.getInputStream()));

    } catch (UnknownHostException e) {

    System.err.println("Don't know about host: taranis.");

    System.exit(1);

    } catch (IOException e) {

    System.err.println("Couldn't get I/O for "

  • 8/3/2019 mc0078 set 1 july2011

    39/42

    + "the connection to: taranis.");

    System.exit(1);

    }

    BufferedReader stdIn = new BufferedReader(

    new InputStreamReader(System.in));

    String userInput;

    while ((userInput = stdIn.readLine()) != null) {

    out.println(userInput);

    System.out.println("echo: " + in.readLine());

    }

    out.close();

    in.close();

    stdIn.close();

    echoSocket.close();

    }

    }

    Note that EchoClient both writes to and reads from its socket, thereby sending data to and receivingdata from the Echo server.Lets walk through the program and investigate the interesting parts. The three statements in

    the try block of the main method are critical. These lines establish the socket connection between the

    client and the server and open a PrintWriter and a BufferedReader on the socket:echoSocket = new Socket("taranis", 7);

    out = new PrintWriter(echoSocket.getOutputStream(), true);

  • 8/3/2019 mc0078 set 1 july2011

    40/42

    in = new BufferedReader(new InputStreamReader(

    echoSocket.getInputStream()));

    The first statement in this sequence creates a new Socket object and names it echoSocket.

    The Socket constructor used here requires the name of the machine and the port number to which youwant to connect. The example program uses the host name taranis. This is the name of a hypotheticalmachine on our local network. When you type in and run this program on your machine, change the hostname to the name of a machine on your network. Make sure that the name you use is the fully qualified IPname of the machine to which you want to connect. The second argument is the port number. Port number7 is the port on which the Echo server listens.

    The second statement gets the sockets output stream and opens a PrintWriter on it. Similarly, the

    third statement gets the sockets input stream and opens a BufferedReader on it. The example usesreaders and writers so that it can write Unicode characters over the socket.

    To send data through the socket to the server, EchoClient simply needs to write to

    the PrintWriter. To get the servers response,EchoClient reads from the BufferedReader.The rest of the program achieves this. If you are not yet familiar with the Java platforms I/O classes, you

    may wish to read Basic I/O.The next interesting part of the program is the while loop. The loop reads a line at a time from thestandard input stream and immediately sends it to the server by writing it to

    the PrintWriter connected to the socket:

    String userInput;

    while ((userInput = stdIn.readLine()) != null) {

    out.println(userInput);

    System.out.println("echo: " + in.readLine());

    }

    The last statement in the while loop reads a line of information from the BufferedReader connected

    to the socket. The readLinemethod waits until the server echoes the information back

    to EchoClient. When readline returns, EchoClient prints the information to the standardoutput.

    The while loop continues until the user types an end-of-input character. That is, EchoClient readsinput from the user, sends it to the Echo server, gets a response from the server, and displays it, until it

    reaches the end-of-input. The while loop then terminates and the program continues, executing the next

    four lines of code:out.close();

    in.close();

    stdIn.close();

    echoSocket.close();

  • 8/3/2019 mc0078 set 1 july2011

    41/42

    These lines of code fall into the category of housekeeping. A well-behaved program always cleans upafter itself, and this program is well-behaved. These statements close the readers and writers connected tothe socket and to the standard input stream, and close the socket connection to the server. The order hereis important. You should close any streams connected to a socket before you close the socket itself.

    This client program is straightforward and simple because the Echo server implements a simple protocol.

    The client sends text to the server, and the server echoes it back. When your client programs are talking toa more complicated server such as an HTTP server, your client program will also be more complicated.However, the basics are much the same as they are in this program:

    1. Open a socket.

    2. Open an input stream and output stream to the socket.

    3. Read from and write to the stream according to the servers protocol.

    4. Close the streams.

    5. Close the socket.

    Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.

    8. What is the advantage of CORBA over EJB?

    Enterprise Java Beans (EJB) is a new distributed object computing technology. Beingnew, EJB simultaneously offers appeal (it is new!) and risk (it is new!). EJB does not have the broadinstalled base like CORBA, nor does it have all of the services. But, undoubtedly, overtime, EJB deployments and services will grow. The main distinctions between EJB and CORBA are on

    flexibility and focus:

    CORBA is language and platform neutral whereas EJB is Java and JVM specific. CORBAs POA/Servant model is more flexible than the EJB Container/Bean model. EJB tends to better support the deployment environment with the strong notion of

    configuration. While CORBA does not say much about configuration, some ORB products are

    particularly strong in this area.

    1) The CORBA and EJB environments can naturally interoperate at the network level. Core Javaand EJB distributed computing uses Java Remote Method Invocation (RMI) for the networkprotocol. CORBAs IIOP and Javas RMI are compatible in the sense that IIOP can carry RMI-basedcalls.

    2) Distributed applications can be developed using both CORBA and EJB. For example, a client

    application might be developed to access a set of EJB and CORBA objects without distinction. There are

    some differences in the interface design patterns in the two environments, but there are

    straightforward to handle.

  • 8/3/2019 mc0078 set 1 july2011

    42/42

    3) EJB was developed relatively recently, well after CORBA had been through its early adoption pains.This gives CORBA a longer track record of successful and unsuccessful system installations. This,however, gives EJB the benefit of handsight. We have said that EJB is CORBA combined with some

    best practices. This is meant to indicate

    At a high-level, EJB and CORBA are more similar than different. The difficult architectural problems of distributed computing are still difficult, regardless of

    which technology is used. These problems reflect more on determining how the system should

    represent interfaces rather than how to act on those interfaces.

    EJB provides some clarifying concepts. For example having two interface keywords, SessionBeanand EntityBean, to indicate the conversational or non-conversational semantics of an object is

    useful. The same thing can be done with CORBAs single style of interface, and most

    real CORBA systems distinguish between conversational and non-conversational interfaces.