Type casting, Constants and enumerations in Java

Type casting

Java supports the conversion of one type into another by using the type casting feature. Type casting can be of two types, which are as follows,

Implicit type casting

When data of one type is assigned to a variable of a similar or larger type, an implicit or automatic conversion from a smaller type to a larger type occurs. This is also called type promotion, in which even if one operand of an expression is the larger, the result of the whole expression is promoted to the larger type.

For example,

int num = 20; 
double numD = num; // assigning integer value to double type

Explicit type casting

Java supports conversion of a higher type to a lower type, however, at the cost of loss of precision. This is called explicit casting.

For example,

float numF = 45.65f; 
int num = (int) numF; // converting a float value to integer type

Here, the fractional part of the number numF will be lost and the result will be saved in the integer type variable num.

Constants

Java constants are variables whose values cannot change once they have been assigned. Constants are declared by using the final keyword.

Example,

final int discount = 10;

Here, the value of the discount variable is fixed to 10. It cannot be modified later since the variable is constant as indicated by the final keyword. When the final keyword is applied to methods, they cannot be overridden and if applied to a class, it cannot be extended.

Enumeration 

Enumeration is a class type that contains a collection of constant values. It can also contain instance variables and constructors. It is defined using the enum keyword.

Unlike a class that is instantiated by using the new operator, the enumeration is used by creating a variable of type enum, similar to a primitive type. Enumerations are generally used with decision-making constructs such as switch-case.

Example,

public class EnumDays {
  // Defining an enumeration of days of the week 
  enum Days {
    Sun,
    Mon,
    Tue,
    Wed,
    Thu,
    Fri,
    Sat
  }
  public static void main(String[] args) {
    // Declaring a variable of type Days 
    Days day;
    // Instantiating the enum Days 
    day = Days.Fri;
    // Printing the value of enum 
    System.out.println("Today is: " + day);
  }
}

Leave a Comment