Module 1 · Java from zero Lesson 2 of 15
Types, variables and casting
Java is statically typed: every variable has a type fixed at compile time. That is why Java programs fail at compile time instead of at 3am, and why interviews start with types.
The concept
Java is statically typed: you declare the type and it does not change. int, long, double, boolean, char and String cover fresher work — note that String starts with a capital, because it is a class and the others are primitives. Declaring the type is what stops a whole class of bugs before they compile.
Narrowing needs an explicit cast and loses information: (int) 9.8 gives 9, and integer division is why 7 / 2 is 3. Widening is automatic and safe. If you need exact money arithmetic, neither is good enough — use BigDecimal, which is what a service-company interviewer is checking when they ask about double.
int age = 21; // whole number
double marks = 88.5; // decimal
boolean placed = false;
char grade = 'A';
String name = "Asha"; // a class, not a primitive
int rounded = (int) marks; // narrowing CAST drops the decimals
String text = Integer.toString(age);
int back = Integer.parseInt(text); // text -> numberCommon mistakes
The mistakes are comparing strings with == instead of .equals() — == compares references, which happen to match inside the string pool and fail on text from a file — and reading a number as a String from Scanner and then doing arithmetic on it. Integer.parseInt() is the bridge.
Worked example
int a = 7; int b = 2; a / b is 3, not 3.5 — integer division truncates. Write (double) a / b and it becomes 3.5. Knowing this one line separates candidates who have run Java from candidates who have read about it.
Your practice task
Write a small calculator that takes the four operations and prints results as decimals, then check the division case carefully.
Do this before moving on. Reading a solution teaches the shape of it; typing it teaches you.
Key takeaway
Java is statically typed: you declare the type and it does not change.
Keep your place in this course
A free account saves which lessons you have finished and unlocks the certificate. The lesson itself stays free to read.
Create free account or sign inCourse complete
You finished every lesson.
Your certificate is ready, and the projects you built are the proof to attach to an application.
Almost there
15 lessons left of 15
Finish every lesson to unlock the certificate. Each one ends in a practice task — do them and the final project brief writes itself.
