Java main string array

String Array in Java

In this guide, you will learn about string array in java, how to use them and various operations that you can perform on string array in java.

String array is a collection of strings, stored in contiguous memory locations.

For example: The following string array contains four elements. These elements are stored in contiguous memory locations and can be accessed using array index such as: names[0] represents first element «Chaitanya» . Similarly names[1] represents second element «Ajeet» , names[2] represents third element «Hari ” and so on.

String Array Declaration

There are two ways to declare a String array in Java.

1. Without specifying the array size:

2. Array size is specified: The following array can hold upto 5 strings.

String[] strArray = new String[5];

String Array Initialization

1. Inline Initialization:

String[] names = new String[] ; OR String[] names = ;

2. Normal Initialization after declaration:
Here, we have declared an array names with the fixed size of 4 and initialized the array later.

String[] names= new String[4]; names[0]= "Chaitanya"; //first element names[1]= "Ajeet"; //second element names[2]= "Hari"; //third element names[3]= "Rahul"; //last element

Simple String Array Example in Java

In this example, we have a string array fruits . This array contains three elements (strings). We are displaying the elements of string array using for loop. The length property of array ( fruits.length ) returns the number of elements in an array, in this case its 3.

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; for (int i=0; i > >

Java String Array

String array ArrayIndexOutOfBoundsException

If the specified index is beyond the size of the array then the compiler throws ArrayIndexOutOfBoundsException .

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //We are trying to print 11th element of the array //but the array contains only 3 elements. This will //throw ArrayIndexOutOfBoundsException System.out.println(fruits[10]); > >

Java string array exception

Iterating a String Array

Let’s see how to iterate a string array. We can iterate using normal for loop or enhanced for loop (for each loop).

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //iterating using normal for loop System.out.println("Iterating using for loop:"); for (int i=0; i //iterating using for-each loop System.out.print("Iterating using foreach loop: "); for (String str: fruits) < System.out.print(str+ " "); >> >

Iterating String array in Java

Adding elements to String array

You already learned that the size of the array is fixed, which means if it is full, you cannot add any more elements to it. However there are two ways, you can add elements to an array. Technically it’s not adding the elements to the existing array, rather a new array with all the elements of previous array along with the new elements.
1. Creating a new array
2. Using ArrayList

1. Adding elements to an array by creating new array

Steps followed in this program are:
1. Create a new array with the larger size to accommodate new elements.
2. Copy all elements from old array to new array.
3. Add new elements to new array.
4. Print new array

public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //we want to add two more elements to the fruits array so let's //create a new array with the size of 5 String[] newFruits = new String[fruits.length+2]; //copying elements from old array to new array for (int i=0; i //Adding new elements newFruits[newFruits.length-2]= "Mango"; //second last element newFruits[newFruits.length-1]= "Kiwi"; //last element //print new array for (String str: newFruits) < System.out.println(str); >> >
Apple Orange Banana Mango Kiwi

2. Adding elements to an array using ArrayList

Steps followed in this program are:
1. Convert array to ArrayList.
2. Add as many elements as you like in ArrayList as ArrayList is dynamic and can grow and shrink automatically.
3. Once addition is done, convert back the ArrayList to an Array.
4. Print the array.

import java.util.*; public class JavaExample < public static void main(String a[])< //declared and initialized a string array String[] fruits = new String[]; //Convert the array "fruits" to an ArrayList ArrayList fruitList = new ArrayList(Arrays.asList(fruits)); //Adding elements to ArrayList fruitList.add("Mango"); fruitList.add("Kiwi"); //Convert the ArrayList to array String[] newFruits = fruitList.toArray(new String[fruitList.size()]); //print new array for (String str: newFruits) < System.out.println(str); >> >
Apple Orange Banana Mango Kiwi

Sorting string array

Here, we are demonstrating how to sort a string array. It is simple, just import java.util.Arrays package to use the sort() method of Arrays class. The array passed in the sort() method is sorted in ascending order.

import java.util.Arrays; public class JavaExample < public static void main(String a[])< String[] names = new String[]; //print array before sorting System.out.println("Array before sorting: "); for (String str: names) < System.out.print(str+ " "); >//sorting array Arrays.sort(names); //new line System.out.println(); //print array after sorting System.out.println("Array after sorting: "); for (String str: names) < System.out.print(str+ " "); >> >

Sorting String Array

Search an element in a String array

Here, we are searching an element in string array. We are iterating the whole array and matching every element with the searchItem , if a match is found, we are storing the index and setting the foundFlag to true . If the whole array is traversed and no match is found then the if-else statement after for loop, prints the message that “String is not found”.

public class JavaExample < public static void main(String a[])< String[] names = new String[]; //this will represent the index of search element when it is found int index=0; //This will set to true, if element is found in array, else it //will remain false. boolean foundFlag = false; //This is the search element, we are searching for this element in array String searchItem ="Rob"; for (int i = 0; i < names.length; i++) < if(searchItem.equals(names[i])) < //if element found, get index, set flag to true and break the loop index = i; foundFlag = true; break; >> if(foundFlag) System.out.println("String "+searchItem +" is found at index: "+index); else System.out.println("String "+searchItem +" is not found"); > >
String Rob is found at index: 2

About the Author

I have 15 years of experience in the IT industry, working with renowned multinational corporations. Additionally, I have dedicated over a decade to teaching, allowing me to refine my skills in delivering information in a simple and easily understandable manner.

Источник

public static void main(String[] args) — Java main method

public static void main(String[] args) - Java main method

The Java main method is usually the first method you learn about when you start programming in Java because its the entry point for executing a Java program. The main method can contain code to execute or call other methods, and it can be placed in any class that’s part of a program. More complex programs usually have a class that contains only the main method. The class that contains the main method can have any name, although typically you can just call the class Main .

In the examples that follow, the class that contains the main method is called Test :

public class Test  public static void main(String[] args) System.out.println("Hello, World!"); > > 

In this article you’ll learn what each component of the main method means.

Java Main Method Syntax

The syntax of the main method is always:

public static void main(String[] args) // some code > 

You can change only the name of the String array argument. For example, you can change args to myStringArgs . The String array argument can be written as String. args or String args[] .

public

The access modifier of the main method needs to be public so that the JRE can access and execute this method. If a method isn’t public, then access is restricted. In the following example code, the main method is missing the public access modifier:

public class Test  static void main(String[] args) System.out.println("Hello, World!"); > > 

When you compile and run the program, the following error occurs because the main method isn’t public and the JRE can’t find it:

Output
Error: Main method not found in class Test, please define the `main` method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

static

When the Java program starts, there is no object of the class present. The main method has to be static so that the JVM can load the class into memory and call the main method without creating an instance of the class first. In the following example code, the main method is missing the static modifier:

public class Test  public void main(String[] args) System.out.println("Hello, World!"); > > 

When you compile and run the program, the following error occurs because the main method isn’t static :

Output
Error: Main method is not static in class Test, please define the `main` method as: public static void main(String[] args)

void

Every Java method must provide the return type. The Java main method return type is void because it doesn’t return anything. When the main method is finished executing, the Java program terminates, so there is no need for a returned object. In the following example code, the main method attempts to return something when the return type is void :

public class Test  public static void main(String[] args) return 0; > > 

When you compile the program, the following error occurs because Java doesn’t expect a return value when the return type is void :

Output
Test.java:5: error: incompatible types: unexpected return value return 0; ^ 1 error

main

The Java main method is always named main . When a Java program starts, it always looks for the main method. The following example code shows a main method renamed to myMain :

public class Test  public static void myMain(String[] args) System.out.println("Hello, World!"); > > 

When you compile and run the program, the following error occurs because the JRE can’t find the main method in the class:

Output
Error: Main method not found in class Test, please define the `main` method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

String[] args

Java main method accepts a single argument of type String array. Each string in the array is a command line argument. You can use command line arguments to affect the operation of the program, or to pass information to the program, at runtime. The following example code shows how to print the command line arguments that you enter when you run the program:

public class Test  public static void main(String[] args) for(String s : args) System.out.println(s); > > > 

When you compile the program and then run it with a few command line arguments separated by spaces, the arguments get printed in the terminal:

Output
1 2 3 Testing the main method

Conclusion

In this article you learned about each component of the Java main method. Continue your learning with more Java tutorials.

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

Источник

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[] .

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 method class type
Оцените статью