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
Java Garbage Collection Basics
More Relevant Posts
-
DAY 24: CORE JAVA 💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using Scanner, many beginners face a common issue called the Buffer Problem. 🔹 What is the Buffer Problem? When we use "nextInt()", "nextFloat()", etc., the scanner reads only the number but leaves the newline character ("\n") in the input buffer. Example: Scanner scan = new Scanner(System.in); int n = scan.nextInt(); // reads number String name = scan.nextLine(); // reads leftover newline ⚠️ The "nextLine()" does not wait for user input because it consumes the leftover newline from the buffer. ✅ Solution: Use an extra "nextLine()" to clear the buffer. int n = scan.nextInt(); scan.nextLine(); // clears the buffer String name = scan.nextLine(); 📌 This is commonly called a dummy nextLine() to flush the buffer. 🔹 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. Primitive Type| Wrapper Class byte| Byte short| Short int| Integer long| Long float| Float char| Character 💡 Wrapper classes allow: - Converting String to primitive values - Storing primitive data in collections - Using useful utility methods Example: String s = "123"; int num = Integer.parseInt(s); // String → int 🔹 Example Use Case Suppose employee data is entered as a string: 1,Swathi,30000 We can split and convert values using wrapper classes: String[] arr = s.split(","); int empId = Integer.parseInt(arr[0]); String empName = arr[1]; int empSal = Integer.parseInt(arr[2]); 🚀 Key Takeaways ✔ Always clear the buffer when mixing "nextInt()" and "nextLine()" ✔ Wrapper classes help convert String ↔ primitive types ✔ They are essential when working with input processing and collections 📚 Concepts like these strengthen the core Java foundation for developers and interview preparation. TAP Academy #Java #CoreJava #JavaProgramming #WrapperClasses #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
-
🚀 Understanding Multithreading in Java Multithreading is one of the most powerful features in Java that allows a program to perform multiple tasks simultaneously. It improves application performance and better utilizes CPU resources. 🔹 What is Multithreading? Multithreading is a process of executing multiple threads (smallest units of a process) concurrently within a single program. Example: A web application can handle multiple user requests at the same time using threads. 🔹 Why Multithreading is Important? ✔ Improves application performance ✔ Better CPU utilization ✔ Enables parallel processing ✔ Allows responsive applications (UI not freezing) 🔹 Ways to Create Threads in Java 1️⃣ Extending the Thread class class MyThread extends Thread { public void run() { System.out.println("Thread is running..."); } } 2️⃣ Implementing the Runnable interface class MyRunnable implements Runnable { public void run() { System.out.println("Thread is running..."); } } 🔹 Key Concepts in Multithreading • Thread Lifecycle • Synchronization • Deadlock • Thread Pool • Executor Framework 🔹 Simple Example class TestThread { public static void main(String[] args) { Runnable r = () -> System.out.println("Thread executed"); Thread t1 = new Thread(r); Thread t2 = new Thread(r); t1.start(); t2.start(); } } 💡 Takeaway: Multithreading helps build scalable and high-performance applications. Understanding synchronization and thread management is essential for backend developers. #Java #Multithreading #JavaDeveloper #BackendDevelopment #Programming #SoftwareDevelopment
To view or add a comment, sign in
-
🚀 Understanding Strings in Java | TAP Academy In Java, a String is a collection (sequence) of characters enclosed within double quotes (" ").A single character is enclosed within single quotes (' '). 🔹 Types of Strings in Java Strings are classified into two types: ✅ 1. Mutable String A mutable string can be modified or changed after creation. Example classes: StringBuilder, StringBuffer. ✅ 2. Immutable String An immutable string cannot be changed once created. The String class in Java is immutable — any modification creates a new object. 🔹 Creating an Immutable String in Java Like arrays, Strings are objects in Java. They are created using the new keyword or string literals, and memory is allocated in the Heap Segment of the JRE. Ways to create a String: Using String Literal → "Java" Using new Keyword → new String("Java") 🔹 Ways to Compare Two Strings in Java Java provides multiple methods to compare strings based on requirement: ✔ == → Compares memory reference (address) ✔ equals() → Compares actual content (values) ✔ compareTo() → Compares lexicographically (dictionary order) ✔ equalsIgnoreCase() → Compares content ignoring case differences 🔹 Memory Allocation of Strings (Heap Segment) The Heap is further divided into two pools: 📌 1. String Constant Pool (SCP) Strings created using literals. Duplicate values are not allowed (memory optimization). 📌 2. Non-Constant Pool (Heap Area) Strings created using the new keyword. Duplicate objects are allowed. ✨ Key Takeaway: Java Strings are powerful and memory-efficient because of immutability and the String Constant Pool, which help in security, performance, and reusability. #Java #StringsInJava #CoreJava #ProgrammingBasics #LearningJourney #TAPAcademy #JavaDevelopment
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
-
In Java, enum types are often introduced as just a list of constants. But they are actually much more powerful: they are real classes, with constructors, methods, and even different behavior for each constant. In this article I explore some lesser-known uses of enums that can make Java code more expressive and robust. ✍️ Stranger Things in Java: Enum Types Happy coding! ☕💻
To view or add a comment, sign in
-
🚀 Java Series – Day 15 📌 Exception Handling in Java (try-catch-finally & Checked vs Unchecked) 🔹 What is it? Exception Handling in Java is used to handle runtime errors so that the program can continue executing smoothly. Java provides keywords to handle exceptions: • try – Code that may cause an exception • catch – Handles the exception • finally – Always executes (used for cleanup) 🔹 Why do we use it? Exception handling helps prevent program crashes and ensures better user experience. For example: In a file upload system, if a file is not found or an error occurs, instead of crashing, the program can show a proper error message and continue execution. Also, Java classifies exceptions into: • Checked Exceptions – Checked at compile time (e.g., IOException) • Unchecked Exceptions – Occur at runtime (e.g., NullPointerException, ArithmeticException) 🔹 Example: public class Main { public static void main(String[] args) { try { int result = 10 / 0; // Exception } catch (ArithmeticException e) { System.out.println("Cannot divide by zero"); } finally { System.out.println("Execution completed"); } } } 💡 Key Takeaway: Exception handling ensures robust and crash-free applications by managing errors effectively. What do you think about this? 👇 #Java #ExceptionHandling #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
ArrayList ✈️ In Java, an ArrayList is a member of the Java Collections Framework and resides in the java.util package. While a standard Java array (e.g., int[]) is fixed in length, an ArrayList is a resizable-array implementation of the List interface. How It Works: The "Growing" Mechanism When you add an element to an ArrayList, Java checks if there is enough room in the underlying memory. If the internal array is full, the ArrayList performs the following: It allocates a new, larger array ✅Key Features in Java Type Safety: It uses Generics, allowing you to specify what type of data it holds (e.g., ArrayList<String>). Wrapper Classes: It cannot store primitive types (like int, double, char) directly. Instead, Java uses "Autoboxing" to convert them into objects (like Integer, Double, Character). Nulls and Duplicates: It allows you to store duplicate elements and null values. Unsynchronized: By default, it is not thread-safe. If multiple threads access it simultaneously, you must handle synchronization manually. It copies all existing elements to the new array. It updates its internal reference to this new array. ✅ArrayList vs. LinkedList A common interview question is when to use ArrayList over LinkedList. ArrayList: Best for frequent access and storing data where you mostly add/remove from the end. LinkedList: Best if you are constantly inserting or deleting items from the beginning or middle of the list. Would you like me to explain the specific differences between ArrayList and Vector, or perhaps show you how to sort an ArrayList using Collections.sort(). Huge thanks for the mentorship on Java ArrayList Anand Kumar Buddarapu Saketh Kallepu Uppugundla Sairam #ArrayList #Java #DataStructures #Programming #Coding #SoftwareEngineering #Backend #JavaDeveloper #Algorithms #TechTips #ComputerScience
To view or add a comment, sign in
-
Understanding Collection and List in Java 🔹 What is Collection in Java? The Collection Framework in Java is a unified architecture that provides interfaces and classes to store and manipulate groups of objects dynamically. It is available in the java.util package and offers ready-made data structures like List, Set, Queue, and more. Why use Collections instead of arrays? ✔ Dynamic size (grow/shrink at runtime) ✔ Built-in utility methods ✔ Better performance handling ✔ Easy data manipulation 🔹 What is List in Java? A List is a child interface of the Collection interface. A List: ✔ Maintains insertion order ✔ Allows duplicate elements ✔ Allows null values ✔ Supports index-based access It is mainly used when order and duplicates matter. 🔹 Types of List in Java 1️⃣ ArrayList Uses a dynamic array internally Fast for reading (random access) Slower for insert/delete in the middle Most commonly used List implementation 2️⃣ LinkedList Uses a doubly linked list internally Fast insertion and deletion Slower random access compared to ArrayList 3️⃣ Vector (Legacy Class) Similar to ArrayList Thread-safe (synchronized) Slower due to synchronization Rarely used in modern applications 4️⃣ Stack (Extends Vector) Follows LIFO (Last In First Out) Methods: push(), pop(), peek() In modern applications, Deque is preferred over Stack Additional Useful Methods: 1. remove(index) 2. remove(Object) 3. clear() 4. contains() 5. isEmpty() 6.add() 📌 Summary Collection provides the framework to manage groups of objects. List is an ordered collection that allows duplicates and index-based access. ArrayList and LinkedList are the most commonly used implementations in real-world applications. Frontlines EduTech (FLM) #Java #Collection #list
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 10 Today I revised the concepts of Abstract Classes and Interfaces in Java and how they help achieve abstraction and flexible application design. 🔖 Abstract Class and Abstract Method: An abstract class is a class that cannot be instantiated and is used to provide partial abstraction. It can contain both abstract methods (without implementation) and concrete methods (with implementation). Abstract methods must be implemented by subclasses. 🔖 Interface: An interface defines a contract for classes by specifying method declarations. It mainly provides abstraction for behavior and allows classes to implement multiple interfaces. Interfaces can also contain default and static methods. 🔖 Abstract Class vs Interface: Abstract classes provide partial abstraction, while interfaces are mainly used to achieve a higher level of abstraction for behavior definition. 🔖Multiple Inheritance through Interface: Java does not support multiple inheritance using classes to avoid complexity. However, a class can implement multiple interfaces, allowing multiple inheritance in a structured way. 🔖Hybrid Inheritance through Interface: Hybrid inheritance is a combination of two or more types of inheritance. In Java, this can be achieved using interfaces. 🔖Diamond Problem and Code Ambiguity: Multiple inheritance using classes can create ambiguity, known as the diamond problem. Java avoids this by not allowing multiple inheritance with classes. Interfaces solve this problem with clear implementation rules. 🔖Loose Coupling vs Tight Coupling: Interfaces help achieve loose coupling, where components depend on abstractions rather than concrete implementations. This makes applications easier to maintain and extend. 💻 Understanding these concepts is essential for designing scalable, maintainable, and well-structured Java applications. Continuing to strengthen my Java fundamentals step by step. #Java #JavaLearning #JavaDeveloper #OOP #BackendDevelopment #Programming #JavaRevisionJourney
To view or add a comment, sign in
-
-
Day 48 – Java 2026: Smart, Stable & Still the Future Non-Static Initializer in Java (Instance Initializer Explained) A non-static initializer block (also called an instance initializer block) is used to initialize instance variables of a class. Unlike static blocks, it executes every time an object of the class is created. It runs before the constructor but after the object memory is allocated in the heap. Syntax { // initialization code } This block does not use the static keyword because it works with object-level variables. Example class Example { int number; { System.out.println("Non-static initializer executed"); number = 100; } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { Example obj1 = new Example(); Example obj2 = new Example(); } } Output Non-static initializer executed Constructor executed Non-static initializer executed Constructor executed Execution Flow in JVM Class is loaded by the ClassLoader. Memory for the object is allocated in the Heap. Non-static initializer block executes. Constructor executes. Object becomes ready for use. Flow: Object Creation ↓ Memory allocated in Heap ↓ Non-static initializer executes ↓ Constructor executes Memory Structure Method Area Class metadata Static variables Static methods Heap Object instance variables Non-static initialization Stack Method execution frames Non-static initializers belong to object creation, so they work with Heap memory. When It Is Used Non-static initializer blocks are useful when: Common initialization code is required for all constructors Reducing duplicate logic inside multiple constructors Preparing instance-level configuration before constructor logic runs Key Point A non-static initializer executes every time an object is created, making it useful for object-level initialization before the constructor runs. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
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