Skip to content
QuizMaker logoQuizMaker
Activity
Java Programming: From Zero to Enterprise
1. Java Fundamentals
1. Getting Started with Java & the JVM
2. Data Types & Variables
3. Control Flow: Ifs & Loops
4. String Manipulation in Depth
5. Methods (Functions) Architecture
6. Arrays & The Enhanced For Loop
7. User Input via Scanner
8. Mathematical Operations & The Math Class
9. Operators in Depth
10. Block Scope & Variable Lifecycles
11. Introduction to Object-Oriented Programming
12. Classes & Instances Deep Dive
13. Constructors
14. Encapsulation & The 'this' Keyword
15. Inheritance: Extending Functionality
16. Polymorphism & Method Overriding
17. Abstraction & Abstract Classes
18. Interfaces: The Ultimate Contract
19. Packages & Access Modifiers
20. Enums (Enumerations)
21. Exceptions: Handling Runtime Errors
22. The 'throw' and 'throws' keywords
23. Dates, Times, and Formatting
24. Enumerable Data Structures
25. LinkedLists: The Alternative
26. HashMaps: Key-Value Architecture
27. HashSets: The Art of Uniqueness
28. Iterator: Safe Collection Traversal
29. Wrapper Classes & Autoboxing
30. Basic File I/O
31. Generics: Type-Safe Templates
32. Lambda Expressions & Functional Interfaces
33. The Stream API: Functional Data Pipelines
34. Optional: Beating the NullPointerException
35. Multithreading & Concurrency Basics
36. JDBC: Connecting to SQL Databases
37. Annotations & Reflection
38. The JVM Garbage Collector
39. Introduction to Spring Boot
40. Unit Testing with JUnit
41. Java Collections for DSA
CONTENTS

2. Data Types & Variables

Learn the difference between primitives and objects, and how to declare them.

Java Programming: From Zero to Enterprise
1. Java Fundamentals
February 22, 2026
121
A

[!NOTE] Variables are named containers holding data in the computer's memory. In Java, every container is strictly labeled with the exact type of data it's allowed to hold.

Statically Typed vs Dynamically Typed

If you are coming from Python or JavaScript, you are used to Dynamic Typing. You can create a variable x = 5 and later change your mind and say x = "Hello".

Java is Statically Typed. When you create a variable, you must explicitly declare its type upfront. Once declared, that variable can never hold a different type of data. If you try to put text inside an integer variable, the code simply will not compile.

Why go through the trouble?

Static typing catches 90% of your bugs at compile-time before the application even starts. In JavaScript, you might not realize an error occurred until a user clicks a button and the app crashes in production. By forcing you to declare types, Java acts as your personal safety net.

Primitive Data Types

Java has 8 foundational "Primitive" types. These are raw values, not objects. They are extremely fast and efficient, living directly on the call stack execution memory.

  1. Integral Numbers

Type Size Range Example Use Case
byte 8-bit -128 to 127 Saving memory in enormous 2D arrays.
short 16-bit -32,768 to 32,767 Rarely used in modern Java.
int 32-bit ~ ±2 Billion Default choice for whole numbers.
long 64-bit ~ ±9 Quintillion Extremely large counts (e.g., global population). Append 'L'.
int currentScore = 1500;
long viewCount = 8000000000L;

  1. Floating-Point Numbers

Type Size Precision Example Use Case
float 32-bit ~7 Decimal Digits Saving memory for 3D graphics. Append 'f'.
double 64-bit ~15 Decimal Digits Default choice for decimals.
double bankBalance = 1542.89;
float pi = 3.14159f;

  1. Characters & Booleans

  • char: A single 16-bit Unicode character. Must be surrounded by single quotes.
  • boolean: Simply true or false.
char grade = 'A'; // Single quotes!
boolean isGameOver = false;

Non-Primitive Data Types (Objects)

Primitives just hold values. Non-primitive types (also called Reference Types) map to fully featured Objects built in the Heap memory. They have methods you can call on them.

The most famous is String. A String is a sequence of characters, enclosed in double quotes.

String playerUsername = "DragonSlayer99";
int usernameLength = playerUsername.length(); // Calling a method on the Object
String upperCaseName = playerUsername.toUpperCase();

Strings are fundamentally different from primitives. int starts with a lowercase letter because it's baked into the language. String starts with a capital letter because it is actually a Class definition located in the java.lang package!

[!IMPORTANT] Variable Naming Conventions: In Java, variables should use camelCase. They should start with a lowercase letter, and every subsequent word should be capitalized (e.g., myFirstVariable).

Choosing the Right Type in Real Code

Types are not only syntax. They describe what kind of value your program expects. Good type choices make code easier to read, safer to change, and easier for the compiler to protect.

For ordinary whole numbers, use int. For very large counts, use long. For decimal measurements, use double. For money, do not use double in serious applications because floating-point values can introduce rounding surprises. Use BigDecimal when exact decimal precision matters.

Better Variable Names

// Weak: the type is visible, but the meaning is not clear
int x = 18;
double y = 499.99;

// Better: the variable name explains the business meaning
int minimumAge = 18;
double cartTotal = 499.99;

Primitive Defaults vs Local Variables

Fields get default values, but local variables inside methods must be assigned before use. This rule prevents accidental reads from uninitialized local data.

class ScoreCard {
    int score; // field default is 0

    void printScore() {
        int bonus;
        // System.out.println(bonus); // compile error: bonus not initialized
        bonus = 10;
        System.out.println(score + bonus);
    }
}

Common Mistakes

  • Using String for numbers that must be calculated later.
  • Forgetting the L suffix on very large long literals.
  • Comparing decimal values as if they are always exact.
  • Naming variables by type only, such as str, num, or data.

Mini Practice

Create variables for a product name, quantity, price, in-stock flag, and rating. Print a one-line invoice summary. Then change the quantity type from int to String and notice which calculations stop compiling.

Practice Lab: Build a Bill Summary

Create variables for a small shopping bill and print a clean summary.

  1. Create variables for product name, quantity, price per item, tax percentage, and whether the item is in stock.
  2. Calculate subtotal and final total.
  3. Print the result in one readable sentence.
  4. Try changing quantity from int to String and observe what breaks.

Goal: Understand why choosing correct types matters before calculations begin.

Revision Checkpoint

  • Static typing: Java checks variable types at compile time.
  • Primitive types: Store raw values such as int, double, boolean, and char.
  • Reference types: Point to objects such as String, arrays, and custom classes.
  • Default integer: Use int for ordinary whole numbers.
  • Money warning: Prefer exact decimal handling such as BigDecimal for serious money calculations.

Before the quiz: Decide whether each value should be int, long, double, boolean, char, or String.

Share this article

Share on TwitterShare on LinkedInShare on FacebookShare on WhatsAppShare on Email

Test your knowledge

Take a quick quiz based on this chapter.

easyJava
Quiz: Data Types
10 questions5 min
Lesson 2 of 10 in 1. Java Fundamentals
Previous in 1. Java Fundamentals
1. Getting Started with Java & the JVM
Next in 1. Java Fundamentals
3. Control Flow: Ifs & Loops
Back to Java Programming: From Zero to Enterprise
Back to moduleCategories