How to display numbers in scientific notation?

You can display numbers in scientific notation using java.text package. Specifically DecimalFormat class in java.text package can be used for this aim.
import java.text.*;
import java.math.*;

public class TestScientific {

  public static void main(String args[]) {
     new TestScientific().doit();
  }

  public void doit() {
     NumberFormat formatter = new DecimalFormat();

     int maxinteger = Integer.MAX_VALUE;
     System.out.println(maxinteger);    // 2147483647

     formatter = new DecimalFormat("0.######E0");
     System.out.println(formatter.format(maxinteger)); // 2,147484E9

     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(maxinteger)); // 2.14748E9


     int mininteger = Integer.MIN_VALUE;
     System.out.println(mininteger);    // -2147483648

     formatter = new DecimalFormat("0.######E0");
     System.out.println(formatter.format(mininteger)); // -2.147484E9

     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(mininteger)); // -2.14748E9

     double d = 0.12345;
     formatter = new DecimalFormat("0.#####E0");
     System.out.println(formatter.format(d)); // 1.2345E-1

     formatter = new DecimalFormat("000000E0");
     System.out.println(formatter.format(d)); // 12345E-6
  }
}
Read more!

How to copy an array in java?

To copy the contents of one array into another array you can use the static method arraycopy() of the System class.
The method takes five parameters: source, source start position, destination, destination start position and finally the length of the data to be copied.
In this example we create an array of integers with ten values and then use the arraycopy() method to copy the contents to another array.
public class Main {
    
    /**
     * Lists the system properties
     */
    public void copyArrayExample() {
        
        int[] intArray = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
        
        int[] arrayCopy = new int[intArray.length];
        
        System.arraycopy(intArray, 0, arrayCopy, 0, intArray.length);
        
        for (int i = 0; i < arrayCopy.length; i++)
            System.out.println(arrayCopy[i]);
        
    }
    
    
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().copyArrayExample();
    }
}

/**The output of the code will be (as you might have guessed):
 *1
 *2
 *3
 *4
 *5
 *6
 *7
 *8
 *9
 *0
 */
Read more!

How applet can read system properties?

Applets can read quite many of system properties by using the following:
System.getProperty("java.version")
System.getProperty("java.vendor")
System.getProperty("java.vendor.url")
System.getProperty("java.class.version")
System.getProperty("os.name")
System.getProperty("os.arch")
System.getProperty("os.version")
System.getProperty("file.separator")
System.getProperty("path.separator")
System.getProperty("line.separator")
Read more!

How to define and export a remote object?

This Java tip illustrates a method of defining and Exporting a Remote Object. The interface Exporter is a high-level API for both exporting a single remote object so that it can receive remote method invocations, and unexporting that same remote object.
1. Define the remote interface.
      import java.rmi.*;

      public interface RObject extends Remote {
          
          void aMethod() throws RemoteException;
          
      }
2. Define the remote object implementation.
      import java.rmi.*;
      import java.rmi.server.UnicastRemoteObject;

      public class RObjectImpl extends UnicastRemoteObject 
              implements RObject {
          
          public RObjectImpl() throws RemoteException {
              super();
          }
          
          // All remote methods must throw RemoteException
          public void aMethod() throws RemoteException {
          }
          
      }
3. Compile the remote object implementation.
          > javac RObject.java RObjectImpl.java
4. Generate the skeletons and stubs.
          > rmic RObjectImpl
5. Create an instance of the remote object and bind it to the RMI registry.
      try {
          
          RObject robj = new RObjectImpl();
          Naming.rebind("//localhost/RObjectServer", robj);
          
      } catch (MalformedURLException e) {
          
      } catch (UnknownHostException e) {
          
      } catch (RemoteException e) {
          
      }
Read more!

Chaining of Streams

The derived classes of FilterInputStream class takes input from a stream and filters it so that when you read from this stream, you get a filtered view of input. Similar is the case with FilterOutputStream class. Filtering merely means that the filter stream provides additional functionality such as buffering monitoring line numbers or aggregating data bytes into more meaningful primitive data type units. Thus filter streams have to work in tandem with a producer /consumer. The design of the filter classes allows multiple chained filters to be created using several layers of nesting. Each subsequent class accesses the output of the previous class through the in variable. This is called as Chaining of Streams.
The following is a sample program on Chaining of Streams using character stream classes. Here the FileReader actually reads from source file. The BufferedReader uses the FileReader object to read input from. The LineNumberBuffer reads from the BufferedReader object and allocates line numbers to each line.
import java.io.*;

public class DemoChanning {

  public static void main(String[] args) {

    String s;

    try {
      FileReader fr = new FileReader("C:\\chainstreams.txt");
      BufferedReader br = new BufferedReader(fr);
      LineNumberReader lr = new LineNumberReader(br);

      while ((s = lr.readLine()) != null)
        System.out.println(lr.getLineNumber() + " " + s);

    } catch (IOException e) {
      System.out.println(e.getMessage());
    }
  }
}

Input File: chainstreams.txt

Output:

1 hi dude 
2 HOW IS your life going on?
3 it's gettting along fine.
Read more!

How to display message in browser status bar?

In this applet example you'll see how to display a message in browser status bar. To make the example a little bit more interesting we'll display the current time as the message. The time will be update every on second during the life time of the applet.
import java.applet.Applet;
import java.awt.Graphics;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
 
public class TimeApplet extends Applet implements Runnable {
private DateFormat formatter = null;
private Thread t = null;
 
public void init() {
formatter = new SimpleDateFormat("hh:mm:ss");
t = new Thread(this);
}
 
public void start() {
t.start();
}
 
public void stop() {
t = null;
}
 
public void paint(Graphics g) {
Date now = Calendar.getInstance().getTime();
//
// Show the current time on the browser status bar
//
this.showStatus(formatter.format(now));
}
 
public void run() {
int delay = 1000;
try {
while (t == Thread.currentThread()) {
//
// Repaint the applet every on second
//
repaint();
Thread.sleep(delay);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Read more!

How to create a Hello World Applet?

The code below demonstrate the very basic of Java applet. Applet is a small Java application that can be embedded on the web browser.
import java.applet.*;
import java.awt.*;
 
public class HelloWorldApplet extends Applet {
public void init() {
}
 
public void start() {
}
 
public void stop() {
}
 
public void destroy() {
}
 
public void paint(Graphics g) {
g.setColor(Color.GREEN);
g.drawString("Hello World", 50, 100);
}
}
Read more!

How to change an applet background color?

By default the applet will have a gray background. If you want to change it then you can call the setBackground(java.awt.Color) and choose the color you want. Defining the background color in the init method will change the color as soon as the applet initialized.
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class WhiteBackgroundApplet extends Applet {
    public void init() {
 //
 // Here we change the default gray color background of an applet to
 // white background.
 //
 setBackground(Color.WHITE);
    }
    
    public void paint(Graphics g) {
 g.setColor(Color.BLACK);
 g.drawString("Applet background example", 0, 50);
    }
}
Read more!

How to extend the size of an array?

This example shows how to extend the size of an array. Since arrays are static in size, they cannot be extended in the way collection objects can (for example a Vector).
Hence we need to create a new array, add the new data and copy data from the first array.
In this example we create an array with three names, then we create another array with the length of 5. We add two names to position 3 and 4 (which is really position 4 and 5 since the first element of an array has the index 0).
Then we use the arraycopy() method of the System class and specify that we want to transfer data from the first position in the names array (param 1 and 2), and we want to insert the data in the array "extended" (param 3) from the first position (param 4) up to the length of the array "names" (param 5).
Finally we print the elements of the extended array.
public class Main {
    
    /**
     * Extends the size of an array.
     */
    public void extendArraySize() {
        
        
        String[] names = new String[] {"Joe", "Bill", "Mary"};
        
        //Create the extended array
        String[] extended = new String[5];
        
        //Add more names to the extended array
        extended[3] = "Carl";
        extended[4] = "Jane";
        
        //Copy contents from the first names array to the extended array
        System.arraycopy(names, 0, extended, 0, names.length);
        
        //Ouput contents of the extended array
        for (String str : extended) 
            System.out.println(str);
        
    }
    /**
     * Starts the program
     *
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        new Main().extendArraySize();
    }
}

/**So the output will look like this when the code above is executed:
 *Joe
 * Bill
 * Mary
 * Carl
 * Jane
 */
Read more!

How to determine the host from where the applet is loaded?

You can determine the host from where an Applet is loaded using getCodeBase() method. An example usage is implementing a simple copy protection scheme. If the retrieved codebase does not equal to your predefined host then you can quit.
import java.applet.*;

public class MyApplet extends Applet {
  public void init() {
    System.out.println(getCodeBase());
    //
    // you can check the value of getCodeBase()
    // to implements a simple copy protection
    // scheme. If it's not equals to your
    // URL then quit.
    //
  }
}

Read more!