Table of Contents
Show you some examples
Example
algorithm
Algorithm 1 (by using the third variable)
Algorithm 2 (without using the third variable)
grammar
Multiple methods
Method 1: Use the third variable
Output
Method 2: Do not use the third variable
Home Java javaTutorial How to modify two array elements in Java

How to modify two array elements in Java

Sep 13, 2023 pm 07:45 PM
array element Revise

How to modify two array elements in Java

An array is a linear data structure in which elements are stored in contiguous memory locations.

According to the problem statement, we have to change two array elements with each other. In other words, changing two array elements can also be called swapping or swapping two elements

Let’s explore this article and see how it can be done using the Java programming language.

Show you some examples

Example 1

Suppose we have the following array = [10, 2, 3, -5, 99, 12, 0, -1]

Now if we swap the 5th and 8th elements,

Then, we got the new array [10, 2, 3, -5, -1, 12, 0, 99]

Example 2

Suppose we have the following array = [55, 10, 29, 74, 12, 45, 6, 5, 269]

Now if we swap the fourth and eighth elements

Then, we got the new array [55, 10, 29, 5, 12, 45, 6, 74, 269]

Example 3

Suppose we have the following array = [556, 10, 259, 874, 123, 453, -96, -54, -2369]

Now if we swap the second and sixth elements

Then, we got the new array [556, 453, 259, 874, 123, 10, -96, -54, -2369]

algorithm

Algorithm 1 (by using the third variable)

  • Step 1 - After storing the array, take two indices to swap the elements.

  • Step 2 - Store the first element in a temporary variable.

  • Step 3 - Now store the second element value in the first element

  • Step 4 - Finally store the temporary variable value in the second element.

  • Step 5 - Print the array elements.

Algorithm 2 (without using the third variable)

  • Step 1 - After storing the array, take two indices to swap the elements.

  • Step 2 - Add the first and second elements and store them in the first element.

  • Step 3 - Subtract the second element from the first element and store it in the second element.

  • Step 4 - Again subtract the second element from the first element and store it in the first element.

  • Step 5 - Print the array elements.

grammar

To get the length of an array (the number of elements in the array), arrays have a built-in property, length.

The following is its syntax -

array.length
Copy after login

Among them, "array" refers to the array reference.

You can use the Arrays.sort() method to sort an array in ascending order.

Arrays.sort(array_name);
Copy after login

Multiple methods

We provide solutions in different ways.

  • Use a third variable to change two array elements.

  • Change two array elements without using a third variable.

Let’s look at the program and its output one by one.

Method 1: Use the third variable

In this method, we change the array element by using another variable that temporarily holds the value of an element.

Example

import java.io.*;
import java.util.Arrays;
public class Main {
   public static void main(String[] args) {
      
      // The array elements
      int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 };
      
      // Print all array elements
      System.out.println("The array elements before swapping are-");
      for (int i : arr) {
         System.out.print(i + " ");
      }
      
      // We will be swapping 2nd index element with 4th index element
      int firstIndex = 2, secondIndex = 4;
      
      // Temp variable
      int temp = arr[firstIndex];
      
      // Swapping
      arr[firstIndex] = arr[secondIndex];
      arr[secondIndex] = temp;
      
      // Print all array elements
      System.out.println("\nThe array elements after swapping are-");
      for (int i : arr) {
         System.out.print(i + " ");
      }
   }
}
Copy after login

Output

The array elements before swapping are-
10 2 3 -5 99 12 0 -1 
The array elements after swapping are-
10 2 99 -5 3 12 0 -1 
Copy after login
Copy after login

Method 2: Do not use the third variable

In this method, unlike the previous method, we can change the array elements without using other variables.

Example

import java.io.*;
import java.util.Arrays;
public class Main {
   public static void main(String[] args) {
      // The array elements
      int arr[] = { 10, 2, 3, -5, 99, 12, 0, -1 };
      
      // Print all array elements
      System.out.println("The array elements before swapping are-");
      for (int i : arr) {
         System.out.print(i + " ");
      }
      
      // We will be swapping 2nd index element with 4th index element
      int firstIndex = 2, secondIndex = 4;
      
      // Swapping array elements
      arr[firstIndex] = arr[firstIndex] + arr[secondIndex];
      arr[secondIndex] = arr[firstIndex] - arr[secondIndex];
      arr[firstIndex] = arr[firstIndex] - arr[secondIndex];
      
      // Print all array elements
      System.out.println("\nThe array elements after swapping are-");
      for (int i : arr) {
         System.out.print(i + " ");
      }
   }
}
Copy after login

Output

The array elements before swapping are-
10 2 3 -5 99 12 0 -1 
The array elements after swapping are-
10 2 99 -5 3 12 0 -1 
Copy after login
Copy after login

In this article, we explored how to change two array elements using the Java programming language.

The above is the detailed content of How to modify two array elements in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk How to change the personal name in the group on DingTalk_How to modify the personal name in the group on DingTalk Mar 29, 2024 pm 08:41 PM

1. First open DingTalk. 2. Open the group chat and click the three dots in the upper right corner. 3. Find my nickname in this group. 4. Click to enter to modify and save.

How to remove duplicate elements from PHP array using foreach loop? How to remove duplicate elements from PHP array using foreach loop? Apr 27, 2024 am 11:33 AM

The method of using a foreach loop to remove duplicate elements from a PHP array is as follows: traverse the array, and if the element already exists and the current position is not the first occurrence, delete it. For example, if there are duplicate records in the database query results, you can use this method to remove them and obtain results without duplicate records.

How to modify the address location of published products on Xianyu How to modify the address location of published products on Xianyu Mar 28, 2024 pm 03:36 PM

When publishing products on the Xianyu platform, users can customize the geographical location information of the product according to the actual situation, so that potential buyers can more accurately grasp the specific location of the product. Once the product is successfully put on the shelves, there is no need to worry if the seller's location changes. The Xianyu platform provides a flexible and convenient modification function. So when we want to modify the address of a published product, how do we modify it? This tutorial guide will provide you with a detailed step-by-step guide. I hope it can help. Everyone! How to modify the release product address in Xianyu? 1. Open Xianyu, click on what I published, select the product, and click Edit. 2. Click the positioning icon and select the address you want to set.

PHP array key value flipping: Comparative performance analysis of different methods PHP array key value flipping: Comparative performance analysis of different methods May 03, 2024 pm 09:03 PM

The performance comparison of PHP array key value flipping methods shows that the array_flip() function performs better than the for loop in large arrays (more than 1 million elements) and takes less time. The for loop method of manually flipping key values ​​takes a relatively long time.

PHP array multi-dimensional sorting practice: from simple to complex scenarios PHP array multi-dimensional sorting practice: from simple to complex scenarios Apr 29, 2024 pm 09:12 PM

Multidimensional array sorting can be divided into single column sorting and nested sorting. Single column sorting can use the array_multisort() function to sort by columns; nested sorting requires a recursive function to traverse the array and sort it. Practical cases include sorting by product name and compound sorting by sales volume and price.

The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy The Art of PHP Array Deep Copy: Using Different Methods to Achieve a Perfect Copy May 01, 2024 pm 12:30 PM

Methods for deep copying arrays in PHP include: JSON encoding and decoding using json_decode and json_encode. Use array_map and clone to make deep copies of keys and values. Use serialize and unserialize for serialization and deserialization.

Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Best Practices for Deep Copying PHP Arrays: Discover Efficient Methods Apr 30, 2024 pm 03:42 PM

The best practice for performing an array deep copy in PHP is to use json_decode(json_encode($arr)) to convert the array to a JSON string and then convert it back to an array. Use unserialize(serialize($arr)) to serialize the array to a string and then deserialize it to a new array. Use the RecursiveIteratorIterator to recursively traverse multidimensional arrays.

Application of PHP array grouping function in data sorting Application of PHP array grouping function in data sorting May 04, 2024 pm 01:03 PM

PHP's array_group_by function can group elements in an array based on keys or closure functions, returning an associative array where the key is the group name and the value is an array of elements belonging to the group.

See all articles