Skip to content

Commit 31cf982

Browse files
committed
feat: Print each character of a string using a basic for loop
🧠 Logic: - Declare a string `str` with the value "Chill bro". - Use a standard for loop to iterate from index `0` to `str.length() - 1`. - On each iteration, use `charAt(i)` to access and print the character at index `i`. - This loop prints each character of the string on a new line. Signed-off-by: Somesh diwan <[email protected]>
1 parent 8b87f7a commit 31cf982

File tree

1 file changed

+16
-15
lines changed

1 file changed

+16
-15
lines changed
Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,23 @@
11
public class ForLoop {
2-
public static void main(String[] args)
3-
{
2+
public static void main(String[] args) {
43
String str = "Chill bro";
5-
for (int i = 0; i <str.length(); i++)
6-
{
4+
for (int i = 0; i <str.length(); i++) {
75
System.out.println(str.charAt(i));
86
}
97
}
108
}
119

12-
//the String class provides several methods to manipulate and interact with strings. Two commonly used methods are charAt() and length(). Let's understand these methods in detail.
13-
//The charAt() method returns the character at a specific position (index) in a string.
14-
//The argument index must be a valid position in the string; otherwise, a StringIndexOutOfBoundsException is thrown.
15-
//Error Handling:
16-
//If you try to access an index outside the string's range, it throws an exception.
17-
//java
18-
//Copy code
19-
//String str = "Java";
20-
//System.out.println(str.charAt(10)); // This will throw StringIndexOutOfBoundsException
21-
//length()
22-
//The length() method returns the total number of characters in a string.
10+
/*
11+
the String class provides several methods to manipulate and interact with strings.
12+
Two commonly used methods are charAt() and length().
13+
Let's understand these methods in detail.
14+
The charAt() method returns the character at a specific position (index) in a string.
15+
The argument index must be a valid position in the string; otherwise, a StringIndexOutOfBoundsException is thrown.
16+
17+
Error Handling:
18+
If you try to access an index outside the string's range, it throws an exception.
19+
String str = "Java";
20+
System.out.println(str.charAt(10)); // This will throw StringIndexOutOfBoundsException
21+
length()
22+
The length() method returns the total number of characters in a string.
23+
*/

0 commit comments

Comments
 (0)