Data types in Java define the type of a variable. They specify what kind of data a variable can hold. Java is a strongly-typed language, meaning that each variable must be declared with a specific data type. Java provides two types of data types: Primitive and Non-Primitive data types.
Primitive data types are the most basic types of data available in Java. They represent single values and are predefined by the language. Java supports eight primitive data types:
true
or false
// Example of Primitive Data Types in Java public class DataTypesExample { public static void main(String[] args) { byte b = 100; // 8-bit integer short s = 5000; // 16-bit integer int i = 100000; // 32-bit integer long l = 1000000000L; // 64-bit integer (L is added to specify long) float f = 5.75f; // 32-bit floating point (f is added) double d = 19.99; // 64-bit floating point char c = 'A'; // 16-bit Unicode character boolean isJavaFun = true; // boolean value System.out.println("Byte value: " + b); System.out.println("Short value: " + s); System.out.println("Int value: " + i); System.out.println("Long value: " + l); System.out.println("Float value: " + f); System.out.println("Double value: " + d); System.out.println("Char value: " + c); System.out.println("Is Java fun? " + isJavaFun); } }
Non-primitive data types, also known as reference types, are used to store references to objects. These are more complex data types and are defined by the user. Examples include:
// Example of Non-Primitive Data Types in Java public class NonPrimitiveExample { public static void main(String[] args) { String greeting = "Hello, World!"; // String (non-primitive) int[] numbers = {1, 2, 3, 4, 5}; // Array of integers (non-primitive) System.out.println("Greeting message: " + greeting); System.out.println("Array elements: "); for (int num : numbers) { System.out.print(num + " "); } } }
int
defaults to 0
, and a boolean
defaults to false
.int
for normal integer operations, and use long
if you need larger values.
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!