TIL : Java Primitive Data Type

Adam Sung Min Park·2022년 9월 24일
0
post-thumbnail

As a Java beginner, data type threw me off the window.
Now I realize how JavaScript was generous (or didn't really care what I was doing) when it comes to my "loose" programming skills.

Java has 7 primitive data types:

Byte , Short, Int, Long, Float, Double
(from most narrow to most wide)

Converting one primitive datatype into another is known as type casting (type conversion) in Java. You can cast the primitive datatypes in two ways namely, Widening and Narrowing.

Widening is when converting a lower datatype to a higher datatype.
Casting/conversion is done automatically, AKA "implicit type casting".
Datatypes have to be compatible.

When does the automatic type conversion happens?

either:

  • the data types are compatible
  • destination type is bigger than the source type

Example

public class WideningExample {
   public static void main(String args[]){
      char ch = 'C';
      int i = ch;
      System.out.println(i);
   }
}

Output

Integer value of the given character: 67

Narrowing is the opposite of widening and in this case, type casting and conversion is not done automatically. It needs to be done by using cast operator "(datatype)". AKA "explicit type casting"
Datatypes can be incompatible.

Example

import java.util.Scanner;
public class NarrowingExample {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter an integer value: ");
      int i = sc.nextInt();
      char ch = (char) i;
      System.out.println("Character value of the given integer: "+ch);
   }
}

Output

Enter an integer value:
67
Character value of the given integer: C

As you can see, in the case of narrowing, int i got casted into (char).

Rules

  1. If byte, short, int are used in math => result comes out in int.
  2. Single Long will turn the expression in Long.
  3. Float operand in expression will convert the whole expression in float.
  4. any operand is double, the result is double.
  5. Boolean cannot be converted to another type.
  6. Java does not allow conversion from double to int.
  7. conversion from long to int is also not possible.

Still really confused about the data casting, but now I am more sure about what I can do with my data and what I can't do.

0개의 댓글