Create an instance of a primitive type using reflection

You have to use the appropriate wrapper classes that are associated with the primitive types:

   boolean    java.lang.Boolean 
   char       java.lang.Character 
   byte       java.lang.Byte 
   short      java.lang.Short 
   int        java.lang.Integer 
   long       java.lang.Long 
   float      java.lang.Float 
   double     java.lang.Double 

This example shows you how to go about creating a Boolean wrapper and converting it to its corresponding primitive type.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         Constructor c = Boolean.class.getConstructor(new Class[] { boolean.class });
         Boolean b = (Boolean) c.newInstance(new Object[] { new Boolean(true) });
 
         boolean result = b.booleanValue();
         System.out.println(result);
      }
      catch(NoSuchMethodException e) {
         System.err.println(e);
      }
      catch(InvocationTargetException e) {
         System.err.println(e);
      }
      catch(InstantiationException e) { 
         System.err.println(e);
      }
      catch(IllegalAccessException e) { 
         System.err.println(e);
      }
   }
}

Using soft references in Java

A soft reference is a type of a reference object that you can use to refere to an object but allow it to become garbage collected only if memory is low and no other normal Java reference is pointing to the object. It can be used for caching purposes where a cached object is only of importance in non-critical situations, but is of no importance when the internal memory is low.

The following example demonstrates this. It creates a soft reference to a StringBuffer, fills up the memory to show that only then this reference object will be garbage-collected:

Main.java:

import java.lang.ref.*;
import java.util.*;
import java.io.*;
   
public class Main {
   public static void main(String[] args) {
      SoftReference sr = new SoftReference(createDummyCacheEntry());
 
      printAccessible(sr);
 
      fillUpMemory();
  
      printAccessible(sr);
   }
 
   public static StringBuffer createDummyCacheEntry() {
      System.out.println("Creating dummy cache entry...");
      StringBuffer sb = new StringBuffer();
 
      for (int i=0; i<100000; i++) {
         sb.append("abcdefghijklmnopqrstuvwxyz");
      }
 
      return sb;
   }      
 
   public static void fillUpMemory() {
      System.out.println("Filling up memory...");
      LinkedList ll = new LinkedList();
      try {
         while (true) {
            ll.add(new Double[999999]);
         }
      } catch(OutOfMemoryError e) {
         ll.clear();
         System.gc();
      }
   }
 
   public static void printAccessible(SoftReference sr) {
      System.out.println("Softreference is" + (sr.get() == null ? " not" : "") + " accessible");
   }
}

outputs:

Creating dummy cache entry...
Softreference is accessible
Filling up memory...
Softreference is not accessible

Convert a String to lowercase or uppercase

The following example is self-explanatory:

public class TestProg
{
    public static void main(String args[])
    {
        String s = "Hello, World!";
        
        String supper = s.toUpperCase();
        String slower = s.toLowerCase();
        
        System.out.println(supper);    // prints out: HELLO, WORLD!
        System.out.println(slower);    // prints out: hello, world!
    }
}

Note: for internationalization purposes, the methods toUpperCase() and toLowerCase() perform some checking for languages as German and Turkish to do the correct conversion.
If you need these functions in time-critical applications, you might want to consider rewriting them without these checkings.

Restarting a thread that has stopped execution

You can’t, well, it depends what you mean by “stopped”. Once the thread has reached the end of its run method or is explicitely stopped (don’t!) using the deprecated stop method, it cannot be restarted. You will have to create a new Thread instance on that object and call start again.

If you need a kind-of pause behavior, implement a boolean inside your thread that you can set externally. The run method checks this flag periodically and when set it will sleep execution until the flag is unset.

Getting the maximum of two numbers

The static method max in the math class takes two values and determines the maximum. It can be used for integer, floats, longs and doubles:

import java.math.*;
                           
public class Main 
{  
   public static void main(String args[]) throws Exception {
      int    i1 = 4,     i2 = -10;
      long   l1 = 234,   l2 = 235;
      float  f1 = 2.2F,  f2 = 2.8F;       
      double d1 = 12.2D, d2 = 12.8D;
 
      int    maxi = Math.max(i1, i2);
      long   maxl = Math.max(l1, l2);
      float  maxf = Math.max(f1, f2);
      double maxd = Math.max(d1, d2);
 
      System.out.println("Maximum of integers (" + i1 + ", " + i2 + ") = " + maxi);
      System.out.println("Maximum of longs    (" + l1 + ", " + l2 + ") = " + maxl);
      System.out.println("Maximum of floats   (" + f1 + ", " + f2 + ") = " + maxf);
      System.out.println("Maximum of doubles  (" + d1 + ", " + d2 + ") = " + maxd);
   }
}

outputs:

Maximum of integers (4, -10) = 4
Maximum of longs    (234, 235) = 235
Maximum of floats   (2.2, 2.8) = 2.8
Maximum of doubles  (12.2, 12.8) = 12.8

Computing the GCD of a BigInteger

The GCD (greatest common divisor) of two numbers a and b is the largest positive number c such that c divides a and c divides b with no remainder. The BigInteger class has a method gcd that serves this purpose.

Main.java:

import java.math.*;
 
public class Main {
   public static void main(String args[]) {
      System.out.println(new BigInteger("12345678").gcd(new BigInteger("123456")));
      System.out.println(new BigInteger("87654321").gcd(new BigInteger("654321")));
   }
}

outputs:

6
3

Listing articles in a newsgroup in Java

There is an undocumented Sun package called sun.net.nntp. Following
example shows you how to list the first 20 articles in comp.lang.java.programmer
of the free newsserver news.uni-stuttgart.de.
Beware:
Why Developers Should Not Write Programs That Call ‘sun’ Packages

import sun.net.nntp.*;
import java.io.*;
 
public class Main {
   public static void main(String[] args) throws IOException {
      String newsserver = "news.uni-stuttgart.de";
      String newsgroup = "comp.lang.java.programmer";
 
      NntpClient nntp = new NntpClient(newsserver);
      //nntp.setGroup(newsgroup);
      NewsgroupInfo group = nntp.getGroup(newsgroup);
 
      for (int i = group.firstArticle; i <= group.lastArticle; i++) {
         try {
            System.out.println("Article nr: " + i);
            InputStream article = nntp.getArticle(i);
            BufferedReader br = new BufferedReader(new InputStreamReader(article));
            String line;
            while ((line = br.readLine()) != null) {
               System.out.println(line);
            }
         }
         catch (NntpProtocolException e) {
            System.out.println(e);
         }
      }
   }
}

Sending an email with the SMTP protocol in Java

The optional package JavaMail allows you to do this. I’ve devoted a separate category that tells you where you can d/l it plus some tutorials and links.

This following class doesn’t use JavaMail, but it uses SMTP commands to allow to send a simple mail. To run it, you need to specify an SMTP server, a from and to email address, subject and body.

SMTPEmail.java:

import java.io.*;
import java.net.*;

public class SMTPEmail
{
    private Socket smtpSocket;
    private BufferedReader br;
    private BufferedWriter bw;
       
    private String smtpHost;
    
    public SMTPEmail(String smtpHost) throws IOException {
        this.smtpHost = smtpHost;
    }
    
    public void connect() throws IOException {
        smtpSocket = new Socket(smtpHost, 25);
        br = new BufferedReader(new InputStreamReader(smtpSocket.getInputStream()));
        bw = new BufferedWriter(new OutputStreamWriter(smtpSocket.getOutputStream()));
    }
    
    private void disconnect() throws IOException {
        smtpSocket.close();
    }
    
    private void send(String str) throws IOException {
        System.out.println("Sending: " + str);
        bw.write(str + "rn");
        bw.flush();
    }
    
    private String receive() throws IOException {
        String str = br.readLine();
        System.out.println("Receiving: " + str);
        return str;
    }
    
    public void sendMail(String fromAddress, String toAddress, 
                         String subject, String body) throws IOException {
        connect();
        String whoami = InetAddress.getLocalHost().getHostName();
        send("HELO " + whoami);
        receive();
        send("MAIL FROM: <" + fromAddress + "> ");
        receive();
        send("RCPT TO: <" + toAddress + "> ");
        receive();
        send("DATA");
        receive();
        send("TO: " + toAddress);
        send("FROM: " + fromAddress);
        send("SUBJECT: " + subject + "rn");
        send(body);
        send("rn.rn");
        receive();
        send("QUIT");
        disconnect();
    }
}

Main.java:

import java.io.*; 
 
public class Main { 
   public static void main(String[] args) { 
      if (args.length != 5) { 
         System.err.println("usage: java Main " + " "); 
         System.exit(1); 
      } 
 
      try { 
         SMTPEmail smtp = new SMTPEmail(args[0]); 
         smtp.sendMail(args[1], args[2], args[3], args[4]); 
      } catch(IOException e) { 
         e.printStackTrace(); 
      } 
   } 
} 

Debugging permissions set by policy files

You can use the option

   -Djava.security.debug=<PARAM>
 
where <PARAM> is one of the following
   all       (turn on all debugging)
   access    (print all checkPermission results)
   jar       (jar verification)
   policy    (loading and granting)
   scl	 (permission SecureClassLoader assigns) 

The following can be used with access (for example access.domain):

   stack	 (include stack trace) 
   domain	 (dumps all domains in context)
   failure   (before throwing exception, dump stack
              and domain that didn't have permission)

When you’re testing policy problems with the Java plug-in, you can go the the plug-in control panel and to Java Runtime Parameters:

   -Djava.security.debug=<PARAM>

However, when I tried this out (with Java plug-in) it crashed the browser (IE5.5) on several params. The parameter policy worked and gave me sufficient results to solve my problem.