Java Interview Question Part - 1
Java coding examples
Question 1: Write a Java program to reverse a string without using any built-in methods or functions.
Solution: Here's one way to solve this problem:
public class StringReverse {
public static void main(String[] args) {
String original = "Hello, world!";
String reversed = "";
for (int i = original.length() - 1; i >= 0; i--) {
reversed += original.charAt(i);
}
System.out.println("Original string: " + original);
System.out.println("Reversed string: " + reversed);
}
}
Explanation: - The program initializes a string with some value.
- The reversed variable is initialized as an empty string.
- 'A' for loop is used to iterate over the characters of the original string in reverse order.
- For each character, the program appends it to the reversed string using the += operator.
- Finally, the program prints out both the original and reversed strings.
public class ReverseString {
public static void main(String[] args) {
String str = "Hello, world!";
String reversed = "";
for (int i = str.length() - 1; i >= 0; i--) {
reversed += str.charAt(i);
}
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reversed);
}
}
Explanation:- The program initializes a string with some value.
- The reversed variable is initialized to an empty string.
- A for loop is used to iterate over the characters of the string in reverse order, starting from the last character.
- For each character, the program appends it to the reversed string.
- Finally, the program prints out both the original and reversed strings.
public class ReverseString {
public static void main(String[] args) {
String str = "Hello, world!";
StringBuilder reversed = new StringBuilder();
for (int i = str.length() - 1; i >= 0; i--) {
reversed.append(str.charAt(i));
}
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reversed.toString());
}
}
Post a Comment
0 Comments