Instantiating an array using reflection

Use the java.lang.reflect.Array class.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      // instantiation of an array of primitives
      int primitives[] = (int[]) Array.newInstance(int.class, 10);
 
      System.out.println(primitives);
 
      // instantiation of an array of objects
      Main objects[] = (Main[]) Array.newInstance(Main.class, 10);
 
      System.out.println(objects);
   }
}

Executing a Linux shell script from Java

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String args[]) {
      try {
         Process p = Runtime.getRuntime().exec("run.sh"); 
         
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
 
         bw.write("1");
         bw.flush();
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
         br.close();
         bw.close();
 
         System.out.println(p.exitValue());
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

Excellent book:
Unix Shells by Example

Converting a primitive to a String

There are several ways you can do this. In Java programs, you will often see that a primitive is converted by using the concatenation operator on Strings (“” + primitive).
A more performant way is to use the method toString on the Object that represents the primitive or to use the static function valueOf in the String class.
Here’s an example:

public class TestProg
{
    public static void main(String args[])
    {
        short   p_short = 4;
        int     p_int = 10;
        long    p_long = 2349945821828L;
        float   p_float = 3.1415F;
        double  p_double = 0.00000000004D;
        boolean p_boolean = false;
        char    p_char = 'E';
        char    p_array[] = { 'e', 's', 'u', 's' };


        System.out.println(""+p_short);                 // 4
        System.out.println(Short.toString(p_short));    // 4
        System.out.println(String.valueOf(p_short));    // 4   (casted to an int!)
        
        System.out.println(""+p_int);                   // 10
        System.out.println(Integer.toString(p_int));    // 10
        System.out.println(String.valueOf(p_int));      // 10
        
        System.out.println(""+p_long);                  // 2349945821828
        System.out.println(Long.toString(p_long));      // 2349945821828
        System.out.println(String.valueOf(p_long));     // 2349945821828
        
        System.out.println(""+p_float);                 // 3.1415
        System.out.println(Float.toString(p_float));    // 3.1415
        System.out.println(String.valueOf(p_float));    // 3.1415
        
        System.out.println(""+p_double);                // 4.0E-11
        System.out.println(Double.toString(p_double));  // 4.0E-11
        System.out.println(String.valueOf(p_double));   // 4.0E-11
        
        System.out.println(""+p_boolean);               // false
        System.out.println(new Boolean(p_boolean).toString());  // false
        System.out.println(String.valueOf(p_boolean));  // false
        
        System.out.println(""+p_char);                  // E
        System.out.println(new Character(p_char).toString());   // E
        System.out.println(String.valueOf(p_char));     // E
        
        System.out.println(""+p_array);                 // esus
        System.out.println(p_array.toString());         // [C@1a
        System.out.println(String.valueOf(p_array));    // esus
    }
}

(Notice that the Boolean and Character classes do not have a static method toString(). In that case, you have to instantiate an object and call the toString method on it.)

To test out the difference in performance of using toString() or valueOf() over ""+p, I ran the following test:

public class TestPerformance
{
    public static void main(String args[])
    {
        double  p_double = 0.00000000004D;
        long start, end;

        System.out.println("Converting to String using concatenation");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = "" + p_double;
        end = System.currentTimeMillis();        
        System.out.println("tElapsed time: " + (end - start));
        

        System.out.println("Converting to String using valueOf");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = String.valueOf(p_double);
        end = System.currentTimeMillis();
        System.out.println("tElapsed time: " + (end - start));


        System.out.println("Converting to String using toString");
        start = System.currentTimeMillis();
        for (int i=0; i<100000; i++)
            String s = Double.toString(p_double);
        end = System.currentTimeMillis();
        System.out.println("tElapsed time: " + (end - start));      
    }
}

The output (times may vary!) shows a performance gain of almost 20%!

Converting to String using concatenation
	Elapsed time: 5270
Converting to String using valueOf
	Elapsed time: 4230
Converting to String using toString
	Elapsed time: 4230

Passing the output of one thread as the input to another (using readers/writers)

A pipe is a communication channel between two threads. It is typically used in producer-consumer systems where one thread produces data (producer) necessary for the other thread (consumer) to operate. In Java, a pipe is implemented by connecting a PipedReader instance to a PipedWriter instance:

   PipedWriter producer = new PipedWriter();
   PipedReader consumer = new PipedReader(producer);

All data written to producer will be stored in a pipe (buffer) until the consumer reads it.

In this example, a thread mimics the behavior of scores for 10 contestants coming in by generating random numbers between [0, 10[. Another thread keeps track of the total votes per contestant.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main {   
   public static void main(String[] args) throws Exception {
      PipedWriter producer = new PipedWriter();
      PipedReader consumer = new PipedReader(producer);
 
      NumberProducer np = new NumberProducer(producer);
      NumberConsumer nc = new NumberConsumer(consumer);
 
      np.start();
      nc.start();
   }
}
 
class NumberProducer extends Thread
{
   BufferedWriter bw;
 
   public NumberProducer(Writer w) {
      this.bw = new BufferedWriter(w);
   }
 
   // thread continually produces random votes
   public void run() {
      try {
         Random r = new Random();
         while (true) {
            String vote = "" + Math.abs((r.nextInt() % 10));
 
            bw.write(vote);
            bw.newLine();
            bw.flush();
 
            sleep(10);
         }  
      }   
      catch(IOException e) {
         System.err.println(e);
      }
      catch(InterruptedException e) {
         System.err.println(e);
      }      
   }
}
 
class NumberConsumer extends Thread
{
   BufferedReader br;
   int[] votes = new int[10];
  
   public NumberConsumer(Reader r) {
      br = new BufferedReader(r);
   }
 
   public void run() {
      try {
         String line;
         int count = 0;
         while ((line = br.readLine()) != null) {
            int contestant = Integer.parseInt(line);
            votes[contestant]++;
 
            count++;
            if (count % 100 == 0) 
               printVotes();
         }      
      }   
      catch(IOException e) {
         System.err.println(e);
      }
   }
 
   public void printVotes() {
      for (int i=0; i<votes.length; i++) {
         System.out.println("Contestant #" + i + ": " + votes[i]);
      }
      System.out.println("——————");
   }
}

outputs:

Contestant #0: 7
Contestant #1: 8
Contestant #2: 10
Contestant #3: 15
Contestant #4: 5
Contestant #5: 11
Contestant #6: 4
Contestant #7: 15
Contestant #8: 16
Contestant #9: 9
------------------
Contestant #0: 22
Contestant #1: 22
Contestant #2: 26
Contestant #3: 21
Contestant #4: 11
Contestant #5: 18
Contestant #6: 13
Contestant #7: 26
Contestant #8: 26
Contestant #9: 15
------------------
Contestant #0: 32
Contestant #1: 29
Contestant #2: 37
Contestant #3: 30
Contestant #4: 29
Contestant #5: 31
Contestant #6: 22
Contestant #7: 35
Contestant #8: 34
Contestant #9: 21
------------------
. . .

Getting the value for e or for pi

Both E (the base of the natural logarithms) and PI
(the ratio of the circumference of a circle to its diameter)
are defined in the Math class as static member variables of type double.
e = 2.7182818284590452354
pi = 3.14159265358979323846

System.out.println(Math.E);    // 2.718281828459045
System.out.println(Math.PI);   // 3.141592653589793

Getting the IP address of a host in Java

The InetAddress class is able to map between hostnames and IP addresses.
Following app demonstrates the use:

import java.net.*;
 
public class Main
{
   public static void main(String [] args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <URL>");
         System.exit(1);
      }
 
      try {
         InetAddress inet = InetAddress.getByName(args[0]);
         System.out.println ("IP of " + args[0] + ": " + inet.getHostAddress());
      }
      catch(UnknownHostException e) {
         System.out.println(e);
      }
   }
}

Running it with

java Main www.yahoo.com

outputs:

IP of www.esus.com: 204.71.202.160

What does the setTcpNoDelay option do?

It allows you to enable or disable Nagle’s algorithm, which is used to conserve bandwidth by minimizing the number of data segments that are sent. When TcpNoDelay is enabled, data will not be sent immediately, instead it waits for more write calls and tries to squeeze in as much as possible into a packet before sending.

If you know your app should be using small packets anyway (eg. chat apps), and send them as soon as possible (no wait), at the cost of more bandwidth, then you
can disable nagle’s algorithm:

 
   setTcpNoDelay(true)

Nagle’s algorithm is described in RFC896.

When to use setSoLinger

It allows you to control a TCP socket close() method. eg.

socket.setSoLinger(true, 5000);
...
socket.close();

the socket.close() method will block until the the data that is still in the send-buffer is sent to the other end and acknowledged. If the linger delay has passed (5000 milliseconds in this case), the socket will be forced to be closed.

What is a digital certificate?

First read the question What is a digital signature? You’ll then understand what the problem is with those signatures. You can’t really proof that the public key that the sender owns to decrypt the message actually belongs to you. That’s where a digital certificate comes in. Those certificates are issued by a certificate authority (CA) which you would have to pay and give lots of information about your identity. You’d also have to send them your public key. The CA uses all this information to generate a certificate and send it back to you. The standard for digital certificates is X.509. It contains information about your identity, your public key and things like a validity period, etc. It’s important that you choose a well-known CA that other people will trust. The CA will have encrypted the certificate with their private key.

When party A now sends a message to party B, it will sign the message with his certificate. Party B will ensure this certificate is correct by decrypting it using the CA’s public key. Now party B has access to your public key and can decrypt the signature to verify the authentication.

BTW, you can also generate a certificate yourself (eg. using the tool keytool) and use that. But people are not likely to accept that certificate as there is no trusted third party involved.

The standard for digital certificates is X.509. This standard allows for certificate chaining. This allows certificates to be put in a hierarchy. Maybe party B doesn’t trust the first CA, but goes up in the hierarchy and finds one that he trusts. For example, an employee of a company might get a certificate from his company who is in turned signed by Thawte (the root CA). Now suppose that employee uses his certificate to try to get the receiver trust him. The receiver isn’t eager to trust the one that issued the certificate, but since that certificate is signed in turn by Thawte, he trust the original certificate.

Generating a MAC that uses MD5 in Java

The following example generates a random key of 128 bits (16 bytes) necessary for HmacMD5 and computes a hash using this key. The key would have to be shared between sender and receiver.

Main.java:

import javax.crypto.spec.*;
import javax.crypto.Mac;
import java.security.*;
import javax.crypto.*;
import sun.misc.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      String message = "the sun is green and the grass shines";
 
      byte[] b = generateMAC(message);
      System.out.println("HMAC-MD5 for message '" + message + "':");
      System.out.println("t" + new BASE64Encoder().encode(generateMAC(message)));
   }
 
   public static byte[] generateMAC(String message) throws Exception {
      // generate key
      SecureRandom sr = new SecureRandom();
      byte[] b = new byte[20];
      sr.nextBytes(b);
      SecretKey key = new SecretKeySpec(b, "HmacMD5");
 
      // generate message digest based on key
      Mac mac = Mac.getInstance("HmacMD5");
      mac.init(key);
 
      return mac.doFinal(message.getBytes());
   }
}

outputs:

HMAC-MD5 for message 'the sun is green and the grass shines':
        JX25ruAB1qM0w39rTQnPGA==