SlideShare uma empresa Scribd logo
1 de 8
1
MC0078 – Java Programming
Question 1- What are the difference between an interface and an abstract class?
An abstract class is a class that leaves one or more method implementations unspecified by
declaring one or more methods abstract. An abstract method has no body (i.e., no
implementation). A subclass is required to override the abstract method and provide an
implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can
be used as a base class.
An interface is a specification, or contract, for a set of methods that a class that implements
the interface must conform to in terms of the type signature of the methods. The class that
implements the interface provides an implementation for each method, just as with an
abstract method in an abstract class. So, you can think of an interface as an abstract class
with all abstract methods. The interface itself can have either public, package, private or
protected access defined. All methods declared in an interface are implicitly abstract and
implicitly public. It is not necessary, and in fact considered redundant to declare a method in
an interface to be abstract. You can define data in an interface, but it is less common to do
so. If there are data fields defined in an interface, then they are implicitly defined to be:
Public, Static and Final.
The main differences are:
1 Methods of a Java interface are implicitly abstract and cannot have implementations.
A Java abstract class can have instance methods that implement a default behavior.
2 Variables declared in a Java interface is by default final. An abstract class may
contain non-final variables.
3 Members of a Java interface are public by default. A Java abstract class can have
the usual flavors of class members like private, protected, etc..
4 Java interface should be implemented using keyword “implements”; A Java abstract
class should be extended using keyword “extends”.
5 An interface can extend another Java interface only; an abstract class can extend
another Java class and implement multiple Java interfaces.
6 A Java class can implement multiple interfaces but it can extend only one abstract
class.
7 Interface is absolutely abstract and cannot be instantiated; A Java abstract class also
cannot be instantiated, but can be invoked if a main() exists.
8 In comparison with java abstract classes, java interfaces are slow as it requires extra
indirection.
Question 2 - Explain the following with respect to Inheritance in Java:
a) Various Access Specifiers and their usage
Public members can be accessed by anybody. Private members can only be accessed by
member functions of the same class. The derived classes cannot access private members.
The protected access specifier restricts access to member functions of the same class, or
those of derived classes.
Second, when a derived class inherits from a base class, the access specifiers may change
depending on the method of inheritance. There are three different ways for classes to inherit
from other classes: public, private, and protected.
2
class Pub: public Base {}; // inherit from Base publicly
class Pri: private Base {}; // inherit from Base privately
class Pro: protected Base {}; // inherit from Base protectedly
There are three ways that members can be accessed:
● A class can always access its own members regardless of access specifier.
● The public accesses the members of a class based on the access specifiers of that
class.
● A derived class accesses inherited members based on the access specifiers of its
immediate parent. A derived class can always access its own members regardless of
access specifier.
Public inheritance - When inherit a base class publicly, all members keep their original
access specifications. Private members stay private, protected members stay protected, and
public members stay public.
Private inheritance - With private inheritance, all members from the base class are inherited
as private. This means private members stay private, and protected and public members
become private. Note that this does not affect that way that the derived class accesses
members inherited from its parent! It only affects the code trying to access those members
through the derived class.
Protected inheritance - Protected inheritance is the last method of inheritance. It is almost
never used, except in very particular cases. With protected inheritance, the public and
protected members become protected, and private members stay private. Protected
inheritance is similar to private inheritance. However, classes derived from the derived class
still have access to the public and protected members directly. The public (stuff outside the
class) does not.
The way that the access specifiers, inheritance types, and derived classes interact causes a
lot of confusion. To try and clarify things as much as possible: First, the base class sets it’s
access specifiers. The base class can always access its own members. The access
specifiers only affect whether outsiders and derived classes can access those members.
Second, derived classes have access to base class members based on the access
specifiers of the immediate parent. The way a derived class accesses inherited members is
not affected by the inheritance method used! Finally, derived classes can change the access
type of inherited members based on the inheritance method used. This does not affect the
derived classes own members, which have their own access specifiers. It only affects
whether outsiders and classes derived from the derived class can access those inherited
members.
b) Abstract classes and their applications
An abstract class is a class that leaves one or more method implementations unspecified by
declaring one or more methods abstract. An abstract method has no body (i.e., no
implementation). A subclass is required to override the abstract method and provide an
implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can
be used as a base class.
abstract public class abstract-base-class-name {
// abstract class has at least one abstract method
public abstract return-type abstract-method-name ( formal-params );
}
3
public class derived-class-name extends abstract-base-class-name {
public return-type abstract-method-name (formal-params) { stmt-list; }
... // other method implementations
}
It would be an error to try to instantiate an object of an abstract type:
abstract-class-name obj = new abstract-class-name();
That is, operator new is invalid when applied to an abstract class.
abstract class Point {
private int x, y;
public Point(int x, int y) { this.x = x; this.y = y; }
public void move(int dx, int dy) { x += dx; y += dy; plot(); }
public abstract void plot(); // has no implementation
}
abstract class ColoredPoint extends Point {
private int color;
protected public ColoredPoint(int x, int y, int color){super(x, y); this.color = color; }
}
class SimpleColoredPoint extends ColoredPoint {
public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); }
public void plot() { ... } // code to plot a SimpleColoredPoint
}
Since ColoredPoint does not provide an implementation of the plot method, it must be
declared abstract. The SimpleColoredPoint class does implement the inherited plot method.
It would be an error to try to instantiate a Point object or a ColoredPoint object. However,
you can declare a Point reference and initialize it with an instance of a subclass object that
implements the plot method:
Point p = new SimpleColoredPoint(a, b, red); p.plot();
An abstract class mixes the idea of mutable data in the form of instance variables, non-
abstract methods, and abstract methods. An abstract class with only static final instance
variables and all abstract methods is called an interface.
Question 3 - Describe Exception Handling in JAVA
An exception is a problem that arises during the execution of a program. An exception can
occur for many different reasons, including the following:
1 A user has entered invalid data.
2 A file that needs to be opened cannot be found.
3 A network connection has been lost in the middle of communications, or the JVM has
run out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
There are three categories of exceptions:
4
1 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.
2 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.
3 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.
Exception Hierarchy:
All exception classes are subtypes of the java.lang.Exception class. The exception class is a
subclass of the Throwable class. Other than the exception class there is another subclass
called Error which is derived from the Throwable class. Errors are not normally trapped form
the Java programs. These conditions normally happen in case of severe failures, which are
not handled by the java programs. Errors are generated to indicate errors generated by the
runtime environment. Example : JVM is out of Memory. Normally programs cannot recover
from errors. The Exception class has two main subclasses : IOException class and
RuntimeException Class.
Catching Exceptions: A method catches an exception using a combination of the try and
catch keywords. A try/catch block is placed around the code that might generate an
exception. Code within a try/catch block is referred to as protected code, and the syntax for
using try/catch looks like the following:
try
{
//Protected code
}catch(ExceptionName e1)
{
//Catch block
}
A catch statement involves declaring the type of exception you are trying to catch. If an
exception occurs in protected code, the catch block (or blocks) that follow the try is checked.
If the type of exception that occurred is listed in a catch block, the exception is passed to the
catch block much as an argument is passed into a method parameter.
Common Exceptions: In java it is possible to define two categories of Exceptions and Errors.
1 JVM Exceptions: - These are exceptions/errors that are exclusively or logically
thrown by the JVM. Examples : NullPointerException,
ArrayIndexOutOfBoundsException, ClassCastException,
2 Programmatic exceptions . These exceptions are thrown explicitly by the
application or the API programmers Examples: IllegalArgumentException,
IllegalStateException.
Question 4 - What do you mean by Object Adapter? Explain with an example?
In a class adapter design, the new adapter class implements the desired interface and
subclasses an existing class. This approach will not always work, notably when the set of
methods that need to adapt is not specified in an interface.
5
In such a case, create an object adapter—an adapter that uses delegation rather than
subclassing. We can create an object adapter by subclassing the class that you need,
fulfilling the required methods by relying on an object of an existing class. The NewClass
class is an example of Adapter. An instance of this class is an instance of the RequiredClass
class. In other words, the NewClass class meets the needs of the client. The NewClass
class can adapt the ExistingClass class to meet the client’s needs by using an instance of
ExistingClass.
Question 5 - Describe the following with respect to implementation of Sockets in Java:
a) Reading from and Writing to a Socket b) Writing the Server Side of a Socket
a) Reading from and Writing to a Socket
The Socket class in the java.net package is a platform-independent implementation of the
client end of a two-way communication link between a client and a server. 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.
This client program, EchoTest, connects to the standard Echo server (on port 7) via a
socket. The client both reads from and writes to the socket. EchoTest sends all text typed
into its standard input to the Echo server by writing the text to the socket. The server echos
all input it receives from the client 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 EchoTest {
public static void main(String[] args) {
Socket echoSocket = null;
DataOutputStream os = null;
DataInputStream is = null;
DataInputStream stdIn = new DataInputStream(System.in);
try {
echoSocket = new Socket("taranis", 7);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
6
} catch (UnknownHostException e) {
System.err.println("Don't know about host: taranis");
} catch (IOException e) {
System.err.println("Couldn't get I/O for the connection to: taranis");
}
if (echoSocket != null && os != null && is != null) {
try {
String userInput;
while ((userInput = stdIn.readLine()) != null) {
os.writeBytes(userInput);
os.writeByte('n');
System.out.println("echo: " + is.readLine());
}
os.close();
is.close();
echoSocket.close();
} catch (IOException e) {
System.err.println("I/O failed on the connection to: taranis");
}}}}
The first line in this sequence creates a new Socket object and names it echoSocket.
echoSocket = new Socket("taranis", 7);
os = new DataOutputStream(echoSocket.getOutputStream());
is = new DataInputStream(echoSocket.getInputStream());
The Socket constructor used here (there are three others) requires the name of the machine
and the port number that you want to connect to. The example program uses the hostname
taranis, which is the name of a (hypothetical) machine on our local network. When you type
in and run this program on your machine, you should change this 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 that you want to connect to. The second argument is the port number. Port number
7 is the port that the Echo server listens to. The second line in the code snippet above opens
an output stream on the socket, and the third line opens an inputstream on the socket.
EchoTest merely needs to write to the output stream and read from the input stream to
communicate through the socket to the server. The rest of the program achieves this. If you
are not yet familiar with input and output streams, you may wish to read Input and Output
Streams. The next section of code reads from Echo Test's standard input stream (where the
user can type data) a line at a time. EchoTest immediately writes the input text followed by a
newline character to the output stream connected to the socket.
String userInput;
while ((userInput = stdIn.readLine()) != null) {
os.writeBytes(userInput);
os.writeByte('n');
System.out.println("echo: " + is.readLine());
}
The last line in the while loop reads a line of information from the input stream connected to
the socket. The readLine() method blocks until the server echos the information back to
EchoTest. When readline() returns, EchoTest prints the information to the standard output.
This loop continues--EchoTest reads input from the user, sends it to the Echo server, gets a
response from the server and displays it--until the user types an end-of-input character.
7
When the user types an end-of-input character, the while loop terminates and the program
continues, executing the next three lines of code:
os.close();
is.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 three lines of code close the
input and output streams connected to the socket, 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, the server echos 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 streams.
5 Close sockets.
Only step 3 differs from client to client, depending on the server. The other steps remain
largely the same.
b) Writing the Server Side of a Socket
ServerSocket is a java.net class that provides a system-independent implementation of the
server side of a client/server socket connection. Typically, the ServerSocket class sits on top
of a platform-dependent implementation hiding the details of any particular system from your
Java program. Thus, when working with ServerSockets, you should always use the
java.net.ServerSocket class and bypass the underlying system-dependent functions. In this
way, the Java programs will remain system neutral. The constructor for ServerSocket will
throw and exception if for some reason (the port is already in use) it could not listen on the
specified port. If the server successfully connected to its port, then the ServerSocket object
was successfully created and the server continues to the next step which is to accept a
connection from a client.
Socket clientSocket = null;
try {
clientSocket = serverSocket.accept();
} catch (IOException e) {
System.out.println("Accept failed: " + 4444 + ", " + e);
System.exit(1);
}
The accept() method blocks (waits) until a client starts up and connects to the same port (in
this case, port 4444) that the server is listening to. When the client requests a connection,
the accept() method accepts the connection, if nothing goes wrong, and returns a socket.
8
This Socket object is a reference to the socket that the client used to establish the
connection with the port. Now, both the server and the client are communicating to each
other via the Socket and the ServerSocket is out of the picture for now.
Question 6 - Define RMI. Define the architecture of RMI invocation.
Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network
programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably
powerful technology and exposes the average Java developer to an entirely new paradigm--
the world of distributed object computing. The design goal for the RMI architecture was to
create a Java distributed object model that integrates naturally into the Java programming
language and the local object model. RMI architects have succeeded; creating a system that
extends the safety and robustness of the Java architecture to the distributed computing
world.
Interfaces: The Heart of RMI
The RMI architecture is based on one important principle: the definition of behavior and the
implementation of that behavior are separate concepts. RMI allows the code that defines the
behavior and the code that implements the behavior to remain separate and to run on
separate JVMs.
Specifically, in RMI, the definition of a remote service is coded using a Java interface. The
implementation of the remote service is coded in a class. Therefore, the key to
understanding RMI is to remember that interfaces define behavior and classes define
implementation.RMI supports two classes that implement the same interface. The first class
is the implementation of the behavior, and it runs on the server. The second class acts as a
proxy for the remote service and it runs on the client.
A client program makes method calls on the proxy object, RMI sends the request to the
remote JVM, and forwards it to the implementation. Any return values provided by the
implementation are sent back to the proxy and then to the client's program.
RMI Architecture Layers - The RMI implementation is essentially built from three
abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view
of the developer. This layer intercepts method calls made by the client to the interface
reference variable and redirects these calls to a remote RMI service.The next layer is the
Remote Reference Layer. This layer understands how to interpret and manage references
made from clients to the remote service objects. The transport layer is based on TCP/IP
connections between machines in a network. It provides basic connectivity, as well as some
firewall penetration strategies.
Stub and Skeleton Layer - The stub and skeleton layer of RMI lie just beneath the view of
the Java developer. In this layer, RMI uses the Proxy design pattern. In the Proxy pattern, an
object in one context is represented by another (the proxy) in a separate context. The proxy
knows how to forward method calls between the participating objects.
Remote Reference Layer - The Remote Reference Layers defines and supports the
invocation semantics of the RMI connection. This layer provides a RemoteRef object that
represents the link to the remote service implementation object.
The stub objects use the invoke() method in RemoteRef to forward the method call. The
RemoteRef object understands the invocation semantics for remote services.
Transport Layer - The Transport Layer makes the connection between JVMs. All
connections are stream-based network connections that use TCP/IP.Even if two JVMs are
running on the same physical computer, they connect through their host computer's TCP/IP
network protocol stack.

Mais conteúdo relacionado

Mais procurados

Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationHoneyChintal
 
Java interfaces
Java interfacesJava interfaces
Java interfacesjehan1987
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaEdureka!
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singhdheeraj_cse
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classesAKANSH SINGHAL
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & InterfaceLinh Lê
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsVinay Kumar
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceOum Saokosal
 
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...Edureka!
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for JavaGaruda Trainings
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAsivasundari6
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interfaceMazharul Sabbir
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for vivaVipul Naik
 

Mais procurados (20)

Interface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementationInterface in java ,multiple inheritance in java, interface implementation
Interface in java ,multiple inheritance in java, interface implementation
 
Java interfaces
Java interfacesJava interfaces
Java interfaces
 
What are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | EdurekaWhat are Abstract Classes in Java | Edureka
What are Abstract Classes in Java | Edureka
 
Interface
InterfaceInterface
Interface
 
Abstract class in java
Abstract class in javaAbstract class in java
Abstract class in java
 
Interface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar SinghInterface in java By Dheeraj Kumar Singh
Interface in java By Dheeraj Kumar Singh
 
Interfaces and abstract classes
Interfaces and abstract classesInterfaces and abstract classes
Interfaces and abstract classes
 
The smartpath information systems java
The smartpath information systems javaThe smartpath information systems java
The smartpath information systems java
 
Abstract & Interface
Abstract & InterfaceAbstract & Interface
Abstract & Interface
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Lecture 17
Lecture 17Lecture 17
Lecture 17
 
Java Programming - Abstract Class and Interface
Java Programming - Abstract Class and InterfaceJava Programming - Abstract Class and Interface
Java Programming - Abstract Class and Interface
 
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...What is Interface in Java | How to implement Multiple Inheritance Using Inter...
What is Interface in Java | How to implement Multiple Inheritance Using Inter...
 
Lecture 12
Lecture 12Lecture 12
Lecture 12
 
Interview Questions and Answers for Java
Interview Questions and Answers for JavaInterview Questions and Answers for Java
Interview Questions and Answers for Java
 
Java interfaces
Java   interfacesJava   interfaces
Java interfaces
 
WHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVAWHAT IS ABSTRACTION IN JAVA
WHAT IS ABSTRACTION IN JAVA
 
javainterface
javainterfacejavainterface
javainterface
 
Abstract class and interface
Abstract class and interfaceAbstract class and interface
Abstract class and interface
 
Java questions for viva
Java questions for vivaJava questions for viva
Java questions for viva
 

Semelhante a Master of Computer Application (MCA) – Semester 4 MC0078

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview QestionsArun Vasanth
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptxAsifMulani17
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core ParcticalGaurav Mehta
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdfParvizMirzayev2
 
Micro Anti-patterns in Java Code
Micro Anti-patterns in Java CodeMicro Anti-patterns in Java Code
Micro Anti-patterns in Java CodeGanesh Samarthyam
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesHabtamu Wolde
 
03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.pptJyothiAmpally
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and InterfacesJamsher bhanbhro
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interviewKuntal Bhowmick
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETDevLabs Alliance
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetdevlabsalliance
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfbca23189c
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDevLabs Alliance
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobGaruda Trainings
 

Semelhante a Master of Computer Application (MCA) – Semester 4 MC0078 (20)

Java/J2EE interview Qestions
Java/J2EE interview QestionsJava/J2EE interview Qestions
Java/J2EE interview Qestions
 
Abstraction in java.pptx
Abstraction in java.pptxAbstraction in java.pptx
Abstraction in java.pptx
 
Java Core Parctical
Java Core ParcticalJava Core Parctical
Java Core Parctical
 
this keyword in Java.pdf
this keyword in Java.pdfthis keyword in Java.pdf
this keyword in Java.pdf
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Micro Anti-patterns in Java Code
Micro Anti-patterns in Java CodeMicro Anti-patterns in Java Code
Micro Anti-patterns in Java Code
 
Object Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and InterfacesObject Oriented Programming - Polymorphism and Interfaces
Object Oriented Programming - Polymorphism and Interfaces
 
Core java by amit
Core java by amitCore java by amit
Core java by amit
 
03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt03_A-OOPs_Interfaces.ppt
03_A-OOPs_Interfaces.ppt
 
Abstraction in Java: Abstract class and Interfaces
Abstraction in  Java: Abstract class and InterfacesAbstraction in  Java: Abstract class and Interfaces
Abstraction in Java: Abstract class and Interfaces
 
Java questions for interview
Java questions for interviewJava questions for interview
Java questions for interview
 
Top 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDETTop 20 basic java interview questions for SDET
Top 20 basic java interview questions for SDET
 
Dev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdetDev labs alliance top 20 basic java interview question for sdet
Dev labs alliance top 20 basic java interview question for sdet
 
Java Core
Java CoreJava Core
Java Core
 
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdfch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
ch4 foohggggvvbbhhhhhhhhhbbbbbbbbbbbbp.pdf
 
Dev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdetDev labs alliance top 20 basic java interview questions for sdet
Dev labs alliance top 20 basic java interview questions for sdet
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Basic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a jobBasic java important interview questions and answers to secure a job
Basic java important interview questions and answers to secure a job
 
Java 06
Java 06Java 06
Java 06
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 

Mais de Aravind NC

MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DE
MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DEMC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DE
MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DEAravind NC
 
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...Aravind NC
 
MC0084 – Software Project Management & Quality Assurance - Master of Computer...
MC0084 – Software Project Management & Quality Assurance - Master of Computer...MC0084 – Software Project Management & Quality Assurance - Master of Computer...
MC0084 – Software Project Management & Quality Assurance - Master of Computer...Aravind NC
 
MC0082 –Theory of Computer Science
MC0082 –Theory of Computer ScienceMC0082 –Theory of Computer Science
MC0082 –Theory of Computer ScienceAravind NC
 
Master of Computer Application (MCA) – Semester 4 MC0080
Master of Computer Application (MCA) – Semester 4  MC0080Master of Computer Application (MCA) – Semester 4  MC0080
Master of Computer Application (MCA) – Semester 4 MC0080Aravind NC
 
Master of Computer Application (MCA) – Semester 4 MC0079
Master of Computer Application (MCA) – Semester 4  MC0079Master of Computer Application (MCA) – Semester 4  MC0079
Master of Computer Application (MCA) – Semester 4 MC0079Aravind NC
 
Master of Computer Application (MCA) – Semester 4 MC0077
Master of Computer Application (MCA) – Semester 4  MC0077Master of Computer Application (MCA) – Semester 4  MC0077
Master of Computer Application (MCA) – Semester 4 MC0077Aravind NC
 
Master of Computer Application (MCA) – Semester 4 MC0076
Master of Computer Application (MCA) – Semester 4  MC0076Master of Computer Application (MCA) – Semester 4  MC0076
Master of Computer Application (MCA) – Semester 4 MC0076Aravind NC
 

Mais de Aravind NC (10)

MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DE
MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DEMC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DE
MC0085 – Advanced Operating Systems - Master of Computer Science - MCA - SMU DE
 
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
MC0083 – Object Oriented Analysis &. Design using UML - Master of Computer Sc...
 
MC0084 – Software Project Management & Quality Assurance - Master of Computer...
MC0084 – Software Project Management & Quality Assurance - Master of Computer...MC0084 – Software Project Management & Quality Assurance - Master of Computer...
MC0084 – Software Project Management & Quality Assurance - Master of Computer...
 
MC0082 –Theory of Computer Science
MC0082 –Theory of Computer ScienceMC0082 –Theory of Computer Science
MC0082 –Theory of Computer Science
 
Master of Computer Application (MCA) – Semester 4 MC0080
Master of Computer Application (MCA) – Semester 4  MC0080Master of Computer Application (MCA) – Semester 4  MC0080
Master of Computer Application (MCA) – Semester 4 MC0080
 
Master of Computer Application (MCA) – Semester 4 MC0079
Master of Computer Application (MCA) – Semester 4  MC0079Master of Computer Application (MCA) – Semester 4  MC0079
Master of Computer Application (MCA) – Semester 4 MC0079
 
Master of Computer Application (MCA) – Semester 4 MC0077
Master of Computer Application (MCA) – Semester 4  MC0077Master of Computer Application (MCA) – Semester 4  MC0077
Master of Computer Application (MCA) – Semester 4 MC0077
 
Master of Computer Application (MCA) – Semester 4 MC0076
Master of Computer Application (MCA) – Semester 4  MC0076Master of Computer Application (MCA) – Semester 4  MC0076
Master of Computer Application (MCA) – Semester 4 MC0076
 
Time travel
Time travelTime travel
Time travel
 
Google x
Google xGoogle x
Google x
 

Último

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 

Último (20)

Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 

Master of Computer Application (MCA) – Semester 4 MC0078

  • 1. 1 MC0078 – Java Programming Question 1- What are the difference between an interface and an abstract class? An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. An interface is a specification, or contract, for a set of methods that a class that implements the interface must conform to in terms of the type signature of the methods. The class that implements the interface provides an implementation for each method, just as with an abstract method in an abstract class. So, you can think of an interface as an abstract class with all abstract methods. The interface itself can have either public, package, private or protected access defined. All methods declared in an interface are implicitly abstract and implicitly public. It is not necessary, and in fact considered redundant to declare a method in an interface to be abstract. You can define data in an interface, but it is less common to do so. If there are data fields defined in an interface, then they are implicitly defined to be: Public, Static and Final. The main differences are: 1 Methods of a Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implement a default behavior. 2 Variables declared in a Java interface is by default final. An abstract class may contain non-final variables. 3 Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private, protected, etc.. 4 Java interface should be implemented using keyword “implements”; A Java abstract class should be extended using keyword “extends”. 5 An interface can extend another Java interface only; an abstract class can extend another Java class and implement multiple Java interfaces. 6 A Java class can implement multiple interfaces but it can extend only one abstract class. 7 Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. 8 In comparison with java abstract classes, java interfaces are slow as it requires extra indirection. Question 2 - Explain the following with respect to Inheritance in Java: a) Various Access Specifiers and their usage Public members can be accessed by anybody. Private members can only be accessed by member functions of the same class. The derived classes cannot access private members. The protected access specifier restricts access to member functions of the same class, or those of derived classes. Second, when a derived class inherits from a base class, the access specifiers may change depending on the method of inheritance. There are three different ways for classes to inherit from other classes: public, private, and protected.
  • 2. 2 class Pub: public Base {}; // inherit from Base publicly class Pri: private Base {}; // inherit from Base privately class Pro: protected Base {}; // inherit from Base protectedly There are three ways that members can be accessed: ● A class can always access its own members regardless of access specifier. ● The public accesses the members of a class based on the access specifiers of that class. ● A derived class accesses inherited members based on the access specifiers of its immediate parent. A derived class can always access its own members regardless of access specifier. Public inheritance - When inherit a base class publicly, all members keep their original access specifications. Private members stay private, protected members stay protected, and public members stay public. Private inheritance - With private inheritance, all members from the base class are inherited as private. This means private members stay private, and protected and public members become private. Note that this does not affect that way that the derived class accesses members inherited from its parent! It only affects the code trying to access those members through the derived class. Protected inheritance - Protected inheritance is the last method of inheritance. It is almost never used, except in very particular cases. With protected inheritance, the public and protected members become protected, and private members stay private. Protected inheritance is similar to private inheritance. However, classes derived from the derived class still have access to the public and protected members directly. The public (stuff outside the class) does not. The way that the access specifiers, inheritance types, and derived classes interact causes a lot of confusion. To try and clarify things as much as possible: First, the base class sets it’s access specifiers. The base class can always access its own members. The access specifiers only affect whether outsiders and derived classes can access those members. Second, derived classes have access to base class members based on the access specifiers of the immediate parent. The way a derived class accesses inherited members is not affected by the inheritance method used! Finally, derived classes can change the access type of inherited members based on the inheritance method used. This does not affect the derived classes own members, which have their own access specifiers. It only affects whether outsiders and classes derived from the derived class can access those inherited members. b) Abstract classes and their applications An abstract class is a class that leaves one or more method implementations unspecified by declaring one or more methods abstract. An abstract method has no body (i.e., no implementation). A subclass is required to override the abstract method and provide an implementation. Hence, an abstract class is incomplete and cannot be instantiated, but can be used as a base class. abstract public class abstract-base-class-name { // abstract class has at least one abstract method public abstract return-type abstract-method-name ( formal-params ); }
  • 3. 3 public class derived-class-name extends abstract-base-class-name { public return-type abstract-method-name (formal-params) { stmt-list; } ... // other method implementations } It would be an error to try to instantiate an object of an abstract type: abstract-class-name obj = new abstract-class-name(); That is, operator new is invalid when applied to an abstract class. abstract class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } public void move(int dx, int dy) { x += dx; y += dy; plot(); } public abstract void plot(); // has no implementation } abstract class ColoredPoint extends Point { private int color; protected public ColoredPoint(int x, int y, int color){super(x, y); this.color = color; } } class SimpleColoredPoint extends ColoredPoint { public SimpleColoredPoint(int x, int y, int color) { super(x,y,color); } public void plot() { ... } // code to plot a SimpleColoredPoint } Since ColoredPoint does not provide an implementation of the plot method, it must be declared abstract. The SimpleColoredPoint class does implement the inherited plot method. It would be an error to try to instantiate a Point object or a ColoredPoint object. However, you can declare a Point reference and initialize it with an instance of a subclass object that implements the plot method: Point p = new SimpleColoredPoint(a, b, red); p.plot(); An abstract class mixes the idea of mutable data in the form of instance variables, non- abstract methods, and abstract methods. An abstract class with only static final instance variables and all abstract methods is called an interface. Question 3 - Describe Exception Handling in JAVA An exception is a problem that arises during the execution of a program. An exception can occur for many different reasons, including the following: 1 A user has entered invalid data. 2 A file that needs to be opened cannot be found. 3 A network connection has been lost in the middle of communications, or the JVM has run out of memory. Some of these exceptions are caused by user error, others by programmer error, and others by physical resources that have failed in some manner. There are three categories of exceptions:
  • 4. 4 1 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. 2 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. 3 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. Exception Hierarchy: All exception classes are subtypes of the java.lang.Exception class. The exception class is a subclass of the Throwable class. Other than the exception class there is another subclass called Error which is derived from the Throwable class. Errors are not normally trapped form the Java programs. These conditions normally happen in case of severe failures, which are not handled by the java programs. Errors are generated to indicate errors generated by the runtime environment. Example : JVM is out of Memory. Normally programs cannot recover from errors. The Exception class has two main subclasses : IOException class and RuntimeException Class. Catching Exceptions: A method catches an exception using a combination of the try and catch keywords. A try/catch block is placed around the code that might generate an exception. Code within a try/catch block is referred to as protected code, and the syntax for using try/catch looks like the following: try { //Protected code }catch(ExceptionName e1) { //Catch block } A catch statement involves declaring the type of exception you are trying to catch. If an exception occurs in protected code, the catch block (or blocks) that follow the try is checked. If the type of exception that occurred is listed in a catch block, the exception is passed to the catch block much as an argument is passed into a method parameter. Common Exceptions: In java it is possible to define two categories of Exceptions and Errors. 1 JVM Exceptions: - These are exceptions/errors that are exclusively or logically thrown by the JVM. Examples : NullPointerException, ArrayIndexOutOfBoundsException, ClassCastException, 2 Programmatic exceptions . These exceptions are thrown explicitly by the application or the API programmers Examples: IllegalArgumentException, IllegalStateException. Question 4 - What do you mean by Object Adapter? Explain with an example? In a class adapter design, the new adapter class implements the desired interface and subclasses an existing class. This approach will not always work, notably when the set of methods that need to adapt is not specified in an interface.
  • 5. 5 In such a case, create an object adapter—an adapter that uses delegation rather than subclassing. We can create an object adapter by subclassing the class that you need, fulfilling the required methods by relying on an object of an existing class. The NewClass class is an example of Adapter. An instance of this class is an instance of the RequiredClass class. In other words, the NewClass class meets the needs of the client. The NewClass class can adapt the ExistingClass class to meet the client’s needs by using an instance of ExistingClass. Question 5 - Describe the following with respect to implementation of Sockets in Java: a) Reading from and Writing to a Socket b) Writing the Server Side of a Socket a) Reading from and Writing to a Socket The Socket class in the java.net package is a platform-independent implementation of the client end of a two-way communication link between a client and a server. 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. This client program, EchoTest, connects to the standard Echo server (on port 7) via a socket. The client both reads from and writes to the socket. EchoTest sends all text typed into its standard input to the Echo server by writing the text to the socket. The server echos all input it receives from the client 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 EchoTest { public static void main(String[] args) { Socket echoSocket = null; DataOutputStream os = null; DataInputStream is = null; DataInputStream stdIn = new DataInputStream(System.in); try { echoSocket = new Socket("taranis", 7); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream());
  • 6. 6 } catch (UnknownHostException e) { System.err.println("Don't know about host: taranis"); } catch (IOException e) { System.err.println("Couldn't get I/O for the connection to: taranis"); } if (echoSocket != null && os != null && is != null) { try { String userInput; while ((userInput = stdIn.readLine()) != null) { os.writeBytes(userInput); os.writeByte('n'); System.out.println("echo: " + is.readLine()); } os.close(); is.close(); echoSocket.close(); } catch (IOException e) { System.err.println("I/O failed on the connection to: taranis"); }}}} The first line in this sequence creates a new Socket object and names it echoSocket. echoSocket = new Socket("taranis", 7); os = new DataOutputStream(echoSocket.getOutputStream()); is = new DataInputStream(echoSocket.getInputStream()); The Socket constructor used here (there are three others) requires the name of the machine and the port number that you want to connect to. The example program uses the hostname taranis, which is the name of a (hypothetical) machine on our local network. When you type in and run this program on your machine, you should change this 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 that you want to connect to. The second argument is the port number. Port number 7 is the port that the Echo server listens to. The second line in the code snippet above opens an output stream on the socket, and the third line opens an inputstream on the socket. EchoTest merely needs to write to the output stream and read from the input stream to communicate through the socket to the server. The rest of the program achieves this. If you are not yet familiar with input and output streams, you may wish to read Input and Output Streams. The next section of code reads from Echo Test's standard input stream (where the user can type data) a line at a time. EchoTest immediately writes the input text followed by a newline character to the output stream connected to the socket. String userInput; while ((userInput = stdIn.readLine()) != null) { os.writeBytes(userInput); os.writeByte('n'); System.out.println("echo: " + is.readLine()); } The last line in the while loop reads a line of information from the input stream connected to the socket. The readLine() method blocks until the server echos the information back to EchoTest. When readline() returns, EchoTest prints the information to the standard output. This loop continues--EchoTest reads input from the user, sends it to the Echo server, gets a response from the server and displays it--until the user types an end-of-input character.
  • 7. 7 When the user types an end-of-input character, the while loop terminates and the program continues, executing the next three lines of code: os.close(); is.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 three lines of code close the input and output streams connected to the socket, 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, the server echos 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 streams. 5 Close sockets. Only step 3 differs from client to client, depending on the server. The other steps remain largely the same. b) Writing the Server Side of a Socket ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. Typically, the ServerSocket class sits on top of a platform-dependent implementation hiding the details of any particular system from your Java program. Thus, when working with ServerSockets, you should always use the java.net.ServerSocket class and bypass the underlying system-dependent functions. In this way, the Java programs will remain system neutral. The constructor for ServerSocket will throw and exception if for some reason (the port is already in use) it could not listen on the specified port. If the server successfully connected to its port, then the ServerSocket object was successfully created and the server continues to the next step which is to accept a connection from a client. Socket clientSocket = null; try { clientSocket = serverSocket.accept(); } catch (IOException e) { System.out.println("Accept failed: " + 4444 + ", " + e); System.exit(1); } The accept() method blocks (waits) until a client starts up and connects to the same port (in this case, port 4444) that the server is listening to. When the client requests a connection, the accept() method accepts the connection, if nothing goes wrong, and returns a socket.
  • 8. 8 This Socket object is a reference to the socket that the client used to establish the connection with the port. Now, both the server and the client are communicating to each other via the Socket and the ServerSocket is out of the picture for now. Question 6 - Define RMI. Define the architecture of RMI invocation. Remote Method Invocation (RMI) technology, first introduced in JDK 1.1, elevates network programming to a higher plane. Although RMI is relatively easy to use, it is a remarkably powerful technology and exposes the average Java developer to an entirely new paradigm-- the world of distributed object computing. The design goal for the RMI architecture was to create a Java distributed object model that integrates naturally into the Java programming language and the local object model. RMI architects have succeeded; creating a system that extends the safety and robustness of the Java architecture to the distributed computing world. Interfaces: The Heart of RMI The RMI architecture is based on one important principle: the definition of behavior and the implementation of that behavior are separate concepts. RMI allows the code that defines the behavior and the code that implements the behavior to remain separate and to run on separate JVMs. Specifically, in RMI, the definition of a remote service is coded using a Java interface. The implementation of the remote service is coded in a class. Therefore, the key to understanding RMI is to remember that interfaces define behavior and classes define implementation.RMI supports two classes that implement the same interface. The first class is the implementation of the behavior, and it runs on the server. The second class acts as a proxy for the remote service and it runs on the client. A client program makes method calls on the proxy object, RMI sends the request to the remote JVM, and forwards it to the implementation. Any return values provided by the implementation are sent back to the proxy and then to the client's program. RMI Architecture Layers - The RMI implementation is essentially built from three abstraction layers. The first is the Stub and Skeleton layer, which lies just beneath the view of the developer. This layer intercepts method calls made by the client to the interface reference variable and redirects these calls to a remote RMI service.The next layer is the Remote Reference Layer. This layer understands how to interpret and manage references made from clients to the remote service objects. The transport layer is based on TCP/IP connections between machines in a network. It provides basic connectivity, as well as some firewall penetration strategies. Stub and Skeleton Layer - The stub and skeleton layer of RMI lie just beneath the view of the Java developer. In this layer, RMI uses the Proxy design pattern. In the Proxy pattern, an object in one context is represented by another (the proxy) in a separate context. The proxy knows how to forward method calls between the participating objects. Remote Reference Layer - The Remote Reference Layers defines and supports the invocation semantics of the RMI connection. This layer provides a RemoteRef object that represents the link to the remote service implementation object. The stub objects use the invoke() method in RemoteRef to forward the method call. The RemoteRef object understands the invocation semantics for remote services. Transport Layer - The Transport Layer makes the connection between JVMs. All connections are stream-based network connections that use TCP/IP.Even if two JVMs are running on the same physical computer, they connect through their host computer's TCP/IP network protocol stack.