Java Data Types, Literals, Variables, Type Conversion & Casting
Java Data Types
Java's type system forms the foundation of its strong typing mechanism, which helps catch errors at compile time rather than runtime. Java data types are divided into two main categories:
Primitive Data Types
Java features eight built-in primitive data types that store simple values:
byte: 8-bit signed integer (-128 to 127)
byte smallNumber = 100;
short: 16-bit signed integer (-32,768 to 32,767)
short mediumNumber = 20000;
int: 32-bit signed integer (-2,147,483,648 to 2,147,483,647)
int standardNumber = 1000000;
long bigNumber = 9223372036854775807L; // Note the 'L' suffix
float: 32-bit floating-point number
float decimalNumber = 3.14f; // Note the 'f' suffix
double: 64-bit floating-point number (higher precision)
double preciseDecimal = 3.14159265359;
char: 16-bit Unicode character
char singleCharacter = 'A';
boolean: Represents true or false values
boolean isJavaFun = true;
Reference Data Types
Reference types store references to objects rather than the actual values:
Classes: User-defined types that serve as blueprints for objects
String name = "Java Programming";
Arrays: Collections of similar data types
int[] numbers = {1, 2, 3, 4, 5};
Interfaces: Abstract types that specify behavior
List<String> programmingLanguages = new ArrayList<>();
Java Literals: Fixed Values in Your Code
Literals are fixed values that appear directly in your code. Java supports several types of literals:
Integer Literals
int decimalLiteral = 42; // Decimal (base 10)
int octalLiteral = 052; // Octal (base 8) - prefix with 0int hexadecimalLiteral = 0x2A; // Hexadecimal (base 16) - prefix with 0xint binaryLiteral = 0b101010; // Binary (base 2) - prefix with 0b
Floating-Point Literals
double standardDouble = 3.14;
double scientificNotation = 3.14e2; // 3.14 × 10² = 314.0
float floatLiteral = 3.14f; // 'f' suffix for float
Character Literals
char regularChar = 'A';
char unicodeChar = '\u0041'; // Unicode representation of 'A'char escape
Char = '\n'; // Newline character
String Literals
String message = "Hello, Java!";
String multiline = """
This is a multi-line
text block in Java 15+
"""; // Text blocks (Java 15+)
boolean isTrue = true;
boolean isFalse = false;
The Null Literal
String emptyReference = null; // Represents absence of a value
Java Variables
Variables are named storage locations that hold values which can be changed during program execution.
Variable Declaration and Initialization
// Declaration
int age;
// Initialization
age = 25;
// Combined declaration and initialization
double salary = 50000.50;
Variable Naming Conventions
- Start with a letter, underscore (_), or dollar sign ($)
- Cannot start with a number
- Can include letters, numbers, underscores, and dollar signs
- Case-sensitive
- Cannot use Java reserved keywords
// Good variable names
int studentCount;
String firstName;
double hourlyRate;
// Poor variable names
int a; // Not descriptive
String s; // Too short
Variable Types Based on Scope
Instance Variables (Non-Static Fields)
public class Person {
String name; // Instance variable
int age; // Instance variable
}
Class Variables (Static Fields)
public class Constants {
static final double PI = 3.14159; // Class variable
}
Local Variables
public void calculateArea() {
double radius = 5.0; // Local variable
double area = Math.PI * radius * radius;
}
Parameters
public void setName(String newName) {
// Parameter
this.name = newName;
}Type Conversion in Java: Changing Data Types
Type conversion is the process of converting a value from one data type to another.
Implicit Type Conversion (Widening)
Java automatically performs widening conversions when there's no risk of data loss:
byte smallNumber = 10;
int largerNumber = smallNumber; // Implicit conversion from byte to int
int intValue = 100;
long longValue = intValue; // int to long
long longNum = 200;
float floatNum = longNum; // long to float
float floatVal = 300.5f;
double doubleVal = floatVal; // float to double
The widening conversion follows this hierarchy:
byte → short → int → long → float → double
Explicit Type Conversion (Narrowing)
When converting from a larger data type to a smaller one, explicit casting is required to acknowledge potential data loss:
double largeDouble = 100.56;
int smallerInt = (int) largeDouble; // Explicit cast, result: 100 (decimal part lost)
int largeInt = 200;
byte smallByte = (byte) largeInt; // Explicit cast, potential overflow
long bigLong = 9876543210L;
int smallerInt2 = (int) bigLong; // Explicit cast, potential data loss
Type Casting in Java: Reference Type Conversions
Type casting with objects involves converting between compatible reference types.
Upcasting (Widening Reference Conversion)
Converting a subclass reference to a superclass reference:
// Assuming Dog extends Animal
Dog myDog = new Dog();
Animal myAnimal = myDog; // Upcasting, no explicit cast needed
Downcasting (Narrowing Reference Conversion)
Converting a superclass reference to a subclass reference:
Animal genericAnimal = new Dog();
Dog specificDog = (Dog) genericAnimal; // Downcasting, explicit cast required
// Safety check with instanceof
if (genericAnimal instanceof Dog) {
Dog safeDog = (Dog) genericAnimal;
}
Pattern Matching for instanceof (Java 16+)
if (genericAnimal instanceof Dog specificDog) {
// specificDog is already cast and available here
specificDog.bark();
}
Best Practices for Java Data Types and Variables
Choose appropriate data types for memory efficiency:
// Good: Using int for a counter
int counter = 0;
// Inefficient: Using long when int would sufficelong small
Counter = 0L;
Use meaningful variable names for code readability:
// Good
int employeeCount = 42;// Poor
int ec = 42;
Initialize variables before using them:
int sum;
// sum = sum + 10; // Error: variable might not have been initialized
int sum = 0;
sum = sum + 10; // Correct
Use constants for fixed values:
final double TAX_RATE = 0.08;
Be cautious with type casting to avoid runtime errors:
// Check before casting
if (obj instanceof String) {
String str = (String) obj;
}
Common Pitfalls and How to Avoid Them
Integer Overflow
int maxInt = Integer.MAX_VALUE;
int overflow = maxInt + 1; // Overflows to negative value
// Solution: Use a larger data type
long safeValue = (long) maxInt + 1;
Floating-Point Precision Issues
double a = 0.1;
double b = 0.2;
System.out.println(a + b == 0.3); // Prints false due to precision issues
// Solution: Use BigDecimal for precise calculations
BigDecimal x = new BigDecimal("0.1");
BigDecimal y = new BigDecimal("0.2");
System.out.println(x.add(y).equals(new BigDecimal("0.3"))); // true
ClassCastException
Object obj = "Hello";
Integer num = (Integer) obj; // Throws ClassCastException
// Solution: Always check with instanceof
if (obj instanceof Integer) {
Integer num = (Integer) obj;
}
