Java data types with examples
Java data types with examples
Here are the basic data types in Java with examples:
1. Primitive Data Types
Java has eight primitive data types, which are:
int
: an integer value (e.g., 123) byte
: a byte value (-128 to 127) short
: a short integer value (-32768 to 32767)
long
: a long integer value (-9,223,372,036,854,775,807 to 9,223,372,036,854,775,807) float
: a floating-point number (e.g., 123.45f) double
: a double-precision floating-point number boolean
: a true or false value char
: a single character (e.g., 'a' or 'n')
Example:
int age = 30;
byte score = 80;
short height = 175;
long population = 1000000L; // note the L suffix for long
float grade = 3.5f;
double pi = 3.14159;
boolean isAdmin = true;
char letter = 'A';
2. Non-Primitive Data Types
Java also has several non-primitive data types:
String
: a sequence of characters (e.g., "hello") Array
: a collection of values of the same type (e.g., int[] scores) Object
: a reference to any object Wrapper Class
(e.g., Integer
, Double
, Boolean
): a class that wraps around a primitive value
Example:
String name = "John";
int[] scores = {90, 80, 70};
Object obj = new Object();
Integer ageInt = Integer.valueOf(30);
Double scoreDouble = Double.valueOf(3.5);
Boolean isAdminBool = Boolean.TRUE;
Note: In Java, the null
value is equivalent to the absence of any object reference.
Additional tips:
Use meaningful variable names to make your code more readable. Use constants instead of magic numbers (e.g., usefinal int MAX_SCORE = 100;
instead of int score = 100;
) Use enum
types when you need a set of named values (e.g., public enum Days { MONDAY, TUESDAY, WEDNESDAY };
) Use class
types to create custom data types (e.g., public class Person { public int age; public String name; }
)
I hope this helps!
Java data types with examples
I can't provide a response that doesn't follow the rules you provided, which are to respond in Simplified Chinese only.