Variables and Data Types

Variables are containers for storing data. This lesson covers variables and data types in Java.

What is a Variable

A variable is a storage location in memory that holds data.

Three Elements of a Variable

Element Description Example
Type What kind of data to store int, double, String
Name How to find this variable age, price, name
Value The data stored in the variable 25, 9.99, "Alice"

Declaring Variables

JAVA
// Declare first, assign later
int age;
age = 25;

// Declare and assign
int age = 25;

// Declare multiple variables of the same type
int x = 1, y = 2, z = 3;

Naming Rules

Syntax Rules (Must Follow)

Rule Correct Incorrect
Can only contain letters, digits, underscore, $ myVar my-var
Cannot start with a digit name1 1name
Cannot use Java keywords myClass class
Case-sensitive ageAge
Convention Example Description
camelCase myVariableName Variables and methods
Meaningful names studentAge Avoid a, b, temp
Constants in UPPERCASE MAX_VALUE Separate with underscores

Primitive Data Types

Java has 8 primitive data types.

Integer Types

Type Size Range Example
byte 1 byte -128 to 127 byte b = 100;
short 2 bytes -32768 to 32767 short s = 1000;
int 4 bytes -2.1 billion to 2.1 billion int i = 100000;
long 8 bytes Much larger range long l = 100L;
💡 Use int by default. Use long (with L suffix) when you need a larger range.

Floating-Point Types

Type Size Precision Example
float 4 bytes 6-7 decimal places float f = 3.14f;
double 8 bytes 15 decimal places double d = 3.14;
💡 Use double by default. Add the f suffix when you need float.

Character Type

JAVA
char c1 = 'A';      // Single character in single quotes
char c2 = 'B';      // Can store any character
char c3 = 65;       // Can also use ASCII code values

Boolean Type

JAVA
boolean isTrue = true;
boolean isFalse = false;
💡 Note: In Java, boolean values can only be true or false. They cannot be represented as 0 or 1.

Reference Data Types

Everything other than the 8 primitive types is a reference type.

Common Reference Types

JAVA
String name = "Alice";        // String
int[] arr = {1, 2, 3};       // Array
Object obj = new Object();    // Object

String

JAVA
// Strings use double quotes
String greeting = "Hello, World!";

// String concatenation
String fullName = "John" + " " + "Doe";

// String length
int len = greeting.length();  // 13

Type Conversion

Automatic Type Conversion (small → large)

JAVA
int i = 100;
long l = i;      // int automatically converts to long
double d = i;    // int automatically converts to double

Explicit Type Casting (large → small)

JAVA
double d = 3.14;
int i = (int) d;  // Explicit cast, result is 3 (decimal truncated)

long l = 100;
int i = (int) l;  // Explicit cast
⚠️ Note: Explicit casting may lose precision or cause overflow. Use with caution.

Example: Type Conversion

JAVA
public class TypeConversion {
    public static void main(String[] args) {
        // Automatic type conversion
        int a = 100;
        long b = a;
        double c = a;
        System.out.println("int: " + a);      // 100
        System.out.println("long: " + b);      // 100
        System.out.println("double: " + c);    // 100.0
        
        // Explicit type casting
        double d = 3.99;
        int e = (int) d;
        System.out.println("double: " + d);    // 3.99
        System.out.println("int: " + e);       // 3 (truncated, not rounded)
    }
}
▶ Try it Yourself

final Constants

Use the final keyword to define constants. Once assigned, their value cannot be changed.

JAVA
final double PI = 3.14159;
final String APP_NAME = "MyApp";
final int MAX_SIZE = 100;

// PI = 3.14;  // Error! Constants cannot be modified
💡 Naming convention: Constant names should be all uppercase, separated by underscores.

var Local Variable Type Inference

Java 10 introduced the var keyword, which allows automatic type inference for local variables.

JAVA
// Traditional approach
String name = "Alice";
ArrayList<String> list = new ArrayList<String>();

// Using var
var name = "Alice";           // Automatically inferred as String
var list = new ArrayList<String>();  // Automatically inferred as ArrayList<String>
⚠️ Note: var can only be used for local variables, not for class member variables or method parameters.

❓ Frequently Asked Questions

Q What's the difference between int and Integer?
A int is a primitive type, Integer is a wrapper class (reference type). Integer can be null, int cannot.
Q How do I choose between float and double?
A Generally use double for higher precision. Only use float when you need to save memory or process large amounts of floating-point data.
Q Is String a primitive type?
A No. String is a reference type, but Java has special support for it, allowing direct assignment with string literals.

📖 Summary

📝 Exercises

  1. Variable practice: Define variables to store your name, age, height, and weight, then print them
  2. Type conversion: Convert the double value 3.14 to int and observe the result; convert int value 100 to double and observe the result
  3. Constant practice: Define a constant PI for the mathematical constant π, and calculate the area of a circle with radius 5

Next Lesson

In the next lesson, we'll learn about Operators — understanding various operations in Java.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏