🚀 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
Java Method Overloading, Command Line Args & Encapsulation
More Relevant Posts
-
🚨 Java Myth Buster: “Finally block always executes” — Really? 🤔 Most developers confidently say: 👉 “Yes, finally always runs!” ❌ Let’s break that myth with a real example 👇 --- 💻 Code Example: public class Test { public static void main(String[] args) { try { System.out.println("Inside try"); System.exit(1); } finally { System.out.println("Inside finally"); } } } --- 📌 Output: Inside try 😳 Wait… where is the "finally" block? --- 💡 Explanation (Simple & Clear): When "System.exit(1)" is executed: - 🚫 JVM shuts down immediately - 🚫 No further code executes - 🚫 "finally" block is completely skipped --- 🔢 Understanding Exit Codes: - "System.exit(0)" → Normal termination ✅ - "System.exit(1)" → Abnormal termination ❌ 👉 But important point: Both will skip the "finally" block! --- ⚠️ So when does finally NOT execute? ✔️ When JVM is forcefully terminated ✔️ Using "System.exit()" ✔️ JVM crash / system failure ✔️ Infinite loop (control never reaches finally) --- 🧠 Interview Takeaway: 👉 “Finally block executes in almost all cases, except when JVM terminates abruptly like with System.exit().” --- 🔥 This is one of the most asked tricky Java interview questions! 💬 Did you know this before? #Java #JavaDeveloper #CodingInterview #Programming #TechTips #Developers #InterviewQuestions #JavaBasics
To view or add a comment, sign in
-
🚨 Java Interview Question: 👉 What is the difference between Checked and Unchecked Exceptions? Understanding this clearly shows your strong command over Java fundamentals 🔥 💡 What is an Exception? An exception is an event that disrupts the normal flow of a program during runtime. In Java, exceptions are handled using try-catch blocks. ✅ 1️⃣ Checked Exception 👉 Checked at compile-time. 👉 Must be handled using try-catch or throws. 👉 Occurs due to external factors (file, database, network). 💻 Example: FileReader file = new FileReader("test.txt"); This throws IOException. If you don’t handle it → compilation error ❌ 🧠 Real-Life Example: Imagine you are traveling by train 🚆 You must carry a valid ticket. If you don’t, you won’t even be allowed to board. 👉 Compiler forces you to handle it. ❌ 2️⃣ Unchecked Exception 👉 Occurs at runtime. 👉 Not mandatory to handle at compile-time. 👉 Usually caused by programming mistakes. 💻 Example: int a = 10 / 0; This throws ArithmeticException. Compiler allows it. But program crashes at runtime. 🧠 Real-Life Example: Driving without checking fuel ⛽ Car stops in middle of road. It’s your mistake, not system’s. 🎯 Strong Interview One-Liner: 👉 Checked exceptions are compile-time exceptions that must be handled, whereas unchecked exceptions occur at runtime due to programming errors. #Java #ExceptionHandling #JavaDeveloper #InterviewPreparation #BackendDevelopment #Programming
To view or add a comment, sign in
-
Understanding the Java "main()" Method — "public static void main(String[] args)" Every Java program starts execution from the main() method. When you run a Java program, the JVM (Java Virtual Machine) looks for this method as the entry point. If a program does not contain a valid "main()" method, the JVM will not start execution. The commonly used syntax is: public static void main(String[] args) Each word in this declaration has a specific purpose: • public → Access modifier that allows the JVM to call the method from outside the class. If it is not public, the JVM cannot access it. • static → Allows the method to be called without creating an object of the class. The JVM can directly invoke the method when the program starts. • void → Specifies that the method does not return any value. Once the main method finishes execution, the Java program terminates. • main → The method name recognized by the JVM as the starting point of the program. Changing this name prevents the program from running. • String[] args → An array that stores command-line arguments passed when running the program. Example: class Example { public static void main(String[] args) { System.out.println("Hello, Java!"); } } Java also allows equivalent forms like: public static void main(String args[]) public static void main(String... args) All of these work because the parameter is still treated as a String array. Key Takeaway: The "main()" method acts as the entry point of a Java application, allowing the JVM to begin executing the program. #Java #JavaProgramming #CoreJava #JVM #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
-
🚀 𝐅𝐚𝐢𝐥-𝐅𝐚𝐬𝐭 𝐯𝐬 𝐅𝐚𝐢𝐥-𝐒𝐚𝐟𝐞 𝐈𝐭𝐞𝐫𝐚𝐭𝐨𝐫𝐬 𝐢𝐧 𝐉𝐚𝐯𝐚 If you're preparing for Java interviews, this is an important concept to understand. When iterating over collections in Java, two types of iterator behaviors exist. 🔴 Fail-Fast Iterator If the collection is modified while iterating, it immediately throws a Concurrent Modification Exception. Example collections: • ArrayList • HashMap • HashSet Example: List<String> list = new ArrayList<>(); list.add("Java"); list.add("Spring"); for (String s : list) { list.add("Docker"); // throws ConcurrentModificationException } These iterators detect structural modifications during iteration and fail immediately. 🟢 Fail-Safe Iterator Fail-Safe iterators work on a copy of the collection, so modifications during iteration do not throw exceptions. Example collections: • ConcurrentHashMap • CopyOnWriteArrayList Example: CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<>(); list.add("Java"); for (String s : list) { list.add("Spring"); // no exception } 📌 Key Difference Fail-Fast → Throws exception if collection is modified during iteration Fail-Safe → Works on a copy, so no exception occurs Understanding this concept is important when working with multithreading and concurrent collections. Follow for more Java internals explained simply. #Java #JavaDeveloper #Programming #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
Top 10 Most Asked Java Interview Questions 1. What is the difference between HashMap and ConcurrentHashMap? HashMap is not thread-safe and can cause data inconsistency in concurrent environments. ConcurrentHashMap uses fine-grained locking and CAS operations to allow safe concurrent reads and writes. 2. What is the difference between final, finally, and finalize? final → keyword used for variables, methods, and classes to restrict modification. finally → block used in exception handling to execute cleanup code. finalize → method used by GC before object collection (deprecated and rarely used). 3. What happens when hashCode() and equals() are not implemented properly? If equal objects produce different hashCodes, collections like HashMap behave incorrectly. This leads to duplicate keys and degraded lookup performance. 4. What is the difference between ArrayList and LinkedList? ArrayList uses a dynamic array and provides fast random access. LinkedList uses a doubly linked structure and is efficient for insertions and deletions. 5. What is the difference between Thread and Runnable? Thread is a class that represents a thread of execution. Runnable is an interface used to define the task that a thread executes. Using Runnable improves flexibility because it separates the task from thread management. 6. What causes memory leaks in Java? Common causes include: - Static collections holding references - Unclosed resources - ThreadLocal misuse - Listeners not removed Heap dumps and tools like MAT help identify leaks. 7. What is the difference between synchronized and Lock? synchronized is simpler and managed by JVM. Lock provides advanced features like tryLock(), fairness policies, and interruptible locks. 8. What is the difference between checked and unchecked exceptions? Checked exceptions must be handled at compile time. Unchecked exceptions occur at runtime and usually indicate programming errors. 9. What is the difference between fail-fast and fail-safe iterators? Fail-fast iterators throw ConcurrentModificationException if the collection is modified during iteration. Fail-safe iterators operate on a copy of the collection. 10. What is the JVM and what are its main components? JVM is the runtime that executes Java bytecode. Main components include: - Heap - Stack - Method Area - Garbage Collector - JIT Compiler #Java #JavaInterview #BackendEngineering #SpringBoot #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Day 5/100 — Loops in Java 🔁 Loops allow a program to repeat a block of code multiple times without writing the same code again and again. They are one of the most important concepts in programming. Java mainly provides three types of loops: 🔹 1. for Loop Used when the number of iterations is known. Syntax: for(initialization; condition; update){ // code to run } Example: for(int i = 1; i <= 5; i++){ System.out.println(i); } Output: 1 2 3 4 5 Here: i = 1 → start value i <= 5 → condition check i++ → increment after each iteration 🔹 2. while Loop Used when the number of iterations is unknown and depends on a condition. Example: int i = 1; while(i <= 5){ System.out.println(i); i++; } The loop runs as long as the condition is true. 🔹 3. do-while Loop Runs the block at least once, even if the condition is false. Example: int i = 1; do{ System.out.println(i); i++; }while(i <= 5); Difference: while → condition checked before execution do-while → condition checked after execution 🔹 Nested Loops A loop inside another loop is called a nested loop. Commonly used for pattern printing problems. Example: Triangle pattern for(int i = 1; i <= 5; i++){ for(int j = 1; j <= i; j++){ System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🔴 Live Example — Inverted Triangle Pattern int rows = 5; for(int i = rows; i >= 1; i--){ for(int j = 1; j <= i; j++){ System.out.print("* "); } System.out.println(); } Output: * * * * * * * * * * * * * * * 🎯 Challenge: Write a program to print an inverted triangle pattern using nested loops. Drop your code in the comments 👇 #Java #CoreJava #100DaysOfCode #JavaLoops #ProgrammingJourney
To view or add a comment, sign in
-
-
🚨 One Java Interview Question Many Developers Still Get Wrong equals() vs hashCode() Most developers know these methods exist in Java, but many don’t fully understand why they must work together. Let’s break it down 👇 🔹 equals() • Used to compare the logical equality of two objects • By default, it compares memory references, not values • We override it when we want to compare object content 🔹 hashCode() • Returns an integer hash value for the object • Used internally by HashMap, HashSet, and HashTable • Helps Java quickly locate objects in hash buckets ⚠️ Important Rule If two objects are equal using equals(), they must return the same hashCode(). Otherwise, collections like HashSet or HashMap may behave incorrectly. 💡 Example Issue You add two logically equal objects into a HashSet, but because their hashCode values are different, both get stored. Result? Duplicate objects inside a Set. ✅ Takeaway Whenever you override equals(), always override hashCode() as well. This small rule can prevent subtle and hard-to-debug issues in real applications. 💬 Have you ever faced a bug related to equals() and hashCode()? #Java #SoftwareDevelopment #Programming #JavaDeveloper #CodingInterview #BackendDevelopment
To view or add a comment, sign in
-
📌Exception Handling in Java ⚠️ ✅Exception Handling is a mechanism to handle unexpected situations that occur while a program is running. When an exception occurs, it disrupts the normal flow of the program. Common examples: • Accessing an invalid index in an array→ ArrayIndexOutOfBoundsException • Dividing a number by zero→ ArithmeticException Java provides thousands of exception classes to handle different runtime problems. 📌 Types of Exceptions in Java 1️⃣ Built-in Exceptions These are predefined exceptions provided by Java. ✅Checked Exceptions -Checked by the compiler at compile time Must be handled using try-catch or declared using throws Examples: IOException SQLException ClassNotFoundException ✅Unchecked Exceptions -Not checked by the compiler at compile time Occur mainly due to programming errors Examples: ArithmeticException NullPointerException ClassCastException 2️⃣ User-Defined (Custom) Exceptions Java also allows developers to create their own exceptions. This is useful when we want to represent specific business logic errors. Basic rules to create a custom exception: 1️⃣ Extend the Exception class 2️⃣ Create a constructor with a message 3️⃣ Throw the exception using throw 4️⃣ Handle it using try-catch 📌 Finally Block ✅The finally block always executes after the try-catch block, whether an exception occurs or not. It is commonly used for cleanup tasks, such as: Closing database connections Closing files Releasing resources 📌 Try-With-Resources ✅Sometimes developers forget to close resources manually. To solve this problem, Java introduced Try-With-Resources. It automatically closes resources once the block finishes execution. This makes resource management safer and cleaner. 📌 Important Keywords ✅throw : Used to explicitly create and throw an exception object. ✅throws: Used in the method signature to indicate that a method may throw an exception. Grateful to my mentor Suresh Bishnoi Sir for explaining Java concepts with such clarity and practical depth . If this post added value, feel free to connect and share it with someone learning Java. #Java #ExceptionHandling #CoreJava #JavaDeveloper #BackendDevelopment #SoftwareEngineering #InterviewPreparation #JavaProgramming #CleanCode
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