Java Variables and Data Types — int, double, boolean, String
Learning Objectives
- Declare and initialize variables with correct Java syntax
- Distinguish primitive types from reference types
- Choose appropriate types for numbers, text, and true or false values
- Follow Java naming rules and common style conventions
Overview
A variable is a named storage slot in memory. You give the slot a name, you place a value inside it, and later you read the value back or replace it. In Java every variable has a fixed data type, and that type decides two things: how much memory the slot uses and which operations are legal.
Java is strongly typed. The compiler checks types at compile time, so mistakes such as storing text in an integer variable are caught early. This strictness feels picky at first, but it prevents entire categories of bugs that plague loosely typed languages.
Declaring Variables
Declaration states the type and the name. Initialization assigns the first value with the equals sign. You may combine both steps on one line, or declare first and assign later.
int age; // declare only
age = 25; // initialize
int score = 10; // declare and initialize
double price = 19.99;
boolean isStudent = true;
String name = "Ada";
If you try to use a variable before assigning it, the compiler reports variable might not have been initialized. Java refuses to run code that reads an unknown value from a local variable.
Primitive Data Types
Java has eight primitive types. Primitives store the actual value directly in the variable. The four you will use most as a beginner are listed below, followed by the rest for reference.
| Type | Size | Range or use | Example |
|---|---|---|---|
| int | 4 bytes | Whole numbers roughly plus or minus 2 billion | 42 |
| double | 8 bytes | Decimal numbers, default for fractions | 3.14 |
| boolean | 1 bit conceptually | true or false | true |
| char | 2 bytes | A single Unicode character | A |
| long | 8 bytes | Very large whole numbers | 100000L |
| float | 4 bytes | Smaller decimal values, needs suffix f | 2.5f |
| byte | 1 byte | Tiny whole numbers, minus 128 to 127 | 7 |
| short | 2 bytes | Small whole numbers | 300 |
Use int for counters, ages, and quantities. Use double for money calculations only when approximate results are acceptable, and note that finance systems often prefer specialized types instead. Use boolean for flags such as isLoggedIn. Use String for any longer piece of text, even a single character you plan to manipulate.
The String Type
String is not a primitive. It is a class from the Java library, which means a String variable holds a reference to an object rather than the characters themselves. You still write it like a simple type, and the double quotes make the intent clear.
String greeting = "Hello";
String message = "Welcome to Java";
System.out.println(greeting + " " + message);
The plus sign concatenates strings, which means it joins them into one. If either side of a plus is a String, Java converts the other side to text before joining.
Naming Rules and Style
The compiler enforces strict naming rules. Names may contain letters, digits, dollar signs, and underscores, but they cannot start with a digit and they cannot use reserved words such as int or class. Names are case sensitive, so count and Count are different variables.
Conventions are softer but widely followed. Use camelCase for variables and methods, starting lowercase: customerAge, totalPrice. Use PascalCase for class names: BankAccount. Give names meaning; avoid x or temp unless the context is obvious, such as a loop index.
Type Conversion Basics
Assigning a smaller numeric type to a larger one happens automatically. This is called widening or implicit conversion, and it is safe because no data is lost.
int students = 30;
double average = students; // int becomes double automatically
System.out.println(average); // prints 30.0
The reverse direction needs an explicit cast and may lose information. You will study both directions in the dedicated type casting lesson.
Key Takeaways
💡
- A variable is a named, typed storage slot in program memory
- Primitives store values directly; String is a reference type built on a class
- int, double, boolean, and String cover most beginner programs
- The compiler rejects use before initialization and illegal type assignments
- Follow camelCase for variables and PascalCase for class names
Practice Questions
- Declare one variable for a user age, one for a test score with decimals, one for a login flag, and one for a username.
- Why is String considered a reference type while int is a primitive type?
- The compiler rejects name = 42 when name was declared as int if you wrap 42 in quotes. Explain why.
Extended Learning: Beyond the Basics
Key Concepts Summary
This lesson covers fundamental concepts that serve as building blocks for more advanced topics. Master these basics before moving to intermediate and advanced material.
Prerequisite Knowledge
Before studying this topic in depth, ensure you understand:
- Basic definitions and terminology
- Core formulas and their derivations
- Common applications in real-world scenarios
- Typical pitfalls and misconceptions
Step-by-Step Walkthrough
Let us work through a complete example to solidify understanding:
Step 1: Identify the problem type. Determine which category this problem falls into and which approach is most appropriate.
Step 2: Apply the relevant formula. Substitute known values into the appropriate equation, paying attention to units and constraints.
Step 3: Simplify and solve. Work through the algebra step by step, checking each intermediate result.
Step 4: Verify the answer. Check that the solution satisfies the original conditions and makes logical sense.
Common Mistakes to Avoid
- Misidentifying the problem type — Always start by categorizing the problem
- Incorrect formula application — Verify the formula applies to your specific case
- Unit errors — Always check units are consistent throughout
- Sign errors — Pay careful attention to positive and negative values
- Rounding too early — Keep full precision until the final answer
- Forgetting constraints — Check that solutions satisfy all given conditions
Real-World Applications
Understanding this concept is essential for:
- Advanced problem solving in examinations
- Building intuition for more complex topics
- Developing analytical thinking skills
- Applying mathematical reasoning to practical situations
Practice Exercises
- Basic: Solve 5 problems of increasing difficulty using the core concept.
- Intermediate: Apply the concept to word problems with multiple steps.
- Advanced: Combine this concept with 2-3 other topics in a comprehensive problem.
- Challenge: Create your own problem that requires this concept plus additional knowledge.
Interview and Exam Tips
- Common question patterns: Identify which exam or interview formats test this topic
- Time management: Practice completing problems within time constraints
- Common traps: Know the typical mistakes examiners set as distractors
- Verification strategy: Develop a quick method to check your answer
Related Topics
- Previous Topic — Build on the foundation laid here
- Next Topic — See how this concept extends to more advanced material
- Practice Problems — Additional exercises with solutions
- Video Explanation — Visual walkthrough of key concepts
Quick Reference Card
| Concept | Formula/Rule | Key Insight | Common Use |
|---|---|---|---|
| Core Definition | See main text | Understand the intuition | Foundation for all applications |
| Key Formula | See main text | Memorize the derivation | Direct problem solving |
| Special Case | See main text | Recognize when it applies | Simplifies complex problems |
| Edge Case | See main text | Know the limitations | Avoids errors |
Further Reading
For students who want to go deeper:
- Standard textbooks on the subject
- Research papers applying this concept
- Online courses with video explanations
- Practice problem collections with detailed solutions