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)

Accessing array elements through reflection

You can do so with Array.get.

Main.java:

import java.lang.reflect.*;
 
public class Main
{
   public static void main(String []args) {
      int[]   intArray    = new int[] { 1, 2, 3, 4, 5 };
      int[][] intintArray = new int[][] { { 1, 2}, {3, 4}, {5} };
      
      printArray(intArray);
      System.out.println();
      printArray(intintArray);
   }
 
   public static void printArray(Object array) {
      int arrayLength = Array.getLength(array);
      Class componentClass = array.getClass().getComponentType(); 
 
      System.out.println("Array length     " + arrayLength);
      System.out.println("Component class  " + componentClass);
      System.out.println("Array contents");
      for (int i=0; i<arrayLength; i++) {
         Object element = Array.get(array, i);
         if (element.getClass().isArray()) {
            printArray(element);
         }
         else {
            System.out.print(Array.get(array, i) + " ");
         }
      }
      System.out.println();
   }
}

outputs:

Array length     5
Component class  int
Array contents
1 2 3 4 5

Array length     3
Component class  class [I
Array contents
Array length     2
Component class  int
Array contents
1 2
Array length     2
Component class  int
Array contents
3 4
Array length     1
Component class  int
Array contents
5

Executing an batch file from Java

Start the process using the Runtime class. Using the methods getInputStream and getOutputStream, you can manipulate the input- and outputstreams of the batch file.
Here’s an example:

import java.io.*;
 
public class Main
{
   public static void main(String args[]) {
      try {
         Process p = Runtime.getRuntime().exec("run.bat"); 
         
         BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
         BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
 
         bw.write("1");
         bw.flush();
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
         br.close();
         bw.close();
 
         System.out.println(p.exitValue());
      }
      catch(Exception e) {
         System.out.println(e);
      }
   }
}

run.bat:

@echo off
choice /c123 /n
if errorlevel 1 echo first
if errorlevel 2 goto second
if errorlevel 3 goto third
exit

first:
echo First option
exit

second:
echo Second option
exit

third:
echo Third option
exit

Problem: returning an exitcode from a batch file to the calling Java app doesn’t seem to work. anyone?

Converting a String to an InputStream

Main.java:

import java.io.*;

public class Main
{
   public static void main(String []args) throws Exception {
      String s = "hello world!";
      
      InputStream is = getInputStream(s, "UTF-8");
      int c;
      while ((c = is.read()) > -1) {
         System.out.print((char) c);
      }
      System.out.println();
   }
   
   public static InputStream getInputStream(String s, String encoding) throws UnsupportedEncodingException {
      return new ByteArrayInputStream(s.getBytes(encoding));
   }
}

The Unicode general category types

Each Unicode character belongs to a certain category. According to the API, “the character attribute tables for specific version of Unicode are available in various subdirectories of ftp://ftp.unicode.org/Public/

0  -  UNASSIGNED			
1  -  UPPERCASE_LETTER			'A', ...
2  -  LOWERCASE_LETTER			'a', ...
3  -  TITLECASE_LETTER		
4  -  MODIFIER_LETTER
5  -  OTHER_LETTER
6  -  NON_SPACING_MARK
7  -  ENCLOSING_MARK
8  -  COMBINING_SPACING_MARK
9  -  DECIMAL_DIGIT_NUMBER
10 -  LETTER_NUMBER
11 -  OTHER_NUMBER
12 -  SPACE_SEPARATOR
13 -  LINE_SEPARATOR
14 -  PARAGRAPH_SEPARATOR
15 -  CONTROL
16 -  FORMAT
18 -  PRIVATE_USE
19 -  SURROGATE
20 -  DASH_PUNCTUATION
21 -  START_PUNCTUATION
22 -  END_PUNCTUATION
23 -  CONNECTOR_PUNCTUATION
24 -  OTHER_PUNCTUATION
25 -  MATH_SYMBOL
26 -  CURRENCY_SYMBOL
27 -  MODIFIER_SYMBOL
28 -  OTHER_SYMBOL

Seeding the random number generator

You can set the seed of the Random class manually:

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

ie:

import java.util.*;
 
public class Main 
{  
   public static void main(String args[]) {
      Random r = new Random(10);
      for (int i=0; i<10; i++) {
         float f = r.nextFloat();
         System.out.println(f);
      }
   }
}

outputs:

0.73043025
0.44563425
0.25780278
0.41291267
0.059201956
0.67215943
0.2441172
0.36817038
0.818809
0.3567646

Running the app another time will yield the same pseudo-random numbers.

Downloading a remote file in Java

Create an instance of the URL class, open the TCP stream and read the data
from the inputstream provided by the URL object.
Following code demonstrates this:

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

prints the following to standard output:

<html>
<body>
<h1> HELLO WORLD! </h1>
</body>
</html>

Getting the file size of a URL file

You could use the HTTP header field content-length as follows:

import java.net.*;
import java.io.*;
 
public class Main {
   public static final void main(String[] args) {
      if (args.length != 1) {
         System.out.println("Usage: java Main <URL>");
         System.exit(1);
      }
 
      try {
         URL url = new URL(args[0]);
         URLConnection connection = url.openConnection();
         int size = connection.getContentLength();
         if (size > -1) {
            System.out.println("Content length is " + size);
         }
         else {
            System.out.println("Content length is not known");
         }
      }
      catch(Exception e) {
         System.err.println(e);
      }
   }
}

outputs with (java Main http://www.esus.com):

Content length is 43041

(I really should start trimming it down :)

Beware that this length does not include the embedded images or other embedded objects.

Also note that a lot of times, especially with dynamically generated pages, getContentLength returns -1 meaning it could not determine the size. In that case you should count the number of bytes as you download the URL through one of the InputStreams or Readers.

Simple example of a DatagramClient and DatagramServer

SenderGram.java:

/*
Program developed by Juleat K.R(Apech Computer education, fortkochi and 
Vinodvalittoor, Aptech Tirur. complaints and compliments send to 
julis_in@yahoo.com or vinwin01@yahoo.com
Thank you..

send datagram....................................... */
 
import java.net.*;
 
public class SenderGram
{
   public static void main(String ar[])
   {
      try {
         if (ar.length != 1) {
            System.err.println("Usage: java SenderGram <message>");
            System.exit(1);
         }
 
         InetAddress ia=InetAddress.getByName("LocalHost");
         int port=Integer.parseInt("2495");
 
         DatagramSocket ds=new DatagramSocket();
         byte buffer[]=ar[0].getBytes();
 
         DatagramPacket dp=new DatagramPacket(buffer,buffer.length,ia,port);
 
         ds.send(dp);
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}

ReceiverGram.java:

/* recieve datagram.................................... */
 
import java.net.*;
 
public class ReceiverGram
{
   public final static int BUFSIZE=20;
 
   public static void main(String ar[])
   {
      try {
         int port=Integer.parseInt("2495");
         DatagramSocket ds=new DatagramSocket(port);
         byte buffer[]=new byte[BUFSIZE];
 
         while (true) {
            DatagramPacket dp=new DatagramPacket(buffer,buffer.length);
            ds.receive(dp);
            String str=new String(dp.getData());
            System.out.println(str);
         } 
      }
      catch(Exception e) {
         System.err.println(e);
      }
   }
}