Java Bytes #2 Code: class Main { public static void main(String[] args) { String String = "String"; System.out.println(String); } } The below will be the output... String This is a valid code because all the predefined class names in Java can be used as identifier names. Only keywords can't be used as identifiers. But it is a good practice to follow the naming conventions as below. 1. class/interface names with capital letter for each word(PascalCase). Eg: Runnable, StudentDto 2. method/variable names with small letter for the starting word followed by capital letter(camelCase). Eg: student, employeeRecord 3. constant names with full capital letters(UPPER_SNAKE_CASE). Eg: MAX_VALUE, MAX_RETRIES 4. package names with all lower case letters. Eg: java.util, java.lang What will be the output for the following code? class Main { public static void main(String[] args) { String String = "String"; String Main = "Main"; String main = "main"; String System = "System"; String out = "out"; String println = "println"; System.out.println(String); System.out.println(Main); System.out.println(main); System.out.println(System); System.out.println(out); System.out.println(println); } } If it is not giving the right output, what is the issue? ----------------- Java is like my girlfriend. I have misunderstood her many times. Still I try to understand her a lot. Please feel free to correct me if I have misunderstood her. #javaBytes #javaIsLove #javaInterviewPrep
Java Naming Conventions and Identifier Names
More Relevant Posts
-
**Post 7 📘 Effective Java – Item 7** “Eliminate obsolete object references” One of the most **silent bugs in Java** is not a crash… It’s a **memory leak**. Java has Garbage Collection, but **GC is not magic**. If *you* keep references, GC can’t help you. 🔍 **Common mistake** We assume that once an object is “logically unused”, Java will clean it up. But if a reference still exists → **memory leak**. 💡 **Classic example** Implementing your own stack, cache, or listener list. If you pop an element from a stack but don’t null out the reference: ➡️ Object stays in memory ➡️ GC cannot reclaim it ✅ **Best practices** * Set references to `null` once they are no longer needed * Be extra careful with: * Custom data structures * Static fields * Caches * Listeners & callbacks * Prefer **weak references** (`WeakHashMap`) for caches when applicable 🧠 **Key takeaway** > Garbage Collection works on *reachability*, not *usefulness*. Writing clean Java isn’t just about syntax or performance — it’s also about **memory hygiene**. This one habit can save you from **production memory leaks** that are extremely hard to debug. source - Effective Java ~ Josch bloch #EffectiveJava #Java #MemoryManagement #GarbageCollection #CleanCode #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
Why String is a immutable in Java? First, What is string, String ? string -> A string is a sequence of characters placed inside double quotes (" "). Technically, it is called a String literal. e.g -> String s1="Om"; -> "Om" is a string literal. String -> A String is a predefined class in Java. It is used to storing a sequence of characters. e.g. -> String s1="om"; -> it is String declaration Now, the main point: Why is String Immutable?-> In Java, String objects are stored in the String Constant Pool (SCP), which resides inside the Heap memory of the JVM. e.g. -> String s1 = "Om"; String s2 = s1.concat("Shelke"); "Om" is stored in the String Constant Pool. When we try to modify or concatenate the string, a new String object is created. The existing String object is never modified. Every modification creates a new object. This behavior is called immutability. String immutable is made for security, memory optimization, and thread safety purposes. #corejava #javadeveloper
To view or add a comment, sign in
-
-
💡 Why is String immutable in Java? If you’ve ever attended a Java interview, code Snippet from String immutability has probably come up. Instead of memorizing the answer, let’s understand the “why” behind the design. Java made String immutable for security, performance, and reliability. Here’s how 👇 🔐 1. Security Strings are heavily used in security-critical areas: Database URLs Usernames & passwords File paths Network connections If String were mutable, a single reference change could compromise sensitive data. ✅ Immutability ensures once created, a string cannot be altered or tampered with. 💾 2. String Pool & Memory Efficiency Java maintains a String Constant Pool. String s1 = "Java"; String s2 = "Java"; Both references point to the same object. If strings were mutable, modifying one would affect all references. ✅ Immutability enables safe sharing and reduced memory usage. 🧵 3. Thread Safety Immutable objects are thread-safe by default. No synchronization required No race conditions No inconsistent state This is crucial in Java’s multi-threaded environment. ⚡ 4. HashCode Caching (Performance) Strings are widely used as keys in: HashMap HashSet Because strings don’t change: Their hashCode() can be cached Lookup operations are faster Mutable strings would break hash-based collections. 🧩 5. Class Loading & Reflection Safety Class names are passed as strings: Class.forName("com.example.MyClass"); Immutability ensures: Reliable class loading Protection against accidental or malicious modification 🧠 6. Predictability & Simplicity Immutability results in: Easier debugging Fewer side effects Safer APIs Java follows a powerful principle: Make commonly used objects safe by default. ✨ Understanding the cause before the effect makes concepts stick longer than memorizing answers. #Java #String #Immutability #JavaInterview #BackendDevelopment #SoftwareEngineering #CleanCode
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 String Is Immutable in Java In Java, String objects are immutable. This means once a String is created, its value cannot be changed. 1️⃣ What Immutability Means When you modify a String, Java does not change the existing object. Instead, it creates a new String object with the updated value. 2️⃣ String Pool Java stores String literals in a special memory area called the String Pool. Because Strings are immutable, multiple references can safely point to the same String object. 3️⃣ Security Benefits Strings are commonly used for sensitive data such as file paths, URLs, and class loading. Immutability ensures these values cannot be changed unintentionally or maliciously. 4️⃣ Performance and Caching • Hash values of Strings can be cached • Strings can be safely reused • Improves performance in collections like HashMap 5️⃣ Thread Safety Immutable objects are inherently thread-safe. Multiple threads can use the same String without synchronization. 💡 Key Takeaways: - String immutability ensures safety and predictability - Enables String Pool optimization - Improves performance and thread safety #Java #CoreJava #String #Immutability #BackendDevelopment
To view or add a comment, sign in
-
📌 Why Is String Immutable in Java? (More Important Than It Sounds) Almost every Java interview asks this question: - Why is String immutable in Java? Most answers stop at: 👉 “For security.” That’s only part of the story. 🔹 1️⃣ Security (the obvious reason) String is used everywhere: - File paths - Database URLs - Network connections - Class loading If a String could change after creation, malicious code could modify critical values after validation. Immutability makes this impossible. 🔹 2️⃣ Hashing & Collections (interview favorite) String is heavily used as a key in HashMap. Because it’s immutable: - Its hashCode() never changes - Hash-based collections remain stable and correct If String were mutable, - HashMap would break in unpredictable ways. 🔹 3️⃣ String Pool & Performance (often missed) Java maintains a String Pool to reuse common strings. Immutability allows: - Safe sharing of the same String object - Reduced memory usage - Faster comparisons Without immutability, pooling would be unsafe. 🔹 4️⃣ Thread Safety (free benefit) Immutable objects are naturally thread-safe. - No synchronization. - No race conditions. - No surprises. 🧠 Interview Insight This question is not about memorizing facts. It tests whether you understand: - How Java balances performance, safety, and simplicity - Why design decisions matter long-term #Java #SoftwareEngineering #InterviewPreparation #Programming #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 I’ve just published a complete, practical guide on Why Strings Are Immutable in Java! Working with strings in Java feels simple at first — but truly understanding why Strings are immutable, how they work internally, and why it matters is what separates average Java developers from strong, production-ready engineers. Java strings are more than just text — they’re objects with critical roles in memory, security, performance, and multi-threading. A weak understanding of String immutability often leads to: ❌ Security vulnerabilities (like unsafe URLs or passwords) ❌ Unexpected behavior when sharing strings ❌ Thread-safety issues in multi-threaded code ❌ Bugs with hash-based collections (HashMap, HashSet) ❌ Inefficient memory usage and poor performance This guide explains String immutability from first principles, focusing on how Java really handles Strings under the hood — not just surface-level facts. 🔍 Here’s what you’ll learn: • What immutability actually means in Java • Internal structure of String objects (char[] vs byte[] storage) • How the String Pool works and why it’s memory-efficient • Security benefits of immutable Strings • Thread safety and safe sharing of Strings • How hashCode caching improves performance in collections • How modifying a String creates a new object • When to use StringBuilder or StringBuffer instead • Why immutable Strings are critical for class loading and JVM safety Whether you’re: ✔ Working with secure Java applications ✔ Optimizing memory and performance ✔ Using Strings as keys in collections ✔ Preparing for Java interviews ✔ Trying to write robust, production-ready Java code This guide will completely change how you reason about Strings in Java. 📖 Read the full article here: 👉 https://lnkd.in/gh_rCSzC
To view or add a comment, sign in
-
-
🤯 Java's Hidden Cache War: Integer vs String - Which One Bites Developers More?♨️ Java caches small Integers (-128 to 127) but Strings work differently. Knowing why saves you from bugs AND improves performance. Quick breakdown: 👇 1. INTEGER CACHE (Reference-Based) Integer a = 100; Integer b = 100; System.out.println(a == b); Why: Integer.valueOf() reuses cached objects Range: -128 to 127 (configurable) Purpose: Performance for common numbers Gotcha: == works only within cache range! 2. STRING POOL (Value-Based) String s1 = "hello"; String s2 = "hello"; System.out.println(s1 == s2); Why: JVM pools string literals Manual control: String.intern() Purpose: Memory optimization Warning: Don't overuse intern()! THE CRITICAL DIFFERENCE: Integer cache: Fixed size, performance-focused String pool: Dynamic, memory-focused GOLDEN RULE: // ❌ Never do this: if (intObj1 == intObj2) // ✅ Always do this: if (intObj1.equals(intObj2) PRACTICAL IMPACT: Loops with autoboxing → Cache helps! Repeated strings → Pool helps! == comparisons → Will bite you! TEST YOURSELF: java Integer x = 200; Integer y = 200; System.out.println(x == y); // ??? Answer below! First 5 correct answers get a Java Memory cheatsheet. Like if you learned something! Save for your next interview prep! Follow for more Java insights! #Java #Programming #Caching #Developer #Coding #Java #JVM #MemoryManagement #PerformanceOptimization #SoftwareEngineering #Programming #Coding #BackendDevelopment #SystemDesign #JavaDeveloper #TechInterview #CleanCode #DeveloperTips #Caching
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
-
Java Bytes #5 What will be the output of the following code? class Main { private static int getNum012(int num) { try { if(num == 1) { return 1; } if(num == 0) { num = num / 0; return 0; } } catch(ArithmeticException e) { return 0; } finally { return 2; } } public static void main(String[] args) { System.out.println(getNum012(0)); System.out.println(getNum012(1)); System.out.println(getNum012(2)); } } ---------------------------------------------------------------- Java is like my girlfriend. I have misunderstood her many times. Still I try to understand her a lot. Please feel free to correct me if I have misunderstood her. #javaBytes #javaIsLove #javaInterviewPrep
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
The issue lies in out variable. It is because we have created a variable called System of type String. Now, the variable System is trying to access the variable called out which is not an instance variable of String class. To resolve the issue and print, you can specify java.lang.System for all the printing statements so that java knows that we are referring to the class called System in java.lang package. Corrected code: class Main { public static void main(String[] args) { String String = "String"; String Main = "Main"; String main = "main"; String System = "System"; String out = "out"; String println = "println"; java.lang.System.out.println(String); java.lang.System.out.println(Main); java.lang.System.out.println(main); java.lang.System.out.println(System); java.lang.System.out.println(out); java.lang.System.out.println(println); } }