Reversing an array, number, string and word is very important for interview point of view for all level of expertise.

Beginner and Experienced both are asked this question again and again in interview.

I will explain each one by one with working code and running it as screenshot.

Problem 1

Write a java code to reverse an array. for example if array is [apple, orange, banana] then after reverse it should look like [banana, orange, apple]

Approach

  1. Loop through the array in a reverse order.
  2. Store each element in a new array.

Code

import java.util.ArrayList;
import java.util.List;

public class ReverseArray {
	public static void main(String[] args) {
		ArrayList<String> fruits = new ArrayList<String>();
		
		fruits.add("apple");
		fruits.add("orange");
		fruits.add("banana");
		
		System.out.println(fruits);
		
		List<String> revFruits = new ArrayList<String>();
		
		for(int i=fruits.size()-1; i >= 0; i--) {
			revFruits.add(fruits.get(i));
		}
		
		System.out.println(revFruits);
		
	}

}

Run Code

Input array: [apple, orange, banana]
After Reverse: [banana, orange, apple]

Problem 2

Write a java code to reverse the number. For example If the number is 12345 then it reverse should be 54321.

Code

public class ReverseNumber {
   public static void main(String[] args) {
	   int num = 12345;
	   
	   System.out.println(num);
	   
	   int remainder = 0;
	   int rev = 0;
	   while (num > 0) {		   
		   remainder = num %10;
		   num = num/10;		   
		   rev = rev*10 + remainder;		   
	   }
	   
	   System.out.println(rev);
   }
}
Input number: 12345
After reverse: 54321

Problem 3

Write a java code to reverse a string. For example if Input string is seoinfotech then reverse should be hcetofnioes.

Code

import java.util.Scanner;

public class ReverseString {
	
	public static String revs(String str) {
		String revStr = "";
		
		for(int i = str.length() -1; i >=0; i--) {
			revStr = revStr + str.charAt(i);
		}
		
		return revStr;
	}
	
	public static void main(String[] args) {
		System.out.println("Enter string  ");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.next();        
        scanner.close();
        
        System.out.print(ReverseString.revs(str));
	}

}

Run Code

Enter string  
seoinfotech
hcetofnioes

Problem 4

Write a java program to reverse a sentence. For example if the input sentence is I Love Java Programming, then after reverse it should be Programming Java Love I

Code

public class ReverseWordString {
	public static void main(String[] args) {
		String str = "I Love Java Programming";
		
		System.out.println(str);
		
	    String[] strArr = str.split(" ");
						
		String finalStr = "";
		for(int i= strArr.length -1; i>=0; i--) {
			finalStr += strArr[i] + " ";
		}
		
		System.out.println(finalStr);
		
	}

Run Code

I Love Java Programming
Programming Java Love I 

So these are four scenario of reverse, in case we found more problem. I will happy to update the same.

Similar Posts