Your language · Java
Basics: types, variables and operators
Data types, variables, operators, type conversion and how values are stored.
Learn: Java basics: types, variables and operators8 minute read
Basics questions check that you know how Java stores simple values such as numbers and true or false. Interviewers ask them first because small mistakes here become real test bugs. If you expect 5 / 2 to be 2.5, or compare two Integer objects with ==, an assertion (a check in a test that must be true) can pass or fail for the wrong reason.
Step 1: primitive types and reference types
A primitive type holds a plain value, and it can never be null (null means "no value"). Java has eight of them. A bit is one 0 or 1 in memory, so a type with more bits can hold bigger numbers:
- whole numbers:
byte(8 bits),short(16),int(32) andlong(64); - decimals:
float(32 bits) anddouble(64 bits, the type of a literal such as2.5); char: one 16-bit character in single quotes, such as'A';boolean: true or false.
Every other type is a reference type: String, arrays, your own classes, enums (explained in step 4) and records (a short way to write a class that only holds data). A reference variable holds a reference (the address of an object in memory), so it can be null.
Each primitive has a wrapper class, an object version of it: Integer, Double, Boolean and so on. Collections store objects only, so a list of numbers is a List<Integer>. Java converts int to Integer for you (autoboxing) and back (unboxing).
Step 2: local, instance and static variables
- A local variable is declared inside a method (a named block of code you can call). It has no default value, so the compiler refuses to let you read it before you assign it.
- An instance variable (a field) belongs to one object. Each object has its own copy, and it starts at a default: 0, false or null.
- A static variable belongs to the class. All objects share one copy.
Since Java 10 you can write var for a local variable that has a starting value: var users = new ArrayList<String>();. The compiler works out the type and fixes it, so Java stays statically typed: every variable has one type, checked before the program runs.
Step 3: arithmetic and conversions
When both operands are integers, / drops the fraction and % gives the remainder. Integer division cuts toward zero, so -7 / 2 is -3. If one operand is a double, Java first converts the other one, and the result is a double. This is called type promotion.
Integer arithmetic never throws on overflow. A sum past the largest int wraps around to a large negative number. Among the plain operators, only integer division or remainder by zero throws ArithmeticException; a double divided by zero gives Infinity. (An exception is an error that Java raises while the program runs; see Exceptions.)
Java widens automatically from a smaller type to a larger one, such as int to long. Going the other way needs a cast, written (int) x, and it can lose data: (int) 3.99 is 3 and (byte) 200 is -56. To turn text into a number use Integer.parseInt("42") or Double.parseDouble; text that is not a number throws NumberFormatException.
public class Main {
public static void main(String[] args) {
System.out.println(5 / 2); // integer division
System.out.println(5 / 2.0); // one double makes a double
System.out.println(-7 / 2 + " " + -7 % 2);
System.out.println((int) 3.99 + " " + (byte) 200);
int max = Integer.MAX_VALUE;
System.out.println(max + 1); // wraps silently
System.out.println(max + 1L); // long has room
Integer a = 127, b = 127, c = 128, d = 128;
System.out.println((a == b) + " " + (c == d) + " " + c.equals(d));
int total = Integer.parseInt("40") + 2;
System.out.println("total=" + total);
}
}
2 2.5 -3 -1 3 -56 -2147483648 2147483648 true false true total=42
The Integer line surprises many people. Autoboxing calls Integer.valueOf, which keeps one shared object for each value from -128 to 127. So a == b is true only because both point at the same cached object, while c == d compares two different objects. Compare wrapper values with equals().
A price read from a page is text, so clean it and parse it before you compare:
String priceText = "1,299.50";
double price = Double.parseDouble(priceText.replace(",", ""));
assert Math.abs(price - 1299.50) < 0.001;
Step 4: the main method, enums and serialisation
The java launcher (the java command that starts your program) begins at public static void main(String[] args). It is public so the launcher can call it, static because no object exists yet, and void because it returns nothing. args holds the command-line arguments, which are the words you type after the program name; with none, it is an empty array, not null.
An enum is a type with a fixed list of named constants. It is a real class, so it can hold fields and methods. Testers use enums for browsers, environments and user roles, so a typo becomes a compile error.
public class Main {
enum Env {
QA("https://qa.example.com"), PROD("https://example.com");
private final String url;
Env(String url) { this.url = url; }
String url() { return url; }
}
public static void main(String[] args) {
Env env = Env.valueOf("QA"); // text to constant
System.out.println(env + " " + env.url() + " " + env.ordinal());
System.out.println(Env.values().length + " environments");
System.out.println("arguments: " + args.length);
}
}
QA https://qa.example.com 0 2 environments arguments: 0
Serialisation turns an object into bytes or text so it can be saved or sent; deserialisation rebuilds it. Testers mostly meet it as JSON, when a library such as Jackson (a Java JSON library) maps API bodies to objects.
How to answer in an interview
Give the rule in one sentence, then prove it with one line of code. For "primitive or wrapper?" you might say: "A primitive holds the value and cannot be null. A wrapper is an object, so it can be null and can go into a collection. Because it is an object, == compares references, so I use equals()." For a "what does this print?" question, read the expression left to right and say the type of each part: "5 / 2 is int division, so it is 2."
Common mistakes
- Comparing
IntegerorLongvalues with==. It works up to 127 and then breaks. - Unboxing a null, for example
int count = map.get("missing");. This throwsNullPointerException. - Expecting an error on overflow. Use
longfor large totals, orMath.addExactwhen an overflow should fail loudly. - Comparing decimals with
==.0.1 + 0.2is 0.30000000000000004, so compare with a small tolerance or useBigDecimal(a class for exact decimal numbers).
Recap
Eight primitives hold values; everything else is a reference to an object. Wrappers can be null and are compared with equals(). Integer division drops the fraction, overflow wraps silently and narrowing casts can lose data. Local variables need a value before use; fields get defaults.
11 questions0/11 solved
| Status | Question | Difficulty | Asked in |
|---|---|---|---|
| Not started | Which of these are primitive types? | Easy | Asked in: Infosys, TCS, Tech Mahindra |
| Not started | Primitive vs wrapper types, local vs instance variables | Easy | Asked in: Infosys, TCS, Tech Mahindra |
| Pro+ | Comparing Integer objects with == | Easy-Medium | Asked in: Capgemini, Infosys, TCS +1 |
| Pro+ | Explain each part of public static void main(String[] args) | Easy | Asked in: Accenture |
| Pro+ | Integer division and type promotion | Easy-Medium | |
| Pro+ | What happens when an int overflows? | Easy-Medium | Asked in: PayPal |
| Pro+ | What is true about var? | Easy-Medium | |
| Pro+ | Enums and when to use them | Easy-Medium | Asked in: Wipro |
| Pro+ | Serialisation and deserialisation of objects | Medium | Asked in: Capgemini, Wipro |
| Pro+ | A class without main, and two public classes in one file | Medium | Asked in: TCS |
| Pro+ | Which language do you automate in, and why? | Easy |
The first 2 questions of each topic are free. Pro+ opens every question.