• Register
140 points
4

This article explains how to reverse a string in java by converting String to the character array in simple steps. Reach out to the below-illustrated steps and find how to reverse a string using JAVA.

What is a String?

A String is a data type that represents a series/set of alphabets and it is mainly used to indicate text other than integers or any other data types. This set of characters may or may not contain spaces between characters or words. Integers can be even considered as a string if the correct data type is used. The string is enclosed within double quotes(“ “), we use a fundamental data type called ‘Char’ to store the character data. Similarly, to store the string data and to perform various operation on string data we use three pre-defined classes they are:
  1. String
  2. String Buffer
  3. String Builder

Approach

  • A string is a pre-defined class java.lang.* Package can be used to handle the string. 
  • String class is immutable which means where content cannot be changed at the time of execution of the program.
  • We use java.io.* pre-defined package, to perform I/O operations and also file operations. The package java.util.* performs scanner class, auto-boxing, and unboxing for each loop and data structure concept in JAVA, where util means utilities.
  • Firstly, as mentioned above, we need to convert the String to a character array by using the built-in java String Class method called toCharArray().
  • The method toCharArray() returns the array of Characters after the completion of converting a string into a sequence of characters. 
  • So this built-in function returns the array where its length is equal to the length of the actual string and the characters in the array are the same as the actual characters in the string.
  • The second step implies,  the scan of the array String from end to the start and thus followed by printing of the character is done one by one.

Program

import java.lang.*;

import java.io.*;

import java.util.*;

class ReverseString {

public static void main(String[] args)

{

String input = "MyFirstKodlogsarticle";

char[] sample = input.toCharArray();

for(int i = sample.length - 1; I>=0; i--)

System.out.println("Reversed String is");

System.out.println(sample[i]);

}

}

Output

Reversed String is
elcitrasgoledoCtsriFyM
 
140 points
4