java1
java1
Definition: Performed automatically by the compiler when converting a value from one
data type to another.
Key Points:
o No explicit instruction from the programmer is needed.
o Converts a smaller data type to a larger one (e.g., int to float) to prevent data loss.
o Commonly referred to as type promotion.
Examples:
int a = 10;
float b = a; // `int` is implicitly converted to `float`
Differences:
Usage Considerations:
If we want a set of
words including
spaces also then use
Sc.nextLine();
import java.util.Scanner;
1. if-else Statement
Syntax:
Java
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
Example:
Java
int age = 25;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
default:
System.out.println("Invalid day");
}
.
EXAMPLE for “continue”
……………………………………………………………………………………
FOR EACH LOOP IN JAVA IS MORE LIKE ACCESSING EACH
ELEMENT OF AN ARRAY SEQUENTIALLY
Java for-each Loop
The for-each loop in Java, also known as the enhanced for loop, is a simplified loop
structure designed to iterate through elements of arrays or collections. It is particularly
useful when you need to access every element sequentially without worrying about the
index.
Syntax:
for (dataType element : arrayOrCollection) {
// body of loop
}
element: A temporary variable that holds the current element being accessed.
Key Points:
1. Ease of Use: The for-each loop eliminates the need for managing indices and reduces errors
like ArrayIndexOutOfBoundsException.
1. Read-Only Access: The element variable is a copy of the array element. Modifications to
element do not affect the original array.
2. Traversal Order: Iterates sequentially from the first to the last element.
Output:
10
20
30
40
50
Characteristics:
1. Applicable to All Array Types: Works for arrays of primitive types (e.g., int, double) and
reference types (e.g., String, custom objects).
1. Immutable Access: You can read elements, but cannot modify them in the original array.
Output:
ALICE
BOB
CHARLIE
Limitations:
1. No Access to Index: If you need the index, use a traditional for loop. Example: for (int i
= 0; i < array.length; i++).
When to Use:
Use for-each for simple iteration where you don’t need to modify the array or know the
index.
Use traditional loops when you need to modify elements, require the index, or want to iterate in
reverse.
For (int number : numbers)
{
// body of for each loop
}
// we are saying like for every element(number) of array(numbers) do the below work(the
work we assign in body of for each loop)
Actually this is how a 2d array looks
but we have made it like a box rows
Multi dimensional array and columns for our easy
visualization
For above picture we are printing row 2: column 1 marks which is 98.
Functions && methods