skip to content

Syntax & Basic Constructs

The lexical and structural rules of Java source: identifiers, keywords, comments, statements, blocks and scope. Quick to learn and quick to check, which is why screening questions start here.

part ofJavaoverview, primer and where to startread it →
on this pageshow

explore

questions

28

What is a block statement in Java, and what does it have to do with variable scope?

level: juniorimportance: must knowfreq 55%

answer

  1. Block = statements inside { }
  2. Block is itself one statement
  3. Local var visible: declaration → closing brace
  4. Not usable before declaration or after block
  5. Bare {} block scopes variables narrowly

basics

~20 s

A block is code wrapped in curly braces { }. It groups statements together. A variable you declare inside a block can only be used inside that block; once the block ends, the variable is gone.

solid answer

~40 s

A block is a sequence of statements enclosed in curly braces. It serves two purposes: it lets you treat several statements as a single unit (for example, the body of an if or a loop), and it defines a scope. A variable declared inside a block is a local variable whose scope is limited to that block and any blocks nested inside it. From the point of declaration to the closing brace, the name is visible; after the closing brace it no longer exists and cannot be referenced. This keeps variables short-lived, prevents accidental reuse, and lets the compiler reclaim the name. You can also write a 'bare' block (just braces, not attached to any statement) purely to scope variables narrowly.

go deeper

for a junior

Knows a block is code in curly braces and that variables declared inside are only usable inside.

for a middle

Articulates scope as 'declaration to closing brace', distinguishes scope from lifetime, and knows bare blocks exist.

for a senior

Explains why narrowing scope improves readability and prevents stale-value bugs; connects per-entry variable instantiation to loops and method calls.

for a principal

Frames scope minimization as a design discipline (locality, immutability bias) and can reason about how it interacts with the compiler's definite-assignment and reachability analysis.

## What a block is In Java, a **block** is a group of zero or more statements enclosed in a pair of curly braces `{ }`. Syntactically, a block is itself a single statement, so anywhere Java allows one statement you can put a block instead. That is why the body of an `if`, `for`, `while`, `try`, a method, or a constructor is written as a block. ```java { int x = 1; System.out.println(x); } ``` The two outermost braces above form a block containing two statements. ## What 'scope' means **Scope** is the region of source code in which a name (such as a variable name) is *visible* — meaning the compiler will let you refer to it. Outside its scope, the name simply does not exist as far as the compiler is concerned, and using it is a compile error. ## The rule for block-local variables When you declare a **local variable** inside a block, its scope runs **from the point of its declaration to the end of the enclosing block** (the matching closing brace). Two consequences: 1. You cannot use the variable *before* the line that declares it. 2. You cannot use it *after* the block closes. ```java void demo() { // x is not visible here yet int x = 10; // declaration System.out.println(x); // OK, inside scope } // x's scope ends here // x is not visible here anymore ``` ## Lifetime vs. scope *Scope* is about source-code visibility; *lifetime* is about when the variable's storage exists at runtime. For a block-local variable these line up closely: the variable comes into being when control reaches its declaration and is eligible to be discarded when the block exits. Each time a block is entered (for example, each iteration of a loop body, or each call of a method) a fresh instance of the local variable is created. ## Bare blocks You can write a block that is not attached to any control statement, just to limit a variable's scope: ```java void f() { { int temp = compute(); use(temp); } // temp gone here // temp cannot be referenced now } ``` This is occasionally used to keep a helper variable from leaking into the rest of a method. ## Why it matters Limiting scope to the smallest block that needs a variable makes code easier to read, prevents accidental reuse of a stale value, and lets the compiler/JVM manage the name efficiently. It is a core part of writing clean Java.

  • Can you reference a local variable on a line above its declaration within the same block?
    No. A local variable's scope starts at its declaration, so any reference earlier in the block is a compile error ('cannot find symbol' / used before declaration).
  • What is a 'bare' block and when would you use one?
    A standalone { } not attached to any statement. You use it to limit a helper variable's scope so it does not leak into the rest of the method.

saying these in an interview costs you the question

  • Thinking a variable declared in a block is visible after the block ends
  • Claiming you can use a local variable before its declaration line
  • Confusing a block with a method — any { } pair can be a block
  • Believing blocks are only the bodies of if/for/while

context

open as a page

What kinds of comments does Java support, and what is the syntax for each?

level: juniorimportance: must knowfreq 70%

basics

~20 s

Java has three: single-line starting with //, multi-line wrapped in /* ... /, and Javadoc written as /* ... */ which is a documentation comment the javadoc tool reads. All of them are ignored by the compiler.

open as a page

What are the standard Java naming conventions for identifiers, and how do conventions differ from the compiler's rules?

level: juniorimportance: must knowfreq 60%

basics

~20 s

Rules are what the compiler enforces; conventions are agreed style. By convention: classes use UpperCamelCase, variables and methods use lowerCamelCase, constants use UPPER_SNAKE_CASE, and packages are all lowercase. Breaking a convention still compiles, but it's bad style.

open as a page

What are keywords (reserved words) in Java, and why can't you use them as identifiers?

level: juniorimportance: must knowfreq 70%

basics

~10 s

Keywords are words Java reserves for its own grammar (like class, if, return, int). The compiler treats them specially, so you can't use them to name your own variables, methods, or classes.

open as a page

In Java, what is the difference between an expression and a statement?

level: juniorimportance: must knowfreq 70%

basics

~20 s

An expression produces a value (like 2 + 3 or x). A statement performs an action and is a complete instruction the program runs (like x = 5; or an if). Expressions compute things; statements do things.

open as a page

What is the role of the semicolon in Java, and what counts as a statement that needs one?

level: juniorimportance: must knowfreq 40%

basics

~20 s

The semicolon ends a statement, like a period ends a sentence. Each instruction - a variable declaration, an assignment, a method call, return - finishes with a ';'. Blocks wrapped in { } and class/method headers do not take one.

open as a page

Is whitespace significant in Java? Explain where it matters and where it doesn't.

level: juniorimportance: must knowfreq 35%

basics

~20 s

Mostly no. Java ignores spaces, tabs, and blank lines between tokens, so you can add them freely for readability. But you need at least one space to separate words like 'int x', and whitespace inside text in quotes is kept exactly.

open as a page

In Java, can an inner block declare a variable with the same name as one in an enclosing block?

level: middleimportance: must knowfreq 60%

basics

~20 s

No. Unlike fields, a local variable in an inner block cannot reuse the name of a local variable from an enclosing block — the compiler reports an error. The inner block can still see the outer variable, but it cannot redeclare it.

open as a page

Which commonly-mistaken Java words are NOT keywords (e.g. String, System, main, length)? How do you tell a keyword from a library identifier?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Words like String, System, main, args, and length are NOT keywords — they're class names, method names, or fields from the libraries. Keywords are the fixed grammar words like class, public, and void. You could even reuse the library names as your own (though it's a bad idea).

open as a page

What are instance initializer blocks and static initializer blocks, and how do they relate to scope and initialization order?

level: middleimportance: should knowfreq 30%

basics

~20 s

Besides ordinary blocks, a class can have a bare { } block (instance initializer) that runs when an object is created, and a static { } block that runs once when the class is loaded. Variables you declare inside these blocks are local to the block, but they can read and set the class's fields.

open as a page

Why can't block comments be nested in Java, and what happens if you try?

level: middleimportance: should knowfreq 55%

basics

~20 s

A block comment ends at the very first / the compiler sees. So if you put one / */ inside another, the inner */ closes the whole thing, and the leftover text after it becomes real code that usually fails to compile.

open as a page

When should you write a comment in Java, and when does a comment signal a deeper code-quality problem?

level: middleimportance: should knowfreq 50%

basics

~20 s

Comment to explain WHY, not WHAT. If a comment just restates the code, rename things or extract a method instead. Use Javadoc for public APIs. Comments that explain confusing code often mean the code should be made clearer.

open as a page

Can Java identifiers contain Unicode (non-ASCII) characters? Explain what 'letter' means in the identifier rules.

level: middleimportance: should knowfreq 40%

basics

~20 s

Yes. Java allows Unicode letters in identifiers, so you can use characters from other languages, like accented letters or non-Latin scripts. A 'letter' is not limited to A–Z; many Unicode letter characters and currency symbols are allowed too.

open as a page

What are the `goto` and `const` keywords in Java, and why are they reserved if they do nothing?

level: middleimportance: should knowfreq 45%

basics

~20 s

goto and const are reserved words in Java but they have no use — you cannot write working code with them. Java reserved them so they can't be variable names and to leave the door open and give clearer errors.

open as a page

What is an expression statement in Java, and why are only certain expressions allowed to be used as statements?

level: middleimportance: should knowfreq 45%

basics

~20 s

An expression statement is an expression followed by a semicolon, like x = 5; or list.add(y);. Java only allows expressions that have a useful side effect (assignment, ++/--, method call, new). A bare value like a + b; is rejected because computing and discarding it is pointless.

open as a page

If indentation and spacing are meaningless to the compiler, why do formatting conventions and tools matter on a real team?

level: middleimportance: should knowfreq 18%

basics

~10 s

The compiler ignores formatting, but people don't. Consistent indentation and spacing make code easy to read, review, and change. Teams use auto-formatters so everyone's code looks the same and diffs only show real changes.

open as a page

When is whitespace actually required between tokens in Java, and what rule of the lexer makes it necessary?

level: middleimportance: should knowfreq 22%

basics

~20 s

You need whitespace when two pieces of code would otherwise stick together into one word, like 'int x' (without the space it becomes the single name 'intx'). The compiler reads the longest possible word at a time, so it can't split joined words by itself.

open as a page

How do block scope and reachability interact with Java's definite-assignment rule for local variables?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Local variables get no default value, so Java forces you to assign one before you read it. The compiler checks this per path through the code. Where you declare a variable (which block) and which branches assign it decide whether every path has given it a value.

open as a page

Why does declaring a variable inside versus outside a loop body matter, especially for lambdas/closures that capture it?

level: seniorimportance: should knowfreq 45%

basics

~20 s

A variable declared inside the loop body is fresh on every iteration; one declared outside is shared across all iterations. This matters for lambdas, which can only capture variables that are effectively final — a fresh per-iteration variable can be captured, a shared mutating one cannot.

open as a page

Why is a comment delimiter like // or /* ignored when it appears inside a string literal?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Inside a string the characters are just data, not source syntax. The lexer knows it is reading a string, so it does not treat // or /* as comment starters. So System.out.println("http://x") prints the whole URL.

open as a page

Why is a single underscore (_) by itself no longer a valid identifier in modern Java?

level: seniorimportance: should knowfreq 35%

basics

~10 s

A lone underscore (_) used to be a legal name, but modern Java reserved it. You can no longer use just _ as a variable name; it now marks an unnamed (ignored) variable instead.

open as a page

What are contextual (restricted) keywords in Java, and how do they differ from regular reserved keywords? Give examples like var, yield, record, sealed, permits.

level: seniorimportance: should knowfreq 50%

basics

~10 s

Contextual keywords (like var, yield, record, sealed) only act as keywords in certain places. Everywhere else they're ordinary names, so old code that used them as variable names still compiles.

open as a page

How does a switch expression differ from a switch statement in Java, and what does this reveal about the expression/statement distinction?

level: seniorimportance: should knowfreq 40%

basics

~20 s

A switch statement performs branching but produces no value. A switch expression (Java 14+) evaluates to a value you can assign or return, using arrow labels (case A -> ...) or yield. So the same keyword can be either a statement (does an action) or an expression (produces a value).

open as a page

Are `true`, `false`, and `null` keywords in Java? Where do they fit among reserved words?

level: middleimportance: nice to knowfreq 35%

basics

~10 s

Technically they are reserved literals, not keywords — true/false are boolean literals and null is the null literal. But like keywords, you cannot use them as names.

open as a page

What is the empty statement in Java, and when can it cause subtle bugs?

level: middleimportance: nice to knowfreq 30%

basics

~20 s

The empty statement is just a single semicolon (;) that does nothing. It is legal anywhere a statement is allowed. It causes bugs when a stray semicolon ends a loop or if early, e.g. while (cond); accidentally makes an empty loop body.

open as a page

Why is Java a free-form (whitespace-insignificant, semicolon-terminated) language, and what are the design tradeoffs versus indentation-significant or semicolon-optional languages?

level: seniorimportance: nice to knowfreq 12%

basics

~20 s

Java separates how code looks from what it means: braces define blocks and semicolons end statements, so spacing is free. This makes parsing simple and unambiguous. Python instead uses indentation for structure, and JavaScript guesses missing semicolons - each choice trades off layout flexibility against safety and simplicity.

open as a page

Why is Java largely statement-oriented rather than expression-oriented, and what are the design trade-offs of each approach?

level: principalimportance: nice to knowfreq 18%

basics

~20 s

In an expression-oriented language almost everything produces a value (even if/blocks). Java is mostly statement-oriented: control flow like if/for produces no value, and you sequence actions explicitly. Statement-orientation is simpler and explicit; expression-orientation reduces boilerplate and mutable variables.

open as a page