Site icon TestingDocs.com

Java Program for Reverse of a String

Overview

In this post, we will learn to write a Java program to reverse of a string using for loop. charAt() method is an inbuilt String method that returns the character specified in the index. 

Tools used:

 

Description

In this program, we have taken an input string from the user. In a loop, we have printed each character is the reverse fashion using a for loop.  charAt() method is an inbuilt String method that returns the character specified in the index.

For example, if the string variable is str with contents:

String str = “TestingDocs”;

str.charAt(7) would return the character ‘D’. The input parameter for the charAt() is Integer index. This value should be within some bounds for the method to work. The method might throw an exception StringIndexOutOfBoundsException if the value is negative or not less than the length of the string. 

For example, in the above example str.charAt(17) would result in 

java.lang.StringIndexOutOfBoundsException String index out of range Exception. 

Eclipse IDE Setup

Some steps and instructions to create a Java application on Eclipse IDE:

https://www.testingdocs.com/create-a-new-java-project-in-eclipse/

https://www.testingdocs.com/create-java-package-in-eclipse-ide/

https://www.testingdocs.com/create-a-new-java-class-in-a-project/

https://www.testingdocs.com/run-java-project-in-eclipse/

Program Code

import java.util.Scanner;

/**************************************************
 * ReverseOfString.java
 * @program : Java program to reverse a String
 * @web : www.TestingDocs.com
 * @author :
 * @version : 1.0
 **************************************************/ 

class ReverseOfString { 
  public static void main(String[ ] arg) { 
    String str; 
    char ch; 
    Scanner sc=new Scanner(System.in); 
    System.out.print("Enter a string : "); 
    str=sc.nextLine(); 
    System.out.println("Reverse of a String '"+str+"' is :"); 
    for(int j=str.length();j>0;--j) {
      System.out.print(str.charAt(j-1)); 
    } 
  } 
}

 

Screenshot

Output

Enter a string: how are you
Reverse of a String ‘how are you’ is :
uoy era woh

 

Java Tutorial on this website: https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/in/java/

Exit mobile version