Java Variables — Java Technical Interview Questions & Answers
Java Variables
Java Variables
- A variable is a named box that holds a value. int age = 21; means an integer box called age with 21 inside. Java wants the type first so it knows what can go in the box.
- A local variable lives only inside a method. An instance variable belongs to each object. A static variable belongs to the class and is shared by all objects. Use names like studentName, not x1.
- If you use a local variable before giving it a value, Java will not compile. Give it a value first. In an interview, show one local, one instance, one static example.
- Let's take this on the board with one tiny Main class — no extra files. Java Variables — output: Asha is 21. age is int, name is String — two real variables. Start from main, go line by line, and stop at each print. That output is the proof for Variables.
Technical Interview Tip: Show one local, one instance, one static. Say where each lives.
Code Examples for Java Variables
Example
public class Main {
public static void main(String[] args) {
int age = 21;
String name = "Asha";
System.out.println(name + " is " + age);
}
}Java Variables — output: Asha is 21. age is int, name is String — two real variables.
How to Explain Java Variables to an Interviewer
What is a variable?
Named box Holds a value int age = 21
Local vs instance vs static?
Local = method Instance = each object Static = class, shared
What if a local has no value?
Compile error