0% found this document useful (0 votes)
56 views27 pages

Java Ch2 Notes

This document provides comprehensive study notes for Java programming, specifically focusing on names and things, covering topics such as syntax, semantics, pragmatics, Java program structure, identifiers, variables, and primitive data types. It emphasizes the importance of understanding the differences between compile-time and runtime errors, the structure of Java programs, and naming conventions. Additionally, it outlines the eight primitive data types in Java, their sizes, ranges, and use cases, which are essential knowledge for interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views27 pages

Java Ch2 Notes

This document provides comprehensive study notes for Java programming, specifically focusing on names and things, covering topics such as syntax, semantics, pragmatics, Java program structure, identifiers, variables, and primitive data types. It emphasizes the importance of understanding the differences between compile-time and runtime errors, the structure of Java programs, and naming conventions. Additionally, it outlines the eight primitive data types in Java, their sizes, ranges, and use cases, which are essential knowledge for interviews.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Chapter 2 — Names & Things | Interview Notes

JAVA PROGRAMMING
Chapter 2: Names and Things
Comprehensive Interview-Level Study Notes

Topics Covered Content

Syntax, Semantics & 3 fundamental dimensions of a


Pragmatics language
Java Program Structure Classes, main(), compilation,
bytecode
Identifiers & Naming Rules Syntax rules + naming
conventions
Variables Memory model, assignment,
strong typing
Primitive Data Types All 8 types with ranges and use
cases
Literals Integer, real, char, boolean, string
literals
String Type Object type, escape sequences,
special behavior
Type Safety & Casting Strong typing rules, common
errors
Operators & Expressions Arithmetic, assignment, boolean
Quick Reference & Summary Tables, tips, interview Q&A

Page 1 of 27
Java Chapter 2 — Names & Things | Interview Notes

1. Introduction: The Three Dimensions of a Language


Every programming language — including Java — can be understood through three key dimensions.
These are not just academic concepts; interviewers frequently probe whether you understand the
difference between a program that compiles and a program that is correct and maintainable.

1.1 Syntax

Syntax refers to the formal rules that define what is a valid, well-formed program in a language. It is the
grammar of the programming language.

• Syntax rules are enforced at compile time by the Java compiler.


• A syntax error prevents compilation entirely.
• Examples of syntax rules: every statement ends with semicolon (;), curly braces must be
balanced, method must have a return type.
• Syntax is like the spelling and grammar rules of English — you must follow them to be
understood.

EXAMPLE
// Syntax ERROR — missing semicolon
int x = 5 // compiler will reject this

// Syntax CORRECT
int x = 5; // compiler accepts this

INTERVIEW TIP
Interviewers distinguish between compile-time errors (syntax) and runtime errors (semantic). Be
clear about which type of error you are discussing.

1.2 Semantics

Semantics refers to the meaning of a program — what it actually does when executed. A program can
be syntactically correct but semantically wrong.

• Semantic correctness means the program produces the correct output for all valid inputs.
• Semantic errors are also called logic errors — the program runs but gives wrong results.
• The compiler cannot catch semantic errors; only testing can reveal them.

EXAMPLE
// Syntactically CORRECT but Semantically WRONG
// Intent: calculate area of rectangle
int area = length + width; // should be length * width!

Page 2 of 27
Java Chapter 2 — Names & Things | Interview Notes

// This compiles fine, runs fine, but gives WRONG answer


// That is a SEMANTIC error

COMMON MISTAKE / TRAP


Many beginners confuse 'the program runs' with 'the program is correct'. A running program can
still have wrong output — always verify semantics through testing.

1.3 Pragmatics

Pragmatics refers to the style, readability, and conventions of writing good code. The computer is
completely indifferent to pragmatics, but human readers are not.

• Includes naming conventions, indentation, use of comments, and code organization.


• Good pragmatics makes code maintainable, readable, and collaborative.
• Following pragmatics earns you the respect of other programmers.
• In interviews, pragmatics shows that you write production-quality code, not just code that passes
test cases.

KEY POINT
Syntax = Rules for writing valid code | Semantics = Meaning/correctness of code | Pragmatics =
Style and readability of code. All three matter in professional development.

Page 3 of 27
Java Chapter 2 — Names & Things | Interview Notes

2. Java Program Structure


Understanding the structure of a Java program is essential — it is one of the first things an interviewer
tests. Every piece of a Java program has a purpose, and you must be able to explain each part.

2.1 The Hello World Program — Dissected

EXAMPLE
// A program to display the message
// 'Hello World!' on standard output

public class HelloWorld {


public static void main(String[] args) {
[Link]("Hello World!");
}
} // end of class HelloWorld

Component What it means Why it matters


public class Declares a public class named Class name must match
HelloWorld HelloWorld filename exactly
public Access modifier — visible from JVM (external) must see main()
outside to call it
static Belongs to class, not an instance JVM calls main() without
creating an object
void Return type — returns nothing main() is the start, not called for
a value
main(String[] args) Entry point method signature JVM always looks for this exact
signature
[Link](... Prints to standard output + Built-in subroutine call —
) newline predefined in Java
{ and } Block delimiters — start/end of Define scope; always must be
code balanced

INTERVIEW TIP
If asked 'why is main() public static void?', explain each keyword separately: public = accessible
by JVM, static = callable without an object, void = returns nothing to the caller.

2.2 Compilation & Execution Process

Java uses a two-step process: compilation to bytecode, then interpretation by the JVM. This is what
makes Java platform-independent (Write Once, Run Anywhere).

Page 4 of 27
Java Chapter 2 — Names & Things | Interview Notes

1. Write source code in a .java file (e.g., [Link])


2. Compile with javac — produces bytecode in a .class file ([Link])
3. Run with java command — the JVM interprets the bytecode on any platform

Source File (.java) Bytecode File (.class)


Source file: [Link] Compiled file: [Link]
Human-readable Java code Java bytecode (not machine code)
Contains class definition Platform-independent binary
Needed for editing/debugging What JVM actually executes
Text file Binary file

KEY POINT
Java is compiled to BYTECODE, not native machine code. The JVM then interprets/JIT-compiles
bytecode at runtime. This is different from C/C++ which compile directly to machine code.

2.3 Comments in Java

Comments are ignored by the compiler but essential for humans. Java has two types:

Comment Type Syntax Use Case Example


Single-line // text Brief explanations on one line // increment counter
Multi-line /* text */ Longer explanations, copyright /* This method sorts...
headers */
Javadoc /** text */ API documentation (auto- /** @param x the value
generates docs) */

COMMON MISTAKE / TRAP


Comments do NOT affect program behavior. Adding comments does not slow down your
program — they are stripped out at compile time. However, missing comments in professional
code is considered poor practice.

Page 5 of 27
Java Chapter 2 — Names & Things | Interview Notes

3. Identifiers and Naming


Names (identifiers) are used everywhere in Java — for classes, variables, methods, packages, and
more. Knowing the rules and conventions for naming is a core interview topic.

3.1 Syntax Rules for Identifiers

• Must begin with a letter, underscore (_), or dollar sign ($).


• After the first character, can contain letters, digits (0-9), underscores, or dollar signs.
• No spaces allowed anywhere in an identifier.
• No special characters like @, #, !, -, +, etc.
• Length is technically unlimited (practically limited by readability).
• Java uses Unicode — international characters count as letters.

Valid Identifiers Invalid Identifiers


N Hello World (space)
n 2rate (starts with digit)
rate class (reserved word)
x15 my-var (hyphen)
HelloWorld my@var (@sign)
quite_a_long_name if (reserved word)
_myVar int (reserved word)
$price null (reserved literal)

INTERVIEW TIP
$ is technically valid in Java identifiers but is reserved for compiler-generated names. You should
never use $ in your own code — avoid it in interviews too.

3.2 Case Sensitivity

Java is case-sensitive. The following are all different, unrelated identifiers:


EXAMPLE
HelloWorld // these are FOUR completely different names
helloworld
HELLOWORLD
hElloWorLD

COMMON MISTAKE / TRAP


A classic bug: naming a variable 'Count' in one place and referring to it as 'count' elsewhere.

Page 6 of 27
Java Chapter 2 — Names & Things | Interview Notes

Java will treat these as two separate variables and give a 'variable not found' error.

3.3 Reserved Words (Keywords)

Reserved words have special meaning in Java and cannot be used as identifiers. You must memorize
these for interviews:

abstract assert boolean break byte case


catch char class const continue default
do double else enum extends final
finally float for goto if implements
import instanceof int interface long native
new package private protected public return
short static strictfp super switch synchronize
d
this throw throws transient try void
volatile while true false null (reserved)

3.4 Naming Conventions (Pragmatics)

Element Convention Example Reasoning


Class names UpperCamelCase HelloWorld, Classes are 'things' —
(PascalCase) BankAccount capitalize like proper nouns
Variable lowerCamelCase interestRate, Distinguishes from classes at a
names myAccount glance
Method names lowerCamelCase calculateInterest(), Same as variables — action
getName() words are good
Constants UPPER_SNAKE_C MAX_VALUE, PI, Visually distinct to flag
ASE TAX_RATE immutable values
Package all lowercase [Link] Avoids conflicts with class
names names

KEY POINT
camelCase: Each word after the first is capitalized. 'interest rate' becomes 'interestRate'. This is
sometimes called 'camel case' because the capital letters in the middle look like humps.

3.5 Compound Names (Qualified Names)

Java allows compound names — multiple simple names separated by dots — to navigate a hierarchy
of containment.

Page 7 of 27
Java Chapter 2 — Names & Things | Interview Notes

EXAMPLE
[Link]("Hello");
// System = class in [Link] package
// out = a static field (PrintStream object) inside System
// println = a method of the PrintStream object

// Think of it as: [Link]

Page 8 of 27
Java Chapter 2 — Names & Things | Interview Notes

4. Variables — Memory and Storage


Variables are the most fundamental building block of any program. Understanding precisely what a
variable is — at the memory level — is critical for interviews.

4.1 What Is a Variable?

A variable is a named location in memory (RAM) that can store a value. It is not the value itself — it is
the container that holds a value.

• Think of a variable as a labeled box in memory.


• The box always stays in the same memory location (same address).
• The contents of the box (the value) can change over time.
• The variable name is a human-readable alias for the memory address.

EXAMPLE
int rate; // declares a box named 'rate' that holds int values
rate = 5; // puts the value 5 into the box
rate = 10; // replaces 5 with 10 — same box, different value

// Memory concept:
// rate --> [address 1000] --> contains value: 10

INTERVIEW TIP
When asked 'what is a variable?', say: A variable is a named memory location that stores a value
of a specific type. The value can change, but the memory location remains the same for the
variable's lifetime.

4.2 Variable Declaration

Before using a variable in Java, you must declare it — specifying its type and name. Optionally, you
can initialize it in the same statement.

Form Example What happens


Declaration only int count; Box created; value is undefined (or default
for fields)
Declaration + int count = 0; Box created and value 5 stored
initialization immediately
Multiple int x, y, z; Three boxes created, all of type int
declarations
Multiple with init int a = 1, b = 2; Two boxes, each initialized to different
values

Page 9 of 27
Java Chapter 2 — Names & Things | Interview Notes

COMMON MISTAKE / TRAP


Local variables (inside methods) in Java are NOT automatically initialized. Reading an
uninitialized local variable is a COMPILE ERROR: 'variable might not have been initialized'.
Class-level fields ARE given defaults (0 for numeric, false for boolean, null for objects).

4.3 Assignment Statements

The assignment statement is the only way to put data into a variable. Its syntax is: variable =
expression;

• The expression on the right is evaluated first.


• The resulting value is then stored in the variable on the left.
• The old value in the variable is completely replaced.

EXAMPLE
rate = 0.07; // put 0.07 into rate
interest = rate * principal; // multiply, put result into interest

// On the RIGHT side of =: variable is READ (its VALUE is used)


// On the LEFT side of =: variable is WRITTEN TO (its box is targeted)

// Step by step:
// 1. rate * principal is computed (e.g., 0.07 * 1000 = 70.0)
// 2. The value 70.0 is stored into 'interest'

COMMON MISTAKE / TRAP


Assignment (=) is NOT equality! 'rate = 0.07' means PUT 0.07 INTO rate. It is a command
executed at a point in time. It is completely different from the mathematical equation rate = 0.07,
which is a permanent truth. In Java, rate could be changed to a different value on the very next
line.

4.4 Strong Typing

Java is a strongly typed language. This means every variable has a fixed type, and you can only store
values of that type (or compatible types) in it.

EXAMPLE
int count = 5; // OK: int value into int variable
count = 3.14; // ERROR: cannot store double in int
String name = "Alice"; // OK
name = 42; // ERROR: cannot store int in String

// Strong typing catches these errors at COMPILE TIME

Page 10 of 27
Java Chapter 2 — Names & Things | Interview Notes

KEY POINT
Strong typing benefits: catches type errors at compile time (before running), makes code self-
documenting, enables the compiler to optimize memory layout, and prevents entire categories of
runtime bugs.

Page 11 of 27
Java Chapter 2 — Names & Things | Interview Notes

5. The 8 Primitive Data Types


Java has exactly 8 primitive types built into the language. These are the basic building blocks — not
objects. Knowing all 8 by heart, with their sizes and ranges, is expected in interviews.

5.1 Integer Types (4 types)

Type Size Min Value Max Value Default Use Case


byte 1 byte (8 -128 127 Raw binary data, file I/O, saving
bits) memory
short 2 bytes (16 -32,768 32,767 Legacy systems, very memory-
bits) constrained apps
int 4 bytes (32 -2,147,483,648 2,147,483,647 DEFAULT for all integer values
bits)
long 8 bytes (64 -9.2 x 10^18 9.2 x 10^18 Large numbers: timestamps,
bits) population, IDs

EXAMPLE
byte b = 100;
short s = 30000;
int i = 2000000000; // default integer type
long l = 9000000000L; // MUST add L suffix for long literals > int
range

// Without L suffix, 9000000000 causes compile error:


// 'integer number too large'

INTERVIEW TIP
Always use 'int' for general integer work unless you have a specific reason for another type. Only
switch to 'long' when int's range (about ±2 billion) is insufficient, like timestamps in milliseconds.

5.2 Floating-Point Types (2 types)

Type Size Approximate Precision When to Use


Range
float 4 bytes (32 ±1.4E-45 to ±3.4E+38 ~7 decimal digits Graphics, when memory
bits) matters, legacy APIs
double 8 bytes (64 ±5.0E-324 to ~15 decimal DEFAULT for all
bits) ±1.8E+308 digits real/decimal values

EXAMPLE

Page 12 of 27
Java Chapter 2 — Names & Things | Interview Notes

double d = 3.14159265358979; // default real type


float f = 3.14F; // MUST add F suffix for float literals

float x = 1.2; // COMPILE ERROR: cannot assign double literal to float


float x = 1.2F; // CORRECT

// Scientific notation:
double big = 1.3e12; // 1.3 x 10^12 = 1,300,000,000,000
double tiny = 9e-8; // 9 x 10^-8 = 0.00000009

COMMON MISTAKE / TRAP


float precision is only ~7 significant digits. 32.3989231134 and 32.3989234399 would both round
to 32.398923 in a float. Use double (15 digits) for any serious numeric computation to avoid
precision loss.

5.3 Character Type — char

• Holds a single character from the Unicode character set.


• Size: 2 bytes (16 bits) — can represent 65,536 different characters.
• Includes standard ASCII (a-z, A-Z, 0-9, symbols) plus international characters.
• Literal syntax: single quotes — 'A', 'z', '3', '*'.
• Default value (for class fields): '\u0000' (null character).

Literal Character Category


'A' Uppercase letter A Regular character
'*' Asterisk symbol Regular character
'\t' Tab character Escape sequence
'\n' Newline (line feed) Escape sequence
'\r' Carriage return Escape sequence
'\'' Single quote character Escape sequence
'\\' Backslash character Escape sequence
'\u00E9' é (e with accent) Unicode escape
'\u0041' A (same as 'A') Unicode escape

INTERVIEW TIP
char in Java is unsigned (0 to 65535) unlike in C/C++ where char can be signed. This matters
when doing arithmetic with char values. Also, char uses single quotes; String uses double quotes
— they are completely different types.

5.4 Boolean Type — boolean

Page 13 of 27
Java Chapter 2 — Names & Things | Interview Notes

• Holds exactly one of two values: true or false.


• These are the only valid boolean literals — lowercase, no quotes.
• Size: not precisely defined by Java spec (JVM dependent, often 1 bit logically).
• Used in all conditional expressions, loops, and flag variables.
• boolean CANNOT be converted to/from int (unlike C/C++ where 0 = false, non-zero = true).

EXAMPLE
boolean isActive = true;
boolean hasError = false;

// Used in conditions:
boolean isAdult = (age >= 18); // evaluates to true or false
boolean inRange = (rate > 0.05); // true if rate > 0.05

// WRONG in Java (valid in C but not Java):


// if (count) --> ERROR, int is not boolean
// Must write: if (count != 0)

COMMON MISTAKE / TRAP


In Java, boolean and int are completely separate types. You CANNOT write 'if (1)' or assign
'boolean x = 1'. This prevents a whole class of bugs common in C/C++ programming.

Page 14 of 27
Java Chapter 2 — Names & Things | Interview Notes

6. Literals — Writing Values Directly in Code


A literal is the source code notation for a fixed value. Knowing how Java interprets different literal
formats is a frequent source of interview questions and coding bugs.

6.1 Integer Literals

Format Example Base Decimal Note


Value
Decimal 177 Base 10 177 Default — what you expect
Octal 045 Base 8 37 Starts with 0 — digits 0-7 only
Hexadecimal 0xFF Base 16 255 Starts with 0x — digits 0-9, A-F
Long 17L or 17l Base 10 17 as long L suffix — uppercase L preferred
Hex Long 0xFFL Base 16 255 as long Combine 0x and L

COMMON MISTAKE / TRAP


CRITICAL TRAP: 045 is NOT 45! Any integer literal starting with 0 is octal (base-8). So 045 =
4×8 + 5 = 37. This is a famous Java (and C) gotcha that trips up beginners.

EXAMPLE
int a = 45; // decimal 45
int b = 045; // octal 45 = DECIMAL 37 (not 45!)
int c = 0x45; // hex 45 = DECIMAL 69 (4*16 + 5)

// In Java 7+, you can also use underscores for readability:


int million = 1_000_000; // same as 1000000, just more readable

6.2 Floating-Point Literals

• Any number with a decimal point or exponent is a double literal by default.


• Append F or f to make a float literal: 3.14F
• Scientific notation uses e or E: 1.3e12 = 1.3 × 10¹², 9.5e-3 = 0.0095
• Append D or d explicitly for double (usually not needed): 3.14D

EXAMPLE
double d1 = 3.14; // double literal (decimal point present)
double d2 = 1.3e12; // double literal in scientific notation
double d3 = 12.3737e-108; // very small double
float f1 = 3.14F; // float literal (F suffix required)
float f2 = 1.2f; // lowercase f also works

Page 15 of 27
Java Chapter 2 — Names & Things | Interview Notes

// COMPILE ERROR:
float bad = 3.14; // 3.14 is double; cannot assign to float
without cast

INTERVIEW TIP
When you see a compile error like 'incompatible types: possible lossy conversion from double to
float', it means you forgot the F suffix on a float literal or forgot to cast.

6.3 Character Literals

Character literals are enclosed in single quotes. They represent a single character value of type char.

EXAMPLE
'A' // letter A
'z' // lowercase z
'3' // CHARACTER three — not the integer 3
'\t' // tab character (one character, despite two symbols in source)
'\n' // newline character
'\r' // carriage return
'\'' // single-quote character itself
'\\' // backslash character itself
'\u00E9'// Unicode: é (e acute accent)

COMMON MISTAKE / TRAP


'3' (char) is NOT the same as 3 (int). '3' has ASCII/Unicode value 51. If you do '3' + 0, you get 51,
not 3. This is a very common interview trick question.

6.4 Boolean Literals

• Exactly two boolean literals exist: true and false


• They are lowercase — True and FALSE are not valid boolean literals.
• They are not strings — do not put quotes around them.

EXAMPLE
boolean flag = true; // CORRECT
boolean flag = True; // ERROR: True is not a keyword
boolean flag = "true"; // ERROR: "true" is a String, not boolean
boolean flag = 1; // ERROR: int is not boolean (unlike C/C++)

Page 16 of 27
Java Chapter 2 — Names & Things | Interview Notes

7. The String Type


String is the most important non-primitive type in Java. It represents a sequence of characters and is
used everywhere. Understanding how Strings differ from primitives is essential.

7.1 String Basics

• String is a class (object type), not a primitive — but it is predefined and gets special treatment.
• A String value is a sequence of zero or more Unicode characters.
• String literals use double quotes: "Hello", "Java", "" (empty string).
• The double quotes are NOT part of the string value — only the characters between them.
• Strings are immutable — once created, the character sequence cannot be changed.

EXAMPLE
String greeting = "Hello World!";
String name = "Alice";
String empty = ""; // empty string — length 0, not null
String singleChar = "A"; // String with one char — NOT same as 'A'
(char)

// String length:
int len = [Link](); // returns 12

char (primitive) String (object)


char c = 'A'; String s = "A";
Single character Sequence of characters (here: 1 char)
Primitive type Object type
2 bytes Object overhead + chars
Single quotes Double quotes

7.2 Escape Sequences in Strings

Sequence Character produced Use case


\n Newline (line feed) Move to next line when printing
\t Tab Indent/align output
\r Carriage return Windows line endings (\r\n)
\" Double quote Include " inside a String literal
\' Single quote Include ' inside a String (not usually needed)
\\ Backslash Include \ itself in a String

Page 17 of 27
Java Chapter 2 — Names & Things | Interview Notes

\uXXXX Unicode character Any Unicode character by code point

EXAMPLE
String s1 = "Hello\nWorld";
// prints: Hello
// World

String s2 = "She said, \"Hello!\"";


// value: She said, "Hello!"

String s3 = "C:\\Users\\Alice";
// value: C:\Users\Alice (Windows path)

String s4 = "caf\u00E9";
// value: café (e with accent)

7.3 String Concatenation

• The + operator concatenates strings: "Hello" + " World" = "Hello World"


• When + is used with a String and any other type, the other type is converted to String first.
• int 42 + " apples" becomes "42 apples" automatically.

EXAMPLE
String result = "Value: " + 42; // "Value: 42"
String r2 = "Pi is " + 3.14; // "Pi is 3.14"
String r3 = "Flag: " + true; // "Flag: true"

// Tricky:
String r4 = 1 + 2 + " items"; // "3 items" (1+2=3 first, then
concat)
String r5 = "items: " + 1 + 2; // "items: 12" (concat left-to-
right!)

COMMON MISTAKE / TRAP


String concatenation with + is left-associative. 'result = 1 + 2 + " items"' gives "3 items" but 'result
= "items: " + 1 + 2' gives "items: 12", NOT "items: 3". Use parentheses to control order.

Page 18 of 27
Java Chapter 2 — Names & Things | Interview Notes

8. Complete Type Reference and Comparison


This section provides a comprehensive reference table for all primitive types, plus key comparisons that
commonly appear in interviews.

8.1 Master Reference Table — All 8 Primitives

Type Categor Size Default Literal Example Wrapper Class


y
byte Integer 8 bits 0 100 Byte
short Integer 16 bits 0 30000 Short
int Integer 32 bits 0 42, 0xFF, 045 Integer
long Integer 64 bits 0L 42L, 9000000L Long
float Real 32 bits 0.0F 3.14F, 1.2e3F Float
double Real 64 bits 0.0 3.14, 1.3e12 Double
char Characte 16 bits '\u0000' 'A', '\t', '\u00E9' Character
r
boolean Boolean JVM- false true, false Boolean
dep.

INTERVIEW TIP
Wrapper classes (Integer, Double, etc.) are object versions of each primitive. They are used
when you need objects — like storing in a List<Integer>. Java's autoboxing automatically
converts between primitives and wrappers.

8.2 Choosing the Right Type

Situation Best Type Why


Whole numbers int 32-bit, sufficient for most use cases, fast
(general)
Very large whole long 64-bit range
numbers (> 2 billion)
Decimal numbers double 15-digit precision, default in Java
(general)
Memory-critical float 4 bytes vs 8 bytes, 7-digit precision
decimals
True/False flags boolean Semantically correct, prevents type errors
Single character char Unicode-aware, 2 bytes
Text/words String Sequence of chars — not a primitive
Binary/file data byte Raw bytes, no sign extension issues

Page 19 of 27
Java Chapter 2 — Names & Things | Interview Notes

Page 20 of 27
Java Chapter 2 — Names & Things | Interview Notes

9. Expressions, Operators, and Type Rules


Expressions combine variables, literals, and operators to compute values. Understanding operator
behavior and type promotion rules prevents many bugs.

9.1 Arithmetic Operators

Operator Name Example Result Notes


+ Addition 5+3 8 Also string concatenation
- Subtraction 10 - 4 6
* Multiplication rate * principal product rate and principal are variables
/ Division 7/2 3 (not 3.5) Integer division truncates!
/ Division 7.0 / 2 3.5 One double operand → double
result
% Modulo 7%3 1 7 = 2*3 + 1
(remainder)

COMMON MISTAKE / TRAP


Integer division truncates toward zero: 7/2 = 3, not 3.5. 9/10 = 0. If you need decimal division, at
least one operand must be a double: 7.0/2 = 3.5 or (double)7/2 = 3.5.

9.2 Type Promotion Rules

When you mix types in an expression, Java automatically promotes smaller types to larger ones. This is
called implicit type promotion or widening conversion.

• byte → short → int → long → float → double (widening hierarchy)


• In any expression with mixed types, all values are promoted to the largest type present.
• int / int = int (no promotion — both same type)
• int / double = double (int is promoted to double)
• byte + byte = int (both promoted to int even for same types!)

EXAMPLE
int a = 5;
double b = 2.0;
double result = a / b; // a promoted to 5.0, result = 2.5

int x = 10;
int y = 3;
int r1 = x / y; // integer division: r1 = 3
double r2 = x / y; // STILL 3! Division happens first (int/int=int)

Page 21 of 27
Java Chapter 2 — Names & Things | Interview Notes

double r3 = (double)x / y; // cast x: 10.0/3 = 3.333...

INTERVIEW TIP
A common interview question: what does 'int result = 7/2' give? Answer: 3, not 3.5. Integer
division truncates. To get 3.5, use double result = 7.0/2 or (double)7/2.

9.3 Boolean Expressions

Operator Meaning Example Result


> Greater than rate > 0.05 true if rate is above 0.05
< Less than age < 18 true if age is below 18
>= Greater than or equal score >= 60 true if score is 60 or above
<= Less than or equal x <= 100 true if x is 100 or below
== Equal to name == null true if same reference (objects) or
value (prims)
!= Not equal to count != 0 true if count is not zero
&& Logical AND a > 0 && b > 0 true only if BOTH are true
|| Logical OR a > 0 || b > 0 true if at LEAST ONE is true
! Logical NOT !isActive flips the boolean value

COMMON MISTAKE / TRAP


Do NOT use == to compare Strings! String == String compares object references (memory
addresses), not content. Use .equals() method: "hello".equals(str) or [Link]("hello"). This is
one of the most common Java bugs.

Page 22 of 27
Java Chapter 2 — Names & Things | Interview Notes

10. Interview Questions & Model Answers


This section covers the most commonly asked interview questions on Chapter 2 topics, with concise,
accurate model answers.

Q1: What is the difference between syntax and semantics?


MODEL ANSWER:
Syntax refers to the rules for writing valid code — violations are caught at compile time.
Semantics refers to the meaning/behavior of code — a program can be syntactically correct
but produce wrong output (semantic error). For example, writing length + width instead of
length * width for area compiles fine but gives wrong results.

Q2: Why is main() declared as public static void?


MODEL ANSWER:
public: The JVM is external to the program — it must be able to call main(), so it must be
visible outside the class. static: The JVM calls main() before any objects are created, so it
must belong to the class itself. void: main() is the entry point and nobody calls it for a return
value — it returns nothing.

Q3: What is the difference between float and double?


MODEL ANSWER:
Both store decimal numbers. float is 4 bytes with ~7 significant digits of precision. double is 8
bytes with ~15 significant digits. double is the default in Java (decimal literals are double).
Use float only when memory is a constraint or you are working with a float-specific API. float
literals need an F suffix: 3.14F.

Q4: What does the literal 045 represent in Java?


MODEL ANSWER:
045 is an octal (base-8) literal because it starts with 0. Its decimal value is 4×8 + 5 = 37, not
45. This is a known gotcha: always avoid leading zeros on integer literals unless you
intentionally mean octal.

Q5: What is the difference between '3' and 3 in Java?


MODEL ANSWER:
'3' is a char literal — a character with Unicode/ASCII value 51. The integer 3 is an int literal
with value 3. They have completely different types. '3' + 0 equals 51 (int arithmetic on char
value), not 3.

Page 23 of 27
Java Chapter 2 — Names & Things | Interview Notes

Q6: Can a variable be used before it is declared?


MODEL ANSWER:
No. In Java, every variable must be declared before use. For local variables inside methods,
they must also be initialized before reading — reading an uninitialized local variable is a
compile error. Class-level fields get default values (0, false, null), but local variables do not.

Q7: What does 'strongly typed' mean in Java?


MODEL ANSWER:
Strongly typed means every variable has a fixed type declared at compile time, and you can
only store values of that type (or compatible types via widening) in it. Attempting to store a
double in an int variable, or a String in an int variable, is a compile error. This catches type
mismatches early.

Q8: What is the difference between = and == in Java?


MODEL ANSWER:
= is the assignment operator — it puts a value into a variable (e.g., x = 5). == is the equality
comparison operator — it tests whether two values are equal and returns a boolean (e.g., x
== 5 is true if x contains 5). Using = in a condition instead of == is a compile error for non-
boolean types in Java.

Page 24 of 27
Java Chapter 2 — Names & Things | Interview Notes

11. Comprehensive Summary — Quick Revision


This section consolidates all key points for fast pre-exam or pre-interview revision. Use this as your final
review sheet.

11.1 Three Dimensions of Programming


• Syntax = grammar rules (enforced by compiler)
• Semantics = meaning and correctness (verified by testing)
• Pragmatics = style and readability (enforced by convention and code review)

11.2 Java Program Structure — Must Know


• All Java code lives inside a class
• Class name MUST match filename: class HelloWorld → [Link]
• Entry point: public static void main(String[] args)
• Source (.java) → compiled to bytecode (.class) → executed by JVM
• Two comment styles: // (single-line) and /* ... */ (multi-line)
• [Link]() = built-in subroutine to print to standard output

11.3 Identifiers
• Start with letter, underscore, or $; contain letters, digits, underscore, $
• Case-sensitive: Rate ≠ rate ≠ RATE
• Cannot use reserved words as identifiers
• Convention: Classes = UpperCamelCase; variables/methods = lowerCamelCase; constants =
UPPER_SNAKE

11.4 Variables
• Named memory location that stores a data value of a specific type
• Assignment: variable = expression; (evaluates right side, stores into left side)
• = is command (executed at runtime), NOT mathematical equality
• Java is strongly typed: each variable holds only its declared type
• Local variables must be initialized before reading; fields get defaults

11.5 The 8 Primitive Types


• Integers (4): byte (8b), short (16b), int (32b) ← default, long (64b, L suffix)
• Reals (2): float (32b, F suffix), double (64b) ← default
• Character (1): char (16b, Unicode, single quotes)
• Boolean (1): boolean (true/false only, NOT 0/1)

Page 25 of 27
Java Chapter 2 — Names & Things | Interview Notes

11.6 Literals — Key Rules


• Integer starting with 0 = octal: 045 = 37 (decimal)
• Integer starting with 0x = hex: 0xFF = 255
• Long needs L suffix: 9000000000L
• Float needs F suffix: 3.14F; decimal literals are double by default
• Char = single quotes; String = double quotes
• Boolean: exactly true or false (lowercase, no quotes)

11.7 String Type


• String is an object (not primitive), but predefined and heavily used
• Immutable: string content cannot change after creation
• Escape sequences: \n (newline), \t (tab), \" (quote), \\ (backslash), \uXXXX (Unicode)
• Concatenation with +; non-strings auto-converted to String
• Use .equals() for content comparison, NOT ==

11.8 Critical Interview Traps


• 045 is octal = decimal 37, NOT decimal 45
• '3' (char, value 51) is NOT the same as 3 (int, value 3)
• int / int = int: 7/2 = 3, not 3.5 (integer truncation)
• float x = 3.14 → compile error; must be 3.14F
• boolean cannot be compared with == to int (not like C/C++)
• String comparison: use .equals(), not ==
• Assignment is a command, not a permanent mathematical truth

Page 26 of 27
Java Chapter 2 — Names & Things | Interview Notes

12. One-Page Cheat Sheet


Use this as the last-minute revision reference.

PRIMITIVE TYPES LITERAL FORMATS


byte (-128 to 127) 42 // int (decimal)
short (-32768 to 32767) 042 // octal = 34
int (-2.1B to 2.1B) ★ DEFAULT 0x2A // hex = 42
long (±9.2×10^18) suffix: L 42L // long
float (7 digits) suffix: F 3.14 // double (default)
double (15 digits) ★ DEFAULT 3.14F // float
char (Unicode, '' quotes) 1.3e12 // 1.3 × 10^12
boolean(true/false only) 'A' '\t' '\u00E9' // char

NAMING CONVENTIONS ESCAPE SEQUENCES


Classes: HelloWorld (PascalCase) \n newline
Variables: interestRate (camelCase) \t tab
Methods: calculateTax() (camelCase) \r carriage return
Constants: MAX_VALUE (UPPER_SNAKE) \' single quote
Packages: [Link] (lower) \" double quote
\\ backslash
\uXXXX any Unicode char

TOP INTERVIEW TRAPS (continued)


1. 045 = octal = 37 (NOT 45) 4. '3' (char=51) ≠ 3 (int=3)
2. float x = 3.14 → ERROR (must be 3.14F) 5. String: use .equals() not ==
3. 7/2 = 3 (integer division truncates!) 6. Assignment (=) ≠ math equality

End of Chapter 2 — Java Names and Things

Page 27 of 27

You might also like