Creating an instance of an inner class from a static method of the outer class

A static inner class can be instantiated without the need of an instance of the outer class.

Main.java:

public class Main {
   public static void main(String args[]) {
 
      Main main = new Main();
      Main.InnerClass ic = new InnerClass();
      ic.test();
   }
 
   static class InnerClass {
      public void test() {
         System.out.println("Method test called!");
      }
   } 
}

You need an instance of the outer class to instantiate a non-static inner class. Just specify it before the new operator.

Main.java:

public class Main {
   public static void main(String args[]) {
 
      Main main = new Main();
      Main.InnerClass ic = main.new InnerClass();
      ic.test();
   }
 
   class InnerClass {
      public void test() {
         System.out.println("Method test called!");
      }
   } 
}

Getting a list of all declared fields and values in an Object

Use the reflection API. It allows you to inspect class members at runtime. The
process is simple: get the classname from the class you want to inspect and invoke
getDeclaredFields. This will give you an array of member variables that have
been declared in that object. To get the actual value, call the get method on
a field instance with the object you want to inspect.

You are not allowed to inspect private values, unless you specifically ask for it
(see second example).

Person.java (the class we are inspecting)

public class Person
{
   public String name;
   private int age;
 
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
}

Main.java

import java.lang.reflect.Field;
  
public class Main
{
   public static void main(String[] args)
   {
      Person p = new Person("John Doe", 36);
 
      try {
         listObjectMembers(p);
      }
      catch(Exception e) { 
         System.out.println(e);
      }
   }
 
   private static void listObjectMembers(Object o) {       
      if (o == null) return;
        
      Class cl = o.getClass();
      Field fields[] = cl.getDeclaredFields();
      for (int i=0; i<fields.length; i++) {
         Field field = fields[i];
         Class fieldType = field.getType();            
 
         System.out.println(fieldType.getName() + " " + field.getName());
 
         try {
            Object member = field.get(o);
            System.out.println("thas value: " + member);
         }
         catch(IllegalAccessException e) {
            System.out.println("t" + e);     
         }        
      }
   }
}

Running this program will yield:

java.lang.String name
	has value: John Doe
int age
	java.lang.IllegalAccessException: Person

As the integer “age” is declared as being private to the class, the Java Runtime
Environment will throw an IllegalAccessException. However, since Java 2, a new
function has been added to the Field class that solves this problem.
Invoke setAccessible(true) on a field that is private, and you’ll get the value.

import java.lang.reflect.Field;
  
public class Main
{
   public static void main(String[] args)
   {
      Person p = new Person("John Doe", 36);
 
      try {
         listObjectMembers(p);
      }
      catch(Exception e) { 
         System.out.println(e);
      }
   }
 
   private static void listObjectMembers(Object o) {       
      if (o == null) return;
        
      Class cl = o.getClass();
      Field fields[] = cl.getDeclaredFields();
      for (int i=0; i<fields.length; i++) {
         Field field = fields[i];
         Class fieldType = field.getType();            
 
         System.out.println(fieldType.getName() + " " + field.getName());
 
         try {
            field.setAccessible(true);
            Object member = field.get(o);
            System.out.println("thas value: " + member);
         }
         catch(IllegalAccessException e) {
            System.out.println("t" + e);     
         }        
      }
   }
}

outputs:

java.lang.String name
	has value: John Doe
int age
	has value: 36

See the Reflection API for more functionality.

Bringing up the Windows Display Properties Window

Look at one of the other questions (eg. how do I bring up the dail-up connection window) on how to call the following external program. You can specify the startup tab.

   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,0
   result:
            displays the Background tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,1
   result:
            displays the Screen Saver tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,2
   result:
            displays the Appearance tab selected
               
   command:
            rundll32.exe shell32.dll,Control_RunDLL desk.cpl,,3
   result:
            displays the Settings tab selected

Using Runnable or extending the Thread class

Java does not support multiple inheritance. If your class already extends from a superclass and want to make it threadable, you will have to use the Runnable interface. In general, it’s good OO practice if you implement Runnable thereby saying your class is a generic Thread, instead of extending it saying “it’s kindof a thread but i want to modify some of the Thread class behavior”. Also, you typically don’t know what’s ahead in your project. If you extend from Thread and your design changes in such a way that you have to extend from another class, you’ll have to do some extra work.

In this example, class A extends from Thread, and class B implements Runnable.

Main.java:

import java.util.*;
import java.io.*;
  
public class Main {   
   public static void main(String[] args) {
 
      // starts object of class extending Thread
      new A().start();
 
      // starts object of class implementing Runnable
      new Thread(new B()).start();
   }
}
 
class A extends Thread {
   public void run() {
      System.out.println("Thread A started (and over)");
   }
}
 
class B implements Runnable {
   public void run() {
      System.out.println("Thread B started (and over)");
   }
}

Rounding up a float or a double

Use the ceil method in the Math class. It rounds up to the next higher integer:

import java.math.*;
                           
public class Main 
{  
   public static void main(String args[]) throws Exception {
      double d1 = 1.3, 
             d2 = 1.8,
             d3 = -1.3, 
             d4 = -1.8;
 
      System.out.println(Math.ceil(d1));
      System.out.println(Math.ceil(d2));
      System.out.println(Math.ceil(d3));
      System.out.println(Math.ceil(d4));
   }
}

outputs:

2.0
2.0
-1.0
-1.0

Converting a BigDecimal to a primitive type

Use the methods doubleValue, floatValue, intValue or longValue.

Main.java:

import java.math.*;
  
public class Main {
   public static void main(String args[]) {
      BigDecimal bd = new BigDecimal("4.9");
 
      int bdInt       = bd.intValue();
      long bdLong     = bd.longValue();
      float bdFloat   = bd.floatValue();
      double bdDouble = bd.doubleValue();
 
      System.out.println("Conversion " + bd + " to:");
      System.out.println("tint:t" + bdInt);
      System.out.println("tlong:t" + bdLong);
      System.out.println("tfloat:t" + bdFloat);
      System.out.println("tdouble:t" + bdDouble);
   } 
}

outputs:

Conversion 4.9 to:
	int:	4
	long:	4
	float:	4.9
	double:	4.9

Reading POP3 email with Java

You can try the optional package JavaMail (check out this category).

If you know the POP commands, you can write a pop client yourself. Here’s an example:

POPEmail.java:

import java.io.*;
import java.net.*;
 
public class POPEmail
{
    private Socket popSocket;
    private String popHost;
    private String username;
    private String password;
    private BufferedReader br;
    private BufferedWriter bw;
       
    private String smtpHost;
    
    public POPEmail(String popHost, String username, String password) throws IOException {
        this.popHost = popHost;
        this.username = username;
        this.password = password;
    }
    
    public void connect() throws IOException {
        popSocket = new Socket(popHost, 110);
        br = new BufferedReader(new InputStreamReader(popSocket.getInputStream()));        
        bw = new BufferedWriter(new OutputStreamWriter(popSocket.getOutputStream()));
        send("USER " + username);
        receive();
        send("PASS " + password);
        String status = receive();
        if (status.startsWith("-ERR"))
            throw new java.io.IOException("ERROR: USER/PASSW WRONG.");
    }
    
    public void disconnect() throws IOException {
        send("QUIT");
        receive();
        popSocket.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 int getMessageCount() {
        try {
            send("LIST");
            int n = 0;
            String line = receive();
            while (!line.equals(".")) {
                line = receive();
                try {
                    if (!line.equals("."))
                        n = Integer.parseInt(line.substring(0, line.indexOf(" ")));
                }
                catch(NumberFormatException nfe) { }
            }
            
            return n;
        }
        catch(IOException e) { }
        
        return 0;
    }
    
    public EmailMessage getMessage(int messagenumber) throws IOException {
        send("RETR " + messagenumber);
        String status = receive();
        if (status.startsWith("-ERR")) throw new IOException("Message does not exist!");
        else {
            StringBuffer stringMsg = new StringBuffer();
            String line;
            do {
                line = receive();
                stringMsg.append(line + "rn");
            } while (!line.equals("."));
            
            EmailMessage message = new EmailMessage();
            message.parse(stringMsg.toString());
            return message;
        }
    }
}

EmailMessage.java:

import java.util.*;
 
public class EmailMessage implements java.io.Serializable
{
    public String from;
    public String replyTo;
    public String to;
    public String subject;
    public String date;
    public String MIMEVersion;
    public String priority;
    public String contentType;
    public String body;
    
    public EmailMessage() {
        from = replyTo = to = subject = date = 
              MIMEVersion = priority = contentType = body = "";
    }
    
    public void parse(String message) {
        StringTokenizer st = new StringTokenizer(message, "rn");
        while (st.hasMoreElements()) {
            String line = (String) st.nextElement();
            //System.out.println("parsing: " + line);
            
            if (line.startsWith("From:"))
                from = line.substring(6);
            else if (line.startsWith("Reply-To:"))
                replyTo = line.substring(10);
            else if (line.startsWith("To:"))
                to = line.substring(4);
            else if (line.startsWith("Subject:"))
                subject = line.substring(9);
            else if (line.startsWith("Date:"))
                date = line.substring(6);
            else if (line.startsWith("MIME-Version:"))
                MIMEVersion = line.substring(14);
            else if (line.startsWith("X-Priority:"))
                priority = line.substring(12);
            else if (line.startsWith("Content-Type:"))
                contentType = line.substring(14);
            else if (line.trim().equals("")) {  // body
                StringBuffer sb = new StringBuffer();
                while (!line.equals(".")) {
                    sb.append(line);
                    line = (String) st.nextElement();
                }
            }    
        }
    }
    
    public String toString() {
        return "From: " + from + "rn" +
               "To: " + to + "rn" + 
               "Reply-To: " + replyTo + "rn" +
               "Subject: " + subject + "rn";
    }
}

Main.java:

import java.io.*; 
 
public class Main {
   public static void main(String[] args) {
      if (args.length != 3) {
         System.err.println("usage: java Main <POP server> <user> <pass>");
         System.exit(1);
      }
  
      try {
         POPEmail pop = new POPEmail(args[0], args[1], args[2]);
         pop.connect();
         System.out.println("There are " + pop.getMessageCount() + " message(s) waiting...");
         pop.disconnect();
      }
      catch(IOException e) {
         e.printStackTrace();
      }           
   }
}

Determining whether an IP address is a multicast address

A multicast address is an ip address used to denote multiple recepients. They fall in the range 224.0.0.1 to 239.255.255.255. You can use invoke the method isMulticastAddress on an instance of InetAddress to determine whether the specified address falls within that range.

Main.java:

import java.net.*;
 
public class Main {
   public static void main(String args[]) {
      try {
         InetAddress address1 = InetAddress.getByName("205.178.180.16");
         InetAddress address2 = InetAddress.getByName("224.120.50.1");
 
         System.out.println(address1.isMulticastAddress());
         System.out.println(address2.isMulticastAddress());
      }
      catch(UnknownHostException e) {
         System.out.println(e);
      }
   }
}

outputs:

false
true

What is privileged code?

It allows you to temporarily grant permission to code that would normally not have permission to run. Normally, the entire execution stack (all callers) needs to have permission to do a sensitive operation.

With Privileged Code, you can specify in a fine-grained way that only the final class in the execution stack needs permission.

For example, consider the following two classes.

Main.java:

public class Main
{
   public static void main(String []args) {
      LowLevel.executeLowLevelAction();
   }
}

LowLevel.java:

public class LowLevel
{
   public static void executeLowLevelAction() {
      System.out.println(System.getProperty("test"));
   }
}

The Main class just executes the static method executeLowLevelAction that gets the property
test.
Run log:

C:> java -Dtest="Hello, World!" Main
Hello, World!
 
C:> java -Dtest="Hello, World!" -Djava.security.manager Main
Exception in thread "main" java.security.AccessControlException: access denied
java.util.PropertyPermission test read)
        at java.security.AccessControlContext.checkPermission(AccessControlCont
xt.java:195)
        at java.security.AccessController.checkPermission(AccessController.java
403)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
        at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1
43)
        at java.lang.System.getProperty(System.java:539)
        at LowLevel.executeLowLevelAction(LowLevel.java:6)
        at Main.main(Main.java:4)

As you expected, the first run can just get the property test without needing any permissions (as no security manager is installed by default). In the second run, we ask the VM to set up a default SecurityManager which results in an AccessControlException because reading System Property “test” is not allowed.

To grant permission to read this property, we need to write a policy security configuration file. But we really only want the class LowLevel to have permission to read the property. We do not want to grant the calling class Main that permission.

So what we could do is jar the LowLevel class up and write a policy file to grant that jar file additional permissions:

C:> jar cvf LowLevel.jar LowLevel.class
added manifest
adding: LowLevel.class(in = 474) (out= 308)(deflated 35%)

C:> del LowLevel.class

mypolicy:

grant codeBase "file:/c:/LowLevel.jar" {
   Permission java.util.PropertyPermission "test", "read";
};

Run log:

C:> java -Dtest="Hello, World!" -Djava.security.manager 
          -Djava.seurity.policy=mypolicy Main
 
Exception in thread "main" java.security.AccessControlException: access denied
java.util.PropertyPermission test read)
        at java.security.AccessControlContext.checkPermission(AccessControlCont
xt.java:195)
        at java.security.AccessController.checkPermission(AccessController.java
403)
        at java.lang.SecurityManager.checkPermission(SecurityManager.java:549)
        at java.lang.SecurityManager.checkPropertyAccess(SecurityManager.java:1
43)
        at java.lang.System.getProperty(System.java:539)
        at LowLevel.executeLowLevelAction(LowLevel.java:6)
        at Main.main(Main.java:4)

AccessControlException!!? How come? Didn’t we grant the permission to LowLevel.jar to read the property “test”? The problem lays in the requirement that every class in the execution stack must have the permission.

The solution is to make the System.getProperty call in a Privileged Block. This could be done as follows.

LowLevel.java:

import java.security.*;
 
public class LowLevel
{
   public static void executeLowLevelAction() {
      String testprop = (String) AccessController.doPrivileged(new PrivilegedAction() {
         public Object run() {
            return System.getProperty("test");
         }
      });
      System.out.println(testprop);
   }
}

Compile and jar it up:

C:> javac LowLevel.java

C:> jar cvf LowLevel.jar LowLevel.class LowLevel$1.class
added manifest
adding: LowLevel.class(in = 603) (out= 384)(deflated 36%)
adding: LowLevel$1.class(in = 449) (out= 307)(deflated 31%)
 
C:> del LowLevel*.class

and run it again:

C:> java -Dtest="Hello, World!" -Djava.security.manager -Djava.sec
urity.policy=mypolicy Main
Hello, World!

Now we get the correct response: allowing only the class LowLevel to run “sensitive” code, no matter who called it, so without worrying about the executing stack.

Difference between the methods update() and doFinal() in Cipher

update() adds data to the Cipher’s internal buffer, then returns all currently completely encoded blocks. If there are any encoded blocks left over, they remain in the Cipher’s buffer until the next call, or a call to doFinal(). This means that if you call update() with a four byte array to encrypt, and the buffer size is eight bytes, you will not receive encoded data on the return (you’ll get a null instead). If your next call to update() passes five bytes of data in, you will get an 8 byte (the block size) array back, containing the four bytes passed in on the previous call, the first four bytes from the current call – the remaining byte from the current call is left in the Cipher’s buffer.

doFinal() on the other hand is much simpler: it encrypts the passed data, pads it out to the necessary length, and then returns it. The Cipher is essentially stateless.