Inverting an image

To invert an image, you can use the class LookupOp. This class works with one or more tables that will be applied to the color values of the pixels. To invert an RGB image, every R, G, and B value are subtracted from 256. The lookup table reflects these changes.

The following example shows the original image and an image that has been inverted.

Main.java:

import java.awt.image.*;
import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
 
public class Main extends JFrame {
   private boolean firstTime = true;
   private BufferedImage sourceBi;
   private BufferedImage destBi;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      }); 
   } 
 
   public void paint(Graphics graphics) {
      Graphics2D g2d = (Graphics2D) graphics;
  
      if (firstTime) {
         Image img = new javax.swing.ImageIcon("meatballs.jpg").getImage(); 
         sourceBi = toBufferedImage(img);
         destBi = new BufferedImage(sourceBi.getWidth(), sourceBi.getHeight(), 
                                    BufferedImage.TYPE_INT_RGB);
         setSize(sourceBi.getWidth(), sourceBi.getHeight()*2);
 
         byte[] intensity = new byte[256];
         for(int i=0; i<256; i++) {
            intensity[i] = (byte) (256 - i);
         }
  
         ByteLookupTable blt = new ByteLookupTable(0, intensity);
         LookupOp op = new LookupOp(blt, null);
         destBi = op.filter(sourceBi, null);
 
         firstTime = false;
      }
 
      g2d.drawImage(sourceBi, 0, 0, this);
      g2d.drawImage(destBi, 0, sourceBi.getHeight(), this);
   }
 
   public static BufferedImage toBufferedImage(Image image) {
      BufferedImage bi = new BufferedImage(image.getWidth(null), image.getHeight(null), 
                                           BufferedImage.TYPE_INT_RGB); 
 
      // copy the original image
      Graphics g = bi.createGraphics();
    
      g.drawImage(image, 0, 0, null);
      g.dispose();
 
      return bi;
   }
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
      main.setSize(300, 150);
   }
}

Image used:

To learn more about image processing,
check out this expensive but excellent book:

Serializing an array in Java

Main.java:

import java.io.*;
 
public class Main
{
   public static void main(String []args) throws Exception {
      String stringArray[] = { "this", "is", "a", "test" };
 
      ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("test.ser"));
      oos.writeObject(stringArray);
      oos.close();
 
      ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.ser"));
      String stringArray2[] = (String[]) ois.readObject();           
      ois.close();
   
      for (int i=0; i<stringArray2.length; i++) {
         System.out.println(stringArray2[i]);
      }
   }
}

Reading data from a text file in Java

If you are reading a text file, you can use the FileReader class in the java.io package. Here’s an example:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         BufferedReader br = new BufferedReader(new FileReader(args[0]));
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

You will probably still see code around that uses the method readLine of the DataInputStream class. Sun has deprecated this method because it does not properly convert bytes (1 byte) to characters (2 bytes). Here’s the code if you’re still using 1.0.2:

import java.io.*;
 
public class Main {
   public static void main(String []args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <textfile>");
         System.exit(1);
      }
  
      try {
         String line;
         DataInputStream dis = new DataInputStream(new FileInputStream(args[0]));
         while ((line = dis.readLine()) != null) {
            System.out.println(line);
         }
      }
      catch (IOException e) {
         System.out.println(e);
      }
   }
}

Determining if a pathname is absolute

A pathname is absolute if it starts with the root.

Main.java: (on a Windows system):

import java.io.*;
 
public class Main {
   public static void main(String args[]) {
      checkAbsolute("autoexec.bat");
      checkAbsolute("c:\windows\system32\.\cloud.gif");
      checkAbsolute("//windows\..\autoexec.bat");
      checkAbsolute("\windows\..\autoexec.bat");
      checkAbsolute("windows\system32");
   }
 
   public static void checkAbsolute(String s) {
      System.out.print(new File(s).isAbsolute() ? "absolute" : "not absolute");
      System.out.println("t" + s);
   }
}

outputs:

not absolute	autoexec.bat
absolute	c:windowssystem32.cloud.gif
absolute	//windows..autoexec.bat
not absolute	windows..autoexec.bat
not absolute	windowssystem32

Catching events while an image is being written out using ImageIO

Register an IIOWriteProgressListener with your ImageWriter.

   IIOWriteProgressListener listener = new MyWriteProgressListener();
   writer.addIIOWriteProgressListener(listener);

This example reads a JPG and creates a new one, vertically subsampled.

Main.java:

import javax.imageio.metadata.*; 
import javax.imageio.stream.*;
import javax.imageio.event.*;
import javax.imageio.*;
 
import java.awt.image.*; 
import java.util.*;
import java.io.*;
  
public class Main 
{ 
   public static void main(String []args) throws Exception {
      if (args.length != 1 || !args[0].endsWith(".jpg")) {
         System.out.println("Usage: java Main image.jpg");
         System.exit(1);
      }
 
      Iterator readers = ImageIO.getImageReadersByFormatName("jpg");
      ImageReader reader = (ImageReader) readers.next();
 
      Iterator writers = ImageIO.getImageWritersByFormatName("jpg");
      ImageWriter writer = (ImageWriter) writers.next();
 
      ImageInputStream iis = ImageIO.createImageInputStream(new File(args[0]));
      reader.setInput(iis, true);
      BufferedImage bi = reader.read(0);
 
      IIOWriteProgressListener listener = new MyWriteProgressListener();
      writer.addIIOWriteProgressListener(listener);
 
      String jpgFile = args[0].substring(0, args[0].length()-4) + "_new.jpg";
      ImageOutputStream ios = ImageIO.createImageOutputStream(new File(jpgFile));
      ImageWriteParam param = writer.getDefaultWriteParam();
 
      IIOImage iioImage = new IIOImage(bi, null, null);
      param.setSourceSubsampling(1, 4, 0, 0);
      writer.setOutput(ios);
      writer.write(null, iioImage, param);
   }
 
   static class MyWriteProgressListener implements IIOWriteProgressListener {
        float last = 0;
 
	public MyWriteProgressListener() {}

        public void imageStarted(ImageWriter dest, int imageIndex)  { 
           System.out.println("0% -----------------------------------> 100%n");
        }
 
        public void imageProgress(ImageWriter dest, final float percentageDone) {
           int n = (int) (percentageDone-last);
           for (int i=0; i<n/2; i++) {
              System.out.print("*");
           }
           last = percentageDone;
        }
 
        public void imageComplete(ImageWriter dest) { 
           System.out.println();
        }
 
        public void writeAborted(ImageWriter dest)                  { }
        public void sequenceComplete(ImageWriter dest)              { }
        public void sequenceStarted(ImageWriter dest, int minIndex) { }
        public void thumbnailComplete(ImageWriter dest)             { }
        public void thumbnailProgress(ImageWriter dest, float percentageDone) { }
        public void thumbnailStarted(ImageWriter dest, int imageIndex, int thumbnailIndex) { }
   }
}

Dynamically loading and creating a class from a JAR

For this example, let’s create a JAR file called testjar.jar containing only one class in a package esus.testpackage. Create a directory structure:

   esus
     |
     +--- testpackage
               |
               +-------- TestClass.java

TestClass.java:

package esus.testpackage;
 
public class TestClass
{
   public void testMethod() {
      System.out.println("testMethod() called!");
   }
}

Compile and create a JAR file:

   javac esustestpackageTestClass.java
   jar cvf testjar.jar esus

Let’s not add this JAR file to the classpath, but dynamically use it to load a class and execute a method on it. For this purpose, use the URLClassLoader which takes a set of URLs pointing to JARs or directories.

Main.java:

import java.lang.reflect.*;
import java.net.*;
  
public class Main {
   public static void main(String[] args) {
      try {
         URL []urls = new URL[] { new URL("file:testjar.jar") };
 
         ClassLoader cl = URLClassLoader.newInstance(urls);
 
         // load class 
         Class c = cl.loadClass("esus.testpackage.TestClass");
 
         // create instance of class esus.testpackage.TestClass
         Object o = c.newInstance();
 
         // execute method testMethod
         Method m = o.getClass().getMethod("testMethod", new Class[] { });
         m.invoke(o, new Object[] { });
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

outputs:

testMethod() called!

Comparing two arrays

If you want to compare if two arrays point to the same memory, you can simply compare its references:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 11, 3, 5, 7, 9 };
 
      int arr2[] = arr;
 
      if (arr == arr2) {
         System.out.println("Arrays are equal"); 
      } 
      else {
         System.out.println("Arrays are not equal"); 
      }
   }
}

If you want to compare each and one of the values of the array’s elements are equal, you can use the handy method equals in the Arrays class. Here’s an example:

import java.util.*;
import java.io.*;
 
public class Main
{
   public static void main(String []args) {
      int arr[] = { 10, 8, 6, 4, 2, 11, 3, 5, 7, 9 }; 
      int arr2[] = { 10, 3, 6, 4, 2, 11, 3, 5, 7, 9 };
 
      if (Arrays.equals(arr, arr2)) {
         System.out.println("Arrays are equal");
      }
      else {
         System.out.println("Arrays are not equal");
      }
   }
}

Declaring static member variables in an inner class

Possible only if they are final. Non-final member variables will generate a compile-time error.
See Java Language Specification 8.1.2.

Static inner classes are nested classes. You can have static member variables in static inner classes.

Main.java:

public class Outer
{
   class Inner {
      static final int a = 10;     // OK 
      static int b = 20;           // compile-error
   }
 
   static class StaticInner {
      static final int c = 10;     // OK
      static int d = 20;           // OK
   }
}

Getting a list of the public constructors of a class through reflection

Call getConstructors on a Class object. There is another method called getDeclaredConstructors but this one returns all constructors, including the private and protected ones.

Main.java:

import java.lang.reflect.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      Class c = Class.forName("MyClass");   // or Class c = MyClass.getClass();
 
      Constructor[] constructors = c.getConstructors();
      for (int i=0; i<constructors.length; i++) {
         System.out.println(constructors[i]);
      }   
   }
}
 
class MyClass
{
   public MyClass() { }
   public MyClass(int a) { }
   protected MyClass(float f) { }
   private MyClass(String s) { }
}

outputs:

public MyClass()
public MyClass(int)