🚀 Can the main method be Overloaded in Java? Short answer: YES ✅ But with an important catch 👇 🔹 What does overloading mean? Method overloading means having multiple methods with the same name but different parameters. 🔹 Can main() be overloaded? Yes, the main method can be overloaded just like any other method in Java. 👉 However, JVM will always call only this signature: public static void main(String[] args) Other overloaded main methods won’t be executed automatically. 🔹 Example: Overloading main() public class MainExample { public static void main(String[] args) { System.out.println("Original main method"); main(10); main("Hello"); } public static void main(int a) { System.out.println("Overloaded main with int: " + a); } public static void main(String s) { System.out.println("Overloaded main with String: " + s); } } Original main method Overloaded main with int: 10 Overloaded main with String: Hello 🔹 Key Points to Remember 💡 ✔️ main()can be overloaded ✔️ JVM always starts execution from public static void main(String[] args) ✔️ Overloaded main() methods must be called explicitly ❌ Overloading does not change program entry point 📌 Interview Tip: If someone asks “Can we overload the main method in Java?” Say: 👉 Yes, but JVM will only call the standard main method signature. #Java #JavaInterview #CoreJava #Programming #CodingTips #SoftwareEngineering
Java Main Method Overloading Explained
More Relevant Posts
-
💻 Java String Problem – Reverse Each Word in a Sentence. 🧠 Problem Statement: Input: "Prince Is Good Singer" Output: "ecnirP sI dooG regniS" 👉 Here, each word is reversed but the sentence order remains the same. 📌 Approach I followed: 1. Take the complete sentence as input. 2. Read the sentence character by character. 3. Create a word until a space is found. 4. When a space appears: a) reverse that word b) add it into the final result 5. Repeat the same process for all words. 6. At the end, reverse the last word and add to the result. 7. Print the final reversed-word sentence. 💡 Important Concept Used: 1. String traversal using loop 2. Character array conversion 3. Swapping logic to reverse a word 4. Building final output step by step 🧾 Java Implementation: public static String reverseWordInString(String str) { String word = ""; String desired_output = ""; for (char ch : str.toCharArray()) { if (ch != ' ') { word += ch; } else { desired_output += reverseString(word) + " "; word = ""; }} desired_output += reverseString(word); // reverse last word return desired_output; } public static String reverseString(String word) { char[] charArr = word.toCharArray(); int charArrLength = charArr.length; for (int i = 0; i < charArrLength / 2; i++) { char temp = charArr[i]; charArr[i] = charArr[charArrLength - 1 - i]; charArr[charArrLength - 1 - i] = temp; } return new String(charArr); } 🚀 Learning Outcome: 1. Improved Java string handling 2. Learned how to reverse words using logic 3. Strengthened problem-solving skills 4. Helpful for Java backend & interview preparation #java #javaPractice #CodingPractice #JavaDeveloper #BackendDeveloper #Programming #LearningJourney #InterviewPreparation
To view or add a comment, sign in
-
-
📌 Switch Expressions in Java – Finally, No More Fall-Through Bugs 🚀 If you're preparing for modern Java interviews, you must know this feature. 👉 Introduced as preview in Java 12 👉 Became stable in Java 14 And it fixed one of the most annoying things in Java. 🤯 The Old Switch Problem switch(day) { case MONDAY: return 1; case TUESDAY: return 2; default: return 0; } Issues: - Verbose - Easy to forget break - Fall-through bugs - Not expressive 🚀 Switch Expression (Modern Way) int result = switch(day) { case MONDAY -> 1; case TUESDAY -> 2; default -> 0; }; Cleaner. Safer. More readable. No break. No accidental fall-through. 🔥 Multi-Line Case Example int result = switch(day) { case MONDAY, TUESDAY -> 1; case WEDNESDAY -> { System.out.println("Midweek"); yield 2; } default -> 0; }; Yes — yield returns a value from a block. 🔑 Final Thought Switch Expressions didn’t just improve syntax. They made switch: - Safer - More functional - More predictable Modern Java is about reducing accidental complexity. #Java #ModernJava #Java14 #SoftwareEngineering #InterviewPreparation
To view or add a comment, sign in
-
-
Day 38 - 🚀 Understanding toString() in Java In Java, the toString() method is used to return a string representation of an object. It belongs to the Object class, which means every Java class inherits it by default. 📌 Default Behavior If you don't override toString(), Java prints a combination of class name + hashcode. class Person { String name; int age; } Person p = new Person(); System.out.println(p); Output: Person@1a2b3c This output is usually not very useful for users or developers. 📌 Overriding toString() To display meaningful object information, we override the toString() method. class Person { String name; int age; @Override public String toString() { return "Person[name=" + name + ", age=" + age + "]"; } } Output: Person[name=John, age=25] 📌 Why toString() is Important ✔ Provides a human-readable representation of objects ✔ Useful for debugging and logging ✔ Makes object data easier to print and understand 💡 Pro Tip Always use the @Override annotation when implementing toString() to ensure the method is correctly overridden. ✅ Conclusion The toString() method helps convert an object into a clear and readable string format, making debugging and displaying data much easier in Java applications. #Java #OOP #JavaProgramming #ToString #ProgrammingConcepts #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Day 26 – Core Java | Method Overloading, Command Line Arguments & Encapsulation Today’s session connected multiple powerful concepts that directly impact interview performance. 🔹 Method Overloading – Deep Understanding We revisited the 3 compiler rules: 1️⃣ Method Name 2️⃣ Number of Parameters 3️⃣ Type of Parameters If all three match → ❌ Duplicate Method Error If no exact match → ✅ Type Promotion If multiple matches possible → ❌ Ambiguity We also explored: ✔ How type promotion works internally ✔ Why ambiguity happens ✔ Real example: System.out.println() is overloaded ✔ Yes — even the main() method can be overloaded Important insight: JVM always executes public static void main(String[] args). 🔹 Command Line Arguments Understood how: javac Demo.java java Demo ABC 123 Arguments are stored in String[] args They are always stored as String type Accessed using args[index] Size is dynamic Also clarified common mistakes like: ArrayIndexOutOfBoundsException 🔹 Introduction to Object-Oriented Programming (OOPS) Started the most important phase of Java. OOPS = Object-Oriented Programming System Built on 4 Pillars: ✔ Encapsulation ✔ Inheritance ✔ Polymorphism ✔ Abstraction Every real-world application is built on these principles. 🔹 Encapsulation – First Pillar Encapsulation = Providing security to important data + Providing controlled access Implemented using: ✔ private → Security ✔ Setter → Set data ✔ Getter → Get data Real-world analogy: Just like a bank protects balance and allows access only through controlled operations. We implemented: Private instance variable Setter with validation Getter to retrieve value Security + Control = Proper Encapsulation 💡 Biggest Takeaway Syntax is easy. Understanding compiler behavior, JVM flow, and memory access control builds real developer confidence. From here onwards, we dive deep into OOPS. Consistency now = Confidence in interviews later 🚀 #Day26 #CoreJava #MethodOverloading #Encapsulation #OOPS #JavaInterview #DeveloperJourney
To view or add a comment, sign in
-
🚨 Java Interview Question: 👉 What is the difference between final, finally, and finalize()? Many developers confuse these three — but they are completely different concepts. ✅ 1️⃣ final (Keyword) final is used to restrict modification. It can be used with: Variables Methods Classes 💻 Example: final int x = 10; x = 20; // ❌ Compilation Error 🔹 With Method: final void show() {} → Cannot be overridden. 🔹 With Class: final class Test {} → Cannot be inherited. 🧠 Real-Life Example: Think of final like a fixed deposit in a bank 💰 Once locked, you cannot change it before maturity. ✅ 2️⃣ finally (Block) finally is used in exception handling. It always executes whether exception occurs or not. 💻 Example: try { int a = 10 / 0; } catch (Exception e) { System.out.println("Exception occurred"); } finally { System.out.println("Cleanup code"); } 👉 finally block runs no matter what. 🧠 Real-Life Example: Think of finally like turning off the gas stove after cooking 🔥 No matter what happens, you must turn it off. ✅ 3️⃣ finalize() (Method) finalize() is a method called by Garbage Collector before destroying an object. ⚠ In modern Java, it is deprecated and not recommended. 💻 Example: protected void finalize() throws Throwable { System.out.println("Object is destroyed"); } It was used for cleanup before object removal from Heap. Managed by the Java Virtual Machine. 🎯 Strong Interview One-Liner: 👉 final restricts modification, 👉 finally executes cleanup code in exception handling, 👉 finalize() was used for garbage collection cleanup (now deprecated). #Java #JavaDeveloper #InterviewPreparation #OOPS #GarbageCollection #Programming #BackendDevelopment
To view or add a comment, sign in
-
🚀 Mastering String, StringBuffer & StringBuilder in Java Today I strengthened my understanding of one of the most important Core Java concepts: String handling and performance optimization. In Java, we commonly use String, StringBuffer, and StringBuilder to work with text, but choosing the right one makes a big difference in performance and memory efficiency. 🔹 String (Immutable) String objects cannot be changed once created. Any modification creates a new object in memory. ✔ Thread-safe ❌ Slower when modified frequently Example: String s = "Hello"; s = s + " World"; --- 🔹 StringBuffer (Mutable & Thread-safe) StringBuffer allows modification without creating new objects and is safe for multi-threaded environments. ✔ Mutable ✔ Thread-safe ❌ Slightly slower due to synchronization Example: StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); --- 🔹 StringBuilder (Mutable & Fastest) StringBuilder is similar to StringBuffer but not thread-safe, making it faster and ideal for single-threaded applications. ✔ Mutable ✔ Fastest performance ❌ Not thread-safe Example: StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); --- 📌 Key Interview Insight: • Use String → when data should not change • Use StringBuffer → multi-threaded environment • Use StringBuilder → single-threaded & high performance Understanding these differences helps write optimized, efficient, and scalable Java applications. #Java #CoreJava #Programming #SoftwareDevelopment #JavaDeveloper #LearningJourney #Coding
To view or add a comment, sign in
-
String vs StringBuilder vs StringBuffer in Java — Explained Simply If you work with Java, you encounter strings frequently. However, many developers may not clearly understand when to use "String," "StringBuilder," or "StringBuffer," and this misunderstanding can negatively impact performance. Let’s break it down logically. 1. String — Immutable A "String" object cannot be modified once created. String str = "Hello"; str.concat(" World"); System.out.println(str); Output: Hello Why? Because every modification creates a new object, leaving the original unchanged. Use when: - The value should not change - Safety and readability matter more than performance - Constants or fixed text 2. StringBuilder — Mutable & Fast "StringBuilder" allows modification without creating new objects. StringBuilder sb = new StringBuilder("Hello"); sb.append(" World"); System.out.println(sb); Output: Hello World Changes happen in the same object, resulting in better performance. Use when: - Heavy string manipulation - Loops or dynamic text building - Single-threaded applications 3. StringBuffer — Mutable & Thread-Safe "StringBuffer" functions like "StringBuilder" but is synchronized. StringBuffer sb = new StringBuffer("Hello"); sb.append(" World"); System.out.println(sb); It is safe for multi-threaded environments but slightly slower due to synchronization. Use when: - Multiple threads access the same string - Data consistency is critical Quick Comparison Feature | String | StringBuilder | StringBuffer Mutability | ❌ Immutable | ✅ Mutable | ✅ Mutable Thread Safety | ✅ Yes | ❌ No | ✅ Yes Performance | Slow | Fastest | Medium Best For | Constant values | Single-thread operations | Multi-thread operations Simple Rule to Remember: - Fixed text → String - Performance needed → StringBuilder - Multi-thread safety → StringBuffer Understanding these differences can significantly enhance memory usage and application performance. #Java #Programming #SoftwareDevelopment #BackendDevelopment #JavaDeveloper #CodingConcepts
To view or add a comment, sign in
-
-
A small Java concept I revisited this week: Difference between String.valueOf() and toString() At first glance, both convert objects to String: String.valueOf(obj) obj.toString() But their behavior is different when the object is null. Example: Object obj = null; String.valueOf(obj); // returns "null" obj.toString(); // throws NullPointerException So why does this happen? Let’s look at the internal working. Inside the String class, String.valueOf(Object obj) is implemented like this: public static String valueOf(Object obj) { return (obj == null) ? "null" : obj.toString(); } This means: • If the object is null → it safely returns the string "null" • Otherwise → it calls obj.toString() But when we directly call: obj.toString() Java tries to invoke a method on a null reference, which immediately throws a NullPointerException. Why this matters in real applications: When converting values (like IDs, numbers, or objects) to String, String.valueOf() is often safer because it avoids unexpected crashes. Small details like this make Java code more reliable. Always interesting how tiny language features can prevent real production bugs. Which one do you usually use in your projects? #Java #BackendEngineering #SoftwareEngineering #JavaTips #LearningInPublic
To view or add a comment, sign in
-
🚀 Wrapper Classes in Java – Explained Simply In Java, Wrapper Classes convert primitive data types into objects. This is important because many Java features like Collections and Generics work only with objects. 🔹 Primitive Types vs Wrapper Classes byte → Byte short → Short int → Integer long → Long float → Float double → Double char → Character boolean → Boolean All wrapper classes belong to the java.lang package, so no import is required. --- 🔹 Why Wrapper Classes are Needed • Collections (ArrayList, HashMap) store objects only • Provide useful utility methods • Support null values • Enable Generics Example: ArrayList<Integer> numbers = new ArrayList<>(); numbers.add(10); numbers.add(20); --- 🔹 Types of Conversion 1. Boxing – Primitive → Object "Integer obj = Integer.valueOf(10);" 2. Unboxing – Object → Primitive "int num = obj.intValue();" 3. Autoboxing (Automatic conversion) "Integer obj = 10;" 4. Auto-Unboxing "int num = obj;" --- 🔹 Common Wrapper Methods "Integer.parseInt("100")" → String → int "Integer.valueOf("200")" → String → Integer "Integer.max(10,20)" "Integer.min(10,20)" --- 🔹 Important Points ✔ Wrapper classes are immutable ✔ Stored as objects in heap memory ✔ Introduced Autoboxing in Java 5 --- 🎯 Java Wrapper Class Interview Questions 1️⃣ What are Wrapper Classes in Java? 2️⃣ Why are wrapper classes needed? 3️⃣ Difference between "parseInt()" and "valueOf()"? 4️⃣ What is Autoboxing and Auto-Unboxing? 5️⃣ Why can't primitives be used in Collections? --- 💡 Understanding wrapper classes is essential when working with Java Collections, APIs, and frameworks. #Java #JavaDeveloper #Programming #Coding #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Pattern Matching in Java – Write Cleaner & Safer Code Java keeps evolving, and Pattern Matching is one of those features that genuinely improves day-to-day coding. 💡 Instead of writing verbose instanceof checks and manual casting, Java now lets us match, test, and extract values in a single step. --- 🔍 Before (Traditional instanceof) Object obj = "Hello Java"; if (obj instanceof String) { String value = (String) obj; System.out.println(value.length()); } --- ✅ After (Pattern Matching) Object obj = "Hello Java"; if (obj instanceof String value) { System.out.println(value.length()); } ✔ No explicit casting ✔ Less boilerplate ✔ More readable and safer code --- ✨ Where Pattern Matching Helps Most Handling heterogeneous objects Cleaner business logic Better null safety Readable conditional flows --- 🧠 Bonus: Pattern Matching with switch (Java 17+) static String process(Object obj) { return switch (obj) { case Integer i -> "Number: " + i; case String s -> "Text: " + s; case null -> "Null value"; default -> "Unknown type"; }; } This makes switch type-aware, expressive, and future-ready. 👉 Pattern Matching is a must-know feature. #Java #Java17 #PatternMatching #CleanCode #BackendDevelopment #JavaDeveloper
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