Reading a BufferedImage using the ImageIO API

The new ImageIO API allows you to read and write any type of image files as long
as there is a plug-in written for it. Those plug-ins can be provided by third parties.
The appropriate plug-in is choosen depending on the file suffix, mime type, contents or format name.

The following example uses the built-in JPG plug-in.

Main.java:

import javax.swing.event.*;
import java.awt.image.*;
import java.awt.event.*;
import javax.imageio.*;
import javax.swing.*;
import java.net.*;
import java.awt.*;
import java.io.*;
 
public class Main extends JFrame
{
   BufferedImage background;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      try {
         background = ImageIO.read(new URL("http://www.esus.com/images/mong.jpg"));
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public void paint(Graphics g) {
      g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setSize(400, 400);
      main.setVisible(true);
   }
}

Who is calling a method

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      test();
   }
 
   public static void test() {
      System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      new Main().new Inner().innerTest();
   }
 
   class Inner {
      public void innerTest() {
         System.out.println("Method that called me: " + FlowInspector.getCallingMethod());
      }
   }
}

FlowInspector.java:

public class FlowInspector
{
   public static String getCallingMethod() {
      try {
         StringWriter sw = new StringWriter();
         (new Exception()).printStackTrace(new PrintWriter(sw));
         StringReader sr = new StringReader(sw.getBuffer().toString());
         BufferedReader br = new BufferedReader(sr);
         br.readLine();
         br.readLine();
         br.readLine(); 
         String line = br.readLine();
         line = line.trim().substring(3);
         line = line.substring(0, line.indexOf('('));
 
         return line;
      } catch (Exception e) {
         e.printStackTrace();
      }
 
      return null;
   }
}

Running Main yields:

Method that called me: Main.main
Method that called me: Main.test

Creating multi-dimensional arrays

Examine the following double array:

      double ar[][] = 
        { { 20.0 },
          { 20.0, 19 },
          { 20.0, 19.0, 18.0 },
          { 20.0, 19.0, 18.0, 17.0 },
          { 20.0, 19.0, 18.0, 17.0, 16.0 } };

You can achieve the same setup dynamically by looping through the row indices and dynamically creating a array with variable length:

public class Main {
   public static void main(String []args) {
      double ar[][] = null;
 
      ar = new double[5][];
      for (int i=0; i<ar.length; i++) {
         ar[i] = new double[i+1];
         for (int j=0; j<i+1; j++) {
            ar[i][j] = (double) 20 - j;
         }
      }
 
      for (int i=0; i<ar.length; i++) {
         for (int j=0; j<ar[i].length; j++) {
            System.out.print(ar[i][j] + " ");
         }
         System.out.println();
      }
   }
}

Filling in new trace information in the stack trace of an Exception

The stack trace is useful to determine where the exception was thrown. There may be times where you need to rethrow an exception and find out where it was rethrown. You can use the method fillInStackTrace for that.

Main.java:

public class Main {
   public static void main(String args[]) {
      try {
         methodWithException1();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
 
   public static void methodWithException1() throws Exception {
      try {
         methodWithException2();
      }
      catch(Exception e) {
         throw (Exception) e.fillInStackTrace();
//         throw e;
      }
   }
 
   public static void methodWithException2() throws Exception {
      throw new Exception("some extra info");
   }
}

outputs:

java.lang.Exception: some extra info
        at Main.methodWithException1(Main.java:16)
        at Main.main(Main.java:4)

If you would have written throw e instead of throw (Exception e.fillInStackTrace, the output would have been:

java.lang.Exception: some extra info
        at Main.methodWithException2(Main.java:22)
        at Main.methodWithException1(Main.java:13)
        at Main.main(Main.java:4)

Executing a method using reflection

The following example shows you how to. First get a Method instance using the getMethod method executed on any Class object of the class containing that method. Make sure you specify the correct method name and parameter list to uniquely identify the method. Then call invoke on that method instance and specify the object instance on which you want to execute that method and specify the parameters (wrap primitive types in their equivalent object types).

If you want to execute a static method, you don’t need to specify an object instance, it is ignored anyway (use null).
Main.java:

import java.lang.reflect.*;
  
public class Main {
   public static void main(String args[]) {
      MyClass myClass = new MyClass();
      MyClass.MyInnerClass myInnerClass = myClass.new MyInnerClass();
 
      try {
         Method m1 = MyClass.class.getMethod("myMethod", new Class[] { int.class });
         Object ret1 = m1.invoke(myClass, new Object[] { new Integer(1) });
         System.out.println("Returned: " + ret1);
 
         Method m2 = MyClass.class.getMethod("myStaticMethod", new Class[] { });
         Object ret2 = m2.invoke(null, new Object[] { });
 
         Method m3 = MyClass.MyInnerClass.class.getMethod("myInnerMethod", new Class[] { });
        
         Object ret3 = m3.invoke(myInnerClass, new Object[] { });
      }
      catch(NoSuchMethodException e) {
         e.printStackTrace();
      }
      catch(IllegalAccessException e) {
         e.printStackTrace();
      }
      catch(InvocationTargetException e) {
         e.printStackTrace();
      }
   }
}
 
class MyClass
{
   public int myMethod(int n) {
      System.out.println("Dynamically invoked myMethod passing: " + n);
      return n + 10;
   }
 
   public static void myStaticMethod() {
      System.out.println("Dynamically invoked myStaticMethod");
   }
 
   class MyInnerClass {
      public void myInnerMethod() {
         System.out.println("Dynamically invoked myInnerMethod");
      }
   }
}

outputs:

Dynamically invoked myMethod passing: 1
Returned: 11
Dynamically invoked myStaticMethod
Dynamically invoked myInnerMethod

Executing a DOS command from Java

Here’s an example I created on my Win2000 machine.

Main.java:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String[] args) throws IOException {
      if (args.length != 1) {
         System.out.println("Usage: java Main "doscmd"");
         System.exit(1);
      }
 
      ArrayList arrayList = new ArrayList();
      int exitValue = executeCmd(args[0], arrayList);
 
      System.out.println("Exit value is " + exitValue);
      System.out.println();
      for (int i=0; i<arrayList.size(); i++) {
         System.out.println("Line " + i + ":t" + arrayList.get(i));
      }
   }
 
   public static int executeCmd(String command, ArrayList arrayList) throws IOException {
      Process process = Runtime.getRuntime().exec("cmd /c " + command);
      InputStreamReader isr = new InputStreamReader(process.getInputStream());
      BufferedReader br = new BufferedReader(isr);
 
      String line;
      while ((line = br.readLine()) != null) {
         arrayList.add(line);
      }
 
      try {
         process.waitFor();
      }
      catch (InterruptedException e) {
      }
      br.close();
    
      return process.exitValue();
   }
}

Example run:

C:myruntime>java Main "dir /w"
Exit value is 0
 
Line 0:  Volume in drive C has no label.
Line 1:  Volume Serial Number is E4D8-7443
Line 2:
Line 3:  Directory of C:myruntime
Line 4:
Line 5: [.]          [..]         Main.class   Main.java
Line 6:                2 File(s)          2,958 bytes
Line 7:                2 Dir(s)   1,925,675,008 bytes free

Difference between String a=”a” and String a=new(“a”)

I’m assuming you mean “what’s the difference between
String a = “a”;
and
String a = new String(“a”);
The simple answer is that in the 2nd case an extra,
unnecessary String object is created. The reason for that is
that even string literals in Java are instances of class
String, so what happens in the 2nd case is that a string
literal “a” is created and then another String object with
a copy of the same value is created.
The complicated answer is that there is another difference.
All Java string literals are saved by the compiler directly
into the class file, the JVM then reads the class file
and creates instances of class String for all the string
literals in the class file. All these instances are saved in
a special internal pool of Strings inside the String class.
What does this mean? It means that if you do:

String a = "a";
String b = "a";

Then both a and b will reference the SAME object (so a==b is
true). But if you do this:

String a = "a";
String b = new String("a");

Then a and b will reference different String objects (both
strings will have the same value, but they will be 2 strings,
not one like in the first case).

You can add a String into the internal pool by invoking the
intern() method on a String. That method creates a new string
with the same value (if none exists in the pool already),
adds it to the pool and returns it.

Determining the Unicode category for a particular character

Try the static method Character.getType.

Main.java:

public class Main {
   public static void main(String args[]) {
      System.out.println(Character.getType('D'));
      System.out.println(Character.getType(' '));
      System.out.println(Character.getType(')'));
      System.out.println(Character.getType('1'));
      System.out.println(Character.getType('-'));
   }
}

outputs:

1	(UPPERCASE_LETTER)
12	(SPACE_SEPARATOR)
22	(END_PUNCTUATION)
9	(DECIMAL_DIGIT_NUMBER)
20	(DASH_PUNCTUATION)

What does the strictfp keyword do?

The keyword strictfp allows you to have more (predictable) control over floating-point arithmetic. It may be used (as a modifier) to classes, interfaces and methods. If a floating point expression is within a strictfp “scope”, the results will be as predictable as described in IEEE 754 (see link below). If the expression is not FP-strict, the specification is more tolerant and the result is determined by the extra precision bits that may be used in evaluating the expression (extended exponent range implemented by the VM being used).
Check out the other link below (Changes to the Java Language Specification).

Connect to the net through a proxy server in Java

An applet will automatically use the browser settings. With an application, the proxy server can be specified with the following properties: proxySet, proxyHost and proxyPort.

They can either be set at the command line or in the source.

At command line:

java -DproxySet=true -DproxyHost=proxyserver.come -DproxyPort=80 Main

In source:

import java.util.Properties;

...

Properties props = System.getProperties();
props.put("proxySet", "true");
props.put("proxyHost", "proxyserver.com");
props.put("proxyPort", "80");
System.setProperties(props);

It could be that the proxy server requires you to authenticate with a username + password. This request has to be in the form “username:password” encoded in base64. A converter to base64 can be found in the package sun.misc – BASE64Encoder. The final call is to setRequestProperty which will change the http header as to get you through the proxy.
Code snippet:

   import sun.misc.*;

   URL url = new URL("http://www.yahoo.com");
   URLConnection connection = url.openConnection();

   String authReq = "myusername:mypassword";   // replace myusername and mypassword
   B64Encoder = new BASE64Encoder();

   String encodedAuthReq = B64Encoder.encode(authReq.getBytes());

   connection.setRequestProperty("Proxy-Authorization", "basic " + encodedAuthReq);