Let me ask you something tricky… 👉 “Can you change the value of a final variable in Java?” Take a second. **Most developers instantly say** ❌ No.. its not possible Because in our minds — final = constant = cannot change(simple logic). But here’s the interesting things comes...👇 👉 The answer is: YES… and also NO. Confused 😄? Let’s break it. 🧠 What you already know At compile time → final variables cannot be reassigned. That rule is absolutely correct. But twist comes in this place 🤯 At runtime, Java has something powerful: 👉 Reflection API It allows you to go under the hood and manipulate class internals. Using reflection, developers used to do this: 1. Access the field via reflection 2. Disable Java access checks 3. Remove the final modifier 4. Update the value Yes… actually changing a final variable 😄 🔥 That’s why this is a classic interview trap If you just say “No” → ❌ incomplete answer If you explain runtime behavior → its really impressive for any interview ⚠️ But here’s the REAL catch (Modern Java) If you’re using Java 12+ (like Java 17) 👇 This trick is mostly dead You can’t access internal modifiers anymore JVM enforces strong encapsulation Reflection hacks are restricted JVM may inline constants, making changes useless 🤯 Even crazier… private final String value = "final"; 👉 JVM may replace this everywhere with "final" directly So even if you “change” it… ➡️ Your program still behaves like it never changed ✅ When can it still sometimes work? private final String value = new String("final"); ✔ Not a compile-time constant ✔ No aggressive inlining ✔ Reflection might work (but not guaranteed ) 🧠 Perfect Interview Answer 👉 Compile-time → ❌ Cannot change 👉 Runtime (Java 8) → ✅ Possible using reflection 👉 Runtime (Java 22) → ⚠️ Restricted & unreliable 🔥 Final Thought 👉 “final is a rule… until you understand how the JVM bends it.” If this question came up in your interview, would you still say just “No”? 😉 Drop your answer below 👇 #Java #ReflectionAPI #JavaInterview #BackendDevelopment #JVM #SoftwareEngineering
Java Final Variable Change via Reflection
More Relevant Posts
-
Java 17+ Interview Question 🔥 | Sealed Interfaces Explained Imagine you have a Payment interface implemented by UPIPayment and CardPayment. Everything is fine until another developer adds a CashPayment class that also implements it — but your client doesn’t want that. How do you restrict which classes can implement the Payment interface? Before Java 17, there was no clean way to enforce this. Solution: Use the sealed keyword (introduced in Java 17) with the permits clause. ————————— sealed interface Payment permits UPIPayment, CardPayment { } final class UPIPayment implements Payment { } final class CardPayment implements Payment { } // This will now give a compilation error // class CashPayment implements Payment { } —————————- Key Rules: • Only the classes listed in permits can implement the sealed interface. • Every implementing class must be explicitly marked as: • final → cannot be extended further • sealed → can define its own permitted subclasses • non-sealed → can be freely extended You can also combine this with records (which are implicitly final). This feature gives you full control over the inheritance hierarchy at compile time — no more unexpected implementations in large codebases. What would you choose for UPIPayment — final, sealed, or non-sealed? And why does a record work without explicitly adding final? Drop your thoughts in the comments 👇 #Java #Java17 #SealedInterfaces #JavaInterviewQuestions #BackendDevelopment #ProgrammingTips #AI #ML
To view or add a comment, sign in
-
-
⏳ Day 16 – 1 Minute Java Clarity – final Keyword in Java What if something should NEVER change? Use final! 🔒 📌 What is final? The final keyword restricts modification. 👉 It can be applied to variables, methods and classes. 📌 1️⃣ Final Variable: final int SPEED_LIMIT = 120; SPEED_LIMIT = 150; // ❌ Compilation Error! 👉 Once assigned, value can NEVER be changed. ✔ By convention, final variables are written in UPPER_CASE. 📌 2️⃣ Final Method: class Vehicle { final void start() { System.out.println("Engine started!"); } } 👉 Child class CANNOT override this method. ✔ Used when core behavior must stay consistent. 📌 3️⃣ Final Class: final class PaymentGateway { // Cannot be extended } 👉 No class can inherit from a final class. ✔ Example from Java itself → String class is final! 💡 Real-time Example: Think of a traffic system 🚦 Speed limit on a highway = 120 km/h No one can change that rule → that's your final variable! PI value in Math = 3.14159… It never changes → Math.PI is declared final in Java ✅ ⚠️ Interview Trap: final vs finally vs finalize — all different! 👉 final → restricts change 👉 finally → block in exception handling 👉 finalize → called by GC before object is destroyed 💡 Quick Summary ✔ final variable → value can't change ✔ final method → can't be overridden ✔ final class → can't be inherited ✔ String is a final class in Java! 🔹 Next Topic → Access Modifiers in Java Did you know String is a final class? Drop 💡 if this was new! hashtag #Java #JavaProgramming #FinalKeyword #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Ever wondered why changing one variable sometimes changes everything in Java? Today I finally understood a concept that used to confuse me a lot — Pass by Value vs Pass by Reference (memory perspective). At first, it felt tricky… but once I visualized how memory works, everything started making sense. What I learned: [1] Pass by Value (Definition): A copy of the actual value is passed to another variable. 👉 Both variables work independently. Example: int x = 10; int y = x; // copy y = 20; System.out.println(x); // 10 System.out.println(y); // 20 ➡️ Changing y does NOT affect x [2] Pass by Reference (Concept in Java objects): Actually, Java is always pass by value… BUT for objects, the value being passed is the reference (address). 👉 So multiple variables can point to the same object in memory. Example: Car a = new Car(); a.name = "Maruti"; Car b = a; // reference copy b.name = "Kia"; System.out.println(a.name); // Kia ➡️ Changing b also changes a because both point to the same object. 💡 Real-life analogy: It’s like one person having multiple names — Parents call you one name, friends call you another… but it’s still YOU. Same in Java: Different references ➝ Same object ➝ Same changes. 🔑 Key Takeaways: Java is always pass by value For objects, the value = reference (address) Multiple references can point to the same object Changing via one reference affects all This concept really changed how I look at Java objects and memory. Still learning, still improving… one concept at a time #Java #Programming #LearningJourney #Coding #JavaDeveloper #BeginnerDeveloper #SoftwareDevelopment #100DaysOfCode
To view or add a comment, sign in
-
-
• Why Does Java Use 2 Bytes for "char"? At first glance, this can feel confusing… =>Why does Java use 2 bytes (16 bits) for a single character, when older languages used just 1 byte? Let’s break it down : -> The Core Reason: Unicode Support Java uses the Unicode standard to represent characters. 1) Unicode is designed to support a wide range of global character sets 2) It includes scripts like Latin, Devanagari, Chinese, Arabic, and more =>To accommodate this, Java chose 16 bits (2 bytes) for "char" => What Does 2 Bytes Mean? - 1 byte = 8 bits - 2 bytes = 16 bits =>This allows representation of up to 65,536 distinct values =>Why Not 1 Byte Like C/C++? Languages like C/C++ were originally based on ASCII: • 1 byte (8 bits) → limited character range => Java, on the other hand, was designed with broader character representation in mind. • Important Insight Java uses UTF-16 encoding for "char" 1) Most commonly used characters fit within 2 bytes 2) Some characters are represented using surrogate pairs --> Conclusion Java’s choice of 2 bytes for "char" is rooted in its design around Unicode-based character representation rather than ASCII limitations. #Java #Programming #Unicode #SoftwareEngineering #BackendDevelopment #Java #CoreJava #JavaDeveloper #JVM #ProgrammingConcepts #BackendDeveloper #DevelopersOfLinkedIn #Tech #Coding
To view or add a comment, sign in
-
-
⏳ Day 14 – 1 Minute Java Clarity – Type Casting in Java Converting one type to another… but Java has rules! 👀 📌 What is Type Casting? Assigning a value of one data type to another type. 👉 Java has 2 types of casting. 📌 1️⃣ Widening (Automatic) Small → Big type. Java does it automatically ✅ int num = 100; double result = num; System.out.println(result); // 100.0 ✔ No data loss ✔ JVM handles it automatically 📌 2️⃣ Narrowing (Manual) Big → Small type. You must do it explicitly ⚠️ double price = 99.99; int rounded = (int) price; System.out.println(rounded); // 99 ⚠️ Decimal part is lost — not rounded, just cut off! 💡 Real-time Example: Think of a payment system — price is 499.99 When you cast to int for processing → you get 499 That 0.99 is gone forever 😬 ⚠️ Interview Trap: byte b = (byte) 130; System.out.println(b); // -126 👉 byte range is -128 to 127 — 130 overflows and wraps around! 💡 Quick Summary ✔ Widening → automatic, safe, no data loss ✔ Narrowing → manual, risky, data loss possible ✔ Watch out for overflow in narrowing! 🔹 Next Topic → static keyword in Java Have you ever lost data because of narrowing casting? 👇 #Java #JavaProgramming #TypeCasting #CoreJava #JavaDeveloper #BackendDeveloper #Coding #Programming #SoftwareEngineering #LearningInPublic #100DaysOfCode #ProgrammingTips #1MinuteJavaClarity
To view or add a comment, sign in
-
-
Day 12 Today’s Java practice was about solving the Leader Element problem. Instead of using nested loops, I used a single traversal from right to left, which made the solution clean and efficient. A leader element is one that is greater than all the elements to its right. Example: Input: {16,17,5,3,4,2} Leaders: 17, 5, 4, 2 🧠 Approach I used: ->Start traversing from the rightmost element ->Keep track of the maximum element seen so far ->If the current element is greater than the maximum, it becomes a leader ->This is an efficient approach with O(n) time complexity and no extra space. ================================================= // Online Java Compiler // Use this editor to write, compile and run your Java code online class Main { public static void main(String[] args) { int a [] ={16,17,5,3,4,2}; int length=a.length; int maxRight=a[length-1]; System.out.print("Leader elements are :"+maxRight+" "); for(int i=a[length-2];i>=0;i--) { if(a[i]>maxRight) { maxRight=a[i]; System.out.print(maxRight+" "); } } } } Output:Leader elements are :2 4 5 17 #AutomationTestEngineer #Selenium #Java #DeveloperJourney #Arrays
To view or add a comment, sign in
-
-
🚀 Day 56: Final & Static — Establishing Rules in Java 🏗️ After exploring the flexibility of Polymorphism yesterday, today was about the "Constants" of Java. I dived into the Final and Static keywords—two tools that help us manage memory and protect our code’s logic. 🔒 1. The Final Keyword: "No Changes Allowed" The final keyword is all about restriction. I learned it can be applied in three ways: ▫️ Final Variables: Creates a constant. Once assigned, the value cannot be changed (e.g., final double PI = 3.14). ▫️ Final Methods: Prevents Method Overriding. If you don't want a subclass to change your logic, you make it final. ▫️ Final Classes: Prevents Inheritance. A final class cannot be extended (like the String class in Java!). 💾 2. The Static Keyword: "Shared by All" The static keyword shifts the focus from "Objects" to the "Class" itself. ▫️ Static Variables: These belong to the class, not the individual objects. Every object of that class shares the exact same variable, which is great for memory efficiency. ▫️ Static Methods: These can be called without creating an object of the class (like Math.sqrt()). ▫️ Static Blocks: Used for initializing static variables when the class is first loaded. Question for the Devs: Do you use final for all your local variables that don't change, or do you find that it makes the code too "noisy"? I'm curious to hear your take on Clean Code vs. Explicit Logic! 👇 #Java #CoreJava #StaticKeyword #FinalKeyword #100DaysOfCode #BackendDevelopment #CleanCode #SoftwareEngineering #LearningInPublic 10000 Coders Meghana M
To view or add a comment, sign in
-
I remember staring at Java code wondering... Why is this variable private? Why can't I extend this class? Why does this method work without an object? Modifiers confused me for a long time. So I built the guide I wish I had back then. A complete, colorful visual guide to Java Modifiers — covering everything in one document: ACCESS MODIFIERS 🔴 private — your own class only 🟢 default — same package family 🟠 protected — package + inherited subclasses 🔵 public — accessible from everywhere NON-ACCESS MODIFIERS 🟣 static — belongs to the class, not the object 🟡 final — cannot be changed, overridden, or extended 🔵 abstract — must be completed by subclass 🔴 synchronized — one thread at a time 🌿 volatile & transient — memory + serialization control Each modifier comes with: → Clear rules (no fluff) → Real-world analogies that actually make sense → VSCode-style dark code examples → Color-coded visibility tables Whether you're a beginner trying to understand encapsulation or prepping for a Java interview — this one is for you. PDF attached — free to download and share! Save this post for your next Java revision session. #Java #JavaProgramming #OOP #AccessModifiers #LearnJava #Programming #Developer #CodeNewbie #SoftwareEngineering #TechLearning
To view or add a comment, sign in
-
☕ Learn Java with Me — Day 16 Yesterday we learned why Java is platform independent. Today let’s understand the 3 most important terms in Java 💻 👉 JDK vs JRE vs JVM These are commonly asked in interviews and are also important for real understanding 🎯 👉 JVM (Java Virtual Machine) JVM is responsible for running Java bytecode. It converts bytecode into machine-readable instructions. Simple: JVM = runs Java program 👉 JRE (Java Runtime Environment) JRE provides the environment required to run Java applications. It includes: → JVM → libraries → supporting files Simple: JRE = JVM + runtime files 👉 JDK (Java Development Kit) JDK is used to develop Java programs. It includes: → JRE → compiler (`javac`) → debugger → development tools Simple: JDK = JRE + tools for coding 📌 Easy memory trick: JVM → Run JRE → Run + libraries JDK → Run + Develop This is not just for studying, but also important from an interview and practical coding perspective 🚀 ❓ Quick Question: Can we run a Java program with only JDK installed? We’re learning deeper — together 🤝 #java #coding #learning #interviewprep #showup #day16
To view or add a comment, sign in
-
-
👉 Constructor = Object initialization + No Inheritance + No Static 🔁 Initialization Order in Java: ->Static variables & static blocks (once / class) ->Instance variables (default → explicit) ->Instance initializer blocks (once / object ) Constructor ⚡ Interview-Ready Facts (No fluff) Can a constructor be static? ❌ No Constructor belongs to object not class Can a constructor be private?-✅ Yes → Used in Singleton, Utility classes Can a constructor be final?❌ No → No inheritance → No overriding → No need Can a constructor be abstract? ❌ No 👉 Abstract = No implementation 👉 Constructor = Must initialize object Can we override a constructor? ❌ No → Not inherited Can we overload a constructor? ✅ Yes Can we call constructor explicitly? ✅ Yes → this() or super() Can constructor return value?❌ No Constructor inside constructor? ✅ Yes → Constructor chaining this() → same class super() → parent class Can constructor throw exception? ✅ Yes Can we call constructor from a method? ❌ No → Only via new A(). 💡 Final Thought Constructor questions are rarely about syntax. They test your understanding of: Object lifecycle Inheritance behavior JVM initialization flow #Java #SDET #InterviewPrep #OOP #BackendDevelopment
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
Great explanation! Worth adding that with Java 26 and JEP 500 (Prepare to Make Final Mean Final), the JVM is moving toward fully enforcing immutability of final fields. So in the future, we won’t need to think about this as much.