Chapter 02
Java Variables & Data Types
5 topics · 1 sections · beginner-friendly study notes · Updated
Variables store data, data types decide what kind of data a variable can hold, casting converts between types, operators perform actions and keywords are reserved words with special meaning.
This chapter covers all five with complete programs.
Almost every exam question about output depends on types, casting and operators.
Mistakes such as integer division and overflow are very common.
Every real program stores values, converts them and calculates results: prices, ages, marks, sensor data and totals.
Java Variables
A variable is a named memory location that stores a value which can change during program execution. In Java every variable must be declared with a type before use: type name = value;
In short: A variable is a labelled box. The type tells what can go inside the box.
Think about it
Programs need to remember values. The variable kind decides its scope, lifetime and default value. A shopping app keeps a local variable total while calculating a bill and a static variable taxRate shared by all bills.
Java has three kinds of variables.
Local variables are declared inside a method or block; they have no default value and must be initialised before use; they live on the stack.
Instance variables are declared inside a class but outside methods; each object has its own copy; they get default values (0, false, null) and live on the heap with the object.
Static variables are declared with static; only one copy exists per class and it is shared by all objects.
Naming rules: letters, digits, underscore and dollar; cannot start with a digit; cannot be a keyword; case-sensitive.
Convention: camelCase for variables, UPPER_CASE for constants.
A constant is a variable marked final.
Since Java 10 you can write var for a local variable and the compiler infers the type: var count = 10;
Key points
- Declaration: Telling the compiler the type and name: int age;
- Initialisation: Giving the first value: age = 20;
- Scope: Part of the program where the variable can be used.
- final: Makes a variable constant after first assignment.
- var: Local variable type inference (Java 10+).
- Local variables have NO default value; using them uninitialised is a compile error.
- Instance variables default to 0, 0.0, false, '\u0000' or
null. - static variables are loaded once when the class is loaded.
- var works only for local variables with an initialiser.
Example
Codethree kinds of variables:
public class VariablesDemo {
static double taxRate = 0.18; // static variable (one copy)
String owner; // instance variable (default null)
int count; // instance variable (default 0)
final double PI_VALUE = 3.14159; // constant
public static void main(String[] args) {
int local = 10; // local variable
// System.out.println(unset); // error: variable might not have been initialized
var message = "Inferred as String"; // var (Java 10+)
VariablesDemo d = new VariablesDemo();
System.out.println("local = " + local);
System.out.println("owner = " + d.owner); // null
System.out.println("count = " + d.count); // 0
System.out.println("static = " + VariablesDemo.taxRate);
System.out.println(message);
int a = 5, b = 7, c; // multiple declarations
c = a + b;
System.out.println("Sum = " + c);
{ // block scope
int inner = 99;
System.out.println(inner);
}
// System.out.println(inner); // error: cannot find symbol
}
}Data Types in Java
A data type specifies the size and kind of value a variable can store. Java has eight primitive data types (byte, short, int, long, float, double, char, boolean) and reference types (classes, interfaces, arrays, enums).
In short: Primitive types hold plain values directly. Reference types hold the address of an object.
Think about it
Choosing the right type avoids overflow, precision loss and wasted memory. Prices use BigDecimal, ages use int, a large user id uses long and flags such as isActive use boolean.
Sizes and ranges: byte 8 bit (-128 to 127), short 16 bit (-32768 to 32767), int 32 bit (about -2.1 billion to 2.1 billion), long 64 bit (use suffix L), float 32 bit (suffix f, about 7 digits precision), double 64 bit (default for decimals, about 15 digits), char 16 bit Unicode (0 to 65535, written in single quotes) and boolean (true or false only; size is JVM dependent).
Default literals: whole numbers are int, decimals are double.
Literal forms: 1_000_000 (underscores), 0b1010 (binary), 017 (octal), 0xFF (hex).
Each primitive has a wrapper class (Integer, Double, Character, Boolean...
) with autoboxing and unboxing.
String is a reference type, not a primitive.
Floating-point numbers are approximate, so 0.1 + 0.2 is not exactly 0.3; use BigDecimal for money.
Key points
- Primitive: Basic built-in type that stores a value directly.
- Reference type: Type whose variable stores a reference to an object.
- Wrapper class: Object version of a primitive (Integer for int).
- Autoboxing: Automatic conversion from primitive to wrapper.
- Overflow: A value goes beyond the type range and wraps around.
- long needs L (100L) and float needs f (3.5f); otherwise the compiler treats them as int and double.
- char is a number internally (Unicode), so (char)('A' + 1) is 'B'.
- Integer.MAX_VALUE + 1 overflows to Integer.MIN_VALUE without any error.
- Compare strings with equals(), not
==.
Read more
Example
Codeall primitive types:
import java.math.BigDecimal;
public class DataTypesDemo {
public static void main(String[] args) {
byte b = 100;
short s = 30000;
int i = 1_000_000;
long l = 9_000_000_000L;
float f = 3.14f;
double d = 3.141592653589793;
char c = 'A';
boolean flag = true;
System.out.println(b + " " + s + " " + i + " " + l);
System.out.println(f + " " + d + " " + c + " " + flag);
System.out.println("int range : " + Integer.MIN_VALUE + " to " + Integer.MAX_VALUE);
System.out.println("byte range : " + Byte.MIN_VALUE + " to " + Byte.MAX_VALUE);
int big = Integer.MAX_VALUE;
System.out.println("Overflow: " + (big + 1)); // -2147483648
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(new BigDecimal("0.1").add(new BigDecimal("0.2"))); // 0.3
char next = (char) (c + 1);
System.out.println("Next of A: " + next); // B
System.out.println((int) c); // 65
int hex = 0xFF, bin = 0b1010, oct = 017;
System.out.println(hex + " " + bin + " " + oct); // 255 10 15
Integer boxed = 50; // autoboxing
int plain = boxed; // unboxing
System.out.println(boxed.equals(plain));
}
}Type Casting in Java
Type casting is converting a value of one data type into another. Widening (implicit) conversion goes from a smaller to a larger type automatically. Narrowing (explicit) conversion goes from a larger to a smaller type and needs a cast operator such as (int).
In short: Small box into big box is automatic. Big box into small box needs your permission, and data can be lost.
Think about it
Unexpected results in calculations usually come from silent integer division or narrowing. Converting user input text "25" to a number needs parseInt; computing an average needs a cast to double.
Widening order: byte -> short -> int -> long -> float -> double, and char -> int.
No data is lost (except possible precision loss from long to float).
Narrowing needs a cast: int x = (int) 9.99 gives 9 because the fraction is truncated.
Casting a large int to byte keeps only the lowest 8 bits, so (byte) 130 is -126.
Type promotion in expressions: byte, short and char are promoted to int before arithmetic, so byte a = 10, b = 20; byte c = a + b; is a compile error and needs (byte)(a + b).
If one operand is long, float or double the whole expression is promoted to that type.
Integer division truncates: 7 / 2 = 3; write 7 / 2.0 to get 3.5.
Reference casting (upcasting and downcasting between classes) is covered under polymorphism.
String conversion uses Integer.
parseInt(), Double.
parseDouble() and String.
valueOf().
Key points
- Widening: Implicit smaller to larger conversion.
- Narrowing: Explicit larger to smaller conversion with a cast.
- Promotion: Automatic widening of operands in an expression.
- Truncation: Dropping the fractional part when converting to an integer.
- parseInt: Converts a String to int.
- Narrowing may lose data; widening is always safe.
- (int) 3.99 gives 3; it truncates, it does not round.
- byte + byte gives int, so assign it back with a cast.
Integer.parseInt("abc")throws NumberFormatException.
Example
Codewidening, narrowing and promotion:
public class CastingDemo {
public static void main(String[] args) {
// Widening (automatic)
int i = 100;
long l = i;
float f = l;
double d = f;
System.out.println(i + " " + l + " " + f + " " + d);
// Narrowing (explicit)
double pi = 9.99;
int truncated = (int) pi;
System.out.println(truncated); // 9
int big = 130;
byte small = (byte) big;
System.out.println(small); // -126
// Type promotion
byte a = 10, b = 20;
// byte c = a + b; // compile error
byte c = (byte) (a + b);
System.out.println(c); // 30
// Integer division vs real division
int x = 7, y = 2;
System.out.println(x / y); // 3
System.out.println((double) x / y); // 3.5
System.out.println((double) (x / y)); // 3.0 (cast after division!)
// char <-> int
char ch = 'a';
System.out.println(ch + 1); // 98 (int)
System.out.println((char) (ch + 1)); // b
// String <-> number
int n = Integer.parseInt("42");
double v = Double.parseDouble("3.5");
String text = String.valueOf(n + v);
System.out.println(n + v + " " + text); // 45.5 45.5
}
}Operators in Java
Operators are symbols that perform operations on operands. Java has arithmetic, relational, logical, bitwise, shift, assignment, unary, ternary and instanceof operators.
In short: Operators are the tools for calculating and comparing values.
Think about it
Operator rules decide the output in most "find the output" questions. Discount logic uses ternary, access checks use &&, flags use bitwise operators and hashing uses shifts.
Arithmetic: + - * / %.
Relational: == !
= > < >= <=.
Logical: && (AND), || (OR), !
(NOT); && and || are short-circuit, meaning the right side is skipped when the result is already known.
Bitwise: & | ^ ~ work on bits.
Shift: << left, >> signed right, >>> unsigned right.
Assignment: = += -= *= /= %=; compound assignment includes an implicit cast.
Unary: ++ -- + - !.
Pre-increment (++x) changes then uses; post-increment (x++) uses then changes.
Ternary: condition ?
valueIfTrue : valueIfFalse.
instanceof checks the type of an object.
Precedence from high to low: postfix, unary, multiplicative, additive, shift, relational, equality, bitwise AND, XOR, OR, logical AND, logical OR, ternary, assignment.
Use brackets when unsure.
The + operator also joins strings: "Sum: " + 1 + 2 gives "Sum: 12".
Key points
- Operand: Value the operator works on.
- Short-circuit: Skipping the right side when the left side decides the result.
- Unary: Operator with one operand.
- Ternary: Operator with three operands: ? :
- Precedence: Priority order of operators.
==compares references for objects and values for primitives.- & and | evaluate both sides; && and || may skip the right side.
- i = i++ leaves i unchanged because the old value is assigned back.
- % with negative numbers keeps the sign of the left operand: -7 % 3 = -1.
Read more
Example
Codeoperator groups:
public class OperatorsDemo {
static boolean check(String name) {
System.out.println("check " + name);
return true;
}
public static void main(String[] args) {
int a = 17, b = 5;
System.out.println(a + b + " " + (a - b) + " " + a * b + " " + a / b + " " + a % b); // 22 12 85 3 2
System.out.println(-7 % 3); // -1
// relational and logical
System.out.println((a > b) && (b > 10)); // false
System.out.println((a > b) || (b > 10)); // true
System.out.println(!(a == b)); // true
// short-circuit
boolean r1 = false && check("A"); // check A is NOT printed
boolean r2 = false & check("B"); // check B IS printed
// increment
int x = 5;
int y = x++ + ++x; // 5 + 7
System.out.println(x + " " + y); // 7 12
// bitwise and shift
System.out.println(6 & 3); // 2
System.out.println(6 | 3); // 7
System.out.println(6 ^ 3); // 5
System.out.println(~6); // -7
System.out.println(5 << 2); // 20
System.out.println(-16 >> 2); // -4
System.out.println(-16 >>> 28); // 15
// compound assignment (implicit cast)
byte bt = 10;
bt += 5; // allowed
System.out.println(bt);
// ternary
int marks = 72;
String result = marks >= 40 ? "Pass" : "Fail";
System.out.println(result);
// string concatenation
System.out.println("Sum: " + 1 + 2); // Sum: 12
System.out.println("Sum: " + (1 + 2)); // Sum: 3
System.out.println(1 + 2 + " is the sum"); // 3 is the sum
Object o = "text";
System.out.println(o instanceof String); // true
}
}Java Keywords
Keywords are reserved words that have a fixed meaning in the Java language. They cannot be used as names of variables, methods or classes.
In short: Keywords are words Java already uses for itself, so you cannot use them as your own names.
Think about it
Compiler errors such as "not a statement" or "<identifier> expected" often come from using a keyword as a name. IDEs colour keywords so you can see at once that class or static is reserved.
Java has 51 reserved keywords: abstract, assert, boolean, break, byte, case, catch, char, class, const, continue, default, do, double, else, enum, extends, final, finally, float, for, goto, if, implements, import, instanceof, int, interface, long, native, new, package, private, protected, public, return, short, static, strictfp, super, switch, synchronized, this, throw, throws, transient, try, void, volatile, while.
const and goto are reserved but unused.
Also true, false and null are literals and cannot be used as identifiers.
Newer words such as var, record, sealed, permits, yield and non-sealed are contextual keywords: they have special meaning only in certain places.
A few are worth remembering by group.
Data types: byte short int long float double char boolean void.
Control flow: if else switch case default for while do break continue return.
Exceptions: try catch finally throw throws.
OOP: class interface extends implements new this super abstract final static instanceof enum.
Access: public private protected.
Others: package import synchronized volatile transient native strictfp assert.
Key points
- Reserved word: Word you cannot use as an identifier.
- Identifier: Name of a variable, method, class or package.
- Literal: Fixed value in code such as 10, true or
null. - Contextual keyword: Word reserved only in a specific context, e.g. var, record.
- true, false and
nullare not keywords but are reserved literals. - const and goto are reserved but not used.
- main, String, System and Integer are not keywords.
- Keywords are always in lowercase; Class is allowed but confusing.
Example
Codeusing keywords correctly:
import java.util.Set;
public class KeywordsDemo {
public static void main(String[] args) {
Set<String> keywords = Set.of(
"abstract", "class", "interface", "static", "final", "public",
"private", "protected", "void", "int", "if", "else", "for", "while");
String[] words = {"class", "String", "static", "main", "interface", "length", "while"};
for (String w : words) {
System.out.println(w + " -> " + (keywords.contains(w) ? "keyword" : "not in this sample list"));
}
// int class = 5; // error: not a statement / <identifier> expected
int classNo = 5; // fine: a keyword as part of a longer name
var record = 10; // allowed: record is only a contextual keyword
System.out.println(classNo + record);
}
}Solved examples
Swap two int variables a = 5 and b = 9 using a third variable.
a = 9, b = 5
Formula Applied:—Approach note: Without a third variable you can use a = a + b; b = a - b; a = a - b; but beware of overflow.
Find the output: int x = 10; double y = x / 4; System.out.println(y);
Printed value
Formula Applied:—Approach note: Write x / 4.0 or (double) x / 4 to get 2.5.
Find the output: int i = 5; i = i++ + ++i; System.out.println(i);
Value of i
Formula Applied:—Approach note: Evaluate left to right and track the current value of i at each step.
What prints? int a = 7; double b = a / 2; double c = a / 2.0; System.out.println(b + " " + c);
Two numbers
Formula Applied:—Approach note: If both operands are int, / truncates toward zero.
Real-world applications
Using Java Variables & Data Types in real projects
Every real program stores values, converts them and calculates results: prices, ages, marks, sensor data and totals.
Common mistakes
❌ Myth: Java has only primitive types.
Why this is wrong: Arrays, classes and interfaces are also types.
✅ Verified Truth: Java has 8 primitives and many reference types.
⚠️ Exam Tip: String is a reference type, not a primitive.
❌ Myth: (int) 3.99 gives 4.
Why this is wrong: Casting truncates the fraction.
✅ Verified Truth: The result is 3. Use Math.round() to round.
⚠️ Exam Tip: Know truncate vs round.
❌ Myth: Local variables get a default value of 0.
Why this is wrong: Only instance and static variables get defaults.
✅ Verified Truth: A local variable must be assigned before use or the compiler gives an error.
⚠️ Exam Tip: Remember "no default for locals".
❌ Myth: 0.1 + 0.2 equals 0.3 in Java.
Why this is wrong: Binary floating point cannot store 0.1 exactly.
✅ Verified Truth: The result is 0.30000000000000004; use BigDecimal for exact money values.
⚠️ Exam Tip: Classic output question.
Revision notes
Variables store data, data types decide what kind of data a variable can hold, casting converts between types, operators perform actions and keywords are reserved words with special meaning. This chapter covers all five with complete programs.
High-Yield Quick Revision Points
- Variable kinds: local (no default, stack), instance (default value, heap), static (one copy per class).
- 8 primitives: byte 1, short 2, int 4, long 8, float 4, double 8, char 2 bytes, boolean true/false.
- Whole-number literals are int and decimal literals are double; use L and f suffixes.
- Widening is automatic; narrowing needs a cast and may lose data.
- byte, short and char are promoted to int in arithmetic.
- Integer division truncates; && and || short-circuit; i++ uses then changes, ++i changes then uses.
- Java has 51 reserved keywords; const and goto are unused; true, false and null are literals.
- Use BigDecimal for money and equals() for strings.
Practice questions
What is the size of an int in Java?
What is the default value of a boolean instance variable?
What is the output of System.out.println(10 / 4)?
Which is a valid identifier?
Which statement gives a compile error?
What is the output of System.out.println("A" + 1 + 2)?