Wednesday 22 April 2020

How to initialize String array

Approach 1
String[] str1 = { "Hello", "World" };

Approach 2
String[] str2 = new String[] { "Hello", "World" };

Approach 3
String[] str3 = new String[2];
str3[0] = "Hello";
str3[1] = "World";

Approach 4
String[] str4 = Stream.of("Hello", "World").toArray(String[]::new);

App.java
package com.sample.app;

import java.util.stream.Stream;

public class App {

	private static void printArray(String[] arr) {
		for (String str : arr) {
			System.out.print(str + " ");
		}
		System.out.println();
	}

	public static void main(String args[]) {

		// Approach 1
		String[] str1 = { "Hello", "World" };

		// Approach 2
		String[] str2 = new String[] { "Hello", "World" };

		// Approach 3
		String[] str3 = new String[2];
		str3[0] = "Hello";
		str3[1] = "World";

		// Approach 4
		String[] str4 = Stream.of("Hello", "World").toArray(String[]::new);

		printArray(str1);
		printArray(str2);
		printArray(str3);
		printArray(str4);

	}

}

Output
Hello World
Hello World
Hello World
Hello World


You may like

No comments:

Post a Comment