Java Data Types, Variables & Type Casting

Java Data Types, Variables & Type Casting
{} Java

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 (age and Age are different variables)
  • Use camelCase for multi-word variable names (e.g., studentName)

🎯 Variable Declaration Examples

VariableExamples.java
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:

// Output will appear here

🔢 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.

Primitive Data Types

Stores simple values directly in memory

8 primitive types in Java

📊 The 8 Primitive Data Types

byte
8-bit
Range: -128 to 127

Used for saving memory in large arrays

byte age = 25;
short
16-bit
Range: -32,768 to 32,767

Can be used to save memory as byte

short temperature = -200;
int
32-bit
Range: -2^31 to 2^31-1

Most commonly used for integer values

int population = 1500000;
long
64-bit
Range: -2^63 to 2^63-1

Used when int is not sufficient

long worldPopulation = 7800000000L;
float
32-bit
Range: ±3.4e-38 to ±3.4e+38

Single-precision floating point

float price = 19.99f;
double
64-bit
Range: ±1.7e-308 to ±1.7e+308

Double-precision floating point (default)

double pi = 3.14159265359;
char
16-bit
Range: 0 to 65,535 (Unicode)

Single Unicode character

char letter = 'A';
boolean
1-bit
Values: true or false

Represents truth values

boolean isActive = true;

🔍 Primitive Type Explorer

Select a primitive type to see its details:

Select a data 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.

Non-Primitive Data Types

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

String
Reference

Sequence of characters (most commonly used)

String name = "Java";
Array
Reference

Collection of similar type elements

int[] numbers = {1, 2, 3};
Class
Reference

User-defined data types

Student s1 = new Student();
Interface
Reference

Blueprint of a class

List<String> list = new ArrayList<>();

💡 String Examples

StringExamples.java
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:

Widening Casting

(Automatic)

byte → short → int → long → float → double

Narrowing Casting

(Manual)

double → float → long → int → short → byte

Widening Casting (Automatic)

Converting a smaller type to a larger type size. Done automatically by the compiler.

WideningCasting.java
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.

NarrowingCasting.java
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:

Select types and value to perform casting

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.

WrapperClasses.java
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);
    }
}

Java Data Types & Variables Tutorial | Understanding Primitive, Non-Primitive Types and Type Casting

Comments

Popular posts from this blog

What is Software Testing? Complete Beginner-Friendly Guide

Defect Management: Complete Guide with Tools & Best Practices

SDLC Models: Complete Guide with Advantages & Disadvantages