Display Strings with Varargs in Java


Create a Java program to display strings passed as arguments using a method with varargs

  • The class DisplayStrings contains a single static method display that takes a variable number of strings as input (using varargs).
  • Inside the display method, a for-each loop is used to iterate over each string in the strings array.
  • During each iteration, the current string str is printed to the console using System.out.println.
  • In the main method, the display method is called with five strings ("Blue", "Pink", "White", "Black", "Yellow") passed as arguments.
  • As a result, each of these strings is printed to the console on separate lines.

Source Code

public class DisplayStrings
{
	static void display(String... strings)
	{
		for (String str : strings)
		{
			System.out.println(str);
		}
	}
 
	public static void main(String[] args)
	{
		display("Blue", "Pink", "White", "Black", "Yellow");
	}
}

Output

Blue
Pink
White
Black
Yellow

Example Programs