Method overloading in Java is when a class has multiple methods with the same name but different parameters (either in number or type). This allows you to perform similar but slightly different tasks using the same method name, improving code readability and reducing redundancy. java example : class Calculator { // Adds two integers public int add(int a, int b) { return a + b; } // Adds three integers public int add(int a, int b, int c) { return a + b + c; } // Adds two double values public double add(double a, double b) { return a + b; } } public class Test { public static void main(String[] args) { Calculator calc = new Calculator(); System.out.println(calc.add(5, 10)); // calls add(int, int) System.out.println(calc.add(5, 10, 15)); // calls add(int, int, int) System.out.println(calc.add(5.5, 3.2)); // calls add(double, double) } } Here, the add method name is overloaded with different parameter lists. The compiler decides which method to call based on arguments given. Summary: Method overloading means same method name, different parameters.Improves code clarity; no need for different method names for similar actions.Compiler selects correct method based on argument types/count. #Java #MethodOverloading #ProgrammingConcepts #CodingTips #JavaBasics #JavaDevelopment #100DaysOfCode #Day6ofcoding
How Java Method Overloading Works
More Relevant Posts
-
🚀 Constructor vs Method in Java – A Must-Know Difference for Every Developer! When you dive deeper into Java, one of the most fundamental yet commonly misunderstood concepts is the difference between a Constructor and a Method. Both may look similar — they can have parameters, perform actions, and even look almost identical in syntax — but their purpose and behavior are quite different 👇 🔹 Constructor 👉Used to initialize objects. 👉Has the same name as the class. 👉No return type, not even void. 👉Automatically invoked when an object is created. 🔹 Method 👉Used to define behavior or functionality of an object. 👉Can have any name (except the class name). 👉Always has a return type (or void). 👉Invoked explicitly after object creation. Here’s a simple and clear example 👇 class Car { String model; int year; // Constructor Car(String model, int year) { thismodel = model; this.year = year; System.out.println("Car object created!"); } // Method void displayDetails() { System.out.println("Model: " + model + ", Year: " + year); } public static void main(String[] args) { Car c1 = new Car("Tesla Model 3", 2024); // Constructor called c1.displayDetails(); // Method called } } ✅ Key Takeaway: Think of a constructor as giving life to an object, while a method defines what that object can do once it’s alive! #Java #OOP #ProgrammingConcepts #LearnJava #CodeBetter #SoftwareDevelopment #JavaDevelopers
To view or add a comment, sign in
-
-
public static void main(String[] args) This line is the main method in Java — the entry point of every Java program. 1. public - It is an access modifier. - It means this method is accessible from anywhere. - The Java Virtual Machine (JVM) must be able to call this method from outside the class — that’s why it must be public. Example : If it’s not public, JVM cannot access it → program won’t run. 2. static - It means the method belongs to the class and not to any specific object. - JVM can call this method without creating an object of the class. Example : ClassName.main(args); // called directly without creating object 3. void - It is the return type. - It means this method does not return any value to the program. Example : If we write int instead of void, we’d have to return an integer value — but main() doesn’t return anything. 4. main This is the method name recognized by JVM as the starting point of every program. Execution always begins from this method. Example : public static void main(String[] args) { System.out.println("Hello, World!"); } Here, execution starts at main(). 5. (String[] args) - This is a parameter (an array of strings). - It stores command-line arguments that you can pass when running the program. Example : If you run: java Test Hello World Then: args[0] = "Hello" args[1] = "World" -- Here we have simple way to understand Part Meaning Purpose public Access Modifier JVM can access it static Belongs to class Called without object void Return Type Doesn’t return anything main Method Name Program entry point String[] args Parameter Stores command-line inputs #Java #Programming #Core java #Codegnan Anand Kumar Buddarapu Uppugundla Sairam Saketh Kallepu
To view or add a comment, sign in
-
-
🚀 Map.of() vs Map.ofEntries(): The Java 9 Feature Every Developer Should Know 🔹 1. What They Are ? Map.of() and Map.ofEntries() are Java 9 factory methods to create immutable maps with clean, concise syntax. 🔹 2. Map.of() — Best for Small Maps Use when: You have up to 10 key-value pairs Highlights Most concise syntax Extremely readable Throws error on duplicate keys Immutable by design Example: Map.of("A", 1, "B", 2, "C", 3); 🔹 3. Map.ofEntries() — Best for Larger Maps Use when: You need more than 10 entries or prefer structured formatting Highlights No limit on number of entries Works with Map.entry(k, v) Cleaner for long or dynamic maps Immutable Example: Map.ofEntries( Map.entry("A", 1), Map.entry("B", 2), Map.entry("C", 3) ); 🔹 4. When to Use What? ✨ Use Map.of() For quick config maps, test constants, or small static data. ✨ Use Map.ofEntries() For big maps, cleaner formatting, or programmatically built entries. #java #interviewprep
To view or add a comment, sign in
-
-
🚀 Mastering Strings in Java – The Backbone of Text Handling! 🧵 In Java, Strings are more than just text — they’re objects that make text manipulation powerful and efficient. Let’s break it down 👇 🔹 1. What is a String? A String in Java is an object that represents a sequence of characters. Example: String name = "Java"; Yes, even though it looks simple — it’s backed by the String class in java.lang package! 🔹 2. Immutable by Nature 🧊 Once created, a String cannot be changed. If you modify it, Java creates a new object in memory. String s = "Hello"; s = s + " World"; // Creates a new String object ✅ Immutability ensures security, caching, and thread-safety. 🔹 3. String Pool 🏊♂️ Java optimizes memory by storing String literals in a special area called the String Constant Pool. If two Strings have the same literal value, they point to the same memory! 🔹 4. Common String Methods 🛠️ s.length(); // Returns length s.charAt(0); // Returns first character s.toUpperCase(); // Converts to uppercase s.equals("Java"); // Compares values s.substring(0, 3);// Extracts substring 🔹 5. Mutable Alternatives 🧱 For performance-heavy string manipulations, use: StringBuilder (non-thread-safe, faster) StringBuffer (thread-safe) 💡 Pro Tip: Use StringBuilder inside loops for better performance instead of concatenating Strings repeatedly. #Java #Programming #Coding #100DaysOfCode #JavaDeveloper #StringsInJava #SoftwareDevelopment #TechLearning
To view or add a comment, sign in
-
💡 Difference between == and .equals() in Java — and why it still confuses even experienced devs In Java, many developers think == and .equals() do the same thing... but they don’t 👇 ⚙️ == — The == operator compares memory references. It checks whether two variables point to the same object. String a = new String("Java"); String b = new String("Java"); System.out.println(a == b); // false 🚫 Here, a and b are two different objects, even if their content is identical. 🧠 .equals() — The .equals() method compares the logical content of the objects (when properly implemented). System.out.println(a.equals(b)); // true ✅ Both Strings contain “Java”, so the result is true. 🧩 Extra tip: Primitive types (int, double, boolean, etc.) use == because they don’t have .equals(). Objects (String, Integer, List, etc.) should use .equals() unless you need to check if they’re the same object in memory. 💬 Conclusion: Use == ➡️ to compare references Use .equals() ➡️ to compare values 💭 Have you ever fallen into this trap? Share your experience below 👇 #Java #Backend #CleanCode #DeveloperTips #SpringBoot #Programming #Learning
To view or add a comment, sign in
-
☕ 33 Core Technical Rules of Java 1. Everything in Java lives inside a class or interface. 2. One public class per file, and the file name must match it. 3. Main entry point: public static void main(String[] args). 4. Primitives (int, boolean, etc.) are not objects. 5. References hold addresses, not the actual values. 6. Strings are immutable and stored in the string pool. 7. Methods must always belong to a class or interface. 8. Constructors have no return type and share the class name. 9. this → current instance; super → parent class. 10. Static members belong to the class, not instances. 11. Overloading → compile-time; Overriding → runtime. 12. Every object extends java.lang.Object. 13. Garbage Collection is automatic — no manual freeing. 14. Access modifiers control visibility (public, private, etc.). 15. final means no modification (variable, method, class). 16. Interfaces can’t hold mutable state. 17. Abstract classes can’t be instantiated. 18. Generics are type-erased at runtime. 19. Arrays are covariant and know their length. 20. Exceptions are divided into checked and unchecked. 21. Checked exceptions must be declared with throws. 22. Threads must start via start(), not run(). 23. synchronized locks on the object monitor. 24. Enums are full classes with fields and methods. 25. Autoboxing handles primitive ↔ wrapper conversions. 26. Annotations can exist at source, class, or runtime. 27. Reflection gives runtime access to class metadata. 28. instanceof checks type; casting may throw exceptions. 29. Fields have default values; locals don’t. 30. Java is pass-by-value only (references are copied by value). 31. switch supports String, enum, and primitives. 32. Modules (module-info.java) define explicit dependencies. 33. The JVM verifies bytecode integrity before execution. #Java #ProgrammingLanguages #SoftwareEngineering #BackendDevelopment #CodeTips #Developers #SystemProgramming #TechPost
To view or add a comment, sign in
-
🎯 Java Generics — Why They Matter If you’ve been writing Java, you’ve probably used Collections like List, Set, or Map. But have you ever wondered why List<String> is safer than just List? That’s Generics in action. What are Generics? Generics let you parameterize types. Instead of working with raw objects, you can define what type of object a class, method, or interface should work with. List<String> names = new ArrayList<>(); names.add("Alice"); // names.add(123); // ❌ Compile-time error Why use Generics? 1. Type Safety – Catch errors at compile-time instead of runtime. 2. Code Reusability – Write flexible classes and methods without losing type safety. 3. Cleaner Code – No need for casting objects manually. public <T> void printArray(T[] array) { for (T element : array) { System.out.println(element); } } ✅ Works with Integer[], String[], or any type — one method, many types. Takeaway Generics aren’t just syntax sugar — they make your Java code safer, cleaner, and more reusable. If you’re still using raw types, it’s time to level up! 🚀 ⸻ #Java #SoftwareEngineering #ProgrammingTips #Generics #CleanCode #TypeSafety #BackendDevelopment
To view or add a comment, sign in
-
💡 String vs. StringBuilder: Why Mutability Drives Performance 🚀 When manipulating text in Java, choosing between the immutable String and the mutable StringBuilder determines your application's efficiency. 1. The String Class (Immutable) 🔒 Mutability: String objects are immutable. Once created, their value cannot be changed in the memory location. Behavior: Any operation that seems to modify a String (like using the + operator or concat()) actually creates a brand new String object in the Heap for the result. The original object is discarded (to be collected by the Garbage Collector). Performance Cost: This continuous creation of new, temporary objects is slow and memory-intensive, especially when concatenating strings repeatedly inside a loop. Use Case: Ideal for text that is constant and will not change. 2. The StringBuilder Class (Mutable & Fast) 🔓 Mutability: StringBuilder objects are mutable. Their value can be changed in the same memory location. Behavior: Methods like append(), insert(), and delete() modify the character sequence directly within the existing buffer. No new object is created for intermediate modifications. Thread Safety: StringBuilder is not thread-safe (unsynchronized). This is a feature, not a bug, in single-threaded environments. Performance Benefit: It's significantly faster than String for repetitive manipulation because it avoids the overhead of creating numerous temporary objects. Use Case: Ideal for complex or repeated text manipulation in a single-threaded environment where performance is the priority. 🎯 The Golden Rule: If you are modifying a string inside a loop, always use StringBuilder to prevent performance degradation caused by creating millions of unnecessary String objects. Thank you sir Anand Kumar Buddarapu,Saketh Kallepu,Uppugundla Sairam,Codegnan #Java #ProgrammingTips #String #StringBuilder #PerformanceOptimization #Codegnan
To view or add a comment, sign in
-
-
Here's a simple Java program that demonstrates basic string operations: public class StringExample { public static void main(String[] args) { String name = "John"; String greeting = "Hello, " + name + "!"; System.out.println(greeting); // Output: Hello, John! System.out.println(name.length()); // Output: 4 System.out.println(name.toUpperCase()); // Output: JOHN System.out.println(name.toLowerCase()); // } } Let's break it down with easy analogies: 1. *String Declaration*: `String name = "John";` Think of a string like a labeled box where you can store a message. Here, we're creating a box called `name` and putting the message "John" inside. 2. *String Concatenation*: `String greeting = "Hello, " + name + "!";` Imagine you're writing a greeting card. You're combining different pieces of paper (strings) to create a complete message. Here, we're combining "Hello, ", the contents of the `name` box (John), and "!" to create a new message. 3. *String Length*: `name.length()` Think of a ruler that measures the length of a piece of string. Here, we're asking for the length of the string "John", which is 4 characters. 4. *String Case Conversion*: `name.toUpperCase()` and `name.toLowerCase()` Imagine a keyboard with a caps lock button. `toUpperCase()` is like turning on the caps lock, and `toLowerCase()` is like turning it off. We're converting the string "John" to all uppercase (JOHN) or all lowercase (john). These are basic string operations in Java, and understanding these concepts will help you work with text data in your programs! What will be the output if we convert it into a lower case? Can anyone guess ? #Java #Coding #Programming
To view or add a comment, sign in
-
💻 Today I Learned About Strings in Java In Java, Strings are a collection of characters enclosed within double quotes. They are objects and play a vital role in almost every Java program. There are two types of strings in Java: 🔹 Immutable Strings — Once created, they cannot be changed. Examples: name, date of birth, gender. 🔹 Mutable Strings — These can be modified. Examples: email ID, password, etc. For immutable strings, the class used is String. Strings created without using new keyword are stored in the String Constant Pool. Strings created using new keyword are stored in the Heap Memory. There are multiple ways to compare strings in Java: == → Compares references equals() → Compares values compareTo() → Compares character by character equalsIgnoreCase() → Compares values ignoring case differences Some commonly used String methods are: toLowerCase(), toUpperCase(), length(), charAt(), startsWith(), endsWith(), contains(), indexOf(), lastIndexOf(), and substring(). For mutable strings, we have two classes: StringBuffer → Synchronized, thread-safe, slower, suitable for multi-threaded environments. StringBuilder → Non-synchronized, not thread-safe, faster, suitable for single-threaded environments. ✨ Understanding strings is fundamental in Java, as they form the basis for text manipulation, data handling, and efficient memory management. #Java #String #Programming #Learning #JavaDeveloper #CodingJourney #TechLearning #SoftwareDevelopment #Immutable #Mutable #StringBuilder #StringBuffer
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