BhauAutomation

Data Types in Java

Data types in Java define the type of data a variable can store. Java supports both primitive and non-primitive data types, ensuring type safety and efficient memory management.

What are Data Types in Java?

Data types in Java specify the size and type of values a variable can hold. They help the compiler allocate memory and enforce type safety for operations.

Categories of Data Types

Java divides data types into two main categories:

Primitive Data Types

These are predefined by Java for simple values such as numbers, characters, and boolean values.

byte    → 1 byte, stores -128 to 127
short   → 2 bytes, stores -32,768 to 32,767
int     → 4 bytes, stores integers
long    → 8 bytes, stores large integers
float   → 4 bytes, single-precision decimal
double  → 8 bytes, double-precision decimal
char    → 2 bytes, single character
boolean → 1 bit, stores true/false
  

Non-Primitive Data Types

These are created by programmers for complex structures.

String     → Stores text
Arrays     → Collection of similar types
Classes    → Custom objects
Interfaces → Contract for classes
  

Example Program

public class DataTypesExample {
  public static void main(String[] args) {
    int age = 25;
    double salary = 45000.50;
    char grade = 'A';
    boolean isJavaFun = true;

    System.out.println("Age: " + age);
    System.out.println("Salary: " + salary);
    System.out.println("Grade: " + grade);
    System.out.println("Is Java Fun? " + isJavaFun);
  }
}
  

Output:

Age: 25
Salary: 45000.5
Grade: A
Is Java Fun? true
  

Best Practices for Data Types

Always select data types carefully for efficiency and readability:

- Use int for small numbers and long for large numbers.

- Use double for decimals unless precision is critical.

- Use String instead of char arrays for text.

- Avoid unnecessary type conversions to reduce memory overhead.