DataTypes in Java(Part 1)

Java Data Types

Java Data Types

Data Type is nothing but the type of data we are storing in a variable.

  • Every variable in Java should have some type.
  • Each and every data type is already defined.
  • Every assignment is checked by the compiler.
  • Because of these reasons, Java is known as a Strictly Typed Language.

Interview Question

Q. Is Java a Pure Object-Oriented Programming Language?

No. Java supports OOP concepts but is not a pure OOP language because it has primitive data types and does not support features like operator overloading and multiple inheritance.

Primitive Data Types

  • Numeric
    • Integral: byte, short, int, long
    • Floating Point: float, double
  • Non Numeric
    • char
    • boolean

Except boolean and char, all remaining primitive data types are signed because they can represent both positive and negative values.

TypeSizeRange
byte1 byte-27 to 27-1 [-128 to 127]
short2 bytes-215 to 215-1 [-32768 to 32767]
int4 bytes-231 to 231-1
long8 bytes-263 to 263-1

byte

Size: 1 byte

Range: -128 to 127

byte b = 10;      // Valid
byte b = -127;    // Valid
byte b = 128;     // Compile Time Error
byte b = 10.3;    // Compile Time Error
byte b = true;    // Compile Time Error
byte b = "500";   // Compile Time Error

Use Case: Used while handling byte streams such as file and network I/O.

short

Size: 2 bytes

Range: -32768 to 32767

short s = 32767;   // Valid
short s = -32767;  // Valid
short s = 32768;   // Compile Time Error
short s = 10.3;    // Compile Time Error
short s = true;    // Compile Time Error
short s = "500";   // Compile Time Error

Most rarely used primitive type. Introduced when 8085 and 8086 processors were common.

int

Size: 4 bytes

Range: -2147483648 to 2147483647

int i = 2147483647;   // Valid
int i = -2147483647;  // Valid
int i = 21474836478;  // Compile Time Error
int i = true;         // Compile Time Error
int i = "500";        // Compile Time Error

Most commonly used data type in Java.

long

Use long when int is not enough to store very large values.

long l = 2147483647L;   // Valid
long l = -2147483648L;  // Valid
long l = true;          // Compile Time Error
long l = "500";         // Compile Time Error

Examples:

  • Distance travelled by light over a very long period.
  • Very large counters or file sizes.

Note

byte, short, int and long are used only for storing integral values. To represent decimal values, Java provides floating-point data types (float and double).

Next Blog

In the next article, we'll discuss Floating Point Data Types (float & double) and Non-Numeric Data Types (char & boolean) in detail.

Comments

Popular posts from this blog

Java Roadmap

Java OOPs Concepts Made Simple: A Complete Beginner-Friendly Guide (Part-2)

Identifiers