Introduce Java Data Types and give examples
Java is a statically typed programming language, which means that every variable must be declared with a data type before it can be used. Java has two main categories of data types: primitive data types and reference data types.
Java has eight primitive data types, which are the most basic data types built into the language. They are:
byte
byte b = 100;
short
short s = 10000;
int
int i = 100000;
long
long l = 100000L; // 'L' suffix indicates a long literal
float
float f = 10.5f; // 'f' suffix indicates a float literal
double
double d = 20.99;
char
char c = 'A';
boolean
true
or false
boolean isJavaFun = true;
Reference data types are used to refer to objects and arrays. They do not store the actual data but rather a reference (or address) to the data. Some common reference data types include:
String
String greeting = "Hello, World!";
Arrays
int[] numbers = {1, 2, 3, 4, 5};
Classes and Interfaces
class Person {
String name;
int age;
}
Person person = new Person();
person.name = "Alice";
person.age = 30;
In summary, Java's data types can be categorized into primitive types, which are the basic building blocks of data, and reference types, which are used to create complex data structures. Understanding these data types is essential for effective programming in Java.