Archives: Core Java

Java – Create Immutable Class Example

[code lang=”java”]// declare class as final
final class Immutable {

// declare all variables as final
private final int val1;
private final String val2;

// provide constructor to set the values
public Immutable(int a, String s) {
val1 = a;
val2 = s;
}

// provide getters only
public int getVal1() {
return val1;
}

public String getVal2() {
return val2;
}
}[/code]
[code lang=”java”]public class ImmutableClassDemo {
public static void main(String[] args) {
Immutable obj = new Immutable(10, "Immutable Class Example");
System.out.println(obj.getVal1());
System.out.println(obj.getVal2());
}
}[/code]


Java – Detect Operating System

[code lang=”java”]
public class OSValidator {

public static void main(String[] args) {
if (isWindows()) {
System.out.println("This is Windows");
} else if (isMac()) {
System.out.println("This is Mac");
} else if (isUnix()) {
System.out.println("This is Unix or Linux");
} else if (isSolaris()) {
System.out.println("This is Solaris");
} else {
System.out.println("Your OS is not support!!");
}
}

public static boolean isWindows() {

String os = System.getProperty("os.name").toLowerCase();
// windows
return (os.indexOf("win") >= 0);

}

public static boolean isMac() {

String os = System.getProperty("os.name").toLowerCase();
// Mac
return (os.indexOf("mac") >= 0);

}

public static boolean isUnix() {

String os = System.getProperty("os.name").toLowerCase();
// linux or unix
return (os.indexOf("nix") >= 0 || os.indexOf("nux") >= 0);

}

public static boolean isSolaris() {

String os = System.getProperty("os.name").toLowerCase();
// Solaris
return (os.indexOf("sunos") >= 0);

}

}[/code]


Java – Calculate Execution Time

[code lang=”java”]
import java.util.Date;

public class TimeMillisecond {
public static void main(String[] argv) {

long lStartTime = new Date().getTime(); //start time

String sArray1[] = createArray(); //method execute

long lEndTime = new Date().getTime(); //end time

long difference = lEndTime – lStartTime; //check different

System.out.println("Elapsed milliseconds: " + difference);

}

static String [] createArray(){

String sArray[] = new String [100000];

for(int i=0; i<100000; i++)
sArray[i] = "Array " + i;

return sArray;
}
}[/code]