Java Basics — Core Interview Notes with Question Answers
Hi, this Java series is just a quick recap of basics before your interviews or exams. At the end of this, you will find some interesting advanced questions on the basics of java!!
1. History & Features
- Developed by: Sun Microsystems, 1995 (by James Gosling)
- Key Features:
- Platform-independent (via JVM)
- Object-Oriented
- Robust (exception handling, garbage collection)
- Secure (bytecode verification, no pointer)
- Multithreaded
- High performance (JIT Compiler)
2. JVM, JRE, JDK
- JVM (Java Virtual Machine): Runs Java bytecode (.class files); platform-specific.
- JRE (Java Runtime Environment): JVM + libraries needed to run Java programs.
- JDK (Java Development Kit): JRE + development tools like
javac,javadoc.
3. Key Interview Concepts
Why Java is different from C++?
- No pointers in Java
- Platform independent
- Automatic memory management
- Simpler syntax (no header files, no operator overloading)
Java vs C++:
- No multiple inheritance via classes (uses interfaces instead)
- Garbage Collection (no need for
delete) - Run-time environment (JVM vs Native code)
4. Data Types
- Primitive Data Types (stored in stack):
byte– 8 bitsshort– 16 bitsint– 32 bitslong– 64 bitsfloat– 32 bitsdouble– 64 bitschar– 16 bits (Unicode)boolean– 1 bit- Non-Primitive (Reference) Types (stored in heap):
- String, Arrays, Objects
Note: Primitive types go in stack; references go in stack but the actual object is in heap.
5. Variables in Java
- Local Variable: Defined inside method/block, not accessible outside.
- Instance Variable: Defined inside class, outside methods; object-level.
- Static Variable: Class-level variable, shared by all objects of the class.
6. Typecasting
- Widening (implicit): smaller → larger type (e.g.,
inttolong) - Narrowing (explicit): larger → smaller type (e.g.,
longtoint)
Extra:
- Upcasting (explicit): Superclass reference to subclass object
- Downcasting (explicit): Subclass reference to superclass object
Strings & Methods — Core Interview Notes
1. String Basics
- Special Behavior:
Unlike C/C++, Java Strings are not null-terminated.
Instead, Java stores the string length internally.
Initialization Types:
String s1 = "Java";→ Stored in String Constant Pool (SCP) → memory-efficient, avoids duplicates.String s2 = new String("Java");→ Stored in Heap memory, even if same content.
Interview Tip: SCP is part of heap but behaves like a fixed-size, deduplicated area.
2. String Types
TypeThread-SafetyMutabilityPerformance
StringThread-Safety:Yes,Immutable,Slow for frequent modifications
StringBufferThread-Safety: Yes,Mutable ,Slower than builder
StringBuilderThread-Safety: No,Mutable,Fastest
StringTokenizer-Tokenizes based on delimiters
StringJoiner-Combines strings with delimiter, prefix, suffix
3. Common String Methods
length()Returns string length
Get Gaurikhard’s stories in your inbox
Join Medium for free to get updates from this writer.
charAt(int i)Returns character at index
substring()Extracts substring
equals()Compares content (case-sensitive)
equalsIgnoreCase()Case-insensitive comparison==Compares references
concat()Appends one string to another
replace()Replaces char or sequence
split(regex)Splits string
toUpperCase() / toLowerCase()Casing
trim()Removes leading/trailing spaces
contains()Checks substring existence
4. Interview Notes
- Immutable Nature: Any modification results in a new object.
- Why immutable?
Security, String pooling, Thread safety, and performance in HashMaps.
Arrays — Core Interview Notes
1. Basics of Arrays
- Arrays are fixed-size, homogeneous, and indexed (0-based).
- Stored in heap memory, even if declared inside a method (because it’s a non-primitive).
- Can be 1D, 2D, or Jagged (irregular) arrays.
2. Cloning Array
- Use
.clone()to make a shallow copy of the array.
Works for all array types.
int[] a = {1, 2, 3};
int[] b = a.clone(); // b is a copy of aFor primitive types, cloning gives a full duplicate.
For object arrays, it’s shallow (references are copied).
3. Advanced Array Initialization
- You can use Java 8 Streams for elegant initialization:
int[] arr = IntStream.range(1, 6).toArray(); // [1, 2, 3, 4, 5]
int[] arr2 = IntStream.rangeClosed(1, 5).toArray(); // [1, 2, 3, 4, 5]
int[] arr3 = IntStream.of(10, 20, 30).toArray(); // [10, 20, 30]
4. Jagged Arrays (2D with variable column sizes)
A jagged array is a 2D array where each row has a different column size.
int[][] jagged = new int[3][];
jagged[0] = new int[2]; // Row 0 has 2 columns
jagged[1] = new int[1]; // Row 1 has 1 column
jagged[2] = new int[3]; // Row 2 has 3 columnsInterview questions from basic java:
Q: What is the internal class loading mechanism in JVM?
A: JVM uses a three-phase class loading process:
- Loading: Loads
.classfiles via ClassLoaders – Bootstrap, Extension, and Application. - Linking: Verifies bytecode (security), prepares static fields, resolves symbolic references.
- Initialization: Executes static blocks and initializes static variables in order.
Q: What’s the difference between heap, stack, and metaspace in JVM?
A:
- Stack: Stores local variables, method calls — thread-specific, fast, LIFO.
- Heap: Stores objects, shared among threads. Garbage collected.
- Metaspace (Java 8+): Stores class metadata outside heap, grows dynamically.
Q: What triggers JIT compiler, and what optimizations does it perform?
A:
- JIT (Just-In-Time) triggers for “hot” code (frequently executed methods).
- It compiles bytecode to native code at runtime, performing inlining, loop unrolling, and dead code elimination.
Q: Why are local variables not initialized by default, but instance/static variables are?
A:
- Instance/static variables are managed by the JVM and initialized to defaults.
- Local variables live on the stack and must be explicitly initialized to prevent undefined behavior.
Q: What’s the difference between widening and narrowing conversions?
A:
- Widening (automatic):
int → long → float → double(safe, no data loss) - Narrowing (manual):
double → intrequires explicit cast, may lose data.
Q: What is the difference between upcasting and downcasting in Java (in OOP)?
A:
- Upcasting: Subclass → Superclass (safe, implicit) :
Animal a = new Dog(); // Upcasting - Downcasting: Superclass → Subclass (unsafe, needs cast):
Dog d = (Dog) a; // Risky, needs `instanceof` check
Q: Why is String immutable in Java? What are the benefits?
A:
- For security, thread-safety, hashcode consistency, and string pooling.
- Immutability allows caching and sharing via the String Constant Pool.
- Q: What’s the difference between
==,.equals(), and.intern()for strings?
A:
==→ compares reference.equals()→ compares content.intern()→ ensures string goes to constant pool, returns pooled reference
Q: What is the difference between shallow copy and deep copy in arrays?
A:
array.clone()→ shallow copy, copies references (for object arrays)- Deep copy → manually create and copy each element, needed for full duplication
- Q: Can a
nullString be concatenated in Java?
A:
- Yes.
"Hello" + nullbecomes"Hellonull". - But
null + "Hello"gives a NullPointerException only if using a null reference with+.
Q: Why does new String("abc") == "abc" return false?
A:
"abc"from pool vs.new String("abc")in heap → different references, even with same content.
Comment down for more such questions!
Happy Coding!!







