[Solved] How To Reverse A String In Place In Java? Example - Java67
Maybe your like
Pages
- Home
- core java
- spring
- online courses
- thread
- java 8
- coding
- sql
- books
- oop
- interview
- certification
- free resources
- best
Algorithm to Reverse a String in Place in Java
Here is a simple example to reverse characters in String by using two pointer technique. This is an in-place algorithm because it doesn't allocate any extra array, it just uses the two integer variables to hold positions from start and end. If you look closely this algorithm is similar to the algorithm we have earlier used to reverse an array in place. That's obvious because String is backed by character array in Java. If you know how to reverse an array in place then reversing a String is not different for you. What is more important is checking for null and empty String because this is where many programmers become lazy and started writing code without validating input. You must write your best code during programming interviews. The code which can stand the test of time in production is what every interview likes to see. If you don't know how to write production-quality code, I suggest you take a look at the Clean Code, one of the books you should read at the start of your programming career. Btw, if you are not familiar with recursion and iteration or basic fundamentals of Data Structures and Algorithms then I suggest you join a comprehensive course like Algorithms and Data Structures - Part 1 and 2 on Pluralsight to learn them well. It makes a lot of sense to solve problems like this when you know fundamentals better. Here is the iterative algorithm to reverse String in place:
Java Program to Reverse a Given String in Place - Example
import org.junit.Assert; import org.junit.Test; /** * Java Program to reverse a String in place, * without any additional buffer in Java. * * @author WINDOWS 8 * */ public class StringReversal { /** * Java method to reverse a String in place * @param str * @return reverse of String */ public static String reverse(String str) { if(str == null || str.isEmpty()){ return str; } char[] characters = str.toCharArray(); int i = 0; int j = characters.length - 1; while (i < j) { swap(characters, i, j); i++; j--; } return new String(characters); } /** * Java method to swap two numbers in given array * @param str * @param i * @param j */ private static void swap(char[] str, int i, int j) { char temp = str[i]; str[i] = str[j]; str[j] = temp; } @Test public void reverseEmptyString(){ Assert.assertEquals("", reverse("")); } @Test public void reverseString(){ Assert.assertEquals("cba", reverse("abc")); } @Test public void reverseNullString(){ Assert.assertEquals(null, reverse(null)); } @Test public void reversePalindromeString(){ Assert.assertEquals("aba", reverse("aba")); } @Test public void reverseSameCharacterString(){ Assert.assertEquals("aaa", reverse("aaa")); } @Test public void reverseAnagramString(){ Assert.assertEquals("mary", reverse("yram")); } } You might have also noticed that this time, I have not used the main() method to test the code, instead I have written a couple of JUnit test cases. It's actually better to write unit test cases all the time to test your code instead of using the main() method as it put unit testing in your habit. Btw, if you feel reluctant about writing unit tests or not sure how to write tests, I suggest you read Test Driven, one of the best books on Test drive development but even if you don't follow TDD, it will help you to write better code and unit tests. I have written the following JUnit tests to check whether our reverse method is working for different kinds of String or not, the JUnit test result is also attached below:- Unit test to reverse an empty String
- Test to reverse a null String
- Reverse a palindrome String
- Unit tests to reverse a one-character string
- JUnit test to reverse a string with the same character
- Reverse a String with a different character
- Reverse an anagram String
You can see that all the unit tests are passing, which is good. You can also add more unit tests to further test our method of reversing String in Java. Btw, If you are preparing for coding interviews then I also recommend Grokking the Coding Interview: Patterns for Coding Questions on Educative, an interactive portal to prepare for coding interviews. This text-based course will teach you some 16 useful coding patterns like Sliding Window, Two Pointers, Fast and Slow Pointers, Merge Intervals, Cyclic Sort, and Top K elements that can help you to solve many frequently asked coding problems on interview. It will also make you a better programmer because you know how to solve an unseen problem using existing patterns. That's all about how to reverse String in place in Java. This is a common algorithm that uses two pointer approach. Since it requires us to traverse the array till the middle, the time complexity is O(n/2) i.e. O(n). It doesn't use any external buffer instead just use two variables to keep track of indices from start and end. Other String based coding problems from Interviews: - How to print all permutations of a String using recursion? (solution)
- Top 5 Courses to learn Data Structure and Algorithms (courses)
- How to reverse String in Java without StringBuffer? (solution)
- Top 50 Data Structure and Algorithms Interview Questions (list)
- How to count the number of words in a given String? (solution)
- Top 5 Books to learn Data Structure and Algorithms (Books)
- How to check if a String is a palindrome in Java? (solution)
- Top 5 Courses to learn Dynamic Programming for Interviews (courses)
- How to find duplicate characters on String? (solution)
- How to find one missing number in a sorted array? (solution)
- How to remove an element from an array in Java? (solution)
- How to count vowels and consonants in a given String? (solution)
- Top 30 linked list coding interview questions (see here)
- Top 50 Java Programs from Coding Interviews (see here)
- 5 Free Data Structure and Algorithms Courses for Programmers (courses)
- 10 Algorithms Books Every Programmer Should Read (books)
- 10 Free Data Structure and Algorithm Courses for Programmers (courses)
- How to reverse words in a given String in Java? (solution)
- 21 String Programming Questions for Programmers (questions)
- 100+ Data Structure and Algorithms Questions for Java programmers (questions)
- 75+ Programming and Coding Interview questions (questions)
9 comments:
philJune 1, 2019 at 6:33 AMSorry, but Strings are immutable in Java. This post makes no mention of this extremely important fact. While it is true that the time complexity of the algorithm is O(n) and the space complexity is O(1), both the toCharArray() method and the new String(char[] buffer) constructor make COPIES of their arrays. This example is NOT reversal in place as that's not possible in Java (without unsafe shenanigans) and it does require the use of extra memory (the original String plus at least two array copies.
ReplyDeleteReplies- Reply
AnonymousJune 1, 2019 at 3:13 PMHow come it is O(1) space if this code creates a new array of characters?
ReplyDeleteReplies
philJune 3, 2019 at 11:26 AMMy mistake! The original article states that the algorithm is O(1) because it (wrongly) says it only uses 2 new variables regards of size of the string. Because two new arrays of the same size of the string are created the space needed will be either 3N or 2N, depending on whether or not you include the original string. Either way, the space complexity is O(n). That is, the space needed grows linearly with the size of the string.
DeleteReplies- Reply
Reply
UnknownAugust 9, 2019 at 3:13 PMvoid reverse( String A) { char[] yArray = new char[A.length()]; char xArray[] =new char[A.length()]; A.getChars(0, A.length(), xArray, 0); System.out.println(xArray); int j=xArray.length; for(int i=0;i<xArray.length; i++) { yArray[i]=xArray[j-1]; j--; System.out.println("character pushed at "+i+" is "+yArray[i]); } System.out.println("Reversed String is : "); System.out.println(yArray); }
ReplyDeleteReplies- Reply
AdityaDecember 17, 2019 at 5:36 PM//simple & efficient way without even declaring 3rd variablepublic static void reversingUsingSwappingLogic(String str) { char[] ca = str.toCharArray(); for(int i = 0; i < str.length()/2; i++) { ca[i] = (char) (ca[i] ^ ca[ca.length - 1 - i]); ca[ca.length - 1 - i] = (char) (ca[i] ^ ca[ca.length - 1 - i]); ca[i] = (char) (ca[i] ^ ca[ca.length - 1 - i]); } str = new String(ca); System.out.println(str); }
ReplyDeleteReplies- Reply
AnonymousJune 16, 2020 at 7:14 AMpublic class MyClass { public static void main(String args[]) { String s= "Nikunj"; Character temp=null; char[] c= s.toCharArray(); for(int i=0;i<c.length/2;i++){ temp=c[i]; c[i]=c[c.length-(i+1)]; c[c.length-(i+1)]=temp; } for(Character ccc:c) System.out.print(ccc); }}
ReplyDeleteReplies- Reply
UnknownSeptember 24, 2021 at 9:42 AM//THIS CODE WILL GIVE THE DESIRED RESULT. string str; cin>>str; for(int i=str.size(); i>=0; i--) { cout<<str[i]; }
ReplyDeleteReplies- Reply
Sukesh RFebruary 7, 2022 at 3:14 AM//This is Using the toCharArray() function to reverse a string in Javapublic static String reverse(String str) { String rev=""; char[] finalarray = str.toCharArray(); for (int i = finalarray.length - 1; i >= 0; i--) rev+=finalarray[i]; return rev;}//Sample Input- "Scaler Academy"//Sample Output-"ymedacA relacS"Reference: https://www.scaler.com/topics/reverse-a-string-in-java/
ReplyDeleteReplies- Reply
UnknownMarch 30, 2022 at 8:43 PMhere's the simplest way using a for loop, I thinkpublic static String reverseString(String s){ char [] a = s.toCharArray(); for(int i=0, j=s.length()-1; i<j; i++, j--) { char temp = a[i]; a[i] = a[j]; a[j] = temp; } return new String(a); }
ReplyDeleteReplies- Reply
Feel free to comment, ask questions if you have any doubt.
Newer Post Older Post Home Subscribe to: Post Comments (Atom)Recommended Courses
- best python courses
- best java courses
- system design courses
- best spring courses
- best hibernate courses
- best design pattern courses
- best Linux courses
- best JavaScript courses
- best data structure and algorithms courses
- Best Multithreading Courses
- best MERN stack courses
- Best Git courses
- Best Microservice Courses
- Best DevOps Courses
- best MEAN stack Courses
- free Java courses
- free DSA courses
- free sql courses
- free Linux courses
- Free Docker courses
- free JUnit courses
String Tutorials
- string - 101 guide
- string - contains
- string - check unique
- string - rotation
- string - count words
- string - join
- string - substring
- string - split
- string - palindrome
- string - reverse words
- string - byte array
- string - to enum
- string - compare
- string - empty
- string - stringbuffer
- string - duplicate
- string - immutable
- string - split regex
- string - remove whitespace
- string - toLowerCase
- string - reverse
Categories
- .NET
- abstract class
- Affiliate marketing
- After Effects
- Agentic AI
- Agile
- AI Tools
- Amazon Web Service
- android
- Angular
- Anonymous class
- Ansible
- apache camel
- Apache kafka
- Apache spark
- app development
- array
- ArrayList
- Artificial Intelligence
- automation
- aws
- aws certification
- Azure Certifications
- backend development
- bash
- basics
- beginners
- best of java67
- best practices
- Big Data
- binary tree
- bit manipulation
- black friday deals
- Blockchain
- BlockingDeque
- books
- Bootstrap
- business analysis
- ByteByteGo
- C programming
- C++
- Career
- ChatGPT
- Chef
- cloud certification
- Cloud Computing
- Code Example
- Code Review
- codecademy
- Codemia
- CodeRabbit
- coding
- coding exercise
- Coding Interview
- Coding Problems
- Comparator
- computer science
- Computer Vision
- concurrency tutorial
- ConcurrentHashMap
- core java
- core java interview question answer
- course review
- Coursera
- courses
- crontab
- CSS
- Cyber Monday
- Cyber Security
- Data Analysis
- data science
- data structure and algorithm
- Data Visualization
- database
- datacamp
- date and time
- debugging
- deep learning
- default methods
- design pattern
- DevOps
- DevSecOps
- Distributed Systems
- Django
- docker
- double
- Drawing
- DSA
- dyanmic programming
- dynamic Programming
- eBooks
- Eclipse
- EJB
- enum
- equals
- error and exception
- Ethical hacking
- Excel
- exception
- Exponent
- expressjs
- FAANG
- Figma
- Firebase
- flatmap
- float
- Flutter
- free resources
- freelancing
- Frontend Masters
- fun
- Fundamental
- fundamentals
- Game development
- garbage collection
- general
- Generics
- gifts
- git and github
- golang
- Google Cloud Certification
- Google Cloud Platform
- Gradle
- grails
- graph
- graphic design
- grep
- Groovy
- gRPC
- Hadoop
- HashMap
- HashSet
- haskell
- Hibernate
- Hibernate interview Question
- homework
- HTML
- HTTP
- HttpClient
- i
- interface
- Internet of Things (IoT)
- interview
- interview questions
- IT Certification
- J2EE
- Jackson
- java
- Java 5 tutorial
- java 7
- Java 8
- java 9
- java basics
- Java Certification
- Java collection tutorial
- java concurrency tutorial
- java design pattern
- Java Enum
- Java file tutorials
- Java Functional Programming
- Java Installation Guide
- Java Interview Question
- Java interview questions
- Java IO interview question
- java io tutorial
- java map tutorials
- java modules
- Java Multithreading Tutorial
- Java networking tutorial
- Java Operator tutorial
- Java programming Tutorial
- Java String tutorial
- Java7
- JavaScript
- JavaScript Interview Question
- JavaScript Tutorial
- JDBC
- JEE Interview Questions
- Jenkins
- JMS
- JPA
- jQuery
- JSON
- JSP
- JSP Interview Question
- JSTL
- JUnit
- JVM
- Keras
- keystore
- Kotlin
- kubernetes
- lambda expression
- Laraval
- learning
- linked list
- Linux
- Log4j
- logging
- Lombok
- LSAT
- Mac OS X
- machine learning
- Mathematics
- Matlab
- Maven
- MERN stack
- Messaging
- Microservices
- Microsoft
- Microsoft Azure Platform
- Microsoft Excel
- Microsoft Power BI
- Mockito
- MongoDB
- MysQL
- MySQL tutorial example
- nested class
- neural network
- Next.js
- NFT
- NLP
- Node.js
- nslookup
- object oriented programming
- OCAJP
- OCMJEA
- OCPJP
- offers
- Oracle
- Perl
- personal development
- Photoshop
- PHP
- pluralsight
- PostgerSQL
- postman
- Powerpoint
- programmers
- programming
- programming problems
- Project Management
- projects
- Prompt Engineering
- Python
- Pytorch
- Quarkus
- questions
- Queue
- R programming
- React
- React Hooks
- react native
- Record
- Recursion
- Redux
- regular expression example
- REST tutorials
- Review
- RoadMap
- Ruby
- Salesforce
- SAT
- Scala
- Scala Interview Questions
- Scalability
- Scanner
- scripting
- Scrum
- Scrum Master Certification
- Selenium
- SEO
- Serialization
- Servlet
- Servlet Interview Questions
- Set
- shell scripting
- smart contracts
- Snowflake SnowPro Certification
- soft link
- soft skills
- software architecture
- Solaris
- Solidity
- Sorting Algorithm
- Spark
- spring boot
- Spring Certification
- spring cloud
- spring data jpa
- spring framework
- spring interview question
- spring mvc
- spring security
- sql
- SQL interview Question
- SQL Joins
- SQL SERVER
- ssl
- Static
- Statistics
- Stream
- String
- Struts
- Swift
- swing
- switch case
- system design
- System Design Interview Questions
- Tableau
- Tailwind
- TensorFlow
- ternary operator
- testing
- thread
- thread interview questions
- Time series analysis
- Tips
- tomcat
- tools
- tree
- TreeMap
- troubleshooting
- TypeScript
- Udacity
- Udemy
- UI and UX Design
- UML
- unit testing
- Unity 3D
- Unix
- unreal engine
- Video Editing
- Vuejs
- web design
- web development
- web scrapping
- Web Service
- Whizlabs
- Wix
- xml
- YAML
- ZTM Academy
Best System Design and Coding Interview Resources
System Design & Interview Prep
- ByteByteGo Lifetime Plan (50% OFF)
- Codemia Lifetime Plan (60% OFF)
- Exponent Annual Plan (70% OFF)
- Educative Premium Plus (55% OFF)
- DesignGurus All Course Bundle (55% OFF)
- Everything Java Interview Bundle (50% OFF)
- 101 Blockchain (50% OFF)
- Vlad Mihalcea's High Performance Bundle (50% OFF)
- Javarevisited Substack Subscription (50% OFF)
- Head First Software Architecture (Book)
Search This Blog
Best Online Learning Resources and Platforms
- Coursera Plus (40% OFF)
- Datacamp Sale (50% OFF)
- AlgoMonster Lifetime Plan (50% OFF)
- Udemy Sale (80% OFF)
- Baeldung (33% OFF)
- LabEx Sale (50% OFF)
- Codecademy Sale (60% OFF)
- Udacity Sale (50% OFF)
- ZTM Academy Sale (66% OFF)
- Frontend Masters Deal
- Whizlabs Deal (70% OFF)
Javarevisited
Loading...Spring Interview Prep List
- Spring Boot Interview questions
- Spring Cloud Interview questions
- Spring MVC Interview Questions
- Microservices Interview questions
- 10 Spring MVC annotations
- Spring Boot Courses
- Spring Framework Courses
Subscribe for Discounts and Updates
FollowInterview Questions
- core java interview questions
- SQL interview questions
- data structure interview question
- coding interview questions
- java collection interview questions
- java design pattern interview questions
- thread interview questions
- hibernate interview questions
- j2ee interview questions
- Spring Interview Questions
- object oriented programming questions
Followers
Blog Archive
- ► 2026 (13)
- ► February (6)
- ► January (7)
- ► 2024 (192)
- ► December (30)
- ► October (32)
- ► September (31)
- ► August (12)
- ► July (3)
- ► June (2)
- ► May (9)
- ► April (3)
- ► March (28)
- ► February (3)
- ► January (39)
- ► 2023 (380)
- ► December (1)
- ► November (2)
- ► October (4)
- ► September (154)
- ► August (12)
- ► July (23)
- ► May (9)
- ► April (116)
- ► March (15)
- ► February (35)
- ► January (9)
- ► 2022 (164)
- ► December (18)
- ► October (1)
- ► September (1)
- ► August (45)
- ► July (27)
- ► June (11)
- ► May (19)
- ► April (16)
- ► March (12)
- ► February (6)
- ► January (8)
- ► 2021 (104)
- ► December (6)
- ► November (2)
- ► October (13)
- ► September (18)
- ► August (31)
- ► July (34)
- ► 2020 (10)
- ► August (2)
- ► July (1)
- ► June (1)
- ► April (3)
- ► March (1)
- ► February (2)
- ► 2019 (9)
- ► December (1)
- ► November (1)
- ► October (1)
- ► September (1)
- ► July (1)
- ► June (1)
- ► April (3)
- ► 2018 (9)
- ► November (1)
- ► April (8)
- ► 2017 (4)
- ► October (1)
- ► September (2)
- ► April (1)
- ► 2015 (8)
- ► July (1)
- ► June (1)
- ► May (1)
- ► February (5)
- ► 2012 (1)
- ► September (1)
Privacy
- Privacy Policy
- Terms & Conditions
Popular Posts
- 17 Free Java Programing Books for Beginners in 2025 - download, pdf and HTML
- How to fix "illegal start of expression" error in Java? Example
- 5 Examples of Formatting Float or Double Numbers to String in Java
- Top 10 Websites to Learn JavaScript Coding for FREE in 2025 - Best of Lot
- Top 10 Frequently asked SQL Query Interview Questions Answers
Subscribe
Get new posts by email:
SubscribeTag » How To Reverse A String In Java
-
Reverse A String In Java - GeeksforGeeks
-
Reverse A String In Java - Stack Overflow
-
How To Reverse A String In Java Using Different Methods - Simplilearn
-
How To Reverse String In Java - Javatpoint
-
How To Reverse A String In Java - Baeldung
-
Know How To Reverse A String In Java – A Beginners Guide - Edureka
-
Reverse A String In Java With Example - FavTutor
-
Reverse A String In Java In 10 Different Ways - Techie Delight
-
Reverse A String In Java - Interview Kickstart
-
Reverse A String In Java - Scaler Topics
-
String Reverse - Java Examples - Tutorialspoint
-
How To Reverse A String In Java
-
Reverse A String In Java
-
Reverse A String In Java - CodeGym
phil
Anonymous