Java Fundamentals Cheat Sheet: Enums, this Keyword, final Keyword, Wrapper Classes & Varargs

Struggling with Java fundamentals? 🚀 In a recent tech discussion, we broke down some core concepts that every Java developer should have on lock. If you’re preparing for an interview or just brushing up, here is the cheat sheet: 1. Comparing Enum Values Always use == for enums. Since enums are singletons, == checks reference equality, is null-safe, and is compile-time checked. Using .equals() is safe but unnecessary here. 2. The this Keyword It refers to the current object instance. Use it to: · Distinguish instance variables from parameters (this.name = name). · Call another constructor of the same class (this()). · Pass the current object as a parameter to another method. 3. final Keyword in Inheritance · final Class: Cannot be subclassed (e.g., String). · final Method: Cannot be overridden by a subclass (prevents behavior change). · final Variable: Cannot be reassigned (makes it a constant). 4. Wrapper Classes & Autoboxing · Wrapper: Objects that encapsulate primitives (e.g., Integer for int). · Autoboxing: Automatic conversion int → Integer when needed. · Unboxing: Automatic conversion Integer → int. Gotcha: Comparing Integer objects with == for values >127 can fail due to caching! 5. Varargs (Variable Arguments) Allows passing an arbitrary number of arguments to a method. · Benefit: Cleaner syntax, no need to explicitly create an array. · Limitation: Must be the last parameter in the method signature. Overloading with varargs can be tricky and lead to ambiguity. 💬 Test Your Knowledge: Q1: Why is it better to use == for enums instead of .equals()? Q2: If a class is marked final, can you still create an instance of it? Q3: What is the output of System.out.println(new Integer(50) == new Integer(50));? (Hint: Think object reference vs value!) Drop your answers in the comments! 👇 #Java #Programming #TechInterview #SoftwareDevelopment #CodingTips

To view or add a comment, sign in

Explore content categories