this and this() in Java
- this refers to the current object of the class. It is used to access instance variables and methods of the current object, especially when variable names are shadowed.
- this() is used to call another constructor from the same class. It must be the first statement inside a constructor.
super and super() in Java
- super refers to the parent class object. It is used to access variables and methods of the superclass.
- super() is used to call the constructor of the parent class. Like this(), it must also be the first statement in a constructor if used.
Local and Global Variables in Java
Variables in Java are categorized based on their scope and behavior:
1. Local Variables
- Declared inside methods, constructors, or blocks.
- Scope is limited to the block where they are defined.
- Must be initialized before use.
- Stored in the stack memory.
2. Global Variables (Instance and Static)
a. Instance Variables
- Declared inside a class but outside any method.
- Each object has its own copy.
- Stored in the heap memory.
- Can be accessed using
this
.
b. Static Variables
- Declared using the static keyword inside a class.
- Shared across all objects of the class.
- Loaded into the method area at the time of class loading.
- Can be accessed using the class name directly.
Java Memory Management (JVM) – The 5 Memory Areas
Java uses five key memory areas during runtime:
Heap Area
Stores all class instances and objects. Static and non-static fields are stored here.Stack Area
Stores method call stacks and local variables. Each thread has its own stack.Method Area
Contains class-level information like metadata, method definitions, and static variables.Program Counter (PC) Register
Holds the address of the currently executing instruction for each thread.Native Method Stack
Used for native code written in other languages like C/C++ that Java interacts with.
Class Loaders in Java
Class loaders are part of the Java Runtime Environment and are responsible for dynamically loading classes into the JVM during runtime.
Types of Class Loaders:
Bootstrap Class Loader
Loads core Java classes (e.g., java.lang.*).Extension Class Loader
Loads classes from the ext directory of the Java installation.Application (System) Class Loader
Loads classes from the application's classpath.
Class loaders use a parent delegation model, where class loading requests are first passed to the parent before attempting to load themselves.
Code Blocks in Java
Java provides two types of blocks:
- Static Blocks: Executed once when the class is loaded.
- Instance Blocks: Executed every time an object is created, just before the constructor.
Top comments (0)