'java reverse string space should be at the same place

I tried this code reverse string space should be at the same place, this code taking input but output not printing not getting error also i'm trying to print output like this

input: java string output:gnir tsavaj

    import java.util.*;
    public class Main
    {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter String");
    String str=sc.nextLine();
    char arr1[]=str.toCharArray();
    char arr2[]=new char[arr1.length];
    for(int i=0;i<=arr1.length-1;i++)
    {
       if(arr1[i]==' ')
       {
           arr2[i]=arr1[i];
       }
   
       for(int j=0;j<=arr1.length-1;j++)
        {
            if(arr2[i]!=' ')
            {
             if(arr2[j]==' ')
            {
                 j--;
            }
            arr2[j]=arr1[i];
            j--;
            }
        }
   }
   str=new String(arr2);
   System.out.print(str);

   }
}


Solution 1:[1]

Just loop your string backwards and add each string to new String.

Below code might help you .

import java.util.*;

    public class Main
    {
    public static void main(String[] args) {
    Scanner sc=new Scanner(System.in);
    System.out.println("Enter String");
    String str=sc.nextLine();
    String revstr="";
    
    int j = 0;
     
     for (int i=str.length()-1; i>=0; i--)
     {
         revstr+= str.charAt(i); 
     }
     
   System.out.print(revstr);
   }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Babji Polisetti