Day 21 – Accessing Non-Static Members of a Class in Java Yesterday I explored static members in Java. Today’s concept was the opposite side of it: 👉 Non-Static Members (Instance Members) Unlike static members, non-static members belong to objects, not the class itself. That means we must create an object of the class to access them. 🔹 Syntax new ClassName().memberName; or ClassName obj = new ClassName(); obj.memberName; 🔹 Example class Demo4 { int x = 100; int y = 200; void test() { System.out.println("running test() method"); } } class MainClass2 { public static void main(String[] args) { System.out.println("x = " + new Demo4().x); System.out.println("y = " + new Demo4().y); new Demo4().test(); } } Output x = 100 y = 200 running test() method 🔹 Important Observation Every time we write: new Demo4() ➡️ A new object is created. Each object has its own copy of non-static variables. This is why instance variables are object-specific, unlike static variables which are shared across objects. 📌 Key takeaway • Static members → belong to the class • Non-static members → belong to objects • Accessing instance members requires object creation Understanding this concept is essential for mastering Object-Oriented Programming in Java. Step by step building stronger Core Java fundamentals. #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
Accessing Non-Static Members in Java: Instance Variables and Methods
More Relevant Posts
-
Day 38 - 🚀 Understanding toString() in Java In Java, the toString() method is used to return a string representation of an object. It belongs to the Object class, which means every Java class inherits it by default. 📌 Default Behavior If you don't override toString(), Java prints a combination of class name + hashcode. class Person { String name; int age; } Person p = new Person(); System.out.println(p); Output: Person@1a2b3c This output is usually not very useful for users or developers. 📌 Overriding toString() To display meaningful object information, we override the toString() method. class Person { String name; int age; @Override public String toString() { return "Person[name=" + name + ", age=" + age + "]"; } } Output: Person[name=John, age=25] 📌 Why toString() is Important ✔ Provides a human-readable representation of objects ✔ Useful for debugging and logging ✔ Makes object data easier to print and understand 💡 Pro Tip Always use the @Override annotation when implementing toString() to ensure the method is correctly overridden. ✅ Conclusion The toString() method helps convert an object into a clear and readable string format, making debugging and displaying data much easier in Java applications. #Java #OOP #JavaProgramming #ToString #ProgrammingConcepts #SoftwareDevelopment
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
-
-
📌 Lambda Expressions in Java — Writing Cleaner Code Lambda expressions allow writing concise and readable code by replacing anonymous classes. They are built on functional interfaces. 1️⃣ What Is a Lambda Expression? A lambda is an anonymous function: • No name • No return type declaration • Shorter syntax Syntax: (parameters) -> expression --- 2️⃣ Traditional vs Lambda Before Java 8: Runnable r = new Runnable() { public void run() { System.out.println("Hello"); } }; With Lambda: Runnable r = () -> System.out.println("Hello"); --- 3️⃣ Syntax Variations • No parameter: () -> System.out.println("Hi") • One parameter: x -> x * 2 • Multiple parameters: (a, b) -> a + b • Multi-line: (a, b) -> { int sum = a + b; return sum; } --- 4️⃣ Why Lambda Is Powerful ✔ Reduces boilerplate code ✔ Improves readability ✔ Enables functional programming ✔ Works seamlessly with Streams --- 5️⃣ Where Lambdas Are Used • Collections (sorting, filtering) • Streams API • Multithreading (Runnable, Callable) • Event handling Example: list.forEach(x -> System.out.println(x)); --- 6️⃣ Important Rule Lambda works only with: ✔ Functional Interfaces (single abstract method) --- 🧠 Key Takeaway Lambda expressions simplify code by focusing on *what to do*, not *how to implement it*. They are the foundation of modern Java programming. #Java #Java8 #Lambda #FunctionalProgramming #BackendDevelopment
To view or add a comment, sign in
-
💻 Understanding Buffer Problem & Wrapper Classes in Java While working with Java input using scanner, many beginners face a tricky issue called the Buffer Problem when using Scanner. What happens? --->>When you use nextInt() or nextFloat(), it reads only the number and leaves the newline (\n) in the buffer. --->>So the next nextLine() gets skipped unexpectedly! ~Quick Fix: Always clear the buffer: int n = scan.nextInt(); scan.nextLine(); // clear buffer String name = scan.nextLine(); 🔄 Wrapper Classes in Java Java provides Wrapper Classes to convert primitive data types into objects. @Examples: int → Integer float → Float char → Character #These are super useful when: ✔ Converting String → primitive ✔ Working with collections (like ArrayList) ✔ Using built-in utility methods 🌍 Real-Time Example Imagine a job application system: User input: 101,John,50000 **To process this** 👇 String[] data = input.split(","); int id = Integer.parseInt(data[0]); String name = data[1]; int salary = Integer.parseInt(data[2]); Here, Wrapper Classes help convert text into usable data types. #Key Takeaways ✔ Always clear buffer when mixing nextInt() & nextLine() ✔ Wrapper classes make data conversion easy ✔ Essential for real-world input handling & backend systems #Mastering these small concepts builds a strong foundation in Java! TAP Academy #Java #Programming #OOP #JavaDeveloper #Coding #SoftwareDevelopment #LearnJava
To view or add a comment, sign in
-
-
🔍 HashMap Internal Working in Java (Simple Explanation) HashMap is one of the most commonly used data structures in Java for storing key-value pairs. Understanding how it works internally helps in writing better and more efficient code. Let’s break it down step by step. 💡 What is HashMap? HashMap stores data in key-value pairs and provides O(1) average time complexity for insertion and retrieval. ⚙️ How HashMap Works Internally When we insert data: map.put("user", 101); Internally, the following steps happen: 1️⃣ Hash Generation Java generates a hash for the key using the hash function. 2️⃣ Bucket Index Calculation Index is calculated using: index = hash & (n - 1) where n = number of buckets 3️⃣ Store in Bucket The value is stored in a bucket as a node: (key, value, hash) 4️⃣ Collision Handling If multiple keys map to the same bucket: 1. Stored using Linked List 2. Converted to Red-Black Tree when bucket size becomes large (Java 8) 5️⃣ Get Operation When map.get(key) is called: Hash is generated again Bucket index is found Linked List / Tree is searched Value is returned 📦 Important Internal Properties • Default Capacity = 16 • Load Factor = 0.75 • Resize happens when: size > capacity × loadFactor • On resize, capacity doubles and rehashing happens • Java 8 uses Red-Black Tree for better performance in collisions 📌 Time Complexity Average - O(1) for Get, Put and Remove operations Worst - O(n) for Get, Put and Remove operations (In Java 8 worst case improves to O(log n) due to Red black trees) 🧠 Rule of Thumb HashMap performance comes from hashing, bucket indexing, and efficient collision handling. 👉 If you are preparing for Java backend interviews, connect & follow - I share short, practical backend concepts regularly. #Java #HashMap #DataStructures #BackendDevelopment #JavaDeveloper #Programming
To view or add a comment, sign in
-
-
Generic Classes in Java – Clean Explanation with Examples 🚀 Generics in Java are a compile-time type-safety mechanism that allows you to write parameterized classes, methods, and interfaces. Instead of hardcoding a type, you define a type placeholder (like T) that gets replaced with an actual type during usage. 🔹Before Generics (Problem): class Box { Object value; } Box box = new Box(); box.value = "Hello"; Integer x = (Integer) box.value; // Runtime error ❌ Issues: • No type safety • Manual casting required • Errors occur at runtime 🔹With Generics (Solution): class Box<T> { private T value; public void set(T value) { this.value = value; } public T get() { return value; } } 🔹Usage: public class Main { public static void main(String[] args) { Box<Integer> intBox = new Box<>(); intBox.set(10); int num = intBox.get(); // ✅ No casting Box<String> strBox = new Box<>(); strBox.set("Hello"); String text = strBox.get(); } } 🔹Bounded Generics: 1.Upper Bound (extends) → Read Only: Restricts type to a subclass List<? extends Number> list; ✔ Allowed: Integer, Double ❌ Not Allowed: String 👉 Why Read Only? You can safely read values as Number, but you cannot add specific types because the exact subtype is unknown at compile time. 2.Lower Bound (super) → Write Only: Restricts type to a superclass List<? super Integer> list; ✔ Allowed: Integer, Number, Object ❌ Not Allowed: Double, String 👉 Why Write Only? You can safely add Integer (or its subclasses), but when reading, you only get Object since the exact type is unknown. 🔹Key Takeaway: Generics = Type Safety + No Casting + Compile-Time Errors Clean code, fewer bugs, and better maintainability - that’s the power of Generics 💡 #Java #Generics #Programming #SoftwareEngineering #Coding
To view or add a comment, sign in
-
Java Garbage Collection: Things Many Developers Don’t Realize When we start learning Java, Garbage Collection (GC) is often explained very simply: "Java automatically removes unused objects from memory." While that statement is true, the reality inside the JVM is much more interesting. After working with Java and studying JVM behavior, I realized there are several important things many developers overlook. Here are a few insights about Java Garbage Collection: 🔹 1. Objects are not removed immediately Just because an object is no longer used doesn’t mean it is deleted instantly. Garbage Collection runs periodically, and the JVM decides when it is the right time to clean memory. 🔹 2. GC is based on Reachability, not null values Setting an object to "null" doesn’t automatically delete it. An object becomes eligible for GC only when no references point to it anymore. Example: User user = new User(); user = null; Now the object may become eligible for GC. But the JVM will clean it later when GC runs. 🔹 3. Most objects die young In real applications, many objects exist only for a short time. Because of this, the JVM uses Generational Garbage Collection: • Young Generation → short-lived objects • Old Generation → long-lived objects This design makes memory management more efficient. 🔹 4. "System.gc()" does not guarantee GC Many developers think calling this will force GC: System.gc(); But in reality, it only suggests the JVM run GC. The JVM may still ignore it. 🔹 5. Memory leaks can still happen in Java Even with automatic garbage collection, memory leaks can occur if objects are still referenced. Common examples: • Static collections holding objects • Unclosed resources • Caches without eviction policies Key takeaway... Garbage Collection is one of the biggest reasons Java is reliable for large-scale systems. But understanding how the JVM actually manages memory helps developers write more efficient and scalable applications. Curious to hear from other developers: What was the most surprising thing you learned about Java Garbage Collection? #Java #JVM #GarbageCollection #BackendDevelopment #SoftwareEngineering #JavaDeveloper
To view or add a comment, sign in
-
#Java strings are length-prefixed objects, not null-terminated sequences, it is a deliberate move towards safer and more predictable string handling, if you were hoping for a hidden \0 at the end, I’m afraid Java decided that was someone else’s problem decades ago. Java strings are not null terminated, they are instances of String, not raw character arrays with a sentinel value tacked on the end, instead of scanning memory until a zero byte shows up, Java stores the length explicitly as part of the object state so when you call length(), the JVM does not go hunting for a terminator like it is 1972, it simply reads a field. This design choice is not just aesthetic, it is architectural, in C-style null terminated strings, determining length is an O(n) operation because you must traverse until \0 appears. Java avoids that entirely, length is O(1), which is exactly what you want in a language that pretends to care about abstraction and performance. Internally, Java strings are backed by arrays, historically char[] and more recently byte[] with a coder flag for compact storage, the crucial detail is that the array is paired with metadata, including length, so the runtime always knows the bounds without relying on a terminator. In Java, the null character \u0000 is just another character, you can place it in the middle of a string and nothing dramatic happens, no truncation, no existential crisis, this alone makes null termination impractical as a contract, since the language explicitly allows that value inside strings. Null terminated strings have a long and rather embarrassing history of buffer overflows and off-by-one errors because developers forget to allocate space for the terminator or fail to write it, java sidesteps the entire category by design, no terminator, no dependency on sentinel correctness, fewer ways to shoot yourself in the foot. There is, however, a trade-off, when interfacing with native code via JNI, you cannot assume Java strings behave like C strings, you must pass both pointer and length explicitly or use conversion helpers, aka, the #JVM will not indulge your nostalgia for null termination. https://lnkd.in/dmKXUtGf
To view or add a comment, sign in
-
Think var in Java is just about saving keystrokes? Think again. When Java introduced var, it wasn’t just syntactic sugar — it was a shift toward cleaner, more readable code. So what is var? var allows the compiler to automatically infer the type of a local variable based on the assigned value. Instead of writing: String message = "Hello, Java!"; You can write: var message = "Hello, Java!"; The type is still strongly typed — it’s just inferred by the compiler. Why developers love var: Cleaner Code – Reduces redundancy and boilerplate Better Readability – Focus on what the variable represents, not its type Modern Java Practice – Aligns with newer coding standards But here’s the catch: Cannot be used without initialization Only for local variables (not fields, method params, etc.) Overuse can reduce readability if the type isn’t obvious Not “dynamic typing” — Java is still statically typed Pro Insight: Use var when the type is obvious from the right-hand side — avoid it when it makes the code ambiguous. Final Thought: Great developers don’t just write code — they write code that communicates clearly. var is a tool — use it wisely, and your code becomes not just shorter, but smarter. Special thanks to Syed Zabi Ulla and PW Institute of Innovation for continuous guidance and learning support. #Java #Programming
To view or add a comment, sign in
-
-
Day 22 – Reference Variables in Java Today I explored an important concept in Object-Oriented Programming — Reference Variables. Unlike primitive variables, reference variables store the address of an object, not the actual value. 🔹 What is a Reference Variable? A reference variable is a non-primitive variable that refers to an object created from a class. It is declared using the class name. Syntax: ClassName referenceVariable; Initialization- referenceVariable = new ClassName(); Or both together: ClassName referenceVariable = new ClassName(); Here: ClassName → Name of the class referenceVariable → Object reference new → Keyword used to create an object ClassName() → Constructor 🔹 Example class Demo5 { int x = 100; int y = 200; } class MainClass3 { public static void main(String[] args) { Demo5 d1 = new Demo5(); System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); System.out.println("modifying x & y"); d1.x = 300; d1.y = 400; System.out.println("x = " + d1.x); System.out.println("y = " + d1.y); } } Output: x = 100 y = 200 modifying x & y x = 300 y = 400 🔹 Important Observation When we write: Demo5 d1 = new Demo5(); Java performs three things: 1️⃣ Creates a reference variable (d1) 2️⃣ Creates a new object in memory 3️⃣ Stores the object reference in the variable #Java #CoreJava #JavaFullStack #OOP #Programming #BackendDevelopment #LearningInPublic #SoftwareDevelopment
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