Hello Java Developers, 🚀 Day 10 – Java Revision Series Today’s topic dives into nested classes in Java and clarifies a common source of confusion. ❓ Question What is the difference between a static nested class and a non-static (inner) class in Java? ✅ Answer Java allows classes to be defined inside another class. These nested classes are mainly of two types: Static Nested Class Non-Static Nested Class (Inner Class) The key difference lies in their relationship with the outer class instance. 🔹 Static Nested Class A static nested class is associated with the outer class itself, not with an object of the outer class. class Outer { static class StaticNested { void display() { System.out.println("Static nested class"); } } } Characteristics: Does not require an instance of the outer class Can access only static members of the outer class Behaves like a regular top-level class (just namespaced) Usage: Outer.StaticNested obj = new Outer.StaticNested(); ✅ Better memory efficiency ✅ Cleaner design when no outer instance is needed 🔹 Non-Static Nested Class (Inner Class) A non-static nested class is tightly bound to an instance of the outer class. class Outer { class Inner { void display() { System.out.println("Inner class"); } } } Characteristics: Requires an outer class object Can access both static and non-static members of the outer class Holds an implicit reference to the outer object Usage: Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); ⚠️ Higher memory overhead due to outer reference #Java #CoreJava #NestedClasses #StaticKeyword #OOP #JavaDeveloper #LearningInPublic #InterviewPreparation
Java Nested Classes Explained: Static vs Non-Static
More Relevant Posts
-
Day 4 of 10 – Core Java Recap: Looping Statements & Comments 🌟 Continuing my 10-day Java revision journey 🚀 Today I revised Looping Concepts and Comments in Java. 🔁 1️⃣ Looping Statements in Java Looping statements are used to execute a block of code repeatedly based on a condition. 📌 Types of loops: ✔ for loop Used when the number of iterations is known. Syntax: for(initialization; condition; updation) { // statements } ✔ while loop Checks condition first, then executes. Syntax: while(condition) { // statements } ✔ do-while loop Executes at least once, then checks condition. Syntax: do { // statements } while(condition); ✔ for-each loop (Enhanced for loop) Used to iterate over arrays and collections. Syntax: for(dataType variable : arrayName) { // statements } 🔹 Nested Loops A loop inside another loop Commonly used for patterns and matrix problems ⛔ break and continue ✔ break → Terminates the loop completely ✔ continue → Skips current iteration and moves to next iteration 📝 2️⃣ Comments in Java Comments are used to provide extra information or explanation in the code. They are not executed by the compiler. 📌 Types of Comments: ✔ Single-line comment // This is a single-line comment ✔ Multi-line comment /* This is a multi-line comment */ ✔ Documentation Comment (Javadoc) /** Documentation comment */ Used to generate documentation Applied at class level, method level Helps describe package, class, variables, and methods 📌 Common Documentation Tags: @author @version @param @return @since 💡 Key Learnings Today: Understood how loops control program flow Learned the difference between for, while, and do-while Practiced nested loops Understood the importance of proper code documentation Building strong fundamentals step by step 💻🔥 #Java #CoreJava #Programming #JavaDeveloper #CodingJourney #Learning
To view or add a comment, sign in
-
Java Fundamentals Series – Day 5 Garbage Collection in Java : In Java, developers do not need to manually free memory. JVM automatically manages memory using Garbage Collection (GC). The Garbage Collector is an Mechanism were default implemented inside JVM which is Invoke automatically In java there has a method gC() which is present inside the System Class this gC() method is a static method so there is no need for object to invoke this method so we can able to access this particular method by the class name *** System.gC() ***. By help of this method we just provide the request to JVM to call the ** Garbage Collector ** but we cannot assure that it may or may not be call the GC . It is totally depends on JVM here we just provide request. What is Garbage Collection? Garbage Collection is the process of automatically removing unused objects from Heap memory. Why GC is Important? 1 Prevents memory leaks 2 Frees unused memory 3 Improves application performance How GC Works? 1 JVM identifies objects that are no longer referenced 2 These objects become eligible for garbage collection 3 GC reclaims the memory occupied by them 4 It removes the memory for anonymous. object Method : void finalize(): Incase we needed to do some set of work before GC get Called in that particular time we can use this finalize () this method is defined as protected for example - closing the file this like operation.we can able to provide inside this finalize() method #Java #GarbageCollection #JVM #BackendDeveloper #Placements
To view or add a comment, sign in
-
Java Collection Framework – ArrayList The Java Collection Framework (JCF) is a unified architecture that provides a set of interfaces, implementations and algorithms to store, manipulate and process a group of objects efficiently. In simple terms, it standardizes how collections such as lists, sets and queues are represented and accessed in Java. The core hierarchy starts from the Collection interface and is mainly divided into: List, Set and Queue. (Note: Map is part of the framework but does not extend the Collection interface.) ArrayList is a resizable array implementation of the List interface. ArrayList – Properties • Implements List interface • Uses a resizable (dynamic) array internally • Allows duplicate elements • Maintains insertion order • Allows random access using index • Allows null values • Not synchronized (not thread-safe by default) Commonly Used ArrayList Methods • add(E e) – adds an element to the list • add(int index, E e) – inserts element at a specific position • get(int index) – retrieves element at a given index • set(int index, E e) – replaces element at a given index • remove(int index) – removes element at a given index • remove(Object o) – removes a specific object • size() – returns the number of elements • isEmpty() – checks whether the list is empty • contains(Object o) – checks if an element exists • indexOf(Object o) – returns the first occurrence index • clear() – removes all elements Ways to Access (Iterate) an ArrayList • Using Iterator • Using ListIterator • Using for loop (index-based loop) • Using enhanced for-each loop Short example An ArrayList can be traversed either by moving through its indices, or by using iterator-based mechanisms depending on whether forward-only or bidirectional traversal is required. #Java #CoreJava #CollectionsFramework #ArrayList #JavaLearning #JavaDeveloper #InterviewPreparation Sharath R, Bibek Singh, Santhosh HG, Harshit T, Ravi Magadum, Vamsi yadav
To view or add a comment, sign in
-
-
☕ Java Generics – Upper Bounded Wildcards Explained In Java Generics, the question mark (?) represents a wildcard, meaning an unknown type. Sometimes, we need to restrict the type of objects that can be passed to a method — especially when working with numbers or specific class hierarchies. That’s where Upper Bounded Wildcards come into play. 🔹 What is an Upper Bounded Wildcard? To restrict a wildcard to a specific type or its subclasses, we use: <? extends ClassName> This means: 👉 Accept ClassName or any of its subclasses. For example, if a method should only work with numeric types, we restrict it to Number and its subclasses like Integer, Double, etc. As explained in the document (Page 1), the syntax uses ? followed by the extends keyword to define the upper bound. 🔹 Practical Example From the example shown (Page 2), a method calculates the sum of elements in a list: public static double sum(List<? extends Number> numberlist) { double sum = 0.0; for (Number n : numberlist) sum += n.doubleValue(); return sum; } 📌 Why ? extends Number? ✔ Ensures only numeric types are allowed ✔ Accepts List<Integer> ✔ Accepts List<Double> ✔ Maintains type safety 🔹 Usage in Main Method List<Integer> integerList = Arrays.asList(1, 2, 3); System.out.println("sum = " + sum(integerList)); List<Double> doubleList = Arrays.asList(1.2, 2.3, 3.5); System.out.println("sum = " + sum(doubleList)); 🔹 Output (Page 3) sum = 6.0 sum = 7.0 This demonstrates how the same method works seamlessly with different numeric types. 💡 Upper bounded wildcards improve flexibility while maintaining compile-time type safety. They are essential for writing reusable and robust generic methods in Java. #Java #Generics #UpperBoundedWildcards #JavaProgramming #OOP #FullStackJava #Developers #AshokIT
To view or add a comment, sign in
-
🚀 100 Days of Java Tips – Day 10 Topic: Modern Switch Expressions (Java 14+) If you’re still using the traditional switch statement with multiple break statements, it’s time to upgrade 😄 Java 14 introduced switch expressions to make your code cleaner, safer, and more readable. In older versions, switch was mainly used as a statement. That meant you had to manually assign values and remember to add break every time. Missing a break could silently introduce bugs. Example – Old Style Switch: String result; switch (day) { case "MONDAY": result = "Start of week"; break; case "FRIDAY": result = "Almost weekend"; break; default: result = "Mid week"; } Now let’s see the modern version. Example – New Switch Expression: String result = switch (day) { case "MONDAY" -> "Start of week"; case "FRIDAY" -> "Almost weekend"; default -> "Mid week"; }; What changed? • No need for break • Cleaner arrow syntax • Directly returns a value • Less chance of fall-through bugs You can also group cases: String type = switch (day) { case "SATURDAY", "SUNDAY" -> "Weekend"; default -> "Weekday"; }; Why this matters? Modern switch makes your intent clear. It reduces boilerplate code. It improves maintainability. Java is evolving to become more expressive and developer-friendly. If you are using Java 14 or above, start using switch expressions in new code. Write code that is not just working, but elegant. #Java #100DaysOfCode #JavaTips #Developers #ModernJava
To view or add a comment, sign in
-
-
📘 Core Java | Constructors While revising Core Java, I strengthened my understanding of Constructors, a fundamental concept in Object-Oriented Programming. 👉 What is a Constructor? A constructor is a special member of a class used to initialize objects. It runs automatically when an object of a class is created. 🔹 Constructor vs Method (Key Differences) 1️⃣ Purpose A constructor is used to initialize the object’s state, whereas a method is used to define the behavior of the object. 2️⃣ Name Rule A constructor must have the same name as the class, whereas a method can have any valid name. 3️⃣ Return Type A constructor does not have any return type(not even `void`), whereas a method must have a return type (including `void`). 4️⃣ How They Are Called A constructor is called automatically when an object is created, whereas a method is called explicitly using an object. 5️⃣ Execution Frequency A constructor runs once per object creation, whereas a method runs every time it is invoked. 🧠 In short: A constructor prepares the object for use, while a method makes the object perform actions. 💡 Constructor Interview Questions ✅ 1. Can a constructor be private? Yes, a constructor can be private. It is mainly used in the Singleton design pattern to restrict object creation from outside the class. ✅ 2. Can we call one constructor from another constructor? Yes, we can use `this()` to call another constructor in the same class. This concept is known as constructor chaining. 🔹 Constructor Overloading Constructor overloading means having multiple constructors in the same class with different parameters. This allows objects to be created in different ways. Example 👇 class Employee { String name; int age; double salary; // 1️⃣ Default Constructor Employee() { name = "Not Provided"; age = 0; salary = 0.0; } // 2️⃣ Constructor with 1 parameter Employee(String name) { this.name = name; age = 0; salary = 0.0; } // 3️⃣ Constructor with 2 parameters Employee(String name, int age) { this.name = name; this.age = age; salary = 0.0; } Constructor overloading improves flexibility while creating objects. Understanding constructors is crucial for writing clean, object-oriented, and interview-ready Java code. Feedback is welcome 😊 #CoreJava #JavaOOP #JavaDeveloper #PlacementPreparation
To view or add a comment, sign in
-
Hello Java Developers, 🚀 Day 11 – Java Revision Series Today’s topic is one of the core pillars of JVM internals and frequently discussed in senior-level Java interviews. ❓ Question What is a ClassLoader in Java and how does it work internally? ✅ Answer A ClassLoader is a part of the JVM responsible for: 👉 Loading Java .class files into memory at runtime Java follows a dynamic class loading mechanism, meaning classes are loaded only when they are needed, not all at once. 🔹 Types of ClassLoaders in Java Java uses a hierarchical ClassLoader architecture: 1️⃣ Bootstrap ClassLoader Loads core Java classes Examples: java.lang.* java.util.* Written in native code (C/C++) Parent of all class loaders 2️⃣ Extension (Platform) ClassLoader Loads classes from: $JAVA_HOME/lib/ext Used for Java extension libraries 3️⃣ Application (System) ClassLoader Loads classes from: Application classpath This is the default class loader for user-defined classes 🔹 ClassLoader Delegation Model (Parent-First) Java follows the Parent Delegation Model: Application ClassLoader checks with Extension ClassLoader Extension checks with Bootstrap ClassLoader If parent cannot load the class, control returns downward ➡️ This prevents: Core Java classes from being overridden Security issues Duplicate class definitions 🔹 How a Class Is Loaded (Internally) A class goes through three main phases: 1️⃣ Loading .class file is read into memory 2️⃣ Linking Includes: Verification (bytecode safety) Preparation (static memory allocation) Resolution (symbolic references → direct references) #Java #CoreJava #NestedClasses #StaticKeyword #OOP #JavaDeveloper #LearningInPublic #InterviewPreparation
To view or add a comment, sign in
-
-
Core Java Fundamentals :Key Traits of Metaspace Permanent Generation in Java PermGen (Permanent Generation) was a memory area in the Java Virtual Machine (JVM) used before Java 8 to store class metadata, interned strings, and static variables. It was part of the JVM heap space and had a fixed size, making it difficult to manage memory efficiently. Fixed and Hard-to-Tune Size in PermGen PermGen had a fixed maximum size, which was often too small for applications with many classes. Correct Tuning was Tricky Even though it was configurable using -XX:MaxPermSize, tuning it correctly was difficult. PermGen was not dynamically expanding Unlike Metaspace, on the other hand, dynamically expands using native memory, eliminating manual tuning issues. OutOfMemoryError If class metadata exceeded 256MB, the application would crash with OutOfMemoryError: PermGen space. Key Features of Metaspace Stores Class Metadata It holds information about classes, methods, and their runtime representations (like method bytecode and field details). Unlike PermGen, it does not store Java objects (which reside in the heap). Uses Native Memory Unlike PermGen, which had a fixed maximum size, Metaspace dynamically expands using native memory(outside the heap), reducing Out of memory errors. Automatic Growth & GC Handling The JVM automatically manages Metaspace size based on the application’s needs. Class metadata is garbage collected when classes are no longer needed (such as when an application uses dynamic class loading). Configurable Maximum Size -XX:MaxMetaspaceSize=256m // Limits Metaspace to 256MB -XX:MetaspaceSize=128m // Initial size before expanding ☕ If this helped you — support my work: 👉 Buy Me a Coffee -https://lnkd.in/ebXVUJn2 #JVMInternals #JavaPerformance #MemoryManagement #SpringBoot #Microservices #SystemDesign
To view or add a comment, sign in
-
-
📌 Callable vs Runnable in Java — Returning Results from Threads In multithreading, not all tasks are the same. Sometimes we need a thread to return a result. This is where Callable comes in. 1️⃣ Runnable • Introduced in Java 1.0 • Does NOT return a result • Cannot throw checked exceptions Example: Runnable task = () -> { System.out.println("Running task"); }; 2️⃣ Callable • Introduced in Java 5 • Returns a result • Can throw checked exceptions Example: Callable<Integer> task = () -> { return 10; }; 3️⃣ Using Callable with Executor ExecutorService executor = Executors.newSingleThreadExecutor(); Future<Integer> future = executor.submit(task); Integer result = future.get(); executor.shutdown(); 4️⃣ What Is Future? Future represents: • Result of an asynchronous computation • Allows checking if task is complete • Can retrieve result using get() 5️⃣ Key Differences Runnable: • No return value • No checked exceptions Callable: • Returns value • Throws checked exceptions • Used with Future 🧠 Key Takeaway Runnable is for fire-and-forget tasks. Callable is for tasks that produce results. Future bridges asynchronous execution with synchronous result retrieval. #Java #Multithreading #ExecutorService #Callable #Concurrency
To view or add a comment, sign in
-
Discover the power of switch statements and expressions in Java. Learn how to efficiently control program flow with concise syntax
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