KEMBAR78
Java Revision Notes Part1 To 16 | PDF | Java (Programming Language) | Java Virtual Machine
0% found this document useful (0 votes)
13 views19 pages

Java Revision Notes Part1 To 16

The document provides a comprehensive overview of Java, covering its definition, history, features, and key components such as JDK, JRE, and JVM. It includes important rules, exceptions, interview questions, and examples related to Java programming, as well as details about Java versions and data types. The content is structured in a way that serves as a quick revision guide for Java concepts and practices.

Uploaded by

sahil dhawale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views19 pages

Java Revision Notes Part1 To 16

The document provides a comprehensive overview of Java, covering its definition, history, features, and key components such as JDK, JRE, and JVM. It includes important rules, exceptions, interview questions, and examples related to Java programming, as well as details about Java versions and data types. The content is structured in a way that serves as a quick revision guide for Java concepts and practices.

Uploaded by

sahil dhawale
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Java Quick Revision Notes - Part 1 to 16

■ 1. What is Java?

■ Concept
- Java is a high-level, class-based, object-oriented programming language.
- Developed by James Gosling at Sun Microsystems in 1995.
- Known for platform independence → "Write Once, Run Anywhere (WORA)".
- Runs using JVM (Java Virtual Machine) which executes bytecode.

■ Important Rules / Exceptions


1. Java is case-sensitive (main ≠ Main).
2. The file name must match the public class name.
3. Only one public class allowed per .java file.
4. main method signature must be:
public static void main(String[] args)
- args can have any name, but String[] type is mandatory.
5. Without main, Java program won’t run (except JShell or static block before Java 7).

■ Interview Questions
- Why is Java called platform independent?
- Difference between JDK, JRE, JVM?
- Can we run a Java program without main() method?
- Why is main() method public static void?
- Is Java 100% Object-Oriented?

■■ Example
class HelloJava {
public static void main(String[] args) {
System.out.println("Hello Java!");
}
}

■ Tips to Remember
- Java = OOP + Platform Independent + Secure + Robust.
- Keywords like goto & const are reserved in Java but not used.
- Always think of Java as a language + platform (JVM).
■ 2. History of Java

■ Concept
- 1991 → Project started by James Gosling & team at Sun Microsystems (called Oak).
- 1995 → Officially released as Java (since Oak was trademarked).
- Designed for embedded systems, interactive TV, later adapted for internet applications.
- 1996 → First JDK (Java Development Kit 1.0).
- 2009 → Oracle acquired Sun Microsystems → Java under Oracle.
- Today → widely used in Enterprise, Android, Microservices, Big Data, Cloud.

■ Important Rules / Exceptions


- Java versioning follows major releases (Java SE 8, 11, 17, 21 are LTS).
- Backward compatibility → Old Java code usually works in newer versions.
- Applets & Java Web Start deprecated & removed in Java 11+.

■ Interview Questions
- Who is the father of Java?
- Why was Java initially named Oak?
- What was Java’s original purpose?
- Which company owns Java now?
- Which Java versions are LTS?

■■ Example (Timeline)
1995 → Java 1.0
2004 → Java 5 (Generics, Annotations)
2011 → Java 7 (try-with-resources, switch on String)
2014 → Java 8 (Lambdas, Streams, Default Methods)
2017 → Java 9 (Modules)
2018 → Java 11 (LTS, Removed Applets, JavaFX out)
2021 → Java 17 (LTS, Sealed classes, Pattern Matching)
2023 → Java 21 (LTS, Virtual Threads)

■ Tips to Remember
- Java’s slogan: "Write Once, Run Anywhere."
- Always know Java 8, 11, 17, 21 → most used in industry.
- Interviewers often ask what changed in latest LTS version.
■ 3. Features of Java

■ Concept
Java provides a rich set of features that made it popular and widely used.

Main Features:
1. Simple – Syntax similar to C/C++, no pointers, no operator overloading.
2. Object-Oriented – Everything is in the form of classes & objects.
3. Platform-Independent – Code compiles to bytecode, runs on any JVM.
4. Secure – No direct memory access (like pointers), runs in JVM sandbox.
5. Robust – Strong memory management + exception handling.
6. Multithreaded – Supports multiple threads of execution.
7. High Performance – Uses JIT (Just-In-Time) compiler.
8. Distributed – Supports networking & RMI.
9. Portable – Same bytecode runs on different machines.
10. Dynamic – Supports runtime polymorphism, reflection, and dynamic class loading.

■ Important Rules / Exceptions


- Java does not support multiple inheritance with classes, but supports it with interfaces.
- final keyword prevents inheritance, overriding, or reassignment.
- Garbage Collection is automatic, but System.gc() is only a request, not a guarantee.
- Pointers & operator overloading are intentionally removed for simplicity & security.

■ Interview Questions
- Why is Java platform-independent?
- Difference between robustness and security in Java?
- How does Java achieve multithreading?
- Why doesn’t Java support multiple inheritance with classes?
- How is Java different from C++?

■■ Example
class FeatureDemo {
public static void main(String[] args) {
// Object-Oriented
Person p = new Person("Sahil");
p.display();

// Robust (exception handling)


try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception handled: " + e);
}

// Multithreaded
Thread t = new Thread(() -> System.out.println("Thread running..."));
t.start();
}
}

class Person {
String name;
Person(String name) { this.name = name; }
void display() { System.out.println("Hello " + name); }
}

■ Tips to Remember
- Always mention WORA (Write Once, Run Anywhere).
- OOPS principles (Encapsulation, Inheritance, Polymorphism, Abstraction) are hot interview topics.
- Java is not 100% OOP (because of primitives like int, char).
- Security & Robustness are always tested in interviews with tricky exception handling questions.
■ 4. JDK, JRE, JVM

■ Concept
1. JVM (Java Virtual Machine)
- Executes Java bytecode line by line.
- Provides platform independence.
- Handles memory management & garbage collection.

2. JRE (Java Runtime Environment)


- Contains JVM + Libraries + Runtime Classes.
- Used to run Java programs.
- Does not have development tools (compiler, debugger).

3. JDK (Java Development Kit)


- Contains JRE + Development Tools (javac, javadoc, debugger).
- Needed for both development & execution.
- Multiple versions available (Standard Edition, Enterprise Edition, etc.).

■ Important Rules / Exceptions


- JDK = JRE + Development Tools.
- JRE = JVM + Libraries.
- JVM is platform-dependent (different implementation per OS), but bytecode is
platform-independent.
- Java 11 onwards: JRE is no longer provided separately, only JDK includes everything.
- HotSpot JVM is the most widely used implementation.

■ Interview Questions
- Difference between JDK, JRE, and JVM?
- Is JVM platform-independent?
- Why is Java platform-independent but JVM is not?
- What is the role of JIT compiler in JVM?
- Can we run Java without JDK installed?

■■ Example (Flow of Compilation & Execution)


Source Code (.java)
↓ [javac compiler]
Bytecode (.class)
↓ [JVM → Class Loader → JIT Compiler → Execution Engine]
Machine Code (OS specific)

class Demo {
public static void main(String[] args) {
System.out.println("Hello from JVM!");
}
}

Compile: javac Demo.java


Run: java Demo

■ Tips to Remember
- Compilation vs Execution: javac compiles → JVM executes.
- Java 11+: only JDK is shipped, no separate JRE.
- JIT Compiler improves performance by compiling bytecode to native machine code at runtime.
- Formula:
- JDK = JRE + Development Tools
- JRE = JVM + Libraries
■ 5. Java Versions

■ Concept
- Java evolves with major releases introducing new features.
- LTS (Long Term Support) versions are most important for industry use.
- Current trend: new release every 6 months, LTS every 3 years.

■ Major Versions & Features


- JDK 1.0 (1996) → First official release.
- JDK 1.2 (1998) → Collections Framework.
- JDK 1.5 / Java 5 (2004) → Generics, Annotations, Enum, Autoboxing.
- Java 6 (2006) → Scripting, JDBC 4.0, better Web Services support.
- Java 7 (2011) → Try-with-resources, Diamond Operator, switch on String.
- Java 8 (2014, LTS) → Lambda Expressions, Streams, Default Methods, Functional Interfaces,
Date/Time API.
- Java 9 (2017) → Module System (Project Jigsaw), JShell.
- Java 10 (2018) → var keyword for local variables.
- Java 11 (2018, LTS) → Removed JavaFX/Applets, new HttpClient API, var in lambda, String
methods (isBlank, lines).
- Java 12–15 → Switch expressions, text blocks ("""), records (preview).
- Java 17 (2021, LTS) → Sealed Classes, Pattern Matching, Strong Encapsulation, Records
finalized.
- Java 21 (2023, LTS) → Virtual Threads (Project Loom), Pattern Matching for switch, Sequenced
Collections.

■ Important Rules / Exceptions


- Backward compatibility → Older code runs in newer versions (mostly).
- Features marked preview need --enable-preview flag.
- Oracle provides paid support for LTS (8, 11, 17, 21).
- Non-LTS versions get support only until the next release.

■ Interview Questions
- Which versions of Java are LTS?
- What is the difference between Java 8 and Java 11?
- What are the key features of Java 17?
- Why was the module system introduced in Java 9?
- What are virtual threads in Java 21?

■■ Example
// Java 8 Example: Lambda + Stream
import java.util.*;
class VersionDemo {
public static void main(String[] args) {
List names = Arrays.asList("Sahil", "Amit", "Raj");
names.stream()
.filter(n -> n.startsWith("S"))
.forEach(System.out::println);
}
}

■ Tips to Remember
- Always highlight Java 8, 11, 17, 21 in interviews → most used in projects.
- Know at least 2–3 new features per LTS version.
- Java 8 = Lambdas & Streams, Java 11 = HttpClient & removed JRE,
Java 17 = Sealed classes, Records, Java 21 = Virtual Threads.
- Interviewers often ask: “Which Java version are you working with?” → be ready to explain its
features.
■ 6. Java Path and JAVA_HOME

■ Concept
- JAVA_HOME: Environment variable pointing to the Java installation directory (e.g., C:\Program
Files\Java\jdk-17).
- PATH: Tells OS where to find executables (javac, java) without typing full path.

■ Steps to Set JAVA_HOME and PATH


Windows
1. Install JDK (e.g., JDK 17).
2. Set JAVA_HOME = C:\Program Files\Java\jdk-17.
3. Add %JAVA_HOME%\bin to PATH.
4. Verify:
java -version
javac -version

Linux / macOS
export JAVA_HOME=/usr/lib/jvm/java-17-openjdk
export PATH=$JAVA_HOME/bin:$PATH
source ~/.bashrc

■ Rules / Exceptions
- Without JAVA_HOME: Some tools (Maven, Gradle, Tomcat) may fail to detect Java.
- PATH must include bin: Otherwise, java/javac won’t run globally.
- If multiple Java versions installed → Use update-alternatives (Linux) or tools like SDKMAN.

■ Interview Questions
- What is the difference between PATH and JAVA_HOME?
- Why do we need to set JAVA_HOME even if PATH works?
- How do you configure multiple Java versions in one system?
- How to check which java your system is using?

■■ Example
# Example: Check Java version and installation path
java -version
which java # Linux/macOS
where java # Windows

Output (Java 17 example)


java version "17.0.9" 2023-10-17 LTS
Java(TM) SE Runtime Environment (build 17.0.9+11-LTS)
Java HotSpot(TM) 64-Bit Server VM

■ Tips to Remember
- JAVA_HOME is must when using Maven, Gradle, Jenkins.
- Always check java -version after setup.
- If interview asks “Your Java command is not recognized, what will you do?” → Answer: Check
PATH variable.
- For troubleshooting → echo %JAVA_HOME% (Windows), echo $JAVA_HOME (Linux).
■ 7. Java Program Compilation Process

■ Concept
Java follows the principle “Write Once, Run Anywhere” (WORA).
This is possible because of the compilation + interpretation model.

■ Steps in Compilation
1. Source Code (.java)
- Written by the programmer.
- Example: HelloWorld.java

2. Compilation → Bytecode (.class)


- Command: javac HelloWorld.java
- Output: HelloWorld.class
- Contains platform-independent bytecode.

3. Execution → JVM
- Command: java HelloWorld
- JVM reads bytecode and converts it to machine code (via JIT compiler).

■ Rules / Exceptions
- File name must match public class name (HelloWorld.java must have public class HelloWorld).
- Only one public class per file.
- If no main() method → Runtime Error.
- Compilation errors stop .class generation.
- Runtime errors occur after compilation (e.g., ArithmeticException).

■ Interview Questions
- What is the role of the javac compiler?
- What is bytecode, and why is it important?
- Difference between JDK, JRE, and JVM in compilation?
- Can Java run without compilation? (No, but JShell can run interactively).
- What happens if filename and public class name don’t match?

■■ Example
// File: HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
}
}

Compile & Run


javac HelloWorld.java # compilation → generates HelloWorld.class
java HelloWorld # execution

Output
Hello, Java!

■ Tips to Remember
- Compile = javac, Run = java.
- .java → .class → machine code.
- Bytecode = platform-independent, JVM makes it platform-dependent.
- Always remember → Java is compiled + interpreted.
- Interviewers love asking about WORA & Bytecode.
■ 8. First Java Program

■ Concept
The simplest Java program demonstrates:
- Class declaration
- main() method (entry point)
- System.out.println() (output statement)

■ Example Program
// File: HelloJava.java
public class HelloJava {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

■ Rules / Exceptions
- File name must match public class name → HelloJava.java.
- main() method signature must be:
public static void main(String[] args)
- public → accessible by JVM
- static → no object needed
- void → no return
- String[] args → command-line arguments
- Java is case-sensitive → Main ≠ main.
- Without main(), program compiles but fails at runtime.

■ Interview Questions
- Why is main() method static in Java?
- Can we run a Java program without main()?
- Difference between System.out.print and System.out.println?
- Can class name and file name be different in Java?
- Why is String[] args used in main()?

■■ Example with Command-line Args


public class HelloArgs {
public static void main(String[] args) {
System.out.println("First argument: " + args[0]);
}
}

Run:
javac HelloArgs.java
java HelloArgs Sahil

Output:
First argument: Sahil

■ Tips to Remember
- Always start learning Java with HelloWorld program.
- In interviews, explain each keyword in public static void main(String[] args).
- Command-line args questions are common.
- If multiple classes are present, JVM runs the class with main().
■ 9. Java Data Types in Detail

■ Concept
Java is a statically typed language → every variable must have a declared type.
There are two categories of data types:
1. Primitive Data Types (8 types)
2. Non-Primitive (Reference) Data Types

■ Primitive Data Types


byte (8-bit), short (16-bit), int (32-bit), long (64-bit), float (32-bit), double (64-bit), char (16-bit),
boolean (1-bit).
Each has specific size, default value, and range.

■ Non-Primitive Data Types


- String, Arrays, Classes, Interfaces
- Default value = null

■ Rules / Exceptions
- Default values apply only to instance variables, not local variables.
- long literals need L suffix (100L).
- float literals need f suffix (3.14f).
- char uses single quotes, String uses double quotes.
- boolean accepts only true/false (not 0/1).

■ Interview Questions
- Difference between primitive and reference data types?
- Why is String not a primitive type in Java?
- What is the default value of local variables?
- Can we assign null to primitive types?
- Why is boolean size not fixed in bits?

■■ Example
public class DataTypesDemo {
byte b = 10;
int i = 100;
long l = 1000L;
float f = 3.14f;
double d = 3.14159;
char c = 'A';
boolean flag = true;

public static void main(String[] args) {


DataTypesDemo obj = new DataTypesDemo();
System.out.println("Byte: " + obj.b);
System.out.println("Int: " + obj.i);
System.out.println("Long: " + obj.l);
System.out.println("Float: " + obj.f);
System.out.println("Double: " + obj.d);
System.out.println("Char: " + obj.c);
System.out.println("Boolean: " + obj.flag);
}
}

■ Tips to Remember
- Always know size, range, and default value of primitives.
- String is immutable (commonly asked in interviews).
- Local variables must be initialized before use.
- Be ready to explain autoboxing/unboxing (int ↔ Integer).
■ 10. Multiple Classes in One File

■ Concept
- Only one class can be public in a .java file.
- The public class name must match the filename.
- Other classes are package-private.

■ Rules
1. File name must match public class name.
2. If no public class, file can have any name.
3. Only one public class per file.
4. Each class generates separate .class files after compilation.
5. JVM executes class containing main() method.

■ Example
// File: Demo.java
class A { void display() { System.out.println("Class A"); } }
class B { void show() { System.out.println("Class B"); } }
public class Demo {
public static void main(String[] args) {
new A().display();
new B().show();
}
}

■ Exceptions
- Two public classes → Compilation error.
- Inner classes are allowed inside one public class.

■ Interview Questions
- Can we have multiple public classes?
- What happens if filename doesn’t match public class?
- How many .class files generated for 3 classes?
- Can a Java program run without a public class?

■ Tips
- Filename must match public class.
- JVM looks for main() method, not class name.
■ 11. Type Casting in Java

■ Concept
- Converting a variable from one type to another.
- Two types:
1. Widening (Implicit, safe)
2. Narrowing (Explicit, possible data loss)

■ Widening
int x = 10;
double y = x; // implicit

■ Narrowing
double d = 9.78;
int i = (int) d; // explicit

■ Object Casting
Parent p = new Child(); // Upcasting
Child c = (Child) p; // Downcasting
Use instanceof to avoid ClassCastException.

■ Rules / Exceptions
- Casting unrelated classes → Compile error.
- boolean cannot be cast to other types.
- int to String requires String.valueOf().

■ Interview Questions
- Difference between widening and narrowing?
- Why explicit casting needed in narrowing?
- What is upcasting & downcasting?
- What happens in invalid downcasting?

■■ Example
public class TypeCastingDemo {
public static void main(String[] args) {
int a = 100; double b = a;
double x = 9.99; int y = (int) x;
char c = 'A'; int ci = c;
Parent p = new Child();
if(p instanceof Child) { Child ch = (Child)p; }
}
}

■ Tips
- Prefer widening (safe).
- Always use instanceof before downcasting.
- ClassCastException occurs in wrong downcasting.
- Casting changes reference, not object.
■ 12. Java Operators

■ Concept
Operators are special symbols that perform operations on variables and values.
Categories include arithmetic, unary, assignment, relational, logical, bitwise, ternary, and
instanceof.

■ Types
1. Arithmetic (+, -, *, /, %)
2. Unary (++ , --, +, -, !)
3. Assignment (=, +=, -=, etc.)
4. Relational (==, !=, >, <, >=, <=)
5. Logical (&&, ||, !)
6. Bitwise (&, |, ^, ~, <<, >>, >>>)
7. Ternary (?:)
8. instanceof operator

■ Rules / Exceptions
- Division by 0: int → ArithmeticException, float → Infinity/NaN.
- == checks reference equality for objects, use .equals() for content.
- >>> fills with 0 (unsigned right shift).
- Pre/Post increment can give tricky outputs.

■ Interview Questions
- Difference between == and .equals()?
- What is short-circuiting in logical operators?
- Difference between >> and >>>?
- What happens on integer division by zero?
- Can instanceof be used with interfaces?

■■ Example
public class OperatorsDemo {
public static void main(String[] args) {
int a = 10, b = 3;
System.out.println("a+b=" + (a+b));
System.out.println("++a=" + (++a));
a += 5;
System.out.println("a after += 5: " + a);
System.out.println("a > b: " + (a > b));
System.out.println((a > 5) && (b < 5));
System.out.println("a & b = " + (a & b));
String result = (a > b) ? "a is greater" : "b is greater";
System.out.println(result);
String s = "Hello";
System.out.println(s instanceof String);
}
}

■ Tips
- Learn operator precedence (* before +).
- == is for references, .equals() for content.
- && and || use short-circuiting.
- Bitwise (&) vs Logical (&&).
- Pre vs Post increment asked often.
■ 13. Java Tokens

■ Concept
Tokens are the smallest units in a Java program that have meaning to the compiler.
Everything in Java code is made up of tokens.

■ Types of Java Tokens


1. Keywords → Reserved words with predefined meaning (e.g., class, if, static, final).
2. Identifiers → Names given to variables, methods, classes, etc.
3. Literals → Constant values (e.g., 10, 3.14, "Hello", true, 'A').
4. Operators → Symbols performing operations (+, -, *, /, ++, etc.).
5. Separators (Delimiters) → Symbols like (), {}, [], ;, , , .
6. Comments → Non-executable notes (//, /* */, /** */).

■ Rules / Exceptions
- Java keywords are case-sensitive (Class ≠ class).
- Identifiers cannot start with digits or use reserved words.
- Literals can’t be modified once assigned.
- null is a literal in Java.
- Unicode characters allowed in identifiers but not recommended.

■ Interview Questions
- What are tokens in Java?
- Difference between identifier and keyword?
- Can an identifier have special characters?
- Is true a keyword or a literal?
- Difference between literals and constants?

■ Example
public class TokenDemo {
public static void main(String[] args) {
// Tokens → class, TokenDemo, {, main, (, String, args, ), { ... }
int num = 10; // num → identifier, 10 → literal
final double PI = 3.14; // PI → constant
if(num > 5) { // if → keyword, > → operator
System.out.println("Greater");
}
}
}

■ Tips
- Java has 50+ reserved keywords.
- const and goto are reserved but not used.
- Identifiers can’t be the same as keywords.
- null, true, false are literals, not keywords.
■ 14. Variables in Java

■ Concept
A variable is a named memory location used to store data.
In Java, every variable has a data type and scope.

■ Types of Variables in Java


1. Local Variables
- Declared inside methods, constructors, or blocks.
- Created when method is invoked, destroyed when method exits.
- Must be initialized before use.

2. Instance Variables (Non-static fields)


- Declared inside a class but outside methods.
- Belong to each object.
- Default values assigned (e.g., 0, null, false).

3. Static Variables (Class variables)


- Declared with static keyword inside class.
- Shared across all objects.
- Stored in class memory area.

■ Rules / Exceptions
- Variable names must follow identifier rules (cannot start with digit, no keywords).
- Default values are only assigned to instance and static variables, not to local variables.
- Static variables are created once per class, not per object.
- final variable = constant (must be initialized once).
- Shadowing allowed → local variable can hide instance variable.

■ Interview Questions
- Difference between local, instance, and static variables?
- What is variable shadowing in Java?
- Can we declare a static variable inside a method?
- What is the default value of local variables?
- Difference between static and final variable?

■ Example
public class VariableDemo {
int instanceVar; // Instance variable
static int staticVar; // Static variable

void display() {
int localVar = 10; // Local variable
System.out.println("Local: " + localVar);
System.out.println("Instance: " + instanceVar);
System.out.println("Static: " + staticVar);
}

public static void main(String[] args) {


VariableDemo obj1 = new VariableDemo();
obj1.display();

VariableDemo.staticVar = 50; // Shared by all objects


VariableDemo obj2 = new VariableDemo();
obj2.display();
}
}
■ Tips
- Local variables → no default values, must initialize.
- Instance variables → object-specific, get default values.
- Static variables → shared across objects.
- Shadowing can confuse code, avoid it in real projects.
■ 15. Constants and the final Keyword

■ Concept
- Constants are fixed values that cannot be changed during program execution.
- In Java, we use the final keyword to declare constants.

■ Uses of final
1. Final Variable → Value cannot be changed once assigned.
2. Final Method → Cannot be overridden in subclasses.
3. Final Class → Cannot be inherited.

■ Rules / Exceptions
- A final variable must be initialized at the time of declaration OR in the constructor.
- If a final variable is not initialized → called a blank final variable (must be assigned in constructor).
- A static final variable must be initialized in static block or at declaration.
- Final does not make objects immutable → only the reference cannot be reassigned.
- finalize() method (from Object class) ≠ final keyword.

■ Interview Questions
- Difference between final, finally, and finalize()?
- Can we declare a constructor as final?
- What is a blank final variable?
- Can we change the state of an object if its reference is final?
- Why are String, Wrapper classes immutable in Java?

■ Example
final class Vehicle { // Final class → cannot be inherited
final int speedLimit = 90; // Constant

final void showSpeed() { // Final method


System.out.println("Speed limit: " + speedLimit);
}
}

public class FinalDemo {


public static void main(String[] args) {
final int x = 10;
// x = 20; // ■ Compilation error (cannot reassign)

final StringBuilder sb = new StringBuilder("Hello");


sb.append(" World"); // ■ Allowed (object state change)
// sb = new StringBuilder("Hi"); // ■ Not allowed (reference reassignment)

System.out.println(sb);
}
}

■ Tips
- final vs immutable → final stops reassignment, immutability stops modification.
- Always remember:
- final variable → constant value.
- final method → no override.
- final class → no inheritance.
- Common interview trap: finalize() is a method for garbage collection, not related to final.
■ 16. Identifiers & Naming Rules

■ Concept
Identifiers are names given to Java elements like variables, methods, classes, interfaces, and
packages.
They help the compiler and programmer uniquely identify elements in code.

■ Rules for Identifiers


1. Can contain letters (A–Z, a–z), digits (0–9), underscore (_), and dollar sign ($).
2. Cannot start with a digit.
3. Cannot be a Java keyword (e.g., class, static).
4. Case-sensitive → MyVar ≠ myvar.
5. No whitespace allowed.
6. Length → No limit (but meaningful names recommended).
7. Unicode letters are allowed (but not recommended in practice).

■ Exceptions & Notes


- $ is legal but discouraged except for compiler-generated names.
- _ can be used, but from Java 9, using just _ as an identifier is not allowed.
- Identifiers should follow Java Naming Conventions.

■ Java Naming Conventions


- Class/Interface → PascalCase (e.g., EmployeeDetails).
- Methods/Variables → camelCase (e.g., getSalary, employeeName).
- Constants → UPPER_CASE (e.g., MAX_SPEED).
- Packages → lowercase (e.g., com.company.project).

■ Interview Questions
- What are identifiers in Java?
- Can an identifier start with $ or _?
- Is String a valid identifier?
- Difference between identifiers and keywords?
- Why should we follow naming conventions?

■ Example
public class IdentifierDemo {
int age = 25; // valid
String name = "John"; // valid
double $salary = 50000; // valid but not recommended
int _id = 101; // valid

// Invalid identifiers
// int 123abc = 10; // ■ cannot start with digit
// int class = 5; // ■ cannot use keyword

public static void main(String[] args) {


IdentifierDemo obj = new IdentifierDemo();
System.out.println(obj.name + " - " + obj.age);
}
}

■ Tips
- Avoid $ and _ in professional code.
- Always follow naming conventions for readability.
- Remember: Keywords ≠ Identifiers.
- Interview trap: true, false, null are literals, not identifiers.

You might also like