Java basics, part 1: values, text and decisions
Part of the free Low-Level Design course on LogicWiz, in the chapter: Start here: your machine and Java. The class-diagram exercises run in the app.
Java basics, part 1: values, text and decisions
"This if (code == "SAVE10") printed the right discount on your laptop. Do you know why it can fail in the test?"
Priya, reviewing Arjun's first Java coupon code
The shape of a Java file
Priya sets each Java construct beside the language you know, so you can map one to the other. Here is a whole program.
public class Receipt {
// prints one line
public static void main(String[] args) {
int quantity = 2;
System.out.println("Milk x " + quantity);
}
}
It prints Milk x 2. A class is a named box that holds code. The next chapters teach classes properly. For now, every Java file has one, and the program starts at main. The file is named after its class, here Receipt.java.
| Idea | Java | Python | JavaScript | C++ |
|---|---|---|---|---|
| End of a statement | ; |
end of line | ; |
; |
| A block of code | { } |
indent | { } |
{ } |
| A comment | // note |
# note |
// note |
// note |
| Print a line | System.out.println(x) |
print(x) |
console.log(x) |
std::cout << x << "\n" |
| Where it starts | main in a class |
top of the file | top of the file | int main() |
Java names variables and methods in camelCase, such as totalPaise, and classes in PascalCase, such as CartItem.
Types: why Java asks what each value is
Every Java variable has a type, written before its name. The type says what the variable may hold.
| Java | Holds | Python | JavaScript | C++ |
|---|---|---|---|---|
int |
whole number, up to about 2.1 billion | int |
number |
int |
long |
whole number, up to about 9 quintillion; write 6800L |
int |
number |
long long |
double |
decimal number | float |
number |
double |
boolean |
true or false |
bool |
boolean |
bool |
char |
one character, 'a' |
a short str |
a short string |
char |
String |
text, "milk" |
str |
string |
std::string |
Python learners meet three surprises here. Look at them in order.
int big = 2_000_000_000;
System.out.println(big + big); // -294967296
long safe = 2_000_000_000L;
System.out.println(safe + safe); // 4000000000
System.out.println(0.1 + 0.2); // 0.30000000000000004
System.out.println(7 / 2); // 3
System.out.println(7 / 2.0); // 3.5
An int that goes past its limit wraps around to a negative number, with no error. That is why SwiftKart keeps money in paise as a long. A double cannot store 0.1 exactly, so money in double drifts. And 7 / 2 between two whole numbers drops the fraction, so the answer is 3, not 3.5. Python's / always gives a decimal. Java's does not.
Why is Java typed? Look at this line.
int count = "five";
// error: incompatible types: String cannot be converted to int
The compiler refuses it before anything runs. In Python the same slip waits until some line treats the text as a number, maybe in production. A type also documents the design: a method long priceFor(int quantity) tells you what goes in and what comes out.
The word var lets the compiler work out the type from the value: var total = 0L; makes a long. The variable is still typed. Writing total = "five" later is still an error. You may use var only for local variables, never for fields or parameters. Use it when the type is obvious.
Text: String and the == trap
Arjun said, "In Python I compare text with ==. Java must be the same." It is not.
String a = "Milk";
String b = new String("Milk");
System.out.println(a == b); // false
System.out.println(a.equals(b)); // true
For text, == asks whether two names point at the same object in memory. It does not compare the letters. equals compares the letters. Two identical words typed in your code are stored once, so == says true for them. The same text read from a file, a user or a calculation is a different object, and == says false. That makes the bug hard to see. That is why code == "SAVE10" passes on your laptop and fails in a test. Always use equals. C++ std::string and Python compare content with ==, so this trap is Java's own.
A String never changes. Methods such as toUpperCase() return a new string and leave the old one alone.
| Task | Java | Python | JavaScript |
|---|---|---|---|
| Length | s.length() |
len(s) |
s.length |
| One character | s.charAt(0) |
s[0] |
s[0] |
| Part of it | s.substring(1, 3) |
s[1:3] |
s.substring(1, 3) |
| Contains | s.contains("ilk") |
"ilk" in s |
s.includes("ilk") |
| Split | s.split(",") |
s.split(",") |
s.split(",") |
| Same text | a.equals(b) |
a == b |
a === b |
| Remove edge spaces | s.strip() |
s.strip() |
s.trim() |
Join text with +, as in "Rs " + 181.
Decisions: if and switch
An if needs a condition in brackets, and the condition must be a boolean.
if (quantity > 10) {
System.out.println("Too many");
} else if (quantity == 0) {
System.out.println("Nothing to add");
} else {
System.out.println("Added");
}
Python lets if count: mean "not zero". Java does not: write count > 0. Use && for and, || for or, and ! for not. Python writes and, or and not. Comparing numbers with == is fine. Comparing text is not, as you saw.
A switch picks one branch from a list of values. The arrow form below is the one to use.
static long deliveryFeePaise(String slot) {
return switch (slot) {
case "EXPRESS" -> 4900;
case "STANDARD" -> 2900;
default -> 0;
};
}
This switch is an expression: it gives back a value. Each arrow gives the result for its case, and default covers every other value. JavaScript and C++ use case X: with break. Without break, they fall through into the next case. The arrow form has no fall-through. Python's match is the closest relative. C++ switch accepts only whole numbers and enums, but Java's accepts strings as well.
Loops over numbers and arrays
| Task | Java | Python | JavaScript | C++ |
|---|---|---|---|---|
| Count | for (int i = 0; i < n; i++) |
for i in range(n): |
for (let i = 0; i < n; i++) |
for (int i = 0; i < n; i++) |
| Each item | for (int q : quantities) |
for q in quantities: |
for (const q of quantities) |
for (int q : quantities) |
| While true | while (n > 0) |
while n > 0: |
while (n > 0) |
while (n > 0) |
An array, written int[], has a fixed size. Its size is quantities.length, with no brackets. A String uses length() with brackets. Everyone mixes these up once.
long[] pricesPaise = {6800, 4500, 3200};
int[] quantities = {2, 1, 3};
long total = 0;
for (int i = 0; i < pricesPaise.length; i++) {
total += pricesPaise[i] * quantities[i];
}
int units = 0;
for (int q : quantities) {
units += q;
}
System.out.println(total + " paise, " + units + " units");
// 27700 paise, 6 units
The first loop needs the position i, because it reads two arrays side by side. The second loop wants only each value, so the enhanced for is shorter and has no position to get wrong. break leaves a loop and continue skips to the next round, as in every language.
Methods, static and printing
A method names a piece of work. Its header gives the return type, then the name, then the inputs with their types.
public class Prices {
static long lineTotal(long pricePaise, int quantity) {
return pricePaise * quantity;
}
static String rupees(long paise) {
return String.format("Rs %d.%02d", paise / 100, paise % 100);
}
public static void main(String[] args) {
System.out.println(rupees(lineTotal(6800, 2)));
// Rs 136.00
}
}
void as a return type means the method gives nothing back. Java copies each input into the method, so a method cannot change the caller's variable.
The word static means the method belongs to the class, not to an object, so main can call it with no object. A helper that needs no object's data is a fine static method. A method that uses an object's own fields is not static. The object-oriented chapter shows that.
Printing has three forms. println prints and ends the line. print does not end the line. String.format and printf fill in placeholders: %d for a whole number, %s for text, %.2f for a decimal with two places. Python's f-strings and JavaScript's template strings do the same job.
Now draw a small class diagram. Every other chapter has exercises like this. An order holds many lines. Each line has a product name, a quantity and a price in paise. Split the order into two boxes and join them with a line.
📌 Summary: Java checks types before running. Keep money in long paise, compare text with equals and never ==, prefer the arrow switch, and give each helper a clear signature.
What Arjun learns next
Arjun can now read and write Java's basic statements. Next, Priya shows him the collections he will use in every problem: lists, maps, sets and queues, plus null and exceptions.
Check your understanding
- Arjun reads a coupon code from the user and writes if (code == "SAVE10"). It passes on his laptop and fails in the test. What is the real problem?
- A cart total of 2,000,000,000 paise plus another 2,000,000,000 paise is added in an int and prints a negative number. Why?
- What does this code hold in half? long half = 7 / 2;
- You need to add up every value in the array int[] quantities, and the position of each value does not matter. Which loop is the best fit?