Thursday, September 10, 2015

Enhanced for loop java

Enhanced for loop java: Enhanced for loop is useful when scanning the array instead of using for loop. Syntax of enhanced for loop is:

for (data_type variable: array_name)

Here array_name is the name of array.

Java enhanced for loop integer array

class EnhancedForLoop { 
public static void main(String[] args) { 
int primes[] = { 2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; 
for (int t: primes) { 
System.out.println(t); 
} 
} 
}
Output of program:

Java enhanced for loop strings

class EnhancedForLoop { 
public static void main(String[] args) { 
String languages[] = { "C", "C++", "Java", "Python", "Ruby"}; 
for (String sample: languages) { 
System.out.println(sample); 
} 
} 
}

Wednesday, September 9, 2015

Java program to find largest of three numbers

This java program finds largest of three numbers and then prints it. If the entered numbers are unequal then "numbers are not distinct" is printed.

Java programming source code

import java.util.Scanner;
class LargestOfThreeNumbers { 
public static void main(String args[]) { 
int x, y, z; 
System.out.println("Enter three integers "); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt(); 
z = in.nextInt();   
if ( x > y && x > z ) 
System.out.println("First number is largest."); 
else if ( y > x && y > z ) 
System.out.println("Second number is largest."); 
else if ( z > x && z > y ) 
System.out.println("Third number is largest."); 
else System.out.println("Entered numbers are not distinct."); 
} 
}

Output of program:


If you want to find out largest of a list of numbers say 10 integers then using above approach is not easy, instead you can use array data structure.

Tuesday, September 8, 2015

Java program to swap two numbers

This java program swaps two numbers using a temporary variable. To swap numbers without using extra variable see another code below.

Swapping using temporary or third variable


import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y, temp; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
temp = x; 
x = y; 
y = temp;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Output of program:


Swapping without temporary variable

import java.util.Scanner;   
class SwapNumbers { 
public static void main(String args[]) { 
int x, y; 
System.out.println("Enter x and y"); 
Scanner in = new Scanner(System.in);   
x = in.nextInt(); 
y = in.nextInt();   
System.out.println("Before Swapping\nx = "+x+"\ny = "+y);   
x = x + y; 
y = x - y; 
x = x - y;   
System.out.println("After Swapping\nx = "+x+"\ny = "+y); 
} 
}
Swapping is frequently used in sorting techniques such as bubble sort, quick sort etc.

Java exception handling tutorial with example programs

In this tutorial we will learn how to handle exception with the help of suitable examples. Exceptions are errors which occur when the program is executing. Consider the Java program below which divides two integers.


import java.util.Scanner;
 
class Division {
 public static void main(String[] args) {
 
 int a, b, result;
 
 Scanner input = new Scanner(System.in);
 System.out.println("Input two integers");
 
 a = input.nextInt();
 b = input.nextInt();
 
 result = a / b;
 
 System.out.println("Result = " + result);
 }
}

Now we compile and execute the above code two times, see the output of program in two cases:

Java program throwing Arithmetic exception (division by zero).

In the second case we are dividing a by zero which is not allowed in mathematics, so a run time error will occur i.e. an exception will occur. If we write programs in this way then they will be terminated abnormally and user who is executing our program or application will not be happy. This occurs because input of user is not valid so we have to take a preventive action and the best thing will be to notify the user that it is not allowed or any other meaningful message which is relevant according to context. You can see the information displayed when exception occurs it includes name of thread, file name, line of code (14 in this case) at which exception occurred, name of exception (ArithmeticException) and it's description('/ by zero'). Note that exceptions don't occur only because of invalid input only there are other reasons which are beyond of programmer control such as stack overflow exception, out of memory exception when an application requires memory larger than what is available.

Java provides a powerful way to handle such exceptions which is known as exception handling. In it we write vulnerable code i.e. code which can throw exception in a separate block called as try block and exception handling code in another block called catch block. Following modified code handles the exception.

Java exception handling example


class Division { 
public static void main(String[] args) { 
int a, b, result;   
Scanner input = new Scanner(System.in); 
System.out.println("Input two integers");   
a = input.nextInt(); 
b = input.nextInt();   
// try block   
try { 
result = a / b; 
System.out.println("Result = " + result); 
}   
// catch block   
catch (ArithmeticException e) { 
System.out.println("Exception caught: Division by zero."); 
} 
} 
}

Whenever an exception is caught corresponding catch block is executed, For example above code catches ArithmeticException only. If some other kind of exception is thrown it will not be caught so it's the programmer work to take care of all exceptions as in our try block we are performing arithmetic so we are capturing only arithmetic exceptions. A simple way to capture any exception is to use an object of Exception class as other classes inherit Exception class, see another example below:

class Exceptions { 
public static void main(String[] args) { 
String languages[] = { "C", "C++", "Java", "Perl", "Python" }; 
try { 
for (int c = 1; c <= 5; c++) { 
System.out.println(languages[c]); 
} 
} 
catch (Exception e) { 
System.out.println(e); 
} 
} 
}

Output of program:
C++
Java
Perl
Python
java.lang.ArrayIndexOutOfBoundsException: 5

Here our catch block capture an exception which occurs because we are trying to access an array element which does not exists (languages in this case). Once an exception is thrown control comes out of try block and remaining instructions of try block will not be executed. At compilation time syntax and semantics checking is done and code is not executed on machine so exceptions can only be detected at run time.

Finally block in Java


Finally block is always executed whether an exception is thrown or not.

class Allocate { 
public static void main(String[] args) {   
try { 
long data[] = new long[1000000000]; 
} 
catch (Exception e) { 
System.out.println(e); 
}   
finally { 
System.out.println("finally block will execute always."); 
} 
} 
}

Output of program:
finally block will execute always.
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at Allocate.main(Allocate.java:5)
Exception occurred because we try to allocate a large amount of memory which is not available. This amount of memory may be available on your system if this is the case try increasing the amount of memory to allocate through the program.

Using multiple classes in Java program

Java program can contain more than one i.e. multiple classes. Following example Java program contain two classes: Computer and Laptop. Both classes have their own constructors and a method. In main method we create object of two classes and call their methods.

Using two classes in Java program


class Computer
{
Computer() { 
System.out.println("Constructor of Computer class."); 
}   
void computer_method() { 
System.out.println("Power gone! Shut down your PC soon..."); 
}   
public static void main(String[] args) { 
Computer my = new Computer(); 
Laptop your = new Laptop();   
my.computer_method(); 
your.laptop_method(); 
} 
}   
class Laptop { 
Laptop() { 
System.out.println("Constructor of Laptop class."); 
}   
void laptop_method() { 
System.out.println("99% Battery available."); 
} 
}
Output of program:


You can also create objects in method of Laptop class. When you compile above code two .class files will be created which are Computer.class and Laptop.class, this has the advantage that you can reuse your .class file somewhere in other projects without compiling the code again. In short number of .class files created will be equal to number of classes in code. You can create as many classes as you want but writing many classes in a single file is not recommended as it makes code difficult to read rather you can create single file for every class. You can also group classes in packages for easily managing your code.