#60DaysOfJava 📚 Day 17 Static Keyword (Java) 📌Static Keyword 🔹 Static is used to define class level members 🔹 It can be used with variables, methods, blocks, and nested classes 📊 Static Variable: 🔸 Shared among all objects of the class 🔸 Belongs to the class, not instances 🔸 Memory is allocated when the class is loaded 🔸 Stored in method area (Metaspace in modern JVM) 💡 Example: static String country = "India"; ⚙️ Static Method: 🔹 Can be called without creating an object 🔹 Belongs to the class 🔹 Used for utility/helper methods 🔹 Cannot access non-static members directly 💡 Example: static void displayIndiaPopulation() { System.out.println("billion"); } 🚀 Static Block: 🔸 Executes once when the class is loaded 🔸 Runs before object creation and constructors 🔸 Used to initialize static variables 🔸 Used to load configuration / register drivers 🔸 Used for one time setup logic 💡 Example: static String country; static { country = "USA"; } Nested class and static nested class we will see upcoming post 🤵 Follow Hariprasath V for daily more helpful resources. ♻ Repost Others also learn and grow together 👍 Hit if this was helpful. ✅ Save it future use. ================================================ #60DaysOfJavaWithHariprasathv6 #Java #JavaBasics #Programming #Coding #Developers #LearningJava #HighLevelDesign #SystemDesign #DSAChallenge #60DaysOfDSA #ProblemSolving #CodingJourney #Consistency #LearnByDoing #DataStructures #Algorithms #InterviewPrep #KeepCoding #Productivity #Focus #DreamBig #Java #SystemDesign #DataStructures #Algorithms #JavaDeveloper #DSA #CodingInterview #TechInterview #SystemDesignInterview #BackendDevelopment #SoftwareEngineering #JavaInterview #LeetCode #InterviewPrep #DataStructureAndAlgorithms #DesignPatterns #LowLevelDesign #Multithreading #SOLIDPrinciples #RESTAPI #BackendEngineer #CodeInterview #interviewtips #interviewexperience #Java #Programming #CoreJava #Learning #Developers #OOP #Java #Programming #Coding #Developers #JavaBasics
Java Static Keyword: Class Level Members and Variables
More Relevant Posts
-
Today I Learned: Queue vs Deque in Java As part of strengthening my Java Collections knowledge, I explored the difference between Queue and Deque — two powerful data structures used heavily in real-world applications and coding interviews. 🔹 Queue (FIFO – First In First Out) A Queue processes elements in the same order they arrive. 💡 Common uses: • Task scheduling • BFS algorithms • Message/Request processing systems Key methods I learned: add(), offer(), remove(), poll(), peek(), element() 👉 Best when order of processing matters and operations happen at one end. 🔹 Deque (Double Ended Queue – FIFO + LIFO) Deque is more flexible — it works as both Queue and Stack. 💡 Common uses: • Sliding window problems • Undo/Redo features • LRU Cache implementation • Stack operations using push() & pop() Key methods I learned: addFirst(), addLast(), removeFirst(), removeLast(), push(), pop() 👉 Perfect when we need operations from both ends. ⭐ Key Takeaway Queue = Simple & Order-based Deque = Flexible & Interview favorite #Java #Collections #Learning #SoftwareDevelopment #TodayILearned #collection #interface #Java #Programming #OOP #Encapsulation #Coding #Developer #SoftwareEngineering #Learning #Tech #JavaDeveloper #Java #OOP #Inheritance #Programming #Coding #JavaDeveloper #Learning #InterviewPrep #Java #JavaProgramming #JavaDeveloper #SoftwareDevelopment #Programming #Coding #BackendDevelopment #TechLearning #Developers #LearnToCode #ProgrammingCommunity #100DaysOfCode #CodeNewbie #TechCareer #SoftwareEngineer
To view or add a comment, sign in
-
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream #Java #Streams #Backend #SpringBoot #Developers #CleanCode
To view or add a comment, sign in
-
-
𝗝𝗮𝘃𝗮 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽: 𝗜𝗻𝘁𝗲𝗴𝗲𝗿 𝗖𝗮𝗰𝗵𝗶𝗻𝗴 & 𝗪𝗿𝗮𝗽𝗽𝗲𝗿 𝗚𝗼𝘁𝗰𝗵𝗮𝘀 𝗘𝘅𝗽𝗹𝗮𝗶𝗻𝗲𝗱! Consider this simple code: class Main { public static void main(String[] args) { Integer a = 128; Integer b = 128; System.out.println(a == b); // ? System.out.println(a.equals(b)); // ? } } 🔍 Output: false true 🤔 Why does this happen? Java internally caches Integer objects in the range -128 to 127. ✅ Within range → same object → == is true ❌ Outside range → new objects → == is false 👉 == compares references (memory address) 👉 .equals() compares actual values 🔥 What about other wrapper classes? ✔ Cached Wrappers: Integer → -128 to 127 Byte → all values cached Short → -128 to 127 Long → -128 to 127 Character → 0 to 127 Boolean → only true & false (always cached) 👉 Example: Integer x = 100; Integer y = 100; System.out.println(x == y); // true ✅ ❗ NOT Cached: Float Double 👉 Example: Float f1 = 10.0f; Float f2 = 10.0f; System.out.println(f1 == f2); // false ❌ Double d1 = 10.0; Double d2 = 10.0; System.out.println(d1 == d2); // false ❌ 💥 Why no caching for Float/Double? Extremely large range of values Precision & representation complexity Not memory-efficient to cache 📌 Golden Rule: 👉 Never use == for wrapper comparison 👉 Always use .equals() or unbox to primitive 🚀 Pro Tip: You can extend Integer cache using JVM option: -XX:AutoBoxCacheMax=<value> 🎯 Interview Insight: This is a classic trap to test: Java memory concepts Autoboxing & unboxing Object vs primitive understanding 💡 Bonus Tip: Be careful with null values when unboxing: Integer i = null; int j = i; // Throws NullPointerException ⚠️ #Java #Programming #InterviewPrep #JavaTips #Coding #Developers #TechCareers
To view or add a comment, sign in
-
🔥 Streams vs Loops in Java Short answer: Loops = control Streams = readability + functional style ⚙️ What are they? ➿ Loops Traditional way to iterate collections using for, while. 🎏 Streams (Java 8+) Functional approach to process data declaratively. 🚀 Why use Streams? 1. Less boilerplate code 2. Better readability 3. Easy chaining (map, filter, reduce) 4. Parallel processing support 🆚 Comparison Loops 1. Imperative (how to do) 2. More control 3. Verbose 4. Harder to parallelize Streams 1. Declarative (what to do) 2. Cleaner code 3. Easy transformations 4. Parallel-ready (parallelStream()) 💻 Example 👉 Problem: Get even numbers and square them Using Loop List<Integer> result = new ArrayList<>(); for (int num : nums) { if (num % 2 == 0) { result.add(num * num); } } Using Stream List<Integer> result = nums.stream() .filter(n -> n % 2 == 0) .map(n -> n * n) .toList(); ⚡ Flow (Streams) Collection → Open stream → Intermediate operations → Terminal operation → Use the result 🧠 Rule of Thumb Simple iteration / performance critical → Loop Data transformation / readability → Stream 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #Streams #Backend #CodingInterview #SpringBoot #Developers #InterviewPrep #CleanCode
To view or add a comment, sign in
-
-
💡 Can 2 + 1 = 4 in Java? Yes — and that should scare you At first glance, this sounds like a joke. But under the hood of the JVM, it’s a powerful reminder: 👉 Abstractions can be bent… if you understand them deeply enough. Java caches `Integer` objects in the range **-128 to 127**. This is done via an internal class called `IntegerCache`. Now here’s where things get interesting — using **Reflection**, you can modify that cache. Yes, you read that right. You can literally change what `2` means inside the JVM. ```java Class<?> cache = Class.forName("java.lang.Integer$IntegerCache"); Field field = cache.getDeclaredField("cache"); field.setAccessible(true); Integer[] array = (Integer[]) field.get(cache); // Make 2 behave like 3 array[130] = array[131]; System.out.println(2 + 1); // 4 ``` 🚨 After this: * `2` becomes `3` * `2 + 2` becomes `6` * Your JVM’s "reality" is now corrupted --- ### 🧠 What this actually teaches: ✔ Integer caching & autoboxing internals ✔ Reflection can break encapsulation ✔ “Immutable” doesn’t always mean “untouchable” ✔ JVM is powerful — but also dangerous in the wrong hands --- ### 🎯 Real Engineering Insight This is NOT about hacking math. This is about understanding: > *How deeply you understand the platform you work on.* At scale, such knowledge helps in: * Debugging impossible production bugs * Understanding memory behavior * Designing safe abstractions --- ### ⚠️ Final Thought Just because you *can* break the JVM… doesn’t mean you *should*. But if you *understand how* — you're no longer just a developer. You're thinking like a systems engineer. --- #Java #JVM #Reflection #SystemDesign #BackendEngineering #Performance #EngineeringMindset
To view or add a comment, sign in
-
#Design a basic URL Shortener service in Java Try Self than check #Solution 1. Functional Requirements: 2. Convert a long URL → short URL 3. Convert a short URL → original long URL 4. Same long URL should always return the same short URL 5. Short URL should be unique and collision-free 6. Handle up to 1 million URLs efficiently Input: encode("https://lnkd.in/geHb6Qua") Output: "http://mahfooz.com/abc123" decode("http://mahfooz.com/abc123") Output: "https://lnkd.in/geHb6Qua" # Constraints 1. Time Complexity: O(1) for encode & decode 2. Space Complexity: Optimize for large data 3. Avoid collisions 4. No external DB (in-memory only) Theory Questions (Must Answer) 1. Why did you choose HashMap? Explain internal working of HashMap What is average & worst-case complexity? 2. How will you avoid collisions? What if two URLs generate same short code? 3. How will you scale this system? If millions of users hit your backend How to move from in-memory → distributed system? 4. Thread Safety Is your solution thread-safe? If not, how will you fix it? 5. Backend Concept If implemented in Spring Boot, how will APIs look? https://lnkd.in/grX_mVes #Java #JavaDeveloper #BackendDeveloper #SoftwareEngineer #CodingInterview #DSA #Programming #Tech #Developers #InterviewPreparation #JavaBackend
To view or add a comment, sign in
-
-
Debugging a microservice with no errors and no logs can be frustrating. I explored this scenario and shared a structured approach to finding the root cause—from thread dumps to DB checks and timeouts. Sharing it here 👇 Would love to hear your approach. #Microservices #Debugging #BackendDevelopment #Java #SystemDesign
To view or add a comment, sign in
-
🚀 Fork/Join Framework (Java) The Fork/Join framework is designed for parallelizing recursive tasks. It uses a work-stealing algorithm to efficiently distribute tasks among available threads. The framework consists of the `ForkJoinPool` and `RecursiveTask` (for tasks that return a result) or `RecursiveAction` (for tasks that don't return a result) classes. Fork/Join is particularly well-suited for divide-and-conquer algorithms, such as sorting and searching large datasets, where tasks can be recursively broken down into smaller subtasks. #Java #JavaDev #OOP #Backend #professional #career #development
To view or add a comment, sign in
-
-
🔥 Day 9: HashMap Internal Working (Java) One of the most important concepts for interviews — let’s break it down simply 👇 🔹 What is HashMap? A HashMap in Java stores data in key-value pairs for fast access. 🔹 How HashMap Works Internally? 👉 Step-by-step: 1️⃣ Hashing Key → converted into a hashcode using hashCode() 2️⃣ Index Calculation Index = hashcode % array size 3️⃣ Storage (Bucket) Data stored in an array (called buckets) 4️⃣ Collision Handling If multiple keys map to same index: ✔ Uses LinkedList (Java 7) ✔ Uses Tree (Red-Black Tree) when entries > 8 (Java 8) 🔹 Simple Example import java.util.HashMap; public class Main { public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); map.put(1, "Java"); map.put(2, "Python"); map.put(3, "C++"); System.out.println(map.get(2)); // Python } } 🔹 Collision Example map.put(10, "A"); map.put(20, "B"); // may go to same bucket 👉 Both stored in same bucket → handled internally 🔹 Key Points ✔ Default size = 16 ✔ Load factor = 0.75 ✔ Resizes when threshold exceeded ✔ Not thread-safe ❌ 🔹 Real-Life Analogy 📦 Think of HashMap like: Apartment building (array) Each flat = bucket People with same flat number = collision 💡 Pro Tip: Good hashCode() + equals() = Better performance 🚀 📌 Final Thought: "HashMap is fast because it uses hashing — not searching." #Java #HashMap #DataStructures #Programming #JavaDeveloper #InterviewPrep #Tech #Learning #Day9
To view or add a comment, sign in
-
-
🚀 Array vs Collection in Java – What’s the Difference? Understanding the difference between Arrays and Collections is essential for writing efficient and scalable Java code. 🔹 Array ✔ Fixed size (defined at creation) ✔ Stores elements of the same data type ✔ Faster due to direct index-based access ✔ Less memory overhead ✔ Simple and straightforward 👉 Best when size is known and performance is critical 🔹 Collection (Java Collection Framework) ✔ Dynamic size (can grow or shrink) ✔ Stores objects (works with wrapper classes) ✔ Rich features like sorting, searching, and manipulation ✔ Slightly more memory usage ✔ More flexible and powerful 👉 Best when size is unknown and flexibility is needed 💡 Key Insight: Array is a basic data structure, while Collection is a powerful framework built on top of data structures. 📌 When to Use What? 🔸 Use Array → When you need speed and fixed size 🔸 Use Collection → When you need flexibility and advanced operations 🔥 Final Thought: Choosing the right data structure can significantly impact performance and code quality. #Java #CoreJava #Collections #DataStructures #Programming #Developers #Coding #Tech #LearnJava #logics #Tricky
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
Most Repeated Java Interview Question 💡 Are you able to overload / override a static method? ✔️ You can overload a static method ❌ You cannot override a static method We will see detailed explanation when we will explore overloading and overriding concept