Data Types in Java
Java is a statically-typed language, which means that variables must be declared with a specific data type before they can be used. Java provides a range of primitive data types and allows you to create complex data types through classes and interfaces.
Here are the basic data types in Java:
Primitive Data Types:
byte: A 1-byte integer with a range of -128 to 127.
short: A 2-byte integer with a range of -32,768 to 32,767.
int: A 4-byte integer with a range of -2^31 to 2^31 - 1.
long: An 8-byte integer with a range of -2^63 to 2^63 - 1.
float: A 4-byte floating-point number used for decimal values.
double: An 8-byte floating-point number used for decimal values (usually preferred over
floatdue to higher precision).char: A 2-byte character representing a single Unicode character.
boolean: Represents true or false values.
Reference Data Types:
Object: The root class for all classes in Java. Every class in Java is a subclass of
Object.String: A sequence of characters. Although it is a reference type, Java provides special syntax to create and manipulate strings.
Array: A data structure that stores elements of the same type in a contiguous memory location. Arrays are reference types.
Class Types: Any user-defined class, interface, or enumeration is a reference type.
Interface Types: Interfaces can be used as data types for objects that implement them.
Enumeration Types: A special data type used to define a set of constants.
Primitive Wrapper Classes: Java provides wrapper classes for each primitive data type (e.g.,
Integer,Double,Character) that allow you to treat primitives as objects.User-Defined Types: You can create your own custom data types by defining classes and interfaces.
Here's an example of declaring variables with different data types:
int age = 30;
double salary = 50000.50;
char grade = 'A';
boolean isEmployed = true;
String name = "John Doe";
int[] numbers = {1, 2, 3, 4, 5}; // An array of integers
It's important to choose the appropriate data type for your variables based on the data they will store. Using the correct data type ensures efficient memory usage and prevents data type-related errors.
Comments
Post a Comment