DEV Community

Adam Sung Min Park
Adam Sung Min Park

Posted on

TIL : Java Data Type

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);
   }
}
Enter fullscreen mode Exit fullscreen mode

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);
   }
}
Enter fullscreen mode Exit fullscreen mode

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).

Image description

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.

Top comments (2)

Collapse
 
thomasbnt profile image
Thomas Bnt

Hello ! Don't hesitate to put colors on your codeblock like this example for have to have a better understanding of your code 😎

console.log('Hello world!');
Enter fullscreen mode Exit fullscreen mode

Example of how to add colors and syntax in codeblocks

Collapse
 
adamsteradam profile image
Adam Sung Min Park

Thanks! kinda new to this platform so i need to learn more about how to use features haha anyways will do :)