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
 

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