Give me some Java Data Types Example
In Java, data types are divided into two main categories: primitive data types and reference data types. Here are examples of each:
int: Represents a 32-bit signed integer.
int age = 25;
double: Represents a double-precision 64-bit floating point.
double salary = 55000.50;
char: Represents a single 16-bit Unicode character.
char initial = 'A';
boolean: Represents a value that can be either true
or false
.
boolean isJavaFun = true;
float: Represents a single-precision 32-bit floating point.
float pi = 3.14f; // Note the 'f' suffix
byte: Represents an 8-bit signed integer.
byte smallNumber = 100;
short: Represents a 16-bit signed integer.
short mediumNumber = 10000;
long: Represents a 64-bit signed integer.
long largeNumber = 100000L; // Note the 'L' suffix
String: Represents a sequence of characters.
String greeting = "Hello, World!";
Arrays: A collection of elements of the same type.
int[] numbers = {1, 2, 3, 4, 5};
Classes: User-defined data types that can contain fields and methods.
class Person {
String name;
int age;
Person(String name, int age) {
this.name = name;
this.age = age;
}
}
Person person = new Person("Alice", 30);
Interfaces: A reference type in Java, similar to a class, that can contain only constants, method signatures, default methods, static methods, and nested types.
interface Animal {
void makeSound();
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Woof");
}
}
Collections: Such as ArrayList
, HashMap
, etc.
import java.util.ArrayList;
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
These examples illustrate the basic data types available in Java, both primitive and reference types. Each type serves different purposes and is used based on the requirements of the program.