Find the maximum value of an array

Just set a variable max to the minimum value possible that your type can contain, for example max = Integer.MIN_VALUE; for an integer array and then loop through all the array’s elements reassigning max every time a higher value is found.

Main.java:

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 };
 
      System.out.println("Maximum: " + findMax(arr));
   }
 
   public static int findMax(int[] arr) {
      int max = Integer.MIN_VALUE;
      for (int i=0; i<arr.length; i++) {
         if (arr[i] > max) {
            max = arr[i];
         }
      }
      return max;
   }
}

Specifying a version for a Java package

You can specify specification and implementation information through the manifest file inside the jar file in which you package up your package. You can specify the following:

   Specification-Title
   Specification-Vendor
   Specification-Version
   Implementation-Title
   Implementation-Vendor
   Implementation-Version

Note that Specification-Version and Implementation-Version need to be encoded as numbers separated by dots, eg. 1.2.3 This is important to compare versions and to determine compatibility.

Following example shows you how to add versioning to a package of your own:

1) Start by writing your package:

mypackageMain.java:

package mypackage;
 
public class Main {
   public static void main(String args[]) {
      Package p = Package.getPackage("mypackage");
 
      System.out.println("For package: " + p.getName());
      System.out.println("  Specification-Title: " + 
         p.getSpecificationTitle());
      System.out.println("  Specification-Vendor: " + 
         p.getSpecificationVendor());
      System.out.println("  Specification-Version: " + 
         p.getSpecificationVersion());
      System.out.println("  Implementation-Title: " + 
         p.getImplementationTitle());
      System.out.println("  Implementation-Vendor: " + 
         p.getImplementationVendor());
      System.out.println("  Implementation-Version: " + 
         p.getImplementationVersion());
   }
}

2) write a manifest file:

Manifest.mf:

Manifest-Version: 1.0
Name: mypackage
Specification-Title: mypackage Specification
Specification-Vendor: Esus, Inc.
Specification-Version: 1.0
Implementation-Title: mypackage implementation
Implementation-Vendor: Esus, Inc.
Implementation-Version: 1.0
Main-Class: mypackage/Main
 

3) package everything up in a JAR file:

jar cfm Main.jar Manifest.mf mypackage/*.class

4) as we have included the Main-Class attribute in the manifest file, we can run it as follows:

java -jar Main.jar

outputs:

For package: mypackage
  Specification-Title: mypackage Specification
  Specification-Vendor: Esus, Inc.
  Specification-Version: 1.0
  Implementation-Title: mypackage implementation
  Implementation-Vendor: Esus, Inc.
  Implementation-Version: 1.0

Getting a list of all methods of a particular class through reflection

Call getDeclaredMethods on a Class object. There is another method called getMethods but this one returns only public methods.

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();
 
      Method []methods = c.getDeclaredMethods();
      for (int i=0; i<methods.length; i++) {
         System.out.println(methods[i]);
      }   
   }
}
 
class MyClass
{
   public MyClass() { }
   protected MyClass(float f) { }
 
   public String method1(int a) { return ""; }
   public float method2() { return (float) 1.2; }
   protected void method3() { }
   private double method4() { return 1.2; }
}

outputs:

public java.lang.String MyClass.method1(int)
public float MyClass.method2()
protected void MyClass.method3()
private double MyClass.method4()

Converting a String into a character array

The String class has a useful method doing just that:

public class TestProg
{
    public static void main(String args[])
    {
        String s = "Hello, world!";
        char array[] = s.toCharArray();
		
        for (int i=0; i<array.length; i++)
            System.out.print(array[i]);
        System.out.println();
    }
}

prints out: Hello, world!

List all Java threads that are running

Main.java:

public class Main
{
   public static void main(String []args) {
      // start up a couple thread belonging to some threadgroups
      ThreadGroup myGroup1 = new ThreadGroup("My ThreadGroup #1");
      new MyThread(myGroup1, "My Thread #1").start();
      new MyThread(myGroup1, "My Thread #2").start();
      ThreadGroup myGroup2 = new ThreadGroup(myGroup1, "My ThreadGroup #2");
      new MyThread(myGroup2, "My Thread #3").start();
 
      ThreadGroup root = Thread.currentThread().getThreadGroup().getParent();
      while (root.getParent() != null) {
         root = root.getParent();
      }
 
      printThreads_aux(root, 0);
   }
 
   public static void printThreads_aux(ThreadGroup group, int indent) {
      indentPrint(indent, group);
      // An application should use the activeCount method to 
      // get an estimate of how big the array should be
      Thread[] threads = new Thread[group.activeCount()*2];
      int nThreads = group.enumerate(threads, false);
      for (int i=0; i<nThreads; i++) {
         indentPrint(indent+3, threads[i]);
      }
 
      ThreadGroup[] groups = new ThreadGroup[group.activeGroupCount()*2];
      int nGroups = group.enumerate(groups, false);
      for (int i=0; i<nGroups; i++) {
         printThreads_aux(groups[i], indent+3);
      }
   }
 
   public static void indentPrint(int cols, Object value) {
      for (int i=0; i<cols; i++) {
         System.out.print(' ');
      }
      System.out.println(value);
   }
}
 
class MyThread extends Thread {
   public MyThread(ThreadGroup group, String name) {
      super(group, name);
 
      // keep this thread running as long as nondaemon main runs
      setDaemon(true);
   }
 
   public void run() {
      while (true);
   }
}    

outputs:

java.lang.ThreadGroup[name=system,maxpri=10]
   Thread[Reference Handler,10,system]
   Thread[Finalizer,8,system]
   Thread[Signal Dispatcher,10,system]
   Thread[CompileThread0,10,system]
   java.lang.ThreadGroup[name=main,maxpri=10]
      Thread[main,5,main]
      java.lang.ThreadGroup[name=My ThreadGroup #1,maxpri=10]
         Thread[My Thread #1,5,My ThreadGroup #1]
         Thread[My Thread #2,5,My ThreadGroup #1]
         java.lang.ThreadGroup[name=My ThreadGroup #2,maxpri=10]
            Thread[My Thread #3,5,My ThreadGroup #2]

Getting the remainder of a floating-point division

% returns the remainder of an integer division. If you want to know the remainder of a floating-point division, you can use the static method IEEEremainder of the Math class:

import java.math.*;
                           
public class Main 
{  
   public static void main(String args[]) throws Exception {
      System.out.println(Math.IEEEremainder(13.5, 3.0));
   }
}

outputs 1.5

Using BigIntegers

As opposed to int or long, respectively 32-bit and 64-bit long, a BigInteger allows you to store an arbitrary big non-decimal number. It can also deal with bits and has the proper methods for that (and, shiftLeft, …)

Here’s a simple example that creates a BigInteger.

Main.java:

import java.math.*;
import java.util.*;
 
public class Main {
   static Random r = new Random();
 
   public static void main(String args[]) {
      BigInteger bi1 = new BigInteger(createLongNumber());
      BigInteger bi2 = new BigInteger(createLongNumber());
 
      BigInteger total = bi1.add(bi2);
 
      System.out.println("  " + bi1);
      System.out.println("+ " + bi2);
      System.out.println("= " + total);
   }
 
   public static String createLongNumber() {
      StringBuffer total = new StringBuffer();
      for (int i=0; i<15; i++) {
         total.append(Math.abs(r.nextInt()));
      }
  
      return total.toString();
   }
}

outputs:

  730749745133351917535396776026235500621194210721376129288654848111179522
31934740694371855592481952346363130735653456760027617802679261977162139
+ 133287034081647952310168992582070726724673519674146599229384783108712083
237393757881612001996413136278288312261653333848082459044525261007117879
= 206362008594983144063708670184694276786792940746284212158250267919830035
469328498575983857588895088624651442997306790608110076847204522984280018

There are other ways to create a BigInteger. See the API for more information. For example, a BigInteger can be created containing a random number. We could have written the previous program using one of these constructors.

Reading an image from a URL

import java.awt.*;
import java.awt.image.*;
import java.util.*;
import java.io.*;
import java.net.*;
 
public class Toolbox
{
        private static Hashtable urlImagesCache = new Hashtable();
 
        public static Image getImage(URL url)
        {
                try
                {
                        Image cached = (Image)urlImagesCache.get(url);
                        if(cached != null) return cached;
 
                        InputStream in = url.openConnection().getInputStream();
                        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
                        byte buffer[] = new byte[1024*4];
                        int last_read_bytes = 0;
                        while((last_read_bytes = in.read(buffer)) != -1)
                        {
                                bytes.write(buffer,0,last_read_bytes);
                        }
 
                        Image image =  java.awt.Toolkit.getDefaultToolkit().createImage(bytes.toByteArray());
                        m.addImage(image,0);
                        try {
                            m.waitForAll();
                        }
                        catch (InterruptedException ex) {ex.printStackTrace();}
                        m.removeImage(image);
 
                        urlImagesCache.put(url,image);
 
                        return image;
                }
                catch (Exception ex)
                {
                        ex.printStackTrace();
                        return null;
                }
        }
}

Implementing an echo Server in Java

You can either use a TCP or UDP version. With UDP, you will have to use a DatagramSocket to create and listen to a port. With TCP (see example), you need to instantiate a ServerSocket. The echo port is 7. The server just creates a thread that loops indefinitely waiting for requests from clients and returns the exact same string the client contacted it with.

To test out following server, compile the source of EchoClient (see EchoClient) and run it using

java EchoClient localhost

EchoServer.java:

import java.util.*;
import java.net.*;
import java.io.*;
 
public class EchoServer {
   public static void main(String args[]) {
      EchoServerThread es = new EchoServerThread();
      es.start();
   }
}
 
class EchoServerThread extends Thread {
   private ServerSocket ss;
   private final int port = 7;
 
   public void run() {
      try {
         ss = new ServerSocket(port);
      } 
      catch(IOException e) {
         e.printStackTrace();
         return;
      }
 
      try { 
         while (true) {
            Socket clientSock = ss.accept();
            BufferedReader br = new BufferedReader(
                         new InputStreamReader(clientSock.getInputStream()));
            BufferedWriter bw = new BufferedWriter(
                         new OutputStreamWriter(clientSock.getOutputStream()));
  
            bw.write(br.readLine());
            clientSock.close();
         }
      }
      catch(IOException e) {
         e.printStackTrace();
      }
   }
}