Difference between the SHA and SHA-1 message digests

SHA stands for Secure Hash Algorithm. SHA-1 is more secure than SHA.

From the standard:

“SHA-1 is a technical revision of SHA (FIPS 180). A circular left shift operation has been added to the specifications in section 7, line b, page 9 of FIPS 180 and its equivalent in section 8, line c, page 10 of FIPS 180″

Encrypting/decrypting using RC6

RC6 (Ron’s Code) is a block cipher, and was submitted by RSA Laboratories as an attempt to become the AES (Advanced Encryption Standard). It didn’t win (Rijndael was selected). Check out this article for more information about AES. RC6 is described in this PDF.

Main.java:

import javax.crypto.spec.*;
import java.security.*;
import javax.crypto.*;
 
public class Main
{
   private static String algorithm = "RC6";
 
   public static void main(String []args) throws Exception {
      String toEncrypt = "The shorter you live, the longer you're dead!";
 
      System.out.println("Encrypting...");
      byte[] encrypted = encrypt(toEncrypt, "password");
 
      System.out.println("Decrypting...");
      String decrypted = decrypt(encrypted, "password");
    
      System.out.println("Decrypted text: " + decrypted);
   } 
 
   public static byte[] encrypt(String toEncrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance(algorithm);
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // create an instance of cipher
      Cipher cipher = Cipher.getInstance(algorithm);
 
      // initialize the cipher with the key
      cipher.init(Cipher.ENCRYPT_MODE, sk);
 
      // enctypt!
      byte[] encrypted = cipher.doFinal(toEncrypt.getBytes());
 
      return encrypted;
   }
 
   public static String decrypt(byte[] toDecrypt, String key) throws Exception {
      // create a binary key from the argument key (seed)
      SecureRandom sr = new SecureRandom(key.getBytes());
      KeyGenerator kg = KeyGenerator.getInstance(algorithm);
      kg.init(sr);
      SecretKey sk = kg.generateKey();
 
      // do the decryption with that key
      Cipher cipher = Cipher.getInstance(algorithm);
      cipher.init(Cipher.DECRYPT_MODE, sk);
      byte[] decrypted = cipher.doFinal(toDecrypt);
 
      return new String(decrypted);
   }
}

Using your own hashfunction in a HashTable

You can tweak the distribution in your Hashtable by overriding the hashCode method (defined in the Object class). Notice that in Hashtable.java, the hashCode is AND’ed with 0x7FFFFFFF (the maximum positive int, 2^31-1) to prevent storing at a negative array index.

Here’s an example:

Main.java:

import java.util.*;

public class Main extends Thread
{
   public static void main(String []args) throws Exception {
      Hashtable ht1 = new Hashtable();
      for (int i=0; i<10; i++) {
         ht1.put(new MyObject1(i), new Object());
      }
      output(ht1); 
 
      Hashtable ht2 = new Hashtable();
      for (int i=0; i<10; i++) {
         ht2.put(new MyObject2(i), new Object());
      }
      output(ht2);       
   }
 
   public static void output(Hashtable ht) {
      Enumeration keys = ht.keys();
      while (keys.hasMoreElements()) {
         System.out.print(keys.nextElement() + " ");
      }
      System.out.println();
   }
}
 
class MyObject1
{   
   int v;
 
   public MyObject1(int v) {
      this.v = v;
   }
 
   public String toString() {
      return "" + v;
   }
}
 
class MyObject2
{   
   int v;
 
   public MyObject2(int v) {
      this.v = v;
   }
 
   public String toString() {
      return "" + v;
   }
 
   public int hashCode() {
      return v;
   }
}

outputs:

2 9 5 4 0 7 1 6 8 3
9 8 7 6 5 4 3 2 1 0

Generating a list of all available timezones

If you invoke the static method getAvailableIDs on the class TimeZone, you’ll get a list of time zone IDs. With such an ID, you can get the TimeZone object that encapsulates all its info (its display name, the difference in milliseconds with GMT and whether or not that Time Zone utilizes a daylight savings time).

Main.java:

import java.util.*;
import java.io.*;
  
public class Main
{
   public static void main(String []args) {
      String[] sarr = TimeZone.getAvailableIDs();
 
      for (int i=0; i<sarr.length; i++) {
         TimeZone tz = TimeZone.getTimeZone(sarr[i]);
         formatInColumn(tz.getDisplayName(false, TimeZone.SHORT), 11);
         formatInColumn("t"+tz.getID(), 30);
         formatInColumn("t"+tz.getRawOffset(), 10);
         formatInColumn("t"+tz.useDaylightTime(), 10);
         System.out.println();
      }
   }
 
   public static void formatInColumn(String s, int col) {
      if (s.length() < col) {
         System.out.print(s);
      }
      else {
         System.out.print(s.substring(0, col));
         return;
      }
 
      for (int i=col; i>s.length(); i--) {
         System.out.print(" ");
      }
   }
}

outputs in four columns: SHORT displayname, ID, difference in ms. with GMT and whether or not it uses
a daylight savings time.

GMT-11:00  	Pacific/Niue                 	-39600000	false    
GMT-11:00  	Pacific/Apia                 	-39600000	false    
GMT-11:00  	MIT                          	-39600000	false    
GMT-11:00  	Pacific/Pago_Pago            	-39600000	false    
GMT-10:00  	Pacific/Tahiti               	-36000000	false    
GMT-10:00  	Pacific/Fakaofo              	-36000000	false    
HST        	Pacific/Honolulu             	-36000000	false    
HST        	HST                          	-36000000	false    
GMT-10:00  	America/Adak                 	-36000000	true     
GMT-10:00  	Pacific/Rarotonga            	-36000000	true     
GMT-09:30  	Pacific/Marquesas            	-34200000	false    
GMT-09:00  	Pacific/Gambier              	-32400000	false    
AKST       	America/Anchorage            	-32400000	true     
AKST       	AST                          	-32400000	true     
GMT-08:30  	Pacific/Pitcairn             	-30600000	false    
GMT-08:00  	America/Vancouver            	-28800000	true     
GMT-08:00  	America/Tijuana              	-28800000	true     
PST        	America/Los_Angeles          	-28800000	true     
PST        	PST                          	-28800000	true     
GMT-07:00  	America/Dawson_Creek         	-25200000	false    
MST        	America/Phoenix              	-25200000	false    
MST        	PNT                          	-25200000	false    
GMT-07:00  	America/Edmonton             	-25200000	true     
GMT-07:00  	America/Mazatlan             	-25200000	true     
MST        	America/Denver               	-25200000	true     
MST        	MST                          	-25200000	true     
GMT-06:00  	America/Belize               	-21600000	false    
GMT-06:00  	America/Regina               	-21600000	false    
GMT-06:00  	Pacific/Galapagos            	-21600000	false    
GMT-06:00  	America/Guatemala            	-21600000	false    
GMT-06:00  	America/Tegucigalpa          	-21600000	false    
GMT-06:00  	America/El_Salvador          	-21600000	false    
GMT-06:00  	America/Costa_Rica           	-21600000	false    
GMT-06:00  	America/Winnipeg             	-21600000	true     
GMT-06:00  	Pacific/Easter               	-21600000	true     
GMT-06:00  	America/Mexico_City          	-21600000	true     
CST        	America/Chicago              	-21600000	true     
CST        	CST                          	-21600000	true     
GMT-05:00  	America/Porto_Acre           	-18000000	false    
GMT-05:00  	America/Bogota               	-18000000	false    
GMT-05:00  	America/Guayaquil            	-18000000	false    
GMT-05:00  	America/Jamaica              	-18000000	false    
GMT-05:00  	America/Cayman               	-18000000	false    
GMT-05:00  	America/Managua              	-18000000	false    
GMT-05:00  	America/Panama               	-18000000	false    
GMT-05:00  	America/Lima                 	-18000000	false    
EST        	America/Indianapolis         	-18000000	false    
EST        	IET                          	-18000000	false    
GMT-05:00  	America/Nassau               	-18000000	true     
GMT-05:00  	America/Montreal             	-18000000	true     
GMT-05:00  	America/Havana               	-18000000	true     
GMT-05:00  	America/Port-au-Prince       	-18000000	true     
GMT-05:00  	America/Grand_Turk           	-18000000	true     
EST        	America/New_York             	-18000000	true     
EST        	EST                          	-18000000	true     
GMT-04:00  	America/Antigua              	-14400000	false    
GMT-04:00  	America/Anguilla             	-14400000	false    
GMT-04:00  	America/Curacao              	-14400000	false    
GMT-04:00  	America/Aruba                	-14400000	false    
GMT-04:00  	America/Barbados             	-14400000	false    
GMT-04:00  	America/La_Paz               	-14400000	false    
GMT-04:00  	America/Manaus               	-14400000	false    
GMT-04:00  	America/Dominica             	-14400000	false    
GMT-04:00  	America/Santo_Domingo        	-14400000	false    
GMT-04:00  	America/Grenada              	-14400000	false    
GMT-04:00  	America/Guadeloupe           	-14400000	false    
GMT-04:00  	America/Guyana               	-14400000	false    
GMT-04:00  	America/St_Kitts             	-14400000	false    
GMT-04:00  	America/St_Lucia             	-14400000	false    
GMT-04:00  	America/Martinique           	-14400000	false    
GMT-04:00  	America/Montserrat           	-14400000	false    
GMT-04:00  	America/Puerto_Rico          	-14400000	false    
GMT-04:00  	PRT                          	-14400000	false    
GMT-04:00  	America/Port_of_Spain        	-14400000	false    
GMT-04:00  	America/St_Vincent           	-14400000	false    
GMT-04:00  	America/Tortola              	-14400000	false    
GMT-04:00  	America/St_Thomas            	-14400000	false    
GMT-04:00  	America/Caracas              	-14400000	false    
GMT-04:00  	Antarctica/Palmer            	-14400000	true     
GMT-04:00  	Atlantic/Bermuda             	-14400000	true     
GMT-04:00  	America/Cuiaba               	-14400000	true     
AST        	America/Halifax              	-14400000	true     
GMT-04:00  	Atlantic/Stanley             	-14400000	true     
GMT-04:00  	America/Thule                	-14400000	true     
GMT-04:00  	America/Asuncion             	-14400000	true     
GMT-04:00  	America/Santiago             	-14400000	true     
NST        	America/St_Johns             	-12600000	true     
NST        	CNT                          	-12600000	true     
GMT-03:00  	America/Fortaleza            	-10800000	false    
GMT-03:00  	America/Cayenne              	-10800000	false    
GMT-03:00  	America/Paramaribo           	-10800000	false    
GMT-03:00  	America/Montevideo           	-10800000	false    
GMT-03:00  	America/Buenos_Aires         	-10800000	false    
GMT-03:00  	AGT                          	-10800000	false    
GMT-03:00  	America/Godthab              	-10800000	true     
GMT-03:00  	America/Miquelon             	-10800000	true     
GMT-03:00  	America/Sao_Paulo            	-10800000	true     
GMT-03:00  	BET                          	-10800000	true     
GMT-02:00  	America/Noronha              	-7200000 	false    
GMT-02:00  	Atlantic/South_Georgia       	-7200000 	false    
GMT-01:00  	Atlantic/Jan_Mayen           	-3600000 	false    
GMT-01:00  	Atlantic/Cape_Verde          	-3600000 	false    
GMT-01:00  	America/Scoresbysund         	-3600000 	true     
GMT-01:00  	Atlantic/Azores              	-3600000 	true     
GMT+00:00  	Africa/Ouagadougou           	0        	false    
GMT+00:00  	Africa/Abidjan               	0        	false    
GMT+00:00  	Africa/Accra                 	0        	false    
GMT+00:00  	Africa/Banjul                	0        	false    
GMT+00:00  	Africa/Conakry               	0        	false    
GMT+00:00  	Africa/Bissau                	0        	false    
GMT+00:00  	Atlantic/Reykjavik           	0        	false    
GMT+00:00  	Africa/Monrovia              	0        	false    
GMT        	Africa/Casablanca            	0        	false    
GMT+00:00  	Africa/Timbuktu              	0        	false    
GMT+00:00  	Africa/Nouakchott            	0        	false    
GMT+00:00  	Atlantic/St_Helena           	0        	false    
GMT+00:00  	Africa/Freetown              	0        	false    
GMT+00:00  	Africa/Dakar                 	0        	false    
GMT+00:00  	Africa/Sao_Tome              	0        	false    
GMT+00:00  	Africa/Lome                  	0        	false    
GMT        	GMT                          	0        	false    
GMT+00:00  	UTC                          	0        	false    
GMT+00:00  	Atlantic/Faeroe              	0        	true     
GMT+00:00  	Atlantic/Canary              	0        	true     
GMT+00:00  	Europe/Dublin                	0        	true     
GMT+00:00  	Europe/Lisbon                	0        	true     
GMT+00:00  	Europe/London                	0        	true     
GMT+01:00  	Africa/Luanda                	3600000  	false    
GMT+01:00  	Africa/Porto-Novo            	3600000  	false    
GMT+01:00  	Africa/Bangui                	3600000  	false    
GMT+01:00  	Africa/Kinshasa              	3600000  	false    
GMT+01:00  	Africa/Douala                	3600000  	false    
GMT+01:00  	Africa/Libreville            	3600000  	false    
GMT+01:00  	Africa/Malabo                	3600000  	false    
GMT+01:00  	Africa/Niamey                	3600000  	false    
GMT+01:00  	Africa/Lagos                 	3600000  	false    
GMT+01:00  	Africa/Ndjamena              	3600000  	false    
GMT+01:00  	Africa/Tunis                 	3600000  	false    
GMT+01:00  	Africa/Algiers               	3600000  	false    
GMT+01:00  	Europe/Andorra               	3600000  	true     
GMT+01:00  	Europe/Tirane                	3600000  	true     
GMT+01:00  	Europe/Vienna                	3600000  	true     
GMT+01:00  	Europe/Brussels              	3600000  	true     
GMT+01:00  	Europe/Zurich                	3600000  	true     
GMT+01:00  	Europe/Prague                	3600000  	true     
GMT+01:00  	Europe/Berlin                	3600000  	true     
GMT+01:00  	Europe/Copenhagen            	3600000  	true     
GMT+01:00  	Europe/Madrid                	3600000  	true     
GMT+01:00  	Europe/Gibraltar             	3600000  	true     
GMT+01:00  	Europe/Budapest              	3600000  	true     
GMT+01:00  	Europe/Rome                  	3600000  	true     
GMT+01:00  	Europe/Vaduz                 	3600000  	true     
GMT+01:00  	Europe/Luxembourg            	3600000  	true     
GMT+01:00  	Africa/Tripoli               	3600000  	true     
GMT+01:00  	Europe/Monaco                	3600000  	true     
GMT+01:00  	Europe/Malta                 	3600000  	true     
GMT+01:00  	Africa/Windhoek              	3600000  	true     
GMT+01:00  	Europe/Amsterdam             	3600000  	true     
GMT+01:00  	Europe/Oslo                  	3600000  	true     
GMT+01:00  	Europe/Warsaw                	3600000  	true     
GMT+01:00  	Europe/Stockholm             	3600000  	true     
GMT+01:00  	Europe/Belgrade              	3600000  	true     
CET        	Europe/Paris                 	3600000  	true     
CET        	ECT                          	3600000  	true     
GMT+02:00  	Africa/Bujumbura             	7200000  	false    
GMT+02:00  	Africa/Gaborone              	7200000  	false    
GMT+02:00  	Africa/Lubumbashi            	7200000  	false    
GMT+02:00  	Africa/Maseru                	7200000  	false    
GMT+02:00  	Africa/Blantyre              	7200000  	false    
GMT+02:00  	Africa/Maputo                	7200000  	false    
GMT+02:00  	Africa/Kigali                	7200000  	false    
GMT+02:00  	Africa/Khartoum              	7200000  	false    
GMT+02:00  	Africa/Mbabane               	7200000  	false    
GMT+02:00  	Africa/Lusaka                	7200000  	false    
GMT+02:00  	Africa/Harare                	7200000  	false    
GMT+02:00  	CAT                          	7200000  	false    
GMT+02:00  	Africa/Johannesburg          	7200000  	false    
GMT+02:00  	Europe/Sofia                 	7200000  	true     
GMT+02:00  	Europe/Minsk                 	7200000  	true     
GMT+02:00  	Asia/Nicosia                 	7200000  	true     
GMT+02:00  	Europe/Tallinn               	7200000  	true     
GMT+02:00  	Africa/Cairo                 	7200000  	true     
GMT+02:00  	ART                          	7200000  	true     
GMT+02:00  	Europe/Helsinki              	7200000  	true     
GMT+02:00  	Europe/Athens                	7200000  	true     
IST        	Asia/Jerusalem               	7200000  	true     
GMT+02:00  	Asia/Amman                   	7200000  	true     
GMT+02:00  	Asia/Beirut                  	7200000  	true     
GMT+02:00  	Europe/Vilnius               	7200000  	true     
GMT+02:00  	Europe/Riga                  	7200000  	true     
GMT+02:00  	Europe/Chisinau              	7200000  	true     
EET        	Europe/Bucharest             	7200000  	true     
GMT+02:00  	Europe/Kaliningrad           	7200000  	true     
GMT+02:00  	Asia/Damascus                	7200000  	true     
GMT+02:00  	Europe/Kiev                  	7200000  	true     
GMT+02:00  	Europe/Istanbul              	7200000  	true     
GMT+02:00  	EET                          	7200000  	true     
GMT+03:00  	Asia/Bahrain                 	10800000 	false    
GMT+03:00  	Africa/Djibouti              	10800000 	false    
GMT+03:00  	Africa/Asmera                	10800000 	false    
GMT+03:00  	Africa/Addis_Ababa           	10800000 	false    
GMT+03:00  	EAT                          	10800000 	false    
GMT+03:00  	Africa/Nairobi               	10800000 	false    
GMT+03:00  	Indian/Comoro                	10800000 	false    
GMT+03:00  	Asia/Kuwait                  	10800000 	false    
GMT+03:00  	Indian/Antananarivo          	10800000 	false    
GMT+03:00  	Asia/Qatar                   	10800000 	false    
GMT+03:00  	Africa/Mogadishu             	10800000 	false    
GMT+03:00  	Africa/Dar_es_Salaam         	10800000 	false    
GMT+03:00  	Africa/Kampala               	10800000 	false    
GMT+03:00  	Asia/Aden                    	10800000 	false    
GMT+03:00  	Indian/Mayotte               	10800000 	false    
GMT+03:00  	Asia/Riyadh                  	10800000 	false    
GMT+03:00  	Asia/Baghdad                 	10800000 	true     
GMT+03:00  	Europe/Simferopol            	10800000 	true     
GMT+03:00  	Europe/Moscow                	10800000 	true     
GMT+03:30  	Asia/Tehran                  	12600000 	true     
GMT+03:30  	MET                          	12600000 	true     
GMT+04:00  	Asia/Dubai                   	14400000 	false    
GMT+04:00  	Indian/Mauritius             	14400000 	false    
GMT+04:00  	Asia/Muscat                  	14400000 	false    
GMT+04:00  	Indian/Reunion               	14400000 	false    
GMT+04:00  	Indian/Mahe                  	14400000 	false    
GMT+04:00  	Asia/Yerevan                 	14400000 	false    
GMT+04:00  	NET                          	14400000 	false    
GMT+04:00  	Asia/Baku                    	14400000 	true     
GMT+04:00  	Asia/Aqtau                   	14400000 	true     
GMT+04:00  	Europe/Samara                	14400000 	true     
GMT+04:30  	Asia/Kabul                   	16200000 	false    
GMT+05:00  	Indian/Kerguelen             	18000000 	false    
GMT+05:00  	Asia/Tbilisi                 	18000000 	false    
GMT+05:00  	Indian/Chagos                	18000000 	false    
GMT+05:00  	Indian/Maldives              	18000000 	false    
GMT+05:00  	Asia/Dushanbe                	18000000 	false    
GMT+05:00  	Asia/Ashkhabad               	18000000 	false    
GMT+05:00  	Asia/Tashkent                	18000000 	false    
GMT+05:00  	Asia/Karachi                 	18000000 	false    
GMT+05:00  	PLT                          	18000000 	false    
GMT+05:00  	Asia/Bishkek                 	18000000 	true     
GMT+05:00  	Asia/Aqtobe                  	18000000 	true     
GMT+05:00  	Asia/Yekaterinburg           	18000000 	true     
GMT+05:30  	Asia/Calcutta                	19800000 	false    
GMT+05:30  	IST                          	19800000 	false    
GMT+05:45  	Asia/Katmandu                	20700000 	false    
GMT+06:00  	Antarctica/Mawson            	21600000 	false    
GMT+06:00  	Asia/Thimbu                  	21600000 	false    
GMT+06:00  	Asia/Colombo                 	21600000 	false    
GMT+06:00  	Asia/Dacca                   	21600000 	false    
GMT+06:00  	BST                          	21600000 	false    
GMT+06:00  	Asia/Alma-Ata                	21600000 	true     
GMT+06:00  	Asia/Novosibirsk             	21600000 	true     
GMT+06:30  	Indian/Cocos                 	23400000 	false    
GMT+06:30  	Asia/Rangoon                 	23400000 	false    
GMT+07:00  	Indian/Christmas             	25200000 	false    
GMT+07:00  	Asia/Jakarta                 	25200000 	false    
GMT+07:00  	Asia/Phnom_Penh              	25200000 	false    
GMT+07:00  	Asia/Vientiane               	25200000 	false    
GMT+07:00  	Asia/Saigon                  	25200000 	false    
GMT+07:00  	VST                          	25200000 	false    
GMT+07:00  	Asia/Bangkok                 	25200000 	false    
GMT+07:00  	Asia/Krasnoyarsk             	25200000 	true     
GMT+08:00  	Antarctica/Casey             	28800000 	false    
GMT+08:00  	Australia/Perth              	28800000 	false    
GMT+08:00  	Asia/Brunei                  	28800000 	false    
GMT+08:00  	Asia/Hong_Kong               	28800000 	false    
GMT+08:00  	Asia/Ujung_Pandang           	28800000 	false    
GMT+08:00  	Asia/Ishigaki                	28800000 	false    
GMT+08:00  	Asia/Macao                   	28800000 	false    
GMT+08:00  	Asia/Kuala_Lumpur            	28800000 	false    
GMT+08:00  	Asia/Manila                  	28800000 	false    
GMT+08:00  	Asia/Singapore               	28800000 	false    
GMT+08:00  	Asia/Taipei                  	28800000 	false    
CST        	Asia/Shanghai                	28800000 	false    
CST        	CTT                          	28800000 	false    
GMT+08:00  	Asia/Ulan_Bator              	28800000 	true     
GMT+08:00  	Asia/Irkutsk                 	28800000 	true     
GMT+09:00  	Asia/Jayapura                	32400000 	false    
GMT+09:00  	Asia/Pyongyang               	32400000 	false    
GMT+09:00  	Asia/Seoul                   	32400000 	false    
GMT+09:00  	Pacific/Palau                	32400000 	false    
JST        	Asia/Tokyo                   	32400000 	false    
JST        	JST                          	32400000 	false    
GMT+09:00  	Asia/Yakutsk                 	32400000 	true     
GMT+09:30  	Australia/Darwin             	34200000 	false    
GMT+09:30  	ACT                          	34200000 	false    
GMT+09:30  	Australia/Adelaide           	34200000 	true     
GMT+10:00  	Antarctica/DumontDUrville    	36000000 	false    
GMT+10:00  	Pacific/Truk                 	36000000 	false    
GMT+10:00  	Pacific/Guam                 	36000000 	false    
GMT+10:00  	Pacific/Saipan               	36000000 	false    
GMT+10:00  	Pacific/Port_Moresby         	36000000 	false    
GMT+10:00  	Australia/Brisbane           	36000000 	false    
GMT+10:00  	Asia/Vladivostok             	36000000 	true     
GMT+10:00  	Australia/Sydney             	36000000 	true     
GMT+10:00  	AET                          	36000000 	true     
GMT+10:30  	Australia/Lord_Howe          	37800000 	true     
GMT+11:00  	Pacific/Ponape               	39600000 	false    
GMT+11:00  	Pacific/Efate                	39600000 	false    
GMT+11:00  	Pacific/Guadalcanal          	39600000 	false    
GMT+11:00  	SST                          	39600000 	false    
GMT+11:00  	Pacific/Noumea               	39600000 	true     
GMT+11:00  	Asia/Magadan                 	39600000 	true     
GMT+11:30  	Pacific/Norfolk              	41400000 	false    
GMT+12:00  	Pacific/Kosrae               	43200000 	false    
GMT+12:00  	Pacific/Tarawa               	43200000 	false    
GMT+12:00  	Pacific/Majuro               	43200000 	false    
GMT+12:00  	Pacific/Nauru                	43200000 	false    
GMT+12:00  	Pacific/Funafuti             	43200000 	false    
GMT+12:00  	Pacific/Wake                 	43200000 	false    
GMT+12:00  	Pacific/Wallis               	43200000 	false    
GMT+12:00  	Pacific/Fiji                 	43200000 	false    
GMT+12:00  	Antarctica/McMurdo           	43200000 	true     
GMT+12:00  	Asia/Kamchatka               	43200000 	true     
GMT+12:00  	Pacific/Auckland             	43200000 	true     
GMT+12:00  	NST                          	43200000 	true     
GMT+12:45  	Pacific/Chatham              	45900000 	true     
GMT+13:00  	Pacific/Enderbury            	46800000 	false    
GMT+13:00  	Pacific/Tongatapu            	46800000 	false    
GMT+13:00  	Asia/Anadyr                  	46800000 	true     
GMT+14:00  	Pacific/Kiritimati           	50400000 	false    

Using a java.util.logging FileHandler

With a FileHandler, you can log to one or more files. Here is a simple example that writes to one log file in the current directory. The default formatter for FileHandler is XMLFormatter, so every log entry is an XML segment.

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) throws IOException {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      FileHandler fh = new FileHandler("Main.log");
 
      fh.setLevel(Level.ALL);
      logger.addHandler(fh);
 
      for (int i=0; i<1000; i++) {
         logger.severe("log message #1");
         logger.warning("log message #2");
         logger.info("log message #3");
         logger.config("log message #4");
         logger.fine("log message #5");
      }
   }
}

You can specify the maximum size of a log file along with a pattern that will be used to dynamically determine the name of the log file.

For example:

Main.java:

import java.util.logging.*;
import java.io.*;
 
public class Main
{
   public static void main(String argv[]) throws IOException {
      Logger logger = Logger.getLogger("main");
      logger.setUseParentHandlers(false);
      logger.setLevel(Level.ALL);
 
      FileHandler fh = new FileHandler("%t/logfiles/Main.%g.log", 10000, 10);
 
      fh.setLevel(Level.ALL);
      logger.addHandler(fh);
 
      for (int i=0; i<1000; i++) {
         logger.severe("log message #1");
         logger.warning("log message #2");
         logger.info("log message #3");
         logger.config("log message #4");
         logger.fine("log message #5");
      }
   }
}

The pattern %t/logfiles/Main.%g.log tells the FileHandler to write to the subdirectory logfiles in the temporary directory (%t). It will use a maximum of 10 files with a limit of approx 10K. To determine the the temporary directory on your system, FileHandler will look at the property java.io.tmpdir. (Find out with System.out.println(System.getProperty(“java.io.tmpdir”));)

This is the directory listing on my system after running the example:

C:Documents and SettingsAdministratorLocal SettingsTemplogfiles>dir
 Volume in drive C has no label.
 Volume Serial Number is E4D8-7443

 Directory of C:Documents and SettingsAdministratorLocal SettingsTemplogfiles

01/20/2002  03:32p      <DIR>          .
01/20/2002  03:32p      <DIR>          ..
01/20/2002  03:32p               5,970 Main.0.log
01/20/2002  03:32p                   0 Main.0.log.lck
01/20/2002  03:32p              10,234 Main.1.log
01/20/2002  03:32p              10,231 Main.2.log
01/20/2002  03:32p              10,234 Main.3.log
01/20/2002  03:32p              10,234 Main.4.log
01/20/2002  03:32p              10,233 Main.5.log
01/20/2002  03:32p              10,234 Main.6.log
01/20/2002  03:32p              10,231 Main.7.log
01/20/2002  03:32p              10,234 Main.8.log
01/20/2002  03:32p              10,234 Main.9.log
              11 File(s)         98,069 bytes
               2 Dir(s)   6,371,955,200 bytes free

For more information about the patterns that can be used, check here:
http://java.sun.com/j2se/1.4/docs/api/java/util/logging/FileHandler.html

Generating a random double between x and y

You can use the formula:

   lowerbound + ((upperbound - lowerbound) * randomdouble)

To get a random double number, instantiate a Random object and call the method nextDouble which returns a pseudo-random float between 0 and 1.

Main.java:

import java.util.*;
  
public class Main {   
   static Random r = new Random();
 
   public static void main(String[] args) throws Exception {
  
      for (int i=0; i<10; i++) 
         System.out.println(getRandomDouble(-10, 15));
   }
 
   public static double getRandomDouble(double min, double max) {
      return min + (r.nextDouble() * (max - min));
   }
}

outputs:

-8.27577613957078
7.8901509288709875
9.692495759967983
-6.980121699011098
6.601079261644884
-9.471052403758076
4.7473270087607045
12.034529118113905
9.762114133902635
-9.449081692716046

Creating a checksum of an InputStream

Use the class CheckedInputStream. This class is a FilterInputStream and calculates a checksum as data passes through it. When creating it, pass it an existing inputstream and an instance of a class that implements the Checksum interface. In the standard API, there are two such classes available: java.util.zip.Adler32 and java.util.zip.CRC32.
The checksum value can be retrieved by invoking getChecksum().getValue().

This method calculates the checksum of a file.

Main.java:

import java.util.zip.*;
import java.io.*;
 
public class Main {
   public static void main(String args[]) throws Exception {
      if (args.length != 1) {
         System.err.println("Usage: java Main <file.txt>");
         System.exit(1);
      }
 
      File file = new File(args[0]);
      CheckedInputStream cis = new CheckedInputStream(new FileInputStream(file), 
                                                      new CRC32());
      byte []buffer = new byte[1024];
      while (cis.read(buffer) > 0) { }
      cis.close();
 
      System.out.println("Checksum of file " + args[0] + " = " 
                            + cis.getChecksum().getValue());
    }
}

Setting the top-left icon of a JDialog

You can’t directly set the top-left icon of a JDialog. It inherits its icon from the owner JFrame. What you could do is pass a dummy JFrame as the owner when you create the JDialog. This example shows you:

import javax.swing.event.*; 
import java.awt.event.*; 
import javax.swing.*; 
import java.awt.*; 
 
public class Main extends JFrame 
{ 
   private AboutBox about; 
   
   public Main() { 
      super("Main test"); 
 
      setSize(450, 350); 
 
      ImageIcon icon = new ImageIcon("first.gif"); 
      setIconImage(icon.getImage()); 
    
      JButton button = new JButton("Open dialog");
      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            about = new AboutBox(new JFrame()); 
            about.setVisible(true);
         }
      });
 
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(0);
         }
      });
   } 
 
   public static void main(String []args) {
      Main main = new Main();
      main.setVisible(true);
   }
}
 
class AboutBox extends JDialog 
{ 
   public AboutBox(JFrame owner) { 
      super(owner, "About Swing Menu", true); 
   
      ImageIcon icon = new ImageIcon("second.gif"); 
      owner.setIconImage(icon.getImage()); 

      JButton button = new JButton("Close");
      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            dispose();
         }
      });
 
      setSize(250, 150); 
   }
}

Center a JFrame on the screen

Use this little code snippet:

   Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
   int x = (int) ((d.getWidth() - getWidth()) / 2);
   int y = (int) ((d.getHeight() - getHeight()) / 2);
   setLocation(x, y);

Applied:

import java.awt.event.*;
import javax.swing.*;
import java.awt.*;
   
public class Main extends JFrame
{ 
   public Main() {
      final JButton button = new JButton("Center me!");
      getContentPane().setLayout(new FlowLayout());
      getContentPane().add(button);
      button.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            Dimension d = Toolkit.getDefaultToolkit().getScreenSize();
            int x = (int) ((d.getWidth() - getWidth()) / 2);
            int y = (int) ((d.getHeight() - getHeight()) / 2);
            setLocation(x, y);
         }
      });
  
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });      
   
      setSize(new Dimension(200, 200));
   } 
 
   public static void main(String[] args) throws Exception {
      Main main = new Main();
      main.setVisible(true);
   }
}