Java Comments and Type Casting

Java Comments and Type Casting

Hey all! Hope you have understood the data types and variables in the previous article. Now it's time to move a step ahead. Today in this article we will cover Comments and Type Casting. So let's start with it. First, we will cover Java comments.

What are Comments? For a random person, comments are used to pass in lecture, But for programmers, comments are used to describe the purpose of a written code statement. In java, comments are given in the following ways:

For one-line comment '//' is used.

int i=1;   //This is one line comment

For multiline comment /*..........*/ is used.

int i=1; 
/* This is 
multiline comment
 */

That's all with comments. Now let's start with Type Casting.

What is Type Casting? Type Casting is used to convert one data type to another data type. Eg: int to double.

Type Casting is categorized into two types:-

  • Widening Casting: This casting is done automatically by the Java compiler. In this, a smaller data type is converted to a larger data type size. The following flow shows how casting is done.

byte--> short--> char --> int --> long --> float --> double

- Narrowing Casting: This casting is done manually. In this, a larger data type is converted to a smaller data type size. The following flow shows how casting is done.

double --> float --> long --> int --> char --> short --> byte

If you are getting confused, then don't worry below codes will help you to understand it properly.

  • Widening Casting:

    public class Main {
    public static void main(String[] args) {
    
           int intNumber=10;
          System.out.println(intNumber);       // Output:  10
    
          double doubleNumber = intNumber;   //Typecasting (Widening) Automatic casting from int to double
          System.out.println(doubleNumber);   // Output: 10.0
    
    }
    }
    
  • Narrow Casting:

public class Main {
  public static void main(String[] args) {

        double doubleNumber = 12.3d;   // Output:  12.3
        System.out.println(doubleNumber);

        int intNumber= (int) doubleNumber;  // Typecasting(Narrow) Manually : double to int
        System.out.println(intNumber);     // Output:  12

  }
}

Tip: In Narrow Casting, you have to type manually the data type in parentheses '( )' in front of the value or variable. In the above code, it is clearly mentioned: int intNumber= (int) doubleNumber; This converts a double data type number to an integer number.

Hope you have understood today's topic. Thanks for your time. Happy Programming!

Did you find this article valuable?

Support ProgrammingForEveryone by becoming a sponsor. Any amount is appreciated!