Java Basic Datatypes
Java - Basic Data Types
Section titled “Java - Basic Data Types”Variables are fundamental to programming. Think of them as named containers in your computer’s memory where you can store information (values). When you declare a variable, you tell Java the variable’s name and the type of data it will hold. This reserves memory space.
The data type determines how much memory is allocated and what kind of data (like whole numbers, decimal numbers, or characters) can be stored. Java has two main categories of data types:
- Primitive Data Types: The basic building blocks for data.
- Reference Data Types: Used to refer to objects (instances of classes).
Primitive Data Types
Section titled “Primitive Data Types”Java provides eight primitive data types. These are built directly into the language and are identified by keywords. They store the actual value directly in the variable’s allocated memory.
Numeric Types (Integers)
Section titled “Numeric Types (Integers)”- Size: 8-bit signed two’s complement integer.
- Range: -128 to 127.
- Default Value: 0.
- Use Case: Saves memory in large arrays when the values are within the byte range. Useful for stream/file data.
- Example:
byte smallNumber = 100; byte negativeByte = -50;
short:
Section titled “short:”- Size: 16-bit signed two’s complement integer.
- Range: -32,768 to 32,767.
- Default Value: 0.
- Use Case: Memory saving like
byte, but for a wider range. Less common thanint. - Example:
short mediumNumber = 10000; short negativeShort = -20000;
- Size: 32-bit signed two’s complement integer.
- Range: -2,147,483,648 to 2,147,483,647 (approximately +/- 2 billion).
- Default Value: 0.
- Use Case: The most commonly used integer type. Generally the default choice for whole numbers unless memory is a critical concern or a larger range is needed.
- Example:
int standardNumber = 100000; int negativeInt = -200000;
- Size: 64-bit signed two’s complement integer.
- Range: -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 (approximately +/- 9 quintillion).
- Default Value: 0L.
- Use Case: When you need a range wider than
int, for example, timestamps in milliseconds or large counters. - Note: Append an ‘L’ or ‘l’ to the number to indicate it’s a long literal.
- Example:
long largeNumber = 100000L; long veryLargeNumber = -9000000000L;
Numeric Types (Floating-Point)
Section titled “Numeric Types (Floating-Point)”float:
Section titled “float:”- Size: Single-precision 32-bit IEEE 754 floating point.
- Default Value: 0.0f.
- Use Case: Saves memory in large arrays of floating-point numbers compared to
double. Not suitable for precise values like currency due to potential rounding errors. - Note: Append an ‘f’ or ‘F’ to the number to indicate it’s a float literal.
- Example:
float percentage = 98.5f; float temperature = -10.2F;
double:
Section titled “double:”- Size: Double-precision 64-bit IEEE 754 floating point.
- Default Value: 0.0d.
- Use Case: The default choice for decimal values. Offers a larger range and more precision than
float. Still not suitable for exact financial calculations. - Note: Decimal literals are treated as
doubleby default (a ‘d’ or ‘D’ suffix is optional). - Example:
double price = 199.99; double piApproximation = 3.1415926535;
Important Note on Precision:
For calculations requiring high precision, especially financial ones, avoid float and double. Use the java.math.BigDecimal class instead. It provides exact representation of decimal numbers.
Other Primitive Types
Section titled “Other Primitive Types”boolean:
Section titled “boolean:”- Represents one bit of information.
- Possible Values: Only
trueorfalse. - Default Value:
false. - Use Case: Used for flags or conditions that track true/false states (e.g., in
ifstatements, loops). - Example:
boolean isLoggedIn = true; boolean isComplete = false;
- Size: Single 16-bit Unicode character.
- Range: ‘\u0000’ (0) to ‘\uffff’ (65,535).
- Default Value: ‘\u0000’.
- Use Case: Stores single characters. Can also store special characters using escape sequences.
- Note: Character literals are enclosed in single quotes.
- Example:
char grade = 'A'; char initial = 'J'; char newlineChar = '\n';
Reference Data Types (Objects)
Section titled “Reference Data Types (Objects)”Unlike primitive types that store values directly, reference variables store the memory address where an object (an instance of a class) is located. Think of it like having a remote control (reference variable) that points to the actual TV (object) in memory.
- Created using class constructors (
new ClassName(...)). - Used to access the object’s fields (state) and methods (behavior).
- Can be assigned to variables of the declared type or a compatible supertype.
- Includes class objects (like
String,Scanner, or custom classes likeEmployee,Dog), arrays, interfaces, and enums. - Default Value:
null(meaning the variable doesn’t currently point to any object). - Example:
String greeting = "Hello"; // String object Dog myDog = new Dog("Buddy"); // Custom Dog objectint[] numbers = new int[10]; // Array object
Java Literals
Section titled “Java Literals”A literal is a fixed value represented directly in the source code, without requiring computation. Literals can be assigned to variables.
Examples:
int age = 30; // Integer literaldouble weight = 65.5; // Floating-point literalboolean active = true; // Boolean literalchar firstInitial = 'C';// Character literalString name = "Alice"; // String literalInteger literals (byte, short, int, long) can be expressed in different number systems:
- Decimal (Base 10): Standard numbers (e.g.,
100). - Hexadecimal (Base 16): Prefix
0xor0X(e.g.,0x64is 100). - Octal (Base 8): Prefix
0(e.g.,0144is 100). Use with caution as it’s easy to mistake for decimal. - Binary (Base 2, Java 7+): Prefix
0bor0B(e.g.,0b1100100is 100).
int decimalValue = 100;int hexValue = 0x64;int octalValue = 0144; // Be careful with leading zeros!int binaryValue = 0b1100100;long socialSecurity = 123_45_6789L; // Underscores (Java 7+) improve readabilityString literals are sequences of characters enclosed in double quotes ("").
"Hello, World!""Line one\nLine two" // \n is a newline escape sequence"He said, \"Java is fun!\"" // \" escapes the double quoteString and char literals support Unicode characters and escape sequences:
char copyrightSymbol = '\u00A9'; // © using Unicode escapeString greeting = "\u0048\u0065\u006C\u006C\u006F"; // "Hello"Common Escape Sequences:
Section titled “Common Escape Sequences:”| Notation | Character Represented |
|---|---|
\n | Newline |
\r | Carriage return |
\f | Form feed |
\b | Backspace |
\t | Tab |
\" | Double quote |
\' | Single quote |
\\ | Backslash |
\uXXXX | Unicode character (hexadecimal XXXX) |
Local Variable Type Inference (var)
Section titled “Local Variable Type Inference (var)”Since Java 10, you can use the var keyword for declaring local variables (variables inside methods). The compiler infers the type based on the assigned value. This can make code more concise, but use it judiciously.
var message = "Hello from var!"; // Compiler infers type Stringvar count = 10; // Compiler infers type intvar list = new java.util.ArrayList<String>(); // Infers ArrayList<String>Note: var is not a keyword but a reserved type name. It cannot be used for fields, method parameters, or return types. For beginners, explicitly declaring types is often clearer.
What’s Next?
Section titled “What’s Next?”Now that you understand the basic data types, the next chapter delves into different types of variables (local, instance, static) and their scope, explaining where and how they are used within Java classes and methods.