java

java

Saturday 17 December 2011

swing 3D effect on lable

Web hosting
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author akhtar
 */

import java.awt.Color;
import java.awt.Dimension;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.font.LineMetrics;

import javax.swing.JFrame;
import javax.swing.JLabel;

public class RichJLabel extends JLabel {

  private int tracking;
  public RichJLabel(String text, int tracking) {
  super(text);
  this.tracking = tracking;
  }

  private int left_x, left_y, right_x, right_y;
  private Color left_color, right_color;
  public void setLeftShadow(int x, int y, Color color) {
    left_x = x;
    left_y = y;
    left_color = color;
  }

  public void setRightShadow(int x, int y, Color color) {
    right_x = x;
    right_y = y;
    right_color = color;
  }

  public Dimension getPreferredSize() {
    String text = getText();
    FontMetrics fm = this.getFontMetrics(getFont());

    int w = fm.stringWidth(text);
    w += (text.length() - 1) * tracking;
    w += left_x + right_x;

    int h = fm.getHeight();
    h += left_y + right_y;

    return new Dimension(w, h);
  }

  public void paintComponent(Graphics g) {
    ((Graphics2D) g).setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
        RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

    char[] chars = getText().toCharArray();

    FontMetrics fm = this.getFontMetrics(getFont());
    int h = fm.getAscent();
    LineMetrics lm = fm.getLineMetrics(getText(), g);
    g.setFont(getFont());

    int x = 0;

    for (int i = 0; i < chars.length; i++) {
      char ch = chars[i];
      int w = fm.charWidth(ch) + tracking;

      g.setColor(left_color);
      g.drawString("" + chars[i], x - left_x, h - left_y);

      g.setColor(right_color);
      g.drawString("" + chars[i], x + right_x, h + right_y);

      g.setColor(getForeground());
      g.drawString("" + chars[i], x, h);

      x += w;
    }

  }

  public static void main(String[] args) {
    RichJLabel label = new RichJLabel("Akhtar Nawaz", 0);
    label.setLeftShadow(1, 1, Color.white);
    label.setRightShadow(1, 1, Color.white);
    label.setForeground(Color.blue);
    label.setFont(label.getFont().deriveFont(140f));

    label.setLeftShadow(5,5,Color.white);
    label.setRightShadow(-3,-3, new Color(0xccccff));
    label.setForeground(new Color(0x8888ff));
    label.setFont(label.getFont().deriveFont(140f));


    JFrame frame = new JFrame("RichJLabel hack");
    frame.getContentPane().add(label);
    frame.pack();
    frame.setVisible(true);
  }

  public static void p(String str) {
    System.out.println(str);
  }
}

Thursday 15 December 2011

Socket Communications

What Is a Socket?

 http://www.getacoder.com/affiliates/ref.php?u=ANTServices


Normally, a server runs on a specific computer and has a socket that is bound to a specific port number. The server just waits, listening to the socket for a client to make a connection request.
On the client-side: The client knows the hostname of the machine on which the server is running and the port number on which the server is listening. To make a connection request, the client tries to rendezvous with the server on the server's machine and port. The client also needs to identify itself to the server so it binds to a local port number that it will use during this connection. This is usually assigned by the system.


A client's connection request
If everything goes well, the server accepts the connection. Upon acceptance, the server gets a new socket bound to the same local port and also has its remote endpoint set to the address and port of the client. It needs a new socket so that it can continue to listen to the original socket for connection requests while tending to the needs of the connected client.


The connection is made
On the client side, if the connection is accepted, a socket is successfully created and the client can use the socket to communicate with the server.
The client and server can now communicate by writing to or reading from their sockets.

Definition: A socket is one endpoint of a two-way communication link between two programs running on the network. A socket is bound to a port number so that the TCP layer can identify the application that data is destined to be sent.

An endpoint is a combination of an IP address and a port number. Every TCP connection can be uniquely identified by its two endpoints. That way you can have multiple connections between your host and the server.
The java.net package in the Java platform provides a class, Socket, that implements one side of a two-way connection between your Java program and another program on the network. The Socket class sits on top of a platform-dependent implementation, hiding the details of any particular system from your Java program. By using the java.net.Socket class instead of relying on native code, your Java programs can communicate over the network in a platform-independent fashion.
Additionally, java.net includes the ServerSocket class, which implements a socket that servers can use to listen for and accept connections to clients. This lesson shows you how to use the Socket and ServerSocket classes.
If you are trying to connect to the Web, the URL class and related classes (URLConnection, URLEncoder) are probably more appropriate than the socket classes. In fact, URLs are a relatively high-level connection to the Web and use sockets as part of the underlying implementation. See Working with URLs for information about connecting to the Web via URLs.

Reading from and Writing to a Socket

Let's look at a simple example that illustrates how a program can establish a connection to a server program using the Socket class and then, how the client can send data to and receive data from the server through the socket.
The example program implements a client, EchoClient, that connects to the Echo server. The Echo server simply receives data from its client and echoes it back. The Echo server is a well-known service that clients can rendezvous with on port 7.
EchoClient creates a socket thereby getting a connection to the Echo server. It reads input from the user on the standard input stream, and then forwards that text to the Echo server by writing the text to the socket. The server echoes the input back through the socket to the client. The client program reads and displays the data passed back to it from the server:
import java.io.*;
import java.net.*;

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

        Socket echoSocket = null;
        PrintWriter out = null;
        BufferedReader in = null;

        try {
            echoSocket = new Socket("taranis", 7);
            out = new PrintWriter(echoSocket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                                        echoSocket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: taranis.");
            System.exit(1);
        } catch (IOException e) {
            System.err.println("Couldn't get I/O for "
                               + "the connection to: taranis.");
            System.exit(1);
        }

 BufferedReader stdIn = new BufferedReader(
                                   new InputStreamReader(System.in));
 String userInput;

 while ((userInput = stdIn.readLine()) != null) {
     out.println(userInput);
     System.out.println("echo: " + in.readLine());
 }

 out.close();
 in.close();
 stdIn.close();
 echoSocket.close();
    }
}
Note that EchoClient both writes to and reads from its socket, thereby sending data to and receiving data from the Echo server.
Let's walk through the program and investigate the interesting parts. The three statements in the try block of the main method are critical. These lines establish the socket connection between the client and the server and open a PrintWriter and a BufferedReader on the socket:
echoSocket = new Socket("taranis", 7);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
                             echoSocket.getInputStream()));
The first statement in this sequence creates a new Socket object and names it echoSocket. The Socket constructor used here requires the name of the machine and the port number to which you want to connect. The example program uses the host name taranis. This is the name of a hypothetical machine on our local network. When you type in and run this program on your machine, change the host name to the name of a machine on your network. Make sure that the name you use is the fully qualified IP name of the machine to which you want to connect. The second argument is the port number. Port number 7 is the port on which the Echo server listens.
The second statement gets the socket's output stream and opens a PrintWriter on it. Similarly, the third statement gets the socket's input stream and opens a BufferedReader on it. The example uses readers and writers so that it can write Unicode characters over the socket.
To send data through the socket to the server, EchoClient simply needs to write to the PrintWriter. To get the server's response, EchoClient reads from the BufferedReader. The rest of the program achieves this. If you are not yet familiar with the Java platform's I/O classes, you may wish to read Basic I/O.
The next interesting part of the program is the while loop. The loop reads a line at a time from the standard input stream and immediately sends it to the server by writing it to the PrintWriter connected to the socket:
String userInput;

while ((userInput = stdIn.readLine()) != null) {
    out.println(userInput);
    System.out.println("echo: " + in.readLine());
}
The last statement in the while loop reads a line of information from the BufferedReader connected to the socket. The readLine method waits until the server echoes the information back to EchoClient. When readline returns, EchoClient prints the information to the standard output.
The while loop continues until the user types an end-of-input character. That is, EchoClient reads input from the user, sends it to the Echo server, gets a response from the server, and displays it, until it reaches the end-of-input. The while loop then terminates and the program continues, executing the next four lines of code:
out.close();
in.close();
stdIn.close();
echoSocket.close();
These lines of code fall into the category of housekeeping. A well-behaved program always cleans up after itself, and this program is well-behaved. These statements close the readers and writers connected to the socket and to the standard input stream, and close the socket connection to the server. The order here is important. You should close any streams connected to a socket before you close the socket itself.
This client program is straightforward and simple because the Echo server implements a simple protocol. The client sends text to the server, and the server echoes it back. When your client programs are talking to a more complicated server such as an HTTP server, your client program will also be more complicated. However, the basics are much the same as they are in this program:
  1. Open a socket.
  2. Open an input stream and output stream to the socket.
  3. Read from and write to the stream according to the server's protocol.
  4. Close the streams.
  5. Close the socket.
Only step 3 differs from client to client, depending on the server. The other steps remain largely the same.

Writing the Server Side of a Socket

This section shows you how to write a server and the client that goes with it. The server in the client/server pair serves up Knock Knock jokes. Knock Knock jokes are favored by children and are usually vehicles for bad puns. They go like this:
Server: "Knock knock!"
Client: "Who's there?"
Server: "Dexter."
Client: "Dexter who?"
Server: "Dexter halls with boughs of holly."
Client: "Groan."
The example consists of two independently running Java programs: the client program and the server program. The client program is implemented by a single class, KnockKnockClient, and is very similar to the EchoClient example from the previous section. The server program is implemented by two classes: KnockKnockServer and KnockKnockProtocol, KnockKnockServer contains the main method for the server program and performs the work of listening to the port, establishing connections, and reading from and writing to the socket. KnockKnockProtocol serves up the jokes. It keeps track of the current joke, the current state (sent knock knock, sent clue, and so on), and returns the various text pieces of the joke depending on the current state. This object implements the protocol-the language that the client and server have agreed to use to communicate.
The following section looks in detail at each class in both the client and the server and then shows you how to run them.

The Knock Knock Server

This section walks through the code that implements the Knock Knock server program. Here is the complete source for the KnockKnockServer class.
The server program begins by creating a new ServerSocket object to listen on a specific port (see the statement in bold in the following code segment). When writing a server, choose a port that is not already dedicated to some other service. KnockKnockServer listens on port 4444 because 4 happens to be my favorite number and port 4444 is not being used for anything else in my environment:
try {
    serverSocket = new ServerSocket(4444);
} catch (IOException e) {
    System.out.println("Could not listen on port: 4444");
    System.exit(-1);
}
ServerSocket is a java.net class that provides a system-independent implementation of the server side of a client/server socket connection. The constructor for ServerSocket throws an exception if it can't listen on the specified port (for example, the port is already being used). In this case, the KnockKnockServer has no choice but to exit.
If the server successfully binds to its port, then the ServerSocket object is successfully created and the server continues to the next step--accepting a connection from a client (shown in bold):
Socket clientSocket = null;
try {
    clientSocket = serverSocket.accept();
} catch (IOException e) {
    System.out.println("Accept failed: 4444");
    System.exit(-1);
}
The accept method waits until a client starts up and requests a connection on the host and port of this server (in this example, the server is running on the hypothetical machine taranis on port 4444). When a connection is requested and successfully established, the accept method returns a new Socket object which is bound to the same local port and has its remote address and remote port set to that of the client. The server can communicate with the client over this new Socket and continue to listen for client connection requests on the original ServerSocket This particular version of the program doesn't listen for more client connection requests. However, a modified version of the program is provided in Supporting Multiple Clients.
After the server successfully establishes a connection with a client, it communicates with the client using this code:
PrintWriter out = new PrintWriter(
                      clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
                        new InputStreamReader(
                            clientSocket.getInputStream()));
String inputLine, outputLine;

// initiate conversation with client
KnockKnockProtocol kkp = new KnockKnockProtocol();
outputLine = kkp.processInput(null);
out.println(outputLine);

while ((inputLine = in.readLine()) != null) {   
    outputLine = kkp.processInput(inputLine);
    out.println(outputLine);
    if (outputLine.equals("Bye."))
        break;
}
This code:
  1. Gets the socket's input and output stream and opens readers and writers on them.
  2. Initiates communication with the client by writing to the socket (shown in bold).
  3. Communicates with the client by reading from and writing to the socket (the while loop).
Step 1 is already familiar. Step 2 is shown in bold and is worth a few comments. The bold statements in the code segment above initiate the conversation with the client. The code creates a KnockKnockProtocol object-the object that keeps track of the current joke, the current state within the joke, and so on.
After the KnockKnockProtocol is created, the code calls KnockKnockProtocol's processInput method to get the first message that the server sends to the client. For this example, the first thing that the server says is "Knock! Knock!" Next, the server writes the information to the PrintWriter connected to the client socket, thereby sending the message to the client.
Step 3 is encoded in the while loop. As long as the client and server still have something to say to each other, the server reads from and writes to the socket, sending messages back and forth between the client and the server.
The server initiated the conversation with a "Knock! Knock!" so afterwards the server must wait for the client to say "Who's there?" As a result, the while loop iterates on a read from the input stream. The readLine method waits until the client responds by writing something to its output stream (the server's input stream). When the client responds, the server passes the client's response to the KnockKnockProtocol object and asks the KnockKnockProtocol object for a suitable reply. The server immediately sends the reply to the client via the output stream connected to the socket, using a call to println. If the server's response generated from the KnockKnockServer object is "Bye." this indicates that the client doesn't want any more jokes and the loop quits.
The KnockKnockServer class is a well-behaved server, so the last several lines of this section of KnockKnockServer clean up by closing all of the input and output streams, the client socket, and the server socket:
out.close();
in.close();
clientSocket.close();
serverSocket.close();

The Knock Knock Protocol

The KnockKnockProtocol class implements the protocol that the client and server use to communicate. This class keeps track of where the client and the server are in their conversation and serves up the server's response to the client's statements. The KnockKnockServer object contains the text of all the jokes and makes sure that the client gives the proper response to the server's statements. It wouldn't do to have the client say "Dexter who?" when the server says "Knock! Knock!"
All client/server pairs must have some protocol by which they speak to each other; otherwise, the data that passes back and forth would be meaningless. The protocol that your own clients and servers use depends entirely on the communication required by them to accomplish the task.

The Knock Knock Client

The KnockKnockClient class implements the client program that speaks to the KnockKnockServer. KnockKnockClient is based on the EchoClient program in the previous section, Reading from and Writing to a Socket and should be somewhat familiar to you. But we'll go over the program anyway and look at what's happening in the client in the context of what's going on in the server.
When you start the client program, the server should already be running and listening to the port, waiting for a client to request a connection. So, the first thing the client program does is to open a socket that is connected to the server running on the hostname and port specified:
kkSocket = new Socket("taranis", 4444);
out = new PrintWriter(kkSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
                            kkSocket.getInputStream()));
When creating its socket, KnockKnockClient uses the host name taranis, the name of a hypothetical machine on our network. When you type in and run this program, change the host name to the name of a machine on your network. This is the machine on which you will run the KnockKnockServer.
The KnockKnockClient program also specifies the port number 4444 when creating its socket. This is a remote port number--the number of a port on the server machine--and is the port to which KnockKnockServer is listening. The client's socket is bound to any available local port--a port on the client machine. Remember that the server gets a new socket as well. That socket is bound to local port number 4444 on its machine. The server's socket and the client's socket are connected.
Next comes the while loop that implements the communication between the client and the server. The server speaks first, so the client must listen first. The client does this by reading from the input stream attached to the socket. If the server does speak, it says "Bye." and the client exits the loop. Otherwise, the client displays the text to the standard output and then reads the response from the user, who types into the standard input. After the user types a carriage return, the client sends the text to the server through the output stream attached to the socket.
while ((fromServer = in.readLine()) != null) {
    System.out.println("Server: " + fromServer);
    if (fromServer.equals("Bye."))
        break;
    fromUser = stdIn.readLine();
    if (fromUser != null) {
        System.out.println("Client: " + fromUser);
        out.println(fromUser);
    }
}
The communication ends when the server asks if the client wishes to hear another joke, the client says no, and the server says "Bye."
In the interest of good housekeeping, the client closes its input and output streams and the socket:
out.close();
in.close();
stdIn.close();
kkSocket.close();

Running the Programs

You must start the server program first. To do this, run the server program using the Java interpreter, just as you would any other Java application. Remember to run the server on the machine that the client program specifies when it creates the socket.
Next, run the client program. Note that you can run the client on any machine on your network; it does not have to run on the same machine as the server.
If you are too quick, you might start the client before the server has a chance to initialize itself and begin listening on the port. If this happens, you will see a stack trace from the client. If this happens, just restart the client.
If you forget to change the host name in the source code for the KnockKnockClient program, you will see the following error message:
Don't know about host: taranis
To fix this, modify the KnockKnockClient program and provide a valid host name for your network. Recompile the client program and try again.
If you try to start a second client while the first client is connected to the server, the second client just hangs. The next section, Supporting Multiple Clients, talks about supporting multiple clients.
When you successfully get a connection between the client and server, you will see the following text displayed on your screen:
Server: Knock! Knock!
Now, you must respond with:
Who's there?
The client echoes what you type and sends the text to the server. The server responds with the first line of one of the many Knock Knock jokes in its repertoire. Now your screen should contain this (the text you typed is in bold):
Server: Knock! Knock!
Who's there?
Client: Who's there?
Server: Turnip
Now, you respond with:
Turnip who?"
Again, the client echoes what you type and sends the text to the server. The server responds with the punch line. Now your screen should contain this:
Server: Knock! Knock!
Who's there?
Client: Who's there?
Server: Turnip
Turnip who?
Client: Turnip who?
Server: Turnip the heat, it's cold in here! Want another? (y/n)
If you want to hear another joke, type y; if not, type n. If you type y, the server begins again with "Knock! Knock!" If you type n, the server says "Bye." thus causing both the client and the server to exit.
If at any point you make a typing mistake, the KnockKnockServer object catches it and the server responds with a message similar to this:
Server: You're supposed to say "Who's there?"!
The server then starts the joke over again:
Server: Try again. Knock! Knock!
Note that the KnockKnockProtocol object is particular about spelling and punctuation but not about capitalization.

Supporting Multiple Clients

To keep the KnockKnockServer example simple, we designed it to listen for and handle a single connection request. However, multiple client requests can come into the same port and, consequently, into the same ServerSocket. Client connection requests are queued at the port, so the server must accept the connections sequentially. However, the server can service them simultaneously through the use of threads - one thread per each client connection.
The basic flow of logic in such a server is this:
while (true) {
    accept a connection ;
    create a thread to deal with the client ;
end while
The thread reads from and writes to the client connection as necessary.

What are Sockets and Threads?

A socket is a software endpoint that establishes bidirectional communication between a server program and one or more client programs. The socket associates the server program with a specific hardware port on the machine where it runs so any client program anywhere in the network with a socket associated with that same port can communicate with the server program.
A server program typically provides resources to a network of client programs. Client programs send requests to the server program, and the server program responds to the request.
One way to handle requests from more than one client is to make the server program multi-threaded. A multi-threaded server creates a thread for each communication it accepts from a client. A thread is a sequence of instructions that run independently of the program and of any other threads.
Using threads, a multi-threaded server program can accept a connection from a client, start a thread for that communication, and continue listening for requests from other clients.

About the Examples

The examples for this lesson consist of two versions of the client and server program pair adapted from the FileIO.java application presented in Part 1, Lesson 6: File Access and Permissions.
Example 1 sets up a client and server communication between one server program and one client program. The server program is not multi-threaded and cannot handle requests from more than one client.
Example 2 converts the server program to a multi-threaded version so it can handle requests from more than one client.

Example 1: Client-Side Behavior

The client program presents a simple user interface and prompts for text input. When you click the Click Me button, the text is sent to the server program. The client program expects an echo from the server and prints the echo it receives on its standard output.

Example 1: Server-Side Behavior

The server program presents a simple user interface, and when you click the Click Me button, the text received from the client is displayed. The server echoes the text it receives whether or not you click the Click Me button.

Example 1: Compile and Run

To run the example programs, start the server program first. If you do not, the client program cannot establish the socket connection. Here are the compiler and interpreter commands to compile and run the example.
  javac SocketServer.java
  javac SocketClient.java

  java SocketServer
  java SocketClient


Example 1: Server-Side Program

The server program establishes a socket connection on Port 4321 in its listenSocket method. It reads data sent to it and sends that same data back to the server in its actionPerformed method.

listenSocket Method

The listenSocket method creates a ServerSocket object with the port number on which the server program is going to listen for client communications. The port number must be an available port, which means the number cannot be reserved or already in use. For example, Unix systems reserve ports 1 through 1023 for administrative functions leaving port numbers greater than 1024 available for use.
public void listenSocket(){
  try{
    server = new ServerSocket(4321); 
  } catch (IOException e) {
    System.out.println("Could not listen on port 4321");
    System.exit(-1);
  }

listenSocketSocketserver.acceptSocket
  try{
    client = server.accept();
  } catch (IOException e) {
    System.out.println("Accept failed: 4321");
    System.exit(-1);
  }

listenSocketBufferedReaderclientPrintWriter
  try{
   in = new BufferedReader(new InputStreamReader(
                           client.getInputStream()));
   out = new PrintWriter(client.getOutputStream(), 
                         true);
  } catch (IOException e) {
    System.out.println("Read failed");
    System.exit(-1);
  }
}

listenSocket
    while(true){
      try{
        line = in.readLine();
//Send data back to client
        out.println(line);
      } catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
      }
    }

actionPerformed Method

The actionPerformed method is called by the Java platform for action events such as button clicks. This actionPerformed method uses the text stored in the line object to initialize the textArea object so the retrieved text can be displayed to the end user.
public void actionPerformed(ActionEvent event) {
   Object source = event.getSource();

   if(source == button){
       textArea.setText(line);
   }
}

Example 1: Client-Side Program

The client program establishes a connection to the server program on a particular host and port number in its listenSocket method, and sends the data entered by the end user to the server program in its actionPerformed method. The actionPerformed method also receives the data back from the server and prints it to the command line.

listenSocket Method

The listenSocket method first creates a Socket object with the computer name ( kq6py) and port number (4321) where the server program is listening for client connection requests. Next, it creates a PrintWriter object to send data over the socket connection to the server program. It also creates a BufferedReader object to read the text sent by the server back to the client.
public void listenSocket(){
//Create socket connection
   try{
     socket = new Socket("kq6py", 4321);
     out = new PrintWriter(socket.getOutputStream(), 
                 true);
     in = new BufferedReader(new InputStreamReader(
                socket.getInputStream()));
   } catch (UnknownHostException e) {
     System.out.println("Unknown host: kq6py");
     System.exit(1);
   } catch  (IOException e) {
     System.out.println("No I/O");
     System.exit(1);
   }
}

actionPerformed Method

The actionPerformed method is called by the Java platform for action events such as button clicks. This actionPerformed method code gets the text in the Textfield object and passes it to the PrintWriter object, which then sends it over the socket connection to the server program.
The actionPerformed method then makes the Textfield object blank so it is ready for more end user input. Lastly, it receives the text sent back to it by the server and prints the text out.
public void actionPerformed(ActionEvent event){
   Object source = event.getSource();

   if(source == button){
//Send data over socket
      String text = textField.getText();
      out.println(text);
      textField.setText(new String(""));
      out.println(text);
   }
//Receive text from server
   try{
     String line = in.readLine();
     System.out.println("Text received: " + line);
   } catch (IOException e){
     System.out.println("Read failed");
     System.exit(1);
   }
}  

Example 2: Multithreaded Server Example

The example in its current state works between the server program and one client program only. To allow multiple client connections, the server program has to be converted to a multithreaded server program.

First Client

Second Client

Third Client
In this example the listenSocket method loops on the server.accept call waiting for client connections and creates an instance of the ClientWorker class for each client connection it accepts. The textArea component that displays the text received from the client connection is passed to the ClientWorker instance with the accepted client connection.
public void listenSocket(){
  try{
    server = new ServerSocket(4444);
  } catch (IOException e) {
    System.out.println("Could not listen on port 4444");
    System.exit(-1);
  }
  while(true){
    ClientWorker w;
    try{
//server.accept returns a client connection
      w = new ClientWorker(server.accept(), textArea);
      Thread t = new Thread(w);
      t.start();
    } catch (IOException e) {
      System.out.println("Accept failed: 4444");
      System.exit(-1);
    }
  }
}

The important changes in this version of the server program over the non-threaded server program are the line and client variables are no longer instance variables of the server class, but are handled inside the ClientWorker class.
The ClientWorker class implements the Runnable interface, which has one method, run. The run method executes independently in each thread. If three clients request connections, three ClientWorker instances are created, a thread is started for each ClientWorker instance, and the run method executes for each thread.
In this example, the run method creates the input buffer and output writer, loops on the input stream waiting for input from the client, sends the data it receives back to the client, and sets the text in the text area.
class ClientWorker implements Runnable {
  private Socket client;
  private JTextArea textArea;

//Constructor
  ClientWorker(Socket client, JTextArea textArea) {
    this.client = client;
    this.textArea = textArea;
  }

  public void run(){
    String line;
    BufferedReader in = null;
    PrintWriter out = null;
    try{
      in = new BufferedReader(new 
        InputStreamReader(client.getInputStream()));
      out = new 
        PrintWriter(client.getOutputStream(), true);
    } catch (IOException e) {
      System.out.println("in or out failed");
      System.exit(-1);
    }

    while(true){
      try{
        line = in.readLine();
//Send data back to client
        out.println(line);
//Append data to text area
        textArea.append(line);
       }catch (IOException e) {
        System.out.println("Read failed");
        System.exit(-1);
       }
    }
  }
}

JTextArea.appendJTextArea.appendtextArea.append(line)synchronizedruntextArea.append(line)appendText(line)
  public synchronized void appendText(line){
    textArea.append(line);
  }
synchronizedtextAreatextAreaThe finalize() method is called by the Java virtual machine (JVM)* before the program exits to give the program a chance to clean up and release resources. Multi-threaded programs should close all Files and Sockets they use before exiting so they do not face resource starvation. The call to server.close() in the finalize() method closes the Socket connection used by each thread in this program.
  protected void finalize(){
//Objects created in run method are finalized when
//program terminates and thread exits
     try{
        server.close();
    } catch (IOException e) {
        System.out.println("Could not close socket");
        System.exit(-1);
    }
  }

Wednesday 14 December 2011

SCJP Questions 211-224

Question 211
Given:
11. class Snoochy {
12. Boochybooch;
13. public Snoochy() { booch = new Boochy(this); }
14. }
15.
16. class Boochy {
17. Snoochy snooch;
18. public Boochy(Snoochy s) { snooch = s; }
19. }
And the statements:
21. public static void main(String[] args) {
22. Snoochy snoog = new Snoochy();
23. snoog = null;
24. // more code here
25. }
Which statement is true about the objects referenced by snoog,
snooch, and booch immediately after line 23 executes?
A. None of these objects are eligible for garbage collection.
B. Only the object referenced by booch is eligible for garbage
collection.
C. Only the object referenced by snoog is eligible for garbage
collection.
D. Only the object referenced by snooch is eligible for garbage
collection.
E. The objects referenced by snooch and booch are eligible for garbage
collection.
Answer: E

Question 212
Given:
1. public class GC {
2. private Object o;
3. private void doSomethingElse(Object obj) { o = obj; }
4. public void doSomething() {
5. Object o = new Object();
6. doSomethingElse(o);
7. o = new Object();
8. doSomethingElse(null);
9.o=null;
10. }
11. }
When the doSomething method is called, after which line does the
Object created in line 5 become available for garbage collection?
A. Line 5
B. Line 6
C. Line 7
D. Line 8
E. Line 9
F. Line 10
Answer: D

Question 213
Which two are true? (Choose two.)
A. A finalizer may NOT be invoked explicitly.
B. The finalize method declared in class Object takes no action.
C. super.finalize() is called implicitly by any overriding finalize method.
D. The finalize method for a given object will be called no more than
once by the garbage collector.
E. The order in which finalize will be called on two objects is based on
the order in which the two objects became finalizable.
Answer: BD

Question 214
A class games.cards.Poker is correctly defined in the jar file Poker.jar.
A user wants to execute the main method of Poker on a UNIX system
using the command:
java games.cards.Poker
What allows the user to do this?
A. put Poker.jar in directory /stuff/java, and set the CLASSPATH to
include /stuff/java
B. put Poker.jar in directory /stuff/java, and set the CLASSPATH to
include /stuff/java/*.jar
C. Put Poker.jar in directory /stuff/java, and set the CLASSPATH to
include /stuff/java/Poker.jar
D. put Poker.jar in directory /stuff/java/games/cards, and set the
CLASSPATH to include /stuff/java
E. put Poker.jar in directory /stuff/java/games/cards, and set the
CLASSPATH to include /stuffijava/*.jar
F. put Poker.jar in directory /stuff/java/games/cards, and set the
CLASSPATH to include /stuff/java/Poker.jar
Answer: C

Question 215
Click the Exhibit button.
Given the fully-qualified class names:
com.foo.bar.Dog
com.foo.bar.blatz.Book
com.bar.Car
com.bar.blatz.Sun
Which graph represents the correct directory structure for a JAR file
from which those classes can be used by the compiler and JYM?
A. Jar A
B. Jar B
C. Jar C
D. Jar D
E. Jar E
Answer: A

Question 216
A developer is creating a class Book that needs to access class Paper.
The Paper class is deployed in a JAR named myLib.jar. Which three,
taken independently, will allow the developer to use the Paper class
while compiling the Book class? (Choose three.)
A. The JAR file is located at $JAVA_HOME/jre/classes/myLib.jar.
B. The JAR file is located at $JAVA_HOME/jre/lib/ext/myLib.jar.
C. The JAR file is located at /foo/myLib.jar and a classpath
environment variable is set that includes /foo/myLib.jar/Paper.class.
D. The JAR file is located at /foo/myLib.jar and a classpath
environment variable is set that includes /foo/myLib.jar.
E. The JAR file is located at /foo/myLib.jar and the Book class is
compiled using javac -cp /foo/myLib.jar/Paper Book.java.
F. The JAR file is located at /foo/myLib.jar and the Book class is
compiled using javac -d /foo/myLib.jar Book.java.
G. The JAR file is located at /foo/myLib.jar and the Book class is
compiled using javac -classpath /foo/myLib.jar Book.java.
Answer: BDG

Question 217
Given:
1. package com.company.application;
2.
3. public class MainClass {
4. public static void main(String[] args) { }
5. }
And MainClass exists in the /apps/com/company/application directory.
Assume the CLASSPATH environment variable is set to “.“ (current
directory). Which two java commands entered at the command line
will run MainClass? (Choose two.)
A. java MainClass if run from the /apps directory
B. java com.company.application.MainClass if run from the /apps
directory
C. java -classpath /apps com.company.application.MainClass if run
from any directory
D. java -classpath . MainClass if run from the
/apps/com/company/application directory
E. java -classpath /apps/com/company/application:. MainClass if run
from the /apps directory
F. java com.company.application.MainClass if run from the
/apps/com/company/application directory
Answer: BC

Question 218
A UNIX user named Bob wants to replace his chess program with a
new one, but he is hot sure where the old one is installed. Bob is
currently able to run a Java chess program starting from his home
directory /home/bob using the command:
java -classpath /test:/home/bob/downloads/* .jar games.Chess
Bob’s CLASSPATH is set (at login time) to:
/usr/lib:/home/bob/classes:/opt/java/lib:/opt/java/lib/* .jar
What is a possible location for the Chess.class file?
A. /test/Chess.class
B. /home/bob/Chess.class
C. /test/games/Chess.class
D. /usr/lib/games/Chess.class
E. /home/bob/games/Chess.class
F. inside jarfile /opt/java/lib/Games.jar (with a correct manifest)
G. inside jarfile /home/bob/downloads/Games.jar (with a correct
manifest)
Answer: C

Question 219
Given:
11. public static void test(String str) {
12. if(str == null | str.lellgth() == 0) {
13. System.out.println(”String is empty”);
14. } else {
15. System.out.println(”String is not empty”);
16. }
17. }
And the invocation:
31. test(llull);
What is the result?
A. Au exception is thrown at runtime.
B. “String is empty” is printed to output.
C. Compilation fails because of au error in line 12.
D. “String is not empty” is printed to output.
Answer: A

Question 220
Given:
11. public static void test(String str) {
12. int check = 4;
13. if (check = str.length()) {
14. System.out.print(str.charAt(check -= 1) +“, “);
15. } else {
16. System.out.print(str.charAt(0) + “, “);
17. }
18. }
and the invocation:
21. test(”four”);
22. test(”tee”);
23. test(”to”);
What is the result?
A. r, t, t,
B. r, e, o,
C. Compilation fails.
D. An exception is thrown at runtime.
Answer: C

Question 221
Given:
10. public class MyClass {
11.
12. public Integer startingI;
13. public void methodA() {
14. Integer i = new Integer(25);
15. startingI = i;
16. methodB(i);
17. }
18. private void methodB(Integer i2) {
19. i2 = i2.intValue();
20.
21. }
22. }
If methodA is invoked, which two are true at line 20? (Choose two.)
A. i2 == startingI returns true.
B. i2 == startingI returns false.
C. i2.equals(startingI) returns true.
D. i2.equals(startingI) returns false.
Answer: BC

Question 222
222. Given:
11. class Cup { }
12. class PoisonCup extends Cup { }
21. public void takeCup(Cup c) {
22. if(c instanceof PoisonCup) {
23. System.out.println(”Inconceivable!”);
24. } else if(c instanceof Cup) {
25. System.out.println(”Dizzying intellect!”);
26. } else {
27. System.exit(0);
28. }
29. }
And the execution of the statements:
Cup cup = new PoisonCup();
takeCup(cup);
What is the output?
A. Inconceivable!
B. Dizzying intellect!
C. The code runs with no output.
D. An exception is thrown at runtime.
E. Compilation fails because of an error in line 22.
Answer: A

Question 223
Given:
11. String[] elements = { “for”, “tea”, “too” };
12. String first = (elements.length > 0)? elements[0] null;
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The variable first is set to null.
D. The variable first is set to elements[0].
Answer: D

Question 224
Given:
42. public class ClassA {
43. public int getValue() {
44.int value=0;
45. boolean setting = true;
46. String title=”Hello”;
47. if (value || (setting && title == “Hello”)) { return 1; }
48. if (value == 1 & title.equals(”Hello”)) { return 2; }
49. }
50. }
And:
70. ClassA a = new ClassA();
71. a.getValue();
What is the result?
A. 1
B. 2
C. Compilation fails.
D. The code runs with no output.
E. An exception is thrown at runtime.
Answer: C

SCJP Questions 201-210

Question 200
Given the command line java Pass2 and:
15. public class Pass2 {
16. public void main(String [] args) {
17.int x=6;
18. Pass2 p = new Pass2();
19. p.doStuff(x);
20. System.out.print(” main x = “+ x);
21. }
22.
23. void doStuff(int x) {
24. System.out.print(” doStuffx = “+ x++);
25. }
26. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuffx = 6 main x = 6
D. doStuffx = 6 main x = 7
E. doStuffx = 7 main x = 6
F. doStuffx = 7 main x = 7
Answer: B

Question 201
Given:
15. public class Yippee {
16. public static void main(String [] args) {
17. for(int x = 1; x < args.length; x++) {
18. System.out.print(args[x] +“ “);
19. }
20. }
21. }
and two separate command line invocations:
java Yippee
java Yippee 1234
What is the result?
A. No output is produced.
123
B. No output is produced.
234
C. No output is produced.
1234
D. An exception is thrown at runtime.
123
E. An exception is thrown at runtime.
234
F. An exception is thrown at rijntime.
1234
Answer: B

Question 202
Given:
12. public class Yippee2 {
13.
14. static public void main(String [] yahoo) {
15. for(int x= 1; x<yahoo.length; x++) {
16. System.out.print(yahoo[x] + “ “);
17. }
18. }
19. }
and the command line invocation:
java Yippee2 a b c
What is the result?
A.a b
B.b c
C.a b c
D. Compilation fails.
E. An exception is thrown at runtime.
Answer: B

Question 203
Given:
11. public class Commander {
12. public static void main(String[] args) {
13. String myProp = /* insert code here */
14. System.out.println(myProp);
15. }
16. }
and the command line:
java -Dprop.custom=gobstopper Commander
Which two, placed on line 13, will produce the output gobstopper?
(Choose two.)
A. System.load(”prop.custom”);
B. System.getenv(”prop.custom”);
C. System.property(”prop.custom”);
D. System.getProperty(”prop.custom”);
E. System.getProperties().getProperty(”prop.custom”);
Answer: DE

Question 204
Click the Exhibit button.
11. class Payload {
12. private int weight;
13. public Payload(int wt) { weight = wt; }
13. public void setWeight(mt w) { weight = w; }
15. public String toString { return Integer.toString(weight); }
16. }
17.
18. public class TestPayload {
19. static void changePayload(Payload p) {
20. /* insert code here */
21. }
22.
23. public static void main(String[] args) {
24. Payload p = new Payload();
25. p.setWeight(1024);
26. changePayload(p);
27. System.out.println(”The value of p is “+ p);
28. }
29. }
Which statement, placed at line 20, causes the code to print “The
value of p is 420.”?
A. p.setWeight(420);
B. p.changePayload(420);
C. p = new Payload(420);
D. Payload.setWeight(420);
E. p = Payload.setWeight(420);
F. p = new Payload();
p.setWeight(420);
Answer: A

Question 205
Click the Exhibit button.
1. public class Item {
2. private String desc;
3. public String getDescription() { return desc; }
4. public void setDescription(String d) { desc = d; }
5.
6. public static void modifyDesc(Item item, String desc) {
7. item = new Item();
8. item.setDescription(desc);
9. }
10. public static void main(String[] args) {
11. Item it = new Item();
12. it.setDescription(”Gobstopper”);
13. Item it2 = new Item();
14. it2.setDescription(”Fizzylifting”);
15. modifyDesc(it, “Scrumdiddlyumptious”);
16. System.out.println(it.getDescription());
17. System.out.println(it2.getDescription());
18. }
19. }
What is the outcome of the code?
A. Compilation fails.
B. Gobstopper
Fizzylifting
C. Gobstopper
Scrumdiddlyumptious
D. Scrumdiddlyumptious
Fizzylifltng
E. Scrumdiddlyumptious
Scrumdiddlyumptious
Answer: B

Question 206
Given:
11. public class ItemTest {
12. private final mt id;
13. public ItemTest(int id) { this.id = id; }
14. public void updateId(int newId) { id = newId; }
15.
16. public static void main(String[] args) {
17. ItemTest fa = new ItemTest(42);
18. fa.updateId(69);
19. System.out.println(fa.id);
20. }
21. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. The attribute id in the Item object remains unchanged.
D. The attribute id in the Item object is modified to the new value.
E. A new Item object is created with the preferred value in the id
attribute.
Answer: A

Question 207
Click the Exhibit button.
10. class Inner {
11. private int x;
12. public void setX( int x) { this.x = x; }
13. public int getX() { return x; }
14. }
15.
16. class Outer {
17. private Inner y;
18. public void setY( Inner y) { this.y = y; }
19. public Inner getY() { return y; }
20. }
21.
22. public class Gamma {
23. public static void main( String[] args) {
24. Outer o = new Outer();
25. Inner i = new Inner();
26.int n=10;
27. i.setX(n);
28. o.setY(i);
29. // insert code here
30. System.out.println( o.getY().getX());
31. }
32. }
Which three code fragments, added individually at line 29, produce the
output 100? (Choose three.)
A. n = 100;
B. i.setX( 100);
C. o.getY().setX( 100);
D. i = new Inner(); i.setX( 100);
E. o.setY( i); i = new Inner(); i.setX( 100);
F. i = new Inner(); i.setX( 100); o.setY( i);
Answer: BCF

Question 208
Click the Exhibit button.
10. class Foo {
11. private int x;
12.publicFoo(intx) {this.x=x; }
13. public void setX( int x) { this.x = x; }
14. public int getX() { return x; }
15. }
16.
17. public class Gamma {
18.
19. static Foo fooBar( Foo foo) {
20. foo = new Foo( 100);
21. return foo;
22. }
23.
24. public static void main( String[] args) {
25. Foo foo = new Foo( 300);
26. System.out.print( foo.getX() + “-“);
27.
28. Foo fooFoo = fooBar( foo);
29. System.out.print( foo.getX() + “-“);
30. System.out.print( fooFoo.getX() + “-“);
31.
32. foo = fooBar( fooFoo);
33. System.out.print( foo.getX() + “-“);
34. System.out.prmt( fooFoo.getX());
35. }
36. }
What is the output of this program?
A. 300-100-100-100-100
B. 300-300-100-100-100
C. 300-300-300-100-100
D. 300-300-300-300-100
Answer: B

Question 209
Given:
11. public void genNumbers() {
12. ArrayList numbers = new ArrayList();
13. for (int i=0; i<10; i++) {
14. int value = i * ((int) Math.random());
15. Integer intObj = new Integer(value);
16. numbers.add(intObj);
17. }
18. System.out.println(numbers);
19. }
Which line of code marks the earliest point that an object referenced
by intObj becomes a candidate for garbage collection?
A. Line 16
B. Line 17
C. Line 18
D. Line 19
E. The object is NOT a candidate for garbage collection.
Answer: D

Question 210
Given:
11. rbo = new ReallyBigObject();
12. // more code here
13. rbo = null;
14. /* insert code here */
Which statement should be placed at line 14 to suggest that the virtual
machine expend effort toward recycling the memory used by the
object rbo?
A. System.gc();
B. Runtime.gc();
C. System.freeMemory();
D. Runtime.getRuntime().growHeap();
E. Runtime.getRuntime().freeMemory();
Answer: A

SCJP Questions 191-200

Question 191
Given classes defined in two different files:
1. package util;
2. public class BitUtils {
3. public static void process(byte[]) { /* more code here */ }
4. }
1. package app;
2. public class SomeApp {
3. public static void main(String[] args) {
4. byte[] bytes = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method
of BitUtils?
A. process(bytes);
B. BitUtils.process(bytes);
C. util.BitUtils.process(bytes);
D. SomeApp cannot use methods in BitUtils.
E. import util.BitUtils.*; process(bytes);
Answer: C

Question : 192
Given classes defined in two different files:
1. package util;
2. public class BitUtils {
3. private static void process(byte[] b) { }
4. }
1. package app;
2. public class SomeApp {
3. public static void main(String[] args) {
4. byte[] bytes = new byte[256];
5. // insert code here
6. }
7. }
What is required at line 5 in class SomeApp to use the process method
of BitUtils?
A. process(bytes);
B. BitUtils.process(bytes);
C. app.BitUtils.process(bytes);
D. util.BitUtils.process(bytes);
E. import util.BitUtils. *; process(bytes);
F. SomeApp cannot use the process method in BitUtils.
Answer: F

Question 193
Given classes defined in two different files:
1. package packageA;
2. public class Message {
3. String getText() { return “text”; }
4. }
and:
1. package packageB;
2. public class XMLMessage extends packageA.Message {
3. String getText() { return “<msg>text</msg>”; }
4. public static void main(String[] args) {
5. System.out.println(new XMLMessage().getText());
6. }
7. }
What is the result of executing XMLMessage.main?
A. text
B. <msg>text</msg>
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 2 of XMLMessage.
E. Compilation fails because of an error in line 3 of XMLMessage.
Answer: E

Question 194
Given a file GrizzlyBear.java:
1. package animals.mammals;
2.
3. public class GrizzlyBear extends Bear {
4. void hunt() {
5. Salmon s = findSalmon();
6. s.consume();
7. }
8. }
and another file, Salmon.java:
1. package animals.fish;
2.
3. public class Salmon extends Fish {
4. void consume() { /* do stuff */ }
5. }
Assume both classes are defined in the correct directories for theft
packages, and that the Mammal class correctly defines the
findSalmon() method. Which two changes allow this code to compile
correctly? (Choose two.)
A. add public to the start of line 4 in Salmon.java
B. add public to the start of line 4 in GrizzlyBear.java
C. add import animals.mammals.*; at line 2 in Salmon.java
D. add import animals.fish.*; at line 2 in GrizzlyBear.java
E. add import animals.fish.Salmon.*; at line 2 in GrizzlyBear.java
F. add import animals.mammals.GrizzlyBear.*;at line 2 in Salmon.java
Answer: AD

Question 195
Given a class Repetition:
1. package utils;
2.
3. public class Repetition {
4. public static String twice(String s) { return s + s; }
5. }
and given another class Demo:
1. // insert code here
2.
3. public class Demo {
4. public static void main(String[] args) {
5. System.out.println(twice(”pizza”));
6. }
7. }
Which code should be inserted at line 1 of Demo.java to compile and
run Demo to print “pizzapizza”?
A. import utils.*;
B. static import utils.*;
C. import utils.Repetition.*;
D. static import utils.Repetition. *;
E. import utils.Repetition.twice();
F. import static utils.Repetition.twice;
G. static import utils.Repetition.twice;
Answer: F

Question 196
Given:
11. interface DeclareStuff{
12. public static final int EASY = 3;
13. void doStuff(int t); }
14. public class TestDeclare implements DeclareStuff {
15. public static void main(String [] args) {
16. int x=5;
17. new TestDeclare().doStuff(++x);
18. }
19. void doStuff(int s) {
20. s += EASY + ++s;
21. System.out.println(”s “ + s);
22. }
23. }
What is the result?
A. s 14
B. s 16
C. s 10
D. Compilation fails.
E. An exception is thrown at runtime.
Answer: D

Question 197
Given:
1. interface DoStuff2 {
2. float getRange(int low, int high); }
3.
4. interface DoMore {
5. float getAvg(int a, int b, int c); }
6.
7. abstract class DoAbstract implements DoStuff2, DoMore { }
8.
9. class DoStuff implements DoStuff2 {
10. public float getRange(int x, int y) { return 3.14f; } }
11.
12. interface DoAll extends DoMore {
13. float getAvg(int a, int b, int c, int d); }
What is the result?
A. The file will compile without error.
B. Compilation fails. Only line 7 contains an error.
C. Compilation fails. Only line 12 contains an error.
D. Compilation fails. Only line 13 contains an error.
E. Compilation fails. Only lines 7 and 12 contain errors.
F. Compilation fails. Only lines 7 and 13 contain errors.
G. Compilation fails. Lines 7, 12, and 13 contain errors.
Answer: A

Question 198
Given:
11. public class Counter {
12. public static void main(String[] args) {
13. int numArgs = /* insert code here */;
14. }
15. }
and the command line:
java Counter one fred 42
Which code, inserted at line 13, captures the number of arguments
passed into the program?
A. args.count
B. args.length
C. args.count()
D. args.length()
E. args.getLength()
Answer: B

Question 199
Given a correctly compiled class whose source code is:
1. package com.sun.sjcp;
2. public class Commander {
3. public static void main(String[] args) {
4. // more code here
5. }
6. }
Assume that the class file is located in /foo/com/sun/sjcp/, the current
directory is /foo/, and that the classpath contains “.“ (current
directory).
Which command line correctly runs Commander?
A. java Commander
B. java com. sim. sjcp.Commander
C. java com/sun/sjcp/Commander
D. java -cp com.sun.sjcp Commander
E. java -cp com/sun/sjcp Commander
Answer: B

Question 200
Given the command line java Pass2 and:
15. public class Pass2 {
16. public void main(String [] args) {
17.int x=6;
18. Pass2 p = new Pass2();
19. p.doStuff(x);
20. System.out.print(” main x = “+ x);
21. }
22.
23. void doStuff(int x) {
24. System.out.print(” doStuffx = “+ x++);
25. }
26. }
What is the result?
A. Compilation fails.
B. An exception is thrown at runtime.
C. doStuffx = 6 main x = 6
D. doStuffx = 6 main x = 7
E. doStuffx = 7 main x = 6
F. doStuffx = 7 main x = 7
Answer: B

SCJP Questions 181-190

Question 181
Given:
1. public class Test {
2. public <T extends Comparable> T findLarger(T x, T y) {
3. if(x.compareTo(y) > 0) {
4. return x;
5. } else {
6. return y;
7. }
8. }
9. }
and:
22. Test t = new Test();
23. // insert code here
Which two will compile without errors when inserted at line 23?
(Choose two.)
A. Object x = t.findLarger(123, “456”);
B. int x = t.findLarger(123, new Double(456));
C. int x = t.findLarger(123, new Integer(456));
D. int x = (int) t.findLarger(new Double(123), new Double(456));
Answer: AC

Question 182
Given:
11. // insert code here
12. private N min, max;
13. public N getMin() { return min; }
14. public N getMax() { return max; }
15. public void add(N added) {
16. if (min == null || added.doubleValue() <min.doubleValue())
17. min = added;
18. if (max == null ||added.doubleValue() > max.doubleValue())
19. max = added;
20. }
21. }
Which two, inserted at line 11, will allow the code to compile? (Choose
two.)
A. public class MinMax<?> {
B. public class MinMax<? extends Number> {
C. public class MinMax<N extends Object> {
D. public class MinMax<N extends Number> {
E. public class MinMax<? extends Object> {
F. public class MinMax<N extends Integer> {
Answer: DF

Question 183
A programmer must create a generic class MinMax and the type
parameter of MinMax must implement Comparable. Which
implementation of MinMax will compile?
A. class MinMax<E extends Comparable<E>> {
E min=null;
E max=null;
public MinMax() { }
public void put(E value) { /* store min or max */ }
}
B. class MinMax<E implements Comparable<E>> {
E min=null;
E max=null;
public MinMax() { }
public void put(E value) { /* store min or max */ }
}
C. class MinMax<E extends Comparable<E>> {
<E> E min = null;
<E> E max = null;
public MinMax() { }
public <E> void put(E value) { /* store min or max */ }
}
D. class MinMax<E implements Comparable<E>> {
<E> E min = null;
<E> E max = null;
public MinMax() { }
public <E> void put(E value) { /* store min or max */ }
}
Answer: A

Question 184
Given:
1. public class Drink implements Comparable {
2. public String name;
3. public int compareTo(Object o) {
4. return 0;
5. }
6. }
and:
20. Drink one = new Drink();
21. Drink two = new Drink();
22. one.name= “Coffee”;
23. two.name= “Tea”;
23. TreeSet set = new TreeSet();
24. set.add(one);
25. set.add(two);
A programmer iterates over the TreeSet and prints the name of each
Drink object.
What is the result?
A. Tea
B. Coffee
C. Coffee
Tea
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.
Answer: B

Question 185
Given:
11. List list = // more code here
12. Collections.sort(list, new MyComparator());
Which code will sort this list in the opposite order of the sort in line
12?
A. Collections.reverseSort(list, new MyComparator());
B. Collections.sort(list, new MyComparator());
list.reverse();
C. Collections.sort(list, new InverseComparator(
new MyComparator()));
D. Collections.sort(list, Collections.reverseOrder(
new MyComparator()));
Answer: D

Question 186
Given:
int[] myArray=newint[] {1, 2,3,4, 5};
What allows you to create a list from this array?
A. List myList = myArray.asList();
B. List myList = Arrays.asList(myArray);
C. List myList = new ArrayList(myArray);
D. List myList = Collections.fromArray(myArray);
Answer: B

Question 187
Given:
13. public static void search(List<String> list) {
14. list.clear();
15. list.add(”b”);
16. list.add(”a”);
17. list.add(”c”);
18. System.out.println(Collections.binarySearch(list, “a”));
19. }
What is the result of calling search with a valid List implementation?
A. 0
B. 1
C. 2
D. a
E. b
F. c
G. The result is undefined.
Answer: G

Question 188
Given:
1. import java.util.*;
2.
3. public class LetterASort {
4. public static void main(String[] args) {
5. ArrayList<String> strings = new ArrayList<String>();
6. strings.add(’aAaA”);
7. strings.add(”AaA”);
8. strings.add(’aAa”);
9. strings.add(”AAaa”);
10. Collections.sort(strings);
11. for (String s: strings) { System.out.print(s + “ “); }
12. }
13. }
What is the result?
A. Compilation fails.
B. aAaA aAa AAaa AaA
C. AAaa AaA aAa aAaA
D. AaA AAaa aAaA aAa
E. aAa AaA aAaA AAaa
F. An exception is thrown at runtime.
Answer: C

Question 189
Given:
ArrayList a = new ArrayList();
containing the values {“1”, “2”, “3”, “4”, “5”, “6”, “7”, “8”}
Which code will return 2?
A. Collections. sort(a, a.reverse());
int result = Collections.binarySearch(a, “6”);
B. Comparator c = Collections.reverseOrder();
Collections.sort(a, c);
int result = Collections.binarySearch(a, “6”);
C. Comparator c = Collections.reverseOrder();
Collections.sort(a, c);
int result = Collections.binarySearch(a, “6”,c);
D. Comparator c = Collections.reverseOrder(a);
Collections.sort(a, c);
int result = Collections.binarySearch(a, “6”,c);
E. Comparator c = new InverseComparator(new Comparator());
Collections.sort(a);
int result = Collections.binarySearch(a, “6”,c);
Answer: C

Question 190
Given:
34. HashMap props = new HashMap();
35. props.put(”key45”, “some value”);
36. props.put(”key12”, “some other value”);
37. props.put(”key39”, “yet another value”);
38. Set s = props.keySet();
39. // insert code here
What, inserted at line 39, will sort the keys in the props HashMap?
A. Arrays.sort(s);
B. s = new TreeSet(s);
C. Collections.sort(s);
D. s = new SortedSet(s);
Answer: B

SCJP Questions 171-180

Question 171
Given:
1. public class Person {
2. private String name;
3. public Person(String name) { this.name = name; }
4. public boolean equals(Person p) {
5. return p.name.equals(this.name);
6. }
7. }
Which is true?
A. The equals method does NOT properly override the Object.equals
method.
B. Compilation fails because the private attribute p.name cannot be
accessed in line 5.
C. To work correctly with hash-based data structures, this class must
also implement the hashCode method.
D. When adding Person objects to a java.util.Set collection, the equals
method in line 4 will prevent duplicates.
Answer: A

Question 172
Which two statements are true about the hashCode method? (Choose
two.)
A. The hashCode method for a given class can be used to test for
object equality and object inequality for that class.
B. The hashCode method is used by the java.util.SortedSet collection
class to order the elements within that set.
C. The hashCode method for a given class can be used to test for
object inequality, but NOT object equality, for that class.
D. The only important characteristic of the values returned by a
hashCode method is that the distribution of values must follow a
Gaussian distribution.
E. The hashCode method is used by the java.util.HashSet collection
class to group the elements within that set into hash buckets for
swift retrieval.
Answer: CE

Question 173
Given:
enum Example { ONE, TWO, THREE }
Which is true?
A. The expressions (ONE == ONE) and ONE.equals(ONE) are both
guaranteed to be true.
B. The expression (ONE < TWO) is guaranteed to be true and
ONE.compareTo(TWO) is guaranteed to be less than one.
C. The Example values cannot be used in a raw java.util.HashMap;
instead, the programmer must use a java.util.EnumMap.
D. The Example values can be used in a java.util.SortedSet, but the
set will NOT be sorted because enumerated types do NOT implement
java.lang.Comparable.
Answer: A

Question 174
Click the Exhibit button.
1. import java.util.*;
2. class KeyMaster {
3. public int i;
4. public KeyMaster(int i) { this.i = i; }
5. public boolean equals(Object o) { return i == ((KeyMaster)o).i; }
6. public int hashCode() { return i; }
7. }
8. public class MapIt {
9. public static void main(String[] args) {
10. Set<KeyMaster> set = new HashSet<KeyMaster>();
11. KeyMaster k1 = new KeyMaster(1);
12. KeyMaster k2 = new KeyMaster(2);
13. set.add(k1); set.add(k1);
14. set.add(k2); set.add(k2);
15. System.out.print(set.size() + “:”);
16. k2.i = 1;
17. System.out.print(set.size() + “:”);
18. set.remove(k1);
19. System.out.print(set.size() + “:”);
20. set.remove(k2);
21. System.out.print(set.size());
22. }
23. }
What is the result?
A. 4:4:2:2
B. 4:4:3:2
C. 2:2:1:0
D. 2:2:0:0
E. 2:1:0:0
F. 2:2:1:1
G. 4:3:2:1
Answer: F

Question 175
Given:
1. import java.util.*;
2. public class Test {
3. public static void main(String[] args) {
4. List<String> strings = new ArrayList<String>();
5. // insert code here
6. }
7. }
Which four, inserted at line 5, will allow compilation to succeed?
(Choose four.)
A. String s = strings.get(0);
B. Iterator i1 = strings.iterator();
C. String[] array1 = strings.toArray();
D. Iterator<String> i2 = strings.iterator();
E. String[] array2 = strings.toArray(new String[1]);
F. Iterator<String> i3 = strings.iterator<String>();
Answer: ABDE

Question 176
Given:
1. import java.util.*;
2. public class Old {
3. public static Object get()(List list) {
4. return list.get(0);
5. }
6. }
Which three will compile successfully? (Choose three.)
A. Object o = Old.get0(new LinkedList());
B. Object o = Old.get0(new LinkedList<?>());
C. String s = Old.getfl(new LinkedList<String>());
D. Object o = Old.get0(new LinkedList<Object>());
E. String s = (String)Old.get0(new LinkedList<String>());
Answer: ADE

Question 177
Given:
11. public static void append(List list) { list.add(”0042”); }
12. public static void main(String[] args) {
13. List<Integer> intList = new ArrayList<Integer>();
14. append(intList);
15. System.out.println(intList.get(0));
16. }
‘What is the result?
A. 42
B. 0042
C. An exception is thrown at runtime.
D. Compilation fails because of an error in line 13.
E. Compilation fails because of an error in line 14.
Answer: B

Question 178
Given a pre-generics implementation of a method:
11. public static int sum(List list) {
12. int sum = 0;
13. for ( Iterator iter = list.iterator(); iter.hasNext(); ) {
14. int i = ((Integer)iter.next()).intValue();
15. sum += i;
16. }
17. return sum;
18. }
Which three changes must be made to the method sum to use
generics? (Choose three.)
A. remove line 14
B. replace line 14 with “int i = iter.next();”
C. replace line 13 with “for (int i : intList) {“
D. replace line 13 with “for (Iterator iter : intList) {“
E. replace the method declaration with “sum(List<int> intList)”
F. replace the method declaration with “sum(List<Integer> intList)”
Answer: ACF

Question 179
Given:
classA {}
class B extends A {}
class C extends A {}
class D extends B {}
Which three statements are true? (Choose three.)
A. The type List<A> is assignable to List.
B. The type List<B> is assignable to List<A>.
C. The type List<Object> is assignable to List<?>.
D. The type List<D> is assignable to List<? extends B>.
E. The type List<? extends A> is assignable to List<A>.
F. The type List<Object> is assignable to any List reference.
G. The type List<? extends B> is assignable to List<? extends A>.
Answer: CDG

Question 180
Given:
11. public void addStrings(List list) {
12. list.add(”foo”);
13. list.add(”bar”);
14. }
What must you change in this method to compile without warnings?
A. add this code after line 11:
list = (List<String>) list;
B. change lines 12 and 13 to:
list.add<String>(”foo”);
list.add<String>(”bar”);
C. change the method signature on line 11 to:
public void addStrings(List<? extends String> list) {
D. change the method signature on line 11 to:
public void addStrings(List<? super String> list) {
E. No changes are necessary. This method compiles without warnings.
Answer: D

SCJP Questions 161-170

Question 161
Given:
10. interface Jumper { public void jump(); }
......
20. class Animal {}
......
30. class Dog extends Animal {
31. Tail tail;
32. }
......
40. class Beagle extends Dog implements Jumper {
41. public void jump() { }
42. }
.......
50. class Cat implements Jumper {
51. public void jump() { }
52. }
Which three are true? (Choose three.)
A. Cat is-a Animal
B. Cat is-a Jumper
C. Dog is-a Animal
D. Dog is-a Jumper
E. Cat has-a Animal
F. Beagle has-a Tail
G. Beagle has-a Jumper
Answer: BCF

Question 162
Given:
1. import java.util.*;
2. public class Example {
3. public static void main(String[] args) {
4. // insert code here
5. set.add(new integer(2));
6. set.add(new integer(l));
7. System.out.println(set);
8. }
9. }
Which code, inserted at line 4, guarantees that this program will
output [1, 2]?
A. Set set = new TreeSet();
B. Set set = new HashSet();
C. Set set = new SortedSet();
D. List set = new SortedList();
E. Set set = new LinkedHashSet();
Answer: A

Question 163
Given:
1. import java.util.*;
2. public class PQ {
3. public static void main(String[] args) {
4. PriorityQueue<String> pq = new PriorityQueue<String>();
5. pq.add(”carrot”);
6. pq.add(”apple”);
7. pq.add(”banana”);
8. System.out.println(pq.poll() +”:” + pq.peek());
9. }
10. }
What is the result?
A. apple:apple
B. carrot:apple
C. apple:banana
D. banana:apple
E. carrot:carrot
F. carrot:banana
Answer: C

Question 164
Given:
1. import java.util.*;
2. public class WrappedString {
3. private String s;
4. public WrappedString(String s) { this.s = s; }
5. public static void main(String[] args) {
6. HashSet<Object> hs = new HashSet<Object>();
7. WrappedString ws1 = new WrappedString(”aardvark”);
8. WrappedString ws2 = new WrappedString(”aardvark”);
9. String s1 = new String(”aardvark”);
10. String s2 = new String(”aardvark”);
11. hs.add(ws1); hs.add(ws2); hs.add(s1); hs.add(s2);
12. System.out.println(hs.size()); } }
What is the result?
A. 0
B. 1
C. 2
D. 3
E. 4
F. Compilation fails.
G. An exception is thrown at runtime.
Answer: D

Question 165
Click the Exhibit button.
1. import java.util.*;
2. public class TestSet {
3. enum Example { ONE, TWO, THREE }
4. public static void main(String[] args) {
5. Collection coll = new ArrayList();
6. coll.add(Example.THREE);
7. coll.add(Example.THREE);
8. coll.add(Example.THREE);
9. coll.add(Example.TWO);
10. coll.add(Example.TWO);
11. coll.add(Example.ONE);
12. Set set = new HashSet(coll);
13. }
14. }
Which statement is true about the set variable on line 12?
A. The set variable contains all six elements from the coll collection,
and the order is guaranteed to be preserved.
B. The set variable contains only three elements from the coll
collection, and the order is guaranteed to be preserved.
C. The set variable contains all six elements from the coil collection,
but the order is NOT guaranteed to be preserved.
D. The set variable contains only three elements from the coil
collection, but the order is NOT guaranteed to be preserved.
Answer: D

Question 166
Given:
1. public class Score implements Comparable<Score> {
2. private int wins, losses;
3. public Score(int w, int 1) { wins = w; losses = 1; }
4. public int getWins() { return wins; }
5. public int getLosses() { return losses; }
6. public String toString() {
7. return “<“ + wins + “,“ + losses + “>”;
8. }
9. // insert code here
10. }
Which method will complete this class?
A. public int compareTo(Object o) {/*mode code here*/}
B. public int compareTo(Score other) {/*more code here*/}
C. public int compare(Score s1,Score s2){/*more code here*/}
D. public int compare(Object o1,Object o2){/*more code here*/}
Answer: B

Question 167
A programmer has an algorithm that requires a java.util.List that
provides an efficient implementation of add(0,object), but does
NOT need to support quick random access. What supports these
requirements?
A. java.util.Queue
B. java.util.ArrayList
C. java.util.LinearList
D. java.util.LinkedList
Answer: D

Question 168
Given:
11. public class Person {
12. private String name, comment;
13. private int age;
14. public Person(String n, int a, String c) {
15. name = n; age = a; comment = c;
16. }
17. public boolean equals(Object o) {
18. if(! (o instanceof Person)) return false;
19, Person p = (Person)o;
20. return age == p.age && name.equals(p.name);
21. }
22. }
What is the appropriate definition of the hashCode method in class
Person?
A. return super.hashCode();
B. return name.hashCode() + age * 7;
C. return name.hashCode() + comment.hashCode() /2;
D. return name.hashCode() + comment.hashCode() / 2 - age * 3;
Answer: B

Question 169
Given:
11. public class Key {
12. private long id1;
13. private long 1d2;
14.
15. // class Key methods
16. }
A programmer is developing a class Key, that will be used as a key in
a standard java.util.HashMap. Which two methods should be
overridden to assure that Key works correctly as a key? (Choose two.)
A. public int hashCode()
B. public boolean equals(Key k)
C. public int compareTo(Object o)
D. public boolean equals(Object o)
E. public boolean compareTo(Key k)
Answer: AD

Question 170
Given:
11. public class Person {
12. private name;
13. public Person(String name) {
14. this.name = name;
15. }
16. public boolean equals(Object o) {
17. if( !o instanceof Person ) return false;
18. Person p = (Person) o;
19. return p.name.equals(this.name);
20. }
21. }
Which is true?
A. Compilation fails because the hashCode method is not overridden.
B. A HashSet could contain multiple Person objects with the same
name.
C. All Person objects will have the same hash code because the
hashCode method is not overridden.
D. If a HashSet contains more than one Person object with
name=”Fred”, then removing another Person, also with name=”Fred”,
will remove them all.
Answer: B