Upload
navya-rao
View
105
Download
2
Embed Size (px)
Citation preview
1. Write a short note on the advantages/features of JFC.
(Any 6: 1M each) [1] Pluggable Look and Feel: Instead of being restricted to a single
"look and feel", we can select a look and feel and "plug it in". An interface made of Swing components can look like a Win32 app, a
Motif app, or a Mac app. It can use the new "Metal" look and feel. Developers can use standard Swing components and design their own
look and feel (L&F) for them, and even allow users to select the look and feel they prefer. The plaf package includes the standard
"Pluggable Look And Feel" classes. [2] MVC Architecture: The Model-View-Controller (MVC) architecture
is used consistently throughout the Swing component set. The View and Controller parts of the architecture are combined in the
component. Each component has an associated Model class and an interface it uses. We can provide our own data-model for a
component by subclassing the Model class or by implementing the appropriate interface.
[3] Keystroke Handling: The JComponent architecture makes it easy to handle keyboard events in nested components. [4] Action Objects: Action-interface objects provide a single point of
control for program actions. [5] Virtual Desktops: The JDesktopPane and JInternalFrame classes
can be used to create a virtual desktop, or "multiple document interface". A JInternalFrame can be specified as iconizable,
expandable, or closable, while the JDesktopPane provides real estate for them to operate in.
[6] Compound Borders: Insets (the space between the edges of the component and the area it is drawn in) can be specified with a blank
border. In addition, many border styles are available, which can be combined to create compound borders.
[7] Customized Dialogs: The JOptionPane class provides a variety of static methods that you can invoke to create and display both
message dialogs and user-choice dialogs in a variety of formats. [8] Standard Dialog Classes: Standard dialogs currently available
include: JFileChooser and JColorChooser [9] Structured Table and Tree Components: The JTable class
provides a data-aware matrix. JTree provides hierarchical-structuring of data elements.
[10] Powerful Text Manipulations: In addition to single-font text fields and text areas, Swing provides a JPassword field for hidden
input and a JTextPane class for displaying multi-font text. In addition, the JEditorPane class provides editing capabilities for multi-
font text, while the text.html and text.rtf packages handle text
encoded in HyperText Markup Language (HTML) or Rich Text Format (RTF).
[11] Generic Undo Capabilities: The undo package provides generic undo capabilities that can be used in a variety of situations.
[12] Accessibility Support: Swing has built-in support for developers to make products that are compatible with Assistive Technologies (for
alternative interfaces like, for example, braille.) All of the Swing components implement interface Accessible.
2. JScrollBar//difference ??
Class: javax.swing.JScrollBar Purpose: An implementation of a scrollbar. The user positions
the knob in the scrollbar to determine the contents of the viewing area. The program typically adjusts the display so that
the end of the scrollbar represents the end of the displayable contents, or 100% of the contents. The start of the scrollbar is
the beginning of the displayable contents, or 0%. The postion of the knob within those bounds then translates to the
corresponding percentage of the displayable contents. Typically, as the position of the knob in the scrollbar changes a
corresponding change is made to the position of the JViewport on the underlying view, changing the contents of the
JViewport. Constructor:
public JScrollBar() Creates a vertical scrollbar with the following initial values:
Creates a scrollbar with the specified orientation and the
following initial values orientation,int value,int extent,int
min,int max) Creates a scrollbar with the specified orientation, value, extent,
mimimum, and maximum. METHODS :
Void setMaximum(int maximum) Sets the models maximum property
Void setMinimum(int minimum) Sets the models minimum property
Void setOrientation(int orientation)
Set the scrollbar orientation to either vertical or horizontal Void setBlockIncremement(int blockincrement)
Sets the blockincrement property
Void setenabled (Boolean x) Enables the component so that the knob position can be
changed Void addAdjustmentListener(adjustmentListner )
Adds an adjustment listener
DIFFERENCE: Jscrollbar controls should be dded to the control that needs
scrolling and a programmer has to write code on events to change the contents of view to show the effect of scrolling . In
jscrollpane scrolling happens automatically
3.JCheckbox Class: javax.swing.JCheckBox
Purpose: An implementation of a check box -- an item that can be selected or deselected, and which displays its state to
the user. By convention, any number of check boxes in a group can be selected.
Constructor: Creates an initially unselected check box button with no text,
no icon. unselected
check box with an icon.
Creates a check box with an icon and specifies whether or not
it is initially selected.
Creates an initially unselected check box with text.
. public JCheckBox( String text,boolean selected)
Creates a check box with text and specifies whether or not it is initially selected.
METHOD: String getLabel() Get a label of checkbox Void setlabel(string s) Set label for a check box Boolean getstate() Get the status of checkbox Void setstate(Boolean b) Set the status of checkbox whether selected or unselected Example:
Extensive book
4.JOptionPane
Class: javax.swing.JOptionPane Purpose:
JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something.
While the JOptionPane class may appear complex because of the large number of methods, almost all uses of this class are one-line
calls to one of the static showXxxDialog methods shown below: showConfirmDialog Asks a confirming question, like yes/no/cancel.
showInputDialog Prompt for some input. showMessageDialog Tell the user about something that has happened. showOptionDialog The
Grand Unification of the above three. Constructor:
public JOptionPane(Object message)
Creates a instance of JOptionPane to display a message using
the plain-message message type and the default options delivered by the UI
Parameters: message - the Object to display
public JOptionPane(Object message,int messageType)
Creates an instance of JOptionPane to display a message with the specified message type and the default options,
Parameters: messageType - the type of message to be displayed:
ERROR_MESSAGE, INFORMATION_MESSAGE,
WARNING_MESSAGE, QUESTION_MESSAGE, or PLAIN_MESSAGE
public JOptionPane(Object message,int messageType,int optionType)
Creates an instance of JOptionPane to display a message with the
specified message type and options. Parameters: optionType - the options to display in the pane: DEFAULT_OPTION, YES_NO_OPTION, YES_NO_CANCEL_OPTION OK_CANCEL_OPTION
public JOptionPane(Object message,int messageType,int optionType,Icon icon)
Creates an instance of JOptionPane to display a message with the specified message type, options, and icon. Parameters: icon - the Icon image to display
public JOptionPane(Object message,int messageType,int optionType,Icon icon,Object[] options)
Creates an instance of JOptionPane to display a message with the
specified message type, icon, and options. None of the options is initially selected. objects should contain either instances of
Components, (which are added directly) or Strings (which are wrapped in a JButton). If you provide Components, you must ensure
that when the Component is clicked it messages setValue in the created JOptionPane.
Parameters: options - the choices the user can select
public JOptionPane(Object message,int messageType,int
optionType,Icon icon,Object[] options,Object initialValue)
Creates an instance of JOptionPane to display a message with the
specified message type, icon, and options, with the initially-selected option specified.
Parameters: initialValue - the choice that is initially selected
METHOD:
5. Write a short note on JFileChooser class.//explain JFileChooser class with one method (Purpose) JFileChooser is a panel that allows users to browse the
contents of the file system and select a file to open or a file to save. The following code pops up a file chooser for the user's home
directory that sees only .jpg and .gif images:
JFileChooser chooser = new JFileChooser(); FileNameExtensionFilter filter = new FileNameExtensionFilter("JPG &
GIF Images", "jpg", "gif"); chooser.setFileFilter(filter);
int returnVal = chooser.showOpenDialog(parent); if(returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName()); }
/* [ public FileNameExtensionFilter(String description, String...
extensions):
Creates a FileNameExtensionFilter with the specified description and file name extensions. The returnedFileNameExtensionFilter will accept all directories and any file with a file name extension contained in extensions ] */
Constructors
1) JFileChooser():
2) JFileChooser (File currentDirectory): 3) JFileChooser (FileSystemView fsview):
4) JFileChooser (String currentDirectoryPath): 5) JFileChooser (File currentDirectory, FileSystemView fsView):
6) JFileChooser (String currentDirectoryPath, FileSystemView fsView):
The file selection begins in the user’s home directory, if no current
directory is specified as either a File object or a string. The FieSystemView object is an object that encapsulates the details of
the host system’s file system. To display the chooser, we use either method showOpenDialog or the method showSaveDialog,
Methods 1) public int showOpenDialog(Component parent) throws
HeadlessException
Pops up an "Open File" file chooser dialog. Note that the text that appears in the approve button is determined by the L&F. The return
state of the file chooser on popdown is:
dismissed
2) public int showSaveDialog(Component parent) throws HeadlessException
Pops up a "Save File" file chooser dialog. Note that the text that
appears in the approve button is determined by the L&F. The return state of the file chooser on popdown is:
R_OPTION if an error occurs or the dialog is dismissed
/* //JFileChooser.java
import javax.swing.*; import java.awt.*;
import java.awt.event.*; public class JFileChooserDemo extends JPanel implements
ActionListener { JButton go;
JFileChooser chooser; String choosertitle;
public JFileChooserDemo() { go = new JButton("Do it");
go.addActionListener(this); add(go);
} public void actionPerformed(ActionEvent e) {
int result; chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File(".")); chooser.setDialogTitle(choosertitle);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); //chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTOR
IES); chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
System.out.println("getSelectedFile() : " + chooser.getSelectedFile()); }
else { System.out.println("No Selection ");
} }
public Dimension getPreferredSize(){ return new Dimension(200, 200);
} public static void main(String s[]) {
JFrame frame = new JFrame("File Dialog Box"); JFileChooserDemo panel = new JFileChooserDemo();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(panel,"Center");
frame.setSize(panel.getPreferredSize()); frame.setVisible(true);
} }
*/ METHOD:
6. State and explain methods of Thread Synchronization. // how
to synchronize thread explain with example (1M for each point)
When two or more threads need access to a shared resource, they
need some way to ensure that the resource will be used by only one thread at a time.
.This process by which this is achieved is called thread synchronization. In other words, synchronization is the way to avoid data
corruption caused by simultaneous access to the same shared data. Because all threads in a program share the same memory space,
it is possible for two threads to access the same variable or run the same method of the same object at same time.
Problems may occur when multiple Threads are accessing the same data concurrently.
Some mechanism is needed to block one Thread’s access to the critical data, if the data is being worked on by another thread.
To avoid polling, Java includes an elegant interprocess communication mechanism via the following methods:
wait( ): This method tells the calling thread to give up the monitor and go to sleep until some other thread enters the same monitor and
calls notify( ). notify( ): This method wakes up the first thread that called wait( )
on the same object. notifyAll( ): This method wakes up all the threads that called wait(
) on the same object. The highest priority thread will run first. These methods are implemented as final methods in Object, so all
classes have them. All three methods can be called only from within a synchronized context.
Synchronization can be done in two ways
[1] A method can be synchronized by using the synchronized keyword as a modifier in the method declaration. Its syntax is as follows:
synchronized void deposit(int amount, String name)
[2] To synchronize access to common data is via a synchronized statement block. This has the following syntax:
synchronized(obj)
{ //statement block
} here, obj is the object to be locked.
7. Write short note on Life cycle of Thread (1M each)
A thread goes through various stages in its life cycle. For example, a thread is born, started, runs and then dies. Following diagram shows
complete life cycle of a thread.
1) New state: this is when the threadable / Thread object is first created by calling the constructor of the Thread class. For example,
our thread is in new state after this statement Thread newThread = new (runnableObj, threadName);
2) Runnable / Ready-to-run state: after calling the start() method
on the thread, it enters the runnable state. That means it is ready to run or to go to some other states. As of the current version of Java, a
thread must enter the runnable state before going to any other state. 3) Running state: a thread is in this state while its run() method is
executing. During this state, the thread can go to blocked state if it gets blocked or has to wait for other threads. When the run() method
finishes, this state ends. 4) Blocked/waiting state: while running a thread can be put to
sleep, interrupted or blocked by other threads. 5) Terminated / dead state: when a thread reaches this state, its life
ends. It can never be revived again. Normally, a thread enters this state because its run() method has ended. However, a thread can also
be terminated even before it is in the runnable state or during the waiting state by calling stop() or suspense() on the thread. Using any
of those methods to move a thread to its terminated state is not suggested because those methods have been deprecated by Java and
are not thread safe. Therefore, ending the run() method is the best way to go.
8. Write a short note on the ResultSet interface of the java.sql
package OR What is a ResultSet? State various types of ResultSet. How to
access data in ResultSet? (3M description + 3M for example)
ResultSet is a table of data representing a database result set, which is usually
generated by executing a statement that queries the database. A ResultSet object maintains a cursor pointing to its current row of data.
Initially the cursor is positioned before the first row. The next method moves the cursor to the next row, and because it returns
false when there are no more rows in the ResultSet object, it can be used in a while loop to iterate through the result set.
A default ResultSet object is not updatable and has a cursor that moves forward only.
Thus, we can iterate through it only once and only from the first row to the last row.
It is possible to produce ResultSet objects that are scrollable and/or updatable. JDBC provides following connection methods to create statements with desired
ResultSet.
o Statement createStatement(int resultSetType, int resultSetConcurrency)
o PreparedStatement prepareStatement(String sql, int resultSetType, int
resultSetConcurrency)
o CallableStatement prepareCall(String sql, int resultSetType, int
resultSetConcurrency)
resultSetType - one of the following ResultSet constants:
ResultSet.TYPE_FORWARD_ONLY
This cursor can only move forward in the result set
ResultSet.TYPE_SCROLL_I
NSENSITIVE
The cursor can scroll
forwards and backwards, and the result set
is not sensitive to changes made by others to the database that occur after the result was created
ResultSet.TYPE_SCROLL_
SENSITIVE
The cursor can scroll forwards and backwards,
and the result set is sensitive to changes made
by others to the database that occur after the result
set was created.
resultSetConcurrency - one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
For example:
Statement st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
ResultSet rs = st.executeQuery("SELECT * FROM EMPMaster"); Here, rs will be scrollable, will not show changes made by others, and will be updatable
Methods
1) boolean absolute(int row):
Moves the cursor to the given row number in this ResultSet object. 2) void close():
Releases this ResultSet object’s database and JDBC resources immediately instead
of waiting for this to happen when it is automatically closed. . 3) boolean first():
Moves the cursor to the first row in this ResultSet object.
4) boolean last():
Moves the cursor to the last row in this ResultSet object. 5) boolean beforeFirst():
Moves the cursor to just before the first row in this ResultSet object.
6) boolean afterLast():
Moves the cursor to just after the last row in this ResultSet object. 7) boolean next():
Moves the cursor to the down one row from its current position .
8) boolean previous():
Moves the cursor to the previous row in its ResultSet object. 9) XXX getXXX(int columnIndex/String columnName):
Retrieves the value of the designated column in the current row of this ResultSet
object as a type XXX.. 10) ResultSetMetaData getMetaData():
Retrieves the number, types and properties of this ResultSet object’s column
9. short note on STORED PROCEDURE
A stored procedure is a group of SQL statements that form a logical unit and perform a particular task, and they are used to encapsulate a set of
operations or queries to execute on a database server. Stored procedures can be compiled and executed with different
parameters and results, and they may have any combination of input, output and input/output parameters.
E.g.
create or replace procedure abc ( dno in number, dname in varchar2, loc in varchar2) is begin
insert into DeptMaster values(dno, dname, loc); end;
10. Explain with an example how to create and use Prepared
Statement. (4M for 4 point + 1M for example)
A PreparedStatement object is more convenient for sending SQL statements to the database.
This special type of statement is derived from the more general class, Statement.
If we want to execute a Statement object many times, use a PreparedStatement object which reduces execution time. The main feature of a PreparedStatement object is that it is given
an SQL statement when it is created. The advantage to this is that in most cases, this SQL statement is sent to the DBMS right away,
where it is compiled. As a result, the PreparedStatement object contains not just an SQL statement, but an SQL statement that has
been precompiled. This means that when the PreparedStatement is executed, the
DBMS can just run the PreparedStatement SQL statement without having to compile it first.
Although PreparedStatement objects can be used for SQL statements with no parameters, we use them most often for SQL
statements that take parameters. The advantage of using SQL statements that take parameters is that you can use the same
statement and supply it with different values each time you execute it.
Creating a PreparedStatement Object: A PreparedStatement objects can be created with a Connection method.
E.g. PreparedStatement updateEmp = con.prepareStatement(
"UPDATE EMPLOYEES SET SALARY = ? WHERE EMP_ID = ?");
Supplying Values for PreparedStatement Parameters: We need to supply values to be used in place of the question mark placeholders (if there are any) before we can execute a
PreparedStatement object.
PreparedStatement class. question mark is a Java int,
we call the method setInt.
String, we call the method setString, and so on.
declared in the Java programming language.
updateEmp.setInt(1, 7500); updateEmp.setInt(2,1030);
updateEmp.executeUpdate(): The method executeUpdate was used to execute both the
Statement stmt and the Prepared Statement updateEmp. Notice, however, that no argument is supplied to execute Update
when it is used to execute update Emp. This is true because updateEmp already contains the SQL statement to be executed.
11. Write a short note on RMI Registry.
(1M for each point) RMI provides a registry service, which makes it possible for the
client applications to locate the remote object before invoking a method on it.
A server registers any remote object that it is exporting with a name server called the registry.
When a client wishes to obtain a reference to a remote object, a lookup is performed with a known registry and a reference to the
remote object is made if the lookup is successful
Registry services can be used in one of the following ways: low the RPC model and maintain a registry server
that is running on a well-known port number. Any number of
applications that export objects can register with this registry as long as they are running on the same physical machine. A client can then
look up the registered services via URLs passed to certain lookup() and list() methods that query the registry.
registry services. This allows the application to have complete control
over the registry but makes it more difficult to define a well-known port that will be used to access remote objects.
that are being exported by their applications
registry’s table of objects by calling certain methods from the
rmi.registry. Registry interface or from the rmi.Naming class.
12. Write a JDBC program to accept the table name from the
user and to display column names only. import java.sql.*;
import java.io.*; class ColumnNamesOnly
{ public static void main(String args[])
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:mydemo"); Statement st = con.createStatement();
System.out.println("Enter table name"); BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); String tableName=br.readLine();
ResultSet rs = st.executeQuery("select * from "+tableName); ResultSetMetaData rsmd = rs.getMetaData();
int colCount = rsmd.getColumnCount(); for(int i=1; i<=colCount; i++)
{ System.out.println(rsmd.getColumnName(i)); }
st.close(); con.close();
} }
13. Explain the class URLConnection (1M description + 1M constructor + 3M methods)
URL connection is a general purpose class for accessing the attributes of a remote resource.
Once a connection is established with the remote server, we can inspect the properties of the remote object before actually transporting
it locally. We can obtain an object of URL connection with the help of
openConnection() of the URL class.
Constructor 1) URLConnection(URLurl): Constructs a URL connection to the
specified URL.
Method 1) abstract void connect() : Opens a communications link to the
resource referenced by this URL, if such a connection has not already been established.
2) String getContentEncoding(): Returns the value of the content-
encoding header field. 3) int getContentLength(): Returns the value of the content-length
header field. 4) String getContentType(): Returns the value of the content-type
header field. 5) long getDate(): Returns the value of the date header field.
6) long getExpiration(): Returns the value of the expires header field. 7) String getHeaderField(int n): Returns the value for the nth header
field. 8) String getHeaderField(String name): Returns the value of the
named header field.
14. Explain the use of following classes/interfaces
(i) Remote
The Remote interface identifies interfaces whose methods may be
invoked remotely from a non-local virtual machine.
Any remote object must directly or indirectly implement this interface. Implementation classes can implement any number of remote interfaces and can extend other remote implementation classes.
The methods specified in a "remote interface", extends java.rmi.Remote.
Therefore, these methods must be defined as being capable of throwing a java.rmi.RemoteException.
This exception is thrown by the RMI system from a remote method
invocation to indicate that either a communication failure or a protocol error has occurred.
The Enterprise Java Bean (EJB) 2.0 specification also contains a remote client view in cases when you plan to use the bean in distributed environments.
To access a remote object, you first need to find it, which can usually be
accomplished through the use of a directory or naming service, such as the RMI registry or JNDI.
When you obtain a reference to a remote object through a directory service, you don't receive an actual reference to that object, but rather a reference to a stub object that implements the same interface as the remote object.
The stub marshals the method parameters and converts them into a
byte-stream representation.
Then it sends the marshaled parameters over the network to a skeleton object, which unmarshals them and invokes the actual remote method you wanted to invoke.
marshals the return value and transports it to the stub, and the stub unmarshals it and returns the value to the caller.
(ii) Naming
The Naming class provides methods for storing and obtaining
references to remote objects in a remote object registry.
name that is a java.lang.String in URL format (without the scheme component) of the form: //host:port/name where host is the host
(remote or local) where the registry is located, port is the port number on which the registry accepts calls, and where name is a
simple string uninterpreted by the registry. Both host and port are optional.
omitted, then the port defaults to 1099, the "well-known" port that
RMI's registry, rmiregistry, uses. Binding a name for a remote object is associating or registering a name for a remote object that can be
used at a later time to look up that remote object.
class's bind or rebind methods. Once a remote object is registered (bound) with the RMI registry on the local host, callers on a remote
(or local) host can lookup the remote object by name, obtain its reference, and then invoke remote methods on the object.
an individual server process may create and use its own registry if
desired.
15. How to create a tree using Swing components?
(Purpose) JTree is a component that displays information in hierarchical format.
Steps for creating a JTree are as follows:
i) Create an instance of JTree
ii) Create objects for all the nodes required with the help of
DefaultMutableTreeNode, which implements MutableTreeNode interface which extends the TreeNode interface. The TreeNode
interface declares methods that obtains information about a TreeNode. To create a hierarchy of TreeNodes the add() of the
DefaultMutableTreeNode can be used.
Create the object of the tree with the topmost node as argument iii) Use the add method to create the hierarchy
iv) Create the object of JScrollPane and add the JTree to it. Add the scroll pane to the content pane.
Event Handling…………………………………………. (2 marks)
The JTree generates a TreeExpansionEvent which is in the package javax.swing.event. The getPath() of this class returns a TreePath object that describes the path to the changed node.
The addTreeExapnsionListener and removeTreeExpansionListener methods allows listeners to register and unregister for the
notifications. The TreeExpansionListener interface provides two methods
Example:
import java.awt.*; import java.awt.event.*;
import javax.swing.*; import javax.swing.tree.*;
/*<applet code="JTreeEvents" width=300 height=300> </applet>*/
public class JTreeEvents extends JApplet {
JTree tree; JTextField jtf; public void init()
{ Container contentPane=getContentPane();
contentPane.setLayout(new BorderLayout()); DefaultMutableTreeNode top=new DefaultMutableTreeNode("Options");
DefaultMutableTreeNode a=new DefaultMutableTreeNode("A"); top.add(a);
DefaultMutableTreeNode a1=new DefaultMutableTreeNode("A1"); a.add(a1);
DefaultMutableTreeNode b=new DefaultMutableTreeNode("B"); top.add(b);
DefaultMutableTreeNode b1=new DefaultMutableTreeNode("B1"); b.add(b1);
tree=new JTree(top); int v=ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED;
int h=ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED; JScrollPane jsp=new JScrollPane(tree,v,h);
contentPane.add(jsp,BorderLayout.CENTER); }
}
16. Explain with an example creation of thread using
Runnable (3M description + 2M example)
To implement Runnable, a class we only need to implement a single method called run( ), which is declared like this:
public void run( ) We will define the code that constitutes the new thread inside
run() method. It is important to understand that run() can call other methods,
use other classes, and declare variables, just like the main thread can.
After we create a class that implements Runnable, we will instantiate an object of type Thread from within that class.
Thread defines several constructors. The one that we will use is the default constructor
After the new thread is created, it will not start running until we call its start( ) method, which is declared within Thread.
The start( ) method is shown here: void start( );
Example: class RunnableY implements Runnable
{ public void run()
{ try
{ while(true)
{ Thread.sleep(2000); System.out.println("Hello");
} } catch(InterruptedException e)
{ e.printStackTrace();
} } }
class ThreadDemo {
public static void main(String args[]) {
RunnableY r = new RunnableY(); Thread t = new Thread(r);
t.start(); }
}
17. What are Thread Safe variables? How are they declared?
Making variables thread-safe removes the danger of their values being changed asynchronously by threads other that the
current one.
Local variables are inherently thread-safe because each
thread has a separate storagearea for local variables. As instance variable of an object declared as a local variable
is thread sage, but fields of a class whose methods run in multiple threads may not be.
Class variables are stored only once and are therefore not thread safe.
Classes ThreadLocal and InheritableThreadLocal provide variables that are local to each thread and therefore thread sage.
A ThreadLocal field has these characteristics. It is declared to be private and static
It holds a value that is identified with the thread. Its value does not change during the execution of the thread
If the thread has child threads, we can use inheritable ThreadLocal so that values from the parent thread are
inherited by the child thread. When a thread ends, its ThreadLocal object become available for garbage collection.
18 . What does InetAddress class represent? State and explain any
four methods of this class.
InetAddress class is used to encapsulate both the Domain
name(E.g., www.google.com) and IP address(e.g., 74.125.236.88). We can Interact with this class by using the Hostname rather than
IP address, more conveniently and understandable way. for example, mostly every internet user don't know IP address for google.com.
Methods
[1] byte[] getAddress()
Returns the raw IP address of this InetAddress object.
[2] static InetAddress[]getAllByName(String host)
Given the name of a host, returns an array of its IP addresses, based on the configured name service on the system.
[3] static InetAddress getByName(String host)
Determines the IP address of a host, given the host's name. [4] String getHostAddress()
Returns the IP address string in textual presentation. [5] String getHostName()
Gets the host name for this IP address. [6] static InetAddress getLocalHost()
Returns the address of the local host.
19. NOTE ON JDBC EXCEPTION CLASS:
20. Write a JDBC program that would create the Friends(F_Name,
F_Mobile, F_Email) table and insert three records in it.
import java.awt.*; class FriendsTable
{ public static void main(String args[])
{ try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:mydemo"); Statement st=con.createStatement();
st.execute("create table Friends(F_Name varchar(22), F_Mobile number(10),
F_Email varchar(22)"); st.execute("insert into Friends values("A", 1234567890,
'[email protected]"); st.execute("insert into Friends values("B", 2234567890,
'[email protected]"); st.execute("insert into Friends values("C", 3234567890,
'[email protected]"); st.close();
con.close(); }
catch(Exception e) {
e.printStackTrace(); } }
}
21. Write a TCP client server program wherein the client sends a number to the server and the server replies with its
factorial. Server program
import java.io.*; import java.net.*;
class FactorialServer {
public static void main(String args[]) {
ServerSocket ss = new ServerSocket(4040); // Makes the server ready to receive requests
Socket s = ss.accept(); // server receives a request BufferedReader br = new BufferedReader(new
InputStreamReader(s.getInputStream())); // To read from socket PrintWriter pw = new PrintWriter(s.getOutputStream,true);//to
write through socket int n = Integer.parseInt(br.readLine()); //read from socket
int f = 1; for(int i=1; i<=n ; i++)
{ f=f*i;
} pw.println("Factorail of "+ n + " is " + f);
pw.flush();
s.close();
ss.close(); } }
Client program import java.io.*;
import java.net.*; class FactorialClient
{ public static void main(String args[])
{ Socket s = new Socket("localhost", 4040); // server receives a request
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); // To read from the keyboard
BufferedReader br_soc = new BufferedReader(new InputStreamReader(s.getInputStream())); // To read from socket
PrintWriter pw = new PrintWriter(s.getOutputStream,true);//to write through socket
System.out.println("Enter a number"); String number = br.readLine(); //read from keyboard
pw.println(number); pw.flush();
String ans = br_soc.readLine(); System.out.println(ans);
s.close(); }
} 22 .Write an RMI program that returns date & time of server to
the client who requests it. import java.rmi.*;
import java.net.*; public class p3e
{ public static void main(String args[]) throws Exception
{ RMISecurityManager rsm = (RMISecurityManager)
System.getSecurityManager(); System.setSecurityManager(rsm);
DateServerImpl dateServerImpl = new DateServerImpl( ); Naming.rebind("DateServer",dateServerImpl);
System.out.println("Server is ready...."); }
} OR
import java.rmi.*; import java.rmi.server.*;
import java.util.Date; public class p3e extends UnicastRemoteObject implements hello
{ public helloimpl() throws RemoteException { }
public String getDate() {
try {
return new Date().toString(); }
catch(RemoteException e) {
e.printStackTrace(); }
} }]
23. 1+2+.3+…………..n
24. Explain methods used for getting IP address from its hostname.
(1M for each point)
The InetAddress class has no visible constructors.
factory methods.
getByName(), and getAllByName() can be used to create instances of
InetAddress. These methods are shown here:
static InetAddress getLocalHost( ) throws UnknownHostException: this method simply returns the InetAddress
object that represents the local host static InetAddress getByName(String hostName) throws
UnknownHostException: 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. static InetAddress[] getAllByName(String hostName) throws
UnknownHostException: this 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.
25. How are swing components different from AWT
components? (1M each)
The AWT components are those provided by the JDK 1.0 and 1.1
platforms.
The AWT button class, for example, is named Button, while the Swing
button class is named JButton. he java.awt package, while the Swing
components are in the javax.swing package.
components is that the Swing components are implemented with absolutely no native code.
aren't restricted to the least common denominator -- the features that are present on every platform -- they can have more functionality than AWT components.
what the AWT components offer:
Swing buttons and labels can display images instead of, or in addition to, text.
We can easily add or change the borders drawn around most Swing components. For example, it's easy to put a box around the outside of
a container or label. We can easily change the behavior or appearance of a Swing
component by either invoking methods on it or creating a subclass of it.
Swing components don't have to be rectangular. Buttons, for example, can be round.
Assistive technologies such as screen readers can easily get information from Swing components. For example, a tool can easily get
the text that's displayed on a button or label.
Swing lets you specify which look and feel your program's GUI uses. By contrast, AWT components always have the look and feel of the native
platform. 26. EXPLAIN USE OF JInternal Frame
27.Write a short note on Text-Entry Components // explain any 3 text entry component
Swing text components display text and optionally allow the user
to edit the text. Programs need text components for tasks ranging from the straightforward (enter a word and press Enter) to the
complex (display and edit styled text with embedded images in an Asian language).
with supporting classes and interfaces that meet even the most complex text
requirements. In spite of their different uses and capabilities, all Swing text components inherit from the same superclass,
JTextComponent, which provides a highly-configurable and powerful foundation for text manipulation. The following figure shows the JTextComponent hierarchy.
28. How to create a JMenu and add it to a JMenuBar inside a JFrame.
JMenu: Within the Swing components hierarchy, menus and menu items are subcalsses of the AbstractButton class.
We can create instances of all the classes in the following syntax
discussions and combine them into menus by using these guidelines: To create a main menu for an application, use a JMenuBar object.
Use the add method to add menus to the menu bar and the setJMenuBar method to add the menu bar to its window.
For a menu that is associated with a component and pops up when the user clicks a component, create a JPopupMenu object.
For every item in a menu, use an instance of JMenuItem or a subclass of JMenuItem
To nest menus, use JMenu objects. A JMenu object is a
JMenuItem object that is itself a menu. For a menu item that is also a check box, use a
JCheckBoxMenuITem object. For a menu item that is also a radio button, use a
JRadioButtonMenuItem object.
JMenuBar Class object encapsulates the sort of menu bars we
often see directly under the title of the frame window for an application. Items in the menu are arranged side by side starting on
the left. Often each item is itself a pull-down menu.
Constructors 1) JMenuBar():
Creates a new menu bar. A JMenuBar object can be set for the top-
level containers JApplet, JDialog, JFrame, JWindow or JInternalFrame.
Methods 1) public JMenu add(JMenu c):
Appends the specified menu to the end of the menu bar.
2) public JMenu getMenu(int index):
Returns the menu at the specified position in the menu bar. 3) public int getMenuCount():
Returns the number of items in the menu bar.
Adding a Menu Bar void setJMenuBar(JMenuBar menubar) : sets the menu bar for this
frame. All top-level containers can have a menu bar. In practice menu bars
usually appear only in frames and perhaps in applets. To add a menu bar to a frame or applet, we creae a JMenuBar object, populate it
with menus, and then call setJMenuBar. To add a menu bar to its frame we use the code:
JMenuBar mbar=new JMenuBar(); frame.setJMenuBar(mbar);
JMenuItem Class
that do not take the form of a check box or a radio button.
Constructors 1) JMenuItem():
2) JMenuItem(Icon icon): 3) JMenuItem(String label): 4) JMenuItem(String label, Icon icon):
5) JMenuItem(String label, int mnemonic):
Usually, we give every item a label, an icon or both so users can identify the menu item. We pass the label toe the constructor as a
String and the icon as an Icon object. A mnemonic character can be specified also.
Methods
1) public KeyStroke getAccelerator():
Returns the KeyStroke which servers as an accelerator for the menu
item. 2) public void setAccelerator(KeyStroke keyStroke):
Sets the key combination which invokes the menu item’s action
listeners without navigating the menu hierarchy. It is the UI’s responsibility to install the correct action. Note that when the
keyboard accelerator is typed, it will work whether or not the menu is currently displayed.
3) public void setMnemonic(int mnemonic):
Sets the keyboard mnemonic on the current model. The mnemonic is the key which when combined with the look and feel's mouseless
modifier (usually Alt) will activate this button if focus is contained somewhere within this button's ancestor window. A mnemonic must
correspond to a single key on the keyboard and should be specified using one of the VK_XXX keycodes defined in
java.awt.event.KeyEvent JMenu Class
public class JMenu extends JMenuItem -
down menu from a JMenuBar object.
Constructors 1) JMenu():
2) JMenuItem(String label): 3) JMenuItem(String label, Boolean tearoff):
The String argument of the label of the JMenu object in the
JMenuBar object or other JMenu object of which this object is a submenu. By default, JMenu object disappear when the user releases
the mouse button. If the native operating system supports tear-off menus-pull-down menus that can be detached from the menu bar
and dragged to another position for convenient access- we can create a tear-off menu nu setting the boolean argument to true.
Methods 1) public JMenuItem add(JMenuItem menuItem):
Appends a menu item to the end of this menu. Returns the menu
item added. 2) public void addSeparator()
Appends a new separator to the end of the menu
3) public boolean isSelected()
Returns true if the menu is currently selected(highlighted) 4) public void setSelected(boolean b)
Sets the selection status of the menu.
29. Explain in detail JScrollPane
JScrollPane provides a scrollable view of a lightweight component.
manages a viewport, optional vertical and horizontal scroll bars, and optional row and column heading viewports.
-- for example, a text file.
displayed by the JViewport view.
the wiring between them, as shown in the diagram.
In addition to the scroll bars and viewport, a JScrollPane can have a column header and a row header.
Each of these is a JViewport object that we specify with setRowHeaderView, and setColumnHeaderView
To add a border around the main viewport, you can use setViewportBorder. A common operation to want to do is to set the background color that will be
used if the main viewport view is smaller than the viewport, or is not opaque. This can be accomplished by setting the background color of the viewport, via
scrollPane.getViewport().setBackground()
Constructor
[1] JScrollPane(): [2] JScrollPane(Component view):
[3] JScrollPane(Component view, int vsbPolicy, int hsbPolicy): [4] JScrollPane( int vsbPolicy, int hsbPolicy):
Creates a JScrollPane that displays the view component in a viewport whose view
position can be controlled with a pair of scrollbars.
Methods [1] JScrollBar createHorizontalScrollBar()
Returns a JScrollPane.ScrollBar by default.
[2] JScrollBar createVerticalScrollBar()
Returns a JScrollPane.ScrollBar by default. [3] protected JViewport createViewport()
Returns a new JViewport by default.
30. EXPLAIN ANY 3 COSTRUCT OR JTREE CLASS
31. NOTE: JAVA PRINT SERVICE
32 . Explain with an example creation of thread using Thread Class
(3M description + 3M example)
Let the class extend “Thread” class
declared like this:
public void run( )
run() method.
use other classes, and declare variables, just like the main thread
can. instantiate an object of that class.
Example: class SimpleThread extends Thread
{ public void run()
{ try
{
while(true) {
Thread.sleep(2000); System.out.println("Hello");
} }
catch(InterruptedException e) {
e.printStackTrace(); }
} }
class ThreadDemo {
public static void main(String args[]) {
SimpleThread t = new SimpleThread(); t.start();
} }
33.METHOD INVLOLVE
34. State the JDBC drivers and explain any two in brief.
(State 4 drivers: ½ m each + explanation of each driver: 2M ) There are four types of JDBC drivers known as:
-ODBC bridge plus ODBC driver, also called Type 1. -API, partly Java driver, also called Type 2.
-Net, pure Java driver, also called Type 3. Native-protocol, pure Java driver, also called Type 4.
Type 1 JDBC-ODBC Bridge. Type 1 drivers act as a "bridge" between JDBC and another database connectivity mechanism
such as ODBC. The JDBC- ODBC bridge provides JDBC access using most
standard ODBC drivers. This driver is included in the Java 2 SDK within the sun.jdbc.odbc package.
In this driver the java statements are converted to jdbc statements.
JDBC statements call the ODBC by using the JDBC-ODBC Bridge. And finally the query is executed by the database.
This driver has serious limitation for many applications. Functions:
1. Translates query obtained by JDBC into corresponding ODBC query, which is then handled by the ODBC driver.
2. Sun provides a JDBC-ODBC Bridge driver.
sun.jdbc.odbc.JdbcOdbcDriver. This driver is in native code and not Java source.
3. java -> JDBC Driver -> ODBC Driver -> Database 4. There is some overhead associated with the translation work
to go from JDBC to ODBC. 5. The ODBC driver needs to be installed on the client machine.
Type 2 Java to Native API. Type 2 drivers use the Java Native
Interface (JNI) to make calls to a local database library API.
The Java Native Interface (JNI) allows Java code to call and to be called by libraries written in other languages, such as C, C++
and assembly. This driver converts the JDBC calls into a database specific call
for databases such as SQL, ORACLE etc. This driver communicates directly with the database server. It
requires some native code to connect to the database. Type 2 drivers are usually faster than Type 1 drivers.
Like Type 1 drivers, Type 2 drivers require native database client libraries to be installed and configured on the client machine.
(See Figure 3.) Functions:
1. This type of driver converts JDBC calls into calls to the client API for that database.
2. java -> JDBC Driver -> Client DB Library -> Database Better performance than Type 1 since no jdbc to odbc translation
is needed.
Type 3 Java to Network Protocol Or All- Java Driver. Type 3 drivers are pure java drivers that use a proprietary network
protocol to communicate with JDBC middleware on the server.
The middleware then translates the network protocol to database-specific function calls.
Type 3 drivers are the most flexible JDBC solution because they do not require native database libraries on the client and can
connect to many different databases on the back end. Type 3 drivers can be deployed over the Internet without client
installation. Java statements-------> JDBC statements------> SQL statements
------> databases. Functions:
1. Follows a three tier communication approach. 2. Can interface to multiple databases .
3. The JDBC Client driver written in java, communicates with a middleware-net-server using a database independent protocol,
and then this net server translates this request into database
commands for that database. 4. Thus the client driver to middleware communication is
database independent. 5. java -> JDBC Driver -> Middleware-Net Server -> Any
Database
Type 4 Java to Database Protocol. Type 4 drivers are pure Java drivers that implement a native database protocol (like Oracle's
SQL*Net) to communicate directly with the database.
Like Type 3 drivers, they do not require native database libraries and can be deployed over the Internet without client installation.
Type drivers communicate directly with the database engine rather than through middleware or a native library, they are
usually the fastest JDBC drivers available. This driver directly converts the java statements to SQL
statements. Functions
1. Type 4 drivers are entirely written in Java that communicate directly with database through socket connections. No
translation or middleware layers, are required, improving performance.
2. The driver converts JDBC calls into the database specific protocol so that client applications can communicate directly
with the database server. 3. Completely implemented in Java to achieve platform
independence. Java -> Native protocol JDBC Driver -> Database .
35. Explain the following methods:
Class.forName() (1M for syntax and 1 M for description)
PUBLIC STATIC Class<?> forName(String className) throws ClassNotFoundException
Returns the Class object associated with the class with the given string name.
Given the fully-qualified name for a class or interface, this method attempts to locate, load and link the class. If it succeeds, returns the Class object representing
the class. If it fails, the method throws a ClassNotFoundException.
For example, the following code fragment returns the runtime Class descriptor for the class named java.lang.Thread:
Class t = Class.forName("java.lang.Thread");
DriverManager.getConnection
(1M for syntax and 1 M for description)
public static Connection getConnection(String url, String user, String password) throws SQLException
Attempts to establish a connection to the given database URL with the given username and password. The DriverManager attempts to select an appropriate
driver from the set of registered JDBC drivers.
For example, the following code fragment establishes the connection Connection con = DriverManager.getConnection(“jdbc:odbc:mydemo”,“pqr”, “abc”);
Connection.createStatement (1M for syntax and 1 M for description)
STATEMENT createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException
Creates a Statement object that will generate ResultSet objects with the given type,
concurrency, and holdability.
resultSetType - one of the following ResultSet constants:
ResultSet.TYPE_FORWARD_ONLY, ResultSet.TYPE_SCROLL_INSENSITIVE, or ResultSet.TYPE_SCROLL_SENSITIVE
resultSetConcurrency - one of the following ResultSet constants: ResultSet.CONCUR_READ_ONLY or ResultSet.CONCUR_UPDATABLE
resultSetHoldability - one of the following ResultSet constants: ResultSet.HOLD_CURSORS_OVER_COMMIT or
ResultSet.CLOSE_CURSORS_AT_COMMIT
36. Describe the way a stored procedure is called in JDBC.
(3M description + 3 M example) Stored Procedure
form a logical unit and perform a particular task, and they
are used to encapsulate a set of operations or queries to execute on a database server.
h different parameters and results, and they may have any
combination of input, output and input/output parameters.
create or replace procedure abc ( dno in number, dname
in varchar2, loc in varchar2) is begin insert into DeptMaster values(dno, dname, loc);
end; Calling a Stored Procedure
JDBC allows us to call a database stored procedure from an application written in the Java programming
language.
The first step is to create a CallableStatement object CallableStatement cs=con.prepareCall(“{call abc}”); A callableStatement object contains a call to a stored
procedure; it does not contain the stored procedure itself. The part that is enclosed in curly braces is the escape
syntax for stored procedures. When the driver encounters "{call abc}", it will translate
this escape syntax into the native SQL used by the database to call the stored procedure named abc.
After preparation of the CallableStatement we will have to call the executeQuery() or execute() or executeUpdate()
method for executing the procedure
ResultSet rs = cs.executeQuery(); [
import java.sql.*; public class PrepareCallDemo
{ public static void main(String[] args)
{ try
{ Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:mydemo");
System.out.println("Connected to the database"); CallableStatement callstat=con.prepareCall("{call
abc(?,?,?)}"); callstat.setInt(1, 80);
callstat.setString(2,"test"); callstat.setString(3,"hyderabad");
callstat.execute(); callstat.close();
con.close(); System.out.println("DisConnected");
} catch (Exception e)
{ e.printStackTrace();
} }
}
stored procedure create or replace procedure abc ( dno in number, dname
in varchar2, loc in varchar2) is begin
insert into DeptMaster values(dno, dname, loc); end;
]
37. EXPLAIN ANY 3 IMP METHOD OF RESULT SET METADATA
38.WHAT IS SOCKET ?
39. What is ServerSocket? How it is used? Explain with an example
ServerSocket The ServerSocket class is designed to be a listener which waits for the clients to
connect. When we create a ServerSocket it will register itself with the system as having an interest in client connection.
Constructor
Example (2 marks)
import java.net.*; import java.io.*;
import java.util.*; class ServerTime
{
public static void main(String args[]) throws IOException {
ServerSocket ss = new ServerSocket(4040); Socket s = ss.accept();
Calendar cal = new GregorianCalendar(); PrintWriter pw = new PrintWriter(s.getOutputStream());
pw.print("Current time is "); pw.println(cal.get(Calendar.HOUR) + ":" + cal.get(Calendar.MINUTE) + ":"
+ cal.get(Calendar.SECOND)); pw.flush();
ss.close(); s.close();
} }
40. EXPLAIN WITH EXAMPLE GETHOST GETPROTOCOL GETFILE GETREF
41. Write a note on the JColorChooser class.
(2M purpose + 2M constructor + 2M methods) (Purpose) JColorChooser is a panel that allows user to browse a palette of
available colors and select one. This class provides three levels of API:
1. A static convenience method which shows a modal color-chooser dialog and returns the color selected by the user.
2. A static convenience method for creating a color-chooser dialog where ActionListeners can be specified to be invoked when the user presses one of the
dialog buttons. 3. The ability to create instances of JColorChooser panes directly (within any
container). PropertyChange listeners can be added to detect when the current "color" property changes.
Constructors 1) JColorChooser():
2) JColorChooser (Color initialSelection): 3) JColorChooser (ColorSelectionModel model):
If the default constructor is used, a dialog box is displayed with white as the initial selection. If a
color is specified, it will be indicated to be the initial selection. By default, a new selection model is
created for the chooser, but it is possible to specify that the chooser use an existing selection model
at construction time.
Methods
1) public static JDialog createDialog(Component c, String title, boolean modal, JColorChooser chooserPane, ActionListener okListener, ActionListener
cancelListener) throws HeadlessException
Creates and returns a new dialog containing the specified ColorChooser pane along with "OK", "Cancel", and "Reset" buttons. If the "OK" or "Cancel" buttons are
pressed, the dialog is automatically hidden (but not disposed). If the "Reset" button is pressed, the color-chooser's color will be reset to the color which was set the last
time show was invoked on the dialog and the dialog will remain showing. Parameters:
- the parent component for the dialog title - the title for the dialog
modal - a boolean. When true, the remainder of the program is inactive until the dialog is closed.
chooserPane - the color-chooser to be placed inside the dialog
okListener - the ActionListener invoked when "OK" is pressed cancelListener - the ActionListener invoked when "Cancel" is pressed
2) public Color getColor():
Gets the current color value from the color chooser.
42. NOTE: EXCEPTION CLASS
43.
44.Write a short note on RMI Architecture
(1M for each point)
[1] Application Layer: 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. 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.
[2] Stub and Skeleton Layer: The stub and skeleton layer of RMI lie just beneath the view of the Java developer. This layer is responsible for managing the remote object interface between the client and server. In this layer, RMI uses the Proxy
design pattern. The proxy knows how to forwarded methods calls between the participating objects.
A stub for a remote object acts as a client's local representative or proxy for the remote object. The caller invokes a method on the local stub which is responsible
for carrying out the method call on the remote object.
When a stub's method is invoked, it does the following: 1. initiates a connection with the remote JVM containing the remote object,
2. marshals (writes and transmits) the parameters to the remote JVM, 3. waits for the result of the method invocation,
4. unmarshals (reads) the return value or exception returned, and returns the value to the caller
The skeleton is responsible for dispatching the call to the actual remote object implementation.
When a skeleton receives an incoming method invocation it does the following:
1. unmarshals (reads) the parameters for the remote method, 2. invokes the method on the actual remote object implementation, and
3. marshals (writes and transmits) the result (return value or exception) to the caller.
[3] Remote Reference Layer: This layer defines and supports the invocation semantics for the RMI connection. This layer is responsible for managing the
"liveliness" of the remote objects. It also manages the communication between the client/server and virtual machine s, (e.g., threading, garbage collection, etc.) for
remote objects. [4] Transport Layer: This is the actual network/communication layer that is used
to send the information between the client and server over the wire. All the connections are stream-based connections that use TCP/IP. [
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. This fits nicely with the needs of a distributed system where clients are
concerned about the definition of a service and servers are focused on providing the service.
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.
While the following diagram illustrates this separation, remember that a Java interface does not contain executable code.
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.
This is shown in the following diagram.
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. ]