- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to move an element of an array to a specific position (swap)?
To move an element from one position to other (swap) you need to –
- Create a temp variable and assign the value of the original position to it.
- Now, assign the value in the new position to original position.
- Finally, assign the value in the temp to the new position.
Example
import java.util.Arrays; public class ChangingPositions { public static void main(String args[]) { int originalPosition = 1; int newPosition = 1; int [] myArray = {23, 93, 56, 92, 39}; int temp = myArray[originalPosition]; myArray[originalPosition] = myArray[newPosition]; myArray[newPosition] = temp; System.out.println(Arrays.toString(myArray)); } }
Output
[23, 39, 56, 92, 93]
Advertisements