Java Data Types, Variables & Type Casting
Data Types & Variables
Understanding Primitive & Non-Primitive Data Types, Variables, and Type Casting in Java
📦 Variables in Java
Variables are containers for storing data values. In Java, every variable must have a specific data type, which determines the size and layout of the variable's memory.
Variable Declaration Syntax: dataType variableName = value;
🔤 Variable Naming Rules
- Must begin with a letter, underscore (_), or dollar sign ($)
- After first character, can include letters, digits, underscores, or dollar signs
- Cannot be Java keywords (like
class,int,public, etc.) - Case-sensitive (
ageandAgeare different variables) - Use camelCase for multi-word variable names (e.g.,
studentName)
🎯 Variable Declaration Examples
public class VariableExamples {
public static void main(String[] args) {
// Integer variable
int age = 25;
// Floating point variable
double salary = 50000.50;
// Character variable
char grade = 'A';
// Boolean variable
boolean isJavaFun = true;
// String variable (non-primitive)
String name = "John Doe";
// Display variables
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: $" + salary);
System.out.println("Grade: " + grade);
System.out.println("Is Java fun? " + isJavaFun);
}
}
⚡ Variable Demo
Try changing the variable values and see the output:
🔢 Primitive Data Types
Primitive data types are the basic building blocks of data manipulation in Java. They are predefined by the language and named by a keyword.
Stores simple values directly in memory
8 primitive types in Java
📊 The 8 Primitive Data Types
Used for saving memory in large arrays
Can be used to save memory as byte
Most commonly used for integer values
Used when int is not sufficient
Single-precision floating point
Double-precision floating point (default)
Single Unicode character
Represents truth values
🔍 Primitive Type Explorer
Select a primitive type to see its details:
🏢 Non-Primitive Data Types
Non-primitive data types are created by the programmer and are not predefined by Java (except String). They are also called reference types because they refer to objects.
Store references to objects in memory
Also called Reference Types
📝 Key Characteristics
- Default value is
null - Can be used to call methods to perform certain operations
- All non-primitive types are classes in Java
- They are stored in heap memory
- They have unlimited size (depends on heap memory)
🔧 Common Non-Primitive Types
Sequence of characters (most commonly used)
Collection of similar type elements
User-defined data types
Blueprint of a class
💡 String Examples
public class StringExamples {
public static void main(String[] args) {
// Different ways to create strings
String str1 = "Hello"; // String literal
String str2 = new String("World"); // Using new keyword
// String concatenation
String message = str1 + " " + str2;
System.out.println(message); // Output: Hello World
// String methods
System.out.println("Length: " + message.length());
System.out.println("Uppercase: " + message.toUpperCase());
System.out.println("Contains 'World': " + message.contains("World"));
}
}
Important: Non-primitive types are reference types. When you assign one reference variable to another, both variables refer to the same object in memory.
🔄 Type Casting in Java
Type casting is when you assign a value of one primitive data type to another type. In Java, there are two types of casting:
(Automatic)
byte → short → int → long → float → double
(Manual)
double → float → long → int → short → byte
⚡ Widening Casting (Automatic)
Converting a smaller type to a larger type size. Done automatically by the compiler.
public class WideningCasting {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double
System.out.println(myInt); // Output: 9
System.out.println(myDouble); // Output: 9.0
}
}
🔧 Narrowing Casting (Manual)
Converting a larger type to a smaller size type. Must be done manually by the programmer.
public class NarrowingCasting {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Output: 9.78
System.out.println(myInt); // Output: 9 (decimal part lost)
}
}
🎮 Type Casting Demo
Try different type casting operations:
Note: When narrowing casting, you may lose data (like when converting from double to int, the decimal part is truncated). Always be cautious with narrowing conversions.
📊 Primitive vs Non-Primitive Comparison
Understanding the differences between primitive and non-primitive data types is crucial for effective Java programming.
| Characteristic | Primitive Data Types | Non-Primitive Data Types |
|---|---|---|
| Definition | Predefined by Java language | Created by the programmer (except String) |
| Size | Fixed size (depends on data type) | Dynamic size (depends on the object) |
| Memory Allocation | Stack memory | Heap memory |
| Default Value | Has default values (0, 0.0, false, etc.) | Default value is null |
| Operations | Can't call methods | Can call methods to perform operations |
| Examples | byte, int, float, boolean, char | String, Array, Class, Interface |
| Performance | Faster access | Slower access (requires dereferencing) |
💡 Key Takeaways
- Use primitive types for simple values and when performance is critical
- Use non-primitive types for complex data structures and when you need methods
- Primitive types are faster but have limited functionality
- Non-primitive types are slower but offer more functionality
- Java provides wrapper classes (like Integer, Double) to use primitives as objects
🔗 Wrapper Classes
Java provides wrapper classes to convert primitive types into objects. This is useful when working with collections that require objects.
public class WrapperClasses {
public static void main(String[] args) {
// Primitive types
int primitiveInt = 10;
double primitiveDouble = 20.5;
// Wrapper classes (autoboxing)
Integer objectInt = primitiveInt; // int → Integer
Double objectDouble = primitiveDouble; // double → Double
// Converting back (unboxing)
int backToPrimitive = objectInt; // Integer → int
System.out.println("Primitive: " + primitiveInt);
System.out.println("Object: " + objectInt);
System.out.println("Back to primitive: " + backToPrimitive);
}
}
Comments
Post a Comment