Java Programming: History, Features & Basics
Java Programming: History, Features & Basics
Java and World Wide Web, Web Browsers, Hardware and Software Requirements, Java Support
Systems, Java Environment. Overview of Java Language: Introduction, Structure of Java
program, Implementing a Java Program, Java Virtual Machine, Command Line Arguments,
Programming Style. Constants, Variables, and Data Types: Introduction, Tokens, Constants,
Variables, Data Types, Declaration of Variables, Giving Values to Variables, Scope of
Variables, Symbolic Constants, Type Conversions, Getting Values of Variables, Standard
Default Values, Operators and Expressions: Introduction, Arithmetic Operators, Relational
Operators, Logical Operators, Assignment Operators, Increment and Decrement Operators,
Conditional Operators, Bitwise Operators, Special Operators, Arithmetic Expressions,
Evaluation of Expressions, Precedence of Arithmetic Operators, Associativity, Mathematical
Functions. Decision making and branching: if and switch statements, Decision making and
looping: The while, do while and for loops, Jumps in Loops Labeled Loops.
Introduction to Java
Java History
Java Features
• Definition: Key distinctions in language design, philosophy, and features between Java
and C.
• Differences:
Feature C Java
Paradigm Procedural Object-Oriented
Platform-dependent (compiled to
Platform Platform-independent (WORA)
native code)
Memory
Manual (malloc(), free()) Automatic (Garbage Collection)
Mgmt.
Pointers Explicitly supported No explicit pointers (references instead)
Multiple
Supported (though complex) Not directly supported (via interfaces)
Inher.
Operator
Supported Not supported
Over.
Goto Stmt. Supported Not supported
Exception Hdl. No built-in Robust try-catch mechanism
Threads No built-in Built-in support for multithreading
Compiles to bytecode (interpreted by
Compilation Compiles to machine code
JVM)
public static void main(String[]
Main Function main() args)
Java and Internet
• Definition: How Java contributed to and integrated with the World Wide Web.
• Contribution:
o Applets: Small Java programs embedded in web pages, providing dynamic and
interactive content that HTML alone couldn't. (Largely deprecated now due to
security concerns and advancements in client-side technologies like JavaScript).
o Servlets & JSPs: Core technologies for server-side web development, enabling
dynamic web pages, handling user requests, and connecting to databases. These
form the backbone of many enterprise web applications.
o Java EE (Enterprise Edition): A robust platform for building large-scale,
distributed enterprise applications, widely used in e-commerce, banking, and
other industries.
Web Browsers
• Definition: The minimum specifications needed to develop and run Java applications.
• Hardware:
o Processor: Any modern CPU (Intel i3/i5/i7/i9, AMD Ryzen, etc.).
o RAM: Minimum 4GB, 8GB or more recommended for development with IDEs.
o Disk Space: Several GBs for JDK, IDE, and project files.
• Software:
o Operating System: Windows, macOS, Linux (most modern versions).
o Java Development Kit (JDK): Essential for compiling and running Java
programs. Includes JRE, compiler (javac), debugger, etc.
o Integrated Development Environment (IDE) - Optional but Recommended:
Eclipse, IntelliJ IDEA, NetBeans. These provide tools for coding, debugging, and
project management.
o Text Editor: (Alternative to IDE for simple programs) Notepad++, VS Code,
Sublime Text.
• Definition: The ecosystem of tools, libraries, and frameworks that enhance Java
development.
• Examples:
o Build Tools: Maven, Gradle (for managing project dependencies and build
processes).
o Testing Frameworks: JUnit, TestNG (for unit testing).
o Logging Frameworks: Log4j, SLF4J, Logback.
o Web Frameworks: Spring, Jakarta EE (formerly Java EE), Struts, JSF.
o Database Connectivity: JDBC (Java Database Connectivity) API.
o Version Control: Git, SVN.
Java Environment
• Definition: The complete setup required to develop and execute Java applications.
• Components:
1. Java Development Kit (JDK): The core set of tools for Java development.
▪ Java Runtime Environment (JRE): Contains the JVM, core classes, and
supporting files needed to run Java programs.
▪ Java Virtual Machine (JVM): An abstract machine that provides the
runtime environment for Java bytecode.
▪ Compiler (javac): Converts Java source code (.java files) into bytecode
(.class files).
▪ Debugger (jdb): For finding and fixing errors.
▪ Archiver (jar): For packaging Java classes and resources into a single
JAR file.
2. Path and Classpath Configuration: Environment variables that tell the OS
where to find Java executables and class files.
3. Integrated Development Environment (IDE): (As mentioned above) Provides a
rich development experience.
Introduction
• Definition: The typical organization and components of a basic Java source file.
• Structure:
Java
• Explanation:
1. Package Declaration: Organizes classes into namespaces. package
packageName;
2. Import Statements: Allows using classes from other packages without fully
qualifying their names. import [Link]; or import
packageName.*;
3. Class Definition: All Java code resides within classes. public class ClassName {
... }
4. Main Method: The starting point of execution for any standalone Java
application. public static void main(String[] args) { ... }
▪ public: Access modifier, visible everywhere.
▪ static: Allows the method to be called without creating an object of the
class.
▪ void: Indicates the method does not return any value.
▪ main: The standard name for the entry point method.
▪ String[] args: An array of String objects to receive command-line
arguments.
5. Statements: Individual instructions that perform actions. Terminated by a
semicolon ;.
6. Comments: Used for documentation, ignored by the compiler.
▪ Single-line: // This is a single-line comment
▪ Multi-line: /* This is a multi-line comment */
▪ Javadoc: /** This is a Javadoc comment */
• Definition: The steps involved in writing, compiling, and running a Java program.
• Steps:
1. Write Source Code: Use a text editor or IDE to write Java code and save it with
a .java extension (e.g., [Link]). The class name should match the
filename.
Example ([Link]):
Java
Bash
javac [Link]
Bash
java HelloWorld
▪ Output:
▪ Hello from Java!
Java Virtual Machine (JVM)
• Definition: An abstract machine that provides the runtime environment for Java
bytecode. It's the core component that enables Java's "Write Once, Run Anywhere"
capability.
• Role:
o Interprets Bytecode: Reads and executes the .class files (bytecode).
o Platform Independence: Translates generic bytecode into native machine code
specific to the underlying operating system and hardware.
o Memory Management: Manages memory allocation and deallocation (garbage
collection).
o Security: Enforces security policies.
o Just-In-Time (JIT) Compiler: Optimizes performance by compiling frequently
executed bytecode sections into native machine code during runtime.
• Analogy: Think of the JVM as a universal interpreter that understands Java's
intermediate language (bytecode) and can speak the native language of any computer it's
installed on.
• Definition: Values passed to a Java program when it's executed from the command line.
These values are received by the main method's String[] args parameter.
• Usage:
Example ([Link]):
Java
Bash
javac [Link]
java CmdArgsDemo Hello World 123
• Output:
• Number of arguments: 3
• Arguments received:
• Arg 1: Hello
• Arg 2: World
• Arg 3: 123
Programming Style
• Definition: A set of conventions and guidelines for writing source code that enhances
readability, maintainability, and consistency. While not enforced by the compiler, good
style is crucial for collaborative development and long-term project health.
• Key Principles:
o Meaningful Names: Use descriptive names for variables, methods, and classes
(e.g., numberOfStudents instead of num).
o Indentation: Use consistent indentation (e.g., 4 spaces or 1 tab) to show code
block structure.
o White Space: Use spaces around operators, after commas, and to separate logical
blocks of code.
o Comments: Use comments to explain complex logic, design decisions, or non-
obvious parts of the code.
o Curly Brace Placement: Consistent placement (e.g., K&R style or Allman style).
o Line Length: Keep lines relatively short (e.g., 80-120 characters).
o Class/Method Size: Keep classes and methods focused and reasonably sized.
o Avoid Magic Numbers: Use named constants instead of hardcoded literal values.
o Follow Naming Conventions (CamelCase, PascalCase, SNAKE_CASE):
▪ Classes/Interfaces: PascalCase (e.g., MyClassName)
▪ Methods/Variables: camelCase (e.g., myMethodName,
myVariableName)
▪ Constants: SCREAMING_SNAKE_CASE (e.g., MAX_VALUE)
▪ Packages: lowercase (e.g., [Link])
• Benefits:
o Improved readability and understanding.
o Easier debugging and maintenance.
o Better collaboration among developers.
o Reduced errors.
Introduction
• Definition: Fundamental building blocks of any program, representing pieces of data that
a program manipulates.
• Key Concepts:
o Constants: Fixed values that do not change during program execution.
o Variables: Named memory locations that hold values that can change during
program execution.
o Data Types: Define the type of data a variable can hold and the operations that
can be performed on it.
Tokens
• Definition: The smallest individual units of a program that are meaningful to the
compiler.
• Types of Tokens in Java:
1. Keywords: Reserved words with predefined meanings (e.g., public, class, int, if,
else).
2. Identifiers: Names given to classes, methods, variables, etc., chosen by the
programmer.
3. Literals: Fixed values (constants) written directly in the code (e.g., 100, 3.14, 'A',
"Hello").
4. Operators: Symbols that perform operations on operands (e.g., +, -, *, /, =, >).
5. Separators (Delimiters): Symbols used to organize code (e.g., { }, ( ), [ ], ;, ,, .).
Constants
• Definition: Fixed values that do not change during the execution of a program. They are
also known as literals.
• Types of Constants (Literals):
1. Integer Literals: Whole numbers.
▪ Decimal: 10, 123
▪ Octal (prefix 0): 010 (decimal 8)
▪ Hexadecimal (prefix 0x or 0X): 0xFF (decimal 255)
▪ Binary (prefix 0b or 0B): 0b101 (decimal 5)
▪ Suffix L or l for long: 123L
2. Floating-Point Literals: Numbers with decimal points.
▪ Suffix F or f for float: 3.14f
▪ Suffix D or d for double (default): 3.14 or 3.14d
3. Character Literals: Single characters enclosed in single quotes.
▪ 'A', 'x', '5', '$'
▪ Escape sequences: '\n' (newline), '\t' (tab), '\\' (backslash), '\'' (single
quote), '\"' (double quote)
4. String Literals: Sequences of characters enclosed in double quotes.
▪ "Hello World", "Java Programming"
5. Boolean Literals: Represent truth values.
▪ true, false
6. Null Literal: Represents the absence of an object reference.
▪ null
Variables
• Definition: Named memory locations used to store data. The value stored in a variable
can change during program execution.
• Declaration: Specifying the data type and name of a variable.
• Initialization: Assigning an initial value to a variable.
Data Types
• Definition: Classify the type of data a variable can hold. Java is a strongly typed
language, meaning every variable must have a declared data type.
• Categories:
1. Primitive Data Types (Built-in): Represent basic values directly.
▪ Boolean:
▪ boolean: true or false (1 bit, but JVM often uses 1 byte)
▪ Numeric:
▪ Integer Types: Store whole numbers.
▪ byte: 1 byte (-128 to 127)
▪ short: 2 bytes (-32,768 to 32,767)
▪ int: 4 bytes (-2,147,483,648 to 2,147,483,647) - Default for
integers
▪ long: 8 bytes (-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807)
▪ Floating-Point Types: Store numbers with decimal components.
▪ float: 4 bytes (single-precision)
▪ double: 8 bytes (double-precision) - Default for floating-
points
▪ Character Type:
▪ char: 2 bytes (stores Unicode characters, \u0000 to \uffff)
2. Non-Primitive (Reference) Data Types: Refer to objects. They don't store the
actual value but a memory address (reference) where the object is stored.
▪ String: Represents a sequence of characters.
▪ Arrays: Ordered collections of elements of the same type.
▪ Classes: User-defined blueprints for objects.
▪ Interfaces: Blueprints of a class.
Declaration of Variables
• Definition: The process of creating a variable by specifying its data type and name.
• Syntax: dataType variableName;
• Examples:
Java
int age;
double price;
char grade;
boolean isActive;
String name;
Java
Java
Scope of Variables
• Definition: The region of a program where a variable is accessible and can be used.
Variables are accessible only within the block ({ }) where they are declared.
• Types of Scope:
1. Local Variables: Declared inside a method, constructor, or block. They are
created when the block is entered and destroyed when the block is exited. Must be
explicitly initialized before use.
Java
Java
Java
Symbolic Constants
• Definition: Constants declared using the final keyword. Their value, once assigned,
cannot be changed. Often used with static to create class-level constants.
• Syntax: final dataType CONSTANT_NAME = value; (By convention, static final
constants are in SCREAMING_SNAKE_CASE).
• Example:
Java
• Definition: The process of converting a value from one data type to another.
• Types:
1. Implicit Type Conversion (Widening Conversion / Automatic):
▪ Happens automatically when converting a smaller data type to a larger
one, where no data loss is possible.
▪ Order: byte -> short -> int -> long -> float -> double
▪ Example:
Java
int i = 100;
long l = i; // int to long (implicit)
float f = l; // long to float (implicit, can lose precision for very large
longs)
[Link]("i: " + i + ", l: " + l + ", f: " + f);
Java
double d = 100.99;
int i = (int) d; // double to int (explicit, data loss: .99 is truncated)
byte b = (byte) i; // int to byte (explicit, data loss if i > 127 or i < -128)
[Link]("d: " + d + ", i: " + i + ", b: " + b);
int x = 200;
byte y = (byte) x; // 200 is out of byte range (-128 to 127), will wrap
around
[Link]("x: " + x + ", y: " + y); // y will be -56
Output:
• Definition: How to read input from various sources, typically the console (keyboard).
• Using Scanner Class: The most common way to read input from the console.
• Steps:
1. Import the Scanner class: import [Link];
2. Create a Scanner object: Scanner scanner = new Scanner([Link]);
3. Use Scanner methods to read different data types:
▪ nextInt(): Reads an integer.
▪ nextDouble(): Reads a double.
▪ nextBoolean(): Reads a boolean.
▪ next(): Reads a single word (token) as a String.
▪ nextLine(): Reads an entire line as a String.
• Example:
Java
import [Link];
• Definition: Values that instance variables and static variables (class variables)
automatically get if they are not explicitly initialized. Local variables do not get default
values and must be initialized before use.
• Defaults:
o Numeric Types (byte, short, int, long, float, double): 0 or 0.0
o char: '\u0000' (null character)
o boolean: false
o Reference Types (String, Arrays, Objects): null
• Example:
Java
// int localVar; // Local variable - if not initialized, will cause compile error if used
// [Link](localVar); // COMPILE ERROR: variable might not have been
initialized
int localVar = 10; // OK
[Link]("Local var: " + localVar);
}
}
• Output:
• Instance intVar: 0
• Instance doubleVar: 0.0
• Instance booleanVar: false
• Instance stringVar: null
• Instance charVar (casted to int): 0
• Static intVar: 0
• Local var: 10
Introduction
• Definition:
o Operators: Symbols that perform specific operations on one or more operands.
o Operands: The values or variables on which operators act.
o Expressions: A combination of operators, operands, literals, and method calls
that evaluates to a single value.
Arithmetic Operators
Java
int a = 10, b = 3;
[Link]("a + b = " + (a + b)); // 13
[Link]("a - b = " + (a - b)); // 7
[Link]("a * b = " + (a * b)); // 30
[Link]("a / b = " + (a / b)); // 3 (integer division)
[Link]("a % b = " + (a % b)); // 1
double x = 10.0, y = 3.0;
[Link]("x / y = " + (x / y)); // 3.333...
• Output:
• a + b = 13
• a-b=7
• a * b = 30
• a/b=3
• a%b=1
• x / y = 3.3333333333333335
Relational Operators
• Definition: Used to compare two operands and determine the relationship between them.
They always return a boolean (true/false) value.
• Operators:
o == (Equal to)
o != (Not equal to)
o > (Greater than)
o < (Less than)
o >= (Greater than or equal to)
o <= (Less than or equal to)
• Example:
Java
int p = 5, q = 10;
[Link]("p == q: " + (p == q)); // false
[Link]("p != q: " + (p != q)); // true
[Link]("p > q: " + (p > q)); // false
[Link]("p < q: " + (p < q)); // true
[Link]("p >= 5: " + (p >= 5)); // true
[Link]("q <= 10: " + (q <= 10)); // true
• Output:
• p == q: false
• p != q: true
• p > q: false
• p < q: true
• p >= 5: true
• q <= 10: true
Logical Operators
Java
boolean isSunny = true;
boolean isWarm = false;
• Output:
• isSunny && isWarm: false
• isSunny || isWarm: true
• !isSunny: false
• Num is between 5 and 15 (exclusive).
• Num is negative or greater than 5.
Assignment Operators
Java
int x = 10;
x += 5; // x is now 15 (x = 10 + 5)
[Link]("x after += 5: " + x);
x -= 3; // x is now 12 (x = 15 - 3)
[Link]("x after -= 3: " + x);
x *= 2; // x is now 24 (x = 12 * 2)
[Link]("x after *= 2: " + x);
x /= 4; // x is now 6 (x = 24 / 4)
[Link]("x after /= 4: " + x);
x %= 5; // x is now 1 (x = 6 % 5)
[Link]("x after %= 5: " + x);
• Output:
• x after += 5: 15
• x after -= 3: 12
• x after *= 2: 24
• x after /= 4: 6
• x after %= 5: 1
Java
int a = 5;
int b = a++; // b = 5, a = 6
[Link]("a: " + a + ", b: " + b);
int x = 5;
int y = ++x; // y = 6, x = 6
[Link]("x: " + x + ", y: " + y);
int c = 10;
int d = c--; // d = 10, c = 9
[Link]("c: " + c + ", d: " + d);
int m = 10;
int n = --m; // n = 9, m = 9
[Link]("m: " + m + ", n: " + n);
• Output:
• a: 6, b: 5
• x: 6, y: 6
• c: 9, d: 10
• m: 9, n: 9
• Definition: A shorthand for a simple if-else statement. It's the only ternary operator
(takes three operands).
• Syntax: condition ? expressionIfTrue : expressionIfFalse;
• Example:
Java
• Output:
• Result: Pass
• Maximum: 20
Bitwise Operators
• Definition: Operate on individual bits of integer data types (byte, short, int, long). They
treat operands as sequences of binary bits.
• Operators:
o & (Bitwise AND)
o | (Bitwise OR)
o ^ (Bitwise XOR - exclusive OR)
o ~ (Bitwise NOT / One's Complement - unary)
o << (Left Shift)
o >> (Signed Right Shift)
o >>> (Unsigned Right Shift)
• Example:
Java
int negNum = -8; // Binary (2's complement for -8): 1111 1000
[Link]("negNum >> 1: " + (negNum >> 1)); // 1111 1100 (-4) - preserves
sign bit
[Link]("negNum >>> 1: " + (negNum >>> 1)); // 0111 1100 (2147483644) -
fills with 0s
• Output:
• a & b: 1
• a | b: 7
• a ^ b: 6
• ~a: -6
• num << 1: 16
• num >> 1: 4
• negNum >> 1: -4
• negNum >>> 1: 2147483644
Special Operators
• Definition: Operators that don't fit into the other categories, performing specific roles.
• Operators:
o . (Dot operator): Used to access members (fields and methods) of a class or
object.
▪ [Link](): System class, out object, println() method.
▪ [Link]()
o new operator: Used to create new objects (allocate memory for them).
▪ MyClass obj = new MyClass();
o instanceof operator: Used to check if an object is an instance of a particular class
or an interface. Returns boolean.
▪ if (obj instanceof String)
o [] (Square brackets): Used for array declaration, creation, and accessing array
elements.
▪ int[] numbers = new int[5];
▪ numbers[0] = 10;
o (type) (Cast operator): Already covered in Type Conversions. Used to explicitly
convert one data type to another.
• Example:
Java
String s = "Hello";
[Link]("Length: " + [Link]()); // Dot operator to access method
• Output:
• Length: 5
• myObject is an instance of String.
• First element: 1
Arithmetic Expressions
Evaluation of Expressions
• Definition: The process by which the Java compiler determines the value of an
expression. This follows strict rules of operator precedence and associativity.
Java
• Output:
• 5 + 2 * 3 = 11
• (5 + 2) * 3 = 21
Associativity
• Definition: The direction in which operators of the same precedence are evaluated.
• Rules:
o Most binary operators (arithmetic, relational, logical) are left-to-right
associative.
▪ a - b + c is evaluated as (a - b) + c
o Assignment operators, unary operators, and the conditional operator are right-to-
left associative.
▪ a = b = c is evaluated as a = (b = c)
▪ !true && false is evaluated as (!true) && false
• Example:
Java
int x = 10, y = 5, z = 2;
int res1 = x - y + z; // (10 - 5) + 2 = 5 + 2 = 7
[Link]("x - y + z = " + res1); // Output: 7
• Output:
• x-y+z=7
• x = y = 20; x: 20, y: 20, res2: 20
• Definition: Java provides a built-in Math class in the [Link] package (no import
needed) that offers common mathematical functions and constants.
• Common Methods:
o [Link](num): Absolute value.
o [Link](num): Square root.
o [Link](base, exponent): Power.
o [Link](double/float): Rounds to the nearest long/int.
o [Link](double): Rounds up to the nearest integer.
o [Link](double): Rounds down to the nearest integer.
o [Link](a, b): Returns the smaller of two numbers.
o [Link](a, b): Returns the larger of two numbers.
o [Link]: Value of Pi.
o Math.E: Value of e (base of natural logarithm).
• Example:
Java
• Output:
• Absolute of -10: 10
• Square root of 25.0: 5.0
• 2 to the power of 3: 8.0
• Round 4.6: 5
• Round 4.3: 4
• Ceil 4.1: 5.0
• Floor 4.9: 4.0
• Min(10, 20): 10
• Max(10, 20): 20
• Value of PI: 3.141592653589793
Decision Making and Branching
• Definition: Control flow statements that allow a program to execute different blocks of
code based on certain conditions.
if statement
Java
if (condition) {
// Code to execute if condition is true
}
2. if-else: Executes one block if the condition is true, and another if it's false.
Java
if (condition) {
// Code if true
} else {
// Code if false
}
Java
if (condition1) {
// Code if condition1 is true
} else if (condition2) {
// Code if condition2 is true
} else if (condition3) {
// Code if condition3 is true
} else {
// Code if none of the above conditions are true
}
• Output:
• Grade: B
• Welcome, User!
switch statement
• Definition: Allows a variable to be tested for equality against a list of values (cases). It
provides a more elegant way to handle multiple if-else if conditions when comparing a
single value.
• Syntax:
Java
switch (expression) {
case value1:
// Code block 1
break; // Optional, to exit the switch
case value2:
// Code block 2
break;
// ... more cases
default: // Optional
// Code block if no case matches
break;
}
• Key Points:
o expression can be byte, short, int, char, String, enum, or wrapper classes (Byte,
Short, Integer, Character).
o value must be a literal or a final constant.
o break statement is crucial to prevent "fall-through" (execution of subsequent case
blocks).
o default case is optional and executes if no case matches.
• Example:
Java
switch (dayOfWeek) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday"; // This will be executed
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
case 6:
case 7: // Multiple cases for the same block
dayName = "Weekend";
break;
default:
dayName = "Invalid Day";
break;
}
[Link]("Day " + dayOfWeek + " is: " + dayName); // Output: Day 3 is:
Wednesday
char grade = 'B';
switch (grade) {
case 'A':
[Link]("Excellent!");
break;
case 'B':
[Link]("Good!"); // This will be executed
break;
case 'C':
[Link]("Fair!");
break;
default:
[Link]("Needs improvement.");
}
• Output:
• Day 3 is: Wednesday
• Good!
• Definition: Control flow statements that allow a block of code to be executed repeatedly
as long as a certain condition is met.
Java
while (condition) {
// Code to be executed repeatedly
// Update condition variable (important to avoid infinite loop)
}
• Example:
Java
int count = 1;
[Link]("Counting up using while loop:");
while (count <= 5) {
[Link]("Count: " + count);
count++; // Increment count, otherwise it's an infinite loop
}
• Output:
• Counting up using while loop:
• Count: 1
• Count: 2
• Count: 3
• Count: 4
• Count: 5
• Definition: Similar to the while loop, but the loop body is executed at least once before
the condition is checked. The condition is checked after each iteration.
• Syntax:
Java
do {
// Code to be executed repeatedly
// Update condition variable
} while (condition);
• Example:
Java
int i = 1;
[Link]("\nCounting up using do-while loop:");
do {
[Link]("i: " + i);
i++;
} while (i <= 5);
int j = 10;
[Link]("\nDo-while with false initial condition:");
do {
[Link]("This will print once: " + j);
j++;
} while (j < 5); // Condition is false, but loop runs once
• Output:
• Counting up using do-while loop:
• i: 1
• i: 2
• i: 3
• i: 4
• i: 5
•
• Do-while with false initial condition:
• This will print once: 10
• Definition: Provides a concise way to write loops that need to be executed a specific
number of times. It's ideal when you know the number of iterations beforehand.
• Syntax:
Java
oInitialization: Executed once at the beginning of the loop (e.g., int i = 0;).
oCondition: Evaluated before each iteration. If true, the loop continues; if false, it
terminates.
o Update: Executed after each iteration (e.g., i++).
• Example:
Java
• Output:
• Counting up using for loop:
• k: 1
• k: 2
• k: 3
• k: 4
• k: 5
•
• Counting down using for loop:
• l: 5
• l: 4
• l: 3
• l: 2
• l: 1
•
• Nested for loop (star pattern):
• *
• **
• ***
• Definition: Statements that alter the normal flow of control within loops.
1. break statement:
o Definition: Immediately terminates the innermost loop (or switch statement) and
transfers control to the statement immediately following the loop/switch.
o Example:
Java
o Output:
o Break statement example:
o i: 1
o i: 2
o i: 3
o i: 4
o Loop ended.
2. continue statement:
o Definition: Skips the rest of the current iteration of the innermost loop and
proceeds to the next iteration (evaluates the loop's condition and update
expression).
o Example:
Java
o Output:
o Continue statement example:
o i: 1
o i: 2
o i: 4
o i: 5
Labeled Loops
• Definition: A feature in Java (and some other languages) that allows you to break or
continue from an outer loop when you have nested loops. You assign a label (an
identifier followed by a colon) to the loop you want to target.
• Syntax:
Java
labelName:
loopStatement {
// ...
if (condition) {
break labelName; // Breaks out of the labeled loop
// or
continue labelName; // Continues to the next iteration of the labeled loop
}
}
• Example (break with label):
Java
Output:
Java