Skip to main content

Java String Interview Questions and Answers

Java String Interview Questions

  1. Reverse a string in java?
  2. Compare two Strings in java program?
  3. Can we use String in switch case?


Reverse a string in java?

We can reverse a string in java by using given below 3 ways:

1- Using for loop and charAt() method

ReverseString.java

package in.techmentor.string.demo;

public class ReverseString {

	public static void main(String[] args) {
		String str = "ABCD";
		String reverseStr = "";
		for (int i = str.length() - 1; i >= 0; i--) {
			reverseStr = reverseStr + str.charAt(i);
		}
		System.out.print(reverseStr);
	}
}

Output:

DCBA

2- Using StringBuffer/StringBuilder class built in reverse() method

ReverseString.java

package in.techmentor.string.demo;

public class ReverseString {

	public static void main(String[] args) {
		String str = "ABCD";
		String reverseStr = null;
		StringBuffer strBuffer = new StringBuffer(str);
		reverseStr = strBuffer.reverse().toString();
		System.out.print(reverseStr);
	}
}

Output:

DCBA

3- Using Collection framework ArrayList class

ReverseString.java

package in.techmentor.string.demo;

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

public class ReverseString {

	public static void main(String[] args) {
		String str = "ABCD";
		List<Character> arrayList = new ArrayList<>();
		char[] charArray = str.toCharArray();

		for (char c : charArray) {
			arrayList.add(c);
		}

		Collections.reverse(arrayList);
		StringBuffer strBuffer = new StringBuffer();

		for (char c : charArray) {
			strBuffer.append(c);
		}

		String reverseStr = strBuffer.toString();
		System.out.println(reverseStr);
	}
}

Output:

DCBA


Compare two Strings in java program?



Can we use String in switch case?

Leave a Reply

Your email address will not be published. Required fields are marked *

Top