Sunday, 31 March 2013

use of throw

// Demonstrate throw.
class Myjava {
static void demoproc() {
try {
throw new NullPointerException("demo");
} catch(NullPointerException e) {
System.out.println("Caught inside demoproc.");
throw e; // rethrow the exception
}
}
public static void main(String args[]) {
try {
demoproc();
} catch(NullPointerException e) {
System.out.println("Recaught: " + e);
}
}
}




o/p

Caught inside demoproc.
Recaught: java.lang.NullPointerException: demo

nested try statement

// An example of nested try statements.
class Myjava {
public static void main(String args[]) {
try {
int a =2; //args.length;
/* If no command-line args are present,
the following statement will generate
a divide-by-zero exception. */
int b = 42 / a;
System.out.println("a = " + a);
try { // nested try block
/* If one command-line arg is used,
then a divide-by-zero exception
will be generated by the following code. */
if(a==1) a = a/(a-a); // division by zero
/* If two command-line args are used,
then generate an out-of-bounds exception. */
if(a==2) {
int c[] = { 1 };
c[42] = 99; // generate an out-of-bounds exception
}
} catch(ArrayIndexOutOfBoundsException e) {
System.out.println("Array index out-of-bounds: " + e);
}
} catch(ArithmeticException e) {
System.out.println("Divide by 0: " + e);
}
}
}



C:\>java Myjava
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java Myjava One
a = 1
Divide by 0: java.lang.ArithmeticException: / by zero
C:\>java Myjava One Two
a = 2
Array index out-of-bounds:
java.lang.ArrayIndexOutOfBoundsException:42

Saturday, 30 March 2013

Variables in Interfaces

public class Myjava implements A,B
{
   
    public static void main(String[] args)
    {
       
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    System.out.println(d);
    System.out.println(e);
   
    System.out.println(a1);
    System.out.println(b1);
    System.out.println(c1);
    System.out.println(d1);
    System.out.println(e1);
   
       
       
       
    }
   
}



interface A
{
   
    int a=1;
    int b=2;
    int c=3;
    int d=4;
    int e=5;
   
}

interface B
{
   
    int a1=11;
    int b1=22;
    int c1=33;
    int d1=44;
    int e1=55;
   
}

Output :

1
2
3
4
5
11
22
33




Interfaces Can be Extended 


public class Myjava implements B
{
   
    public static void main(String[] args)
    {
       
    System.out.println(a);
    System.out.println(b);
    System.out.println(c);
    System.out.println(d);
    System.out.println(e);
   
    System.out.println(a1);
    System.out.println(b1);
    System.out.println(c1);
    System.out.println(d1);
    System.out.println(e1);
   
       
       
       
    }
   
}



interface A
{
   
    int a=1;
    int b=2;
    int c=3;
    int d=4;
    int e=5;
   
}

interface B extends A
{
   
    int a1=11;
    int b1=22;
    int c1=33;
    int d1=44;
    int e1=55;
   
   
   
}










Output :

1
2
3
4
5
11
22
33
44
55