Java Virtual Machine (JVM):
The Java Virtual Machine (JVM) is an abstract computing machine that enables a
computer to run Java programs. It acts as an interpreter between the compiled Java
bytecode and the underlying hardware, allowing Java applications to be executed on
any platform without modification.
This is often referred to as the "write once, run anywhere" (WORA) principle, meaning
that Java code can be written on one machine and run on any other machine that has a
compatible JVM installed.
How Does the JVM Work?
When you write Java code, it is first compiled into bytecode, which is a platform-
independent code stored in .class files. The JVM then takes this bytecode and translates
it into machine code that the host operating system can understand.
This process involves several key components:
Class Loader: This component loads the .class files into memory. It is responsible for
reading the bytecode and preparing it for execution by verifying and linking the classes.
Execution Engine: This part of the JVM executes the bytecode. It can either interpret
the bytecode line by line or compile it into native machine code using a Just-In-Time (JIT)
compiler for better performance.
Runtime Data Areas: The JVM manages memory for the program's data, including
variables and objects. It allocates memory for these data structures and handles
garbage collection to free up memory that is no longer in use.
-------------------------------------------------------------------------------------------------------------
Labeled Loops:
In Java, labeled loops allow you to give a name (label) to a loop so you can
control which loop to break or continue from, especially when you have nested loops.
Normally:
1,break exits only the innermost loop.
2,continue skips to the next iteration of the innermost loop.
With labels:
1, break labelName; exits the labeled loop directly.
2, continue labelName; jumps to the next iteration of the labeled loop.
Example:
public class Example {
public static void main (String[] args) {
outerLoop: // Label for the outer loop
for (int i = 1; i <= 3; i++) {
[Link]("Outer loop i = " + i);
for (int j = 1; j <= 3; j++) {
[Link](" Inner loop j = " + j);
if (i == 2 && j == 2) {
[Link](" Breaking out of outer loop!");
break outerLoop; // exits both loops
outerLoop2: // Another example with continue
for (int i = 1; i <= 3; i++) {
[Link]("Outer loop i = " + i);
for (int j = 1; j <= 3; j++) {
if (j == 2) {
[Link](" Skipping to next outer loop iteration!");
continue outerLoop2; // skips rest of inner loop and moves to next outer loop iteration
[Link](" Inner loop j = " + j);
}
How This Works
break outerLoop;
Immediately stops the outer loop (and inner loop too).
continue outerLoop2;
Skips the rest of the inner loop and moves to the next iteration of the outer loop.