Friday, June 5, 2020

Casting And Type Conversion in Java

type_conversion_and_casting_java

In the Java programming language, Type Casting is used to determine and change a value from one data type to another data type. For example, if we have variable A with Integer data type, then we can determine the value of variable A to be float data type or vice versa. There are 2 types of Type Casting in Java called Implicit Casting and Explicit Casting.

Both are used to change the value of one data type variable. The difference between the two types is, Implicit is used to change from small data types to large data types, for example, Bytes to Long or Short to Double.

Widening Conversion (Implicit Casting)


Implicit Casting is used to convert values from small data types to large data types, such as the following:
  • From short data types to int, long, float, or double data types
  • From int data types into long, float, or double data types
  • From char data types into int, long, float, or double data types
  • From float data types into double data types
  • From long data types or into float or double data types
  • From byte data type to short, int, long, float, or double data types
Example of an Implicit Casting program in Java:


public class HelloWorld {
    public static void main(String[] args){
        
        short data1 = 457;
        double double_data = data1; //short to double
        
        char data2 = 'W';
        long long_data = data2;//char to long
        
        int  data3 = 456;
        float int_data = data3;// int to float
        
        byte data4 = 127;
        long long_data2 = data4;//byte to long
        
        float data5 = 565.3f;
        double double_data2 = data5;//float to double
        
        System.out.println("Short to Double: "+ double_data);
        System.out.println("Char to Long: "+long_data);
        System.out.println("Int to Float: "+int_data);
        System.out.println("Byte to Long: "+long_data2);
        System.out.println("Float to Double: "+double_data2);
    }
}

Result:

implicit_casting_java

Narrow Conversion (Explicit Casting)


Explicit Casting is the opposite of Implicit Casting, which is to change values from large data types to small data types, such as:
  • From short data types to bytes or char
  • From double data types to bytes, short, char, int, long or float
  • From char data types to bytes or short
  • From long data types to bytes, short, char or int
  • From int data types to bytes, short, or char
  • From float data type to byte, short, char, int or long
  • From byte data type into the char data type

Examples of Explicit Casting programs in Java:


public class HelloWorld {
    public static void main(String[] args){
        
        short data1 = 3;
        char char_data = (char) data1; //short to char
        
        long data2 = 246447;
        byte byte_data = (byte) data2;//long to byte
        
        int  data3 = 34;
        char char_data2 = (char) data3;// int to char
        
        char data4 = 1;
        short short_data2 = (short) data4;//char to short
        
        double data5 = 345.3;
        float float_data2 = (float) data5;//double to float
        
        System.out.println("Short to Char: "+ char_data);
        System.out.println("Long to Byte: "+byte_data);
        System.out.println("Int to Char: "+char_data2);
        System.out.println("Char to Short: "+short_data2);
        System.out.println("Double to Float: "+float_data2);
    }
}

Result:

explicit_casting_java

What is important in the process of casting and conversion in Java is known beforehand about the type of data in java.

Wednesday, June 3, 2020

Understanding Exception Handling In Java Programming With Examples

exception_handling_in_java


If the Java Virtual Machine (JVM) detects that an operation is not possible, a runtime error will appear during the program runs.

For example, if you are accessing an array using the index out of the bonds, then you will get a runtime error ArrayIndexOutOfBoundsException. Or suppose when you enter a value of type double, but your program is designed for integer values, then you will get a runtime error InputMismatchException.

In Java programs, this runtime error will be thrown as exceptions. These exceptions are also objects that represent an error or condition that prevents the execution from running normally. If an exception is not handled, then the program will stop abnormally.

The question is, how do you handle exceptions so that the java program can continue or stop properly?

Exception handling is an important part of writing powerful Java applications.

Therefore, exception handling is a non-functional requirement for any application. Aims to deal with conditions where errors occur properly such as resources that are not available, invalid input, null input, and so forth.

Java provides several features for handling exceptions built-in in the form of keyword try, catch and finally. The Java programming language also allows you to create new exceptions and throw them using keyword throw and throws.

Exception Handling Overview


Exceptions are thrown from a method. The caller of the method can catch and handle the exception.

To understand handing exceptions, see the sample code below:

import java.util.Scanner;

public class Division {
 
 public static void main(String[] args) {
  
  Scanner input = new Scanner (System.in);
  
  // ask the user to enter two integer numbers
  System.out.println("Enter two integers: ");
  int number1 = input.nextInt();
  int number2 = input.nextInt();
  
  System.out.println("Results of " + number1 + " divided " + number2 
    + " is: " + (number1/number2));
  
 }

}

In the java code above, when the user enters the number 0 in the second number, then a runtime error will occur because the integer cannot be divided by the number 0. For example the output example below:

number_exception_java

A simple way to overcome this problem is to use the conditional if, as in the following example:

import java.util.Scanner;

public class DivisionWithIf{
 
public static void main(String[] args) {
  
  Scanner input = new Scanner (System.in);
  
  // ask the user to enter two integer numbers
  System.out.println("Enter two integers: ");
  int number1 = input.nextInt();
  int number2 = input.nextInt();
  
  if(number2 != 0){
  System.out.println("Results of " + number1 + " divided " + number2 
    + " is: " + (number1/number2));
  }else{
   System.out.println("The divisor number cannot be zero!");
  }
 }

}

Example output:

exception_with_if_java

Before going any further in java exception handling, the above code can be rewritten using a method for division like the example below:

import java.util.Scanner;

public class DivisionWithMethod {
 
 // Static method for calculating division results
 public static int calculateDivision(int number1, int number2){
  if(number2 == 0){
                 System.out.println("The divisor number cannot be zero!");
   System.exit(1);
  }
  return (number1/number2);
 }
 
 public static void main(String[] args) {
  Scanner input = new Scanner (System.in);
  
  // ask the user to enter two integer numbers
  System.out.println("Enter two integers: ");
  int number1 = input.nextInt();
  int number2 = input.nextInt();
  
  int result = calculateDivision(number1, number2);
  
  System.out.println("Results of " + number1 + " divided " + number2 
    + " is: " + (number1/number2));
 }

}

In the above code, the method inline (6-12) will return the results of the division of two integers. If the second number is 0 as the divisor, the program will be terminated on line 9.

This is a problem, because you shouldn't have created a method to stop the program.

So, how can a method notify the caller that an exception has occurred? Java allows a method to throw an exception that can be caught and handled by the caller.

So the code above can be rewritten as:

import java.util.Scanner;

public class DivisionWithException {
 
 // Static method for calculating division results
 public static int calculateDivision(int number1, int number2){
  if(number2 == 0){
    
   throw new ArithmeticException("The divisor number cannot be zero!");
  }
  return (number1/number2);
 }
  
 public static void main(String[] args) {
  
  Scanner input = new Scanner(System.in);
  
  // ask the user to enter two integer numbers
  System.out.println("Enter two integers: ");
  int number1 = input.nextInt();
  int number2 = input.nextInt();
  
  try{
   int result = calculateDivision(number1, number2);
   
   System.out.println("Results of " + number1 + " divided " + number2 
    + " is: " + (number1/number2));
  }
  
   catch (ArithmeticException exception){
    System.out.println("Exception: An integer "
      + "cannot be divided by zero!");
  }
  
  System.out.println("Program execution continues ...");
 }

}

In the java code above, if the second number or the divisor is 0, then the method will throw an exception at line 9:

throw new ArithmeticException ("The divisor number cannot be zero!");

The value threw, in this case, is new ArithmeticException ("The divisor number cannot be zero!"); called an exception. Whereas the execution of the throw statement is called throwing an exception.

An exception object is an object created from the Exception class. In this case, the Exception class is java.lang.ArithmeticException.

With a hierarchy:

java.lang.Object 
      java.lang.Throwable 
          java.lang.Exception 
              java.lang.RuntimeException 
                  java.lang.ArithmeticException

ArithmeticException (String s) constructor is called to construct an exception object. Where String s is a message that explains about exceptions.

When an exception is thrown, then the normal execution flow will be interrupted. Like the term "throw an exception" which means to pass an exception from one place to another.

Try And Catch Blocks


The statement to call the method is contained in a try and catch block. The try block on lines 23 - 28 contains the code to run under normal circumstances.

Meanwhile, the exception will be caught by the catch block on lines 30 - 33. So the code contained in the catch block aims to handle the exception.

Then statement on line 35 will be executed after the catch block is executed.

This throw statement can be analogous to method calls. However, it is not a method that is called, but a catch block.

In this case, a catch block is like a method definition with parameters that match the type of value being thrown. Unlike the method, however, after the catch block is executed, the program control does not return to the throw statement, but will continue to execute the next statement after the catch block.

Block Catch Parameter


On line 30:

catch (ArithmeticException exception)

An exception identifier acts the same as a parameter in a method. Thus, this parameter is referred to as a catch block parameter.

The ArithmeticException above, which was written before the exception is to determine what types of exceptions can be caught by the catch block. Once an exception is captured, then you can access the value thrown from this parameter in the body of the catch block.

In summary, a template of the try-throw-catch block will look like below:

try {
  //Code to run;
  //A statement or method that might throw an exception;
  //Other codes to run;
}
catch (type exception) {
  //Code for processing exceptions;
}

An exception might be raised directly by using the throw statement inside the try block. Or you can also use methods that can throw exceptions.

On line 24, the main method calls calculateDivision(). If the calculateDivision() method runs normally, it returns a value to the caller.

Conversely, if the calculateDivision method finds an exception, it throws the exception back to the caller. Then the catch block of the caller will handle the exception.

Advantages of Using Exception Handling in Java


Now you can see the benefits of using exception handling in java. The advantage is that it allows a method to throw an exception at the caller and allows the caller to handle the exception.

Without these capabilities, the method that is called itself must handle exceptions or terminate the program. Often the method called does not know what to do when an error occurs. This is a typical case for library methods. The library method can detect errors but only the caller can identify what to do when an error occurs.

The main benefit of exception handling is that it separates detection of errors from handling errors.

Many library methods throw exceptions. Following is an example of handling InputMismatchException when reading an input.

import java.util.Scanner;

public class TestInputMismatchException {
 
 public static void main(String[] args) {
  Scanner input = new Scanner(System.in);
  boolean continueInput = true;
  
  do{
   try{
    System.out.print("Enter an integer: ");
    int number = input.nextInt();
    
    //Showing results
    System.out.println("The number entered is "+ number);
    continueInput = false;
   }
   
   catch(InputMismatchException ex){
    System.out.println ("Try again. (Invalid input: An integer is required)");
    input.nextLine();
   }
  }while(continueInput);

 }
}

When executing input.nextInt() on line 12, an InputMismatchException occurs if the user enters a number that is not an integer.

For example, the value 2.9 is inputted, then InputMismatchException occurs and program control will be moved to the 19-22 catch line block. The statements in the block will be executed.

The input.nextLine() statement on line 21 will destroy the current input line and then the user can input the new line.

The variable continueInput controls the loop. The initial value is true on line 7 and when a valid value is received, then it converted to false on line 16. When a valid input value is received, there is no need to continue input numbers.