Most developers believe that a Java program can only have one "main()" method, but this isn't entirely accurate. A Java class can indeed contain multiple "main()" methods through method overloading, provided their parameter lists differ. However, the Java Virtual Machine (JVM) will only initiate execution from this specific method signature: "public static void main(String[] args)". Any additional "main()" methods will not execute automatically; they must be invoked manually from the original "main()" method. For example: public class Test { public static void main(String[] args) { System.out.println("Original main method"); main(10); } public static void main(int a) { System.out.println("Overloaded main method: " + a); } } In conclusion, while multiple "main()" methods are permissible, the JVM recognizes only one entry point. #Java #Programming #JavaDeveloper #JavaInterview #BackendDevelopment
Java Multiple Main Methods: Myth Busted
More Relevant Posts
-
How Does "ConcurrentHashMap" Achieve Thread Safety in Java? In multithreaded applications, using a normal "HashMap" can lead to race conditions and inconsistent data. While "Hashtable" provides thread safety, it locks the entire map, which can reduce performance. This is where "ConcurrentHashMap" comes in. It provides high performance and thread safety by allowing multiple threads to read and write simultaneously. 🔹 How it Works 1️⃣ Segment / Bucket Level Locking (Java 7) Instead of locking the entire map, "ConcurrentHashMap" divides the map into segments. Each segment can be locked independently, allowing multiple threads to work on different segments. This significantly improves concurrency. 2️⃣ Fine-Grained Locking (Java 8+) In Java 8, the implementation was improved further. Instead of segments, it uses: ✔ CAS (Compare-And-Swap) operations ✔ Node-level synchronization when needed This allows better performance and scalability. 🔹 Example import java.util.concurrent.ConcurrentHashMap; public class Example { public static void main(String[] args) { ConcurrentHashMap<Integer, String> map = new ConcurrentHashMap<>(); map.put(1, "Java"); map.put(2, "Spring"); map.put(3, "Kafka"); map.forEach((k,v) -> System.out.println(k + " : " + v)); } } Multiple threads can safely read and update the map without blocking the entire structure. 🔹 Key Benefits ✔ Thread-safe operations ✔ Better performance than "Hashtable" ✔ Allows concurrent reads and writes ✔ Highly scalable in multithreaded environments In simple terms: "HashMap" → Not thread safe "Hashtable" → Thread safe but slow "ConcurrentHashMap" → Thread safe and optimized for concurrency. #Java #ConcurrentHashMap #Multithreading #JavaDeveloper #Concurrency #Programming
To view or add a comment, sign in
-
🚨 Most Common Confusion with Variables in Java (Even for Experienced Developers) Many Java developers get confused between Class Variables, Instance Variables, and Local Variables. Understanding the difference is important for writing clean and efficient code. Let’s simplify it 👇 🔹 1. Class Variable (Static Variable) A variable declared with the static keyword. It belongs to the class, not to objects, so all objects share the same copy. Example: class Student { static String schoolName = "ABC School"; } Here, schoolName is shared across all Student objects. 🔹 2. Instance Variable Declared inside a class but without static. Each object gets its own copy. Example: class Student { String name; } Each student object can have a different name. 🔹 3. Local Variable Declared inside methods or blocks and accessible only within that scope. Example: void display() { int count = 10; } This variable exists only during method execution. 📌 Quick Comparison • Class Variable → One copy per class • Instance Variable → One copy per object • Local Variable → Exists only inside method/block 💡 Pro Tip: Local variables must be initialized before use, while class and instance variables get default values automatically. #Java #JavaProgramming #SoftwareDevelopment #CodingTips #BackendDevelopment #Developers
To view or add a comment, sign in
-
💡 **Java Tip: Optional is not just for null checks!** Many developers think `Optional` in Java is only used to avoid `NullPointerException`. But when used correctly, it can make your code **cleaner, more readable, and expressive**. Instead of writing: ``` if(user != null){ return user.getEmail(); } else { return "Email not available"; } ``` You can write: ``` return Optional.ofNullable(user) .map(User::getEmail) .orElse("Email not available"); ``` ✔ Reduces boilerplate null checks ✔ Improves readability ✔ Encourages functional-style programming in Java But remember — **Optional should be used for return types, not fields or method parameters.** Small improvements like this can significantly improve **code quality in large-scale Java applications.** *What’s your favorite Java feature that improves code readability?* #Java #JavaDevelopment #CleanCode #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
Most assume exceptions in Java are straightforward. Until asked to clarify the difference between checked and unchecked. Early on, every exception seemed the same—something fails, an error pops up, you catch and continue. But Java draws a distinct line: Checked exceptions must be caught or declared—they’re verified at compile time. Unchecked exceptions don’t require explicit handling. Take IOException, for example: it’s checked, so Java insists you handle or declare it. NullPointerException is unchecked—still dangerous, but no forced handling. Why does this matter? Checked exceptions often signal recoverable issues. Unchecked usually indicate bugs or logic errors. Grasping this distinction leads to cleaner, more robust code. Great Java developers don’t just catch exceptions—they judge which to handle and which to prevent altogether. #Java #Programming #SoftwareEngineering #JavaDeveloper #CodingTips #SpringBoot
To view or add a comment, sign in
-
Java Devs, let's talk about a core concept that makes our code cleaner and more flexible: "Method Overloading"! Ever wanted to perform similar operations with different inputs without creating a bunch of uniquely named methods? That's where Method Overloading shines! It's a fantastic example of compile-time polymorphism (aka static polymorphism or early binding) that allows a class to have multiple methods with the "same name", as long as their parameter lists are different. Key takeaways: * Same method name, different parameters = ✅ * Cannot overload by return type alone (parameters *must* differ) ⚠️ * The compiler is smart! It picks the most specific match. 🧠 Check out this quick example: ```java class Product { public int multiply(int a, int b) { // Multiplies two numbers return a * b; } public int multiply(int a, int b, int c) { // Multiplies three numbers return a * b * c; } } // Output: // Product of the two integer value: 2 // Product of the three integer value: 6 ``` See how elegant that is? One `multiply` method, multiple functionalities! What are your favorite use cases for Method Overloading in your Java projects? Share in the comments! 👇 #Java #JavaDevelopment #Programming #SoftwareDevelopment #BeginnerProgramming
To view or add a comment, sign in
-
-
NullPointerException — the most famous Java error every developer meets at least once. You write the code. You compile it. You run it with confidence. And then Java says: Exception in thread "main" java.lang.NullPointerException What happened? Your code expected an object… but Java found nothing. In simple words: Developer: “Use this object.” Java: “Which object? There is nothing here.” And boom 💀 Every Java developer has faced this moment at least once. The real lesson? Always check for null values, initialize objects properly, and understand how references work in Java. Because sometimes the problem isn't the code… It's the missing object behind the reference. Be honest 👀 How many times has NullPointerException ruined your day? #Java #JavaDeveloper #Programming #SoftwareDevelopment #Coding #Developers #Tech #BackendDevelopment #LearnJava #CodingLife
To view or add a comment, sign in
-
-
Understanding == vs .equals() in Java 🔍 As I start sharing on LinkedIn, I thought I'd kick things off with a fundamental Java concept that often trips up developers: the difference between == and .equals() **The == Operator:** → Compares memory addresses (reference equality) → Checks if two references point to the exact same object → Works for primitives by comparing actual values **The .equals() Method:** → Compares the actual content of objects → Can be overridden to define custom equality logic → Default implementation in Object class uses == (unless overridden) Here's a practical example: String str1 = new String("Java"); String str2 = new String("Java"); str1 == str2 → false (different objects in memory) str1.equals(str2) → true (same content) **Key Takeaway:** Use == for primitives and reference comparison. Use .equals() when you need to compare the actual content of objects. This fundamental concept becomes crucial when working with Collections, String operations, and custom objects in enterprise applications. What other Java fundamentals would you like me to cover? Drop your suggestions in the comments. #Java #Programming #SoftwareDevelopment #BackendDevelopment #CodingTips #JavaDeveloper
To view or add a comment, sign in
-
-
🚀 Important Java Concepts Every Developer Should Know If you're learning Java or preparing for interviews, these core concepts are a must👇 🔹 OOP Principles Java is based on Object-Oriented Programming: ✔️ Encapsulation ✔️ Inheritance ✔️ Polymorphism ✔️ Abstraction 🔹 JVM, JRE, JDK Understanding how Java runs: ➡️ JVM executes bytecode ➡️ JRE provides runtime environment ➡️ JDK includes tools for development 🔹 Data Types & Variables Know the difference between: ✔️ Primitive (int, float, char, etc.) ✔️ Non-primitive (String, Arrays, Classes) 🔹 Exception Handling Handle errors using: ✔️ try-catch ✔️ finally ✔️ throw & throws 🔹 Collections Framework Important interfaces: ✔️ List ✔️ Set ✔️ Map 🔹 Multithreading Run multiple tasks simultaneously using threads 🔹 String Handling Remember: Strings are immutable in Java 💡 Mastering these basics builds a strong foundation for advanced Java development.
To view or add a comment, sign in
-
🚀 Java Trap: Why "finally" Doesn’t Change the Returned Value 👇 👉 Primitive vs Object Behavior in "finally" 🤔 Looks tricky… but very important to understand. --- 👉 Example 1 (Primitive): public static int test() { int x = 10; try { return x; } finally { x = 20; } } 👉 Output: 10 😲 Why not 20? 💡 Java stores return value before executing "finally" - "x = 10" stored - "finally" runs → changes "x" to 20 - But already stored value (10) is returned --- 👉 Example 2 (Object): public static StringBuilder test() { StringBuilder sb = new StringBuilder("Hello"); try { return sb; } finally { sb.append(" World"); } } 👉 Output: Hello World 😲 Why changed here? 💡 Object reference is returned - Same object is modified in "finally" - So changes are visible --- 🔥 Rule to remember: - Primitive → value copied → no change - Object → reference returned → changes visible --- 💭 Subtle concept… very common interview question. #Java #Programming #Coding #Developers #JavaTips #InterviewPrep 🚀
To view or add a comment, sign in
-
🚀 Understanding Lambda Functions in Java (Simplified) In Java, a Lambda Expression is a concise way to implement a method of a functional interface (an interface with only one abstract method). 👉 Instead of writing bulky code with anonymous classes, lambda helps you write clean and readable code. 🔹 Syntax: (parameters) -> expression 🔹 Example: @FunctionalInterface interface Calculator { int add(int a, int b); } Calculator add = (a, b) -> a + b; System.out.println(add.add(5, 3)); // Output: 8 💡 Key Benefits: ✔ Reduces boilerplate code ✔ Improves readability ✔ Widely used in Collections & Streams ⚠️ Important: Lambda works only with functional interfaces (one abstract method) 💡 About @FunctionalInterface: @FunctionalInterface is optional. Even if we don’t use it, lambda will work as long as the interface has only one abstract method. However, it provides compile-time safety and ensures the interface remains functional. 🚨 Common Mistake: If you add more than one abstract method, it will throw a compile-time error: @FunctionalInterface interface Calculator { int add(int a, int b); int sub(int a, int b); // ❌ Error: Not a functional interface } 🔥 In real-world projects (especially automation & backend), lambda is heavily used for: ✔ Sorting collections ✔ Filtering data ✔ Writing clean logic #Java #Lambda #Programming #Coding #Developers #Java8 #SoftwareEngineering
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