1. For/Each loop
Instead of looping with a numeric index, set a local variable to each item of a collection or array in order.
public void goThis(String[] strArray){
for(String obj:strArray){
System.out.println(obj);
}
}
2. Scanner Class - Scanner class is easily used to read the input from console.
Scanner inputScanner = new Scanner(System.in);
String s = inputScanner.nextLine();
int i = inputScanner.nextInt();
double d = inputScanner.nextDouble();
But you can also attach a Scanner to a File, a Socket, a Process, and more
3. Autoboxing - To insert java primitive into tables, list or anything expecting Object can be done using Java wrappers.
Although its a useful feature of java5 still its a performance hit because -
1. Every insert converts to wrapper type.
2. Every retrieval converts to primitive type
List
int i = 12;
arrayList.add(i);
int num = arrayList.get(0);
arrayList.add(num+1);
4. Varargs - A way to pass any number of a particular type of argument to the method. It becomes an array of that type. It should be te last in the list of arguments like
public static String method (String name, int ... numbers);
Sample code -
public class MathUtils {
public static int min(int ... numbers) {
int minimum = Integer.MAX_VALUE;
for(int number: numbers) {
if (number < minimum) {
minimum = number;
}
}
return(minimum);
}
public static void main(String[] args) {
System.out.printf("Min of 2 nums: %d.%n",min(2,1));
System.out.printf("Min of 7 nums: %d.%n",min(2,4,6,8,1,2,3));
}
No comments:
Post a Comment