🚀 Java Series – Day 18 📌 Serialization in Java (Why Serializable is a Marker Interface?) 🔹 What is it? Serialization is the process of converting a Java object into a byte stream so it can be stored in a file or transferred over a network. The reverse process is called Deserialization. Java uses the Serializable interface to enable serialization. 🔹 Why do we use it? Serialization is useful when we want to save object state or send objects across systems. For example: In a banking or login system, user session data can be serialized and stored, then later restored when needed. 🔹 Why is Serializable a Marker Interface? A marker interface is an empty interface (no methods) that signals the JVM to perform special behavior. "Serializable" does not contain any methods. It simply tells the JVM: 👉 “This object is allowed to be converted into a byte stream.” If a class does not implement "Serializable", Java will throw a NotSerializableException. 🔹 Example: import java.io.*; class Student implements Serializable { int id; String name; Student(int id, String name) { this.id = id; this.name = name; } } public class Main { public static void main(String[] args) throws Exception { Student s = new Student(1, "Raushan"); // Serialization ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("data.txt")); out.writeObject(s); out.close(); System.out.println("Object Serialized"); } } 💡 Key Takeaway: "Serializable" is a marker interface that enables object serialization without defining any methods. What do you think about this? 👇 #Java #Serialization #JavaDeveloper #Programming #BackendDevelopment
Java Serialization with Serializable Interface Explained
More Relevant Posts
-
🚀 Java Series – Day 21 📌 Inner Classes in Java (Static vs Non-Static) 🔹 What is it? An Inner Class is a class defined inside another class. Java provides different types of inner classes: • Member Inner Class (Non-static) • Static Nested Class • Local Inner Class (inside method) • Anonymous Inner Class 🔹 Why do we use it? Inner classes help in logical grouping of classes and improve code readability & encapsulation. For example: In a banking system, a "Bank" class can contain an inner class "Account" to tightly couple related logic. 🔹 Static vs Non-Static Inner Class: • Non-Static Inner Class (Member Inner Class) - Requires outer class object - Can access all members of outer class - Used when inner class depends on outer class • Static Inner Class (Static Nested Class) - Does NOT require outer class object - Can access only static members of outer class - Used for utility/helper classes 🔹 Example: class Outer { int x = 10; static int y = 20; // Non-static inner class class Inner { void display() { System.out.println("x = " + x); // can access all } } // Static inner class static class StaticInner { void display() { System.out.println("y = " + y); // only static access } } } public class Main { public static void main(String[] args) { // Non-static inner class Outer outer = new Outer(); Outer.Inner inner = outer.new Inner(); inner.display(); // Static inner class Outer.StaticInner obj = new Outer.StaticInner(); obj.display(); } } 💡 Key Takeaway: Use non-static inner classes when tightly coupled with outer class, and static inner classes for independent utility behavior. What do you think about this? 👇 #Java #InnerClass #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
🚀 Java Revision Journey – Day 25 Today I revised the PriorityQueue in Java, a very important concept for handling data based on priority rather than insertion order. 📝 PriorityQueue Overview A PriorityQueue is a special type of queue where elements are ordered based on their priority instead of the order they are added. 👉 By default, it follows natural ordering (Min-Heap), but we can also define custom priority using a Comparator. 📌 Key Characteristics: • Elements are processed based on priority, not FIFO • Uses a heap data structure internally • Supports standard operations like add(), poll(), and peek() • Automatically resizes as elements are added • Does not allow null elements 💻 Declaration public class PriorityQueue<E> extends AbstractQueue<E> implements Serializable ⚙️ Constructors Default Constructor PriorityQueue<Integer> pq = new PriorityQueue<>(); With Initial Capacity PriorityQueue<Integer> pq = new PriorityQueue<>(10); With Comparator PriorityQueue<Integer> pq = new PriorityQueue<>(Comparator.reverseOrder()); With Capacity + Comparator PriorityQueue<Integer> pq = new PriorityQueue<>(10, Comparator.reverseOrder()); 🔑 Basic Operations Adding Elements: • add() → Inserts element based on priority Removing Elements: • remove() → Removes the highest-priority element • poll() → Removes and returns head (safe, returns null if empty) Accessing Elements: • peek() → Returns the highest-priority element without removing 🔁 Iteration • Can use iterator or loop • ⚠️ Iterator does not guarantee priority order traversal 💡 Key Insight PriorityQueue is widely used in algorithmic problem solving and real-world systems, such as: • Dijkstra’s Algorithm (shortest path) • Prim’s Algorithm (minimum spanning tree) • Task scheduling systems • Problems like maximizing array sum after K negations 📌 Understanding PriorityQueue helps in designing systems where priority-based processing is required, making it essential for DSA and backend development. Continuing to strengthen my Java fundamentals step by step 💪🔥 #Java #JavaLearning #PriorityQueue #DataStructures #JavaDeveloper #BackendDevelopment #Programming #JavaRevisionJourney 🚀
To view or add a comment, sign in
-
-
☄️🎊Day 67 of 90 – Java Backend Development 🎆 🧨 In Java, immutability means that once a String object is created, its value cannot be changed. If you try to "modify" a string—for example, by appending text—Java actually creates a brand-new string object in memory rather than altering the original one. This design choice wasn't accidental; it’s a foundational pillar of how Java handles memory, security, and performance. 👉 Core Reasons for Immutability 👉 1. The String Constant Pool Java uses a special memory area called the String Pool. When you create a string literal, the JVM checks if that value already exists in the pool. If it does, it returns a reference to the existing object instead of creating a new one. If strings were mutable, changing the value of one variable would secretly change the value for every other variable pointing to that same literal, leading to unpredictable bugs. 👉 2. Security Strings are used heavily in sensitive areas of Java programming, such as: Database URLs and credentials. Network connections. File paths. Class loading. If a string were mutable, an untrusted piece of code could receive a reference to a file path, verify it has permission, and then sneakily change the path before the file is actually opened. Immutability ensures that once a value is validated, it stays that way. 👉 3. Thread Safety Because a String cannot change, it is inherently thread-safe. You can share a single string across multiple threads without worrying about synchronization or data corruption. This significantly simplifies concurrent programming in Java. 👉 4. Caching HashCodes In Java, strings are frequently used as keys in HashMap or elements in HashSet. The hashCode() of a string is calculated and cached the first time it's called. Since the string is immutable, the hash code will never change. This makes lookups in collections incredibly fast, as the JVM doesn't have to re-calculate the hash every time the string is accessed. #String #Immutability #HashCodes
To view or add a comment, sign in
-
-
🚀🎊Day 81 of 90 – Java Backend Development ✨🎆 In Java, Wrapper classes provide a way to use primitive data types (like int, boolean, etc.) as objects. Since Java is an object-oriented language, many of its most powerful features—like Collections (ArrayList, HashMap) and Generics—only work with objects, not primitives. 👉Why do we need them? Primitives are fast and memory-efficient, but they lack the "bells and whistles" of objects. Wrapper classes bridge this gap by "wrapping" a primitive value inside an object. i) Collections Support: You cannot create an ArrayList<int>, but you can create an ArrayList<Integer>. ii) Utility Methods: They provide handy methods for conversion (e.g., converting a String to an int). iii) Null Values: Primitives must have a value; Wrapper objects can be null, which is useful in databases or web forms. 👉Autoboxing and unboxing Modern Java (since version 5) handles the conversion between primitives and wrappers automatically. This makes your code much cleaner. 1. Autoboxing The automatic conversion of a primitive type to its corresponding wrapper class. int primitive = 10; Integer wrapper = primitive; // Autoboxing 2. Unboxing The reverse process: converting a wrapper object back into a primitive. Integer wrapper = 20; int primitive = wrapper; // Unboxing 👉 Useful features: Wrapper classes aren't just containers; they are packed with static utility methods. For example: i) Parsing Strings: int x = Integer.parseInt("123"); ii) Constants: Integer.MAX_VALUE or Double.NaN. iii) Type Conversion: myInteger.doubleValue(); #Wrapperclass #PrimitiveDataType #Autoboxing #Autounboxing
To view or add a comment, sign in
-
-
🚀 Java Series – Day 19 📌 Multithreading in Java (Thread vs Runnable) 🔹 What is it? Multithreading is a process of executing multiple threads simultaneously to perform tasks efficiently. A thread is a lightweight unit of execution within a program. Java provides two main ways to create threads: • Extending the Thread class • Implementing the Runnable interface 🔹 Why do we use it? Multithreading helps improve performance and responsiveness. For example: In a web application, one thread can handle user requests while another processes background tasks like data saving or logging. 🔹 Thread vs Runnable: • Thread Class - Extend "Thread" - Less flexible (Java doesn’t support multiple inheritance) • Runnable Interface - Implement "Runnable" - More flexible (can extend another class) - Preferred approach in real-world applications 🔹 Example: // Using Thread class MyThread extends Thread { public void run() { System.out.println("Thread using Thread class"); } } // Using Runnable class MyRunnable implements Runnable { public void run() { System.out.println("Thread using Runnable"); } } public class Main { public static void main(String[] args) { MyThread t1 = new MyThread(); t1.start(); Thread t2 = new Thread(new MyRunnable()); t2.start(); } } 💡 Key Takeaway: Use Runnable for better flexibility and scalability in multithreaded applications. What do you think about this? 👇 #Java #Multithreading #JavaDeveloper #Programming #BackendDevelopment
To view or add a comment, sign in
-
-
Day 8 of Java Series ☕💻 Today we dive into one of the most important real-world concepts in Java — Exception Handling 🚨 👉 Exception Handling is used to handle runtime errors so that the normal flow of the program can be maintained. 🧠 What is an Exception? An Exception is an unwanted event that occurs during program execution and disrupts the normal flow of the program. ⚙️ Types of Exceptions: Checked Exceptions (Compile-time) Example: IOException, SQLException Unchecked Exceptions (Runtime) Example: ArithmeticException, NullPointerException Errors Example: StackOverflowError, OutOfMemoryError 🛠️ Exception Handling Keywords: try → Code that may throw exception catch → Handles the exception finally → Always executes (cleanup code) throw → Used to explicitly throw exception throws → Declares exceptions 💻 Example Code: Java Copy code public class Main { public static void main(String[] args) { try { int a = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("Execution Completed"); } } } ⚡ Custom Exception: You can create your own exception by extending Exception class. Java Copy code class MyException extends Exception { MyException(String msg) { super(msg); } } 🎯 Why Exception Handling is Important? ✔ Prevents program crash ✔ Maintains normal flow ✔ Improves debugging ✔ Makes code robust 🚀 Pro Tip: Always catch specific exceptions instead of generic ones for better debugging! 📢 Hashtags: #Java #ExceptionHandling #JavaSeries #Programming #CodingLife #LearnJava #Developers #Tech
To view or add a comment, sign in
-
-
🚀 Understanding Method Overloading in Java 🔥 Let's break down the concept of method overloading in Java! Method overloading allows developers to define multiple methods with the same name but different parameters, making code more flexible and readable. This means you can have multiple methods with the same name, as long as the parameters differ in type or number. ⚡️ Why does method overloading matter for developers? It helps streamline code by promoting code reusability and enhancing readability. By using method overloading, developers can create cleaner code that is easier to maintain and understand. 👨💻 Here's a step-by-step breakdown: 1️⃣ Create multiple methods with the same name 2️⃣ Ensure the parameters are different in either type or number 3️⃣ The Java compiler determines which method to execute based on the arguments provided 📝 Full code example: ``` public class Calculate { public int sum(int a, int b) { return a + b; } public double sum(double a, double b) { return a + b; } } ``` 💡 Pro tip: Avoid overloading methods with the same number and type of parameters, as it can lead to ambiguity. ⚠️ Common mistake: Forgetting that the return type of the overloaded methods can be the same. ❓ How do you use method overloading in your Java projects? Do you have any favorite tricks? Share below! 💬 🌐 View my full portfolio and more dev resources at tharindunipun.lk #JavaProgramming #MethodOverloading #CodeFlexibility #LearnToCode #DeveloperTips #CleanCode #JavaDev #CodingCommunity #TechTalks
To view or add a comment, sign in
-
-
Building Native Image for a Java application requires configuration of reflection, proxies, and other dynamic Java mechanisms. But why is this necessary if the JVM handles all of this automatically? To answer that, we need to look at the differences between static and dynamic compilation in Java. https://lnkd.in/eVyGYHZk
To view or add a comment, sign in
-
🚀 Java Series – Day 28 📌 Reflection API in Java (How Spring Uses It) 🔹 What is it? The **Reflection API** allows Java programs to **inspect and manipulate classes, methods, fields, and annotations at runtime**. It allows operations like **creating objects dynamically, invoking methods, and reading annotations** without hardcoding them. 🔹 Why do we use it? Reflection helps in: ✔ Dependency Injection – automatically injects beans ✔ Annotation Processing – reads `@Autowired`, `@Service`, `@Repository` ✔ Proxy Creation – supports AOP and transactional features For example: In Spring, it can detect a class annotated with `@Service`, create an instance, and inject it wherever required without manual wiring. 🔹 Example: `import java.lang.reflect.*; @Service public class DemoService { public void greet() { System.out.println("Hello from DemoService"); } } public class Main { public static void main(String[] args) throws Exception { Class<?> clazz = Class.forName("DemoService"); // load class dynamically Object obj = clazz.getDeclaredConstructor().newInstance(); // create instance Method method = clazz.getMethod("greet"); // get method method.invoke(obj); // invoke method dynamically } }` 🔹 Output: `Hello from DemoService` 💡 Key Takeaway: Reflection makes Spring **dynamic, flexible, and powerful**, enabling features like DI, AOP, and annotation-based configuration without manual coding. What do you think about this? 👇 #Java #ReflectionAPI #SpringBoot #JavaDeveloper #BackendDevelopment #TechLearning #CodingTips
To view or add a comment, sign in
-
-
Learn how to use the this keyword in Java to resolve naming conflicts, enable method chaining, and write clear, maintainable code.
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://github.com/raushansingh7033/core-java