🚀 Day 3 of my Java journey — OOP concepts! (Part 1) Today I explored Object Oriented Programming — the heart of Java! 🫀 ⚙️ Method Overloading ✅Same Class, Same method name, different parameters ✅ Example: add(int a, int b) ,add(int a, int b,int c) and add(double a, double b) ✅ Decided at compile time ✅Socho ek calculator hai — add button ek hi hai lekin tum 2 number bhi jod sakte ho, 3 number bhi! Same naam, alag parameter! 🔁 Method Overriding ✅ Child class redefines parent class method ✅ Same name, same parameters — different behaviour ✅ Decided at runtime — this is polymorphism! ✅Method Overriding — Child apna kaam khud karta hai ✅(Socho Papa kehte hain "khana khao" — matlab roti khao. Lekin beta kehta hai "khana khao" — matlab pizza khao! Same baat, alag matlab! ) ✅child apne papa ka kaam badal deta hai 🔑 this keyword ✅ Refers to the current object inside a class ✅ Used to avoid confusion between class variables and method parameters ✅this — "Main khud hoon(Intense variable,method and constructor )" 👨👩👦 super keyword ✅ Used to call parent class methods or constructor ✅ super() calls parent constructor ✅ super.methodName() calls parent method ✅ super — "Mere papa hain(parent Class)" 🧬 Inheritance ✅ Child class inherits properties and methods from parent class ✅ Single inheritance — one parent, one child ✅ Multiple inheritance via interfaces (Java does not allow multiple class inheritance directly) 💉 Dependency Injection(DI) ✅ Instead of creating objects inside a class, we pass them from outside ✅ Makes code flexible, testable and clean ✅ Used heavily in Spring Boot (next goal!) Socho tumhara ek Car hai. Car ko Engine chahiye. ✅Bina DI: Car khud engine banati hai andar — agar engine badlani ho toh poori car todna padega! ✅DI ke saath: Engine bahar se car mein daali jaati hai — engine badlo, car wahi rehti hai! ✅Galat tarika — tightly coupled ✅cheez bahar se do, andar mat banao OOP is not finished yet — Day 4 will cover more! 🔥 Day 1 ✅ | Day 2 ✅ | Day 3 ✅ | Day 4 coming... If you are on a similar Java journey, connect with me! 🙏 #Java #JavaDeveloper #OOP #ObjectOrientedProgramming #Inheritance #Polymorphism #DependencyInjection #100DaysOfCode #BackendDevelopment #TechCareer
Java OOP Concepts: Day 3 - Method Overloading, Inheritance & DI
More Relevant Posts
-
Mastering Asynchronous Programming in Java with CompletableFuture Most backend systems slow down not because of bad logic, but because everything runs sequentially. Every API call, database query, or external request adds delay. So here’s a better approach: Why wait, when tasks can run independently? 👉What is CompletableFuture? CompletableFuture (Java 8) lets you: - Run tasks asynchronously - Chain operations cleanly - Handle failures without breaking flow The Key Idea java CompletableFuture.supplyAsync(() -> "Hello") .thenApply(s -> s + " World"); - thenApply() → transforms result - thenCompose() → chains async calls Running Tasks in Parallel java CompletableFuture.allOf(f1, f2, f3).join(); Multiple tasks. No blocking. Better performance. Handling Failures java future.handle((res, err) -> res != null ? res : "Fallback"); No crashes. Just controlled behavior. Final Thought Synchronous code waits. Asynchronous code scales. If you're building APIs or working with Spring Boot, understanding CompletableFuture is not optional anymore—it’s essential. #Java #SpringBoot #BackendDevelopment #AsyncProgramming #Multithreading
To view or add a comment, sign in
-
Day 39 of Learning Java: Downcasting & instanceof Explained Clearly 1. What is Downcasting? Downcasting is the process of converting a parent class reference → child class reference. It is the opposite of Upcasting. 👉 Key Points: Requires explicit casting Used to access child-specific methods Only works if the object is actually of the child class Example: class A {} class B extends A {} A ref = new B(); // Upcasting B obj = (B) ref; // Downcasting 💡 Here, ref actually holds a B object, so downcasting is safe. 2. When Downcasting Fails If the object is NOT of the target subclass → it throws: ClassCastException 📌 Example: A ref = new A(); B obj = (B) ref; // Runtime Error 👉 This is why we need a safety check! 3. instanceof Keyword (Safety Check ) The instanceof keyword is used to check whether an object belongs to a particular class before casting. 📌 Syntax: if (ref instanceof B) { B obj = (B) ref; } 💡 Prevents runtime errors and ensures safe downcasting. 4. Real-World Example class SoftwareEngineer { void meeting() { System.out.println("Attending meeting"); } } class Developer extends SoftwareEngineer { void coding() { System.out.println("Writing code"); } } class Tester extends SoftwareEngineer { void testing() { System.out.println("Testing application"); } } 📌 Manager Logic using instanceof: void review(SoftwareEngineer se) { if (se instanceof Developer) { Developer dev = (Developer) se; dev.coding(); } else if (se instanceof Tester) { Tester t = (Tester) se; t.testing(); } } 💡 This is a real use of polymorphism + safe downcasting 5. Key Rules to Remember ✔ Downcasting requires upcasting first ✔ Always use instanceof before downcasting ✔ Helps access child-specific behavior ✔ Wrong casting leads to runtime exceptions 💡 My Key Takeaways: Upcasting gives flexibility, Downcasting gives specificity instanceof is essential for writing safe and robust code This concept is widely used in real-world applications, frameworks, and APIs #Java #OOP #LearningInPublic #100DaysOfCode #Programming #Developers #JavaDeveloper #CodingJourney
To view or add a comment, sign in
-
-
my Java Journey... Today I went deeper than just theory. I actually wrote a program that talks to the user. And it felt like real coding for the first time. What I built today A program that: - Asks for your name - Asks for your city - Then greets you personally Simple? Yes. But to build this I had to understand 3 important concepts. Concept 1 — Scanner Class Java does not take user input automatically. You have to tell it to listen. That is what Scanner does. javaimport java.util.Scanner; Scanner sc = new Scanner(System.in); Think of Scanner like a microphone. You turn it on — now Java can hear the user. Concept 2 — nextLine() To actually read what the user types — javaString name = sc.nextLine(); nextLine() waits for the user to type something and press Enter. Then stores it in the variable. Concept 3 — String Concatenation ➕ Combining text and variables together in one line. javaSystem.out.println("Hello " + name + " from " + city); That + sign joins everything together. Output: Hello Raj from Mumbai The full program javapackage abstraction; import java.util.Scanner; public class demo3 { public static void main(String[] args) { System.out.println("main starts"); Scanner sc = new Scanner(System.in); System.out.println("enter your name"); String name = sc.nextLine(); System.out.println(name); System.out.println("enter your city"); String city = sc.nextLine(); System.out.println(city); System.out.println("Hello " + name + " from " + city); sc.close(); System.out.println("main ends"); } } Wait — sc.close(). Why? Always close your Scanner after use. It frees up memory. Like turning off the microphone when you are done talking. This is called good coding practice. And recruiters notice this. What this taught me beyond the code A program is not just logic. It is a conversation between the user and the machine. Your job as a developer or automation tester — Is to make that conversation smooth, clean and error free. 3 things recruiters look for even in beginner code: - Clean structure — proper indentation, readable code - Good practices — closing Scanner, meaningful variable names - Understanding flow — knowing WHY each line exists, not just copying it I am not just writing code. I am building habits that will make me hireable. #qa #corejava #job #manualtesting #hiringqa #automationtesting
To view or add a comment, sign in
-
-
Here’s🚀 Coding Interview Questions + Answers (Part 2) (Java 🧑💻 Python | Medium Level) If you can solve these, you're already ahead of 70% candidates 👇 --- 🔹 11. Second Largest Element Java: int first = Integer.MIN_VALUE, second = Integer.MIN_VALUE; for(int n : arr){ if(n > first){ second = first; first = n; } else if(n > second && n != first){ second = n; } } Python: arr = [1,5,3,9,7] print(sorted(set(arr))[-2]) --- 🔹 12. Remove Duplicates Java: Set<Integer> set = new LinkedHashSet<>(list); Python: list(set(arr)) --- 🔹 13. Missing Number (1–n) Java: int sum = n*(n+1)/2; int actual = Arrays.stream(arr).sum(); System.out.println(sum - actual); Python: n = 5 arr = [1,2,3,5] print(n*(n+1)//2 - sum(arr)) --- 🔹 14. Merge Sorted Arrays Java: int i=0,j=0; while(i<a.length && j<b.length){ if(a[i]<b[j]) System.out.print(a[i++]); else System.out.print(b[j++]); } Python: a=[1,3,5]; b=[2,4,6] print(sorted(a+b)) --- 🔹 15. Character Frequency Java: Map<Character,Integer> map = new HashMap<>(); for(char c: str.toCharArray()) map.put(c, map.getOrDefault(c,0)+1); Python: from collections import Counter print(Counter("test")) --- 🔹 16. Anagram Check Java: char[] a = s1.toCharArray(); char[] b = s2.toCharArray(); Arrays.sort(a); Arrays.sort(b); System.out.println(Arrays.equals(a,b)); Python: print(sorted(s1)==sorted(s2)) --- 🔹 17. Move Zeros to End Java: int j=0; for(int i=0;i<arr.length;i++) if(arr[i]!=0) arr[j++]=arr[i]; Python: arr = [0,1,0,3] res = [x for x in arr if x!=0] + [0]*arr.count(0) --- 🔹 18. First Non-Repeating Character Java: for(char c: str.toCharArray()) if(str.indexOf(c)==str.lastIndexOf(c)) System.out.println(c); Python: for c in s: if s.count(c)==1: print(c); break --- 🔹 19. Sort Without Inbuilt Java (Bubble Sort): for(int i=0;i<n;i++) for(int j=0;j<n-i-1;j++) if(arr[j]>arr[j+1]){ int t=arr[j]; arr[j]=arr[j+1]; arr[j+1]=t; } Python: for i in range(len(arr)): for j in range(len(arr)-i-1): if arr[j] > arr[j+1]: arr[j],arr[j+1] = arr[j+1],arr[j] --- 🔹 20. Common Elements Java: Set<Integer> set = new HashSet<>(); for(int n : arr1) set.add(n); for(int n : arr2) if(set.contains(n)) System.out.println(n); Python: print(set(a) & set(b)) --- 💡 Pro Tip: 👉 These are pattern-based questions 👉 Master them once → reuse in multiple interviews --- 🎯 Next: Part 3 (Advanced 🔥) Comment “PART 3” Follow Sri Harish Chintha for more information Watsup channel… https://lnkd.in/grR24xHU Instagram : https://lnkd.in/gdm-2PuD #Coding #Java #Python #InterviewPrep #Developers #LeetCode #SDE
To view or add a comment, sign in
-
Most Common Java OOPs Interview Questions (With Answers) 1. What is Object Oriented Programming (OOP)? OOP is a programming model that focuses on real-world objects. It organises code in classes and objects to achieve better modularity, code reusability, and scalability. OOP separates programs into reusable components, with each one representing an entity with its state (data) and behaviour (methods). 2. What are the Four Main Pillars of OOP? The four key principles of OOP are: Encapsulation-bundling the data with the methods that operate on that data into a single unit and restricting access to some components. Inheritance-allowing the class to inherit properties and behaviours from another class. Polymorphism-an ability whereby objects can interact in multiple forms via method overloading or overriding. Abstraction-hiding the internal functioning of an object and exposing only the necessary features. 3. What is a Class and What is an Object? A class is the blueprint for creating objects. It defines how the object's structure and behaviour will be. An object is the instance of a class-an entity that holds the state and behavior defined by class. 4. What is Encapsulation? Encapsulation means keeping the internal state of an object hidden and allowing controlled access through methods. This helps safeguard the data and reduces the complexity of the system by hiding unnecessary details. It enhances the maintainability of code and makes it easier to debug. 5. What is Inheritance? It implies that it is possible for a class to inherit the fields and methods of another class. The inheriting class is known as the "subclass" or "child class," and the class from which the inheritance is made is the "superclass" or "parent class." Inheritance increases code reusability and encapsulates the hierarchical classification concept. 6. What is Polymorphism? It means in Latin, "many forms." In Java, it allows one interface to be used for a general class of actions; most commonly forms of polymorphism are both: Compile-time polymorphism - it is accomplished with method overloading (the same name through many parameters). Runtime polymorphism is achieved through method overriding (subclass specifies a particular definition of a method already defined in its superclass). 7. Abstraction Abstraction is hiding the working and internal details in showing only the essential information. It helps in reducing the complexity of programming, thereby increasing its efficiency. 8. What Is the Difference Between an Abstract Class and an Interface? An abstract class is one that is only partially implemented. It may contain a mix of method declarations (without bodies) and concrete methods (with bodies). Thus, it embraces inheritance and can own constructors and member variables. Also, you can attend the master class on the interviews that are held every weekend at Softronix! Join the league today!
To view or add a comment, sign in
-
-
🚀 From Writing Code to Understanding Memory — My Java Learning (Post #3) 🧠💻 In my previous posts, I shared what I learned about Access Modifiers and Non-Access Modifiers. This time, I wanted to go a bit deeper into something I’ve been using without really thinking about it: 👉 Where do variables and objects actually live in Java? Here’s my current understanding 👇 🧠 Java doesn’t directly use memory — it runs inside the JVM, which manages how data is stored in RAM. The three main areas I focused on: 🔹 Stack Memory (Execution Area) ⚡ Used for method calls and local variables. public class Main { public static void main(String[] args) { int x = 10; int y = 20; } } Here, x and y are stored in the Stack. ✔️ Fast ✔️ Temporary ✔️ Automatically cleared after execution 🔹 Heap Memory (Object Storage) 📦 Used for storing objects and instance variables. class Student { int age; } public class Main { public static void main(String[] args) { Student s1 = new Student(); s1.age = 25; } } What clicked for me here: 👉 s1 is just a reference (stored in Stack) 👉 The actual object is stored in Heap 🔹 Static Variables (Class-Level Memory) 🏫 This part confused me at first 👀 class Student { static String schoolName = "ABC School"; } ✔️ Not stored in Stack ✔️ Not inside objects in Heap 👉 Stored in a special area (Method Area) 👉 Only ONE copy exists and is shared across all objects 💡 Real-world example that helped me: Think of a university system 🎓 • Students → Objects (Heap) • Student ID → Reference (Stack) • University Name → Static variable (shared across all students) 📌 Key takeaways: ✔️ Stack = execution (temporary data) ✔️ Heap = object storage ✔️ Static = class-level shared data ✔️ JVM manages memory (physically stored in RAM) This topic really changed how I look at Java code. Earlier, I was just writing programs — now I’m starting to understand what happens behind the scenes 🔍 I’m currently focusing on strengthening my Core Java fundamentals, and I’d really appreciate any feedback, corrections, or guidance from experienced developers here 🙌 🚀 Next, I’m planning to explore Garbage Collection and how JVM manages memory efficiently. #JavaDeveloper #BackendEngineering #JavaInternals #SoftwareDevelopment #TechLearning #CodeNewbie
To view or add a comment, sign in
-
-
🚀 Java OOP Practice | Abstract Classes & Polymorphism (Medium–Hard) Today I worked on an interesting problem inspired by real-world systems like AI chat platforms (think Gemini / Snapchat-style interactions). 💡 The goal was to design a Smart Query System using: Abstract Classes Method Overriding Runtime Polymorphism Input Validation 🧠 Problem Overview (Medium–Hard Level) We designed an abstract class AIQuery that represents a generic user query with: Username Prompt Timestamp Then we created two specialized query types: 🔹 NormalQuery Standard processing Fixed response time 🔹 PriorityQuery Faster response Priority-based behavior Dynamic response time ⚙️ Key Concepts Applied ✔ Abstraction → Common structure defined in base class ✔ Inheritance → Subclasses extend functionality ✔ Polymorphism → Same method behaves differently ✔ Validation → Real-world input handling 📌 What I Learned How abstract classes help in designing scalable systems How runtime polymorphism works in real applications How small design decisions improve flexibility and readability 💬 Example Insight Same method call: AIQuery q = new PriorityQuery(...); q.generateResponse(); 👉 Different output based on object type — this is real polymorphism! 🔥 Difficulty Level: Medium–Hard 📖 Practicing these problems is helping me strengthen my Core Java + OOP fundamentals, which are essential for backend development and interviews. 💭 Have you tried similar OOP design problems? Let’s discuss in comments 👇 #Java #OOP #Abstraction #Polymorphism #CodingPractice #BackendDevelopment #LearningJourney
To view or add a comment, sign in
-
-
🚀 Learning Core Java – Understanding Aggregation and Composition Today I explored an important OOP concept in Java — Aggregation and Composition. Both Aggregation and Composition are called Associative Relationships because they represent the “Has-A” relationship between classes. This means one class contains or uses objects of another class instead of inheriting from it. 🔹 What is Has-A Relationship? In this relationship: ✔ There is one Primary Class ✔ There can be one or more Secondary Classes The way secondary class objects participate inside the primary class defines the type of relationship. 🔹 Aggregation Aggregation means: 👉 The secondary class can exist independently, even without the primary class. This represents a weak association. Example: 📱 Mobile has a Charger Even if the mobile phone is removed, the charger can still exist independently. So this is Aggregation. 🔹 Composition Composition means: 👉 The secondary class cannot exist independently without the primary class. This represents a strong association. Example: 📱 Mobile has an Operating System Without the mobile phone, the operating system has no separate meaningful existence in that context. So this is Composition. 🔎 Simple Difference ✔ Aggregation → Independent existence possible ✔ Composition → Dependent existence only 💡 Key Insight Aggregation and Composition help us model real-world relationships more accurately and build better object-oriented designs. 👉 Both are Has-A relationships 👉 Aggregation = Weak association 👉 Composition = Strong association Understanding these concepts is essential for writing clean, scalable, and maintainable Java applications. Excited to keep strengthening my OOP fundamentals! 🚀 #CoreJava #Aggregation #Composition #ObjectOrientedProgramming #HasARelationship #JavaDeveloper #ProgrammingFundamentals #LearningJourney
To view or add a comment, sign in
-
-
🚀 Ever wondered what really happens when your Java code runs? 🤔 Let’s peel back the layers and uncover the deterministic, and highly optimized execution flow of Java code—because understanding this isn’t just academic, it’s transformational for writing efficient systems. 🔍 1. Compilation: From Human Logic to Bytecode When you write Java code, the javac compiler doesn’t convert it directly into machine code. Instead, it produces platform-independent bytecode. 👉 This is where Java’s "Write Once, Run Anywhere" promise begins—clean, structured, and universally interpretable instructions. ⚙️ 2. Class Loading: Dynamic & Lazy The ClassLoader subsystem kicks in at runtime, loading classes on demand—not all at once. This involves three precise phases: Loading → Bytecode enters memory Linking → Verification, preparation, resolution Initialization → Static variables & blocks executed 💡 This lazy loading mechanism is what makes Java incredibly memory-efficient and modular. 🧠 3. Bytecode Verification: Security First Before execution, the JVM performs rigorous bytecode verification. It ensures: No illegal memory access Proper type usage Stack integrity 👉 This step is Java’s silent guardian, preventing malicious or unstable code execution. 🔄 4. Execution Engine: Interpretation vs JIT Compilation Here’s where things get fascinating. The JVM uses: Interpreter → Executes bytecode line-by-line (fast startup) JIT Compiler (Just-In-Time) → Converts hot code paths into native machine code 🔥 The result? A hybrid execution model that balances startup speed with runtime performance. 🧩 5. Runtime Data Areas: Structured Memory Management Java doesn’t just run code—it orchestrates memory intelligently: Heap → Objects & dynamic allocation Stack → Method calls & local variables Method Area → Class metadata PC Register & Native Stack → Execution tracking 💡 This segmentation ensures predictable performance and scalability. ♻️ 6. Garbage Collection: Autonomous Memory Reclamation Java eliminates manual memory management with sophisticated garbage collectors. From Mark-and-Sweep to G1 and ZGC, the JVM continuously: Identifies unused objects Reclaims memory Optimizes allocation 👉 This results in robust, leak-resistant applications with minimal developer intervention. 💥 Why This Matters Understanding this flow isn’t just theoretical—it empowers you to: ✔ Write high-performance code ✔ Diagnose memory and latency issues ✔ Leverage JVM optimizations effectively 🔥 Java isn’t just a language—it’s a meticulously engineered execution ecosystem. So next time you run a .java file, ask yourself: 👉 Am I just coding… or truly understanding the machine beneath? #Java #JVM #Programming #SoftwareEngineering #Performance #Developers #TechInsights
To view or add a comment, sign in
-
-
Java- Automatic Type Promotion of Primitives I am trying to explore and explain the concept of automatic type promotion of primitives using a simple code in java using two byte values: class TestAutomatictypepromotion{ public static void main(String[] ar){ byte a=10; byte b=20; int sum=a+b; System.out.println(sum); }} Perfect! Let me prove the byte → int promotion step by step through actual bytecode analysis.We have the real bytecode. Now let me build the full visual explanation. javac your souce code javap -c TestAutomatictypepromotion.class (we will get the vyte code) The 3 smoking-gun proofs from the actual bytecode Here is the raw javap -c output from your exact code, with the proof highlighted: 0: bipush 10 ← pushes 10 as INT (not byte) 2: istore_1 ← "i" = integer store (no bstore exists!) 3: bipush 20 ← pushes 20 as INT 5: istore_2 ← integer store 6: iload_1 ← "i" = integer load (no bload exists!) 7: iload_2 ← integer load 8: iadd ← "i" = INTEGER add ← THE KEY PROOF 9: istore_3 Proof 1 — iload, not bload: When a and b are loaded from local variable slots, the opcode is iload_1 and iload_2. The i prefix means integer. There is literally no bload instruction in the entire JVM specification. Proof 2 — iadd, not badd: The addition uses iadd. There is no badd opcode. The JVM arithmetic instruction set only has iadd, ladd, fadd, dadd (int, long, float, double). Bytes have no dedicated add — they must become ints first. Proof 3 — println:(I)V: The method descriptor in constant pool entry #13 is println:(I)V. The I is the JVM type descriptor for int. So even println receives an int, not a byte. Why does Java do this? The JVM's operand stack and local variable slots work natively in 32-bit units. Byte, short, char, and boolean values are all widened to int the moment they enter the stack — this is called numeric promotion. It's defined in the JLS §5.6.1 (Unary Numeric Promotion) and §5.6.2 (Binary Numeric Promotion). The JVM spec simply has no byte-level arithmetic opcodes — they were intentionally omitted to keep the instruction set small and the stack 32-bit aligned. Want me to show what happens when the result overflows a byte, or demonstrate why byte c = a + b causes a compile-time error without an explicit cast: Let me cover both — byte overflow AND the compile-time error proof through actual bytecode! byte data type has a range: -128 to 127 Assume we declare the variables llike : byte b=100.byte b=100; then try to add both (byte values) like byte c=a+b; The result :200 is not in byte range. So overflow happens. Compiler will not allow. The compiled and interpreted way in Java is the base for such standard code. Most developers fear the JVM. Java developers understand it. Codeest Software Factory Anirudh Mangore Sandip Magdum Mehvish Fansopkar Mitali Dere Sakshi Randive Shruti Chavan NILESH GHAVATE Shaikh Abdulkhadir Java Recruiting Group,OpenJDK
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
https://www.youtube.com/watch?v=q6z_UCBM5Ek&t=3720s