Category: Java Codes
Exception Handling snippet – try, catch, finally (Java)
public class Main { //Keywords : Try, catch, finally, throw, throws public static void main(String[] args) { //Throwable class is base for Class of Errors and //Class of Exception. Then in Exception class you have specific classes //like arrayoutofbound i.e. they are derived classes try{ int a = 10; int b = 0; int c = a/b; //Code will crash here so further statements won't be executed System.out.println(c); int arr [] = {1,2,3,4}; System.out.println(arr[1]); System.out.println(arr[4]); } catch(ArrayIndexOutOfBoundsException e){ System.out.println("You are crossing the limit where no value exists\n\n"); } catch (ArithmeticException e) { System.out.println("Aw, sorry you can't divide by 0. Please ... Read moreAll about static snippet (Java)
import java.util.Random; public class Emp { //To get a unique employee id i.e. it doesn't starts with 0 static private int empId; private int actualEmpid; private String empName; private int empSal; static private String compName; static private int totalEmp = 0; //Java has 3 things: Static data, static function and static block static{ //This is executed just after creation of object. After object creation, static datas are created n then static block. System.out.println("Static block created..."); Random random = new Random(); //Random number in the range 0-1000 empId = random.nextInt( 1000 ); } Emp(){ //Constructor //Post increment so that it is ... Read moreArrays snippet w/ string illustration (Java)
public class Collection { public static void main( String [] args){ int [] arr, arr1; //int arr []; is also allowed but not preferred arr = new int[5]; arr1 = new int[] {10, 12, 33,43}; for(int i : arr){ System.out.println(i); } System.out.println("-------------------------"); for(int i = 0; i < arr1.length ; i++){ System.out.println(arr1[i]); } System.out.println("-------------------------"); int [] [] arr3 = new int[3][]; arr3[0] = new int[2]; arr3[1] = new int[3]; arr3[2] = new int[2]; for(int i = 0; i < arr3.length ; i++){ for(int j=0;j<arr3[i].length;j++){ System.out.printf(arr3[i][j] + " "); //printf so that on each loop new line is not automatically generated ... Read moreBeginner Program – Parameterized Constructor (Java)