Day 25 – Understanding Blocks in Java (Static & Non-Static) One interesting concept I learned today in Core Java is Initialization Blocks. Blocks are special members of a class used to initialize variables automatically during program execution. There are mainly two types of blocks in Java: 🔹 Static Block 🔹 Non-Static Block (Instance Initialization Block) ---------------------------------------------- 🔹 Static Block A static block is used to initialize static variables of a class. Key points: ✔ Executed only once ✔ Runs during class loading ✔ Executes before the main() method Example: class Employee { static int x; static { x = 20; } public static void main(String[] args) { System.out.println(Employee.x); } } 📌 Static block executes automatically when the class is loaded into memory. ---------------------------------------------- 🔹 Non-Static Block (Instance Block) A non-static block is used to initialize non-static (instance) variables. Key points: ✔ Executes every time an object is created ✔ Can run multiple times ✔ Runs before the constructor Example: class Employee { int id; String name; { id = 1; name = "Raj"; } } Whenever we create a new object: Employee e1 = new Employee(); Employee e2 = new Employee(); The non-static block runs twice because two objects are created. ---------------------------------------------- 🔹 Order of Execution in Java Understanding execution order is important: 📌 Static Block → main() → Non-Static Block → Constructor This explains how Java initializes classes and objects internally. 📌 Key Takeaway Initialization blocks help in automatic setup of variables before objects start working. Understanding this concept helps build strong fundamentals in Java memory behavior and object creation. Every day I’m learning something new about how Java actually works behind the scenes. #Java #CoreJava #JavaProgramming #JavaDeveloper #Programming #SoftwareDevelopment #LearningInPublic #CodingJourney #BackendDevelopment #100DaysOfCode
Java Initialization Blocks: Static & Non-Static Explained
More Relevant Posts
-
Hii everyone, Sharing some commonly asked Java interview questions for practice: 1. Why is Java a platform independent language? 2.Why is Java not a pure object oriented language? 3.Tell us something about JIT compiler. 4. Can you tell the difference between equals() method and equality operator (==) in Java? 5.Briefly explain the concept of constructor overloading 5.Define Copy constructor in java. 6.Can the main method be Overloaded.how? 7.Explain the use of final keyword in variable, method and class 8.Do final, finally and finalize keywords have the same function? 9. When can you use super keyword and this keyword? 10. Why is the main method static in Java? 11.. Can the static methods be overridden? 13.Difference between static methods, static variables, and static classes in java. 14.What is a ClassLoader Explain its types? 15.How would you differentiate between a String, StringBuffer, and a StringBuilder? 16.Why string is immutable? 17.What do you understand by class and object? Also, give example. 18.What are the characteristics of an abstract class? 19.What is composition? 20.What is Coupling in OOP and why it is helpful? 21.Explain overloading and overriding with example? 22.Give a real-world example of polymorphism? 23.What is inheritance explain its type? 24.EXplain Encapsulation? 25.What are the differences between error and exception? 26. Using relevant properties highlight the differences between interfaces and abstract classes. 27.type of exception explain it? 28.Different bw throw and throws? 29.What are the differences between HashMap and HashTable in Java? 30.What makes a HashSet different from a TreeSet? 31.Java works as “pass by value” or “pass by reference” phenomenon? 32.Different bw ISA relationship HAS a Relationship? 33. Will the finally block get executed when the return statement is written at the end of try block and catch block as shown below? 34. Explain various interfaces used in Collection framework? 35.What is the difference between ArrayList and LinkedList? 36.What is the difference between List and Set? 37.What is the difference between Comparable and Comparator? 38. How to remove duplicates from ArrayList? 39.HashMap internal works? 40.Can you explain the Java thread lifecycle? 41. What do you understand by marker interfaces in Java? 42.types of memory in java? 43.Why is multiple inheritance not supported in java? 44.Can we override the private methods? 45.What is the difference between compile-time polymorphism and runtime polymorphism? 46.What is exception propagation? 47.volatile keyword? 48.dead lock? 49.Synchronization in java? 50.what is HashMap and weak HashMap? 51.diff b/w jdk jre jvm? 52.what is sterilization and deserialization? 53.diff HashMap and hash table? 54.wrapper class in java?
To view or add a comment, sign in
-
Day 49 – Java 2026: Smart, Stable & Still the Future Difference Between Static and Non-Static Initializers in Java In Java, initializer blocks are used to initialize variables during the class loading or object creation phase. There are two types: Static Initializer Non-Static (Instance) Initializer Understanding their difference helps in learning how JVM memory management and class loading work. 1. Static Initializer A static initializer block is used to initialize static variables of a class. It executes only once when the class is loaded into memory by the ClassLoader. class Example { static int a; static { a = 10; System.out.println("Static initializer executed"); } public static void main(String[] args) { System.out.println(a); } } Key idea: It runs once during class loading. 2. Non-Static Initializer A non-static initializer block is used to initialize instance variables. It executes every time an object is created. class Example { int b; { b = 20; System.out.println("Non-static initializer executed"); } Example() { System.out.println("Constructor executed"); } public static void main(String[] args) { new Example(); new Example(); } } Key idea: It runs every time an object is created. 3. Key Differences FeatureStatic InitializerNon-Static InitializerKeywordUses staticNo keywordExecution timeWhen class loadsWhen object is createdRuns how many timesOnce per classEvery object creationVariables initializedStatic variablesInstance variablesMemory areaMethod AreaHeapExecution orderBefore main()Before constructor4. Execution Flow in JVM When a Java program runs: ClassLoader loads the class Static initializer executes main() method starts Object is created Non-static initializer executes Constructor executes Flow: Program Start ↓ Class Loaded ↓ Static Initializer ↓ Main Method ↓ Object Creation ↓ Non-Static Initializer ↓ Constructor Key Insight Static initializer → class-level initialization (runs once) Non-static initializer → object-level initialization (runs every object creation) Understanding these concepts helps developers clearly see how JVM manages class loading, memory, and object initialization. #Java #JavaDeveloper #JVM #OOP #Programming #BackendDevelopment
To view or add a comment, sign in
-
🔥 Core Java (Must Prepare) 1. What is the difference between == and .equals()? == → compares reference (memory location) .equals() → compares content/value 2. Why String is immutable? Security (used in DB, network, etc.) Thread-safe String pool optimization 3. What is String Pool? A memory area in heap where unique String literals are stored. Avoids duplicate objects → improves performance 4. Difference: ArrayList vs LinkedList FeatureArrayListLinkedListStructureDynamic ArrayDoubly Linked ListAccessFastSlowInsert/DeleteSlowFast 5. How HashMap works internally? Uses hashing (hashCode + equals) Stores data in buckets Collision handled using: LinkedList (Java 7) Tree (Java 8 → Balanced Tree) 6. Difference: HashMap vs ConcurrentHashMap HashMap → not thread-safe ConcurrentHashMap → thread-safe (segment locking / CAS) 🔥 OOP & Design 7. What are OOP principles? Encapsulation Inheritance Polymorphism Abstraction 8. Method Overloading vs Overriding Overloading → same method name, different parameters Overriding → runtime polymorphism (same method in subclass) 9. What is SOLID principle? S → Single Responsibility O → Open/Closed L → Liskov Substitution I → Interface Segregation D → Dependency Injection 🔥 Multithreading (VERY IMPORTANT) 10. What is Thread? Lightweight process for parallel execution 11. Runnable vs Callable Runnable → no return Callable → returns value + throws exception 12. What is Synchronization? Prevents multiple threads accessing same resource 13. What is Deadlock? When threads are waiting on each other forever 14. What is Executor Framework? Manages thread pool → improves performance 15. What is volatile keyword? Ensures visibility of changes across threads 🔥 Java 8+ (VERY IMPORTANT) 16. What is Lambda Expression? Short way to write functional code (list) -> list.size() 17. What is Functional Interface? Interface with one abstract method Example: Runnable 18. Stream API? Used for data processing (filter, map, reduce) 19. Optional class? Avoids NullPointerException 🔥 Exception Handling 20. Checked vs Unchecked Exception Checked → compile-time (IOException) Unchecked → runtime (NullPointerException) 21. Difference: throw vs throws throw → used to throw exception throws → declares exception 🔥 Memory & JVM 22. What is JVM? Executes Java bytecode 23. Heap vs Stack Heap → Objects Stack → Method calls, variables 24. What is Garbage Collection? Automatically removes unused objects 🔥 Advanced (4+ Year Level) 25. What is Serialization? Convert object → byte stream 26. transient keyword? Skips variable during serialization 27. Comparable vs Comparator Comparable → natural sorting Comparator → custom sorting 28. Fail-fast vs Fail-safe Fail-fast → throws exception (ArrayList) Fail-safe → works on copy (ConcurrentHashMap) 🔥 Real Interview Scenario Questions 29. How do you handle high traffic in Java? Caching (Redis) Thread pool Load balancing 30. How do you debug production issue? Logs (ELK) Thread dump Heap dump
To view or add a comment, sign in
-
Standard Signature of main() Method in Java In every programming language there must be an entry point of execution from where program execution begins. In C/C++, the entry point is the main() function, which is invoked by the Operating System. OS expects 0 as exit status indicating successful program execution so the return type of main is commonly int. In Java, the entry point is also the main() method, but it is invoked by the Java Virtual Machine (JVM) instead of the OS. Since the JVM handles execution internally, there is no need to return a status code, therefore the return type of the main method is always void. In Java, every method belongs to a class, so the main method must be defined inside a class. Example: class Main { void main() { // code } } However, this method cannot be executed by the JVM because it is not accessible outside the class. To allow the JVM to access it, the method must be declared public. class Main { public void main() { // code } } In Java, methods normally belong to objects and are invoked using an object reference. If the main method were not static, the JVM would have to create an object of the class before calling it. Since main is the entry point of every program, this would add unnecessary overhead. To allow the JVM to invoke the method without creating an object, the main method is declared static. class Main { public static void main() { // code } } But this method still cannot receive data from the command line arguments. To accept input from the command line during program execution, the main method takes a parameter which is an array of strings. Each element of this array represents one argument passed from the command line. Final standard signature of the main method: class Main { public static void main(String[] args) { // code } } Here: public → allows the JVM to access the method static → allows the JVM to call the method without creating an object void → no return value required String[] args → receives command line arguments However, for a beginner writing "public static void main(String[] args)" is overwhelming. So Java developer decided to introduce simplified syntax for new comer to maintain language acceptance and popularity among all. In newer Java versions, we can write a simpler program like: void main() { System.out.println("Hello"); } Introduced in JDK 21 and finally accepted in JDK 25 (2025). The compiler automatically wraps this into a class behind the scenes. However, this feature is mainly designed for learning and small scripts, while the traditional main method remains the standard approach used in real applications. Grateful to my mentor Syed Zabi Ulla for explaining these concepts so clearly and helping me build a strong foundation in programming. #OOP #Java #Programming #ComputerScience #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
A Thought I Had About Multiple Inheritance in Java Recently I was thinking about a common question in Java: Why does Java allow multiple inheritance through interfaces but not through classes? At first, it feels like multiple inheritance through classes could have been possible. My Initial Thought Imagine we had something like this: class A { int x = 10; } class B { int x = 20; } class C extends A, B { } Now if we create an object: C obj = new C(); System.out.println(obj.x); This creates ambiguity. Should it print 10 or 20? But I was thinking — couldn't this be solved if Java simply forced us to specify the parent? For example: System.out.println(((A)obj).x); // 10 System.out.println(((B)obj).x); // 20 So technically, the ambiguity could be resolved by explicitly specifying which parent we want. But the Real Problem Is Bigger Variables are not the main issue. The real problem appears with methods and inheritance hierarchy. Consider this structure: A / \ B C \ / D This is known as the Diamond Problem. If class D inherits from both B and C, which both inherit from A, Java has to answer tricky questions: Should D contain one copy of A or two copies? If A has a method, which path should Java follow? How should the JVM manage memory layout and method resolution? Supporting this would require complex rules inside the JVM and would make the language harder to understand and maintain. Java’s Design Choice Instead of adding that complexity, Java designers made a simple rule: Classes → Single Inheritance Interfaces → Multiple Inheritance Example with interfaces: interface A { void show(); } interface B { void show(); } class C implements A, B { public void show() { System.out.println("Implementation in C"); } } Here there is no ambiguity because the child class provides the implementation. Final Insight Multiple inheritance through classes could theoretically exist, but it would significantly increase JVM complexity and introduce problems like the diamond problem. By allowing it only through interfaces, Java keeps the language simpler, safer, and easier to maintain. I find it fascinating how many design decisions in programming languages are not just about what is possible, but about what keeps the language simple and predictable. #Java #JavaDeveloper #JavaProgramming #CoreJava #OOP #ObjectOrientedProgramming #SoftwareDevelopment #BackendDevelopment #BackendDeveloper #Programming #Coding #CodingLife #DeveloperCommunity #DevCommunity #JVM #JavaConcepts #JavaInterview
To view or add a comment, sign in
-
-
🚀 Day 24 – Java Concepts for Interviews Method Overriding | Final Keyword | Method Hiding 🔹 1️⃣ Class Terminology In Java inheritance: Parent class → Superclass / Base class Child class → Subclass / Derived class The relationship is called an “is-a” relationship and is created using the extends keyword. 🔹 2️⃣ Method Overriding – 4 Important Rules Method overriding means a child class inherits a method and changes its implementation. Always use @Override for better readability and compile-time checking. Rule 1 – Access Modifier The child method must have same or higher visibility. Visibility order: private → default → protected → public Example: If parent method is protected, child can use: ✔ protected ✔ public ❌ default ❌ private Rule 2 – Return Type Return type must normally be same as parent method. Rule 3 – Covariant Return Type (JDK 5+) Child method can return a subclass type. Example: class Animal {} class Lion extends Animal {} class Base { Animal display() { return new Animal(); } } class Derived extends Base { @Override Lion display() { return new Lion(); } // Valid } ⚠ Works only for objects, not primitives like int, double. Rule 4 – Parameters Parameters must be exactly the same: same number same type same order Only method body changes, not the signature. 🔹 3️⃣ Overriding vs Overloading (Interview Trap) If parent has: display() and child has: display(int a, int b, int c) This is NOT overriding ❌ This is method overloading ✔ Because parameters are different. Using @Override here will give a compile-time error. 🔹 4️⃣ Final Keyword in Java final can be used with variables, methods, and classes. Final Variable Becomes a constant. final float PI = 3.142f; PI = 3.14f; // Error Convention: UPPERCASE_SNAKE_CASE Example: MAX_VALUE, MIN_VALUE Final Method Can be inherited Cannot be overridden Used when behavior must not change in child classes. Final Class A final class cannot be extended. Example: final class Calculator {} class Child extends Calculator {} // Compilation error Examples in Java: String, StringBuilder, StringBuffer, wrapper classes like Integer. 🔹 5️⃣ Static Members and Inheritance Static Variables If child declares the same variable → Variable Hiding Static Methods Static methods cannot be overridden. If same method exists in child → Method Hiding Example: class Parent { static void display() { System.out.println("Parent"); } } class Child extends Parent { static void display() { System.out.println("Child"); // Method hiding } } Using @Override here → ❌ Compilation error #Java #JavaProgramming #OOP #MethodOverriding #MethodOverloading #FinalKeyword #JavaInterviewQuestions #CodingInterview #SoftwareEngineering #LearnJava #100DaysOfCode #Day24
To view or add a comment, sign in
-
-
Basic Java Interview Q&A ✅ 1. What is Java? Java is a high-level, object-oriented, platform-independent programming language. Its “Write Once, Run Anywhere” principle is powered by the Java Virtual Machine (JVM). ✅ 2. Key Features of Java Simple & Secure Object-Oriented Platform Independent (via JVM) Robust & Multithreaded High Performance (with JIT Compiler) ✅ 3. Difference Between JDK, JRE, and JVM JDK (Java Development Kit) → Includes compiler, tools, and JRE. JRE (Java Runtime Environment) → Contains JVM + core libraries. JVM (Java Virtual Machine) → Executes bytecode, platform-dependent. ✅ 4. Four OOP Principles in Java Encapsulation → Data hiding through classes. Inheritance → Reuse properties and methods. Polymorphism → One interface, multiple implementations. Abstraction → Hide implementation details, expose essential features. ✅ 5. Difference Between == and .equals() == → Compares memory references. .equals() → Compares actual values or content. ✅ 6. What is String Immutability? Strings in Java are immutable, meaning once created, they cannot be changed. Any modification results in a new String object in the memory pool. ✅ 7. What is the difference between Array and ArrayList? Array → Fixed size, can store primitives & objects ArrayList → Dynamic size, only stores objects, part of Collections framework ✅ 8. Types of Access Modifiers public → Accessible from anywhere. protected → Accessible within the same package and subclasses. default → Accessible only within the package. private → Accessible only within the same class. ✅ 9. What is Exception Handling? A mechanism to handle runtime errors using keywords: try, catch, finally, throw, and throws. ✅ 10. Checked vs. Unchecked Exceptions Checked → Compile-time (e.g., IOException, SQLException). Unchecked → Runtime (e.g., NullPointerException, ArithmeticException). ✅ 11. What is Garbage Collection? Automatic memory management that removes unused objects from the heap to free memory space. ✅ 12. What is the difference between Overloading and Overriding? Overloading → Same method name, different parameters (Compile-time polymorphism) Overriding → Subclass redefines parent class method (Runtime polymorphism) Follow Programming [Assignment-Project-Coursework-Exam-Report] Helper For Students | Agencies | Companies for more #Java #JavaInterview #CoreJava #OOP #BackendDevelopment #JavaProgramming #CodingInterview #100DaysOfCode
To view or add a comment, sign in
-
✅ *Top Java Interview Questions with Answers: Part-4* ☕ *3️⃣1️⃣ What is the Stream API in Java 8?* Stream API allows functional-style operations on collections. Example: ```java List<String> names = list.stream() .filter(s -> s.startsWith("A")) .collect(Collectors.toList()); ``` It supports map, filter, reduce, sorted, etc., for better performance and readable code. *3️⃣2️⃣ What is Optional in Java 8?* A container to avoid `null`. Helps prevent `NullPointerException`. Example: ```java Optional<String> name = Optional.ofNullable(getName()); name.ifPresent(System.out::println); ``` *3️⃣3️⃣ What are default and static methods in interfaces?* - *Default*: Provide method implementation inside interface. - *Static*: Belongs to interface, not to instance. ```java default void show() { ... } static void log() { ... } ``` *3️⃣4️⃣ What is garbage collection in Java?* Automatic memory management. Unused objects are removed to free up memory. The JVM’s garbage collector handles it. *3️⃣5️⃣ What is the finalize() method?* A method called *before* an object is garbage collected. Deprecated in modern Java. ```java protected void finalize() { ... } ``` *3️⃣6️⃣ What are annotations?* Metadata used to provide information to compiler or runtime. Examples: `@Override`, `@Deprecated`, `@FunctionalInterface`. *3️⃣7️⃣ What is reflection in Java?* Used to inspect classes, methods, and fields at runtime. Example: ```java Class<?> cls = Class.forName("MyClass"); Method[] methods = cls.getDeclaredMethods(); ``` *3️⃣8️⃣ What is serialization and deserialization?* - *Serialization*: Converting an object to a byte stream - *Deserialization*: Reconstructing object from bytes Used for saving/transferring objects ```java implements Serializable ``` *3️⃣9️⃣ What is the transient keyword?* Prevents a field from being serialized. Used when sensitive or temporary data shouldn’t be saved. *4️⃣0️⃣ How does Java handle memory management?* Java uses heap and stack memory. - *Heap*: Stores objects (GC-managed) - *Stack*: Stores method calls and local variables Garbage collector reclaims unused memory automatically. 💬 *Tap ❤️ for Part-5*
To view or add a comment, sign in
-
Day 33 – Types of Inheritance in Java Today let's go deeper into Inheritance in Java, focusing on why we use it and the different types it offers. ---------------------------------------------- 🔹 Why Inheritance? 👉 The primary goal is Code Reusability 👉 Helps in Software Enhancement & Scalability 👉 Supports concepts like Polymorphism & Abstraction ---------------------------------------------- 🔹 Types of Inheritance in Java 📌 Java supports the following: 1️⃣ Single Level Inheritance → One child class inherits from one parent class 2️⃣ Multilevel Inheritance → A chain of inheritance (A → B → C) 3️⃣ Hierarchical Inheritance → Multiple child classes inherit from one parent 4️⃣ Multiple Inheritance (❌ Not supported with classes) → One class inheriting from multiple parents 5️⃣ Hybrid Inheritance → Combination of multiple types (achieved using interfaces in Java,also with class but it's should not be in cyclic from- cause diamond problem) ---------------------------------------------- 🔹 Examples (Simple Understanding) ✔ Single → A → B ✔ Multilevel → A → B → C ✔ Hierarchical → A → B & A → C ---------------------------------------------- 🔹 Important Rule ❌ Java does NOT support Multiple Inheritance using classes 👉 Reason: Diamond Problem (Ambiguity Issue) If a class inherits from two parents having the same method, ➡️ Java won’t know which method to execute This leads to confusion, so Java avoids it. ---------------------------------------------- 🔹 Final Keyword in Inheritance 👉 If a class is declared as final ❌ It cannot be extended final class A {} // class B extends A ❌ Not allowed #Java #OOP #Inheritance #LearningInPublic #Programming #Developers #SoftwareEngineering #JavaFullStack
To view or add a comment, sign in
-
-
💡 Functional Interfaces in Java — Beyond the Basics If you think Functional Interfaces are just about Lambda expressions, you're only scratching the surface. Let’s go deeper 👇 🔹 Recap: What is a Functional Interface? An interface with exactly one abstract method, annotated optionally with "@FunctionalInterface" for clarity and compile-time safety. --- 🔹 Key Characteristics ✔ Can have multiple default and static methods ✔ Enables functional programming style in Java ✔ Works seamlessly with lambda expressions and method references --- 🔹 Custom Functional Interface Example @FunctionalInterface interface Calculator { int operate(int a, int b); } Usage: Calculator add = (a, b) -> a + b; System.out.println(add.operate(5, 3)); // 8 --- 🔹 Lambda vs Method Reference Lambda: (a, b) -> a + b Method Reference: Integer::sum 👉 Cleaner and more reusable when method already exists. --- 🔹 Where are Functional Interfaces Used? 🔥 1. Streams API list.stream() .filter(x -> x > 10) // Predicate .map(x -> x * 2) // Function .forEach(System.out::println); // Consumer 🔥 2. Multithreading new Thread(() -> System.out.println("Running thread")).start(); 🔥 3. Event Handling & Callbacks Used heavily in asynchronous and reactive programming. --- 🔹 Types of Functional Interfaces (Deep View) ✨ Predicate<T> → Boolean conditions Used for filtering data ✨ Function<T, R> → Transformation Convert one form of data to another ✨ Consumer<T> → Performs action Logging, printing, updating ✨ Supplier<T> → Generates data Lazy loading, object creation ✨ BiFunction / BiPredicate → Work with 2 inputs --- 🔹 Why Companies Care? (Interview Insight) ✔ Reduces boilerplate code ✔ Encourages clean architecture ✔ Essential for Spring Boot & Microservices ✔ Frequently used in real-world production code --- 🔹 Common Mistakes to Avoid ❌ Adding more than one abstract method ❌ Ignoring built-in functional interfaces ❌ Overusing lambdas (readability matters!) --- 🔹 Pro Tip for Freshers 🚀 When solving DSA or backend problems, try rewriting logic using: 👉 Lambda expressions 👉 Streams 👉 Built-in functional interfaces This shows modern Java proficiency in interviews. --- 💬 Final Thought: Functional Interfaces are not just a feature—they represent a shift in how Java developers think and write code. Master them, and your code becomes shorter, smarter, and more powerful ⚡ #Java #FunctionalProgramming #Java8 #BackendDeveloper #CodingJourney #SoftwareEngineering #InterviewPrep
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
Great explanation! Static block runs once during class loading, while non-static block runs every time an object is created. Very useful concept.