- Java Tutorial
- Java Introduction
- Java Features
- Java Simple Program
- JVM, JDK and JRE
- Java Syntax
- Java Comments
- Java Keywords
- Java Variables
- Java Literals
- Java Separators
- Java Datatypes
- Java Operators
- Java Statements
- Java Strings
- Java Arrays
- Control Statement
- Java If
- Java If-else
- Java If-else-if
- Java Nested If
- Java Switch
- Iteration Statement
- Java For Loop
- Java For Each Loop
- Java While Loop
- Java Do While Loop
- Java Nested Loop
- Java Break/Continue
- Java Methods
- Java Methods
- Java Method Parameters
- Java Method Overloading
- Java Recursion
- Java OOPS
- Java OOPs
- Java Classes/Objects
- Java Inheritance
- Java Polymorphism
- Java Encapsulation
- Java Abstraction
- Java Modifiers
- Java Constructors
- Java Interface
- Java static keyword
- Java this keyword
- Java File Handling
- Java File
- Java Create File
- Java Read/Write File
- Java Delete File
- Java Program To
- Add Two Numbers
- Even or Odd Numbers
- Reverse a String
- Swap Two Numbers
- Prime Number
- Fibonacci Sequence
- Palindrome Strings
- Java Reference
- Java String Methods
- Java Math Methods
Java Program To Reverse a String
Here's a simple Java program to reverse a string:
public class ReverseString {
public static void main(String[] args) {
// Input string
String str = "Hello, World!";
// Call the reverseString method and print the result
System.out.println("Original string: " + str);
System.out.println("Reversed string: " + reverseString(str));
}
// Method to reverse a string
public static String reverseString(String str) {
// Convert the string to a character array
char[] charArray = str.toCharArray();
// Initialize variables for indices
int left = 0;
int right = charArray.length - 1;
// Iterate through the character array and swap characters
while (left < right) {
// Swap characters at left and right indices
char temp = charArray[left];
charArray[left] = charArray[right];
charArray[right] = temp;
// Move indices towards the center
left++;
right--;
}
// Convert the character array back to a string
return new String(charArray);
}
}
This program defines a reverseString method that takes a string as input, converts it to a character array, and then iterates through the array to swap characters from both ends until the entire string is reversed. Finally, it returns the reversed string. The main method demonstrates how to use this method by passing a sample string and printing the original and reversed strings.