Coding Interview on Database - JDBC (java.sql) -  Two
 
Writing Text to a Socket

try { 

BufferedWriter wr = new BufferedWriter( 

new OutputStreamWriter(socket.getOutputStream()));

wr.write("aString");

wr.flush();

} catch (IOException e) {

}

Sending a Datagram

public static void send(InetAddress dst, 

int port, byte[] outbuf, int len) { 

try { 

DatagramPacket request = new DatagramPacket( 

outbuf, len, dst, port); 

DatagramSocket socket = new DatagramSocket(); 

socket.send(request); 

} catch (SocketException e) { 

} catch (IOException e) { 

Receiving a Datagram

try { 

byte[] inbuf = new byte[256]; // default size 

DatagramSocket socket = new DatagramSocket(); 

// Wait for packet 

DatagramPacket packet = new DatagramPacket( 

inbuf, inbuf.length); 

socket.receive(packet); 

// Data is now in inbuf 

int numBytesReceived = packet.getLength(); 

} catch (SocketException e) { 

} catch (IOException e) { 

Joining a Multicast Group

public void join(String groupName, int port) { 

try { 

MulticastSocket msocket = new MulticastSocket(port); 

group = InetAddress.getByName(groupName); 

msocket.joinGroup(group); 

} catch (IOException e) { 

Receiving from a Multicast Group

public void read(MulticastSocket msocket, 

byte[] inbuf) { 

try { 

DatagramPacket packet = new DatagramPacket( 

inbuf, inbuf.length); 

// Wait for packet 

msocket.receive(packet); 

// Data is now in inbuf 

int numBytesReceived = packet.getLength(); 

} catch (IOException e) { 

Sending to a Multicast Group

byte[] outbuf = new byte[1024]; 

int port = 1234;

try {

DatagramSocket socket = new DatagramSocket();

InetAddress groupAddr = InetAddress.getByName(

"228.1.2.3");

DatagramPacket packet = new DatagramPacket(

outbuf, outbuf.length, groupAddr, port);

socket.send(packet);

} catch (SocketException e) {

} catch (IOException e) {

}

Defining and Exporting a Remote Object

1. Define the remote interface. 

import java.rmi.*; 

public interface RObject extends Remote { 

void aMethod() throws RemoteException; 

Looking Up a Remote Object and Invoking a Method

try { 

// Look up remote object 

RObject robj = (RObject) Naming.lookup( 

"//localhost/RObjectServer"); 

// Invoke method on remote object 

robj.aMethod(); 

} catch (MalformedURLException e) { 

} catch (UnknownHostException e) { 

} catch (NotBoundException e) { 

} catch (RemoteException e) { 

Passing Parameters to a Remote Method

Arguments to remote methods must be primitive, serializable, or Remote. This example demonstrates the declaration and use of all three parameter types. 

1. Define the remote interface. 

import java.rmi.*; 

public interface RObject extends Remote { 

// This parameter is primitive. 

void primitiveArg(int num) throws RemoteException; 

// This parameter implements Serializable. 

void byValueArg(Integer num) throws RemoteException; 

// This parameter implements Remote. 

void byRefArg(ArgObject arg) throws RemoteException; 

public interface ArgObject extends Remote { 

int aMethod() throws RemoteException; 

2. Define the remote object implementation. 

import java.rmi.*; 

import java.rmi.server.UnicastRemoteObject; 

public class RObjectImpl extends UnicastRemoteObject implements RObject

public RObjectImpl() throws RemoteException { 

super(); 

public void primitiveArg(int num) throws RemoteException { 

public void byValueArg(Integer num) throws RemoteException { 

public void byRefArg(ArgObject arg) throws RemoteException { 

3. Compile the remote object implementation. 

> javac RObject.java RObjectImpl.java

4. Generate the skeletons and stubs. 

> rmic RObjectImpl

5. Create an instance of RObjectImpl and bind it to the RMI Registry. 

try {

RObject robj = new RObjectImpl();

Naming.rebind("//localhost/RObjectServer", robj);

} catch (MalformedURLException e) {

} catch (UnknownHostException e) {

} catch (RemoteException e) {

}

6. Look Up the Remote object and pass the parameters. 

try {

// Look up the remote object

RObject robj = (RObject) Naming.lookup("//localhost/RObjectServer");

// Pass a primitive value as argument

robj.primitiveArg(1998);

// Pass a serializable object as argument

robj.byValueArg(new Integer(9));

// Pass a Remote object as argument

robj.byRefArg(new ArgObjectImpl());

} catch (MalformedURLException e) {

} catch (UnknownHostException e) {

} catch (NotBoundException e) {

} catch (RemoteException e) {

}

Returning Values from a Remote Method

Return values from remote methods must be primitive, serializable, or Remote. This example demonstrates the declaration and use of all three return types. 1. Define the remote interface. 

import java.rmi.*; 

public interface RObject extends Remote { 

// This return value is primitive. 

int primitiveRet() throws RemoteException; 

// This return value implements Serializable. 

Integer byValueRet() throws RemoteException; 

// This return value implements Remote. 

ArgObject byRefRet() throws RemoteException; 

public interface ArgObject extends Remote { 

int aMethod() throws RemoteException; 

2. Define the remote object implementation. 

import java.rmi.*; 

import java.rmi.server.UnicastRemoteObject; 

public class RObjectImpl extends UnicastRemoteObject 

implementsRObject

public RObjectImpl() throws RemoteException { 

super(); 

public int primitiveRet() throws RemoteException { 

return 3000

public Integer byValueRet() throws RemoteException { 

return new Integer(2000)

public ArgObject byRefRet() throws RemoteException { 

return new ArgObjectImpl()

3. Compile the remote object implementation. 

> javac RObject.java RObjectImpl.java 

4. Generate the skeletons and stubs. 

> rmic RObjectImpl

5. Create an instance of RObjectImpl and bind it to the RMI Registry. 

try { 

RObject robj = new RObjectImpl(); 

Naming.rebind("//localhost/RObjectServer", robj); 

} catch (MalformedURLException e) { 

} catch (UnknownHostException e) { 

} catch (RemoteException e) { 

6. Look Up the Remote object, invoke the methods, and receive the return values. 

try { 

// Look up the remote object 

RObject robj = (RObject) Naming.lookup( 

"//localhost/RObjectServer"); 

// Receive the primitive value as return value 

int r1 = robj.primitiveRet(); 

// Receive the serializable object as return value 

Integer r2 = robj.byValueRet(); 

// Receive the Remote Object as return value 

ArgObject aobj =robj.byRefRet(); 

} catch (MalformedURLException e) { 

} catch (UnknownHostException e) { 

} catch (NotBoundException e) { 

} catch (RemoteException e) { 

Throwing an Exception from a Remote Method

1. Define the remote interface.

import java.rmi.*; 

public interface RObject extends Remote { 

void aMethod() throws RemoteException; 

2. Define the remote object implementation. 

import java.rmi.*; 

import java.rmi.server.UnicastRemoteObject; 

public class RObjectImpl extends 

UnicastRemoteObject implements RObject

public RObjectImpl() throws RemoteException { 

super(); 

public void aMethod() throws RemoteException { 

// The actual exception must be wrapped in 

// a RemoteException 

throw new RemoteException( 

"message", new FileNotFoundException("message")); 

3. Compile the remote object implementation. 

> javac RObject.java RObjectImpl.java 

4. Generate the skeletons and stubs. 

> rmic RObjectImpl

5. Create an instance of RObjectImpl and bind it to the RMI Registry. 

try { 

RObject robj = new RObjectImpl(); 

Naming.rebind("//localhost/RObjectServer", robj); 

} catch (MalformedURLException e) { 

} catch (UnknownHostException e) { 

} catch (RemoteException e) { 

6. Look up the Remote object, invoke the method, and catch the exception. 

try { 

// Look up the remote object. 

RObject robj = (RObject) Naming.lookup( 

"//localhost/RObjectServer"); 

// Invoke the method. 

robj.aMethod(); 

} catch (MalformedURLException e) { 

} catch (UnknownHostException e) { 

} catch (NotBoundException e) { 

} catch (RemoteException e) { 

// Get the actual exception that was thrown. 

Throwable realException = e.detail; 

Strings (java.lang)

Constructing a String

If you are constructing a string with several appends, it may be more efficient to construct it using a StringBuffer and then convert it to an immutable String object. 

StringBuffer buf = new StringBuffer("Initial Text");

// Modify

int index = 1;

buf.insert(index, "abc");

buf.append("def");

// Convert to string

String s = buf.toString();

Getting a Substring from a String

int start = 1;

int end = 4;

String substr = "aString".substring(start, end);// Str

Searching a String

String string = "aString";

// First occurrence.

int index = string.indexOf('S');// 1

// Last occurrence.

index = string.lastIndexOf('i');// 4

// Not found.

index = string.lastIndexOf('z');// -1

Replacing Characters in a String

// Replace all occurrences of 'a' with 'o' 

String newString = string.replace('a''o');

Replacing Substrings in a String

static String replace(String str, 

String pattern, String replace) { 

int s = 0; 

int e = 0; 

StringBuffer result = new StringBuffer(); 

while ((e = str.indexOf(pattern, s)) >= 0) { 

result.append(str.substring(s, e)); 

result.append(replace); 

s = e+pattern.length(); 

result.append(str.substring(s)); 

return result.toString(); 

Converting a String to Upper or Lower Case

// Convert to upper case 

String upper = string.toUpperCase();

// Convert to lower case

String lower = string.toLowerCase();

Converting a String to a Number

int i = Integer.parseInt("123");

long l = Long.parseLong("123");

float f = Float.parseFloat("123.4");

double d = Double.parseDouble("123.4e10");

Converting Unicode to UTF-8

try { 

String string = "\u5639\u563b";

byte[] utf8 = string.getBytes("UTF8");

} catch (UnsupportedEncodingException e) {

}

Converting UTF-8 to Unicode

public static String toUnicode(byte[] utf8buf) { 

try { 

return new String(utf8buf, "UTF8"); 

} catch (UnsupportedEncodingException e) { 

return null; 

}

Determining a Character's Unicode Block

char ch = '\u5639';

Character.UnicodeBlock block = 

Character.UnicodeBlock.of(ch);

Breaking a String into Words

String aString = "word1 word2 word3";

StringTokenizer parser = 

new StringTokenizer(aString);

while (parser.hasMoreTokens()) {

processWord(parser.nextToken());

}


Related:

Have Java Problem
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.