Thursday, December 20, 2007

Java Code For Reading and Writing a Properties File

// Read properties file.
Properties properties = new Properties();
try {
properties.load(new FileInputStream("filename.properties"));
} catch (IOException e) {
}

// Write properties file.
try {
properties.store(new FileOutputStream("filename.properties"), null);
} catch (IOException e) {
}
Here is an example of the contents of a properties file: # a comment
! a comment

a = a string
b = a string with escape sequences \t \n \r \\ \" \' \ (space) \u0123
c = a string with a continuation line \
continuation line
d.e.f = another string

Tuesday, December 18, 2007

Java Code For Getting and Setting Properties

String string = properties.getProperty("a.b");
properties.setProperty("a.b", "new value");

Saturday, November 10, 2007

Java Code For Creating a Set

A set is a collection that holds unique values. Adding a value that's already in the set has no effect. // Create the set

Set set = new HashSet();

// Add elements to the set
set.add("a");
set.add("b");
set.add("c");

// Remove elements from the set
set.remove("c");

// Get number of elements in set
int size = set.size(); // 2

// Adding an element that already exists in the set has no effect
set.add("a");
size = set.size(); // 2

// Determining if an element is in the set
boolean b = set.contains("a"); // true
b = set.contains("c"); // false

// Iterating over the elements in the set
Iterator it = set.iterator();
while (it.hasNext()) {
// Get element
Object element = it.next();
}

// Create an array containing the elements in the set (in this case a String array)
String[] array = (String[])set.toArray(new String[set.size()]);

Thursday, September 6, 2007

Java Code For Comparing Dates

Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);

Calendar newyears = new GregorianCalendar(1999, Calendar.JANUARY, 1);

// Determine which is earlier
boolean b = xmas.after(newyears); // false
b = xmas.before(newyears); // true


// Get difference in milliseconds
long diffMillis = newyears.getTimeInMillis()-xmas.getTimeInMillis();

// Get difference in seconds
long diffSecs = diffMillis/(1000); // 604800

// Get difference in minutes
long diffMins = diffMillis/(60*1000); // 10080

// Get difference in hours
long diffHours = diffMillis/(60*60*1000); // 168

// Get difference in days
long diffDays = diffMillis/(24*60*60*1000); // 7

Saturday, September 1, 2007

Java Code For Getting the Current Date : java.util.Date

Calendar cal = new GregorianCalendar();

// Get the components of the date
int era = cal.get(Calendar.ERA); // 0=BC, 1=AD
int year = cal.get(Calendar.YEAR); // 2002
int month = cal.get(Calendar.MONTH); // 0=Jan, 1=Feb, ...
int day = cal.get(Calendar.DAY_OF_MONTH); // 1...
int dayOfWeek = cal.get(Calendar.DAY_OF_WEEK); // 1=Sunday, 2=Monday, ...

Java Code For Creating a Date Object for a Particular Date

Calendar xmas = new GregorianCalendar(1998, Calendar.DECEMBER, 25);
Date date = xmas.getTime();

Java Code to Determine If a Year Is a Leap Year : java.util.Date

GregorianCalendar cal = new GregorianCalendar();
boolean b = cal.isLeapYear(1998); // false
b = cal.isLeapYear(2000); // true
b = cal.isLeapYear(0); // true

Saturday, August 25, 2007

Java Code to Compare Arrays :java.util.Arrays

// null arrays are equal
boolean[] bArr1 = null;
boolean[] bArr2 = null;
boolean b = Arrays.equals(bArr1, bArr2); // true

// Compare two boolean arrays
bArr1 = new boolean[]{true, false};
bArr2 = new boolean[]{true, false};
b = Arrays.equals(bArr1, null); // false
b = Arrays.equals(bArr1, bArr2); // true

// There are equals() methods for all eight primitive types
b = Arrays.equals(new byte[]{0}, new byte[]{0}); // true
b = Arrays.equals(new char[]{'a'}, new char[]{'a'}); // true
b = Arrays.equals(new short[]{0}, new short[]{0}); // true
b = Arrays.equals(new int[]{0}, new int[]{0}); // true
b = Arrays.equals(new long[]{0L}, new long[]{0L}); // true
b = Arrays.equals(new float[]{0F}, new float[]{0F}); // true
b = Arrays.equals(new double[]{0D}, new double[]{0D}); // true

// When comparing Object arrays, null elements are equal.
// If the elements are not null, Object.equals() is used.
b = Arrays.equals(new String[]{"a"}, new String[]{"a"}); // true
b = Arrays.equals(new String[]{null}, new String[]{null}); // true
b = Arrays.equals(new String[]{"a"}, new String[]{null}); // false

Saturday, August 18, 2007

Java Code to Convert a Collection to an Array : java.util.Arrays

// Create an array containing the elements in a list
Object[] objectArray = list.toArray();
MyClass[] array = (MyClass[])list.toArray(new MyClass[list.size()]);

// Create an array containing the elements in a set
objectArray = set.toArray();
array = (MyClass[])set.toArray(new MyClass[set.size()]);

// Create an array containing the keys in a map
objectArray = map.keySet().toArray();
array = (MyClass[])map.keySet().toArray(new MyClass[set.size()]);

// Create an array containing the values in a map
objectArray = map.values().toArray();
array = (MyClass[])map.values().toArray(new MyClass[set.size()]);
Related Examples

Saturday, August 11, 2007

Java Code to Shuffle the Elements of a List or Array : java.util.Arrays

Use Collections.shuffle() to randomly reorder the elements in a list.
// Create a list
List list = new ArrayList();

// Add elements to list

// Shuffle the elements in the list
Collections.shuffle(list);

// Create an array
String[] array = new String[]{"a", "b", "c"};

// Shuffle the elements in the array
Collections.shuffle(Arrays.asList(array));

Saturday, August 4, 2007

Java Code to Compare Arrays : java.util.Arrays

// null arrays are equal
boolean[] bArr1 = null;
boolean[] bArr2 = null;
boolean b = Arrays.equals(bArr1, bArr2); // true

// Compare two boolean arrays
bArr1 = new boolean[]{true, false};
bArr2 = new boolean[]{true, false};
b = Arrays.equals(bArr1, null); // false
b = Arrays.equals(bArr1, bArr2); // true

// There are equals() methods for all eight primitive types
b = Arrays.equals(new byte[]{0}, new byte[]{0}); // true
b = Arrays.equals(new char[]{'a'}, new char[]{'a'}); // true
b = Arrays.equals(new short[]{0}, new short[]{0}); // true
b = Arrays.equals(new int[]{0}, new int[]{0}); // true
b = Arrays.equals(new long[]{0L}, new long[]{0L}); // true
b = Arrays.equals(new float[]{0F}, new float[]{0F}); // true
b = Arrays.equals(new double[]{0D}, new double[]{0D}); // true

// When comparing Object arrays, null elements are equal.
// If the elements are not null, Object.equals() is used.
b = Arrays.equals(new String[]{"a"}, new String[]{"a"}); // true
b = Arrays.equals(new String[]{null}, new String[]{null}); // true
b = Arrays.equals(new String[]{"a"}, new String[]{null}); // false

Sunday, July 29, 2007

Java Code to Associate a Value with an Object

This example demonstrates how to associate a value with an arbitrary object. The technique involves saving the object and the associated value as a key/value pair in an IdentityHashMap. A HashMap cannot be used for this purpose since if two objects happen to equal via the Object.equals() method, one of the objects will not be stored.
// Create the map
Map objMap = new IdentityHashMap();

// Add the object and value pair to the map
Object o1 = new Integer(123);
Object o2 = new Integer(123);
objMap.put(o1, "first");
objMap.put(o2, "second");

// Retrieve the value associated with the objects
Object v1 = objMap.get(o1); // first
Object v2 = objMap.get(o2); // second

Thursday, July 26, 2007

Java Code to Set the Default Locale

There are two ways to change the default locale. The first is to set it on the command line:
> java -Duser.language=2-char-language-code -Duser.region=2-char-country-code MyApp

// Set only language code
> java -Duser.language=fr -Duser.region= MyApp
// Set language and country code
> java -Duser.language=fr -Duser.region=CA MyApp


The second way to change the default locale is to call Locale.setDefault():
// Get default locale
Locale locale = Locale.getDefault();

// Set the default locale to pre-defined locale
Locale.setDefault(Locale.FRENCH);

// Set the default locale to custom locale
locale = new Locale("fr", "CA");
Locale.setDefault(locale);

Tuesday, July 24, 2007

Java Code to Get Listing Of All Available Locales

Locale[] locales = Locale.getAvailableLocales();

for (int i=0; i // Get the 2-letter language code
String language = locales[i].getLanguage();

// Get the 2-letter country code; may be equal to ""
String country = locales[i].getCountry();

// Get localized name suitable for display to the user
String locName = locales[i].getDisplayName();
}

Here's a sample of output using a default locale of Locale.ENGLISH:
Language Code, Country Code, Localized Name
ar, , Arabic
ar, AE, Arabic (United Arab Emirates)
ar, BH, Arabic (Bahrain)
ar, DZ, Arabic (Algeria)
ar, EG, Arabic (Egypt)
ar, IQ, Arabic (Iraq)
ar, JO, Arabic (Jordan)
ar, KW, Arabic (Kuwait)
ar, LB, Arabic (Lebanon)

Here's a sample of output using a default locale of Locale.FRENCH:
Language Code, Country Code, Localized Name
ar, , arabe
ar, AE, arabe (Emirats Arabes Unis)
ar, EG, arabe (Egypte)
ar, IQ, arabe (Irak)
ar, JO, arabe (Jordanie)
ar, KW, arabe (Koweit)
ar, LB, arabe (Liban)

Friday, July 20, 2007

Breaking a String into Words

String aString = "word1 word2 word3";
StringTokenizer parser = new StringTokenizer(aString);
while (parser.hasMoreTokens()) {
processWord(parser.nextToken());
}

Tuesday, July 10, 2007

Generating a Random Number - Package java.util

Random rand = new Random();

// Random integers
int i = rand.nextInt();
// Continually call nextInt() for more random integers ...

// Random integers that range from from 0 to n
int n = 10;
i = rand.nextInt(n+1);

// Random bytes
byte[] bytes = new byte[5];
rand.nextBytes(bytes);

// Other primitive types
boolean b = rand.nextBoolean();
long l = rand.nextLong();
float f = rand.nextFloat(); // 0.0 <= f < 1.0
double d = rand.nextDouble(); // 0.0 <= d < 1.0


// Create two random number generators with the same seed
long seed = rand.nextLong();
rand = new Random(seed);
Random rand2 = new Random(seed);