Catching CTRL-C or the unix kill command

Run this program and press CTRL-C! (JDK1.3+)

public class Main {
   public static void main(String[] args) {
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
      while (true) ;
   public static void cleanup() {
      System.out.println("Cleaning up...");

Converting a String to a Reader

Use the class StringReader and pass it a String as an argument. Then you can use the typical Reader’s methods.

public class Main
   public static void main(String []args) {
      StringReader sr = new StringReader("Hello, world!");
      try {
         int ch;
         while ((ch = > 0) {
            System.out.println("Read: " + (char) ch);
      catch(IOException e) {

What is UTF-8?

The standard UTF-8 format is a Unicode encoding that is compatible with ASCII, allowing old programs to work with the new format (text searching, etc). ASCII values are encoded into a single byte. Java has a modified UTF-8 format. Arabic, Greek and Hebrew characters are encoded in two bytes and the rest is encoded in three bytes. The JVM does not recognize longer UTF-8 formats than 3 bytes. There is another exception in Java, ‘u0000′ is encoded in two bytes.

u0000 is encoded in two bytes:
        byte 1        byte 2 
        110 00000  |  10 000000
range 'u0001' to 'u007f'  (ASCII values) are encoded in one byte:
        byte 1
        0 bits 0-6
range 'u0080' to 'u07ff' are encoded in two bytes:
        byte 1            byte 2
        110 bits 6-10  |  10 bits 0-5
range 'u0800' to 'uffff' are encoded in three bytes:
        bytes 1             byte 2           byte 3
        1110 bits 12-15  |  10 bits 6-11  |  10 bits 0-5

For example: (I’ll take the example of the RFC – see links).

The Unicode sequence: "Hi Mom <WHITE SMILING FACE>!" with encoding 
0048, 0069, 0020, 004D, 006F, 006D, 0020, 263A, 0021 
may be encoded as 
 48    69    20    4D    6F    6D    20 E2 98 BA 21

Getting a random floating-point number

Use the Random class in the java.util package. Following example prints out 10 pseudo-randomly selected floating point numbers:

import java.util.*;
public class Main 
   public static void main(String args[]) {
      Random r = new Random();   // seed automatically set to System.currentTimeMillis()
      for (int i=0; i<10; i++) {
         float f = r.nextFloat();

(possibly) outputs:


You could set the seed manually:

   Random r = new Random(10);
   Random r = new Random();

Getting the IP of the localhost

Following code demonstrates this:


public class Main
   public static void main(String []args) {
      try {
         InetAddress local = InetAddress.getLocalHost();

         System.out.println ("IP of localhost: " + local.getHostAddress());
      catch(UnknownHostException e) {


IP of localhost:

Checking the last-modified date of a URL file

The getLastModified() Method in the URLConnection connection class allows you to get the Last modified date.

It can be done in the following manner:

        String urlpath = new String("");
	url = new URL(urlpath);
	connection = url.openConnection();
        System.out.println(urlpath+ " was last modified on "+ new java.util.Date(connection.getLastModified()));

The getLastModified() method returns a long value, the number of seconds since the start of the epoch( 1970 ) till the modified date. The output for the above url was “Last Modified on Thu Apr 19 03:01:25 GMT+05:30 2001″

When to use UDP sockets

TCP sockets are connection-oriented and reliable sockets i.e they make sure for data to be successfully transmitted to destination, so if u want to transfer files or some imp. data u need to do it thru TCP

on the contrary, UDP sockets are connection less i.e. data divided into packets can transfer to dest. via any of valid routes and as no acknowledgement is required from destn. it is unreliable data transfer mode so if you are transferring lee useful data like some voice rec. or video streams u can use it.

Creating a digital certificate with keytool

Look at the command-line options of keytool.

For example, to create a public/private key pair and store it in the default keystore (in my case C:Windows.keystore) under the alias mykey:

C:> keytool -genkey -keyalg RSA -alias mykey
Enter keystore password:  esuspass
keytool error: Key pair not generated, alias <mykey> already exists

C:>keytool -genkey -keyalg RSA -alias esuskey
Enter keystore password:  esuspass
What is your first and last name?
  [Unknown]:  Joris Van den Bogaert
What is the name of your organizational unit?
  [Unknown]:  Esus Team
What is the name of your organization?
  [Unknown]:  Esus, Inc.
What is the name of your City or Locality?
  [Unknown]:  Meerbeek
What is the name of your State or Province?
What is the two-letter country code for this unit?
  [Unknown]:  BE
Is <CN=Joris Van den Bogaert, OU=Esus Team, O="Esus, Inc.", L=Meerbeek, ST=Unkno
wn, C=BE> correct?
  [no]:  yes

Encrypting/decrypting a message using a symmetric encryption method (eg. DES)

Eric Young has written an implementation of DES. Here are the source files:

The file has been slightly modified (added a memset method to ensure 8 bytes are used for the key).

Here’s an example on how to use these classes:

public class Main
   public static void main(String []args) {
      // key (8 bytes) 
      String key = "12345678";
      // encrypt using Eric Young's DES Java implementation
      byte[] de = Des.encrypt(key, ", aiming to provide the largest Java directory on the web");
      // decrypt 
      String s = Des.decrypt(key, de);

Encrypting/decrypting a message using an assymetric encryption method (eg. RSA)

The following code demonstrates using a pair of RSA public/private key pairs to secure a message between a producer and a consumer. It also generates and validates a signature along the way since that is another common task.

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import javax.crypto.*;
public class AsymetricTest {
    // these algorithms need to work together!
    public static String keyAlgorithm = "RSA" ;
    public static String cipherAlgorithm = "RSA/OAEP" ;
    public static String signatureAlgorithm = "SHA1WithRSAEncryption" ;
    static public void main(String[] args) {
	String testData = "Hugh, and only Hugh, can prevent florist friars." ;
	try {
	    // make sure the BC provider is registered.
	    Security.addProvider(new BouncyCastleProvider());
	     * Generate two pairs of keys, one for the producer
	     * and one for the consumer.
	    KeyPairGenerator gen = KeyPairGenerator.getInstance(keyAlgorithm, "BC");
	    gen.initialize(1024, new SecureRandom());
	    System.out.println("Generating keys . . .") ;
	    KeyPair producerPair = gen.generateKeyPair();
	    KeyPair consumerPair = gen.generateKeyPair();
	    System.out.println("Generated keys, proceeding") ;
	     * first on the producer side: encrypt and sign the
	     * original data.  The producer knows the consumer public key.
	    // encrypt the testData using the public key
	    byte[] encryptedData = encrypt(testData.getBytes(), consumerPair.getPublic()) ;
	    System.out.println("Encrypted byte count: " + encryptedData.length) ;
	    // generate a digital signature
	    byte[] dataSignature = generateSignature(testData, producerPair.getPrivate()) ;
	    System.out.println("Signature created, bytes: " + dataSignature.length) ;
	     * uncomment one of these lines to befoul either the
	     * encrypted data or the signature "in transit" if you want
	     * to see a failure in the next steps.
	    //encryptedData[8] = 0 ;
	    //dataSignature[8] = 0 ;
	     * and now on the consumer side: decrypt the original data,
	     * then use that result to validate the signature.  The
	     * consumer knows the producer's public key.
	    // decrypt the message using the private key
	    byte[] receivedData = decrypt(encryptedData, consumerPair.getPrivate()) ;
	    System.out.println("Data decoded, byte count: " + receivedData.length) ;
	    System.out.println("[" + new String(receivedData) + "]") ;
	    // and validate the signature
	    if ( ! validateSignature(receivedData, dataSignature, producerPair.getPublic()) ) {
		throw new SignatureException("Signature validation failed") ;
	    System.out.println("Signature OK.") ;
	catch ( Exception ex ) {
	    ex.printStackTrace() ;

    public static byte[] encrypt(byte[] toEncrypt, PublicKey key)
				    throws GeneralSecurityException {
	Cipher cipher = Cipher.getInstance(cipherAlgorithm) ;
	cipher.init(Cipher.ENCRYPT_MODE, key) ;
	byte[] result = cipher.doFinal(toEncrypt) ;
	return result ;

    public static byte[] decrypt(byte[] toDecrypt, PrivateKey key)
				    throws GeneralSecurityException {
	Cipher deCipher = Cipher.getInstance(cipherAlgorithm) ;
	deCipher.init(Cipher.DECRYPT_MODE, key) ;
	deCipher.update(toDecrypt) ;
	byte[] result = deCipher.doFinal() ;
	return result ;

    public static byte[] generateSignature(String toSign, PrivateKey key)
				    throws GeneralSecurityException {
	Signature genSig = Signature.getInstance(signatureAlgorithm) ;
	genSig.initSign(key) ;
	genSig.update(toSign.getBytes()) ;
	byte[] result = genSig.sign() ;
	return result ;

    public static boolean validateSignature(byte[] dataToValidate, byte[] sigToValidate, PublicKey key)
				    throws GeneralSecurityException {
	Signature valSig = Signature.getInstance(signatureAlgorithm) ;
	valSig.initVerify(key) ;
	valSig.update(dataToValidate) ;
	return valSig.verify(sigToValidate) ;

(tested with the BouncyCastle JCE provider,