- How to reverse a string in java without using reverse function
- Reverse a string in java
- Write a program to reverse string without using any function java
- First of all "there is no direct built in function or method in string class to reverse a string" but still it is frequently asked question in java interviews.
- It's not possible to reverse a string without using string methods. (length(),chgarAt())
public static String reverseString(String s) {
char[] chars = s.toCharArray();
int left = 0;
int right = chars.length - 1;
while (left < right) {
char temp = chars[left];
chars[left] = chars[right];
chars[right] = temp;
left++;
right--;
}
return new String(chars);
}
This method converts the input string to a character array using the toCharArray() method. Then, it initializes two pointers, left and right, to the first and last positions in the array, respectively.
Then, it enters a while loop that continues as long as the left pointer is less than the right pointer. In each iteration of the loop, the characters at the positions indicated by the left and right pointers are swapped using a temporary variable. Then, the left and right pointers are incremented and decremented, respectively.
Finally, the reversed character array is converted back to a string and returned.
This method is more efficient than using string functions because strings are immutable in Java and any operation that modifies the string creates a new object, whereas a character array can be modified in place.
- Lets discuss on how to reverse a string in java with using any built in string functions or methods.
- Using charAt() function/method
1:Using charAt():
- Take a for loop and iterate string by checking length of the string from n to 1.
- Use charAt() method of string and take each character and append to another string.
- By the end of the loop you will get all characters in reverse order.
- Like this we can reverse a string in java with using string method.
#1: Reverse a string in java with using inbuilt function
- package com.instaceofjava;
- public class ReverseString {
- public static void main(String[] args) {
- String str="Hello world";
- String revstring="";
- for(int i=str.length()-1;i>=0;--i){
- revstring +=str.charAt(i);
- }
- System.out.println(revstring);
- }
- }
OutPut:
- dlrow olleH
- This program reads a string from the user, and then uses a loop to iterate over the characters in the string in reverse order. It appends each character to a new string called reversed, and then prints out the reversed string after the loop has finished.
- Note that this program does not modify the original string, but creates a new reversed string instead. If you want to reverse the original string in place, you can use an array of characters instead of a string, and swap the elements at opposite ends of the array until you reach the middle.
- This program works by first converting the input string to a character array using the toCharArray method.
- It then uses two pointers, i and j, to traverse the array from opposite ends. On each iteration, it swaps the characters at indices i and j, and increments i and decrements j until they meet in the middle.
- Finally, it converts the reversed character array back to a string using the String constructor.
2: Using StringBuffer Object:
Another way to reverse a string in Java without using any built-in string functions is to use a StringBuilder or StringBuffer object.
Here is an example using a StringBuilder:
public static String reverseString(String s) {
StringBuilder sb = new StringBuilder(s);
return sb.reverse().toString();
}
Here, the input string is passed to the constructor of the StringBuilder object. Then, the reverse() method is called on the object, which reverses the order of the characters in the string. Finally, the toString() method is called on the StringBuilder object to convert it back to a string and return it.
StringBuffer is similar to StringBuilder, it is thread safe, whereas StringBuilder is not.
public static String reverseString(String s) {
StringBuffer sb = new StringBuffer(s);
return sb.reverse().toString();
}
The above approach is more efficient than the previous one that used a character array because it avoids the need to create a temporary array and copy the characters to it.
In both cases, the method takes a single string parameter and returns the reversed version of it.
- Print prime numbers?
- What happens if we place return statement in try catch blocks
- Write a java program to convert binary to decimal
- Java Program to convert Decimal to Binary
- Is it possible to print message without using System.out.println()
- Java program to restrict a class from creating not more than three objects
- Java basic interview programs on this keyword
- Java Program to Sort elements of Java ArrayList Example
- Interfaces allows constructors?
- Can we create static constructor in java
- Super keyword interview questions java
- Java interview questions on final keyword
- Can we create private constructor in java
- Java Program Find Second highest number in an integer array
- Java interview programming questions on interfaces
- Top 15 abstract class interview questions
- Java interview Questions on main() method
- Sort employee object by id in descending order using comparable and TreesSet
- Top 20 collection framework interview Questions
- Java Interview Program to find smallest and second smallest number in an array
- Java Coding Interview programming Questions : Java Test on HashMap
- Explain java data types with example programs
- How to check internet connection using java
- Constructor chaining in java with example programs
- Top 10 Interview Programs and questions on method overriding in java
- Swap two numbers without using third variable in java
- Find sum of digits in java
- How to create immutable class in java
- AtomicInteger in java
- Check Even or Odd without using modulus and division
- String Reverse Without using String API
- Find Biggest substring in between specified character
- Check string is palindrome or not?
- Reverse a number in java?
- Fibonacci series with Recursive?
- Fibonacci series without using Recursive?
- Sort the String using string API?
- Sort the String without using String API?
- what is the difference between method overloading and method overriding?
- How to find largest element in an array with index and value ?
- Sort integer array using bubble sort in java?
- Object Cloning in java example?
- Method Overriding in java?
- Program for create Singleton class?
- Print numbers in pyramid shape?
- Check armstrong number or not?
- Producer Consumer Problem?
- Remove duplicate elements from an array
- Convert Byte Array to String
- Print 1 to 10 without using loops
- Add 2 Matrices
- Multiply 2 Matrices
- How to Add elements to hash map and Display
- Sort ArrayList in descending order
- Sort Object Using Comparator
- Count Number of Occurrences of character in a String
- Can we Overload static methods in java
- Can we Override static methods in java
- Can we call super class static methods from sub class
- Explain return type in java
- Can we call Sub class methods using super class object?
- Can we Override private methods ?
- Basic Programming Questions to Practice : Test your Skill
- Java programming interview questions on collections
No comments