foreach-ui logo
codeLanguages
account_treeDSA

Quick Actions

quizlock Random Quiz
trending_uplock Progress
  • 1
  • 2
  • 3
  • 4
  • quiz
Java
  • Understand variables and how to declare them
  • Learn primitive and reference data types
  • Master type conversion techniques

Variables and Data Types in Java

Think of variables as labeled boxes where you store different kinds of things. Some boxes hold numbers, others hold text, and Java needs to know what type of box you're using so it can handle the contents correctly.

Variables — your data containers

A variable is just a named spot in memory where you store a value. Before you can use a variable in Java, you tell the compiler what type of data it will hold and give it a name.

int playerScore = 0;
String username = "alex";
boolean isLoggedIn = true;

Here's what's happening:

  • int playerScore creates a box that holds whole numbers
  • String username creates a box for text
  • boolean isLoggedIn creates a box for true/false values

Naming your variables

Java has rules about variable names, and most are common sense:

Valid names:

int age;
String firstName;
double account_balance;  // works but not conventional
int $price;              // works but unusual

Invalid names:

int 2names;      // can't start with a digit
int class;       // can't use reserved words
int my-variable; // can't use hyphens

Convention (what everyone actually uses):

int userAge;           // camelCase for variables
String emailAddress;   // first word lowercase, rest capitalized
boolean isActive;      // clear, descriptive names

Use names that explain what the variable holds. int x is legal but int studentCount tells you what it represents.

Primitive types — the building blocks

Java has eight primitive types built into the language. These are not objects; they're simple values stored directly in memory.

The integer family

Type Size Range When to use it
byte 8 bits -128 to 127 Rarely — only when memory is tight
short 16 bits -32,768 to 32,767 Also rare
int 32 bits ±2 billion Default for whole numbers
long 64 bits ±9 quintillion Very large numbers, add L suffix

Practical example:

int daysInYear = 365;              // normal use
long worldPopulation = 8000000000L; // note the L suffix
byte sensorReading = 42;            // if you're reading hundreds of sensors

Decimal numbers

Type Size Precision When to use it
float 32 bits ~7 decimal digits Rarely — graphics, memory-constrained
double 64 bits ~15 decimal digits Default for decimals
double price = 19.99;
double pi = 3.141592653589793;

float temperature = 98.6f;  // note the f suffix

If you write 3.14, Java assumes it's a double. For float, add the f: 3.14f.

Other primitives

char initial = 'A';          // single character, use single quotes
boolean isComplete = false;  // only true or false

Common mistake:

char letter = "A";  // WRONG — double quotes make it a String
char letter = 'A';  // RIGHT — single quotes for char

Reference types — pointing to objects

Everything that's not a primitive is a reference type. The variable doesn't hold the actual data; it holds a reference (memory address) to where the data lives.

Strings — special but not primitive

String greeting = "Hello";
String name = "World";
String message = greeting + " " + name;  // "Hello World"

Strings look primitive but they're objects. This matters:

String a = "test";
String b = "test";
String c = new String("test");

// a == b is true (same object in string pool)
// a == c is false (different objects)
// a.equals(c) is true (same content)

Use .equals() to compare String content, not ==.

Type conversion — fitting square pegs in round holes

Automatic widening (safe conversions)

Java automatically converts smaller types to larger ones because there's no risk of data loss:

int wholeNumber = 100;
double decimal = wholeNumber;  // int → double, works fine

The widening path:

byte → short → int → long → float → double
       char  → int

Manual narrowing (you take responsibility)

Going from larger to smaller types might lose data, so Java makes you explicitly cast:

double price = 19.99;
int dollars = (int) price;  // becomes 19, loses the cents

What happens:

double d = 128.7;
byte b = (byte) d;  // b = 127 (byte max), data loss!

Narrowing can produce unexpected results. If you cast a double with value 300 to a byte, you'll get strange wrapping behavior because 300 doesn't fit in a byte.

Parsing strings to numbers

Real-world scenario: you read user input as a string but need a number.

String input = "42";
int number = Integer.parseInt(input);

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

Wrong way:

String age = "25";
int userAge = (int) age;  // compile error — can't cast String to int

Right way:

String age = "25";
int userAge = Integer.parseInt(age);  // converts string to int

Constants — values that don't change

Use final to create constants. Convention is to use UPPER_CASE names:

final double PI = 3.14159;
final int MAX_USERS = 100;
final String API_KEY = "abc123xyz";

// PI = 3.0;  // compile error — can't change final variables

Constants improve readability:

// Hard to understand:
if (speed > 299792458) { ... }

// Clear intent:
final int SPEED_OF_LIGHT = 299792458;
if (speed > SPEED_OF_LIGHT) { ... }

Common mistakes and how to avoid them

1. Uninitialized variables

int count;
System.out.println(count);  // compile error — not initialized

Fix: Always initialize before use.

int count = 0;
System.out.println(count);  // prints 0

2. Integer overflow

int bigNumber = 2147483647;  // max int value
bigNumber = bigNumber + 1;   // wraps to -2147483648 (overflow!)

Fix: Use long if you need bigger numbers.

3. Floating-point precision issues

double result = 0.1 + 0.2;
System.out.println(result);  // prints 0.30000000000000004

This is how floating-point math works in computers. For money calculations, use BigDecimal:

BigDecimal a = new BigDecimal("0.1");
BigDecimal b = new BigDecimal("0.2");
BigDecimal result = a.add(b);  // exactly 0.3

Practical examples

Swapping two variables:

int a = 5;
int b = 10;

// Wrong way (a becomes 10, b becomes 10)
a = b;
b = a;

// Right way
int temp = a;
a = b;
b = temp;

Calculating with mixed types:

int total = 10;
int count = 3;
double average = total / count;      // gives 3.0 (integer division!)

double correctAverage = (double) total / count;  // gives 3.333...

Quick reference table

Type Example Use case
int int age = 25; Whole numbers, counters
double double price = 9.99; Decimal numbers, calculations
boolean boolean isActive = true; Flags, conditions
char char grade = 'A'; Single character
String String name = "Alex"; Text, messages
long long distance = 384400000L; Very large whole numbers

What to remember

  • Declare variables with a type and a name: int count = 0;
  • Use int for whole numbers, double for decimals, String for text
  • Java converts smaller types to larger ones automatically (widening)
  • You must explicitly cast when going from larger to smaller (narrowing)
  • Use final for values that shouldn't change
  • Choose descriptive names: userAge not x
  • Compare strings with .equals(), not ==

The choice of data type affects memory use and what operations you can perform. Pick the simplest type that fits your needs—most of the time, that's int, double, boolean, and String.

© 2026 forEach. All rights reserved.

Privacy Policy•Terms of Service