MC0078 Ans

41
1. Write Java program to convert the Rupees to Dollars. Ans. import java.util.Scanner; public class rupeesconversion { public static void main(float[] args) { //Have the user to enter rupees System.out.println("Enter rupees"); double rupees_r; //Convert rupees to dollars. if (rupees_r>1) { double dollar = ruppes_r/45.2; System.out.println("the converted value from rupees to dollars is:"dollar); } else System.out.println("Try again"); } } 2. Discuss the following with suitable example programs for each: A) Data Types in Java B) Variables in Java Ans. Data Types in Java There are two kinds of data types in Java

Transcript of MC0078 Ans

Page 1: MC0078 Ans

1. Write Java program to convert the Rupees to Dollars.

Ans.

import java.util.Scanner;

public class rupeesconversion

{

public static void main(float[] args)

{

//Have the user to enter rupees

System.out.println("Enter rupees");

double rupees_r;

//Convert rupees to dollars.

if (rupees_r>1)

{

double dollar = ruppes_r/45.2;

System.out.println("the converted value from rupees to dollars is:"dollar);

}

else

System.out.println("Try again");

}

}

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

Page 2: MC0078 Ans

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 into the Java language. The Java compiler holds detailed instructions on each legal operation the data type supports. There are eight primitive data types in Java.

The data types – byte, 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. All these data types can hold negative values. However, the keyword unsigned can be used to restrict the range of values to positive numbers. Amongst others, boolean can hold only the value true or false and char can hold only a single character.

Abstract/Derived Data Types

Abstract data types are based on primitives data types and have more functionality that the primitive data types. 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 it has 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. Java provides 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 of variables may change in a program, but the values of constants, as the name suggests, do not change. You must assign unique names to variables and constants. Variable names are used in a program in much the same 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 statement specifying 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

Page 3: MC0078 Ans

A program refers to a variable using its name. Certain rules and conventions govern the naming of variables. You must adhere to rules. Conventions help improve the readability of the program, but following 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:

<data_type> <variable_name>

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

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

· Switch – case statement

2. Looping Statement

· For loop

· While loop

· Do-while loop

3. Other statement

· Break

· Continue

· Label

Page 4: MC0078 Ans

If-else statement

The if statement is Java’s conditional branch statement. It can be used to route program execution through two 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 it exists) is executed. In no case will both statements be executed. For example, consider the following:

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 code fragment:

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 more statements, you’ll need to create a block, as in this fragment:

int bytesAvailable;

Page 5: MC0078 Ans

// …

if (bytesAvailable > 0) {

ProcessData();

bytesAvailable -= n;

} else

waitForMoreData();

Here, both statements within the if block will execute if bytesAvailable is greater than zero. Some programmers find it convenient to include the curly braces when using the if, even when there is only one statement in each clause. This makes it easy to add another statement at a later date, and you don’t have to worry about forgetting the braces. In fact, forgetting to define a block when one 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 the else clause, because of the indentation level. However, as you recall, whitespace is insignificant to Java, and there is no way for the compiler to know what was intended. This code will compile without 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;

Page 6: MC0078 Ans

}

The if-else-if Ladder

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 controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none 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. If there 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)

season = "Spring";

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

Page 7: MC0078 Ans

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

Switch Statement

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

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;

.

.

.

case valueN:

// statement sequence

break;

Page 8: MC0078 Ans

default:

// default statement sequence

}

The expression must be of type byte, short, int, or char; each of the values specified in the case statements must be of a type compatible with the expression. 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 the literal values in the case statements. If a match is found, the code sequence following that case statement 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 matches and no default is present, then no further 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. This has the effect of "jumping out" of the switch.

Example

The break statement is optional. If you omit the break, execution will continue on into the next case. It is sometimes desirable to have multiplecases 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<12; i++)

switch(i) {

Page 9: MC0078 Ans

case 0:

case 1:

case 2:

case 3:

case 4:

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

break;

case 5:

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

Page 10: MC0078 Ans

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 outer switch. This is called a nested switch. Since a switch statement defines its own block, no conflicts arise between the case constants in the inner 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 of Boolean expression. That is, theswitch looks only for a match between the value of the expression and one of its case constants.

· No two case constants in the same switch can have identical values. Of course, a switch statement enclosed 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. When it 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 faster than the equivalent logic coded using a sequence of if-elses. The compiler can do this

Page 11: MC0078 Ans

because it knows that the case constants are all the same type and simply must be compared for equality with the switch expression. The compiler has no such knowledge of a long list of if expressions.

‘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 flower braces. 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

Page 12: MC0078 Ans

Like all other programming languages, Java allows loops to be nested. That is, one loop may be inside another. 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<10; i++) {

for(j=i; j<10; j++)

System.out.print(".");

System.out.println();

}

}

}

The output produced by this program is shown here:

……….

………

……..

…….

……

…..

While Statement

The while loop is Java’s most fundamental looping statement. It repeats a statement or block while its controlling 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 the conditional expression is true. When conditionbecomes false, control passes to the next line of code immediately following the loop. The curly braces are unnecessary if only a single statement is being repeated.

Page 13: MC0078 Ans

Example

‘do….while’ statement

As you just saw, if the conditional expression controlling a while loop is initially false, then the body of the loop will not be executed at all. However, sometimes it is desirable to execute the body of a while loop at least once, even if the conditional expression is false to begin with. In other words, there are times when you would like to test the termination expression at the end of the 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 conditional expression 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 the conditional expression. If this expression is true, the loop will repeat. Otherwise, the loop terminates. As with all of Java’s loops, condition must be a boolean expression.

Example

Page 14: MC0078 Ans

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 a very simple help system for Java’s 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");

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

Page 15: MC0078 Ans

System.out.println("if(condition) statement;");

System.out.println("else statement;");

break;

case ‘2′:

System.out.println("The switch:\n");

System.out.println("switch(expression) {");

System.out.println(" case constant:");

System.out.println(" statement sequence");

System.out.println(" break;");

System.out.println(" // …");

System.out.println("}");

break;

case ‘3′:

System.out.println("The while:\n");

System.out.println("while(condition) statement;");

break;

case ‘4′:

System.out.println("The do-while:\n");

System.out.println("do {");

System.out.println(" statement;");

System.out.println("} while (condition);");

break;

case ‘5′:

System.out.println("The for:\n");

System.out.print("for(init; condition; iteration)");

System.out.println(" statement;");

break;

}

}

Page 16: MC0078 Ans

}

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 the perfect loop to accomplish this.

A few other points about this example: Notice that characters are read from the keyboard by calling System.in.read( ). This is one of Java’s console input functions. Although Java’s console I/O methods won’t be discussed in detail until System.in.read( ) is used here to obtain the user’s choice. It reads 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 type will be sent to your program.

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

‘Break’ statement

By using break, you can force immediate termination of a loop, bypassing the conditional expression and any remaining code in the body of the loop. When a break statement is encountered inside a loop, the loop is terminated and program control resumes at the next statement 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<100; i++) {

Page 17: MC0078 Ans

if(i == 10) break; // terminate loop if i is 10

System.out.println("i: " + i);

}

System.out.println("Loop complete.");

}

}

This program generates the following output:

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 to terminate 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 running the 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 loop’s end. Thecontinue statement performs such an action. In while and do-while loops, a continue statement causes control to be transferred directly to the conditional expression that controls the loop. In a for loop, control goes first to the iteration portion of the for statement and then to the conditional expression. 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 each line:

// Demonstrate continue.

class Continue {

public static void main (String args[]) {

Page 18: MC0078 Ans

for (int i=0; i<10; i++) {

System.out.print (i + " ");

if (i%2 == 0) continue;

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 the break statement, continue may specify a label to describe which enclosing loops to continue. Here is an example program that usescontinue to print a triangular multiplication table for 0 through 9.

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

Ans.

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

Common Exceptions

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

· Arithmetic Exception

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

Page 19: MC0078 Ans

· NullPointer 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:

- Using an object without allocating memory for it.

- Calling the methods of a null object.

- Accessing or modifying the attributes 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 that’s has only ten elements, the exception will be thrown.

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

Ans.

Bound Properties

Bound properties support 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 PropertyChangeListener objects by calling their propertyChange methodsThe convenience PropertyChangeSupport (in the API reference documentation) class enables your bean 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 listener list on the bean containing the bound property. It must also be able to respond to the event notification method that signals a property change.

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

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 PropertyChangeSupport object. This object maintains the property change listener list and fires property change events. You can also make your class a PropertyChangeSupport subclass.

Page 20: MC0078 Ans

3. Implement methods to maintain the property change listener list. Since a PropertyChangeSupport subclass implements these methods, you merely wrap calls to the property-change support object’s methods.4. Modify a property’s 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.

Note that the title property and the multicast event source pattern PropertyChangeListener were added to the Bean Patterns structure.You can also modify existing code generated in the previous lesson to convert the title and lines properties 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

Page 21: MC0078 Ans

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

}

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;

Page 22: MC0078 Ans

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

}

}

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

{

if ( str != null )

g.drawString( str, 0, height );

}

}

Constrained Properties

A bean property is constrained if 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 reference documentation).

Page 23: MC0078 Ans

Constrained properties are more complicated than bound properties because they also support property change listeners which happen to be vetoers.The following operations in the setXXX method for the constrained property must be implemented in this 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 setXXX method 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 responsible for the following actions:· Catching exceptions.

· Reverting to the old value for the property.

· Issuing a new VetoableChangeListener.vetoableChange call to all listeners to report the reversion.The VetoableChangeListener class throws a PropertyVetoException and handles the PropertyChangeEvent event fired by the bean with the constrained property.· The VetoableChangeSupport provides the following operations:· Keeping track of VetoableChangeListener objects.· Issuing the vetoableChange method on all registered listeners.· Catching any vetoes (exceptions) thrown by listeners.

· Informing all listeners of a veto by calling vetoableChange again, but with the old property value as the proposed "new" value.

Creating a Constrained Property

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

Page 24: MC0078 Ans

Note that the Multicast Source Event Pattern – vetoableChangeListener was added to the Bean Patterns hierarchy.

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

implements Serializable

{

private String title;

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

private final PropertyChangeSupport pcs = new PropertyChangeSupport( this );

Page 25: MC0078 Ans

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

}

/**

* This method throws the PropertyVetoException

* if some vetoable listeners reject the new lines value

*/

public void setLines( String[] lines )

Page 26: MC0078 Ans

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 ){this.vcs.addVetoableChangeListener( listener );}public void removeVetoableChangeListener( VetoableChangeListener listener ){this.vcs.removeVetoableChangeListener( listener );

Page 27: MC0078 Ans

}

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:

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

Page 28: MC0078 Ans

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

RMI is the distributed object system that is built into the core Java environment. You can think of RMI as a built-in facility for Java that allows you to interact with objects that are actually running in Java virtual machines on remote hosts on the network. With RMI (and other distributed object APIs we discuss in this book), you can get a reference to an object that "lives" in a remote process and invoke methods on it as if it were a local object running within the same virtual machine as your code (hence the name, "Remote Method 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 Java 2 platform), in recognition of the critical need for support for distributed objects in distributed-application development. 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 remote processes/agents can access it directly as a Java object. So, instead of defining a low-level message protocol and data transmission format between processes in your distributed application, you use Java interfaces as the "protocol" and the exported method arguments become the data transmission format. The distributed object system (RMI in this case) handles all the underlying networking needed to make your remote method calls work.

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

The advantages of RMI primarily revolve around the fact that it is "Java-native." Since RMI is part of the core Java API and is built to work directly with Java objects within the Java VM, the integration of its remote object facilities into a Java application is almost seamless. You really can use RMI-enabled objects as if they live in the local Java environment. And since Java RMI is built on the assumption that both the client and server are Java objects, RMI can extend the internal garbage-collection mechanisms of the 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 use to interact with each other.

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

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

These layers interact with each other as shown in Figure. In this figure, the server is the application that provides remotely accessible objects, while the client is any remote application that communicates with these 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, and a number of remote processes are accessing it. We might be tempted to call the first

Page 29: MC0078 Ans

process the server and 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 is using an object exported from the client, which turns the tables somewhat. The "server" is really the server for one object and the client of another object, and the "client" is a client and a server, too. For the sake 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 clear client or server, I'll refer to elements of the system in terms of application-specific roles (e.g., chat participant, chat facilitator).

The RMI architecture

As you can see in Figure, a client makes a request of a remote object using a client-side stub; the server object receives this request from a server-side object skeleton. A client initiates a remote method invocation by calling a method on a stub object. The stub maintains an internal reference to the remote object 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 to forward the method request and arguments to the appropriate remote object. Marshalling involves converting local objects into portable form so that they can be transmitted to a remote process. Each object 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.MarshalException back to the client.

If the marshalling of method arguments succeeds, the client-side remote reference layer receives the remote 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-point object references, replicated objects, or multicast objects. The remote reference layer is responsible for knowing which communication style is in effect for a given remote object and

Page 30: MC0078 Ans

generating the corresponding transport-level requests. In the current version of RMI (Version 1.2 of Java 2), the only communication style provided out of the box is point-to-point object references, so this is the only style we'll discuss in this chapter. For a point-to-point communication, the remote reference layer constructs a single network-level request and sends it over the wire to the sole remote object that corresponds to the remote reference passed along with the request.

On the server, the server-side remote reference layer receives the transport-level request and converts it into 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 the method arguments into the server environment and passing them to the server object. As you might expect, unmarshalling is the inverse procedure to the marshalling process on the client. Arguments sent as remote references are converted into local stubs on the server, and arguments sent as serialized objects are converted into local copies of the originals.

If the method call generates a return value or an exception, the skeleton marshals the object for transport back to the client and forwards it through the server reference layer. This result is sent back using the appropriate transport protocol, where it passes through the client reference layer and stub, is unmarshaled by 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) DatagramDescribe the steps in reading and writing data from sockets.

Ans.

Socket

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 the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server’s machine and port. The client also needs to identify itself to the server so 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 socket bound 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 while tending to the needs of the connected client.

Page 31: MC0078 Ans

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 the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.

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 class sits 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 Java programs can communicate over the network in a platform-independent fashion.Additionally, java.net includes the ServerSocket class, which implements a socket that servers can 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 underlying implementation.

Port

A computer has a single physical connection to the network. All data destined for a particular computer arrives through that connection. However, the data may be intended for different applications running on the computer. So how does the computer know to which application to forward the data? Through the use of ports.Data transmitted over the Internet is accompanied by addressing information that identifies the computer and the port for which it is destined. The computer is identified by its 32-bit IP address, which IP uses to deliver data to the right computer on the network. Ports are identified by a 16-bit number, which TCP and UDP 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 port number. This has the effect of registering the server with the system to receive all data destined for that port. A client can then rendezvous with the server at the server’s port, as illustrated here:

Definition

Page 32: MC0078 Ans

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

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

Port numbers range from 0 to 65,535 because ports are represented by 16-bit numbers. The port numbers ranging from 0 – 1023 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 not attempt to bind to them.

Datagram

Clients and servers that communicate via a reliable channel, such as a TCP socket, have a dedicated 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. All data sent over the channel is received in 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 independent packets 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 to send 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

Let’s 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 the server through the socket.The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7.

Page 33: MC0078 Ans

EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. 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 "

+ "the connection to: taranis.");

System.exit(1);

}

BufferedReader stdIn = new BufferedReader(

Page 34: MC0078 Ans

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 receiving data from the Echo server.Let’s 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);

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 you want to connect. The example program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect. The second argument is the port number. Port number 7 is the port on which the Echo server listens.The second statement gets the socket’s output stream and opens a PrintWriter on it. Similarly, the third statement gets the socket’s input stream and opens a BufferedReader on it. The example uses readers 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 server’s response, EchoClient reads from the BufferedReader. The rest of the program achieves this. If you are not yet familiar with the Java platform’s I/O classes, you may wish to read Basic I/O.

Page 35: MC0078 Ans

The next interesting part of the program is the while loop. The loop reads a line at a time from the standard 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 readLine method waits until the server echoes the information back to EchoClient. When readline returns, EchoClient prints the information to the standard output.The while loop continues until the user types an end-of-input character. That is, EchoClient reads input 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();

These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is 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 to a 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 server’s 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.

Page 36: MC0078 Ans

8. What is the advantage of CORBA over EJB?

Ans.

Advantages of CORBA over EJB

1. CORBA works with more than just Java. EJB can use IIOP, but while we can get an EJB client to talk to a CORBA server, we can't get a CORBA client to talk to an EJB server.

2. EJB containers are typically much slower than custom CORBA servers, and you still end up using all the distributed programming tricks you learned from CORBA when you write EJBs. The big myth of EJB programming is that you don't have to worry about scalability issues since the container does it for you. The truth is that you still do because most containers blow.

3. EJB isn't quite as flexible as CORBA. With CORBA you can code just about any type of servant object you want, with EJB you are limited to whatever the container supports, and only a few models with EJB itself (although, these are pretty flexible in their own right).

4. EJB containers are still fairly new, and you could easily get locked into something that evaporates a few years later. Many of your CORBA ORBs that are available have been around for a long time and have a better track record.

5. Finally, there are more services available with CORBA 3.0, and they are well defined. This is a debatable one though, since most vendors can't seem to get these right.