Java Brain Teaser: Are you declaring what you think you're declaring? Take a look at these two lines of code. They look almost identical, but they behave very differently: Scenario A: int[] ids, types; Scenario B: int ids[], types; 🔍 The Breakdown In Scenario A, you get exactly what you’d expect: two int arrays. ids ➡️ int[] types ➡️ int[] In Scenario B, things get weird. By moving the brackets to the variable name, you change the scope of the array declaration: ids ➡️ int[] (Array) types ➡️ int (Simple primitive!) 💡 Why does this happen? Brackets on the Type: Apply to every variable in that declaration line. Brackets on the Name: Apply only to that specific variable. >>The "Clean Code" Takeaway Always place brackets on the type (int[] ids). Avoid declaring multiple variables of different types (or dimensions) on a single line. #Java #Programming #CleanCode #SoftwareDevelopment #CodingTips
Java Array Declaration Gotcha: Brackets on Type vs Name
More Relevant Posts
-
Java Brain Teaser: Are you declaring what you think you're declaring? Take a look at these two lines of code. They look almost identical, but they behave very differently: Scenario A: int[] ids, types; Scenario B: int ids[], types; 🔍 The Breakdown In Scenario A, you get exactly what you’d expect: two int arrays. ids ➡️ int[] types ➡️ int[] In Scenario B, things get weird. By moving the brackets to the variable name, you change the scope of the array declaration: ids ➡️ int[] (Array) types ➡️ int (Simple primitive!) 💡 Why does this happen? Brackets on the Type: Apply to every variable in that declaration line. Brackets on the Name: Apply only to that specific variable. >>The "Clean Code" Takeaway Always place brackets on the type (int[] ids). Avoid declaring multiple variables of different types (or dimensions) on a single line. #Java #Programming #CleanCode #SoftwareDevelopment #CodingTips
To view or add a comment, sign in
-
♻️ Why should you always close Scanner in Java? Scanner is used to read input, from the console, a file, or a stream. But a lot of beginners (including me, early on) never bother closing it after use. Here's why that's a problem: ->it holds onto system resources even after your program is done with them ->for file-based Scanners, it can lock the file or cause data not to be flushed properly ->in larger programs, unclosed Scanners can quietly lead to resource leaks The fix is simple, either call: ✔️ sc.close() at the end ✔️ or use a try-with-resources block so Java closes it automatically While practicing Java basics, I realized the code worked either way… but one way was responsible, and the other wasn't. That's something no compiler warning will tell you. Writing correct code and writing clean, responsible code are two different things. Learning the difference early makes you a better developer. Learning in public, improving step by step 🤍 #Java #ResourceManagement #LearningInPublic #Programming
To view or add a comment, sign in
-
@programiz 🚀 Mini Java Project: Rock Paper Scissors Game As part of my continuous learning in Java development, I built a simple Rock Paper Scissors console game using Java. 🔹 Concepts used in this project: • Java Basics & Control Flow • Loops and Conditional Statements • Random class for computer choice • Scanner for user input • Switch expressions • Basic game logic implementation The program allows a user to play 3 rounds against the computer, and it tracks wins, losses, and draws before declaring the final result. Small projects like this help strengthen problem-solving skills and improve understanding of Java logic building #Java #Programming #Coding #SoftwareDevelopment #LearningJourney #JavaDeveloper
To view or add a comment, sign in
-
In Java, both ArrayList and Vector are classes used to store dynamic arrays (resizable arrays). But there are important differences between them. 🔹 1️⃣ Basic Introduction Java provides both ArrayList and Vector in the java.util package. Both implement the List interface. Both allow duplicate elements. Both maintain insertion order. 🔹 2️⃣ ArrayList ArrayList is not synchronized, so it is faster. ✅ Features: Not thread-safe Faster performance Introduced in Java 1.2 Increases size by 50% when full 🔹 3️⃣ Vector Vector is synchronized, so it is thread-safe. ✅ Features: Thread-safe (synchronized methods) Slower than ArrayList Legacy class (introduced in Java 1.0) Doubles its size when full Thankful to my mentor, Anand Kumar Buddarapu, and the practice sessions that continue to strengthen my core Java knowledge. Continuous learning is the key to growth! hashtag #Java #Collections #ThreadSafety #BackendDevelopment #Coding
To view or add a comment, sign in
-
-
✨ DAY-39: 🌳 Understanding DRY Principle in Java through Nature While learning Java, I came across the powerful concept of DRY (Don’t Repeat Yourself) — and the best way I visualized it is through a tree. In nature, a tree doesn’t grow multiple trunks for the same purpose. Instead, it has one strong trunk that supports many branches. 💡 Similarly in Java: Avoid writing the same code again and again Create reusable methods or functions Maintain a single source of truth 🌿 Without DRY: Imagine creating multiple trees for every branch → messy, hard to maintain ❌ 🌿 With DRY: One strong tree (method/class) → multiple branches (reuse) ✅ 👨💻 Java Example: Instead of repeating logic: System.out.println("Welcome"); System.out.println("Welcome"); Use DRY: public void printMessage() { System.out.println("Welcome"); } ✨ Call the method whenever needed! 🚀 Key Benefits: ✔ Cleaner code ✔ Easier maintenance ✔ Better readability ✔ Reduced errors 🌱 Write once, reuse everywhere — just like a tree grows efficiently from a single root. #Java #CleanCode #DRYPrinciple #Programming #CodingJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
Java does not support multiple inheritance through classes, and this is a deliberate design choice rather than a limitation. Allowing multiple inheritance like C++ could lead to the Diamond Problem, where a child class may inherit the same method from two parent classes, creating confusion. Instead, Java promotes a cleaner design by avoiding this complexity. However, Java does permit multiple inheritance through interfaces. A class can implement multiple interfaces, and in cases of method conflicts, Java requires the developer to override the method, eliminating any ambiguity. Here’s an example: interface A { void show(); } interface B { void show(); } class Test implements A, B { public void show() { System.out.println("Multiple inheritance using interfaces"); } public static void main(String[] args) { new Test().show(); } } It's essential to understand that Java does allow multiple inheritance, but it does so in a controlled and safer manner through interfaces instead of classes. For those looking to enhance their foundational knowledge, resources like w3schools.com and GeeksforGeeks can be valuable. #Java #OOP #MultipleInheritance #Interfaces #JavaDeveloper #Programming #Backend #SoftwareEngineering #InterviewPrep
To view or add a comment, sign in
-
-
🚀 StringBuffer vs StringBuilder in Java – When to Use Which? While working with Java Strings, I learned an important concept. In Java, Strings are immutable, which means every time we modify a String, a new object is created in memory. When this happens repeatedly (especially in loops), it can reduce performance. To handle this efficiently, Java provides two mutable classes: 🔹 StringBuffer • Thread-safe (synchronized) • Safe for multi-threaded environments • Slightly slower due to synchronization 🔹 StringBuilder • Not thread-safe • Faster performance • Best for single-threaded applications 💡 Simple rule to remember: Thread safety needed → Use StringBuffer Better performance needed → Use StringBuilder Learning small concepts like these helps write more efficient and optimized Java code. Special thanks to my mentor Anand Kumar Buddarapu for guiding me in understanding these concepts and encouraging continuous learning. 🙏 #Java #Programming #JavaDeveloper #CodingJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
Strings in Java are not just text… they are attitude 😌 Once created, they don’t change. No matter how much you try… Java just creates a new one. You think you updated the String… but Java be like: “Na bro, I made a fresh object.” ☕ That’s the power of immutability — better security, better performance, and no unexpected changes. Simple truth: Strings in Java are like promises… once made, they cannot be changed 💔 Be honest 👀 Did you know this… or did Java just break your illusion today? #Java #CoreJava #JavaConcepts #Programming #BackendDevelopment #SoftwareEngineering #Coding #DeveloperLife #LearnJava #TechHumor
To view or add a comment, sign in
-
-
✨DAY-17: 🌳 Understanding Strings in Java – A Real-World Example Learning Java becomes easier when we connect concepts to real life. This image explains Strings in Java using trees as an example: 🔹 Single Tree with One Rope – Just like a simple string reference. 🔹 Multiple Trees Connected by Ropes – Represents the String Pool, where identical string values share memory. 🔹 Separate Trees with Separate Ropes – Represents new String() objects, which create new memory even if the value is the same. 💡 Key Insight: In Java, string literals share memory inside the String Pool to optimize performance, while using new String() creates a new object in heap memory. Understanding this concept helps in: ✅ Writing memory-efficient code ✅ Avoiding unnecessary object creation ✅ Improving performance in large applications Sometimes, the best way to understand programming is to visualize it in nature 🌱 #Java #Programming #CodingLife #JavaDeveloper #LearningJourney #TechConcepts
To view or add a comment, sign in
-
-
Is Java Pass-by-Value or Pass-by-Reference? 👉 Java is strictly Pass-by-Value. Let’s understand why. In Java, method arguments are always passed as copies. For Primitives When a primitive variable (like int, double, etc.) is passed to a method, a copy of its value is created. Inside the method, we modify that copied value, not the original variable. So even if the method changes the parameter, the original variable outside the method remains unchanged. For Objects Objects work slightly differently. When an object is passed to a method, a copy of the reference value is passed. That copied reference still points to the same object in memory. So when we modify the object’s fields inside the method, we are actually modifying the same object, which is why the changes are visible outside the method. Let’s look at a quick visual to understand this better 👇 #Java #JavaDeveloper #BackendDevelopment #Programming #CodingInterview #SoftwareEngineering #JavaBasics #LearnToCode #TechLearning
To view or add a comment, sign in
-
Explore related topics
- Idiomatic Coding Practices for Software Developers
- Coding Best Practices to Reduce Developer Mistakes
- Writing Clean, Dynamic Code in Software Development
- How to Achieve Clean Code Structure
- Intuitive Coding Strategies for Developers
- How to Use Arrays in Software Development
- Ways to Improve Coding Logic for Free
- How to Organize Code to Reduce Cognitive Load
- How to Improve Your Code Review Process
- Setting Up A Clean Code Checklist
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