Java string list argument

What is String args[ ] in Java?

Java Course - Mastering the Fundamentals

String args[] in java is an array of type java.lang.String class that stores java command line arguments. Here, the name of the String array is args (short form for arguments), however it is not necessary to name it args always, we can name it anything of our choice, but most of the programmers prefer to name it args.

We can write String args[] as String[] args as well, because both are valid way to declare String array in Java.

From Java 5 onwards, we can use variable arguments in main() method instead of String args[] . This means that the following declaration of main() method is also valid in Java : public static void main(String. args) , and we can access this variable argument as normal array in Java.

Why is String. args[] in Java Needed?

Varargs or Variable Arguments in Java was introduced as a language feature in J2SE 5.0. This feature allows the user to pass an arbitary number of values of the declared date type to the method as parameters (including no parameters) and these values will be available inside the method as an array. While in previous versions of Java, a method to take multiple values required the user to create an array and put those values into the array before invoking the method, but the new introduces varargs feature automates and hides this process.

The dots or periods( . ) are known as ELLIPSIS , which we usually use intentionally to omit a word, or a whole section from a text without altering its original meaning. The dots are used having no gap in between them.

The three periods( . ) indicate that the argument may be passed as an array or as a sequence of arguments. Therefore String… args is an array of parameters of type String, whereas String is a single parameter. A String[] will also fulfill the same purpose but the main point here is that String… args provides more readability to the user. It also provides an option that we can pass multiple arrays of String rather than a single one using String[] .

Читайте также:  Java приоритет логических операций

Example to Modify our Program to Print Content of String args[] in Java

When we run a Java program from command prompt, we can pass some input to our Java program. Those inputs are stored in this String args array. For example if we modify our program to print content of String args[] , as shown below:

The following Java Program demonstrates the working of String[] args in the main() method:

Compile the above program using the javac Test.java command and run the compiled Test file using the following command:

Explanation:

In the above example, we have passed three arguments separated by white space during execution using java command. If we want to combine multiple words, which has some white space in between, then we can enclose them in double quotes. If we run our program again with following command:

Conclusion

  • string args[] in java is an array of type java.lang.String class that stores java command line arguments.
  • Variable argument or varargs in Java allows us to write more flexible methods which can accept as many arguments as we need
  • The three periods(. ) in String… args[] indicate that the argument may be passed as an array or as a sequence of arguments.
  • (String… args) is an array of parameters of type String, whereas String[] is a single parameter. String[] can full fill the same purpose but just (String… args) provides more readability and easiness to use.

Источник

Java String Array

Java String Array

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

  • Java String array is basically an array of objects.
  • There are two ways to declare string array — declaration without size and declare with size.
  • There are two ways to initialize string array — at the time of declaration, populating values after declaration.
  • We can do different kind of processing on string array such as iteration, sorting, searching etc.
Читайте также:  Символ лупы в css

Let’s go over java string array example programs now.

Java String Array Declaration

Below code snippet shows different ways for string array declaration in java.

String[] strArray; //declare without size String[] strArray1 = new String[3]; //declare with size 

Note that we can also write string array as String strArray[] but above shows way is the standard and recommended way. Also in the above code, strArray is null whereas strArray1 value is [null, null, null] .

Java String Array Initialization

Let’s look at different ways to initialize string array in java.

//inline initialization String[] strArray1 = new String[] ; String[] strArray2 = ; //initialization after declaration String[] strArray3 = new String[3]; strArray3[0] = "A"; strArray3[1] = "B"; strArray3[2] = "C"; 

All the three string arrays will have same values. However if you will call equals method on them, it will return false.

System.out.println(strArray1.equals(strArray2)); // false System.out.println(Arrays.toString(strArray1).equals(Arrays.toString(strArray2)));// true 

The reason is that array are Objects and Object class implements equals() method like below.

public boolean equals(Object obj)

Second statement is true because when converted to String, their values are same and String class equals() method implementation check for values. For more details, please check String class API documentation.

Iterating over java string array

We can iterate over string array using java for loop or java foreach loop.

String[] strArray2 = ; for (int i = 0; i < strArray2.length; i++) < System.out.print(strArray2[i]); >for (String str : strArray2)

Search for a String in the String array

We can use for loop to search for an string in the array, below is a simple example for that.

package com.journaldev.stringarray; public class JavaStringArrayExample < public static void main(String[] args) < String[] strArray = < "A", "B", "C" >; boolean found = false; int index = 0; String s = "B"; for (int i = 0; i < strArray.length; i++) < if(s.equals(strArray[i])) < index = i; found = true; break; >> if(found) System.out.println(s +" found at index "+index); else System.out.println(s +" not found in the array"); > > 

Notice the use of break keyword to get out of the loop as soon as we found the string.

Читайте также:  JavaScript test() Method

Java String Array Sorting

We can implement our own sorting algorithm, or we can use Arrays class sorting method.

String[] vowels = ; System.out.println("Before sorting "+Arrays.toString(vowels)); Arrays.sort(vowels); System.out.println("After sorting "+Arrays.toString(vowels)); 

Output of above code snippet will be:

Before sorting [a, i, u, e, o] After sorting [a, e, i, o, u] 

Note that String implements Comparable interface, so it works for natural sorting. Incase you want to sort by some other way, you can use Arrays.sort() overloaded method by passing a Comparator. Learn about these sorting techniques at Comparable and Comparator in java.

Convert String to String Array

We can convert String to string array using it’s split() method. It’s useful when you get a single string as input with values separated using delimiter character.

String str = "a,e,i,o,u"; String[] vowels = str.split(","); System.out.println(Arrays.toString(vowels)); //[a, e, i, o, u] 

Convert String Array to String

We can use Arrays.toString() method to convert String array to String. Note that array doesn’t implement toString() method, so if you will try to get it’s string representation then you will have to rely on Arrays class, or else write your own custom code.

String[] vowels = < "a", "e", "i", "o", "u" >; System.out.println(vowels); System.out.println(Arrays.toString(vowels)); 

Output will be like below.

[Ljava.lang.String;@3d04a311 [a, e, i, o, u] 

The first output is because of Object class toString() implementation like below.

Java String Array to List

We can get a list representation of string array using Arrays.toList() method. Note that this list is backed by the array and any structural modification will result in java.lang.UnsupportedOperationException .

String[] vowels = < "a", "e", "i", "o", "u", "a", "o" >; List vowelsList = Arrays.asList(vowels); System.out.println("vowelsList = "+vowelsList); //vowelsList.add("x"); //java.lang.UnsupportedOperationException vowelsList.set(0, "x"); //allowed because no structural modification System.out.println("vowelsList = "+vowelsList); 

That’s all for java string array. Reference: Arrays Oracle Documentation

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Источник

Оцените статью