Saturday, June 27, 2009

How to Read Text from a File


try {
BufferedReader in = new BufferedReader(new FileReader("C:/temp/temp.txt"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
} catch (IOException e) {
}

How to Read Text from Standard Input


try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
str = in.readLine();
System.out.println(str);
}
} catch (IOException e) {
}

How to Delete a Directory


boolean success = (new File("directoryName")).delete();
if (success) {
// Deletion successful
}

How to Get the Current Working Directory


String currrentDirectory = System.getProperty("user.dir");

How to Rename a File


File oldFile = new File("C:/temp/oldTemp.txt");
File newFile = new File("C:/temp/newTemp.txt");
// Rename file
boolean success = oldFile.renameTo(newFile);
if (success) {
// File was successfully renamed
}

How Delete a File


boolean success = (new File("C:/temp/temp.txt")).delete();
if (success) {
// Deletion succeeded
}

How to Get the Size of a File


File file = new File("C:/temp/temp.txt");
// Get the number of bytes in the file
long length = file.length();

How to Determine If a File or Directory Exists


boolean existsFlag = (new File("C:/temp/temp.txt")).exists();
if (existsFlag) {
// File or directory exists
} else {
// File or directory does not exist
}

How to Create a File


try {
File file = new File("C:/temp/temp.txt");
} catch (IOException e) {
}

How to Determine If a File Path Is a File or a Directory


File file = new File("filepath");
boolean isDirectory = file.isDirectory();
if (isDirectory) {
// file is a directory
} else {
// file is a file
}

How to Get an Absolute File Path


File file = new File("C:"+File.separatorChar+"temp"+File.separatorChar+"temp.txt");
file = file.getAbsoluteFile(); // c:\temp\temp.txt

How to Construct a File Path


String path = File.separator +"temp"; // /temp

Thursday, June 25, 2009

How to Compare Dates


Calendar cal1 = new GregorianCalendar(2007, Calendar.SEPTEMBER, 1);
Calendar cal2 = new GregorianCalendar(2007, Calendar.SEPTEMBER, 15);

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

// Get difference in milliseconds
long diffMillis = cal2.getTimeInMillis()-cal1.getTimeInMillis(); //1209600000

How to Create a Date Object


Calendar cal = new GregorianCalendar(2007, Calendar.SEPTEMBER, 1);
Date date = cal.getTime(); // Sat Sep 01 00:00:00 PDT 2007

How to Get the Current Date


Calendar cal = new GregorianCalendar();

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

How to Get the Current Time in Another Time Zone


// Get the current time in London
Calendar cal = new GregorianCalendar(TimeZone.getTimeZone("London"));

int hour12 = cal.get(Calendar.HOUR);
int minutes = cal.get(Calendar.MINUTE);
int seconds = cal.get(Calendar.SECOND);
int am = cal.get(Calendar.AM_PM);

// Get the current hour-of-day at GMT
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
int hour24 = cal.get(Calendar.HOUR_OF_DAY);

How to Get the Current Time


Calendar cal = new GregorianCalendar();

// Get the components of the time
int hour12 = cal.get(Calendar.HOUR);
int hour24 = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int millisecond = cal.get(Calendar.MILLISECOND);
int ampm = cal.get(Calendar.AM_PM);

How to Sort an Array


String[] strArray = new String[] {"x", "y", "Z"};
Arrays.sort(strArray);
// [Z, x, y]

How to Use Sorted Map


Keys in the TreeMap will automatically be sorted.

Map map = new TreeMap();
map.put("a", new Integer(1));
map.put("c", new Integer(3));
map.put("b", new Integer(2));
// [a=1, b=2, c=3]

How to Use Hash Table


Difference between HashMap and Hashtable :

1) HashMap accepts null key, whereas Hashtable doesn't.
2) HashMap is not thread-safe, whereas Hashtable is thread-safe.

Map map = new Hashtable();
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));
//map.put(null, new Integer(1)); // not allowed

How to Retain the Insertion Order in a Map


Use LinkedHashMap to retain

Map map = new LinkedHashMap();
// Add some elements
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

// List the entries
for (Iterator it=map.keySet().iterator(); it.hasNext(); ) {
Object key = it.next();
Object value = map.get(key);
}
// [a=1, b=2, c=3]

How to Iterate the Map


// Iterate over the keys in the map
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
// Get key
Object key = it.next();
}

// Iterate over the values in the map
it = map.values().iterator();
while (it.hasNext()) {
// Get value
Object value = it.next();
}

How to Remove the Entry from the Map


// Create a hash map
Map map = new HashMap();

// Add key/value pairs to the map
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

// remove method returns the value of removed key
oldValue = map.remove("c"); // 3

How to Create a Map


Map is a list of key-value pairs

// Create a hash map
Map map = new HashMap();

// Add key/value pairs to the map
map.put("a", new Integer(1));
map.put("b", new Integer(2));
map.put("c", new Integer(3));

How to Use Sorted Set


Elements in the TreeSet will automatically be arranged in sorted form.

// Create the sorted set
Set set = new TreeSet();

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

//[a,b,C]

How to Retain the Insertion Order in a Set


Use LinkedHashSet to retain the insertion order

Set set = new LinkedHashSet();

// Add some elements
set.add("1");
set.add("2");
set.add("3");
set.add("1");

// Iterate the set
for (Iterator it=set.iterator(); it.hasNext(); ) {
Object o = it.next();
}
// [1, 2, 3]

How to Add and Remove One Set to Another


// Create the sets
Set set1 = new HashSet();
Set set2 = new HashSet();

set1.add("A");
set2.add("A");
set2.add("B");

// set1=set1+set2-common elements
set1.addAll(set2); // set1=["A","B"]

// set1=set1-set2
set1.removeAll(set2); // set1=[]

How to Iterate a Set


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

How to Create a Set


Difference between List and Set : List can contain duplicate elements. Set can contain only unique elements. If you try to add the same element again then it will overwrite the new element on old one.

// Create the set
Set set = new HashSet();
// Add elements to the set
set.add("X");
set.add("Y");
set.add("Z");

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

// Remove elements from the set
set.remove("Z"); //set=["X","Y"]


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

How to Add and Remove One List from Another


// Create the lists
List samplelist1 = new ArrayList();
List samplelist2 = new ArrayList();

samplelist1.add("A");
samplelist2.add("B");

// Copy all the elements from samplelist2 to samplelist1 (samplelist1=samplelist1+samplelist2)
samplelist1.addAll(samplelist2); // samplelist1=["A","B"]

// Remove all the elements in samplelist1 from samplelist2 (samplelist1=samplelist1-samplelist2)
samplelist1.removeAll(samplelist2); // samplelist1=["A"]

How to Sort a List


// Create a list
String[] strArray = new String[] {"e", "a", "A"};
List list = Arrays.asList(strArray);

// Sort
Collections.sort(list); // A, a, e

Wednesday, June 24, 2009

How to Create an ArrayList


// Create the list
List list = new ArrayList();
// Append an element to the list
list.add("abc");
// Insert an element at the head of the list
list.add(0, "xyz");

How to Determine If the Current Thread Is Holding a Synchronized Lock


public synchronized void myMethod() {
boolean hasLock = false;
Object obj = new Object();

// Determine if current thread has lock for obj
hasLock = Thread.holdsLock(obj); // false
synchronized (obj) {
hasLock = Thread.holdsLock(obj); // true
}
}

How to Pause the Current Thread


try {
long delay = 7000; // 7 seconds
Thread.sleep(delay);
} catch (InterruptedException e) {
}

How to Determine When a Thread Has Finished


// Create and start a thread
Thread thread = new SampleThread();
thread.start();

if (thread.isAlive()) {
// Thread is still running
} else {
// Thread is finished
}

How to Stop a Thread


There are two methods(stop() and suspend()) available in Thread class to stop the thread. As these methods are deprecated, it is advisable not to use these methods and use below mentioned approach to stop the thread.

// Create and start the thread
SampleThread thread = new SampleThread();
thread.start();
//...Some Code...
// Stop the thread
thread.done = true;

class SampleThread extends Thread {
boolean done = false;
// This method is called when the thread runs
public void run() {
while (true) {
// ...Some Code...
if (done) {
return;
}
// ...Some Code...
}
}
}

How to Create a Thread


There are two ways to create a thread.
1) Using Thread class
2) Using Runnable interface

Using Thread class:

// This class extends Thread
class SampleThread extends Thread {
// This method is the entry point of thread. It is called when thread runs.
public void run() {
}
}

// Create and start the thread
Thread thread = new SampleThread();
thread.start();


Using Runnable interface:

class SampleThread implements Runnable {
// This method is called when the thread runs
public void run() {
}
}

// Create the object with the run() method
Runnable runnable = new SampleThread();

Thread thread = new Thread(runnable);

// Start the thread
thread.start();

How to Execute a Command


try {
// Execute a command. "ls -a" a unix command. So, this command will work on unix only.
String command = "ls -a";
Process child = Runtime.getRuntime().exec(command);

} catch (IOException e) {

}

How to List All System Properties


// Get all system properties
Properties props = System.getProperties();

// Enumerate all system properties
Enumeration enum = props.propertyNames();
for (; enum.hasMoreElements(); ) {
// Get property name
String propName = (String)enum.nextElement();

// Get property value
String propValue = (String)props.get(propName);
}

How to Get and Set the Value of a System Property


// Get a system property
String dir = System.getProperty("SampleProperty");

// Set a system property
String previousValue = System.setProperty("SampleProperty", "newValue");

Tuesday, June 23, 2009

How to Convert a Primitive Type Value to a String


// Use String.valueOf()
String s = String.valueOf(true); // true
s = String.valueOf('a'); // a
s = String.valueOf((short)111); // 111
s = String.valueOf(111); // 111
s = String.valueOf(111L); // 111
s = String.valueOf(1.11F); // 1.11
s = String.valueOf(1.11D); // 1.11

How to Convert a String to Upper or Lower Case


// Convert to upper case
String upper = “abc”.toUpperCase(); // ABC

// Convert to lower case
String lower = “ABC”.toLowerCase(); // abc

How to Search a String for a Character or a Substring


String string = "Java Java";
// First occurrence of a character ‘a’
int index = string.indexOf('a'); // 1

// First occurrence of a sting “dam”
index = string.indexOf("ava"); // 1

How to Get a Substring from a String


int start = 1;
int end = 3;
String substr = "Java".substring(start, end); // av

How to Construct a String


StringBuffer buf = new StringBuffer("Hi");

// Append
buf.append(" Welcome");
buf.append(“ To Java”);

// Convert to string
String s = buf.toString(); // Hi Welcome To Java

How to Compare Strings


String s1 = "a";
String s2 = "A";

// Check if identical
boolean b = s1.equals(s2); // false

// Check if identical ignoring case
b = s1.equalsIgnoreCase(s2); // true

StringBuffer sbuf = new StringBuffer("a");
b = s1.contentEquals(sbuf); // true

How to Construct a String From StringBuffer


StringBuffer buf = new StringBuffer("Hi");
// Append
buf.append(" Welcome");
// Convert StringBuffer to string
String s = buf.toString();

How to Get the Package of a Class


Class cls = java.lang.String.class;
Package packageOfClass = cls.getPackage();
String packageName = packageOfClass.getName(); // java.lang

How to List the Interfaces That a Class Implements


Class cls = java.lang.String.class;
Class[] interfaces = cls.getInterfaces();

How to Get the Superclass of an Object


Object o = new String();
Class superClass = o.getClass().getSuperclass(); // java.lang.Object

How to Determine If a Class Object Represents a Class or Interface


Class cls = java.lang.String.class;
boolean isClass = cls.isInterface(); // false

cls = java.lang.Cloneable.class;
isClass = cls.isInterface(); // true

How to Get the Name of a Class Object


Class cls = java.lang.String.class;
String name = cls.getName();

How to Get an Object of the Class


There are three ways to retrieve a class object.

1) Class cls = object.getClass();

2)
try {

cls = Class.forName("java.lang.String");

} catch (ClassNotFoundException e) {

}

3) cls = java.lang.String.class;

Monday, June 22, 2009

How to Wrape a Primitive Type in a Wrapper Object


    // Create wrapper object for each primitive type
Boolean sampleBoolean = new Boolean(
true);
Byte sampleByte = new Byte((byte)245
);
Character sampleChar = new Character(
'Y');
Short sampleShort = new Short((short)
245);
Integer sampleInt = new Integer(
245);
Long sampleLong = new Long(
245L);
Float sampleFloat = new Float(
245F);
Double sampleDouble = new Double(
24.5D);

// Retrieving the value in a wrapper object
boolean bool = sampleBoolean.booleanValue();
byte b = sampleByte.byteValue();
char c = sampleChar.charValue();
short s = sampleShort.shortValue();
int i = sampleInt.intValue();
long l = sampleLong.longValue();
float f = sampleFloat.floatValue();
double d = sampleDouble.doubleValue();

How to Clone an Object


    class SampleClass implements Cloneable {
public
SampleClass() {
}
public Object clone() {
Cloneable theClone = new
SampleClass();
// Initialize theClone.
return theClone;
}
}
Here's some code to create a clone.
SampleClass myObject = new SampleClass();
SampleClass myObjectClone = (SampleClassmyObject.clone();

How to Get the Size of the Java Memory Heap


// Get current size of heap in bytes
long heapSize = Runtime.getRuntime().totalMemory();

// Get maximum size of heap in bytes.
long heapMaximumSize = Runtime.getRuntime().maxMemory();

// Get amount of free memory within the heap in bytes.
long heapFreeSize = Runtime.getRuntime().freeMemory();

How to Redirecte Standard Output and Error


System.out.println("My Sample Output");
System.err.println("My Sample Error");

How to Compute Elapsed Time


// Get current time
long startTime = System.currentTimeMillis();

// .....Do something Here.......

// Get elapsed time in milliseconds
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSeconds = endTime-startTime;

How to Terminate a Java Program


// Terminate
System.exit(-1);

How to Write a Simple Java Program


public class SampleJavaClass {
public static void main(String[] args) {
for (int i=0; i<args.length; i++) {
// process args[i];
}
// Output in console
System.out.println(
"This is my first java program!!!");
}
}

java.lang package


The java.lang package contains classes and interfaces essential to the Java language.
A few components of java.lang package is as follows.
  1. The most popular class, Object class
  2. Multithreading
  3. Exception handling
  4. Java Primitive Types (int, float, boolean, long, double, char etc.)
  5. String and StringBuffer
  6. System properties
  7. Assertions

Blog Archive

 

Sample Java Codes Copyright © 2008 Green Scrapbook Diary Designed by SimplyWP | Made free by Scrapbooking Software | Bloggerized by Ipiet Notez