WHAT IS OBJECT CREATION? How is an Object Created in Java? A class provides the blueprint for objects. An object is a real-world instance created from that class. In Java, we use the "new" keyword to create objects. There are three important steps in object creation: 1. Declaration A reference variable is declared with the class type. Example: Car c1; 2. Instantiation The "new" keyword is used to allocate memory in RAM. Example: new Car(); 3. Initialization The constructor is called to initialize the object. Example: Car c1 = new Car(); General Syntax: class_name object_name = new class_name(); Example: Car c1 = new Car(); Here: Car → Class c1 → Reference variable new → Allocates memory Car() → Constructor Important Note: Even if a class contains multiple methods, they will not execute automatically. For execution to begin, the program must contain a main() method. The main() method gives Control Of Execution (COE). MAIN METHOD IN C LANGUAGE: #include <stdio.h> void main() { printf("HELLO WORLD"); } In C, execution begins from main(). MAIN METHOD IN JAVA: Basic Rule: Every method in Java must be inside a class. Correct Java main method structure: public static void main(String[] args) Let’s understand step by step why each keyword is required. Step 1 – public If main is not public, JVM cannot access it. So we attach PUBLIC to make it visible. Step 2 – static If main is not static, JVM cannot call it without creating an object. So we attach STATIC to make it accessible without object creation. Step 3 – void main does not return any value, so return type is void. Step 4 – String[] args JVM looks for this exact identifier. It represents command line arguments. It is an array of Strings used to collect input data. args is a dynamic array that stores values passed from command line. Initially, args is empty. Different Valid Main Method Signatures: public static void main(String[] args) static public void main(String[] args) public static void main(String args[]) public static void main(String... args) All are valid. Key Points to Remember • Save the file with the same name as the class containing main(). Example: Demo.java • Compile using: javac Demo.java This generates Demo.class (bytecode file). • Run using: java Demo JVM converts bytecode into machine-level code. • If main is not public → Error: main method not found. • If main is not static → Error: main method is not static. Quick Summary: Class → Blueprint Object → Instance of class new → Creates object Constructor → Initializes object main() → Entry point of program String[] args → Command line arguments javac → Compiles source code java → Executes bytecode #java #OOPS #Coding
Java Object Creation: Classes, Objects, Constructors, and Main Method
More Relevant Posts
-
🔥 Understanding StringBuffer, StringBuilder & StringTokenizer in Java When working with strings in Java, choosing the right class can significantly impact performance and memory usage. Most beginners use String everywhere — but in real-world applications, mutable strings are often the better choice. Let’s break it down 👇 🔹 1️⃣ StringBuffer – Thread-Safe & Mutable StringBuffer is a mutable sequence of characters. ✔ Default capacity = 16 ✔ Automatically increases capacity when needed ✔ Synchronized (Thread-safe) ✔ Slower than StringBuilder (because of synchronization) 📌 Capacity formula when full: (current capacity × 2) + 2 Example: Java 👇 StringBuffer sb = new StringBuffer(); sb.append("JAVA"); sb.append("JAVASCRIPT"); System.out.println(sb.capacity()); 🔹 2️⃣ StringBuilder – Faster Alternative StringBuilder is almost the same as StringBuffer but: ✔ Not synchronized ✔ Faster ✔ Best for single-threaded applications Use this when performance matters and multiple threads are NOT modifying the same object. 🔹 3️⃣ StringTokenizer – Breaking Strings into Tokens StringTokenizer is used to split a string into smaller parts (tokens). Example: Java 👇 StringTokenizer st = new StringTokenizer("JAVA PYTHON SQL"); while(st.hasMoreTokens()){ System.out.println(st.nextToken()); } 🚀 Important Points to Remember ✔ String is immutable ✔ StringBuffer & StringBuilder are mutable ✔ StringBuffer is thread-safe ✔ StringBuilder is faster ✔ Capacity grows automatically ✔ Use trimToSize() to reduce unused memory ✔ StringTokenizer acts like a cursor to fetch tokens 💼 Best Real-Time Example 🔥 Example: Building Dynamic SQL Queries In enterprise applications: Instead of: Java 👇 String query = ""; query += "SELECT * FROM users "; query += "WHERE status = 'ACTIVE'". This creates multiple unnecessary string objects ❌ Better way: Java 👇 StringBuilder query = new StringBuilder(); query.append("SELECT * FROM users "); query.append("WHERE status = 'ACTIVE'"); ✔ More memory efficient ✔ Better performance ✔ Used in backend systems daily 🎯 When to Use What? Scenario Recommended Single-threaded app StringBuilder Multi-threaded app StringBuffer Simple fixed text String Token parsing StringTokenizer / split() 💡 Choosing the right string class improves performance, reduces memory overhead, and makes your application scalable. TAP Academy #Java #Programming #BackendDevelopment #StringBuilder #StringBuffer #SoftwareEngineering #Coding
To view or add a comment, sign in
-
-
🚀 Day 6/100 — Methods in Java 🔧 As programs grow bigger, repeating the same code again and again becomes messy. This is where methods help. A method is a reusable block of code that performs a specific task. Instead of rewriting logic multiple times, you write it once and call it whenever needed. This follows the DRY principle — Don't Repeat Yourself. 🔹 Basic Method Syntax returnType methodName(parameters){ // method body } Example: public static void greet(){ System.out.println("Hello Java!"); } Calling the method: greet(); Output: Hello Java! 🔹 Method with Parameters Parameters allow methods to work with different inputs. Example: public static void add(int a, int b){ int sum = a + b; System.out.println(sum); } add(5, 3); Output: 8 🔹 Method with Return Value Sometimes a method needs to return a result. Example: public static int square(int num){ return num * num; } int result = square(4); System.out.println(result); Output: 16 🔹 Method Overloading Java allows multiple methods with the same name but different parameters. This is called method overloading. Java automatically chooses the correct method based on the arguments. Example: public static int add(int a, int b){ return a + b; } public static int add(int a, int b, int c){ return a + b + c; } Usage: System.out.println(add(5,3)); // calls first method System.out.println(add(5,3,2)); // calls second method 🔴 Live Example — Max of 3 Numbers public static int max(int a, int b, int c){ if(a >= b && a >= c){ return a; } else if(b >= a && b >= c){ return b; } else{ return c; } } public static void main(String[] args){ int result = max(10, 25, 15); System.out.println("Maximum number is: " + result); } Output: Maximum number is: 25 🎯 Challenge: Write a method to find the maximum of 3 numbers and test it with different inputs. Drop your solution in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaMethods #ProgrammingJourney
To view or add a comment, sign in
-
-
Day 28: Exploring Strings in Java Today I practiced some important concepts related to Strings in Java and how they behave in memory. One of the key characteristics of Java Strings is that they are "immutable". This means once a String object is created, its value cannot be changed. Any operation like replace() or concat() creates a new String object instead of modifying the existing one. For scenarios where frequent modifications are required, using StringBuilder or StringBuffer is recommended because they are mutable. 🔹 Ways to create Strings in Java String str1 = "java"; // String literal String str2 = new String("java"); // Using new operator When Strings are created using literals, they are stored in the String Constant Pool (SCP) inside the heap memory. The SCP avoids duplicate objects to save memory. Because of this: String str1 = "java"; String str3 = "java"; System.out.println(str1 == str3); // true "==" returns true because both references point to the same object in the String Constant Pool. But when we create a String using the new operator: String str3 = new String("java"); System.out.println(str1 == str3); // false System.out.println(str1.equals(str3)); // true == compares memory addresses, while .equals() compares actual values. 🔹 Immutability Example String str7 = "Hello "; str7.concat("Everyone"); System.out.println(str7); // Output: Hello The String is not modified because Strings are immutable. 🔹 Mutable Alternative StringBuilder sb = new StringBuilder("Hello "); sb.append("Everyone"); System.out.println(sb); //Output: Hello Everyone StringBuilder and StringBuffer allow modification without creating multiple objects, making them better for frequent string manipulations in problem solving. 📌 Key Takeaways • Strings are immutable in Java • == compares references, .equals() compares values • String literals use the String Constant Pool • Use StringBuilder/StringBuffer when frequent modifications are required Learning these concepts helped me better understand how Java manages memory and string operations internally. #Java #Programming #JavaDeveloper #CodingJourney #SoftwareDevelopment #LearningInPublic Raviteja T Mohammed Abdul Rahman 10000 Coders
To view or add a comment, sign in
-
-
🚀 **Understanding Why We Create Objects in Java | JVM Memory Basics** While learning Java and OOP concepts, one important question arises: **Why do we create objects in Java?** To understand this, we need to look at how the **Java program execution process** works inside the JVM. 1️⃣ Compilation Phase A Java program is first compiled using the **Java Compiler (javac)**, which converts the `.java` file into a `.class` file containing **bytecode**. ``` Main.java → Main.class ``` This `.class` file is stored on the **hard disk**. --- 2️⃣ Class Loading When we run the program using the **Java Virtual Machine**, the **Java ClassLoader** loads the `.class` file into RAM. At this stage, the JVM loads: * Class metadata * Static variables * Static blocks * Method definitions ⚠️ **Important:** Non-static variables are **not created yet**. 3️⃣ Program Execution Starts The JVM searches for the entry point of the program: public static void main(String[] args) Execution begins from the **first line of the `main()` method**. 4️⃣ Static vs Non-Static Members **Static Members** * Loaded when the class is loaded. * Stored in the **method area**. * Accessible without creating an object. Example: ```java static int a = 10; ``` **Non-Static Members** * Created only when an object is created. * Stored in **Heap memory**. Example: ```java int x = 10; ``` --- ### 5️⃣ Why Do We Create Objects? Objects are created for two main reasons: ✔ To allocate memory for **non-static members** ✔ To access **non-static variables and methods** Example: ```java Main obj = new Main(); ``` --- ### 6️⃣ What Happens When We Use the `new` Operator? When the JVM encounters: ```java new Main(); ``` The following steps occur: 1️⃣ Memory is allocated in the **Heap** 2️⃣ Non-static variables are loaded into memory 3️⃣ Variables are initialized (default or assigned values) 4️⃣ Constructor is executed 5️⃣ The memory address of the object is returned The variable `obj` stores the **reference (address)** of the object. --- ### 7️⃣ Example Program ```java public class Main { int x = 10; public static void main(String[] args) { int y = 10; System.out.println(y); Main obj = new Main(); System.out.println(obj.x); } } ``` In this example: * `y` is stored in **Stack memory** * `x` is stored in **Heap memory** * `obj` is a **reference variable** pointing to the object --- ### 8️⃣ Garbage Collection Once the `main()` method finishes execution: * Local variables are removed from the stack * The reference to the object may be lost If no references point to the object anymore, the **Java Garbage Collector** automatically removes it from memory. This process is called **Garbage Collection**. --- #Java #OOP #JVM #JavaMemoryModel #Programming #SoftwareEngineering #BackendDevelopment
To view or add a comment, sign in
-
I revised one of the most important concepts in Java — String handling. At first glance, Strings look simple. But behind the scenes, Java manages them using: 🔹 Heap Memory 🔹 String Constant Pool (SCP) 🔹 Immutability concept Let’s break it down 👇 🧠 1️⃣ String Memory (Heap vs SCP) Java 👇 String s1 = "JAVA"; String s2 = "JAVA"; String s3 = new String("JAVA"); ✅ s1 and s2 point to the same object in String Constant Pool ❌ s3 creates a new object in Heap memory 👉 Important: == compares references (memory address) equals() compares values 🔍 2️⃣ String Comparison ✔ equals() Compares values (case-sensitive) Java 👇 s1.equals(s2); ✔ equalsIgnoreCase() Ignores uppercase/lowercase ✔ compareTo() Lexicographically compares two strings Returns 0 → Equal Negative → First string is smaller Positive → First string is greater Example: Java 👇 "SACHIN".compareTo("SAURAV"); 🔗 3️⃣ String Concatenation Java 👇 String s1 = "JAVA"; String s2 = "PYTHON"; String s3 = s1 + s2; String s4 = s1.concat(s2); ⚠ Important: Strings are immutable in Java. Every concatenation creates a new object in heap. 🛠 4️⃣ Important String Methods length() charAt() indexOf() substring() toLowerCase() toUpperCase() contains() startsWith() endsWith() split() toCharArray() 💡 Real-Time Example (User Login System) Imagine building a login system: Java 👇 String dbPassword = "Admin@123"; String userInput = "admin@123"; if (dbPassword.equals(userInput)) { System.out.println("Login Success"); } If we use == instead of equals() ❌ Login may fail even if values look same. 👉 This is why understanding String comparison is very important in real projects. 🎯 Key Takeaways ✔ Strings are immutable ✔ == checks reference, equals() checks value ✔ compareTo() is used for sorting ✔ Concatenation creates new objects ✔ SCP improves memory efficiency Mastering Strings helps in: Authentication systems Form validation Data processing APIs & backend development Competitive programming TAP Academy #Java #String #CoreJava #Programming #SoftwareDevelopment #CodingJourney #Learning
To view or add a comment, sign in
-
🚀 Day 24 – Java Concepts for Interviews Method Overriding | Final Keyword | Method Hiding 🔹 1️⃣ Class Terminology In Java inheritance: Parent class → Superclass / Base class Child class → Subclass / Derived class The relationship is called an “is-a” relationship and is created using the extends keyword. 🔹 2️⃣ Method Overriding – 4 Important Rules Method overriding means a child class inherits a method and changes its implementation. Always use @Override for better readability and compile-time checking. Rule 1 – Access Modifier The child method must have same or higher visibility. Visibility order: private → default → protected → public Example: If parent method is protected, child can use: ✔ protected ✔ public ❌ default ❌ private Rule 2 – Return Type Return type must normally be same as parent method. Rule 3 – Covariant Return Type (JDK 5+) Child method can return a subclass type. Example: class Animal {} class Lion extends Animal {} class Base { Animal display() { return new Animal(); } } class Derived extends Base { @Override Lion display() { return new Lion(); } // Valid } ⚠ Works only for objects, not primitives like int, double. Rule 4 – Parameters Parameters must be exactly the same: same number same type same order Only method body changes, not the signature. 🔹 3️⃣ Overriding vs Overloading (Interview Trap) If parent has: display() and child has: display(int a, int b, int c) This is NOT overriding ❌ This is method overloading ✔ Because parameters are different. Using @Override here will give a compile-time error. 🔹 4️⃣ Final Keyword in Java final can be used with variables, methods, and classes. Final Variable Becomes a constant. final float PI = 3.142f; PI = 3.14f; // Error Convention: UPPERCASE_SNAKE_CASE Example: MAX_VALUE, MIN_VALUE Final Method Can be inherited Cannot be overridden Used when behavior must not change in child classes. Final Class A final class cannot be extended. Example: final class Calculator {} class Child extends Calculator {} // Compilation error Examples in Java: String, StringBuilder, StringBuffer, wrapper classes like Integer. 🔹 5️⃣ Static Members and Inheritance Static Variables If child declares the same variable → Variable Hiding Static Methods Static methods cannot be overridden. If same method exists in child → Method Hiding Example: class Parent { static void display() { System.out.println("Parent"); } } class Child extends Parent { static void display() { System.out.println("Child"); // Method hiding } } Using @Override here → ❌ Compilation error #Java #JavaProgramming #OOP #MethodOverriding #MethodOverloading #FinalKeyword #JavaInterviewQuestions #CodingInterview #SoftwareEngineering #LearnJava #100DaysOfCode #Day24
To view or add a comment, sign in
-
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
To view or add a comment, sign in
-
𝗗𝗔𝗬 𝟯 – 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 + 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 𝗜𝗻 𝘁𝗵𝗲 𝗹𝗮𝘀𝘁 𝘁𝘄𝗼 𝗽𝗼𝘀𝘁𝘀 𝘄𝗲 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗼𝗼𝗱: • Why Java is Platform Independent • How JDK, JRE, and JVM work together to run a Java program Now it's time to move from 𝘁𝗵𝗲𝗼𝗿𝘆 → 𝗮𝗰𝘁𝘂𝗮𝗹 𝗰𝗼𝗱𝗲. 𝗟𝗲𝘁’𝘀 𝘄𝗿𝗶𝘁𝗲 𝗮 𝘀𝗶𝗺𝗽𝗹𝗲 𝗝𝗮𝘃𝗮 𝗽𝗿𝗼𝗴𝗿𝗮𝗺. ``` 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 { 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) { 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); } } ``` At first glance this may look confusing. But if we break it down, the structure becomes very simple. 𝗦𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗲 𝗼𝗳 𝗮 𝗝𝗮𝘃𝗮 𝗣𝗿𝗼𝗴𝗿𝗮𝗺 Every Java program generally contains: 1️⃣ 𝗖𝗹𝗮𝘀𝘀 𝗗𝗲𝗰𝗹𝗮𝗿𝗮𝘁𝗶𝗼𝗻 𝚙𝚞𝚋𝚕𝚒𝚌 𝚌𝚕𝚊𝚜𝚜 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍 In Java, everything starts with a class. The filename must match the class name. Example: 𝙷𝚎𝚕𝚕𝚘𝚆𝚘𝚛𝚕𝚍.𝚓𝚊𝚟𝚊 2️⃣ 𝗠𝗮𝗶𝗻 𝗠𝗲𝘁𝗵𝗼𝗱 𝚙𝚞𝚋𝚕𝚒𝚌 𝚜𝚝𝚊𝚝𝚒𝚌 𝚟𝚘𝚒𝚍 𝚖𝚊𝚒𝚗(𝚂𝚝𝚛𝚒𝚗𝚐[] 𝚊𝚛𝚐𝚜) This is the entry point of every Java program. When we run a program, the JVM starts execution from the 𝗺𝗮𝗶𝗻() 𝗺𝗲𝘁𝗵𝗼𝗱. 3️⃣ 𝗦𝘁𝗮𝘁𝗲𝗺𝗲𝗻𝘁𝘀 𝚂𝚢𝚜𝚝𝚎𝚖.𝚘𝚞𝚝.𝚙𝚛𝚒𝚗𝚝𝚕𝚗("𝙷𝚎𝚕𝚕𝚘 𝚆𝚘𝚛𝚕𝚍"); This statement simply prints output on the console. 𝗡𝗼𝘄 𝗹𝗲𝘁’𝘀 𝘂𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱 𝘀𝗼𝗺𝗲𝘁𝗵𝗶𝗻𝗴 𝘃𝗲𝗿𝘆 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝗶𝗻 𝗝𝗮𝘃𝗮. 𝗝𝗮𝘃𝗮 𝗧𝗼𝗸𝗲𝗻𝘀 Tokens are the smallest building blocks of a Java program. Java programs are basically made up of tokens. 𝗧𝗵𝗲𝗿𝗲 𝗮𝗿𝗲 𝗺𝗮𝗶𝗻𝗹𝘆 𝟱 𝘁𝘆𝗽𝗲𝘀: • 𝗞𝗲𝘆𝘄𝗼𝗿𝗱𝘀 → public, class, static, void • 𝗜𝗱𝗲𝗻𝘁𝗶𝗳𝗶𝗲𝗿𝘀 → names of variables, classes, methods • 𝗟𝗶𝘁𝗲𝗿𝗮𝗹𝘀 → actual values (10, "Hello", true) • 𝗦𝗲𝗽𝗮𝗿𝗮𝘁𝗼𝗿𝘀 → { } ( ) [ ] ; , • 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 → + - * / = == Example identifier rules: ✔ Cannot start with a number ✔ Cannot use Java keywords ✔ No spaces allowed ✔ Can use letters, numbers, _ and $ Once you understand structure + tokens, reading Java code becomes much easier. If you look at the Java program again, you’ll now notice: It is simply a combination of tokens working together. Once you understand tokens and structure, reading Java code becomes much easier. 𝗧𝗼𝗺𝗼𝗿𝗿𝗼𝘄 (𝗗𝗮𝘆 𝟰) 𝗪𝗲’𝗹𝗹 𝗴𝗼 𝗱𝗲𝗲𝗽𝗲𝗿 𝗶𝗻𝘁𝗼 𝗼𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗶𝗺𝗽𝗼𝗿𝘁𝗮𝗻𝘁 𝘁𝗼𝗽𝗶𝗰𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮: • Data Types • Variables • Primitive vs Non-Primitive types • Memory basics behind variables Because before writing real programs, understanding how Java stores data is critical. 𝗦𝗲𝗲 𝘆𝗼𝘂 𝗶𝗻 𝗗𝗮𝘆 𝟰. #Java #BackendDevelopment #Programming #LearnInPublic #Day3
To view or add a comment, sign in
-
📍One of the most powerful features in Java is Method Overloading — also known as Static Binding or Compile-Time Polymorphism. But what does it really mean? 👉 Method Overloading allows multiple methods in the same class with the same name but different parameters. That’s it. Same name. Different behavior. 💡 Simple Example Java 👇 class Calculator { void add(int a, int b) { System.out.println(a + b); } void add(double a, double b) { System.out.println(a + b); } void add(int a, int b, int c) { System.out.println(a + b + c); } } Same method name add() Different parameter list ✅ Java compiler decides which method to call during compile time. 🔥 Can We Overload main() Method? Yes, we can. Java 👇 public class Demo { public static void main(String[] args) { System.out.println("Original main"); main(10); main(); } public static void main() { System.out.println("Overloaded main without parameters"); } public static void main(int a) { System.out.println("Overloaded main with int"); } } But remember: 👉 JVM always starts execution from public static void main(String[] args) 👉Other main() methods must be called manually. 📌 Important Points (Very Important for Interviews) ✅ Method name must be same ✅ Parameters must be different (number or type) ❌ Return type alone cannot overload a method ✅ Happens at compile time ✅ Also called Static Binding ✅ Improves code readability ✅ Supports polymorphism 🏢 Best Real-Time Example 🛒 E-Commerce Payment System Imagine an online shopping application: Java 👇 processPayment(double amount) processPayment(double amount, String couponCode) processPayment(String upiId, double amount) Same method name: processPayment() Different input types → Different behavior ✔ Without coupon ✔ With coupon ✔ Using UPI This keeps the code clean and professional. 🎯 Why This Concept is Important? Because real-world applications don’t use different method names like: processPaymentWithCoupon() processPaymentWithoutCoupon() Instead, they use overloading to keep code clean and scalable. 💬 Final Thought Method Overloading is not just a concept. It is how real software handles flexibility without complexity. TAP Academy #Java #CoreJava #LearningJourney #MethodOverloading #Programming #SoftwareDevelopment #InternshipJourney 🚀
To view or add a comment, sign in
-
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
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