0% found this document useful (0 votes)
0 views38 pages

OOP With Java Module 1 an Overview of Java - Copy[1]

Module 1 provides an overview of Java and its object-oriented programming principles, including encapsulation, inheritance, and polymorphism. It covers data types, variables, arrays, operators, control statements, and lexical issues, emphasizing Java's strong typing and the importance of type compatibility. The module also includes examples of simple Java programs and explains the usage of various literals and variable declarations.

Uploaded by

gnaneshwaritrmk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views38 pages

OOP With Java Module 1 an Overview of Java - Copy[1]

Module 1 provides an overview of Java and its object-oriented programming principles, including encapsulation, inheritance, and polymorphism. It covers data types, variables, arrays, operators, control statements, and lexical issues, emphasizing Java's strong typing and the importance of type compatibility. The module also includes examples of simple Java programs and explains the usage of various literals and variable declarations.

Uploaded by

gnaneshwaritrmk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

MODULE-1

An Overview of Java: Object-Oriented Programming (Two Paradigms, Abstraction, The Three OOP
Principles), Using Blocks of Code, Lexical Issues (Whitespace, Identifiers, Literals, Comments,
Separators, The Java Keywords).
Data Types, Variables, and Arrays: The Primitive Types (Integers, Floating-Point Types, Characters,
Booleans), Variables, Type Conversion and Casting, Automatic Type Promotion in Expressions, Arrays,
Introducing Type Inference with Local Variables.
Operators: Arithmetic Operators, Relational Operators, Boolean Logical Operators, The Assignment
Operator, The ? Operator, Operator Precedence, Using Parentheses.
Control Statements: Java’s Selection Statements (if, The Traditional switch), Iteration Statements
(while, do-while, for, The For-Each Version of the for Loop, Local Variable Type Inference in a for Loop,
Nested Loops), Jump Statements (Using break, Using continue, return).
Chapter 2, 3, 4, 5

Object-Oriented Programming:
Core of Java: OOP is fundamental to Java; all Java programs are object-oriented
to some degree.
Two Paradigms:
Process-Oriented Model: Focuses on "what is happening" (code acting on data).
Object-Oriented Model: Focuses on "who is being affected" (data controls
access to code).

Abstraction:
Simplifies complexity by managing details through hierarchical classifications.
Example: A car is viewed as a single object, despite being composed of many
subsystems.

Three OOP Principles:


Encapsulation:
- Binds data and code together, protecting them from outside interference.
- Implemented using classes, with public and private access controls.

1|Page OOP with java – Module 1


Inheritance:
- Enables objects to acquire properties of other objects, supporting hierarchical
classification.
- Allows subclasses to inherit attributes from their superclasses.

Polymorphism:
- Allows one interface to be used for a general class of actions.
- Example: Different data types (int, float, char) can use the same stack
operations.

OOP Benefits:
- Encapsulation: Keeps code and data secure and modular.
- Inheritance: Promotes code reusability and manageability.
2|Page OOP with java – Module 1
- Polymorphism: Simplifies code, making it cleaner and more adaptable.

OOP in Java:
- Every Java program utilizes encapsulation, inheritance, and polymorphism.
- Java's built-in class libraries heavily use these principles.

These principles make Java programs more robust, scalable, and maintainable.

A First Simple Program


class Example {
public static void main(String args[]) {
System.out.println("This is a simple Java program.");
}
}

- `class Example {`:


- Declares a new class named `Example`.
- Class: Blueprint for creating objects.

- `public static void main(String args[]) {`:


- `public`: Method is accessible from outside the class.
- `static`: Method belongs to the class, not instances of the class.
- `void`: Method does not return any value.
- `main`: Entry point of the program; Java looks for this method to start execution.
- `String args[]`: Array of strings passed as command-line arguments.

- `System.out.println("This is a simple Java program.");`:


- `System`: Built-in class in the `java.lang` package.
- `out`: Static member of the `System` class, represents the standard output stream.
- `println`: Method that prints the argument passed to it followed by a new line.

- `}`:
- Closes the `main` method and the `Example` class.

A Second Short Program


class Example2 {
public static void main(String args []) {
int num; // this declares a variable called num
num = 100; // this assigns num the value 100
System.out.println("This is num: " + num);
num = num * 2;
System.out.print("The value of num * 2 is ");
System.out.println(num);
3|Page OOP with java – Module 1
}
}

Using Blocks of Code


- Code Blocks:
- Group two or more statements together using curly braces `{}`.
- Create a logical unit that acts as a single statement.
- Usage:
- Can be used in control structures like `if`, `for`, etc.
- Ensures that all statements within the block execute together.

- Example:
- In the `if` statement:
if(x < y) {
x = y;
y = 0;
}
- Both statements execute if `x < y`.

- In the `for` loop:


for(x = 0; x < 10; x++) {
System.out.println("This is x: " + x);
System.out.println("This is y: " + y);
y = y - 2;
}
- All statements within the block execute with each iteration.
- Output:
- Each iteration of the `for` loop outputs values of `x` and `y` with `y` decrementing by 2.
- Purpose:
- Code blocks create logically inseparable units, ensuring multiple statements work together as one.

Lexical Issues
- Java Program Components:
- Java programs consist of whitespace, identifiers, literals, comments, operators, separators, and keywords.
- Whitespace:
- Java is a free-form language, meaning there are no strict rules on indentation.
- Whitespace includes spaces, tabs, and newlines.
- At least one whitespace character is needed between tokens unless separated by an operator or separator.
- Identifiers:
- Names for classes, variables, and methods.
- Can include letters (both cases), numbers, underscores, and dollar signs.
- Cannot begin with a number and are case-sensitive.
- Example valid identifiers: `AvgTemp`, `count`, `a4`, `$test`, `this_is_ok`.
- Invalid identifiers: `2count`, `high-temp`, `Not/ok`.
- Using an underscore (`_`) alone as an identifier is not recommended from JDK 8 onwards.
- Literals:
- Represent constant values directly in the code.
- Examples:
4|Page OOP with java – Module 1
- `100` (integer) - `98.6` (floating-point) - `'X'` (character) - `"This is a test"` (string).
- Can be used wherever a value of their type is required.
- Comments:
- Three types:
- Single-line (`//`) - Multiline (`/* ... */`) - Documentation (`/ ... */`), used to generate HTML
documentation.
- Separators:
- Parentheses `()`: Used in method definitions, invocations, expression precedence, and control statements.
- Braces `{}`: Contain block of code, arrays, classes, methods, and local scopes.
- Brackets `[]`: Declare and dereference arrays.
- Semicolon `;`: Terminates statements.
- Comma `,`: Separates variables and chains statements in `for` loops.
- Period `.`: Separates package names, subpackages, classes, and reference variables from methods.
- Colons `::`: Used in method or constructor references (introduced in JDK 8).

- Java Keywords:
- Java has 50 keywords that are integral to the language structure.
- Examples: `abstract`, `boolean`, `class`, `static`, `void`, `for`, `if`, `public`, `return`, `while`.
- `const` and `goto` are reserved but not used.
- Additional reserved words: `true`, `false`, `null`.
- These keywords cannot be used as identifiers (variable names, class names, method names).

Data Types, Variables, and Arrays


Here are the key points from the chapter in simple note form:
 Data Types, Variables, and Arrays:
o Java supports various data types, used to declare variables and create arrays.
o Java’s approach to data types, variables, and arrays is clean, efficient, and cohesive.
 Java is Strongly Typed:
o Every variable has a specific type.
o Every expression also has a strictly defined type.
o Java’s strong typing contributes to its safety and robustness.
 Type Checking:
o All variable assignments and parameter passing are checked for type compatibility.
o There are no automatic type conversions of incompatible types (unlike some languages).
o The Java compiler enforces strict type compatibility.
 Type Mismatches:
o Any type mismatches result in errors that must be corrected before successful compilation.

This ensures that Java programs are safe and less prone to runtime errors due to improper type usage.

The Primitive Types (Integers, Floating-Point Types, Characters,Booleans)


Java defines eight primitive (simple) data types: `byte`, `short`, `int`, `long`, `char`, `float`, `double`, and
`boolean`. These are categorized into four groups:
1. Integers:
 Includes `byte`, `short`, `int`, `long`.
 Used for whole numbers (both positive and negative).
 All integers in Java are signed, unlike in some languages that support unsigned types.

5|Page OOP with java – Module 1


2. Floating-Point Numbers:
 Includes `float` and `double`.
 Used for numbers with fractional parts (i.e., decimals).
3. Characters:
 The `char` type is used to represent characters (letters, numbers, symbols).
 Java uses **Unicode**, so `char` is a 16-bit type.
4. Boolean**:
 The `boolean` type has only two possible values: `true` and `false`.
 Commonly used for conditional statements like `if` and `for`.
Java is Strongly Typed:
 All variables, expressions, and types are strictly defined.
 Type compatibility is enforced; mismatches cause errors.

Integer Types and Their Ranges:


| Name | Width (Bits) | Range |
| `long` | 64 | –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 |
| `int` | 32 | –2,147,483,648 to 2,147,483,647 |
| `short` | 16 | –32,768 to 32,767 |
| `byte` |8 | –128 to 127 |

Examples:
1. Byte: The smallest integer type (`byte`) is useful when working with raw binary data.
byte b, c;
2. Integer: Most commonly used integer type. Can hold large ranges and is often promoted when evaluating
expressions.
int x = 100;
3. Long: Used when `int` is not large enough to hold the value. Example program:
// Compute distance light travels using long variables.
class Light {
public static void main(String args[]) {
int lightspeed = 186000;
long days = 1000;
long seconds = days * 24 * 60 * 60;
long distance = lightspeed * seconds;
System.out.println("In " + days + " days light will travel about " + distance + " miles.");
}
}

Floating-Point Types:
 float: Single-precision 32-bit.
 double: Double-precision 64-bit, often faster for complex mathematical calculations.
Example:
// Compute the area of a circle using double
class Area {
public static void main(String args[]) {
double pi = 3.1416;
double r = 10.8;
double a = pi * r * r;
System.out.println("Area of circle is " + a);
6|Page OOP with java – Module 1
}
}

Character Type (`char`):


 Java uses Unicode, and `char` is 16 bits wide, unlike C/C++ where `char` is 8 bits.
Example:
class CharDemo {
public static void main(String args[]) {
char ch1 = 88; // ASCII for 'X'
char ch2 = 'Y';
System.out.println("ch1 and ch2: " + ch1 + " " + ch2);
}
}

Boolean Type:
 `boolean` type can only hold `true` or `false`. Used in control flow and comparisons.
Example:
// Demonstrate boolean values
class BoolTest {
public static void main(String args[]) {
boolan b = false;
System.out.println("b is " + b);
b = true;
System.out.println("b is " + b);
// Boolean controlling an if statement
if(b) System.out.println("This is executed.");
// Boolean result of a relational operator
System.out.println("10 > 9 is " + (10 > 9));
}
}

Key Points:
- Primitive types are efficient and represent single values.
- Java’s strict type definitions allow for platform-independent data sizes.
- Arithmetic operations and expressions may involve implicit type promotions.

Literals in Java
1. Integer Literals:
 Decimal: Any whole number like `1, 42`, etc.
 Octal: Starts with a `0`, valid digits range from `0-7` (e.g., `07`).
 Hexadecimal: Starts with `0x` or `0X`, uses `0-9` and `A-F` (e.g., `0x7F`).
 Binary** (JDK 7+): Starts with `0b` or `0B` (e.g., `0b1010`).
 Underscore usage (JDK 7+): Can be used for readability, e.g., `1_000_000`.
 Long literal: Append `L` or `l` (e.g., `9223372036854775807L`).
2. Floating-Point Literals:
 Standard notation: Includes fractional components (e.g., `2.0`, `0.6667`).
 Scientific notation: Uses `E` or `e` for exponent (e.g., `6.022E23`).
 Default type: `double` (64-bit), specify `float` with `F` or `f` (32-bit).

7|Page OOP with java – Module 1


 Hexadecimal floating points: Start with `0x` and use `P` or `p` for the exponent (e.g., `0x12.2P2`).
 Underscore usage (JDK 7+): Allowed for readability (e.g., `9_423_497_862.0`).
3. Boolean Literals:
 Values: `true` or `false`.
 Cannot be converted into numerical values.
4. Character Literals:
 Enclosed in single quotes, like `'a'`, `'@'`.
 Escape sequences: E.g., `\'` for single quote, `\n` for newline.
 Octal and Hexadecimal notation: E.g., `\141` for 'a', `\u0061` for 'a'.
5. String Literals:
 Enclosed in double quotes, e.g., `"Hello World"`.
 Can include escape sequences like `\n` for newline.
 Must begin and end on the same line; no line continuation.
Variables
1. Variable Declaration:
 Format: `type identifier [ = value ][, identifier [= value] …];`
 Must be declared before use.
 Can initialize variables during declaration.
Examples:
int a, b, c; // Declares three integers
int d = 3, e, f = 5; // Declares and initializes 'd' and 'f'
double pi = 3.14159; // Declares a double
char x = 'x'; // Declares a char
2. Dynamic Initialization:
 Variables can be initialized using expressions or method calls.
Example:
class DynInit {
public static void main(String args[]) {
double a = 3.0, b = 4.0;
double c = Math.sqrt(a * a + b * b); // Dynamically initializes 'c'
System.out.println("Hypotenuse is " + c);
}
}
3. Scope and Lifetime of Variables:
 Scope: Defines the visibility of variables. Variables declared in a block are only accessible within
that block.
 Lifetime: A variable is created when its scope is entered and destroyed when its scope is exited.
Example:
class Scope {
public static void main(String args[]) {
int x = 10; // Visible throughout main
if (x == 10) { // Start new scope
int y = 20; // Only visible within this block
System.out.println("x and y: " + x + " " + y);
x = y * 2;
}
// System.out.println(y); // Error: y is not visible here
System.out.println("x is " + x);

8|Page OOP with java – Module 1


}
}
4. Lifetime and Reinitialization:
 Variables are reinitialized each time a block is entered.
Example:
class LifeTime {
public static void main(String args[]) {
int x;
for (x = 0; x < 3; x++) {
int y = -1; // Reinitialized every time the block is entered
System.out.println("y is: " + y);
y = 100;
System.out.println("y is now: " + y);
}
}
}

5. Variable Naming in Nested Scopes:


 You cannot declare a variable with the same name as one in the outer scope.
**Example (Incorrect Program):**
class ScopeErr {
public static void main(String args[]) {
int bar = 1;
{
int bar = 2; // Error: 'bar' already defined in outer scope
}
}
}

Type Conversion and Casting


1. Automatic (Widening) Type Conversions: Happens when:
 Types are compatible.
 Destination type is larger than the source type.
Example: `int` to `long` or `byte` to `int`.
Widening occurs for numeric types (integer and floating-point), but not between `char` and `boolean`.
Example:
int a = 100;
long b = a; // Automatic conversion (int to long)
2. Casting (Narrowing) Conversions:
 Used to explicitly convert between incompatible types.
 Syntax: `(target-type) value`
Example: `int` to `byte` or `double` to `int`.
int a = 257;
byte b = (byte) a; // Cast int to byte
3. Truncation with Floating-point to Integer:
 When converting a floating-point number to an integer, the fractional part is lost.
Example:
double d = 323.142;
int i = (int) d; // Truncates 323.142 to 323
4. Modulo Operation during Narrowing:
9|Page OOP with java – Module 1
 If the value is too large for the target type, it is reduced modulo the range of the target type.
Example Program:**
// Demonstrate casts.
class Conversion {
public static void main(String args[]) {
byte b;
int i = 257;
double d = 323.142;
// Conversion of int to byte
System.out.println("\nConversion of int to byte.");
b = (byte) i;
System.out.println("i and b: " + i + " " + b);
// Conversion of double to int
System.out.println("\nConversion of double to int.");
i = (int) d;
System.out.println("d and i: " + d + " " + i);
// Conversion of double to byte
System.out.println("\nConversion of double to byte.");
b = (byte) d;
System.out.println("d and b: " + d + " " + b);
}
}

Program Output:
Conversion of int to byte.
i and b: 257 1

Conversion of double to int.


d and i: 323.142 323

Conversion of double to byte.


d and b: 323.142 67

Explanation:
 int to byte: The value 257 is reduced modulo 256, so the result is 1.
 double to int: The fractional part of 323.142 is truncated, leaving 323.
 double to byte: The value is reduced modulo 256, resulting in 67.

Automatic Type Promotion in Expressions


1. Automatic Type Promotion in Expressions:
 Java automatically promotes `byte`, `short`, and `char` to `int` in expressions.
 If one operand is `long`, the entire expression is promoted to `long`.
 If one operand is `float`, the entire expression is promoted to `float`.
 If one operand is `double`, the entire expression is promoted to `double`.
byte a = 40;
byte b = 50;
byte c = 100;
int d = a * b / c; // a * b is promoted to int
In the above expression, `a * b` is performed using integers, even though `a` and `b` are `byte`.

2. Compile-Time Errors Due to Promotions:


10 | P a g e OOP with java – Module 1

Operations involving `byte`, `short`, or `char` are promoted to `int`, so assigning the result back to a
smaller type without casting will cause an error.
byte b = 50;
b = b * 2; // Error: result promoted to int
 To fix this, use explicit casting:
b = (byte)(b * 2); // Correct: cast result to byte

3. Type Promotion Rules:


 `byte`, `short`, `char` → `int`
 If any operand is `long`, result → `long`
 If any operand is `float`, result → `float`
 If any operand is `double`, result → `double`
class Promote {
public static void main(String args[]) {
byte b = 42;
char c = 'a';
short s = 1024;
int i = 50000;
float f = 5.67f;
double d = .1234;

double result = (f * b) + (i / c) - (d * s);


System.out.println((f * b) + " + " + (i / c) + " - " + (d * s));
System.out.println("result = " + result);
}
}

Explanation of Promotions:
 `f * b`: `b` is promoted to `float`; result is `float`.
 `i / c`: `c` is promoted to `int`; result is `int`.
 `d * s`: `s` is promoted to `double`; result is `double`.

Finally, `float + int` results in `float`, and `float - double` promotes to `double`.

Program Output:
238.14 + 390 - 126.2816
result = 501.8584

Arrays
Definition: An array is a group of variables of the same type, accessed using a common name. Java arrays
can be one-dimensional or multidimensional.

One-Dimensional Arrays
 Declaration: Syntax: `type var-name[];`
Example: `int month_days[];` declares an array of integers.
 Memory Allocation: Arrays must be allocated memory using `new`.
Syntax: `array-var = new type[size];`
Example: `month_days = new int[12];` allocates space for 12 integers.

11 | P a g e OOP with java – Module 1


 Accessing Elements:
Array elements are accessed using their index. Indexing starts at 0.
Example: `month_days[1] = 28;` assigns 28 to the second element of `month_days`.
 Initialization: Arrays can be initialized during declaration.
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };

Example Program:
class Array {
public static void main(String args[]) {
int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
System.out.println("April has " + month_days[3] + " days.");
}
}

Multidimensional Arrays

 Declaration:Syntax: `type var-name[][];`


Example: `int twoD[][] = new int[4][5];` declares a 2D array with 4 rows and 5 columns.
 Accessing Elements:Multidimensional arrays are accessed using multiple indices.
Example: `twoD[1][3] = 42;`
 Uneven Arrays: Multidimensional arrays in Java can have uneven sub-arrays.
int twoD[][] = new int[4][];
twoD[0] = new int[1];
twoD[1] = new int[2];

- Example Program:
class TwoDArray {
public static void main(String args[]) {
int twoD[][] = new int[4][5];
int k = 0;
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
twoD[i][j] = k++;
}
}
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 5; j++) {
System.out.print(twoD[i][j] + " ");
}
System.out.println();
}
}
}

12 | P a g e OOP with java – Module 1


Array Type Promotion; Type Promotion Rules:
 `byte`, `short`, and `char` are promoted to `int`.
 If one operand is `long`, the result is promoted to `long`.
 If one operand is `float`, the result is promoted to `float`.
 If one operand is `double`, the result is promoted to `double`.

Type Inference with Local Variables (var) in Java


Java 10 introduced **type inference** for local variables using the `var` keyword. It allows the compiler to
automatically determine the type of a local variable based on the value assigned to it.
Simplifies Code: By using `var`, you can eliminate explicit type declarations while maintaining strong
typing.
Local Variables Only: `var` can only be used with local variables inside methods, constructors, or
initialization blocks. It cannot be used for instance variables or method parameters.
Type is Determined at Compile-Time: The compiler infers the type based on the right-hand side of the
assignment, and the type is known at compile time.

#### Syntax
var variableName = value;

#### Example
var num = 10; // inferred as int
var message = "Hello, World!"; // inferred as String
Here, `num` is inferred to be of type `int`, and `message` is inferred to be of type `String`.

Rules and Restrictions


1. Cannot be Uninitialized: You must initialize the variable at the time of declaration.
var x; // Error: variable 'x' might not have been initialized
2. Cannot Change Type: Once a type is inferred, it cannot be changed.
var number = 10; // inferred as int
number = "test"; // Error: incompatible types
3. Readable Code: While `var` simplifies code, using it for complex expressions can make the code less
readable. Use `var` when the type is obvious from the context.

Example Program
13 | P a g e OOP with java – Module 1
public class TypeInferenceExample {
public static void main(String[] args) {
var count = 5; // inferred as int
var name = "John"; // inferred as String
System.out.println("Count: " + count);
System.out.println("Name: " + name);
}
}

Benefits of Type Inference


1. Less Verbose: Reduces the need for explicit type declarations, making code shorter and easier to
read.
2. No Impact on Performance: Type inference only simplifies the code but does not affect the
performance or runtime behavior, as the types are determined at compile time.

Limitations
1. Not for Every Use Case: Overuse of `var` can lead to less readable code, especially when the type is
not immediately obvious from the assignment expression.
2. Cannot be used for null**: `var x = null;` is not allowed because the compiler cannot infer the type
from `null`.

When to Use `var`


- When the type is clear and obvious, such as in loops, lambdas, or simple initializations.
- When refactoring code to reduce verbosity.

Example Use Cases


1. **For Loops**:
for (var i = 0; i < 10; i++) {
System.out.println(i);
}
2. **Lambda Expressions**:
var list = List.of(1, 2, 3);
list.forEach(var num -> System.out.println(num));

By using `var`, Java combines the benefits of strong typing with simpler, more concise code.

Operators
Java provides a rich set of operators that can be divided into four main groups: arithmetic, bitwise,
relational, and logical. Additionally, Java defines certain special operators like the type comparison operator
`instanceof` and the arrow operator `->`.

1. Arithmetic Operators
- Used for mathematical operations.
- Operators:
| Operator | Result |
|----------|---------------------------------|
| `+` | Addition (also unary plus) |
| `-` | Subtraction (also unary minus) |

14 | P a g e OOP with java – Module 1


| `*` | Multiplication |
| `/` | Division |
| `%` | Modulus (remainder) |
| `++` | Increment |
| `--` | Decrement |
| `+=` | Addition assignment |
| `-=` | Subtraction assignment |
| `*=` | Multiplication assignment |
| `/=` | Division assignment |
| `%=` | Modulus assignment |

-Numeric Types Only: Arithmetic operators can only be used with numeric types like `int`, `double`,
`float`, `char`, etc., not with `boolean`.

Basic Arithmetic Operators Program:


// Demonstrate the basic arithmetic operators.
class BasicMath {
public static void main(String args[]) {
// Arithmetic using integers
System.out.println("Integer Arithmetic");
int a = 1 + 1;
int b = a * 3;
int c = b / 4;
int d = c - a;
int e = -d;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
System.out.println("e = " + e);

// Arithmetic using doubles


System.out.println("\nFloating Point Arithmetic");
double da = 1 + 1;
double db = da * 3;
double dc = db / 4;
double dd = dc - a;
double de = -dd;
System.out.println("da = " + da);
System.out.println("db = " + db);
System.out.println("dc = " + dc);
System.out.println("dd = " + dd);
System.out.println("de = " + de);
}
}
Output:
Integer Arithmetic
a=2
b=6
15 | P a g e OOP with java – Module 1
c=1
d = -1
e=1

Floating Point Arithmetic


da = 2.0
db = 6.0
dc = 1.5
dd = -0.5
de = 0.5

2. Modulus Operator (`%`)


- Returns the remainder of a division operation.
- Can be used with both integers and floating-point types.
Modulus Operator Program:
// Demonstrate the % operator.
class Modulus {
public static void main(String args[]) {
int x = 42;
double y = 42.25;
System.out.println("x mod 10 = " + x % 10);
System.out.println("y mod 10 = " + y % 10);
}
}
Output:
x mod 10 = 2
y mod 10 = 2.25

3. Compound Assignment Operators - Combine arithmetic operation with assignment.


- Examples:
- `a = a + 4;` → `a += 4;`
- `a = a % 2;` → `a %= 2;`
Compound Assignment Operator Program:
// Demonstrate several assignment operators.
class OpEquals {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c = 3;
a += 5;
b *= 4;
c += a * b;
c %= 6;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
}
}
Output:
16 | P a g e OOP with java – Module 1
a=6
b=8
c=3

4. Increment and Decrement Operators


- `++` → Increment (adds 1 to the operand)
- `--` → Decrement (subtracts 1 from the operand)
- Can be used in prefix or postfix form:
- Prefix: Increments or decrements before using the value.
- Postfix: Uses the value first, then increments or decrements.
Increment and Decrement Operators Program:
// Demonstrate ++.
class IncDec {
public static void main(String args[]) {
int a = 1;
int b = 2;
int c;
int d;
c = ++b;
d = a++;
c++;
System.out.println("a = " + a);
System.out.println("b = " + b);
System.out.println("c = " + c);
System.out.println("d = " + d);
}
}
Output:
a=2
b=3
c=4
d=1

The Bitwise Operators


Java provides several bitwise operators that can be applied to integer types (`long`, `int`, `short`, `char`, and
`byte`), affecting individual bits in their operands.

| **Operator** | **Description** |
|-------------- |------------------------------------------|
| `~` | Bitwise NOT (Unary Operator) |
| `&` | Bitwise AND |
| `|` | Bitwise OR |
| `^` | Bitwise XOR (Exclusive OR) |
| `<<` | Left shift |
| `>>` | Right shift (Sign-extended) |
| `>>>` | Right shift (Zero-fill) |
| `&=` | Bitwise AND assignment |
| `|=` | Bitwise OR assignment |

17 | P a g e OOP with java – Module 1


| `^=` | Bitwise XOR assignment |
| `<<=` | Left shift assignment |
| `>>=` | Right shift assignment |
| `>>>=` | Right shift zero fill assignment |

Representation of Numbers in Binary and Two’s Complement


 Java uses two’s complement to represent negative integers.
 Positive numbers are straightforward binary representations (e.g., 42 is `00101010`).
 Negative numbers are stored by inverting the bits of the positive counterpart and adding 1.
For example:
 `42` in binary: `00101010`
 `-42` in binary: `11010110` (after inversion and adding 1)

Common Bitwise Operators


1. Bitwise NOT (`~`): Inverts all bits.
- Example: `~42` results in `11010101`.
2. Bitwise AND (`&`): Results in `1` only when both bits are `1`.
- Example: `42 & 15` results in `00001010` (binary for 10).
3. Bitwise OR (`|`): Results in `1` if either bit is `1`.
- Example: `42 | 15` results in `00101111` (binary for 47).
4. Bitwise XOR (`^`): Results in `1` if only one operand has a `1`.
- Example: `42 ^ 15` results in `00100101` (binary for 37).

Shift Operators
1. Left Shift (`<<`): Shifts bits to the left, filling with zeros.
- Example: `64 << 2` results in `256`.
2. Right Shift (`>>`): Shifts bits to the right, preserving the sign (sign extension).
- Example: `35 >> 2` results in `8`.
3. Unsigned Right Shift (`>>>`): Shifts bits to the right, filling with zeros regardless of sign.
- Example: `-1 >>> 24` results in `255`.

Compound Bitwise Assignment Operators


These combine a bitwise operation and assignment:
- `a |= b` is equivalent to `a = a | b`.
- `a >>= 4` is equivalent to `a = a >> 4`.

Examples
1. Bitwise Operations in a Program:
class BitLogic {
public static void main(String args[]) {
int a = 3; // 0011 in binary
int b = 6; // 0110 in binary
int c = a | b; // 0111 (7 in binary)
int d = a & b; // 0010 (2 in binary)
int e = a ^ b; // 0101 (5 in binary)
int f = (~a & b) | (a & ~b); // 0101 (5 in binary)
int g = ~a & 0x0f; // 1100 (12 in binary)

System.out.println("a|b = " + c);


18 | P a g e OOP with java – Module 1
System.out.println("a&b = " + d);
System.out.println("a^b = " + e);
System.out.println("~a&b|a&~b = " + f);
System.out.println("~a = " + g);
}
}
2. Left Shift Example:
class ByteShift {
public static void main(String args[]) {
byte a = 64; // 01000000 in binary
int i = a << 2; // 256 (000100000000)
System.out.println("Shifted value: " + i);
}
}

Relational Operators
- Purpose: Determine the relationship between two operands, such as equality or ordering.
- Operators and Their Functions:
| Operator | Description |
| `==` | Equal to |
| `!=` | Not equal to |
| `>` | Greater than |
| `<` | Less than |
| `>=` | Greater than or equal to |
| `<=` | Less than or equal to |

- Result: Always returns a boolean value (`true` or `false`).


- Usage: Commonly used in control statements such as `if` and loop conditions.

Applicable Types:
- Equality (`==`) and Inequality (`!=`): Can be used with any type (integers, floating-point numbers,
characters, Booleans).
- Ordering (`>`, `<`, `>=`, `<=`): Only applicable to numeric types (integers, floating-point, characters).

Important Notes:
- Equality Operator: In Java, equality is tested with `==`, not with a single `=` (which is the assignment
operator).

Example Code:
int a = 4;
int b = 1;
boolean c = a < b; // c will be false, as 4 is not less than 1

Comparison with C/C++:


- C/C++ Style:
int done;
if (!done) ... // Valid in C/C++
if (done) ...

19 | P a g e OOP with java – Module 1


- Java Style: In Java, true and false are not numeric values (true ≠ 1, false ≠ 0).
if (done == 0) ... // Valid in Java
if (done != 0) ...

Boolean Logical Operators


-Purpose: These operators are used for evaluating expressions that result in a boolean value (`true` or
`false`).
- Types of Operators:
| Operator | Description |
| `&` | Logical AND |
| `|` | Logical OR |
| `^` | Logical XOR (exclusive OR) |
| `||` | Short-circuit OR |
| `&&` | Short-circuit AND |
| `!` | Logical unary NOT |
| `&=` | AND assignment |
| `|=` | OR assignment |
| `^=` | XOR assignment |
| `==` | Equal to |
| `!=` | Not equal to |
| `?:` | Ternary if-then-else (conditional operator) |

Boolean Logic Table:


|A |B | A \| B | A & B | A ^ B | !A |
| False | False | False | False | False | True |
| True | False | True | False | True | False|
| False | True | True | False | True | True |
| True | True | True | True | False | False|

Explanation of Key Operators:


1. Logical AND (`&`): Returns `true` if both operands are `true`, otherwise `false`.
2. Logical OR (`|`): Returns `true` if at least one operand is `true`.
3. Logical XOR (`^`): Returns `true` if exactly one of the operands is `true`, otherwise `false`.
4. Logical NOT (`!`): Inverts the boolean value (`!true == false` and `!false == true`).
5. Short-circuit AND (`&&`): Same as `&`, but the second operand is evaluated only if necessary.
6. Short-circuit OR (`||`): Same as `|`, but the second operand is evaluated only if necessary.

Example Code:
class BoolLogic {
public static void main(String args[]) {
boolean a = true;
boolean b = false;

boolean c = a | b;
boolean d = a & b;
boolean e = a ^ b;
boolean f = (!a & b) | (a & !b);

20 | P a g e OOP with java – Module 1


boolean g = !a;

System.out.println(" a = " + a);


System.out.println(" b = " + b);
System.out.println(" a|b = " + c);
System.out.println(" a&b = " + d);
System.out.println(" a^b = " + e);
System.out.println("!a&b|a&!b = " + f);
System.out.println(" !a = " + g);
}
}
Output:
a = true
b = false
a|b = true
a&b = false
a^b = true
!a&b|a&!b = true
!a = false

Short-Circuit Logical Operators:


- Short-circuit AND (`&&`) and Short-circuit OR (`||`) avoid unnecessary evaluation of the second operand
if the result can already be determined from the first operand.
- Example:
if (denom != 0 && num / denom > 10)
- The division `num / denom` is only evaluated if `denom != 0`, avoiding a potential division by zero
error.

Use of Single-character Logical Operators:


- Single `&` and `|` can be used for bitwise operations or when both sides must be evaluated, such as in the
following example:
if (c == 1 & e++ < 100) d = 100;
- In this case, `e++` is executed whether `c == 1` is `true` or `false`.

Ternary Operator (`?:`):


- Used for concise if-else expressions:
int result = (condition) ? value_if_true : value_if_false;

The Assignment Operator in Java


Symbol: `=`: Purpose: Assigns the value on the right-hand side to the variable on the left-hand side.
Syntax: var = expression;
- `var`: A variable that will receive the value.
- `expression`: The value or expression to be assigned to the variable.

Compatibility:The type of `var` must be compatible with the result of `expression`. For example:
int a = 10; // Valid: int can hold an integer value.

Chain Assignments:

21 | P a g e OOP with java – Module 1


- Java allows multiple variables to be assigned the same value in a single statement using a chain of
assignments.

Example:
int x, y, z;
x = y = z = 100; // Sets x, y, and z to 100

- How it works:
- First, `z = 100` is evaluated, which returns the value `100`.
- Next, `y = z`, so `y` also becomes `100`.
- Finally, `x = y`, making `x` also equal to `100`.

- Usage: This is useful for initializing several variables to the same value efficiently.

Key Points:
- The assignment operator returns the value of the right-hand expression, allowing the chaining of
assignments.
- It is widely used for initializing multiple variables at once, keeping the code concise.

The ? Operator
- Purpose: The ternary operator is a shorthand for the `if-then-else` statement.
- Syntax: expression1 ? expression2 : expression3;
- `expression1`: A boolean expression that evaluates to `true` or `false`.
- `expression2`: Executed if `expression1` is `true`.
- `expression3`: Executed if `expression1` is `false`.

- Result: The ternary operator returns the value of either `expression2` or `expression3`, depending on the
condition (`expression1`). Both expressions must return a value of the same or compatible type.
Example:
int ratio = denom == 0 ? 0 : num / denom;
- If `denom == 0`, the value `0` is assigned to `ratio`.
- If `denom != 0`, the value `num / denom` is assigned to `ratio`.

Here is a program that demonstrates the use of the ternary operator to obtain the absolute value of a variable:
// Demonstrate the ternary operator.
class Ternary {
public static void main(String args[]) {
int i, k;

i = 10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);

i = -10;
k = i < 0 ? -i : i; // get absolute value of i
System.out.print("Absolute value of ");
System.out.println(i + " is " + k);
}
}
22 | P a g e OOP with java – Module 1
Output:
Absolute value of 10 is 10
Absolute value of -10 is 10

Key Points:
- The ternary operator helps in writing concise conditional statements.
- It's useful when there are simple conditions with two possible outcomes.

Operator Precedence

Using Parentheses
Purpose: Parentheses are used in Java to control or clarify the order of operations in an expression.
Operator Precedence: Java evaluates operators based on a defined order of precedence. If an expression
contains operators of different precedence levels, the higher precedence operator is executed first.
Parentheses are used to change the default precedence.

Examples:
1. Without Parentheses: a >> b + 3
- This expression first adds `3` to `b`, then shifts `a` right by the result of that addition.
- Equivalent to: a >> (b + 3)
2. With Parentheses:
If you want to first shift `a` right by `b` positions and then add `3`: (a >> b) + 3
3. Clarifying Complex Expressions:
Parentheses can help make complex expressions easier to read.
- Without extra parentheses: a | 4 + c >> b & 7
- With parentheses for clarity: (a | (((4 + c) >> b) & 7))

Key Points:
- Priority Management: Parentheses raise the precedence of the enclosed expressions, ensuring the
operations inside are executed first.
- Readability: Adding redundant parentheses can help clarify complex expressions, making the code easier
to understand.

23 | P a g e OOP with java – Module 1


- No Performance Degradation: Using parentheses does not negatively affect the performance of a Java
program.

In conclusion, while parentheses change the order of operations, they are also an important tool for
enhancing code readability without any performance cost.

Control Statements
Java’s Selection Statements
`if` Statement
 Purpose: Java’s conditional branch statement for selecting between two paths.
 Syntax:
if (condition) statement1;
else statement2;
 Condition: Any expression that returns a boolean value.
 Block of Code: Use curly braces `{}` to include multiple statements.
 Example:
int a, b;
if(a < b) a = 0;
else b = 0;

If `a < b`, `a` is set to zero; otherwise, `b` is set to zero.

 Using Boolean Variable**:


boolean dataAvailable;
if (dataAvailable) ProcessData();
else waitForMoreData();

Executes `ProcessData()` if `dataAvailable` is true; otherwise, waits for more data.

 Using Blocks:
int bytesAvailable;
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
{
waitForMoreData();
}

 Common Error: Forgetting braces can lead to logic issues.


int bytesAvailable;
if (bytesAvailable > 0)
{
ProcessData();
bytesAvailable -= n;
}
else
{

24 | P a g e OOP with java – Module 1


waitForMoreData();
bytesAvailable = n; // Corrected: `bytesAvailable = n;` is inside `else`.
}

Nested `if` Statements


 Definition: An `if` statement inside another `if` or `else`.
 Example:
if (i == 10) {
if (j < 20) a = b;
if (k > 100) c = d;
else a = c;
}
else
a = d;

`if-else-if` Ladder
 Purpose: Chain of `if-else` statements to test multiple conditions.
 Example:
if (month == 12 || month == 1 || month == 2) season = "Winter";
else if (month == 3 || month == 4 || month == 5) season = "Spring";
else season = "Bogus Month";

Output:
April is in the Spring.

`switch` Statement
 Purpose: Java’s multiway branch statement for better efficiency than `if-else-if`.
 Syntax:
switch(expression) {
case value1: statement sequence; break;
case value2: statement sequence; break;
...
default: default sequence;
}

 Expression Type: Can be `byte`, `short`, `int`, `char`, `String` (from JDK 7), or enum.
 Example:
class SampleSwitch {
public static void main(String args[]) {
for (int i = 0; i < 6; i++) {
switch(i) {
case 0: System.out.println("i is zero."); break;
case 1: System.out.println("i is one."); break;
case 2: System.out.println("i is two."); break;
default: System.out.println("i is greater than 3.");
}
}
}
}

Output:
```

25 | P a g e OOP with java – Module 1


i is zero.
i is one.
i is two.
i is greater than 3.
i is greater than 3.
```

Using `switch` without `break`**


 Example:
class MissingBreak {
public static void main(String args[]) {
for (int i = 0; i < 12; i++) {
switch(i) {
case 0: case 1: case 2: case 3: case 4:
System.out.println("i is less than 5");
break;
case 5: case 6: case 7: case 8: case 9:
System.out.println("i is less than 10");
break;
default:
System.out.println("i is 10 or more");
}
}
}
}

 Output:
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 5
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is less than 10
i is 10 or more
i is 10 or more

String-Based `switch` (from JDK 7)


 Example:
class StringSwitch {
public static void main(String args[]) {
String str = "two";
switch(str) {
case "one": System.out.println("one"); break;
case "two": System.out.println("two"); break;
case "three": System.out.println("three"); break;
default: System.out.println("no match");
}
}

26 | P a g e OOP with java – Module 1


}

 Output:
two

Nested `switch` Statements


 Definition: A `switch` inside another `switch`.
 Example
switch(count) {
case 1:
switch(target) {
case 0: System.out.println("target is zero"); break;
case 1: System.out.println("target is one"); break;
}
break;
case 2: //...
}

Key Points:
 `if` vs `switch`: `if` evaluates any boolean expression; `switch` only checks for equality.
 Efficiency: `switch` is more efficient for large groups of values due to the use of a "jump table."

Iteration Statements
while` Loop
 Purpose: Repeats a statement or block while a condition is true.
 Synta*:
while (condition) {
// body of loop
}
 Condition: Any boolean expression.
 Behavior: Executes the body as long as the condition is true. Exits when the condition becomes false.

 Example: Counting down from 10


class While {
public static void main(String args[]) {
int n = 10;
while (n > 0) {
System.out.println("tick " + n);
n--;
}
}
}
 Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
27 | P a g e OOP with java – Module 1
tick 3
tick 2
tick 1

 Condition False Initially: Loop will not execute if the condition is false at the start.
int a = 10, b = 20;
while (a > b)
System.out.println("This will not be displayed");

 Empty Loop Body: The body of the loop can be empty, using a null statement (a single semicolon).
class NoBody {
public static void main(String args[]) {
int i, j;
i = 100;
j = 200;
// find midpoint between i and j
while (++i < --j); // no body in this loop
System.out.println("Midpoint is " + i);
}
}
 Output:
Midpoint is 150

 Explanation:
- `i` is incremented and `j` is decremented in the condition.
- Loop continues while `i` is less than `j`.
- Upon loop exit, `i` is midway between the original values of `i` and `j`.

 Use Case: Short loops with all logic in the condition itself.

do-while` Loop
 Purpose: Ensures that the body of the loop is executed at least once, regardless of the condition.
 Syntax:
do {
// body of loop
} while (condition);
 Behavior: Executes the loop body first, then evaluates the condition. If the condition is true, the loop
repeats; otherwise, it terminates.

 Example: Counting down from 10


class DoWhile {
public static void main(String args[]) {
int n = 10;
do {
System.out.println("tick " + n);
n--;
} while (n > 0);
}
28 | P a g e OOP with java – Module 1
}
 Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1
```

 Optimized Example:
do {
System.out.println("tick " + n);
} while (--n > 0);
 Explanation: The expression `--n > 0` combines the decrement and condition check. `--n`
decrements `n` and returns the new value, which is then compared with zero.

 -Menu Selection Example: Using `do-while` to process user input


class Menu {
public static void main(String args[]) throws java.io.IOException {
char choice;
do {
System.out.println("Help on: ");
System.out.println(" 1. if");
System.out.println(" 2. switch");
System.out.println(" 3. while");
System.out.println(" 4. do-while");
System.out.println(" 5. for\n");
System.out.println("Choose one:");
choice = (char) System.in.read();
} while (choice < '1' || choice > '5');

System.out.println("\n");
switch (choice) {
case '1':
System.out.println("The if:\n");
System.out.println("if(condition) statement;");
System.out.println("else statement;");
break;
case '2':
System.out.println("The switch:\n");
System.out.println("switch(expression) {");
System.out.println(" case constant:");
System.out.println(" statement sequence");
System.out.println(" break;");
29 | P a g e OOP with java – Module 1
System.out.println(" //...");
System.out.println("}");
break;
case '3':
System.out.println("The while:\n");
System.out.println("while(condition) statement;");
break;
case '4':
System.out.println("The do-while:\n");
System.out.println("do {");
System.out.println(" statement;");
System.out.println("} while (condition);");
break;
case '5':
System.out.println("The for:\n");
System.out.print("for(init; condition; iteration)");
System.out.println(" statement;");
break;
}
}
}

 Sample Output:
Help on:
1. if
2. switch
3. while
4. do-while
5. for
Choose one:
4
The do-while:
do {
statement;
} while (condition);

 Explanation:
- The `do-while` loop ensures that the menu is displayed at least once.
- User input is read using `System.in.read()`, which requires handling `IOException`.
- `System.in.read()` reads characters as integers, hence casting to `char`.

for` Loop:Traditional `for` Loop


 Purpose: Provides a concise way to execute a block of code a specific number of times.
 Syntax:
for (initialization; condition; iteration) {
// body of loop
}
 Initialization: Executed once at the start of the loop. Typically sets up the loop control variable.

30 | P a g e OOP with java – Module 1


 Condition: A Boolean expression evaluated before each iteration. If true, the loop body executes; if
false, the loop terminates.
 Iteration: Executed after the loop body. Usually increments or decrements the loop control variable.

 Example: Counting down from 10


class ForTick {
public static void main(String args[]) {
int n;
for (n = 10; n > 0; n--) {
System.out.println("tick " + n);
}
}
}
 Output:
tick 10
tick 9
tick 8
tick 7
tick 6
tick 5
tick 4
tick 3
tick 2
tick 1

 Explanation:
- Initialization: `int n = 10;` sets the initial value of `n`.
- Condition: `n > 0;` checks if `n` is greater than 0.
- Iteration: `n--` decrements `n` by 1 after each loop iteration.
- Body: `System.out.println("tick " + n);` executes with each loop iteration.

For-Each Version of the `for` Loop


 Overview: The enhanced `for` loop, also known as the "for-each" loop, simplifies iteration over
collections like arrays. It automates the process of traversing through elements in a collection,
eliminating the need for explicit indexing.
 General Form
for (type itr-var : collection) {
// statement-block
}
- `type*: Type of the elements in the collection.
- `itr-var`: Variable that receives each element in turn.
- `collection`: Collection to be iterated over (e.g., array).

 Example: Summing Array Elements: Traditional `for` Loop**:


int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
}
31 | P a g e OOP with java – Module 1
System.out.println("Summation: " + sum);

 Enhanced `for` Loop:


class ForEach {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
// Use for-each style for to display and sum the values
for (int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}
System.out.println("Summation: " + sum);
}
}
 Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55

Using `break` Statement


The `for-each` loop can be exited early using the `break` statement.
Example: Summing First 5 Elements:
class ForEach2 {
public static void main(String args[]) {
int sum = 0;
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Use for-each to display and sum the values
for (int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if (x == 5) break; // Stop the loop when 5 is obtained
}
System.out.println("Summation of first 5 elements: " + sum);
}
}
 Output:
Value is: 1
Value is: 2
Value is: 3
Value is: 4
32 | P a g e OOP with java – Module 1
Value is: 5
Summation of first 5 elements: 15

Read-Only Iteration Variable


The iteration variable in a `for-each` loop is effectively read-only; changes to it do not affect the underlying
array or collection.

 Example: Attempting to Modify Array Elements:


class NoChange {
public static void main(String args[]) {
int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
for (int x : nums) {
System.out.print(x + " ");
x = x * 10; // No effect on nums
}
System.out.println();
for (int x : nums)
System.out.print(x + " ");
System.out.println();
}
}
 Output:
1 2 3 4 5 6 7 8 9 10
1 2 3 4 5 6 7 8 9 10

The `for-each` loop simplifies iterating through collections, providing cleaner and less error-prone code for
sequential access. However, it is important to remember that you cannot modify the collection being iterated
directly using this loop.

Local Variable Type Inference with `var` in `for` Loops

Java 10 introduced `var` for local variable type inference, simplifying code by letting the compiler determine
the type.
 Using `var` in a `for` Loop: Traditional `for` Loop: Before Java 10:**
for (int i = 0; i < 10; i++) {
System.out.println(i);
}

 With `var`:
for (var i = 0; i < 10; i++) {
System.out.println(i);
}

 Enhanced `for` Loop:- Before Java 10:


int nums[] = {1, 2, 3, 4, 5};
for (int x : nums) {
System.out.println(x);
}

33 | P a g e OOP with java – Module 1


 With `var`:
int nums[] = {1, 2, 3, 4, 5};
for (var x : nums) {
System.out.println(x);
}

Key Points
 Type Inference: `var` infers the type based on initialization.
 Initialization Required: Must be initialized on the same line.
 Improves Readability: Reduces verbosity, but use judiciously for clarity.
Using `var` makes your `for` loops cleaner by removing redundant type declarations.

Nested Loops
Like all other programming languages, Java allows loops to be nested. That is, one loop
may be inside another. For example, here is a program that nests for loops:

// Loops may be nested.


class Nested {
public static void main(String args[]) {
int i, j;
for(i = 0; i < 10; i++) {
for(j = i; j < 10; j++)
System.out.print(".");
System.out.println();
}
}
}
Explanation:
Outer Loop (`i` loop): Runs from `i = 0` to `i < 10`.
- For each value of `i`, the inner loop executes.

- Inner Loop (`j` loop): Starts from `j = i` to `j < 10`.


- Prints `.` for each value of `j`.

-Effect: Each iteration of the outer loop prints a new line. The number of `.` characters printed decreases as
`i` increases, leading to a pattern where each line has fewer `.` than the previous one.

Output:
..........
.........
........
.......
......
.....
....
...
..
.

34 | P a g e OOP with java – Module 1


Jump Statements
Uses of `break`:
1.Exit a `switch` statement.
2.Exit loops early—used to stop a loop before it naturally finishes.
3. Simulate a "goto" for breaking out of nested loops or code blocks in a structured manner.

Example 1: Using `break` to Exit a `for` Loop


Explanation: The loop runs from 0 to 99, but it stops when `i` reaches 10 due to the `break` statement.
class BreakLoop {
public static void main(String args[]) {
for(int i = 0; i < 100; i++) {
if(i == 10) break; // Exit loop when i equals 10
System.out.println("i: " + i);
}
System.out.println("Loop complete.");
}
}
Output:
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
i: 6
i: 7
i: 8
i: 9
Loop complete.

Example 2: Using `break` in a `while` Loop


Explanation: Here, the loop runs until `i` reaches 10. When `i` equals 10, `break` ends the loop early.
class BreakLoop2 {
public static void main(String args[]) {
int i = 0;
while(i < 100) {
if(i == 10) break; // Exit loop when i equals 10
System.out.println("i: " + i);
i++;
}
System.out.println("Loop complete.");
}
}
Output Same as above.

Example 3: Using `break` with Nested Loops

35 | P a g e OOP with java – Module 1


Explanation: The `break` statement only terminates the inner loop, allowing the outer loop to continue.
class BreakLoop3 {
public static void main(String args[]) {
for(int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for(int j = 0; j < 100; j++) {
if(j == 10) break; // Exit inner loop when j equals 10
System.out.print(j + " ");
}
System.out.println();
}
System.out.println("Loops complete.");
}
}

Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9
Pass 1: 0 1 2 3 4 5 6 7 8 9
Pass 2: 0 1 2 3 4 5 6 7 8 9
Loops complete.

Example 4: Using `break` with Labels (Simulating `goto`)


Explanation: The `break` statement breaks out of the block labeled `second`, skipping the rest of the inner
blocks.

class Break {
public static void main(String args[]) {
boolean t = true;
first: {
second: {
third: {
System.out.println("Before the break.");
if(t) break second; // Break out of second block
System.out.println("This won't execute");
}
System.out.println("This won't execute");
}
System.out.println("This is after second block.");
}
}
}
Output:
Before the break.
This is after second block.

Example 5: Breaking Out of Nested Loops with Labels


Explanation: Using the label `outer`, both loops are exited when `j` equals 10.

class BreakLoop4 {
36 | P a g e OOP with java – Module 1
public static void main(String args[]) {
outer: for(int i = 0; i < 3; i++) {
System.out.print("Pass " + i + ": ");
for(int j = 0; j < 100; j++) {
if(j == 10) break outer; // Exit both loops
System.out.print(j + " ");
}
System.out.println("This will not print");
}
System.out.println("Loops complete.");
}
}

Output:
Pass 0: 0 1 2 3 4 5 6 7 8 9
Loops complete.

Using `continue` in Java


Explanation: The `continue` statement skips the remaining code in the current loop iteration and jumps to
the next iteration.

Example 6: `continue` in a `for` Loop


Explanation: Skips printing a new line when `i` is even.
class Continue {
public static void main(String args[]) {
for(int i = 0; i < 10; i++) {
System.out.print(i + " ");
if (i % 2 == 0) continue; // Skip the rest when i is even
System.out.println("");
}
}
}
Output:
01
23
45
67
89

Example 7: `continue` with a Label


Explanation: The `continue outer;` skips to the next iteration of the outer loop when `j > i`.

class ContinueLabel {
public static void main(String args[]) {
outer: for (int i = 0; i < 10; i++) {
for(int j = 0; j < 10; j++) {
if(j > i) {
System.out.println();
continue outer; // Continue outer loop
37 | P a g e OOP with java – Module 1
}
System.out.print(" " + (i * j));
}
}
System.out.println();
}
}
Output:
0
01
024
0369
0 4 8 12 16
0 5 10 15 20 25
0 6 12 18 24 30 36
0 7 14 21 28 35 42 49
0 8 16 24 32 40 48 56 64
0 9 18 27 36 45 54 63 72 81

Using `return` in Java


Explanatio*: The `return` statement exits from the current method and returns control to the caller.
Example 8: `return` in a Method
Explanation**: Once `return` is executed, the remaining code in the method is skipped.
class Return {
public static void main(String args[]) {
boolean t = true;
System.out.println("Before the return.");
if(t) return; // Exit the method
System.out.println("This won't execute.");
}
}

Output:
Before the return.

38 | P a g e OOP with java – Module 1

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy