Day 42 – Java 2026: Smart, Stable & Still the Future Topic: Constructor in Java What is a Constructor? A constructor is a special method in Java that is automatically executed when an object is created. It is mainly used to initialize object data. Simple definition: A constructor initializes the state of an object at the time of object creation. Rules for Creating a Constructor • Constructor name must be the same as the class name • Constructor does not have a return type (not even void) • Constructor is automatically called when the object is created • Can be overloaded • Cannot be static, final, or abstract • If no constructor is written, Java provides a default constructor Types of Constructors in Java Default Constructor No-Argument Constructor Parameterized Constructor Copy Constructor (User-defined) One-Line Explanation of Each Constructor 1. Default Constructor Automatically provided by JVM when no constructor is defined in the class. 2. No-Argument Constructor A constructor explicitly created by programmer that takes no parameters. 3. Parameterized Constructor A constructor that accepts parameters to initialize object values. 4. Copy Constructor A constructor that copies values from one object to another object. Small Example (All Types) class Student { String name; int age; // No-Argument Constructor Student() { name = "Unknown"; age = 0; } // Parameterized Constructor Student(String n, int a) { name = n; age = a; } // Copy Constructor Student(Student s) { name = s.name; age = s.age; } } public class Main { public static void main(String[] args) { Student s1 = new Student(); // No-arg Student s2 = new Student("Sneha", 22); // Parameterized Student s3 = new Student(s2); // Copy System.out.println(s1.name + " " + s1.age); System.out.println(s2.name + " " + s2.age); System.out.println(s3.name + " " + s3.age); } } Key Points • Constructor runs only once per object • Used for initialization • Supports overloading • Improves object creation control Key Takeaway: Constructor ensures every object starts with a valid and predictable state. #Java #Constructor #OOP #LearnJava #JavaDeveloper #Programming #100DaysOfCode
Sneha Burhade’s Post
More Relevant Posts
-
📘 Why Does Java Allow the `$` Symbol in Identifiers? While learning about Java identifiers, I noticed something interesting. Unlike many programming languages, **Java allows the `$` symbol in identifier names.** Example: ```java int $value = 100; int total$amount = 500; ``` But this raises an interesting question: 👉 Why was `$` added to Java identifiers in the first place? 🔹 The historical reason When Java was designed in the 1990s, the language architects included `$` mainly for internal use by Java compilers and tools. The Java compiler often generates special class names automatically. For example, when you create an inner class, the compiled class file often uses `$` in its name: ``` OuterClass$InnerClass.class ``` Here, `$` helps represent the relationship between the outer class and the inner class. 🔹 Use in frameworks and generated code Many frameworks, libraries, and code generation tools also use `$` internally to create unique identifiers without conflicting with normal developer-defined names. 🔹 Should developers use `$` in identifiers? Technically, it is allowed. However, Java naming conventions discourage its use in normal code. The `$` symbol is generally reserved for: • Compiler-generated classes • Framework-generated code • Internal tooling 🔹 Key takeaway Sometimes language features exist not for everyday developers, but to support the ecosystem of compilers, frameworks, and tools that power the language. The `$` symbol in Java identifiers is one such design choice. #Java #Programming #SoftwareDevelopment #Coding #ComputerScience #LearnInPublic
To view or add a comment, sign in
-
-
DAY 26: CORE JAVA 🚀 Understanding the Use Cases of Static Variables and Static Methods in Java In Java, the "static" keyword plays a powerful role in managing shared data and class-level behavior. It allows variables and methods to belong to the class itself rather than to individual objects. Let’s explore why and when we use them. 👇 🔹 Static Variables (Class Variables) Static variables are shared among all objects of a class. Only one copy exists in memory, making them highly efficient. ✅ Use Cases • Storing common data shared by all objects (e.g., interest rate, company name, configuration values) • Reducing memory usage since the variable is created only once • Accessing class-level constants and configuration settings Example: class Businessman { static float rate = 15.2f; // shared interest rate } Here, every object of "Businessman" will use the same interest rate value. 🔹 Static Methods Static methods belong to the class, not the object. They can be called without creating an instance of the class. ✅ Use Cases • Utility or helper methods (e.g., Math calculations) • When method logic does not depend on instance variables • Entry point of Java programs ("main()" method) Example: class Test { static void display() { System.out.println("Inside static method"); } } Called as: Test.display(); 🔹 Key Advantages ✔ Efficient memory utilization ✔ Easy access without object creation ✔ Useful for shared data and utility functions ✔ Improves program organization and readability 📌 Real-world example: In a simple interest calculator, the interest rate can be static because it remains the same for all customers. 💡 Takeaway: Use static variables for shared data and static methods for operations that do not depend on object state. TAP Academy #Java #Programming #JavaDevelopment #Coding #SoftwareEngineering #LearnToCode
To view or add a comment, sign in
-
-
🚀 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
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
-
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
-
-
🌟 Day 7 of 10 – Core Java Recap: Encapsulation, Inheritance & Access Modifiers 🌟 Continuing my 10-day Core Java revision journey 🚀 Today I revised very important OOP concepts used in real-world applications. 🔐 1️⃣ Encapsulation in Java Encapsulation is the process of wrapping data (variables) and code (methods) into a single unit (class). It is mainly used for data hiding and security. In encapsulation: Variables are declared as private Access is provided using public getter and setter methods Key Benefits: ✔ Data hiding ✔ Controlled access to data ✔ Better code security ✔ Improved maintainability Example concept: Private variables + Public getters/setters = Encapsulation ⚙ 2️⃣ Implementation of Encapsulation Key points: Use private data members Provide public getter() and setter() methods Prevent direct access from outside the class Example: private String name; public String getName() { return name; } public void setName(String name) { this.name = name; } 🧬 3️⃣ Inheritance in Java Inheritance is a mechanism in which one class acquires the properties and behaviors of another class. Real-time relation: Parent Class → Child Class Superclass → Subclass Advantages: ✔ Code reusability ✔ Readability ✔ Maintainability 📚 4️⃣ Types of Inheritance Single Inheritance Multilevel Inheritance Hierarchical Inheritance Hybrid Inheritance (supported using interfaces in Java) Note: Java does not support multiple inheritance using classes to avoid ambiguity (Diamond Problem). 🔓 5️⃣ Access Modifiers in Java Access modifiers define the accessibility (scope) of classes, variables, and methods. Types of Access Modifiers: Public Private Protected Default (No modifier) 📊 6️⃣ Scope of Access Modifiers 🔹 Private Accessible only within the same class Provides maximum data security 🔹 Default Accessible within the same package No keyword is used 🔹 Protected Accessible within the same package Also accessible in subclasses (even in different packages) 🔹 Public Accessible from anywhere in the program Access Level Order: Private < Default < Protected < Public 💡 Key Learnings Today: Understood encapsulation and data hiding Learned how getters and setters control data access Revised inheritance and its types Clearly understood access modifiers and their scope Strengthening my OOP concepts step by step for interviews and real-world development 💻🔥 #Java #CoreJava #OOP #Encapsulation #Inheritance #AccessModifiers #JavaLearning #CodingJourney
To view or add a comment, sign in
-
🚨throw vs throws in Java - One Letter, Completely Different Meaning When I first started learning Java, two keywords confused me a lot: throw & throws They look almost identical... but they do very different things. Let's break it down simply👇 💠throw - Used to actually throw an exception -> Used within methods to explicitly raise an exception instance, allowing one checked or unchecked exception at a time. 🧩Example: if(age < 18){ throw new IllegalArgumentException("Age must be 18 or above"); } Here, the program immediately throws an exception. 💠throws - Used to declare possible exceptions -> Used in method signatures to declare one or more potential checked exceptions, signaling to the caller that the exception must be handled. 🧩Example: public void readFile() throws IOException { FileReader file = new FileReader("data.txt"); } This method itself does not handle the exception - it passes responsibilty to the caller. 🧠Simple way to remember throw->used inside a method (creates) throws->used in method declaration (warns) 💡Understanding this difference helps to: ✅Write cleaner APIs ✅Handle errors properly ✅Make the code easier for others to use. 💬 Quick question for Java developers here: Which exception confused you the most when you were starting out? NullPointerException still haunts many developers 😅 #Java #ExceptionHandling #JavaDeveloper #BackendDevelopment #Programming #SoftwareEngineering #LearningInPublic
To view or add a comment, sign in
-
-
Understanding the Java "main()" Method — "public static void main(String[] args)" Every Java program starts execution from the main() method. When you run a Java program, the JVM (Java Virtual Machine) looks for this method as the entry point. If a program does not contain a valid "main()" method, the JVM will not start execution. The commonly used syntax is: public static void main(String[] args) Each word in this declaration has a specific purpose: • public → Access modifier that allows the JVM to call the method from outside the class. If it is not public, the JVM cannot access it. • static → Allows the method to be called without creating an object of the class. The JVM can directly invoke the method when the program starts. • void → Specifies that the method does not return any value. Once the main method finishes execution, the Java program terminates. • main → The method name recognized by the JVM as the starting point of the program. Changing this name prevents the program from running. • String[] args → An array that stores command-line arguments passed when running the program. Example: class Example { public static void main(String[] args) { System.out.println("Hello, Java!"); } } Java also allows equivalent forms like: public static void main(String args[]) public static void main(String... args) All of these work because the parameter is still treated as a String array. Key Takeaway: The "main()" method acts as the entry point of a Java application, allowing the JVM to begin executing the program. #Java #JavaProgramming #CoreJava #JVM #BackendDevelopment #Programming #LearnToCode
To view or add a comment, sign in
-
-
💡 Java Tip: Using getOrDefault() in Maps When working with Maps in Java, we often need to handle cases where a key might not exist. Instead of writing extra conditions, Java provides a simple and clean method: getOrDefault(). 📌 What does it do? getOrDefault(key, defaultValue) returns the value for the given key if it exists. Otherwise, it returns the default value you provide. ✅ Example: Map<String, Integer> map = new HashMap<>(); map.put("apple", 10); map.put("banana", 20); System.out.println(map.getOrDefault("apple", 0)); // Output: 10 System.out.println(map.getOrDefault("grapes", 0)); // Output: 0 🔎 Why use it? • Avoids null checks • Makes code shorter and cleaner • Very useful for frequency counting problems 📊 Common Use Case – Counting frequency map.put(num, map.getOrDefault(num, 0) + 1); This small method can make your code more readable and efficient. Thankful to my mentor, Anand Kumar Buddarapu, and the practice sessions that continue to strengthen my core Java knowledge. Continuous learning is the key to growth! #Java #Programming #JavaDeveloper #CodingTips #SoftwareDevelopment
To view or add a comment, sign in
-
-
📌Exception Handling in Java ⚠️ ✅Exception Handling is a mechanism to handle unexpected situations that occur while a program is running. When an exception occurs, it disrupts the normal flow of the program. Common examples: • Accessing an invalid index in an array→ ArrayIndexOutOfBoundsException • Dividing a number by zero→ ArithmeticException Java provides thousands of exception classes to handle different runtime problems. 📌 Types of Exceptions in Java 1️⃣ Built-in Exceptions These are predefined exceptions provided by Java. ✅Checked Exceptions -Checked by the compiler at compile time Must be handled using try-catch or declared using throws Examples: IOException SQLException ClassNotFoundException ✅Unchecked Exceptions -Not checked by the compiler at compile time Occur mainly due to programming errors Examples: ArithmeticException NullPointerException ClassCastException 2️⃣ User-Defined (Custom) Exceptions Java also allows developers to create their own exceptions. This is useful when we want to represent specific business logic errors. Basic rules to create a custom exception: 1️⃣ Extend the Exception class 2️⃣ Create a constructor with a message 3️⃣ Throw the exception using throw 4️⃣ Handle it using try-catch 📌 Finally Block ✅The finally block always executes after the try-catch block, whether an exception occurs or not. It is commonly used for cleanup tasks, such as: Closing database connections Closing files Releasing resources 📌 Try-With-Resources ✅Sometimes developers forget to close resources manually. To solve this problem, Java introduced Try-With-Resources. It automatically closes resources once the block finishes execution. This makes resource management safer and cleaner. 📌 Important Keywords ✅throw : Used to explicitly create and throw an exception object. ✅throws: Used in the method signature to indicate that a method may throw an exception. Grateful to my mentor Suresh Bishnoi Sir for explaining Java concepts with such clarity and practical depth . If this post added value, feel free to connect and share it with someone learning Java. #Java #ExceptionHandling #CoreJava #JavaDeveloper #BackendDevelopment #SoftwareEngineering #InterviewPreparation #JavaProgramming #CleanCode
To view or add a comment, sign in
-
More from this author
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