Java Variables and Data Types

Variables store data that your program can use and change. Every useful program needs them. A game tracks your score in a variable. A calculator stores numbers you’re working with. A login system holds your username.

Java is particular about variables. You must declare what type of data each variable holds before you use it. This strictness catches errors early and makes code easier to understand.

Declaring Variables

A variable declaration has two parts: the type and the name.

int score;
String username;
double price;

These lines create three variables but don’t put anything in them yet. The variable score can hold integers. The variable username can hold text. The variable price can hold decimal numbers.

You can declare and assign a value in one line:

int score = 0;
String username = "player1";
double price = 19.99;

The equals sign here means assignment, not equality. You’re putting the value on the right into the variable on the left.

Naming Rules

Java enforces some rules for variable names. Names must start with a letter, underscore, or dollar sign. After the first character, you can use letters, digits, underscores, or dollar signs. Names cannot be Java reserved words like int, class, or public.

These names are valid:

int playerScore;
int _count;
int $total;
int score2;

These names are not valid:

int 2score;    // cannot start with digit
int player-score;  // hyphens not allowed
int class;     // reserved word

Java is case-sensitive. The variables Score, score, and SCORE are three different variables.

Naming Conventions

Beyond the rules, Java developers follow conventions. Variable names use camelCase: start lowercase, capitalize each subsequent word. No underscores between words.

int playerScore;      // good
int playerHighScore;  // good
int player_score;     // works but not conventional
int playerscore;      // works but hard to read

Choose descriptive names. A variable called x tells you nothing. A variable called numberOfStudents tells you exactly what it holds.

Primitive Data Types

Java has eight primitive types built into the language. These are the most basic forms of data.

Integer Types

Four types store whole numbers, differing in how much memory they use and how large a number they can hold.

byte uses 8 bits and stores values from -128 to 127. Use it when memory is tight and values are small.

short uses 16 bits and stores values from -32,768 to 32,767. Rarely used in practice.

int uses 32 bits and stores values from about -2.1 billion to 2.1 billion. This is the default choice for whole numbers.

long uses 64 bits and stores very large values. Add an L suffix to long literals.

byte smallNumber = 100;
short mediumNumber = 30000;
int regularNumber = 2000000000;
long bigNumber = 9000000000000000000L;

For most purposes, just use int. You’ll rarely need the others unless you’re working with very large numbers or optimizing memory usage.

Floating-Point Types

Two types store decimal numbers.

float uses 32 bits and provides about 6-7 significant digits. Add an f suffix to float literals.

double uses 64 bits and provides about 15 significant digits. This is the default for decimal numbers.

float temperature = 98.6f;
double pi = 3.14159265358979;

Use double unless you have a specific reason to use float. The extra precision prevents rounding errors in calculations.

The boolean Type

A boolean holds exactly two possible values: true or false. Use booleans for yes/no conditions.

boolean isLoggedIn = true;
boolean hasPermission = false;
boolean gameOver = false;

You’ll use booleans constantly with if statements and loops.

The char Type

A char holds a single character. Use single quotes around the character.

char letter = 'A';
char digit = '7';
char symbol = '@';

Note the single quotes. Double quotes create a String, which is different. 'A' is a char. "A" is a String containing one character.

Reference Types: String

Strings aren’t primitive types. They’re objects. But you’ll use them so often that they deserve attention here.

A String holds text of any length, including empty text.

String name = "Alice";
String empty = "";
String sentence = "Java is a programming language.";

Use double quotes for Strings. You can join Strings together with the + operator:

String firstName = "Alice";
String lastName = "Smith";
String fullName = firstName + " " + lastName;
System.out.println(fullName);  // Alice Smith

Strings have many built-in methods. Here are a few common ones:

String text = "Hello, World!";

int len = text.length();              // 13
String upper = text.toUpperCase();    // HELLO, WORLD!
String lower = text.toLowerCase();    // hello, world!
char first = text.charAt(0);          // H
boolean hasHello = text.contains("Hello");  // true

Default Values

If you declare a variable without assigning a value, what does it contain?

For instance variables (variables declared inside a class but outside any method), Java assigns default values. Numbers default to 0, booleans default to false, and object references default to null.

For local variables (variables declared inside a method), Java requires you to assign a value before using them. The compiler refuses to run code that reads an uninitialized local variable.

public class Example {
    int instanceVar;  // defaults to 0
    
    public void method() {
        int localVar;
        // System.out.println(localVar);  // compiler error!
        
        localVar = 5;
        System.out.println(localVar);  // works fine
    }
}

This rule prevents bugs. Using an uninitialized variable is almost always a mistake.

Type Casting

Sometimes you need to convert a value from one type to another. Java handles some conversions automatically and requires explicit casting for others.

Automatic Widening

Java automatically converts smaller types to larger types when no data is lost. An int fits comfortably in a long. A float fits in a double.

int small = 100;
long big = small;      // automatic conversion

float f = 3.14f;
double d = f;          // automatic conversion

Explicit Narrowing

Converting a larger type to a smaller type might lose data. Java requires you to explicitly acknowledge this with a cast.

double price = 19.99;
int rounded = (int) price;  // rounded is 19, decimal part lost

long bigNumber = 1000;
int smaller = (int) bigNumber;  // explicit cast required

The cast syntax is the target type in parentheses before the value. Be careful: if the value doesn’t fit in the target type, you get unexpected results, not an error.

Converting Strings to Numbers

Strings don’t automatically convert to numbers. Use parsing methods:

String numText = "42";
int num = Integer.parseInt(numText);       // 42

String priceText = "19.99";
double price = Double.parseDouble(priceText);  // 19.99

If the String doesn’t contain a valid number, these methods throw an exception and your program crashes unless you handle it. More on exception handling in a later tutorial.

Converting Numbers to Strings

Going the other direction is easier. Concatenate with an empty String, or use String.valueOf():

int score = 100;
String scoreText = "" + score;           // "100"
String scoreText2 = String.valueOf(score);  // "100"

Constants with final

Sometimes a value shouldn’t change after you set it. The final keyword prevents reassignment.

final double TAX_RATE = 0.08;
final int MAX_PLAYERS = 4;
final String APP_NAME = "JavaKing";

By convention, constant names use all uppercase letters with underscores between words.

If you try to change a final variable, the compiler stops you:

final int MAX_SCORE = 100;
MAX_SCORE = 200;  // compiler error!

Use constants for values that are fixed throughout your program. They make code clearer and prevent accidental changes.

Putting It Together

Here’s a complete program using several variable types:

public class PlayerProfile {
    public static void main(String[] args) {
        // Player information
        String playerName = "Alice";
        int level = 15;
        double health = 87.5;
        boolean isPremium = true;
        char rank = 'B';
        
        // Game constants
        final int MAX_LEVEL = 100;
        final double STARTING_HEALTH = 100.0;
        
        // Calculate health percentage
        double healthPercent = (health / STARTING_HEALTH) * 100;
        
        // Display profile
        System.out.println("Player: " + playerName);
        System.out.println("Level: " + level + " / " + MAX_LEVEL);
        System.out.println("Health: " + healthPercent + "%");
        System.out.println("Rank: " + rank);
        System.out.println("Premium: " + isPremium);
    }
}

Output:

Player: Alice
Level: 15 / 100
Health: 87.5%
Rank: B
Premium: true

Common Mistakes

Using a variable before declaring it. Java reads top to bottom. Declare variables before you use them.

System.out.println(score);  // error: score not defined yet
int score = 10;

Forgetting the f suffix on floats. Without it, Java treats the number as a double and complains about type mismatch.

float temperature = 98.6;   // error
float temperature = 98.6f;  // correct

Confusing = and ==. Single equals assigns a value. Double equals compares values. We’ll cover comparison operators in a later tutorial.

int x = 5;    // assigns 5 to x
x == 5;       // compares x to 5, returns true or false

Integer division surprise. When you divide two integers, Java discards the decimal part.

int result = 7 / 2;  // result is 3, not 3.5

If you want the decimal, make at least one operand a double:

double result = 7.0 / 2;  // result is 3.5

What’s Next

Variables hold data. Operators manipulate it. The next tutorial covers arithmetic, comparison, and logical operators that let you calculate, compare, and combine values.


Related: Your First Java Program: Hello World | Java Operators Explained

Sources

  • Oracle. “Primitive Data Types.” The Java Tutorials. docs.oracle.com
  • Oracle. “Variables.” The Java Tutorials. docs.oracle.com
Scroll to Top