Java Java Tutorial Java Methods Java Classes Java File Handling Java Reference



Java Data Types

Java is a strongly typed language, which means that every variable and expression has a type that is known at compile time. Java has two categories of data types: primitive data types and reference data types.

Primitive Data Types

Primitive data types are the most basic data types in Java. They are predefined by the language and are used to represent simple values. There are eight primitive data types in Java:

  • byte: 8-bit signed integer
  • short: 16-bit signed integer
  • int: 32-bit signed integer
  • long: 64-bit signed integer
  • float: 32-bit floating point number
  • double: 64-bit floating point number
  • char: 16-bit Unicode character
  • boolean: true or false

Primitive data types are stored directly in memory and are passed by value. This means that when you pass a primitive data type to a method, a copy of the value is passed, not a reference to the original value.

Here is an example of declaring and initializing primitive data types:


 

int x = 10;

double y = 3.14;

char c = 'a';

boolean b = true;

Reference Data Types

Reference data types are used to refer to objects. An object is an instance of a class, which is a blueprint for creating objects. Reference data types are created using the new keyword and are stored in the heap memory.

There are two types of reference data types in Java:

  • Class types
  • Array types

Class types are created using a class name and are used to create objects. Array types are used to create arrays of objects or primitive data types.

Here is an example of declaring and initializing a reference data type:


 

String str = new String("Hello World");

In this example, we are creating a new String object and assigning it to the str variable.

Conclusion

Java data types are an essential part of the language. Understanding the different types of data that can be used in Java is crucial for writing efficient and effective code. By using the correct data types, you can ensure that your code is optimized for performance and memory usage.

References

Activity