How to Add Prefix to each element of an Array in Java

Hello Coder’s in this Tutorial we will learn how to add Prefix to each element of an Array in Java. Or you can also say add a string to array elements in Java.

Explanation:

While accessing the array, update the element by adding the prefix with all the elements.

Steps:




  • Create an array with elements.
  • strArray is a collection. Str is a variable name.
  • Create a for loop. To go to the next element by incrementing.
  • It will add a prefix to the existing elements in an array.
  • Now calling for each loop. We will create a variable iteration
  • For (type var : collection )
  • Then we will print the value.

Java Program to add Prefix to each element of an Array

class Main {
  public static void main (String[] args) {
    String[] strArry = {"Banana", "Apple", "Mango"};
    for (int i=0 ; i < strArry.length; i++) {
      strArry[i] = "To Eat " + strArry[i];
    }
    
    for (String str: strArry) {
      System.out.println (str);
    }
  }
}

INPUT:

{"banana", "apple", "mango"}

PREFIX:

"To eat"

 

OUTPUT:

{"To eat banana", "To eat apple", "To eat mango"}

If you have any query regarding this tutorial you may comment in the below comment section. We will be happy to help you out.

You may also read:

Product of array elements except for the current index in Java
Java program to calculate surface area and volume of a sphere


Leave a Reply

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