Monday, 27 April 2020

How to initialize string array?

Following are different ways to initialize string array.

Approach 1: Using literal notation
String[] str1 = { "Hello", "How", "Are", "You" };

Approach 2: By defining the array and initialize elements using index notation.
String[] str2 = new String[4];
str2[0] = "Hello";
str2[1] = "How";
str2[2] = "Are";
str2[3] = "You";

Approach 3: Using literal notation
String[] str3 = new String[] { "Hello", "How", "Are", "You" };

Approach 4: Using Stream.of method
String[] str4 = Stream.of("Hello", "How", "Are", "You").toArray(String[]::new);

Approach 5: Using streams.
String[] str5 = Arrays.asList("Hello", "How", "Are", "You").stream().toArray(String[]::new);

Find the below working application.

App.java
package com.sample.app;

import java.util.Arrays;
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[]) {
  String[] str1 = { "Hello", "How", "Are", "You" };

  String[] str2 = new String[4];
  str2[0] = "Hello";
  str2[1] = "How";
  str2[2] = "Are";
  str2[3] = "You";

  String[] str3 = new String[] { "Hello", "How", "Are", "You" };

  String[] str4 = Stream.of("Hello", "How", "Are", "You").toArray(String[]::new);

  String[] str5 = Arrays.asList("Hello", "How", "Are", "You").stream().toArray(String[]::new);

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

}

Output
Hello How Are You
Hello How Are You
Hello How Are You
Hello How Are You
Hello How Are You


You may like

No comments:

Post a Comment