-------------------------------------- Java Sag is under construction: fundamental
Please inform us if you find a non good advertisement : info.enim dot gmail.com

Best Web Hosting

Affichage des articles dont le libellé est fundamental. Afficher tous les articles
Affichage des articles dont le libellé est fundamental. Afficher tous les articles

mercredi 9 mai 2012

How do I create static variables in Java?

Class variables or static variable is variable that declared with static modifier. A given class will have only one copy of each of its static variables, regardless of how many times the class has been instantiated.

If the value of a static variable is changed, the new value is available equally in all instances of the class. The final keyword could be added to indicate the value of static variable will never change. If you try to assign a new value to final variable, you will get a compile error.
package org.kodejava.example.fundametal;

public class StaticDemo {
    // static variable
    static int x = 12;

    // static variable with final value that never change
    final static int Y = 20;

    // non-static variable
    int z;

    public static void main(String[] args) {
        StaticDemo sd0 = new StaticDemo();

        System.out.println("x before update = " + StaticDemo.x);
        System.out.println("y= " + StaticDemo.Y);

        sd0.z = StaticDemo.x + StaticDemo.Y;
        System.out.println("z= " + sd0.z);

        StaticDemo.x = 15;
        System.out.println("x after update = " + StaticDemo.x);

        StaticDemo sd1 = new StaticDemo();
        StaticDemo sd2 = new StaticDemo();
        StaticDemo.x = 20;

        System.out.println("StaticDemo.x = " + StaticDemo.x);
        System.out.println("sd0 = " + sd0.getX());
        System.out.println("sd1 = " + sd1.getX());
        System.out.println("sd2 = " + sd2.getX());

        //
        // try to assign value to final variable, it will cause a
        // compile time error
        //
        // StaticDemo.Y = 30;
    }

    public int getX() {
        return StaticDemo.x;
    }
}

Here is the output printed by the program:

x before update = 12
y= 20
z= 32
x after update = 15
StaticDemo.x = 20
sd0 = 20
sd1 = 20
sd2 = 20

How do I catch multiple exceptions?

If a try block can throw several different kind of exceptions and you want to handle each exception differently, you can put several catch blocks to handle it.
package org.kodejava.example.fundametal;

public class MultipleCatchExample {
    public static void main(String[] args) {
        int[] numbers1 = {1, 2, 3, 4, 5};
        int[] numbers2 = {1, 2, 3, 4, 5, 6};

        try {
            //
            // This line throws an ArrayIndexOutOfBoundsException
            //
            MultipleCatchExample.printResult(numbers1);

            //
            // This line throws an ArithmeticException
            //
            MultipleCatchExample.printResult(numbers2);
        } catch (ArithmeticException e) {
            e.printStackTrace();
        } catch (ArrayIndexOutOfBoundsException e) {
            e.printStackTrace();
        } finally {
            System.out.println("Finally block is always executed.");
        }
    }

    /**
     * Divide the given first number by the second number.
     *
     * @param x the first number.
     * @param y the second number.
     * @return the result of division.
     */
    private static int divide(int x, int y) {
        return x / y;
    }

    /**
     * Print the output result of divide operation by calling the
     * divide() method.
     *
     * @param numbers integer arrays of the divided number
     * @throws ArrayIndexOutOfBoundsException when an exception
     * occurs.
     */
    private static void printResult(int[] numbers) {
        int x, z, y = 1;
        for (int i = 0; i < 6; i++) {
            x = numbers[i];
            if (i == 5) {
                y = 0;
            }
            z = MultipleCatchExample.divide(x, y);
            System.out.println("z = " + z);
        }
    }
}

How do I use the super keyword?

When a class extends from other class, the class or usually called as subclass inherits all the accessible members and methods of the superclass. If the subclass overrides a method provided by its superclass, a way to access the method defined in the superclass is through the super keyword.
package org.kodejava.example.fundametal;

public class Bike {
    public void moveForward() {
        System.out.println("Bike: Move Forward.");
    }
}

In the ThreeWheelsBike's moveForward() method we call the overridden method using the super.moveForward() which will print the message from the Bike class.
package org.kodejava.example.fundametal;

public class ThreeWheelsBike extends Bike {
    @Override
    public void moveForward() {
        super.moveForward();
        System.out.println("Three Wheels Bike: Move Forward.");
    }

    public static void main(String[] args) {
        Bike bike = new ThreeWheelsBike();
        bike.moveForward();
    }
}

How do I use the this keyword in Java?

The program below demonstrate how to use the switch statement. The switch statement can work with thebyteshortint and char primitive data types and the corresponding wrappers of these data type such asByteShortInteger and Character. It also work with work with enumerated types, refer to the following example: How do I use enum in switch statement?.
The switch block or the body can contains one or more case or default labels. The switch statement evaluates its expression and evaluate the appropriate case.
You'll also notice that after each case labels we have a break statement. This break statement causes the program execution to continue outside the switch block. Without using a break the case will fall-through to another case or default label.
package org.kodejava.example.lang;

public class SwitchDemo {
    public static void main(String[] args) {
        System.out.println("The Planets");
        System.out.println("===================================");
        System.out.println("1. Mercury");
        System.out.println("2. Venus");
        System.out.println("3. The Earth");
        System.out.println("4. Mars");
        System.out.println("5. Jupiter");
        System.out.println("6. Saturn");
        System.out.println("7. Uranus");
        System.out.println("8. Neptune");
        System.out.println("");
        System.out.print("Please choose your favorite destination: ");

        int destionation = 0;
        try {
            destionation = Integer.valueOf(System.console().readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        System.out.print("Welcome to ");
        switch (destionation) {
            case 1:
                System.out.println("Mercury"); break;
            case 2:
                System.out.println("Venus"); break;
            case 3:
                System.out.println("The Earth"); break;
            case 4:
                System.out.println("Mars"); break;
            case 5:
                System.out.println("Jupiter"); break;
            case 6:
                System.out.println("Saturn"); break;
            case 7:
                System.out.println("Uranus"); break;
            case 8:
                System.out.println("Neptune"); break;
            default:
                System.out.println("Invalid Destination");
        }
    }
}

When you run the program you'll have to following on the screen:

The Planets
===================================
1. Mercury
2. Venus
3. The Earth
4. Mars
5. Jupiter
6. Saturn
7. Uranus
8. Neptune

Please choose your favorite destination: 3
Welcome to The Earth

How do I define a constant variable?

To define a constant in Java, use final modifier which combined with static modifier. The final modifier indicates that the value of this field cannot change.

If you change the value of the constant, you need to recompile the class to get the current value. Other feature in Java that provide similar functionality is enumeration (a list of named constants). You can simply create an enumeration by using the enum keyword.
package org.kodejava.example.fundametal;

public class ConstantDemo {
    public static void main(String[] args) {
        int sunday = DayConstant.SUNDAY;
        System.out.println("Sunday= " + sunday);

        String dozen = MeasureConstant.DOZEN;
        System.out.println("Dozen: " + dozen);
    }

}

class DayConstant {
    public final static int SUNDAY = 0;
    public final static int MONDAY = 1;
    public final static int TUESDAY = 2;
    public final static int WEDNESDAY = 3;
    public final static int THURSDAY = 4;
    public final static int FRIDAY = 5;
    public final static int SATURDAY = 6;
}

class MeasureConstant {
    final static String UNIT = "unit";
    final static String DOZEN = "dozen";
}

How do I use the return keyword in Java?

The return keyword is used to return from a method when its execution is complete. When a return statement is reached in a method, the program returns to the code that invoked it.

A method can return a value or reference type or does not return a value. If a method does not return a value, the method must be declared void and it doesn't need to contain a return statement.

If a method declare to return a value, then it must use the return statement within the body of method. The data type of the return value must match the method's declared return type.
package org.kodejava.example.fundametal;

public class ReturnDemo {

    public static void main(String[] args) {
        int z = ReturnDemo.calculate(2, 3);
        System.out.println("z = " + z);

        Dog dog = new Dog("Spaniel", "Doggie");
        System.out.println(dog.getDog());
    }

    public static int calculate(int x, int y) {
        //
        // return an int type value
        //
        return x + y;
    }

    public void print(){
        System.out.println("void method");

        //
        // it does not need to contain a return statement, but it
        // may do so
        //
        return;
    }

    public String getString(){
        return "return String type value";

        //
        // try to execute a statement after return a value will
        // cause a compile-time error.
        //
        String error = "error";
    }
}

class Dog {
    private String breed;
    private String name;

    Dog(String breed, String name) {
        this.breed = breed;
        this.name = name;
    }

    public Dog getDog() {
        //
        // return Dog type
        //
        return this;
    }

    public String toString(){
        return "breed: " + breed.concat("name: " + name);
    }
}

How do I use the while loop statement?

The code below demonstrate how to use the while loop statement. The while statement will check if its expression evaluates to true and execute the while statement block.

The program below will executes while the countDown value is bigger or equals to zero.
package org.kodejava.example.lang;

public class WhileDemo {
    public static void main(String[] args) {
        //
        // Start the count down from 10
        //
        int countDown = 10;

        //
        // Do the count down process while the value of
        // countDown is bigger or equals to zero.
        //
        while (countDown >= 0) {
            System.out.println(countDown);
            countDown--;

            try {
                //
                // Adds one second delay.
                //
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

How do I get constants name of an enum?

To get the constants name of an enumeration you can use the values() method of the enumeration type. This method return an array that contains a list of enumeration constants.
package org.kodejava.example.fundametal;

enum Month {
    JANUARY,
    FEBRUARY,
    MARCH,
    APRIL,
    MAY,
    JUNE,
    JULY,
    AUGUST,
    SEPTEMBER,
    OCTOBER,
    NOVEMBER,
    DECEMBER
}

public class EnumValuesTest {
    public static void main(String[] args) {
        //
        // values() method return an array that contains a list of the
        // enumeration constants.
        //
        Month[] months = Month.values();
        System.out.println("Month size: " + months.length);
        
        //
        // We can user for each statement to print each enumeration
        // constant.
        //
        for (Month month : Month.values()) {
            System.out.println("Month: " + month);
        }
    }
}

How do I use the do-while loop statement?

There is also a do-loop in the Java programming language. Instead of evaluating the expression at the beginning like the while loop does the do-while loop evaluates its expression at the end of the loop. Due to this the loop executes at least once during the program execution.
package org.kodejava.example.lang;

public class DoWhileDemo {
    public static void main(String[] args) {
        int i = 0;

        //
        // The do-while statement executes at least once because
        // the expression is checked at the end of the loop
        // process.
        //
        do {
            //
            // This block will be executed while i is smaller or
            // equals to 10.
            //
            System.out.println(i);
            i++;
        } while (i <= 10);
    }
}

The program prints the following result:

0
1
2
3
4
5
6
7
8
9
10

How do I create a class in Java?

A class is a specification or blueprint from which individual objects are created. A class contains fields that represent the object's states and methods that defines the operations that are possible on the objects of the class.

The file name that contains the definition of a class is always the same as the public class name and the extension is .java to identify that the file contains a Java source code.

A class has constructors, a special method that is used to create an instance or object of the class. When no constructor define a default constructor will be used. The constructor method have the same name with the class name without a return value. The constructors can have parameters that will be used to initialize object's states.

Here is a Person.java file that defines the Person class.
package org.kodejava.example.fundametal;

public class Person {
    private String name;
    private String title;
    private String address;

    /**
     * Constructor to create Person object
     */
    public Person() {

    }

    /**
     * Constructor with parameter
     *
     * @param name
     */
    public Person(String name) {
        this.name = name;
    }

    /**
     * Method to get the name of person
     *
     * @return name
     */
    public String getName() {
        return name;
    }

    /**
     * Method to set the name of person
     *
     * @param name
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * Method to get the title of person
     *
     * @return title
     */
    public String getTitle() {
        return title;
    }

    /**
     * Method to set the title of person
     *
     * @param title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * Method to get address of person
     *
     * @return address
     */
    public String getAddress() {
        return address;
    }

    /**
     * Method to set the address of person
     *
     * @param address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Method to get name with title of person
     *
     * @return nameTitle
     */
    public String getNameWithTitle() {
        String nameTitle;
        if (title != null) {
            nameTitle = name + ", " + title;
        } else {
            nameTitle = name;
        }
        return nameTitle;
    }

    /**
     * Method used to print the information of person
     */
    @Override
    public String toString() {
        return "Info [" +
                "name='" + name + '\'' +
                ", title='" + title + '\'' +
                ", address='" + address + '\'' +
                ']';
    }
}

Here is a ClassExample.java file that defines the ClassExample class that use the Person class
package org.kodejava.example.fundametal;

public class ClassExample {
    public static void main(String[] args) {
        Person person = new Person();
        person.setName("Andy");
        person.setTitle("MBA");
        person.setAddress("NY City");
        System.out.println(person);

        String nameTitle1 = person.getNameWithTitle();
        System.out.println("Name with title: " + nameTitle1);

        Person person2 = new Person("Sarah");
        String nameTitle2 = person2.getNameWithTitle();
        System.out.println("Name with title 2: " + nameTitle2);
    }
}

How do I use the this keyword in Java?

Every instance method has a variable with the name this that refers to the current object for which the method is being called. You can refer to any member of the current object from within an instance method or a constructor by using this keyword.

Each time an instance method is called, the this variable is set to reference the particular class object to which it is being applied. The code in the method will then relate to the specific members of the object referred to by this keyword.
package org.kodejava.example.fundamental;

public class RemoteControl {
    private String channelName;
    private int channelNum;
    private int minVolume;
    private int maxVolume;

    RemoteControl() {

    }

    RemoteControl(String channelName, int channelNum) {
        // 
        // use the this keyword to call another constructor in the 
        // same class
        //
        this(channelName, channelNum, 0, 0);  
    }

    RemoteControl(String channelName, int channelNum, int minVol, int maxVol) {
        this.channelName = channelName;
        this.channelNum = channelNum;
        this.minVolume = minVol;
        this.maxVolume = maxVol;
    }

    public void changeVolume(int x, int y) {
        this.minVolume = x;
        this.maxVolume = y;
    }

    public static void main(String[] args) {
        RemoteControl remote = new RemoteControl("ATV", 10);
        
        // 
        // when the following line is executed, the this variable in
        // changeVolume() is refer to remote object.
        //
        remote.changeVolume(0, 25);
    }
}

How do I use the final keyword in Java?

The final modifier is used to mark a class final so that it cannot inherited, to prevent a method being overridden, and to prevent changing the value of a variable. Arguments of a method if declared as final is also can not be modified within the method.
package org.kodejava.example.fundametal;

public class FinalExample {
    //
    // breed is declared final. 
    // can't change the value assigned to breed
    //
    public final String breed = "pig";   
    private int count = 0;

    // 
    // sound() method is declared final, so it can't be overridden
    //
    public final void sound() {     
        System.out.println("oink oink");
    }

    // 
    // number parameter is declared final. can't change the value 
    // assigned to number
    //
    public int count(final int number) {
        //
        // assign a value to number variable will cause a 
        // compile-time error
        //
        number = 1;
        
        count = +number;
        return count;
    }

    public static void main(String[] args) {
        FinalExample fe = new FinalExample();
        // 
        // assign a value to breed variable will cause a 
        // compile-time error
        //
        fe.breed = "dog";
        
        int number = fe.count(20);
    }
}

final class SubFinalExample extends FinalExample {

    //
    // try to override sound() method of superclass will cause a 
    // compile-time error
    //
    public void sound() {
         System.out.println("oink");
    }
}

//
// try to inherit a class that declared final will cause a 
// compile-time error
//
class OtherFinalExample extends SubFinalExample {
}

How do I use the boolean negation (!) operator in Java?

The ! operator is a logical compliment operator. The operator inverts the value of a boolean expression
package org.kodejava.example.fundametal;

public class NegationOperator {
    public static void main(String[] args) {
        //
        // negate the result of boolean expressions
        //
        boolean negate = !(2 < 3);
        boolean value = !false;

        System.out.println("result: " + negate);
        System.out.println("value : " + value);
    }
}

Here is the result of the program:

result: false
value : true

dimanche 6 mai 2012

How do I use the for loop statement?

The for loop can be use to iterate over a range of values. For instance if you want to iterate from zero to 10 or if you want to iterate through all the items of an array. Below you'll see two forms of a for loop. The first one is the general form of a for loop and the second one is an enhanced for loop that also known as the for..each loop.

The general form of for loop consists of three parts:
-----------------------------------------------------
for (initialization; termination; increment) {
....
}
-----------------------------------------------------
The initialization: it initializes the loop, it executed once at the beginning of the loop.
The termination: the loop executes as long as the termination evaluates to true.
The increment: it executed at the end of every loop, the expression can be either an increment or decrement.

package org.kodejava.example.lang;

public class ForDemo {
    public static void main(String[] args) {
        //
        // Do a loop from 0 to 10.
        //
        for (int i = 0; i <= 10; i++) {
            System.out.println("i = " + i);
        }

        //
        // Loop through all the array items.
        //
        int[] numbers = new int[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
        for (int number : numbers) {
            System.out.println("number = " + number);
        }
    }
}

The result of the program is:

i = 0
i = 1
i = 2
i = 3
i = 4
i = 5
i = 6
i = 7
i = 8
i = 9
i = 10
number = 0
number = 1
number = 2
number = 3
number = 4
number = 5
number = 6
number = 7
number = 8
number = 9
number = 10

How do I define a field in enum type?

As we know that Java enumeration type is powerful compared to enum implementation in other programming language. Basically enum is class typed so it can have constructors, methods and fields.

In the example below you'll see how a field is defined in an enumeration type. Because each constant value for the Fruit enum is a type of Fruit itself it will have its own price field. The price field holds a unique value for each constant such as APPLE, ORANGE, etc.

In the result you'll see that the constructor will be called for each constant value and initialize it with the value passed to the constructor.
package org.kodejava.example.fundametal;

enum Fruit {
    APPLE(1.5f), ORANGE(2), MANGGO(3.5f), GRAPE(5);

    private float price;

    Fruit(float price) {
        System.out.println("Name: " + this.name() + " initialized.");
        this.price = price;
    }

    public float getPrice() {
        return this.price;
    }
}

public class EnumFieldDemo {
    public static void main(String[] args) {
        //
        // Get the name and price of all enum constant value.
        //
        for (Fruit f : Fruit.values()) {
            System.out.println("Fruit = " + f.name() + "; Price = " + f.getPrice());
        }
    }
}

Our demo result is below:

Name: APPLE initialized.
Name: ORANGE initialized.
Name: MANGGO initialized.
Name: GRAPE initialized.
Fruit = APPLE; Price = 1.5
Fruit = ORANGE; Price = 2.0
Fruit = MANGGO; Price = 3.5
Fruit = GRAPE; Price = 5.0

How do I use the if-then-else statement?

The if-then-else control flow statement adds a secondary path to the if statement when the expression evaluates to false. When it evaluates to false the else block will be executed.

Below is the program that takes input of user test score and evaluates the score to get the corresponding grade.
package org.kodejava.example.lang;

import java.io.Console;

public class IfThenElseDemo {
    public static void main(String[] args) {
        //
        // Get an instance of system console for taking user
        // input.
        //
        Console c = System.console();

        int score = 0;
        String grade;

        System.out.print("Please enter your score: ");

        try {
            //
            // Take user score input and convert the input
            // value into number.
            //
            score = Integer.valueOf(c.readLine());
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        if (score >= 90) {
            grade = "A";
        } else if (score >= 80) {
            grade = "B";
        } else if (score >= 60) {
            grade = "C";
        } else if (score >= 50) {
            grade = "D";
        } else {
            grade = "F";
        }

        System.out.println("Grade = " + grade);
    }
}

-----------------------------------------------
When the program executed you'll need to input the test score and the program will give you the grade.

Please enter your score: 75
Grade = C

How do I count the occurrences of a number in an array?

package org.kodejava.example.lang;

import java.util.Map;
import java.util.HashMap;
import java.util.Iterator;

public class NumberOccurrenceInArray {
    public static void main(String[] args) {
        int[] numbers = new int[] {1, 8, 3, 4, 3, 2, 5, 7, 3, 1, 4, 5, 6, 4, 3};

        Map map = new HashMap();
        for (int i = 0; i < numbers.length; i++) {
            int key = numbers[i];
            if (map.containsKey(key)) {
                int occurrence = map.get(key);
                occurrence++;
                map.put(key, occurrence);
            } else {
                map.put(key, 1);
            }
        }

        Iterator iterator = map.keySet().iterator();
        while (iterator.hasNext()) {
            int key = (Integer) iterator.next();
            int occurrence = map.get(key);

            System.out.println(key + " occur " + occurrence + " time(s).");
        }
    }
}

The result are:

1 occur 2 time(s).
2 occur 1 time(s).
3 occur 4 time(s).
4 occur 3 time(s).
5 occur 2 time(s).
6 occur 1 time(s).
7 occur 1 time(s).
8 occur 1 time(s).

What is reference variable in Java?

The only way you can access an object is through a reference variable. A reference variable is declared to be of a specific type and that type can never be changed. Reference variables can be declared as static variables, instance variables, method parameters, or local variables.

A reference variable that is declared final can't ever be reassigned to refer to a different object. The data within the object can be modified, but the reference variable cannot be changed.
package org.kodejava.example.fundametal;

public class ReferenceDemo {
    public static void main(String[] args) {
        //
        // declaration of reference variable
        //
        Reference ref1, ref2;
        
        // 
        // ref3 is declared final, it will cause it can reassign 
        // or refer to different object
        //
        final Reference ref3; 

        // 
        // assign ref1 with object Reference
        //
        ref1 = new Reference("This is the first reference variable", 1);
        
        //
        // access method getNumber() of object Reference through 
        // variable ref1
        //
        int number = ref1.getNumber(); 
        System.out.println("number= " + number);

        // 
        // assign ref2 with object Reference
        //
        ref2 = new Reference("This is the second reference variable", 2);
        
        //
        // passing ref2 as method parameter of printText() method
        //
        ReferenceDemo.printText(ref2); 

        //
        // assign ref3 with object Reference
        //
        ref3 = new Reference("This is the third reference variable", 3);
        
        //
        // try to reassign ref3 will cause a compile-time error
        //
        //ref3 = new Reference("Try to reassign",3);

    }

    public static void printText(Reference reference) {
        String text = reference.getText();
        System.out.println(text);
    }
}

class Reference {
    private int number;
    private String text;

    Reference(String text, int number) {
        this.text = text;
        this.number = number;
    }

    public String getText() {
        return text;
    }

    public int getNumber() {
        return number;
    }
}

How do I use the ternary operator?

The ternary operator or conditional operator can be use as a short version of the if-then-else statement. When you have a simple if-then-else statement in your code that return a value you might use the ternary operator, it can make your code easier to read.

The ternary operator is written using the symbol of ?: and it has the following syntax:
-----------------------------------------
result = testCondition ? value1 : value2;
----------------------------------------
When the test condition evaluates to true the expression value1 will be returned else the expression value2 will be returned. The value1 or value2 is not only for a simple field or variable, it can be a call to a method for example. But it is advisable to use the ternary operator for a simple thing, because if you over do it, it will make your code harder to read.

Let's see the following code:
package org.kodejava.example.lang;

public class TernaryOperatorDemo {
    public static void main(String[] args) {
        int a = 10;
        int b = 20;

        //
        // Get the maximum value
        //
        int min = a < b ? a : b;

        //
        // The use of ternary operator above is an alternative
        // of the following if-then-else statement.
        //
        int minValue;
        if (a < b) {
            minValue = a;
        } else {
            minValue = b;
        }

        //
        // Get the minimum value.
        //
        int max = a > b ? a : b;

        //
        // Get the absolute value.
        //
        int abs = a < 0 ? -a : a;

        System.out.println("min      = " + min);
        System.out.println("minValue = " + minValue);
        System.out.println("max      = " + max);
        System.out.println("abs      = " + abs);
    }
}

How do I create custom exception class?

You can define your own exception class for your application specific purposes. The exception class is created by extending the java.lang.Exception class for checked exception or java.lang.RuntimeException for unchecked exception. By creating your own Exception classes, you could identify the problem more precisely.
package org.kodejava.example.fundametal;

public class CustomExceptionExample {
    public static void main(String[] args) {
        int x = 1, y = 0;

        try {
            int z = CustomExceptionExample.divide(x, y);
            System.out.println("z = " + z);
        } catch (DivideByZeroException e) {
            e.printStackTrace();
        }

    }

    public static int divide(int x, int y)
            throws DivideByZeroException {
        try {
            return (x / y);
        } catch (ArithmeticException e) {
            String m = x + " / " + y + ", trying to divide by zero";
            throw new DivideByZeroException(m, e);
        }
    }
}

class DivideByZeroException extends Exception {
    DivideByZeroException() {
    }

    DivideByZeroException(String message) {
        super(message);
    }

    DivideByZeroException(String message, Throwable cause) {
        super(message, cause);
    }
}

Best Web Hosting