Learning Java starts with three pillars: variables, data types, and operators. This beginner-friendly guide explains each concept in simple language with Java 21+ in mind. You’ll see short, complete programs and outputs, learn the syntax step by step, avoid common mistakes, and build confidence for your next practice session.
What is a variable in Java?
A variable is a named storage location that holds a value while your program runs. In Java, every variable has a type (like int or String) and a name (like age or message). Java is statically typed, which means the compiler knows each variable’s type and checks it before running the program.
Why variables are used
- To store input or intermediate results
- To make programs readable (good names explain intent)
- To control program flow (conditions based on variable values)
Basic syntax
- Declaration:
type name;(e.g.,int count;) - Initialization:
name = value;(e.g.,count = 10;) - Combined:
type name = value;(e.g.,double price = 49.99;) - Local type inference with
var(Java 10+):var city = "Jaipur";The compiler infers the type from the initializer. It’s still statically typed.
How to declare and use variables in Java step by step
class="cd-keyword cd-access">public class VariablesIntro {
class="cd-keyword cd-access">public static void main(String[] args) {
// Explicit types
int age = 18;
double price = 49.99;
boolean passed = true;
char grade = 'A';
String name = "Riya";
// Local type inference (Java 10+)
var city = "Jaipur"; // inferred as String
var score = 92; // inferred as int
// Update and use variables
score = score + 5;
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Grade: " + grade);
System.out.println("Passed: " + passed);
System.out.println("Price: " + price);
System.out.println("City: " + city);
System.out.println("Score: " + score);
// ___CDPHSTR10___ limitations (these lines would not compile if uncommented)
// var notSet; // Error: ___CDPHSTR11___ requires an initializer
// var nothing = null; // Error: cannot infer type for local variable
}
}Name: Riya
Age: 18
Grade: A
Passed: true
Price: 49.99
City: Jaipur
Score: 97Variable scope and lifetime (beginner guide)
Scope is the region of code where a variable can be used. Lifetime is how long the variable exists during execution.
- Local variables (inside methods/blocks): must be initialized before use; no default value.
- Fields (variables inside a class, but outside methods): get default values (e.g.,
0,0.0,false,'u0000',null). - Block scope: a variable declared inside
{ }is not visible outside that block.
class="cd-keyword cd-access">public class ScopeDemo {
int count; // instance field; default value is 0
class="cd-keyword cd-access">public static void main(String[] args) {
ScopeDemo demo = new ScopeDemo();
System.out.println("Default field 'count': " + demo.count); // 0
if (true) {
int inside = 10;
System.out.println("Inside block: " + inside);
}
// System.out.println(inside); // Error: cannot find symbol
// Local variables must be initialized before use:
// int notInitialized;
// System.out.println(notInitialized); // Error: might not have been initialized
}
}Default field 'count': 0
Inside block: 10Java data types overview
Java (21+) includes two broad categories: primitive types and reference types.
Primitive types (8)
- Integers:
byte,short,int,long - Floating point:
float,double - Character:
char - Boolean:
boolean
Use int for whole numbers by default; use long for very large integers. Use double for most real numbers. Use boolean for true/false logic, char for single Unicode characters.
Reference types
Everything else is a reference type: String, arrays (int[]), classes, interfaces, records, and enums. Reference variables hold references that point to objects in memory.
Primitive vs reference types (what’s the difference?)
- Primitives store actual values (e.g.,
42). - References store the address of an object (e.g., a
Stringobject). - Equality: For objects, use
.equals(...)to compare content;==compares references.
class="cd-keyword cd-access">public class StringEqualityDemo {
class="cd-keyword cd-access">public static void main(String[] args) {
String a = "hi";
String b = new String("hi");
System.out.println(a == b); // compares references
System.out.println(a.equals(b)); // compares content
}
}false
trueBeginner guide to Java type casting
- Widening (safe, automatic): small type to bigger type (e.g.,
inttodouble). - Narrowing (explicit, may lose data): bigger type to smaller type (e.g.,
doubletoint).
class="cd-keyword cd-access">public class CastingDemo {
class="cd-keyword cd-access">public static void main(String[] args) {
int items = 5;
double avg = items; // widening (int -> double)
System.out.println("avg = " + avg); // 5.0
double gpaExact = 8.75;
int gpaRoundedDown = (int) gpaExact; // narrowing, truncates
System.out.println("gpaRoundedDown = " + gpaRoundedDown); // 8
char letter = 'A';
int code = letter; // char -> int (Unicode code point)
System.out.println("code = " + code); // 65
// Type mismatch example (would not compile if uncommented):
// int x = 10.5; // Error: cannot convert from double to int
}
}avg = 5.0
gpaRoundedDown = 8
code = 65Java operators explained with simple programs and output
Operators perform actions on variables and values. Below are the most common groups you will use in beginner programs.
Arithmetic operators
+,-,*,/,%- Unary:
++,--
Integer division truncates toward 0. To get a decimal result, make at least one operand a floating-point number.
class="cd-keyword cd-access">public class ArithmeticDivisionDemo {
class="cd-keyword cd-access">public static void main(String[] args) {
int a = 5, b = 2;
System.out.println(a / b); // 2 (int division)
System.out.println(5 / 2.0); // 2.5 (double division)
// Avoid double/float for money; use BigDecimal for exact decimals
System.out.println(0.1 + 0.2); // 0.30000000000000004
java.math.BigDecimal x = new java.math.BigDecimal("0.1");
java.math.BigDecimal y = new java.math.BigDecimal("0.2");
System.out.println(x.add(y)); // 0.3
}
}2
2.5
0.30000000000000004
0.3Relational and logical operators
- Relational:
<,<=,>,>=,==,!= - Logical:
&&(AND),||(OR),!(NOT) - Short-circuit: with
&&and||, the right side may not run if not needed.
class="cd-keyword cd-access">public class LogicalShortCircuitDemo {
static boolean riskyDivide(int n) {
System.out.println("Dividing 10 by " + n);
return 10 / n > 1; // would throw if n == 0
}
class="cd-keyword cd-access">public static void main(String[] args) {
int n = 0;
boolean ok = (n != 0) && riskyDivide(n); // right side not evaluated
System.out.println("ok = " + ok);
boolean value = true || riskyDivide(2); // not evaluated due to short-circuit
System.out.println("value = " + value);
}
}ok = false
value = trueBitwise and shift operators (integers)
- Bitwise:
&,|,^,~ - Shifts:
<<(left),>>(arithmetic right),>>>(logical right)
class="cd-keyword cd-access">public class BitwiseShiftDemo {
class="cd-keyword cd-access">public static void main(String[] args) {
int p = 0b1111; // 15
int q = 0b1010; // 10
System.out.println(p & q); // 10
System.out.println(p | q); // 15
System.out.println(p ^ q); // 5
int n = -8;
System.out.println(n >> 1); // -4 (arithmetic right shift)
System.out.println(n >>> 1); // 2147483644 (logical right shift)
}
}10
15
5
-4
2147483644Conditional (ternary) operator
The conditional operator ? : picks one of two values based on a boolean expression.
class="cd-keyword cd-access">public class ConditionalOperatorDemo {
class="cd-keyword cd-access">public static void main(String[] args) {
int marks = 72;
String result = (marks >= 33) ? "Pass" : "Fail";
System.out.println(result);
}
}PassModern Java pattern variables (Java 21)
Java 21 finalizes pattern matching for switch. A pattern can both test a type and bind a pattern variable if it matches. This is part of “Java 21 basics for students” you should know.
class="cd-keyword cd-access">public class PatternSwitchDemo {
static void printInfo(Object o) {
switch (o) {
case Integer i -> System.out.println("Twice: " + (i * 2));
case String s -> System.out.println("Length: " + s.length());
case null -> System.out.println("Null value");
default -> System.out.println("Unknown type: " + o.getClass().getSimpleName());
}
}
class="cd-keyword cd-access">public static void main(String[] args) {
printInfo(123);
printInfo("Java");
printInfo(3.14);
printInfo(null);
}
}Twice: 246
Length: 4
Unknown type: Double
Null valueCommon beginner mistakes and how to fix them
- Using
==for strings:==checks references, not content. Use.equals(). - Forgetting integer division:
5/2is2, not2.5. Use5/2.0or cast:(double)5/2. - Type mismatch errors: Assigning a
doubleto anintwithout a cast causes a compile-time error. - Not initializing local variables: Always assign a value before using local variables.
- Misusing
var: It’s only for local variables with an initializer; not for fields, parameters, ornull-only initializers. - Using
float/doublefor currency: Floating-point rounding can surprise you. For money, preferBigDecimal.
- Pick types wisely:
int(whole),double(decimal),boolean(true/false),String(text). - Initialize local variables before use; fields get defaults, locals do not.
- Use literal suffixes when needed:
Lforlong,Fforfloat(e.g.,10L,3.5F). - Compare strings with
.equals(), not==. - Force decimal division when needed:
5/2.0or(double)a / b. - Money math: prefer
BigDecimalwith string constructors. - Using
var? It must be a local variable with an initializer; not for fields ornull-only. - Watch overflow: promote to
longbefore large multiplications (e.g.,100000L * 100000). - Use parentheses to clarify complex boolean expressions.
- Print values while learning:
System.out.println("x = " + x);
Practice exercises using Java data types and operators for students
- Temperature converter
- Read a Celsius value in a variable, convert to Fahrenheit using
F = C * 9/5 + 32. Print both. - Try with
intand withdouble; observe the difference.
- Read a Celsius value in a variable, convert to Fahrenheit using
- Marks grading
- Use the conditional operator to print
"Pass"/"Fail"from amarksvariable. - Extend with ranges:
Afor90+,Bfor80+, etc.
- Use the conditional operator to print
- Bitwise practice
- Given
int mask = 0b0101;andint value = 0b1100;, print results of&,|, and^. - Shift
valueleft and right, and print results.
- Given
- Type casting challenge
- Store
3.99in adouble, cast it toint, and explain the result. - Store
'₹'incharand print its code point asint.
- Store
FAQ: Java variables, data types and operators for beginners
What is a variable in Java and how do I declare one?
A variable is a named container for a value. Declare it with type name = value; For example: int count = 5;. In Java 10+, you can use var for local variables with an initializer: var count = 5;.
Which data types does Java 21 include and when should I use them?
Java has 8 primitives: byte, short, int, long, float, double, char, boolean; plus reference types like String, arrays, classes, records, and enums. Start with int for whole numbers, double for real numbers, and boolean for true/false.
What is the difference between primitive and reference types in Java?
Primitives hold raw values (e.g., 10), while reference types hold addresses to objects (e.g., String). For objects, compare content with .equals() instead of ==.
How do Java arithmetic and logical operators work with examples?
Arithmetic operators like +, -, *, /, and % do math. Logical operators &&, ||, and ! combine booleans. For instance, 5/2 yields 2 (integer division), while 5/2.0 yields 2.5.
Why do I get type mismatch errors and how can I fix them in Java?
They happen when you assign a value of one type to a variable of another incompatible type. Fix by matching types or adding an explicit cast when safe (e.g., int x = (int) 10.5;), but remember narrowing casts can lose data.
Notes for learners on Java 21+
- Local variable type inference (
var) keeps Java statically typed; it only infers types for local variables with initializers. - Pattern matching for
switchis finalized in Java 21 and introduces pattern variables safely. - String Templates were a preview in Java 21/22 but were withdrawn in Java 23, so do not rely on them in production learning paths.
- These fundamentals are stable from Java 21 to the current releases (Java 25 LTS and beyond).
Keep learning
Continue with more beginner-friendly lessons and examples in our Java track: CodDesire Java Tutorials.
Sources / Further reading
- Java Language Specification (SE 21): JLS 21 PDF
- Expressions and operators (current online): JLS Chapter 15
- Local Variable Type Inference (
var): Oracle Language Guide - Pattern Matching for switch (Java 21): JEP 441
- Operators tutorial (Oracle): Java Tutorials
- String Templates preview and withdrawal: JEP 430 and JDK 23 Changes
BigDecimalAPI: Java SE API


