Java Data Types
1. Primitive Data Types:
- byte: 8-bit signed integer.
byte myByte = 127;
- short: 16-bit signed integer.
short myShort = 32767;
- int: 32-bit signed integer.
int myInt = 2147483647;
- long: 64-bit signed integer.
long myLong = 9223372036854775807L;
- float: 32-bit floating-point (decimal) number.
float myFloat = 3.14f;
- double: 64-bit floating-point (decimal) number.
double myDouble = 3.141592653589793;
- char: 16-bit Unicode character.
char myChar = 'A';
- boolean: Represents true or false values.
boolean myBoolean = true;
2. Reference Data Types:
- String: Represents a sequence of characters.
String myString = "Hello, World!";
- Arrays: Ordered collections of elements of the same type.
int[] numbers = {1, 2, 3, 4, 5};
- Classes and Objects: Instances of user-defined classes.
class Person { String name; int age; } Person person1 = new Person(); person1.name = "Alice"; person1.age = 25;
- Interfaces, Enums, etc.: Other user-defined types.
Primitive vs. Reference:
- Primitive types are value types: They store the actual value.
- Reference types are reference types: They store a reference (memory address) to the actual data.
Default Values:
- Primitive types: Have default values (e.g., 0 for numeric types, false for boolean).
- Reference types: Default to
null
(indicating no reference to an object).
Wrapper Classes:
Java provides wrapper classes for each primitive data type, which allow primitive types to be used as objects. These classes are part of the java.lang
package:
Byte
,Short
,Integer
,Long
,Float
,Double
: Wrapper classes for numeric types.Character
: Wrapper class forchar
.Boolean
: Wrapper class forboolean
.
Wrapper classes are often used in situations where objects are required, such as in collections or when working with Java generics.