Monday 2 February 2015

MCS-024 Ignou BCA Solved Assignment - 2015

QUESTION: 1

a) What is Object Oriented Programming? Explain features of Object Oriented

Programming. Write a program in java to show data hiding.

Solution:

Object-oriented programming (OOP) is a programming language model organized

around “objects” rather than “actions” and data rather than logic. Historically, a program

has been viewed as a logical procedure that takes input data, processes it, and

produces output data. A type of programming in which programmers define not only the

data type of a data structure, but also the types of operations (functions) that can be

applied to the data structure. In this way, the data structure becomes an object that

includes both data and functions. In addition, programmers can create relationships

between one object and another. For example, objects can inherit characteristics from

other objects. One of the principal advantages of object-oriented programming

techniques over procedural programming techniques is that they enable programmers to

create modules that do not need to be changed when a new type of object is added. A

programmer can simply create a new object that inherits many of its features from

existing objects. This makes object-oriented programs easier to modify.

Objects

Objects are the basic unit of OOP. They are instances of class, which have data

members and uses various member functions to perform tasks.

Class

It is similar to structures in C language. Class can also be defined as user defined data

type but it also contains functions in it. So, class is basically a blueprint for object. It

declare & defines what data variables the object will have and what operations can be

performed on the class’s object.

Abstraction

Abstraction refers to showing only the essential features of the application and hiding the

details. In C++, classes provide methods to the outside world to access & use the data

variables, but the variables are hidden from direct access.

Encapsulation

It can also be said data binding. Encapsulation is all about binding the data variables

and functions together in class.

Inheritance

Inheritance is a way to reuse once written code again and again. The class which is

inherited is called base calls & the class which inherits is called derived class. So when,

a derived class inherits a base class, the derived class can use all the functions which

are defined in base class, hence making code reusable.

Polymorphism

Polymorphism makes the code more readable. It is a features, which lets is create

functions with same name but different arguments, which will perform differently. That is

function with same name, functioning in different

Overloading

Overloading is a part of polymorphion. Where a function or operator is made & defined

many times, to perform different functions they are said to be overloaded.

Exception Handling

Exception handling is a feature of OOP, to handle unresolved exceptions or errors produced at runtime.

A program in java to show data hiding.

public class EncapTest{

private String name;

private String idNum;

private int age;

public int getAge(){

return age;

}

public String getName(){

return name;

}

public String getIdNum(){

return idNum;

}

public void setAge( int newAge){

age = newAge;

}

public void setName(String newName){

name = newName;

}

public void setIdNum( String newId){

idNum = newId;

}


}



b) Explain why java is platform independent. Also explain how memory is managed in java.

Solution:

The most important feature of “java is platform Independent”. Here ‘platform’ stands for

Operating systems used by end user.

There are lots of Operating Systems and java supports all of them, java language does

not depend on particular Operating system or any hardware system. It means every

single java program can run on different operating system shows platform independent

nature of java. Basically Java runs on JVM (Java Virtual Machine), and JVM (Java

Virtual Machine) is platform dependent. Java is one of the most powerful and portable

language, because it is compiled as well as interpreted language. After compilation an

intermediate code is generate, this code is known as ‘byte code’ and cause of byte code,

java is known as platform independent because in actual, byte code has a powerful

feature to run on any platform or operating system. Byte code is found in form of ‘.class’

file and

We can run the same ‘.class’ file on any operating system (Windows, Linux, Mac, Unix).

To run or execute a java file on different platforms, we need only ‘.class’ file of and

application or program.

In java, memory is managed via garbage collector. Few techniques for memory

management are:

1. Reference Counting: A count of references to each object is maintained. When

garbage collector runs, it deletes objects with zero reference count.

Drawback: Circular references are maintained in memory.

2. Tracing collectors/Copy Collector/Stop and copy collector: Start from a root object and

keep a track of all references which have direct/indirect reference to the root object.

Then all the live objects are moved to another heap, taking care of references properly.

Drawback: At each point of time, you will have 2 heaps thus consuming twice the

memory.

3. Mark sweep collectors/Stop and work collector: Similar to tracing collector except that

instead of copying the references to the new heap, they are swept out of memory, after

a list of live and dead objects is known.

Mark and sweep is a stop-the-world garbage collection technique; that is all application

threads stop until garbage collection completes or until a higher-priority thread interrupts

the garbage collector. If the garbage collector is interrupted it must restart which can

lead to application thrashing with little apparent result.


QUESTION: 2

a) What is static method? Explain application of static method with example.

Solution:

Static methods use no instance variables of any object of the class they are defined in. If

you define a method to be static, you will be given a rude message by the compiler if

you try to access any instance variables. You can access static variables, but except for

constants, this is unusual. Static methods typically take all they data from parameters

and compute something from those parameters, with no reference to variables. This is

typical of methods which do some kind of generic calculation. A good example of this is

the many utility methods in the predefined Math class.

Static methods are used for methods that do not need to access to an object’s state or

only use static fields. For example, the main method is a static method: public static void

main(String [] args)

It is the starting point for a Java application and does not need to access an object’s

state. In fact, there aren’t any objects created at this point. Any parameters that it needs

can be passed as a String array.

To find out more about using the static keyword have a look at Static Fields.

public class HowToAccessStaticMethod{

int i;

static int j;

public static void staticMethod(){

System.out.println("you can access a static method this way");

}

public void nonStaticMethod(){

i=100;

j=1000;

System.out.println("Don't try to access a non static method");

}

public static void main(String[] args) {

//i=100;

j=1000;

//nonStaticMethod();

staticMethod();

}

}

Output of the program is given below:


C:\java>java HowToAccessStaticMethod you can access a static method this way


b) What are different arithmetic and logical operators in java? Write a Java program and

show uses of all arithmetic operators.

Solution:

The Arithmetic Operators:

Arithmetic operators are used in mathematical expressions in the same way that they

are used in algebra. The following table lists the arithmetic operators:

Operator Description Example

+ Addition - Adds values on either side of the operator A + B will give 30

- Subtraction - Subtracts right hand operand from left hand operand A - B will

give -10

* Multiplication - Multiplies values on either side of the operator A * B will

give 200

/ Division - Divides left hand operand by right hand operand B / A will give 2

% Modulus - Divides left hand operand by right hand operand and returns remainder

B % A will give 0

++ Increment - Increases the value of operand by 1 B++ gives 21

-- Decrement - Decreases the value of operand by 1 B-- gives 19

The Logical Operators:

The following table lists the logical operators: Assume Boolean variables A holds true

and variable B holds false, then:

Operator Description Example

&& Called Logical AND operator. If both the operands are non-zero, then the

condition (A && B) is false

becomes true.

|| Called Logical OR Operator. If any of the two operands are non-zero, then the

(A || B) is true.

condition becomes true.

! Called Logical NOT Operator. Use to reverses the logical state of its operand.

If a !(A && B) is true

condition is true then Logical NOT operator will make false.

A Java program and show uses of all arithmetic operators.

public class ArithmeticOperatorsDemo {

public ArithmeticOperatorsDemo() {

int x, y = 10, z = 5;

x = y + z;

System.out.println("+ operator resulted in " + x);


x = y - z;

System.out.println("- operator resulted in " + x);

x = y * z;

System.out.println("* operator resulted in " + x);

x = y / z;

System.out.println("/ operator resulted in " + x);

x = y % z;

System.out.println("% operator resulted in " + x);

x = y++;

System.out.println("Postfix ++ operator resulted in " + x);

x = ++z;

System.out.println("Prefix ++ operator resulted in " + x);

x = -y;

System.out.println("Unary operator resulted in " + x);

// Some examples of special Cases

int tooBig = Integer.MAX_VALUE + 1; // -2147483648 which is

// Integer.MIN_VALUE.

int tooSmall = Integer.MIN_VALUE - 1; // 2147483647 which is

// Integer.MAX_VALUE.

System.out.println("tooBig becomes " + tooBig);

System.out.println("tooSmall becomes " + tooSmall);

System.out.println(4.0 / 0.0); // Prints: Infinity

System.out.println(-4.0 / 0.0); // Prints: -Infinity

System.out.println(0.0 / 0.0); // Prints: NaN

double d1 = 12 / 8; // result: 1 by integer division. d1 gets the value

// 1.0.

double d2 = 12.0F / 8; // result: 1.5

System.out.println("d1 is " + d1);

System.out.println("d2 iss " + d2);

}

public static void main(String args[]) {

new ArithmeticOperatorsDemo();

}


}



c) What is final keyword in java? Explain different uses of final keyword.

Solution:

The final keyword is a way of marking a variable as “read-only”. Its value is set once and

then cannot be changed.

For example, if year is declared as

Final int year = 2005;

Variable year will be containing value 2005 and cannot take any other value after words.

The final keyword is used for three purposes:

i. Making constants

ii. Preventing method to be overridden

iii. Preventing a class to be inherited

The final keyword can also be applied to methods, with similar semantics: i.e. the

definition will not change. You cannot override a final method in subclasses, this means

the definition is the “final” one. You should define a method final when you

are concerned that a subclass may accidentally or deliberately redefine the method

(override). If you want to prevent a class to be inherited, apply the final keyword to an


entire class definition.



QUESTION: 3

a) What is method overloading? How it is different from method overriding? Write a java

program to explain overloading and overriding of methods.

Solution:

If a class has multiple methods by same name but different parameters, it is known as

Method Overloading. If we have to perform only one operation, having same name of

the methods increases the readability of the program. Suppose you have to perform

addition of the given numbers but there can be any number of arguments, if you write

the method such as a (int, int) for two parameters, and b (int,int,int) for three parameters

then it may be difficult for you as well as other programmers to understand the behaviour

of the method because its name differs. So, we perform method overloading to figure out

the program quickly.

With method overloading, programmer can have multiple methods with the same name

but their functionality changes according to the situations.Whereas method overriding is

used in the situation where we want a method with the same name to behave in a

different manner in different classes in the hierarchy.

public class OverloadingOverridingTest {

public static void main(String[] args) {

// Example of method overloading in Java

Loan cheapLoan = Loan.createLoan(“HSBC”);

Loan veryCheapLoan = Loan.createLoan(“Citibank”);

// Example of method overriding in Java

Loan personalLoan = new PersonalLoan();

personalLoan.toString();

} }

public class Loan {

private double interestRate;

private String customer;

private String lender;

public static Loan createLoan(String lender) {

Loan loan = new Loan();

loan.lender = lender;

return loan;

}

public static Loan createLoan(String lender, double interestRate) {

Loan loan = new Loan();

loan.lender = lender;

loan.interestRate = interestRate;

return loan;

}

public String toString() {

return “This is Loan by Citibank”;

}

}

public class PersonalLoan extends Loan {

@Override

public String toString() {

return “This is Personal Loan by Citibank”;

}


}



b) What is abstract class? Explain why abstract class is used in java, with the help of an

example program.

Solution:

An abstract class is a class that is declared abstract—it may or may not include abstract

methods. Abstract classes cannot be instantiated, but they can be sub classed. An

abstract method is a method that is declared without an implementation (without braces,

and followed by a semicolon), like this:


abstract void moveTo(double deltaX, double deltaY);

If a class includes abstract methods, then the class itself must be declared abstract, as

in:

public abstract class GraphicObject {

// declare fields

// declare nonabstract methods

abstract void draw();

}

When an abstract class is subclassed, the subclass usually provides implementations for

all of the abstract methods in its parent class. However, if it does not, then the subclass

must also be declared abstract.

abstract class A {

abstract void callme();

// concrete methods are still allowed in abstract classes

void callmetoo() {

System.out.println(“This is a concrete method.”);

}

}

class B extends A {

void callme() {

System.out.println(“B’s implementation of callme.”);

}

}

class AbstractDemo {

public static void main(String args[]) {

B b = new B();

b.callme();

b.callmetoo();

}

}

Notice that no objects of class A are declared in the program. As mentioned, it is not

possible to instantiate an abstract class. One other point: class A implements a concrete

method calledcallmetoo( ). This is perfectly acceptable. Abstract classes can include as


much implementation as they see fit.



QUESTION: 4

a) What is inheritance? Explain different types of inheritance supported by java.

Solution:

Inheritance is a mechanism in which one object acquires all the properties and behaviours of parent object.

The idea behind inheritance is that you can create new classes that are built upon

existing classes. When you inherit from an existing class, you reuse (or inherit) methods

and fields, and you add new methods and fields to adapt your new class to new

situations.

Inheritance represents the IS-A relationship.

Types of inheritance supported by java

1. Single: Single inheritance is damn easy to understand. When a class extends another

one class only then we call it a single inheritance. The below flow diagram shows that

class B extends only one class which is A. Here A is aparent class of B and B would be

a child class of A.

2. Multilevel: Multilevel inheritance refers to a mechanism in OO technology where one

can inherit from a derived class, thereby making this derived class the base class for the

new class. As you can see in below flow diagram C is subclass or child class of B and B

is a child class of A. For more details and example refer – Multilevel inheritance in Java.


3. Hierarchical: In such kind of inheritance one class is inherited by many sub classes.

In below example class B,C and D inherits the same class A. A is parent class (or base

class) of B,C & D. Read More at – Hierarchical Inheritance in java with example

program.


4. Hybrid: In simple terms you can say that Hybrid inheritance is a combination of Single

and Multiple inheritance. A typical flow diagram would look like below. A hybrid

inheritance can be achieved in the java in a same way as multiple inheritances can be!!

Using interfaces. Yes you heard it right. By using interfaces you can have multiple as

well as hybrid inheritance in Java.

Note: multiple inheritance is not supported in java. To reduce the complexity and simplify
the language, multiple inheritance is not supported in java.



b) What is an exception? Explain haw an exception is handled in Java. Create your own

exception class to handle undesirable operation in your program.

Solution:

An exception is an event, which occurs during the execution of a program, that disrupts

the normal flow of the program’s instructions. When an error occurs within a method, the

method creates an object and hands it off to the runtime system. The object, called an

exception object, contains information about the error, including its type and the state of

the program when the error occurred. Creating an exception object and handing it to the

runtime system is called throwing an exception.After a method throws an exception, the

runtime system attempts to find something to handle it. The set of possible “somethings”

to handle the exception is the ordered list of methods that had been called to get to the

method where the error occurred. The list of methods is known as the call stack.

To understand how exception handling works in Java, you need to understand the three

categories of exceptions:

• Checked exceptions: A checked exception is an exception that is typically a user error or

a problem that cannot be foreseen by the programmer. For example, if a file is to be

opened, but the file cannot be found, an exception occurs. These exceptions cannot

simply be ignored at the time of compilation.

• Runtime exceptions: A runtime exception is an exception that occurs that probably

could have been avoided by the programmer. As opposed to checked exceptions,

runtime exceptions are ignored at the time of compilation.

• Errors: These are not exceptions at all, but problems that arise beyond the control of

the user or the programmer. Errors are typically ignored in your code because you can

rarely do anything about an error. For example, if a stack overflow occurs, an error will

arise. They are also ignored at the time of compilation.

Catching Exceptions and building blocks in java: The basic building blocks are try-catch-
finally Any java method catches an exception using a combination of the try and catch
keywords as shown below. The try/catch block is placed around the code that might

generate an exception. There might be many try/catch blocks. The catch block defines

exceptions classes which the code might throw. The parent class is ‘Exception’ but the

user can define any exception class inside catch block. The finally block always

executes irrespective of the type of exception.

Create your own exception class to handle undesirable operation in your program.

package com.journaldev.exceptions;

import java.io.FileNotFoundException;

import java.io.IOException;

public class ExceptionHandling {

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

try{

testException(-5);

testException(-10);

}catch(FileNotFoundException e){

e.printStackTrace();

}catch(IOException e){

e.printStackTrace();

}finally{

System.out.println(“Releasing resources”);

}

testException(15);

}

public static void testException(int i) throws FileNotFoundException, IOException{

if(i < 0){ FileNotFoundException myException = new FileNotFoundException(“Negative

Integer “+i); throw myException; }else if(i > 10){

throw new IOException(“Only supported for index 0 to 10′′);

}

}

}

Output of above program is:

java.io.FileNotFoundException: Negative Integer -5

at

com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:24

)

at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:10)

Releasing resources

Exception in thread “main” java.io.IOException: Only supported for index 0 to 10

at

com.journaldev.exceptions.ExceptionHandling.testException(ExceptionHandling.java:27

)


at com.journaldev.exceptions.ExceptionHandling.main(ExceptionHandling.java:19)



QUESTION: 5
a) Write a java program to create a file of given name and directory and copy a file named

myjava.java available at desktop.

Solution:

b) What is String class in java? Explain different constructors and method of String class.

Also write a java program to find the length of a given string.


Solution:

Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot

be changed on the same reference. A java.lang.String class is final which implies no

class and extend it. The java.lang.String class differs from other classes, one difference

being that the String objects can be used with the += and + operators for concatenation.

Two useful methods for String objects are equals( ) and substring( ). The equals( )

method is used for testing whether two Strings contain the same value. The substring( )

method is used to obtain a selected portion of a String.

Constructor is a special type of method that is used to initialize the object.Constructor is

invoked at the time of object creation. It constructs the values i.e. provides data for the

object that is why it is known as constructor.

There are two types of constructors:

1. default constructor (no-arg constructor): A constructor that have no parameter is

known as default constructor.

2. parameterized constructor: A constructor that have parameters is known as

parameterized constructor.

Methods with Description

char charAt(int index):Returns the character at the specified index.

int compareTo(Object o): Compares this String to another Object.

int compareTo(String anotherString: Compares two strings lexicographically.

int compareToIgnoreCase(String str): Compares two strings lexicographically, ignoring

case differences.

String concat(String str): Concatenates the specified string to the end of this string.

boolean contentEquals(StringBuffer sb): Returns true if and only if this String represents

the same sequence of characters as the specified StringBuffer.

static String copyValueOf(char[] data): Returns a String that represents the character

sequence in the array specified.

static String copyValueOf(char[] data, int offset, int count): Returns a String that

represents the character sequence in the array specified.

boolean endsWith(String suffix): Tests if this string ends with the specified suffix.

boolean equals(Object anObject): Compares this string to the specified object.

A java program to find the length of a given string

import java.io.*;

public class Test{

public static void main(String args[]){

String Str1 = new String(“Welcome to ignou.nisecomputers.com”);

String Str2 = new String(“Tutorials” );

System.out.print(“String Length :” );

System.out.println(Str1.length());

System.out.print(“String Length :” );

System.out.println(Str2.length());

}

}

This produces the following result:

String Length :34


String Length : 9


QUESTION: 6

a) What is multithreading? Write a java program to explain how concurrency control is

done.

Solution:

Java is a multithreaded programming language which means we can develop

multithreaded program using Java. A multithreaded program contains two or more parts

that can run concurrently and each part can handle different task at the same time

making optimal use of the available resources specially when your computer has

multiple CPUs. By definition multitasking is when multiple processes share common

processing resources such as a CPU. Multithreading extends the idea of multitasking

into applications where you can subdivide specific operations within a single application

into individual threads. Each of the threads can run in parallel. The OS divides

processing time not only among different applications, but also among each thread

within an application. Multithreading enables you to write in a way where multiple

activities can proceed concurrently in the same program.

class Pool { // Incomplete

protected java.util.ArrayList items = new ArrayList();

protected java.util.HashSet busy = new HashSet();

protected final Semaphore available;

public Pool(int n) {

available = new Semaphore(n);

initializeItems(n);

}

public Object getItem() throws InterruptedException {

available.acquire();

return doGet();

}

public void returnItem(Object x) {

if (doReturn(x))

available.release();

}

protected synchronized Object doGet() {

Object x = items.remove(items.size()-1);

busy.add(x); // put in set to check returns

return x;

}

protected synchronized boolean doReturn(Object x) {

if (busy.remove(x)) {

items.add(x); // put back into available item list

return true;

}

else return false;

}

protected void initializeItems(int n) {

// Somehow create the resource objects

// and place them in items list.

}


}


b) What is I/O stream in Java? Explain what is byte steam? How byte stream is different

from character stream.

Solution:

Java performs I/O through Streams. A Stream is linked to a physical layer by java I/O

system to make input and output operation in java. In general, a stream means

continuous flow of data. Streams are clean way to deal with input/output without having

every part of your code understand the physical.

Java encapsulates Stream under java.io package. Java defines two types of streams.

They are,

Byte Stream: It provides a convenient means for handling input and output of byte.

Character Stream: It provides a convenient means for handling input and output of

characters. Character stream uses Unicode and therefore can be internationalized.

Java byte streams are used to perform input and output of 8-bit bytes. Though there are

many classes related to byte streams but the most frequently used classes are ,

FileInputStream andFileOutputStream. Following is an example which makes use of

these two classes to copy an input file into an output file:

import java.io.*;

public class CopyFile {

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

{

FileInputStream in = null;

FileOutputStream out = null;

try {

in = new FileInputStream(“input.txt”);

out = new FileOutputStream(“output.txt”);

int c;

while ((c = in.read()) != -1) {

out.write(c);

}

}finally {

if (in != null) {

in.close();

}

if (out != null) {

out.close();

}

}

}

}

CopyBytes seems like a normal program, but it actually represents a kind of low-level I/O

that you should avoid. Since xanadu.txt contains character data, the best approach is to

use character streams, as discussed in the next section. There are also streams for

more complicated data types. Byte streams should only be used for the most primitive

I/O.

CopyCharacters is very similar to CopyBytes. The most important difference is that

CopyCharacters uses FileReader and FileWriter for input and output in place of

FileInputStream and FileOutputStream. Notice that both CopyBytes and CopyCharacters

use an int variable to read to and write from. However, in CopyCharacters, the int

variable holds a character value in its last 16 bits; in CopyBytes, the int variable holds a

byte value in its last 8 bits. There are two general-purpose byte-to-character “bridge”

streams: InputStreamReader and OutputStreamWriter. Use them to create character

streams when there are no prepackaged character stream classes that meet your

needs. The sockets lesson in the networking trail shows how to create character streams

from the byte streams provided by socket classes.



QUESTION: 7

a) What is Java Applet? Create an Applet program to display your details including your

academic and personal information. Use appropriate GUI components and images to make

your applet more attractive and informative.

Solution:

A Java applet is a special kind of Java program that a browser enabled with Java

technology can download from the internet and run. An applet is typically embedded

inside a web page and runs in the context of a browser. An applet must be a subclass of

the java.applet.Applet class. The Applet class provides the standard interface between

the applet and the browser environment.

Swing provides a special subclass of the Applet class called javax.swing.JApplet. The

JApplet class should be used for all applets that use Swing components to construct

their graphical user interfaces (GUIs). The browser’s Java Plug-in software manages the

lifecycle of an applet.


b) What are principles of event delegation model? Explain different sources of events and

event listener.

Solution:

The concepts of the event delegation model. This model allows special classes, known

as “adapter classes” to be built and be registered with a component in order to handle

certain events. Three simple steps are required to use this model:

1. Implement the desired listener interface in your adapter class. Depending on what

event you’re handling, a number of listener interfaces are available. These include:

ActionListener, WindowListener, MouseListener, MouseMotionListener,

ComponentListener, FocusListener, and ListSelectionListener.

2. Register the adapter listener with the desired component(s). This can be in the form of

an add XXX Listener () method supported by the component for example include add

ActionListener (), add MouseListener (), and add FocusListener ().

3. Implement the listener interface’s methods in your adapter class. It is in this code that

you will actually handle the event.

The event delegation model allows the developer to separate the component’s display

(user interface) from the event handling (application data) which results in a cleaner and

more object-oriented design

Event Source: An event source is the object that generated the event, for example, if you

click a button an ActionEvent Object is generated. The object of the ActionEvent class

contains information about the event (button click).

Low-Level Events: These events are those that represent a low-level input or windows-
system occurrence on a visual component on the screen.

The various low-level event classes and what they generate are as follows:

! A Container Event Object is generated when components are added or removed from

container.

! A Component Event object is generated when a component is resized moved etc.

! A Focus Event object is generated when component receives focus for input.

! A Key Event object is generated when key on keyboard is pressed, released etc.

! A Window Event object is generated when a window activity, like maximizing or close
occurs.

! A Mouse Event object is generated when a mouse is used.

! A Paint Event object is generated when component is painted.

Event Listeners: An object delegates the task of handling an event to an event listener.

When an event occurs, an event object of the appropriate type (as explained below) is

created. This object is passed to a Listener. The listener must implement the interface

that has the method for event handling. A component can have multiple listeners, and a

listener can be removed using remove Action Listener () method.


QUESTION: 8

a) What is InetAddress class in Java? Explain its methods and their uses.

Solution:

The java.net.InetAddress class represents an IP address. The Inet Address class

provides methods to get the IP of any host name. This class is used for encapsulating

numerical IP address and domain name for that address. Because InetAddress is not

having any constructor, its objects are created by using any of the following three

methods

static InetAddress getLocalHost() throws UnknownHostException:

returns the InetAddress object representing local host

static InetAddress getByName() throws UnknownHostException:

returns the InetAddress object for the host name passed to it.

static InetAddress getAllByName() throws UnknownHostException:

returns an array of InetAddresses representing all the addresses that a particular name

is resolves to.

The InetAddress class has no visible constructors. To create an InetAddress object, you

have to use one of the available factory methods. Factory methods are merely a

convention whereby static methods in a class return an instance of that class. This is

done in lieu of overloading a constructor with various parameter lists when having

unique method names makes the results much clearer. In the case ofInetAddress, the

three methods getLocalHost (), getByName (), and getAllByName () can be used to

create instances of InetAddress.

The getLocalHost ( ) method simply returns the InetAddress object that represents the

local host. The getByName ( ) method returns an InetAddress for a host name passed to

it. If these methods are unable to resolve the host name, they throw an

UnknownHostException.

On the Internet, it is common for a single name to be used to represent several

machines. In the world of web servers, this is one way to provide some degree of

scaling. The getAllByName( ) factory method returns an array of InetAddresses that

represent all of the addresses that a particular name resolves to. It will also throw an

UnknownHostException if it can’t resolve the name to at least one address.



b) What is RMI? Explain architecture of RMI.

Solution:

The Remote Method Invocation (RMI) is an API that provides a mechanism to create

distributed application in java. The RMI allows an object to invoke methods on an object

running in another JVM.The RMI provides remote communication between the

applications using two objects stub and skeleton.

The RMI system consists of three layers:

• The stub/skeleton layer – client-side stubs (proxies) and server-side skeletons

• The remote reference layer – remote reference behavior (such as invocation to a single

object or to a replicated object)

• The transport layer – connection set up and management and remote object tracking

The application layer sits on top of the RMI system. The relationship between the layers

is shown in the following figure.

A remote method invocation from a client to a remote server object travels down through

the layers of the RMI system to the client-side transport, then up through the server-side

transport to the server.

A client invoking a method on a remote server object actually makes use of a stub or

proxy for the remote object as a conduit to the remote object. A client- held reference to

a remote object is a reference to a local stub. This stub is an implementation of the

remote interfaces of the remote object and forwards invocation requests to that server

object via the remote reference layer. Stubs are generated using the rmic compiler.

The remote reference layer is responsible for carrying out the semantics of the

invocation. For example, the remote reference layer is responsible for determining

whether the server is a single object or is a replicated object requiring communications

with multiple locations. Each remote object implementation chooses its own remote

reference semantics-whether the server is a single object or is a replicated object

requiring communications with its replicas.

The transport layer is responsible for connection setup, connection management, and

keeping track of and dispatching to remote objects (the targets of remote calls) residing

in the transport’s address space.

In order to dispatch to a remote object, the transport forwards the remote call up to the

remote reference layer. The remote reference layer handles any server-side behavior

that needs to occur before handing off the request to the server-side skeleton. The

skeleton for a remote object makes an up call to the remote object implementation which

carries out the actual method call.

The return value of a call is sent back through the skeleton, remote reference layer, and

transport on the server side, and then up through the transport, remote reference layer,

and stub on the client side.

No comments:

Post a Comment