Finding out the classloader that loaded a particular class

You can have your classes loaded by several distinct classloaders. For example, you may have a URLClassLoader that loads your classes over the network.

To determine what ClassLoader loaded a particular class, you can invoke getClassLoader on the Class object of that class. This method returns null if the default system classloader was used to load the class.

Main.java:

public class Main {
   public static void main(String args[]) throws Exception {
 
      System.out.println(Main.class.getClassLoader());
      System.out.println(A.class.getClassLoader());
      System.out.println(String.class.getClassLoader());
   }
}
 
class A 
{
}

outputs:

sun.misc.Launcher$AppClassLoader@81012801
sun.misc.Launcher$AppClassLoader@81012801
null

Returning multiple values from a method

Strictly speaking you cannot return multiple values from a method call. A method can only return a single primitive value or Object.

Since however, you can return an Object you can always create a new class that contains the values you want to return and simply return a single Object of that class which contains the values needed.

Here we’re trying to get the first and last names of a user with a single call to the User object.

public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";

   /**
    * This isn't really what you want, since the two values
    * are merged together.
    */
   public String getName() {
      return ivFirstName+" "+ivLastName;
   }
}

Here, we use a new class called UserName that can hold the two values in question.

public class UserName {
   protected String ivFirstName, ivLastName;
 
   public UserName(String first, String last) {
      ivFirstName = first;
      ivLastName  = last;
   }
 
   public String getFirstName() {
      return ivFirstName;
   }
 
   public String getLastName() {
      return ivLastName;
   }
}
 
public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";
 
   /**
    * This is returning a single Object, which contains
    * multiple values.
    */
   public UserName getName() {
      return  new UserName(ivFirstName, ivLastName);
   }
}

It’s better in general to just return a single value. There are some rare instances where multiple values need to be returned, but these are the exception, and can be dealt with by the preceeding example.

public class User {
   protected String ivFirstName = "Java";
   protected String ivLastName  = "Developer";
 
   /**
    * This is better practice all around.
    */
   public String getFirstName() {
      return ivFirstName;
   }
 
   /**
    * This is better practice all around.
    */
   public String getLastName() {
      return ivLastName;
   }
}

Accessing the private members of a class using reflection

Work with the Field class and the method setAccessible introduced in JDK1.2.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      Person person = new Person();
 
      Field field = Person.class.getDeclaredField("name");
      field.setAccessible(true);
 
      field.set(person, "alicia");
 
      System.out.println("Name is now: " + person.getName());
   }
}
 
class Person {
   private String name = "joris";
 
   public String getName() {
      return name;
   }
}

prints out:

alicia

You can disallow setAccessible capability by installing a security manager.

Catching CTRL-C or the unix kill command

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

Main.java:

public class Main {
   public static void main(String[] args) {
      Runtime.getRuntime().addShutdownHook(new Thread() {
         public void run() {
            cleanup();
         }
      });
 
      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.

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      StringReader sr = new StringReader("Hello, world!");
 
      try {
         int ch;
         while ((ch = sr.read()) > 0) {
            System.out.println("Read: " + (char) ch);
         }
      }
      catch(IOException e) {
         System.out.println(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();
         System.out.println(f);
      }
   }
}

(possibly) outputs:

0.2020728
0.9253481
0.60519326
0.9515787
0.013608098
0.739903
0.8019556
0.15060985
0.7387842
0.109374285

You could set the seed manually:

   Random r = new Random(10);
   
   or
  
   Random r = new Random();
   r.setSeed(10);

Getting the IP of the localhost

Following code demonstrates this:

import java.net.*;

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) {
         System.out.println(e);
      }
   }
}

displays:

IP of localhost: 212.190.6.190

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("http://www.esus.com/respondquestionexample.html");
	url = new URL(urlpath);
	connection = url.openConnection();
        connection.connect();
        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″