Computer Science, asked by MrTSR, 3 months ago

\bold{Computer\:Science\:Question}

乡 Write a program to display reverse string 乡

[ Write in JAVA! ]​

Answers

Answered by ajha22480
2

Answer:

See here :-

Explanation:

JAVA

public class Reverse.

{

public static void main(String[] args) {

String string = "Dream big";

//Stores the reverse of given string.

String reversedStr = "";

//Iterate through the string from last and add

each character to variable reversedStr.

for(int i = string.length()-1; i >= 0; i--){

Answered by Oreki
12

\text{\large\bf Different ways to Reverse a String in Java}

  \textsf{\textbf{Native Lo\symbol{111}ping Approach}}

       \texttt{String string = "Reverse", reversedString = "";}\\\texttt{for (int i = 1; i <= string.length(); i++)}\\\texttt{\hspace{1.5em} reversedString += string.charAt(string.length() - i);}\\\texttt{System.out.println("Reversed String - " + reversedString);}

  \textsf{\textbf{Array approach (modified lo\symbol{111}ping approach)}}

       \texttt{char[] string = "Reverse".toCharArray();}\\\texttt{String reversedString = "";}\\\texttt{for (int i = string.length - 1; i >= 0; i--)}\\\texttt{\hspace{1.5em} reversedString += string[i];}\\\texttt{\hspace{1.5em} \symbol{92}\symbol{92} Or directly print using System.out.print(string[i]);}\\\texttt{System.out.println("Reversed String - " + reversedString);}

  \textsf{\textbf{Using In-built classes (StringBuffer or StringBuilder)}}

       \texttt{StringBuffer sb = new StringBuffer("Reverse");}\\\texttt{sb.reverse();}\\\texttt{String reversedString = sb.toString();}\\\texttt{System.out.println("Reversed String - " + reversedString);}

       \textsf{\textit{Smaller version}}\\\begin{footnotesize}\texttt{String reversedString = new StringBuffer("Reverse").reverse().toString();}\\\texttt{System.out.println("Reversed String - " + reversedString);}\end{footnotesize}

           \textsf{StringBuilder can be used in the similar way and the only difference is}\\\textsf{StringBuffer is synchronized i.e. multiple threads can work on it and }\\\textsf{produce reliable results. StringBuilder is non-synchronized i.e.}\\\textsf{multiple threads can work on it and may produce unreliable results.}

Similar questions