Java Interview Questions
Java
Web DevelopmentBackendQuestion 6
What are the different data types available in Java?
Answer:
In Java, data types specify the type and size of data that can be stored in a variable. Java supports two categories of data types: primitive data types and reference data types.
Primitive Data Types
Primitive data types are predefined by the language and named by a reserved keyword. There are 8 primitive data types in Java:
-
byte
- Size: 8-bit
- Range: -128 to 127
- Example:
byte b = 100;
-
short
- Size: 16-bit
- Range: -32,768 to 32,767
- Example:
short s = 10000;
-
int
- Size: 32-bit
- Range: -2^31 to 2^31 - 1
- Example:
int i = 100000;
-
long
- Size: 64-bit
- Range: -2^63 to 2^63 - 1
- Example:
long l = 100000L;
-
float
- Size: 32-bit floating point
- Range: approximately Β±3.40282347E+38F (6-7 significant decimal digits)
- Example:
float f = 10.5f;
-
double
- Size: 64-bit floating point
- Range: approximately Β±1.79769313486231570E+308 (15 significant decimal digits)
- Example:
double d = 20.5;
-
char
- Size: 16-bit Unicode character
- Range: '\u0000' (or 0) to '\uffff' (or 65,535)
- Example:
char c = 'A';
-
boolean
- Size: not precisely defined, typically a single bit
- Values:
true
orfalse
- Example:
boolean b = true;
Reference Data Types
Reference data types are objects that are instances of classes. They store references (addresses) to the actual data, rather than the data itself. Reference types include:
-
Classes
- Used to define objects that encapsulate data and methods.
- Example:
class Car { String model; int year; } Car myCar = new Car(); myCar.model = "Toyota"; myCar.year = 2020;
-
Interfaces
- Used to define abstract methods that classes can implement.
- Example:
interface Vehicle { void start(); } class Car implements Vehicle { public void start() { System.out.println("Car started."); } } Vehicle myCar = new Car(); myCar.start(); // Output: Car started.
-
Arrays
- Containers that hold fixed-size sequential collections of elements of the same type.
- Example:
int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers[0]); // Output: 1
-
Enums
- Special classes that represent a group of constants (unchangeable variables).
- Example:
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } Day today = Day.MONDAY; System.out.println(today); // Output: MONDAY
Summary
- Primitive Data Types: byte, short, int, long, float, double, char, boolean.
- Reference Data Types: Class, Interface, Array, Enum.
Primitive data types store actual values, while reference data types store references to the objects. Understanding these data types is crucial for efficient memory management and effective Java programming.