🚀 Java Gotcha: Can we override static methods? 🤔 👉 Short answer: NO ❌ But there’s a twist… class Parent { static void show() { System.out.println("Parent"); } } class Child extends Parent { static void show() { System.out.println("Child"); } } 👉 Now check this: Parent obj = new Child(); obj.show(); // ? ❓ Output? 👉 Parent ✅ 💡 Why? - static methods belong to class, not object - They are resolved at compile time - This is called method hiding, NOT overriding --- 🔥 Key Takeaway: ✔ static methods → cannot be overridden ✔ They can only be hidden 💬 Interview Tip: If polymorphism is involved → static methods won’t behave like instance methods #Java #Programming #Coding #JavaTips #OOP #InterviewPreparation
Java Gotcha: Static Methods Cannot Be Overridden
More Relevant Posts
-
☕ Java Interview Question 📌 When is ArrayStoreException thrown? ArrayStoreException occurs when you try to store an incompatible data type in an array. 🔹 Why it happens: ✔ Arrays in Java are type-safe at runtime ✔ Storing a different object type than the array’s actual type triggers this exception 🔹 Example Scenario: ✔ Assigning an Integer into an array declared as Double[] ✔ The compiler may allow it (due to polymorphism), but it fails at runtime 🔹 Key Insight: ✔ Happens during runtime, not compile time ✔ Common in cases involving inheritance and object arrays 💡 In Short: ArrayStoreException ensures type safety by preventing invalid object assignments in arrays 🚀 👉For Java Course Details Visit : https://lnkd.in/gwBnvJPR . #Java #CoreJava #ExceptionHandling #Programming #InterviewPreparation #TechLearning #AshokIT
To view or add a comment, sign in
-
-
🔥 Day 20: Thread Lifecycle in Java Understanding thread lifecycle is key to mastering multithreading 👇 🔹 What is Thread Lifecycle? 👉 It defines the different states a thread goes through during its execution. 🔹 Thread States in Java 1️⃣ NEW 👉 Thread is created but not started Thread t = new Thread(); 2️⃣ RUNNABLE 👉 Thread is ready or running (after start()) 3️⃣ BLOCKED 👉 Waiting to acquire a lock (synchronization) 4️⃣ WAITING 👉 Waiting indefinitely for another thread (e.g., wait()) 5️⃣ TIMED_WAITING 👉 Waiting for a specific time (e.g., sleep(1000)) 6️⃣ TERMINATED 👉 Thread execution is completed 🔹 Simple Example class MyThread extends Thread { public void run() { System.out.println("Thread Running..."); } } public class Main { public static void main(String[] args) { MyThread t = new MyThread(); System.out.println(t.getState()); // NEW t.start(); System.out.println(t.getState()); // RUNNABLE } } 🔹 Lifecycle Flow NEW → RUNNABLE → (BLOCKED / WAITING / TIMED_WAITING) → TERMINATED 🔹 Key Points ✔ start() → moves thread to RUNNABLE ✔ sleep() → TIMED_WAITING ✔ wait() → WAITING ✔ Lock issues → BLOCKED 💡 Pro Tip: Thread state may change quickly — don’t rely on exact timing in real systems. 📌 Final Thought: "Threads have a life cycle — understanding it helps you control execution." #Java #Multithreading #ThreadLifecycle #Programming #JavaDeveloper #Coding #InterviewPrep #Day20
To view or add a comment, sign in
-
-
Today’s learning and revising ✨ Dived deep into one of the most fundamental concepts in Java — Variables. 🔹 What is a Variable? A variable is a named memory location used to store data that can change during program execution. 🔹 How JVM allocates memory? JVM divides memory mainly into Stack 🧱 and Heap 🌐 Stack → Stores method calls & local variables Heap → Stores objects & instance variables Memory is efficiently managed using stack frames and garbage collection 🔹 Types of Variables in Java: 1️⃣ Local Variable Declared inside methods Stored in stack memory No default values 2️⃣ Instance Variable Declared inside class but outside methods Stored in heap memory Each object has its own copy 3️⃣ Static Variable (Class Variable) Shared among all objects Allocated once in method area 💡 Key takeaway: Understanding variables is not just syntax — it’s about how memory works behind the scenes and how efficiently we use it. #Java #FullStackDevelopment #LearningJourney #JVM #Programming
To view or add a comment, sign in
-
-
#DSAREVISION #Series LECTURE: 14 Java String foundation BY: Love Babbar Link: https://lnkd.in/gGTvBJXb ♦️What is a String in Java? A String is a sequence of characters. ♦️Why Strings Are Important; Strings are used in: 🔹 user input 🔹search systems 🔹 text processing 🔹validation (email, password) 🔹logs & messages 🔹problem solving ♦️How to Create Strings; Method 1: Using String Literal (Most Common) String str = "Hello"; Method 2: Using new Keyword String str = new String("Hello"); ♦️ Strings are Immutable : Once a string is created, it cannot be changed. ♦️Taking String Input: Using Scanner ♦️Common String Methods length() size charAt(i) character equals() compare toLowerCase() convert toUpperCase() convert concat() join #Dsa #LearntoCode
To view or add a comment, sign in
-
-
🔢 Divisible Sum Pairs Problem | Java Solution 💻 Today I solved an interesting problem based on arrays and modular arithmetic! 📌 Problem: Given an array and a number k, count pairs (i, j) such that: 👉 i < j 👉 (arr[i] + arr[j]) % k == 0 ⚡ Approach: Instead of brute force O(n²), I used an optimized O(n) approach using remainder frequency. ✔️ Key Idea: Store frequency of (element % k) For each element, find its complement remainder Count valid pairs efficiently 💡 This improves performance significantly for large inputs! 🧠 Concepts Used: Arrays Modulo Arithmetic Hashing Technique 👨💻 Language: Java #Java #CodingPractice #DataStructures #Algorithms
To view or add a comment, sign in
-
-
🔥 Serialization & Deserialization in Java A very important concept for saving and transferring objects in Java 👇 🔹 1. Serialization 👉 Converting an object into a byte stream so it can be saved to a file or sent over a network. ✔ Used for file storage ✔ Used in networking ✔ Implemented using "Serializable" interface 🔹 2. Deserialization 👉 Converting the byte stream back into an object. ✔ Restores object state ✔ Used when reading from file/network 💻 Simple Example: // Serialization ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("data.txt")); oos.writeObject(s1); oos.close(); // Deserialization ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.txt")); Student s2 = (Student) ois.readObject(); ois.close(); 📌 Key Points: ✔ Class must implement "Serializable" ✔ Use "ObjectOutputStream" → write object ✔ Use "ObjectInputStream" → read object ✔ "transient" keyword → skip fields 📦 Real-Life Analogy: Serialization = Packing an object into a box Deserialization = Unpacking it back 💡 Pro Tip: Always define "serialVersionUID" to avoid version mismatch issues 📌 Final Thought: "Serialization turns objects into data. Deserialization brings them back to life." #Java #Serialization #Deserialization #JavaDeveloper #Programming #Coding #InterviewPrep #BackendDevelopment
To view or add a comment, sign in
-
-
Leetcode Practice - 15. 3Sum The problem is solved using JAVA. Given an integer array nums, return all the triplets [nums[i], nums[j], nums[k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0. Notice that the solution set must not contain duplicate triplets. Example 1: Input: nums = [-1,0,1,2,-1,-4] Output: [[-1,-1,2],[-1,0,1]] Explanation: nums[0] + nums[1] + nums[2] = (-1) + 0 + 1 = 0. nums[1] + nums[2] + nums[4] = 0 + 1 + (-1) = 0. nums[0] + nums[3] + nums[4] = (-1) + 2 + (-1) = 0. The distinct triplets are [-1,0,1] and [-1,-1,2]. Notice that the order of the output and the order of the triplets does not matter. Example 2: Input: nums = [0,1,1] Output: [] Explanation: The only possible triplet does not sum up to 0. Example 3: Input: nums = [0,0,0] Output: [[0,0,0]] Explanation: The only possible triplet sums up to 0. Constraints: 3 <= nums.length <= 3000 -105 <= nums[i] <= 105 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
Leetcode Practice - 16. 3Sum Closest The problem is solved using JAVA Given an integer array nums of length n and an integer target, find three integers at distinct indices in nums such that the sum is closest to target. Return the sum of the three integers. You may assume that each input would have exactly one solution. Example 1: Input: nums = [-1,2,1,-4], target = 1 Output: 2 Explanation: The sum that is closest to the target is 2. (-1 + 2 + 1 = 2). Example 2: Input: nums = [0,0,0], target = 1 Output: 0 Explanation: The sum that is closest to the target is 0. (0 + 0 + 0 = 0). Constraints: 3 <= nums.length <= 500 -1000 <= nums[i] <= 1000 -104 <= target <= 104 #LeetCode #Java #CodingPractice #ProblemSolving #DSA #Array #DeveloperJourney #TechLearning
To view or add a comment, sign in
-
-
Mastering Java & DSA Through LeetCode Day 34 Today I solved a Medium-level Tree problem that strengthened my understanding of Prefix Sum + DFS — a powerful pattern used in many interview questions. LeetCode Problem: 437. Path Sum III Problem Summary: Given a binary tree and a target sum, we need to find the number of paths where the sum of node values equals the target. The path must go downward (parent → child), but it doesn’t need to start from the root. Key Insight: Instead of checking all possible paths (which is inefficient), we use: Prefix Sum HashMap to store frequencies DFS traversal This helps reduce time complexity from O(n²) → O(n) ⚡ Approach: Maintain a running sum while traversing the tree Check if (currentSum - target) exists in the map Use backtracking to maintain correct state What I Learned: How prefix sum works in trees (not just arrays!) Optimizing brute-force solutions Importance of hashmap in reducing complexity Consistency Update: Day 34 of solving DSA problems daily 💪 Small steps every day = big results over time #LeetCode #Java #DSA #CodingJourney #100DaysOfCode #SoftwareEngineering #PlacementPreparation #CodingInterview
To view or add a comment, sign in
-
-
Leetcode Practice - 8. String to Integer (atoi) The problem is solved using JAVA. Implement the myAtoi(string s) function, which converts a string to a 32-bit signed integer. The algorithm for myAtoi(string s) is as follows: ✔ Whitespace: Ignore any leading whitespace (" "). ✔ Signedness: Determine the sign by checking if the next character is '-' or '+', assuming positivity if neither present. ✔ Conversion: Read the integer by skipping leading zeros until a non-digit character is encountered or the end of the string is reached. If no digits were read, then the result is 0. ✔ Rounding: If the integer is out of the 32-bit signed integer range [-231, 231 - 1], then round the integer to remain in the range. Specifically, integers less than -231 should be rounded to -231, and integers greater than 231 - 1 should be rounded to 231 - 1. Return the integer as the final result. Example 1: Input: s = "42" Output: 42 Explanation: The underlined characters are what is read in and the caret is the current reader position. Step 1: "42" (no characters read because there is no leading whitespace) ^ Step 2: "42" (no characters read because there is neither a '-' nor '+') ^ Step 3: "42" ("42" is read in) #LeetCode #Java #StringHandling #CodingPractice #ProblemSolving #DSA #DeveloperJourney #TechLearning
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