📘 Java Learning – Types of Variables (Part 2: Static & Local Variables) While strengthening my Core Java fundamentals, I gained clarity on how static and local variables differ in purpose, scope, and memory behavior. Here are my key learnings 👇 ▶️ Static Variables • Used when a variable’s value does not change from object to object • Declared at class level using the static keyword • Only one shared copy exists for the entire class 📌 Any change to a static variable affects all objects. ✅ Memory & Lifecycle • Created during class loading • Destroyed during class unloading • Stored in the Method Area • Scope = class scope ✅ Access • Can be accessed using class name (recommended) • Can also be accessed using object reference • Accessible from both static and instance areas ✅ Initialization • JVM provides default values automatically ▶️ Local Variables • Declared inside methods, constructors, or blocks • Used for temporary requirements • Stored in stack memory ✅ Scope & Lifecycle • Created when the block starts execution • Destroyed when the block ends • Scope limited to the declaring block ✅ Initialization Rules • JVM does not provide default values • Must be initialized before use 📌 Best practice: initialize at the time of declaration. ✅ Modifiers • Only final is allowed • Any other modifier causes a compile-time error ⭐ What I Gained from This • Clear distinction between shared and temporary data • Better understanding of scope and memory management • Strong foundation for writing efficient Java code Understanding static and local variables is essential for building optimized and predictable Java applications. #Java #CoreJava #StaticVariables #LocalVariables #JavaInternals #JavaFullStack #LearningJourney #BackendDeveloper
Java Static & Local Variables: Scope, Memory & Access
More Relevant Posts
-
📘 Java Learning – Exception Handling (Core Concepts) While strengthening my Core Java fundamentals, I learned how exception handling helps applications fail gracefully instead of crashing abruptly. Here’s a practical breakdown 👇 🚨 What is an Exception? An exception is an unwanted and unexpected event that disturbs the normal flow of a program. 🧪 Example: int x = 10 / 0; // ArithmeticException 🎯 Why Exception Handling? Exception handling does not repair the problem. It provides an alternative execution path so the program can continue or terminate properly. 📌 Main goal: Graceful termination of the program 🧠 Runtime Stack Mechanism • JVM creates a runtime stack for every thread • Each method call creates a stack frame • Stack frame contains local variables and method call information • When a method completes, its stack frame is removed • When the thread ends, the stack is destroyed 🧪 Example: void m1() { m2(); } void m2() { System.out.println(10 / 0); } 📌 Exception occurs in m2() → JVM starts stack unwinding. ⚙️ Default Exception Handling in Java When an exception occurs: 1️⃣ Exception object is created with: Exception name Description Stack trace 2️⃣ JVM checks for handling code (try-catch) 3️⃣ If not found: • Current method terminates abnormally • Stack frame is removed • JVM checks the caller method 4️⃣ If main() also doesn’t handle it: • JVM invokes Default Exception Handler 🧪 Output format: ExceptionName: description at ClassName.method(line number) ⭐ Key Takeaways • Exceptions disturb normal program flow • JVM uses runtime stack to track method calls • Default exception handling prints diagnostic details • Proper handling leads to stable and maintainable applications Building strong Java fundamentals — one exception at a time ☕🚀 #Java #CoreJava #ExceptionHandling #JVM #JavaInternals #BackendDeveloper #JavaFullStack #LearningJourney
To view or add a comment, sign in
-
📘 Java Learning Journey — Day 13: Variables & Memory Management Today, I learned about variables and how Java manages memory at runtime. A variable is a memory location used to store values and manipulate data in a program. Every variable is associated with a specific data type, which defines the type of data it can hold. 🔹 Types of Variables in Java 1️⃣ Local Variables Declared inside a method or block Accessible only within that method or block No default values are assigned Memory is allocated in the Stack Segment Memory is deallocated automatically when the method or block execution ends 2️⃣ Instance Variables Declared inside a class, outside any method Accessible throughout the class using object reference Default values are provided by JVM Memory is allocated in the Heap Segment Exists as long as the object exists 🔹 Java Runtime Memory Structure (JRE) When a Java program runs, RAM allocates memory called the Java Runtime Environment (JRE). It consists of four major segments: Code Segment – Stores compiled machine-level (bytecode) instructions Static Segment – Stores static members Stack Segment – Stores local variables and object references Heap Segment – Stores objects and instance variables 🔹 Object Creation & Memory Allocation When execution starts from the main method: Objects are created using the new keyword The object is stored in the Heap Segment The reference variable is stored in the Stack Segment Example: Demo d = new Demo(); Here, new instructs the JVM to create an object in heap memory, while d holds the reference in stack memory. 🚀 This session helped me clearly understand variable scope, lifetime, and JVM memory allocation, which are crucial for writing efficient and optimized Java programs. #Java #CoreJava #Variables #JVM #MemoryManagement #LearningJourney #SoftwareDevelopment
To view or add a comment, sign in
-
-
📘 Java Learning – HAS-A Relationship (Composition & Aggregation) While strengthening my Core Java fundamentals, I explored the HAS-A relationship, which focuses on how objects collaborate rather than inherit behavior. This concept plays a key role in designing flexible and reusable systems. 🔰 What is HAS-A Relationship? A HAS-A relationship means one class uses another class as part of its functionality. 📌 HAS-A is implemented using object references, often created using the new keyword or passed from outside. 📌 There is no special keyword like extends for HAS-A. ▶️ Why HAS-A Relationship? • Encourages code reusability • Supports modular design • Reduces tight inheritance hierarchies 🧪 Example: class Engine { void start() { System.out.println("Engine started"); } } class Car { Engine engine = new Engine(); // HAS-A relationship } 📌 Car has an Engine. 🔰 Composition vs Aggregation HAS-A can be implemented in two ways 👇 🔒 Composition (Strong Association) • Contained object cannot exist without the container • If container is destroyed → contained object is also destroyed • Strong lifecycle dependency 🧪 Example: class Engine { } class Car { private Engine engine = new Engine(); } 📌 Without Car, Engine has no independent existence. 🔗 Aggregation (Weak Association) • Contained object can exist independently • Container only holds a reference • Weak lifecycle dependency 🧪 Example: class Engine { } class Car { Engine engine; Car(Engine engine) { this.engine = engine; } } 📌 Engine can exist even if Car is destroyed. ⚠️ Things to Consider While Using HAS-A • Can increase dependency between classes • May lead to maintenance challenges if overused 📌 Hence, design should balance reuse vs coupling. ⭐ Key Takeaways • HAS-A = object collaboration • Composition → strong association • Aggregation → weak association • Prefer HAS-A over inheritance when behavior reuse is needed Designing with the right relationships leads to cleaner, scalable, and maintainable Java applications 🚀 #Java #CoreJava #OOP #HasARelationship #Composition #Aggregation #JavaInternals #JavaFullStack #BackendDeveloper #LearningJourney
To view or add a comment, sign in
-
📘 Java Learning Journey — Day 10, 11 & 12 Over the past few sessions, I deepened my understanding of some fundamental Java concepts that play a crucial role in writing efficient and reliable programs. 🔹 Day 10: Typecasting in Java Typecasting is the process of converting one data type into another. Java supports two types of typecasting: 1️⃣ Implicit Typecasting (Widening) This occurs when a smaller data type is automatically converted into a larger data type by the JVM. Example: byte → int → float → double No data loss occurs because the destination type has a wider range. Real-world analogy: Think of pouring water from a small bucket into a big bucket — it fits perfectly without spilling. 2️⃣ Explicit Typecasting (Narrowing) This is the manual conversion of a larger data type into a smaller data type using casting syntax. Here, loss of precision may occur, which is known as truncation. Real-world analogy: Trying to pour water from a big bucket into a small bucket — overflow is unavoidable unless you limit the quantity. 🔹 Day 11: Increment & Decrement Operators I explored pre-increment (++a) and post-increment (a++), and how their behavior differs during execution. An interesting observation was with byte overflow: A byte ranges from -128 to 127 Incrementing beyond 127 causes the value to wrap around to -128 This happens at runtime, not during compilation This highlights how Java handles arithmetic operations internally during execution. 🔹 Day 12: Execution Behavior & Data Overflow Understanding how Java manages data at runtime helped clarify: Why arithmetic operations on smaller data types are promoted to int How overflow occurs silently during execution The importance of choosing the right data type for accuracy and safety 🚀 These concepts strengthened my foundation in Java and improved my understanding of how the JVM handles data behind the scenes. #Java #CoreJava #TypeCasting #IncrementDecrement #ProgrammingBasics #LearningJourney #SoftwareDevelopment #JVM
To view or add a comment, sign in
-
-
📘 Java Learning – Polymorphism (Part 2: Runtime Polymorphism / Method Overriding) While strengthening my Core Java fundamentals, I learned how Method Overriding allows the same method to behave differently at runtime, making programs more flexible and extensible. ▶️ What is Method Overriding? When a child class provides its own implementation of a parent class method using the same method signature. 📌 Method signature = method name + argument list (Return type is not part of the method signature) 🔰 Why Method Overriding? Method overriding enables runtime polymorphism, where the JVM resolves method calls at runtime based on the actual object, not the reference type. ➡️ Hence, overriding is also called: • Runtime polymorphism • Dynamic polymorphism • Late binding • Dynamic method dispatch 🧪 Example: class Parent { void show() { System.out.println("Parent"); } } class Child extends Parent { void show() { System.out.println("Child"); } } Parent p = new Child(); p.show(); // Output: Child 📌 Even though the reference type is Parent, the Child’s method executes at runtime. 📌 Key Observations • Method names and arguments must match • Covariant return types are allowed (object types only) • Final methods cannot be overridden • Private methods are not overridden • Access modifier scope can be increased but not reduced • Static methods result in method hiding, not overriding • Overriding applies only to methods, not variables ⭐ What I Gained from This • Clear understanding of runtime method resolution • Strong clarity on object-based method execution • Better insight into Java’s dynamic behavior Method overriding plays a key role in achieving true polymorphism in Java. Continuing to strengthen my Core Java & OOPS fundamentals step by step. #Java #CoreJava #OOPS #Polymorphism #MethodOverriding #LearningByDoing
To view or add a comment, sign in
-
📘 Java Learning – Types of Variables (Part 1: Primitive, Reference & Instance Variables) While strengthening my Core Java fundamentals, I focused on understanding how variables are classified in Java and how instance variables behave internally at runtime. Here are my key learnings 👇 ✅ Classification Based on Type of Value Represented ▶️ Primitive Variables • Used to store primitive values • Stores actual data 🧪 Example: int x = 10; ▶️ Reference Variables • Used to refer to objects • Stores the reference (address) of the object, not the actual data 🧪 Example: Student s = new Student(); 📌 Here, s is a reference variable pointing to a Student object. ✅ Classification Based on Purpose & Position of Declaration Based on where and why variables are declared, they are divided into: 1️⃣ Instance variables 2️⃣ Static variables 3️⃣ Local variables 📌 (In this post, focusing only on Instance Variables) ✅ Instance Variables • If the value of a variable changes from object to object, it is called an instance variable • For every object, a separate copy of instance variables is created ✅ Memory & Lifecycle • Instance variables are created at the time of object creation • They are destroyed when the object is destroyed • Scope of instance variables is exactly the same as the object • Stored as part of the object in heap memory ✅ Declaration Rules Must be declared: • Inside the class • Outside methods, constructors, and blocks ✅ Access Rules • Cannot be accessed directly from a static context • Must be accessed using an object reference 📌 From instance methods, instance variables can be accessed directly. ✅ Initialization • Explicit initialization is not mandatory • JVM automatically provides default values 📌 No garbage values for instance variables. ✅ Alternate Names Instance variables are also known as: • Object-level variables • Attributes ⭐ What I Gained from This • Clear understanding of how data differs between objects • Better clarity on object-level memory allocation Understanding instance variables is essential for designing object-oriented programs where each object maintains its own independent state. #Java #CoreJava #Variables #InstanceVariables #JavaInternals #JavaFullStack #BackendDeveloper #LearningJourney
To view or add a comment, sign in
-
🚀 Java Learning Series | Introduction to Methods in Java Understanding methods is a major milestone in Java programming — it’s where clean design, reusability, and logic come together. Here’s a structured breakdown of what I explored 👇 🔹 2️⃣ Introduction to Methods in Java Methods are used to: ✔ Reuse code ✔ Reduce duplication ✔ Improve readability and maintainability 📌 A method is a block of code that performs a specific task and executes only when it is called. 🔹 3️⃣ Method Declaration Syntax General Syntax: Java modifiers returnType methodName(parameters) { // code to execute return value; } 📌 Important Points: ▪ Return type and return value must be the same or compatible ▪ Applies to both primitive and non-primitive data types ▪ Java enforces this strictly because it is a strongly typed language ▪ return sends the result back to the calling method and ends method execution 🔹 4️⃣ Return Types Discussed Explored multiple return types: void, char, byte, short, int, long, float, double, boolean 💡 Understanding return types helped me clearly see how data flows between methods. 🔹 5️⃣ Method Calling ▪ A method executes only when it is called ▪ Method calling helps reuse logic without rewriting code ▪ Promotes modular and maintainable programs 🔹 6️⃣ Instance Methods vs Static Methods 🔸 Instance Methods ▪ Belong to objects ▪ Require an object to be called 🔸 Static Methods ▪ Belong to the class ▪ No object required ▪ Can be called using the class name or directly within the same class 🔹 7️⃣ Who Calls the main() Method? ▪ The JVM calls the main() method ▪ It must be public and static ▪ During .class file loading, JVM loads main() into memory and starts execution 🔹 8️⃣ Practice Problems on Methods Hands-on practice to strengthen concepts 💻 ✔ Finding sum, difference, product, and division of two numbers ✔ Calculating the square of a number ✔ Finding the sum of squares using call by value 📈 Learning Java step by step — focusing not just on syntax, but on why things work the way they do. Consistency + practice = confidence 💪 #Java #JavaProgramming #JavaMethods #CoreJava #OOP #ProgrammingConcepts #LearningJourney #DeveloperLife
To view or add a comment, sign in
-
🚀 Java Learning Series — Day 10/100 📘 Relational & Logical Operators in Java Today I learned about Relational and Logical operators, which are essential for comparison, validation, and decision-making in Java applications. 🔹 Relational Operators Used to compare values and return a boolean result. == → Checks whether two values are equal != → Checks whether two values are different > → Verifies if the left value is greater than the right < → Verifies if the left value is smaller than the right >= → Checks if a value meets or exceeds a limit <= → Checks if a value is within an allowed range 🔹 Logical Operators Used to combine multiple conditions. && (AND) → True only when all conditions are true || (OR) → True when at least one condition is true ! (NOT) → Reverses the result of a condition 🔐 Real-Time Example: Login Validation 💡 Idea Behind the Example This program simulates a real-world login system where access is granted only when: Username matches Password matches User age is 18 or above Relational operators are used to compare values, while logical operators combine all login rules into a single boolean expression. The final result is stored in a boolean variable, which determines whether the login is successful or failed — without using conditional statements. 📸 (Code image attached below) ✨ Key Takeaways Relational operators handle value comparison Logical operators connect multiple validation rules Boolean expressions can decide outcomes efficiently Widely used in authentication and form validation systems 📌 Day 10 completed successfully! #Java #CoreJava #JavaDeveloper #BackendDevelopment #BackendDeveloper #SoftwareDevelopment #Programming #Coding #CleanCode #Authentication #SystemDesignBasics #ProblemSolving #DeveloperJourney #LearningInPublic #100DaysOfJava # Meghana M # 10000 Coders
To view or add a comment, sign in
-
-
🚀 Day 4 | Core Java Learning Journey 📘 Topic: Data Types, Variables & Operators in Java Continuing my Java learning journey, today I explored data types, variables, wrapper classes, autoboxing/unboxing, and operators—the fundamental building blocks of Java programs. 🔑 Key Concepts Covered Today: 🔹 Data Types in Java • Primitive Types: byte, short, int, long, float, double, char, boolean • Non-Primitive Types: String, Arrays, Classes, Interfaces 🔹 Wrapper Classes & Autoboxing/Unboxing • Each primitive has a wrapper class (e.g., Integer for int, Double for double) • Autoboxing: primitive → wrapper object automatically • Unboxing: wrapper object → primitive automatically 🔹 Variables in Java Variables are containers for data. Types of Variables: • Local: Inside methods; accessible only there • Instance: Each object has its own copy • Static/Class: Shared across all objects • Final/Constant: Value cannot change; constants usually static final • Global: Simulated using static variables 🔹 Operators in Java (overview only) Operators perform operations on variables/values: • Arithmetic: +, -, *, /, %, ++, -- • Relational: ==, !=, >, <, >=, <= • Logical: &&, ||, ! • Bitwise: &, |, ^, ~, <<, >>, >>> • Assignment: =, +=, -=, etc. • Ternary: condition ? trueValue : falseValue • instanceof: checks object type 📌 Why this matters: Understanding data types, variables, and operators is the foundation of Java. Strong grip here makes OOP, collections, and advanced concepts much easier. Special thanks to my mentor Vaibhav Barde for guiding me through these concepts. #Java #CoreJava #Variables #DataTypes #WrapperClasses #Autoboxing #Unboxing #Operators #JavaProgramming #FinalVariables #Constants #LearningJourney #BackendDevelopment #DailyLearning
To view or add a comment, sign in
-
-
Day 2 – Learning Java Full Stack Java may look simple on the surface, but today I learned what actually happens behind the scenes when a Java program runs. Here’s a clear breakdown of my learning 👇 🔹 Execution of a Java Program A Java program follows a two-step process: 1️⃣ Compilation 2️⃣ Interpretation (Execution) 🔹 Step 1: Compilation Java source code must be saved with a .java extension The javac compiler checks for syntax errors If a syntax error exists → compile-time error (bytecode is NOT generated) If no errors → bytecode (.class file) is generated Important: Without successful compilation, execution never happens. 🔹 Step 2: JVM Verification & Execution Once bytecode is generated, JVM performs multiple checks: ✔️ Confirms bytecode is generated by javac ✔️ Verifies bytecode is not modified ✔️ Checks for logical errors during execution If all checks pass → ➡️ JVM converts bytecode into machine code and executes it. If a logical error occurs → ➡️ Exception is raised, and execution stops immediately. 🔹 Understanding Exceptions with Examples Division by zero → ArithmeticException When an exception occurs: Statements before the error execute Statements after the error do NOT execute 🔹 Key Commands I Practiced javac Demo.java → compilation java Demo → execution And revisited the basic structure: Class declaration main() method → entry point of execution Key takeaway: Java doesn’t blindly execute code. It verifies, validates, and protects execution through compiler checks, JVM verification, and exception handling. Sharing my learning as I go — hoping this helps someone understand Java execution more clearly 🙌 More insights coming soon. #Java #JavaFullStack #JVM #ExceptionHandling #LearningInPublic #BackendDevelopment #ProgrammingBasics
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