𝙩𝙝𝙞𝙨 and 𝙨𝙪𝙥𝙚𝙧 keyword in java: 𝗣𝗼𝗶𝗻𝘁𝘀 𝘁𝗼 𝗿𝗲𝗺𝗲𝗺𝗯𝗲𝗿 In Java, 𝙩𝙝𝙞𝙨 and 𝙨𝙪𝙥𝙚𝙧 are reference keywords used to manage object behavior clearly and avoid ambiguity. => 𝙩𝙝𝙞𝙨 refers to the current object of the class. • It is mainly used to differentiate instance variables(variables declared inside class) from local variables, call current class methods, and chain constructors using this(). 𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀: • Refers to current class object • Used to avoid variable shadowing • Cannot be used in static context • Supports constructor chaining 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝘤𝘭𝘢𝘴𝘴 𝘗𝘦𝘳𝘴𝘰𝘯 { 𝘚𝘵𝘳𝘪𝘯𝘨 𝘯𝘢𝘮𝘦; 𝘗𝘦𝘳𝘴𝘰𝘯(𝘚𝘵𝘳𝘪𝘯𝘨 𝘯𝘢𝘮𝘦) { 𝘵𝘩𝘪𝘴.𝘯𝘢𝘮𝘦 = 𝘯𝘢𝘮𝘦; } } ===================================================== => 𝙨𝙪𝙥𝙚𝙧 refers to the parent class object. • It is used in inheritance to access parent class variables, methods, and constructors. 𝗞𝗲𝘆 𝗽𝗼𝗶𝗻𝘁𝘀: • Refers to immediate parent class • Used during method overriding • super() calls parent constructor • Must be first statement in constructor 𝗘𝘅𝗮𝗺𝗽𝗹𝗲: 𝘤𝘭𝘢𝘴𝘴 𝘗𝘢𝘳𝘦𝘯𝘵 { 𝘪𝘯𝘵 𝘹 = 10; } 𝘤𝘭𝘢𝘴𝘴 𝘊𝘩𝘪𝘭𝘥 𝘦𝘹𝘵𝘦𝘯𝘥𝘴 𝘗𝘢𝘳𝘦𝘯𝘵 { 𝘪𝘯𝘵 𝘹 = 20; 𝘷𝘰𝘪𝘥 𝘴𝘩𝘰𝘸() { 𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵𝘭𝘯(𝘹); // 20 𝘚𝘺𝘴𝘵𝘦𝘮.𝘰𝘶𝘵.𝘱𝘳𝘪𝘯𝘵𝘭𝘯(𝘴𝘶𝘱𝘦𝘳.𝘹); // 10 } } 𝗤𝘂𝗶𝗰𝗸 𝗱𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝗰𝗲: • this → current class • super → parent class • this() → current constructor • super() → parent constructor ✨ Follow for more 𝗝𝗮𝘃𝗮 & 𝗕𝗮𝗰𝗸𝗲𝗻𝗱 concepts! #Java #CoreJava #OOP #JavaInterview #BackendDevelopment #SpringBoot #SoftwareEngineering
Java this and super keywords explained
More Relevant Posts
-
How to add all elements of an array in Java (Explained simply) Imagine you’re sitting in front of me and you ask: 👉 “How do I add all the numbers present in an array using Java?” I’d explain it like this 👇 Think of an array as a box that already contains some numbers. For example: [2, 4, 6, 8] Now our goal is simple: ➡️ Take each number one by one ➡️ Keep adding it to a total sum Step-by-step thinking: First, we create a variable called sum and set it to 0 (because before adding anything, the total is zero) Then we loop through the array Each time we see a number, we add it to sum After the loop finishes, sum will contain the final answer Java Code: int[] arr = {2, 4, 6, 8}; int sum = 0; for (int i = 0; i < arr.length; i++) { sum = sum + arr[i]; } System.out.println(sum); What’s happening here? arr[i] → current element of the array sum = sum + arr[i] → keep adding elements one by one Loop runs till the last element Final Output: 20 One-line explanation: “We start from zero and keep adding each element of the array until nothing is left.” If you understand this logic, you’ve already learned: ✔ loops ✔ arrays ✔ problem-solving mindset This is the foundation of many real-world problems in Java 🚀 #Java #Programming #DSA #BeginnerFriendly #LearnJava #CodingBasics
To view or add a comment, sign in
-
Fun with pattern matching scope in Java 21 I’m switching to Java 21 and I stumbled upon a comment under 2023 article that was good to share as Java puzzle: By coincidence, one of our projects, is still on Java 11. At the same time, some dependencies have moved to Java 17. So I ended up by using OpenRewrite to backport modern Java features. Along the way, I learned many interesting things. For example, that this is perfectly valid Java: if (!(obj instanceof String str)) { throw new IllegalArgumentException(); } System.out.println(str.length()); And also this (yes, these are two different str variables): if (!(obj instanceof String str)) { Integer str = null; System.out.println(str); } else { System.out.println(str); } Now let’s play a game. Without running this code or copying it into an IDE, can you confidently tell in which cases str is available in the else branch on attached screenshot? Still too easy? Add more conditions. Nest a few "if". Use multiple pattern variables. Go wild. At some point, str starts behaving like a Heisenberg variable: until you paste the code into an IDE, you can’t be 100% sure about its scope In the end, I wrote more tests than actual transformation code: tests: https://lnkd.in/e4PncArw transformation: https://lnkd.in/emqktnFC Comment source: https://lnkd.in/eP-H2Cza
To view or add a comment, sign in
-
-
Mastering Wrapper Classes in Java: Converting Primitives to Objects If you are working with Java, you’ve likely used both int and Integer. But do you know why Java provides both? In Java, Wrapper Classes provide a way to use primitive data types (int, boolean, etc.) as objects. This is essential when working with Collections (like ArrayList or HashMap), which can only store objects, not primitives. The 8 Wrapper Classes Each primitive type has a corresponding wrapper class: Integer for int Double for double Character for char Boolean for boolean Float for float Long for long Byte for byte Short for short Key Concepts to Remember: 1. Autoboxing: The automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes (e.g., converting int to Integer). 2. Unboxing: The reverse process—converting an object of a wrapper class back to its corresponding primitive type (e.g., Integer to int). Why do we need them? Collections Framework: List, Set, and Map require objects. Utility Methods: Wrapper classes provide useful methods for conversion (like Integer.parseInt()). Null Values: Objects can be null, whereas primitives always have a default value. Understanding these fundamentals is a huge step toward becoming a proficient Java developer! #Java #JavaProgramming #FullStackDeveloper #BackendDevelopment #CodingTips #SoftwareEngineering #LearningJava #JavaDeveloper #TechEducation #WrapperClasses
To view or add a comment, sign in
-
-
📌 new String() vs String Literal in Java In Java, Strings can be created in two different ways. Although they may look similar, they behave differently in memory. 1️⃣ String Literal When a String is created using a literal: • The value is stored in the String Pool • JVM checks if the value already exists • Existing reference is reused if available Example: String s1 = "java"; String s2 = "java"; Both references point to the same object. 2️⃣ new String() When a String is created using the `new` keyword: • A new String object is created in heap memory • It does not reuse the String Pool object by default Example: String s3 = new String("java"); `s3` points to a different object even if the value is the same. 3️⃣ Memory Impact • String literals reduce memory usage through reuse • `new String()` always creates an additional object • Using `new` unnecessarily can increase memory consumption 4️⃣ When to Use • Prefer String literals for most use cases • Use `new String()` only when a distinct object is explicitly required 💡 Key Takeaways: - String literals use the String Pool - `new String()` creates a separate heap object - Understanding this helps write memory-efficient code #Java #CoreJava #String #JVM #BackendDevelopment
To view or add a comment, sign in
-
🤔 Why does 1 == 1 return true but 500 == 500 return false in Java? Same numbers… different results? Let’s break this Java mystery in a simple and logical way 🔍 == behaves differently in Java 👉 For primitives (int) == compares actual values Example: int a = 1; int b = 1; a == b; // true ✔ Both variables store the value 1 👉 For objects (Integer) == compares memory references, not values Example: Integer a = 500; Integer b = 500; a == b; // false =>Even though values look same =>a and b point to different objects in memory 🧠 The Hidden Rule: Integer Caching Java has an Integer Cache Java caches Integer values from:-128 to 127 These values are reused instead of creating new objects ✅ Inside the cache range Integer x = 100; Integer y = 100; x == y; // true Both variables point to the same cached object ❌Outside the cache range Integer x = 500; Integer y = 500; x == y; // false => New object created every time => Different memory references ⚠️ Important: Integer caching is an optimization, not a rule to rely on in business logic. 🧪 Another Mind-Bender Example: Integer a = 500; int b = 500; System.out.println(a == b); // true Why? Java unboxes Integer → int Now it becomes value vs value 500 == 500 → true ✍ The Golden Rule : ❌ Don’t do this Integer a = 500; Integer b = 500; a == b; ✅ Always do this a.equals(b); ✔ .equals() compares values, not memory ✔ Safe, predictable, professional 📌 Best Practices for Java Developers ☑️Use == → only for primitives ☑️ Use .equals() → for wrapper classes ⚠️ Never rely on Integer cache behavior 🧠 If Java feels “random” → you’re probably comparing references Java didn’t break logic. We compared references instead of values. If this helped you, drop a 👍 If this bug ever surprised you — welcome to the club 😄 #Java #JavaInterview #BackendDevelopment #CodingTips #learning
To view or add a comment, sign in
-
🔹 Question: What are Records in Java 17? How are they different from traditional POJOs? 🔹 Answer: Records are a special type of class introduced to represent immutable data carriers with minimal boilerplate. Before Java 17, a simple DTO required: fields constructor getters equals() / hashCode() toString() 🔹 Traditional POJO: public class User { private final String name; private final int age; public User(String name, int age) { this.name = name; this.age = age; } public String name() { return name; } public int age() { return age; } } 🔹 Java 17 Record: public record User(String name, int age) {} 🔹 What Java Automatically Generates: ✅ private final fields ✅ Canonical constructor ✅ Accessor methods ✅ equals() and hashCode() ✅ toString() 🔹 Why Records Were Introduced: Promote immutability by default Reduce boilerplate Improve readability Encourage value-based design 🔹 Important Constraints (Interview Favorite): Records are final (cannot be extended) Fields are implicitly final Can implement interfaces Can contain validation logic inside the constructor public record User(String name, int age) { public User { if (age < 0) throw new IllegalArgumentException("Age cannot be negative"); } } 🔹 Real-World Use Cases: REST API request/response DTOs Event payloads Database projections Configuration objects 🔹 Interview Tip: Use Records when the class is meant to hold data, not behavior. 📌 Records + Sealed Classes + Pattern Matching = Modern Java Design #Java17 #JavaInterview #Records #BackendDevelopment #SpringBoot #CleanCode #JavaDeveloper #LTS
To view or add a comment, sign in
-
-
I used Java Varargs for years without really thinking about them. Those three little dots ... just felt convenient. Until one day I stopped and asked: What’s actually happening here? 👇 Ever seen a method call like this? printLog("User", "Login", "Success") Those three dots are called Varargs (Variable Arguments) — one of Java’s cleanest pieces of syntactic sugar. --- 🚫 Life before Varargs (pre-Java 5) Passing a variable number of arguments meant manually creating arrays every time: printLog(new String[] { "User", "Login", "Success" }) Correct? Yes. Readable? Not really. --- 🍬 What Varargs fixed You define your method like this: public void printLog(String... messages) Now Java lets you pass: • one argument • many arguments • or none Clean call sites. Less noise. --- 🕵️♂️ What’s really happening under the hood? Varargs are not magic. At compile time, the Java compiler converts comma-separated values into an array. So this: foo("A", "B", "C") Becomes this internally: foo(new String[] { "A", "B", "C" }) Which means: String... args == String[] args Same behavior. Better syntax. ⚠️ Two rules to remember 1️⃣ Varargs must be the LAST parameter 2️⃣ You can only have ONE varargs parameter per method (Java is flexible — but not that flexible 😄) --- I love Varargs for: • logging • utility methods • internal helpers For public APIs, I sometimes prefer List<T> for clarity. 👉 What do you prefer — Varargs or Collections? And where do you consciously avoid Varargs? --- Java Syntactic Sugar — Part 3 #JavaTips #JavaInternals #BackendJava #JavaDevelopers #BackendDevelopment #SoftwareEngineering #JavaSyntacticSugar
To view or add a comment, sign in
-
-
💡 Java Tip: Stop letting null surprise you — meet Optional In Java☕️ we have all seen it → NullPointerException at the worst possible moment. So what’s the modern way to avoid this mess? Use Optional to represent absence safely. 🧱 What Optional actually is Optional<T> is a wrapper that may or may not hold a value — instead of returning null, you return a clear signal: 🔍 How it improves our code Instead of defensive programming like this ⛔: if (username != null) { System.out.println(username.length()); } You can write expressive intent ✔️: username.ifPresent(u -> System.out.println(u.length())); Cleaner, Safer and More readable 😃 ⚙️ Optional in action Optional<User> user = findUserByEmail(email); user.filter(u -> u.isActive()) .map(User::getFullName) .ifPresent(System.out::println); ✔️ No null checks. ✔️ No fear of hidden surprises. 📌 Where Optional shines: Use it especially in method return types: Optional<Order> getOrderById(Long id) {} It forces the caller to handle absence intentionally. 🚫 Where to avoid it - Don’t use it for class fields - Don’t wrap collections inside Optional - Don’t turn everything into Optional — use it where absence is meaningful 🎯 Optional makes missing data explicit instead of accidental. Less null, fewer crashes, clearer code. #java #learning #interview #programming #concept #codingtips #learnjava
To view or add a comment, sign in
-
-
🚀 Day 11/15 – Strings in Java (What Really Happens Behind the Scenes) 🧵 Strings look simple. But in Java, they quietly test how well you understand memory, performance, and design choices. Today’s focus wasn’t just using strings — it was understanding how Java treats them differently. 🔹 Why Strings Are Special in Java In real applications, strings are everywhere: User names Passwords API responses Logs Messages So Java treats them very carefully. 🔹 String vs StringBuilder vs StringBuffer (Real Thinking) Instead of definitions, this is how I now think about them 👇 String When data should not change (usernames, IDs, constants) StringBuilder When data keeps changing (loops, building responses, performance-critical code) StringBuffer When multiple threads might touch the same data (rare, but important) 👉 Choosing the wrong one doesn’t break code — but it hurts performance. 🧠 The Big Learning for Me The biggest mistake beginners make is: > “All strings are the same.” They are not. Java forces you to think before you modify text — and that mindset carries into clean coding everywhere else. 🏦 Real-World Example In a Bank Application: Account number → String (never changes) Transaction message → StringBuilder (keeps appending) Shared log message → StringBuffer (thread-safe) Same data type… very different intent. ✨ Simple Takeaway > Strings are not about text — they are about intent and performance. Once this clicks, a lot of Java suddenly makes sense. 💬 Community Question Have you ever faced a performance issue just because of string concatenation in loops? #Java #Strings #15DaysChallenge #JavaDeveloper #CleanCode #BackendDevelopment #LearningInPublic
To view or add a comment, sign in
-
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development