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) {
}
Saturday, June 27, 2009
How to Read Text from Standard Input
11:26 PM
Posted by
Techsavy
try {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String str = "";
while (str != null) {
str = in.readLine();
System.out.println(str);
}
} catch (IOException e) {
}
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
11:24 PM
Posted by
Techsavy
boolean success = (new File("directoryName")).delete();
if (success) {
// Deletion successful
}
if (success) {
// Deletion successful
}
How to Get the Current Working Directory
11:23 PM
Posted by
Techsavy
String currrentDirectory = System.getProperty("user.dir");
How to Rename a File
6:48 PM
Posted by
Techsavy
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
}
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
6:45 PM
Posted by
Techsavy
boolean success = (new File("C:/temp/temp.txt")).delete();
if (success) {
// Deletion succeeded
}
if (success) {
// Deletion succeeded
}
How to Get the Size of a File
6:42 PM
Posted by
Techsavy
File file = new File("C:/temp/temp.txt");
// Get the number of bytes in the file
long length = file.length();
// Get the number of bytes in the file
long length = file.length();
How to Determine If a File or Directory Exists
6:39 PM
Posted by
Techsavy
boolean existsFlag = (new File("C:/temp/temp.txt")).exists();
if (existsFlag) {
// File or directory exists
} else {
// File or directory does not exist
}
if (existsFlag) {
// File or directory exists
} else {
// File or directory does not exist
}
How to Create a File
6:37 PM
Posted by
Techsavy
try {
File file = new File("C:/temp/temp.txt");
} catch (IOException e) {
}
File file = new File("C:/temp/temp.txt");
} catch (IOException e) {
}
How to Determine If a File Path Is a File or a Directory
6:34 PM
Posted by
Techsavy
File file = new File("filepath");
boolean isDirectory = file.isDirectory();
if (isDirectory) {
// file is a directory
} else {
// file is a file
}
boolean isDirectory = file.isDirectory();
if (isDirectory) {
// file is a directory
} else {
// file is a file
}
How to Get an Absolute File Path
6:30 PM
Posted by
Techsavy
File file = new File("C:"+File.separatorChar+"temp"+File.separatorChar+"temp.txt");
file = file.getAbsoluteFile(); // c:\temp\temp.txt
file = file.getAbsoluteFile(); // c:\temp\temp.txt
How to Construct a File Path
6:23 PM
Posted by
Techsavy
String path = File.separator +"temp"; // /temp
Thursday, June 25, 2009
How to Compare Dates
8:36 PM
Posted by
Techsavy
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
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
8:36 PM
Posted by
Techsavy
Calendar cal = new GregorianCalendar(2007, Calendar.SEPTEMBER, 1);
Date date = cal.getTime(); // Sat Sep 01 00:00:00 PDT 2007
Date date = cal.getTime(); // Sat Sep 01 00:00:00 PDT 2007
How to Get the Current Date
8:35 PM
Posted by
Techsavy
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, ...
// 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
8:35 PM
Posted by
Techsavy
// 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);
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
8:34 PM
Posted by
Techsavy
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);
// 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
8:34 PM
Posted by
Techsavy
String[] strArray = new String[] {"x", "y", "Z"};
Arrays.sort(strArray);
// [Z, x, y]
Arrays.sort(strArray);
// [Z, x, y]
How to Use Sorted Map
8:33 PM
Posted by
Techsavy
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]
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
8:32 PM
Posted by
Techsavy
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
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
8:31 PM
Posted by
Techsavy
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]
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
8:30 PM
Posted by
Techsavy
// 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();
}
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
8:30 PM
Posted by
Techsavy
// 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
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
8:29 PM
Posted by
Techsavy
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));
// 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
8:28 PM
Posted by
Techsavy
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]
// 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
8:27 PM
Posted by
Techsavy
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]
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
8:27 PM
Posted by
Techsavy
// 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=[]
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
8:26 PM
Posted by
Techsavy
Iterator it = set.iterator();
while (it.hasNext()) {
// Get the element
Object element = it.next();
}
while (it.hasNext()) {
// Get the element
Object element = it.next();
}
How to Create a Set
8:25 PM
Posted by
Techsavy
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
// 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
8:24 PM
Posted by
Techsavy
// 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"]
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
8:23 PM
Posted by
Techsavy
// Create a list
String[] strArray = new String[] {"e", "a", "A"};
List list = Arrays.asList(strArray);
// Sort
Collections.sort(list); // A, a, e
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
8:22 PM
Posted by
Techsavy
// 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");
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
8:21 PM
Posted by
Techsavy
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
}
}
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
8:21 PM
Posted by
Techsavy
try {
long delay = 7000; // 7 seconds
Thread.sleep(delay);
} catch (InterruptedException e) {
}
long delay = 7000; // 7 seconds
Thread.sleep(delay);
} catch (InterruptedException e) {
}
How to Determine When a Thread Has Finished
8:20 PM
Posted by
Techsavy
// Create and start a thread
Thread thread = new SampleThread();
thread.start();
if (thread.isAlive()) {
// Thread is still running
} else {
// Thread is finished
}
Thread thread = new SampleThread();
thread.start();
if (thread.isAlive()) {
// Thread is still running
} else {
// Thread is finished
}
How to Stop a Thread
8:18 PM
Posted by
Techsavy
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...
}
}
}
// 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
8:17 PM
Posted by
Techsavy
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();
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
8:16 PM
Posted by
Techsavy
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) {
}
// 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
8:15 PM
Posted by
Techsavy
// 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);
}
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
8:14 PM
Posted by
Techsavy
// Get a system property
String dir = System.getProperty("SampleProperty");
// Set a system property
String previousValue = System.setProperty("SampleProperty", "newValue");
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
7:58 PM
Posted by
Techsavy
// 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
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
7:57 PM
Posted by
Techsavy
// Convert to upper case
String upper = “abc”.toUpperCase(); // ABC
// Convert to lower case
String lower = “ABC”.toLowerCase(); // abc
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
7:57 PM
Posted by
Techsavy
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
// 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
7:56 PM
Posted by
Techsavy
int start = 1;
int end = 3;
String substr = "Java".substring(start, end); // av
int end = 3;
String substr = "Java".substring(start, end); // av
How to Construct a String
7:56 PM
Posted by
Techsavy
StringBuffer buf = new StringBuffer("Hi");
// Append
buf.append(" Welcome");
buf.append(“ To Java”);
// Convert to string
String s = buf.toString(); // Hi Welcome To Java
// Append
buf.append(" Welcome");
buf.append(“ To Java”);
// Convert to string
String s = buf.toString(); // Hi Welcome To Java
How to Compare Strings
7:55 PM
Posted by
Techsavy
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
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
7:54 PM
Posted by
Techsavy
StringBuffer buf = new StringBuffer("Hi");
// Append
buf.append(" Welcome");
// Convert StringBuffer to string
String s = buf.toString();
// Append
buf.append(" Welcome");
// Convert StringBuffer to string
String s = buf.toString();
How to Get the Package of a Class
7:54 PM
Posted by
Techsavy
Class cls = java.lang.String.class;
Package packageOfClass = cls.getPackage();
String packageName = packageOfClass.getName(); // java.lang
Package packageOfClass = cls.getPackage();
String packageName = packageOfClass.getName(); // java.lang
How to List the Interfaces That a Class Implements
7:53 PM
Posted by
Techsavy
Class cls = java.lang.String.class;
Class[] interfaces = cls.getInterfaces();
Class[] interfaces = cls.getInterfaces();
How to Get the Superclass of an Object
7:52 PM
Posted by
Techsavy
Object o = new String();
Class superClass = o.getClass().getSuperclass(); // java.lang.Object
Class superClass = o.getClass().getSuperclass(); // java.lang.Object
How to Determine If a Class Object Represents a Class or Interface
7:52 PM
Posted by
Techsavy
Class cls = java.lang.String.class;
boolean isClass = cls.isInterface(); // false
cls = java.lang.Cloneable.class;
isClass = cls.isInterface(); // true
boolean isClass = cls.isInterface(); // false
cls = java.lang.Cloneable.class;
isClass = cls.isInterface(); // true
How to Get the Name of a Class Object
7:50 PM
Posted by
Techsavy
Class cls = java.lang.String.class;
String name = cls.getName();
String name = cls.getName();
How to Get an Object of the Class
7:49 PM
Posted by
Techsavy
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;
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
10:57 PM
Posted by
Techsavy
// 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
10:55 PM
Posted by
Techsavy
class SampleClass implements Cloneable {Here's some code to create a clone.
public SampleClass() {
}
public Object clone() {
Cloneable theClone = new SampleClass();
// Initialize theClone.
return theClone;
}
}
SampleClass myObject = new SampleClass();
SampleClass myObjectClone = (SampleClassmyObject.clone();
How to Get the Size of the Java Memory Heap
10:52 PM
Posted by
Techsavy
// 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
10:47 PM
Posted by
Techsavy
System.out.println("My Sample Output");
System.err.println("My Sample Error");
System.err.println("My Sample Error");
How to Compute Elapsed Time
9:39 PM
Posted by
Techsavy
// Get current time
long startTime = System.currentTimeMillis();
// .....Do something Here.......
// Get elapsed time in milliseconds
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSeconds = endTime-startTime;
long startTime = System.currentTimeMillis();
// .....Do something Here.......
// Get elapsed time in milliseconds
long endTime = System.currentTimeMillis();
long elapsedTimeInMilliSeconds = endTime-startTime;
How to Write a Simple Java Program
9:22 PM
Posted by
Techsavy
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
8:41 PM
Posted by
Techsavy
The java.lang package contains classes and interfaces essential to the Java language.
A few components of java.lang package is as follows.
A few components of java.lang package is as follows.
- The most popular class, Object class
- Multithreading
- Exception handling
- Java Primitive Types (int, float, boolean, long, double, char etc.)
- String and StringBuffer
- System properties
- Assertions
Subscribe to:
Posts (Atom)