Run java class with arguments

Java Arguments Explained [Easy Examples]

Java arguments are the actual values that are passed to variables defined in the method header when the method is called from another method. Remember that these are not the variables but actual values. In this tutorial, we will learn about java arguments. We will discuss the difference between java arguments and parameters as well. At the same time. we will cover and solve different problems by passing java arguments to the java built-in methods. We will also see how we can pass different arguments to the main method of the java language. Moreover, we will also cover java command line arguments by taking various examples.

All in all, this tutorial is going to be one of the informative tutorials to get started working with java arguments.

Getting started with Java arguments

As we already discussed Arguments in Java are the actual values that are passed to variables defined in the method header when the method is called from another method. That is, whenever any particular method is called during the execution of the program, there are some values that are passed to call that particular method. For example, we call the absolute method in java by passing an integer value as an argument.

Notice that in the above example -23 is a java argument that we have passed to the absolute method.

Difference between Java arguments and parameters

Now we have basic knowledge of java arguments. Many people confuse between java arguments and java parameters. They are two different terms. In this section, we will highlight some of the basic differences between java arguments and java parameters. See the list below:

  • The Java argument is a variable whose value is passed into a function and is used whenever a function is called. The parameter is the value that is defined in a functional block. So, it is basically used whenever we need to pass a value to a particular functional block.
  • Arguments are used to send the values to the function whereas parameters are used to receive or hold the values of arguments.
  • During a function call, each argument is associated with a parameter and vice versa is also true.
  • Arguments are called the actual parameter whereas parameters are called formal parameters.

See the diagram below which shows the difference between java arguments and parameters.

java arguments

Notice that the variables that are used in the definition of a method are called parameters and the actual values that are used while calling the method are called arguments as shown above.

Understanding Java arguments with examples

So far we have learned theoretical knowledge about java arguments. In this section, we will look at more practical examples and use java arguments in our java program. For simplicity, first, we will use java built-in methods including finding the maximum, minimum, and power by providing arguments. Then we will also create our own function and then call that function by providing arguments.

Example-1 Finding maximum and minimum value

Let us now find the Maximum and minimum values by calling the methods max() and min() which is located inside Java Math class. See the example below:

// java main class public class Main < // java main method public static void main(String[] args) < // creating variables Integer num1 = 34; Integer num2 = 23; // printing the max and min value // calling method by providing java arguments System.out.println("The maximum value is :"+ Math.max(num1, num2)); System.out.println("The minimum value is :"+ Math.min(num1, num2)); >>
The maximum value is :34 The minimum value is :23

Notice that we provide two numbers as arguments to the min and max method.

Читайте также:  Сериализация массива объектов java

Example-2 Finding the power of a number

Now we will find the power of a number by using power() method which is again found inside the java Math class. See the example below:

// java main class public class Main < // java main method public static void main(String[] args) < // calling power method by providing java arguments System.out.println("The power of 2 to 4 is :"+ Math.pow(2, 4)); >>
The power of 2 to 4 is :16.0

Notice that we provide two arguments to the power method. The power method will return the first argument raised to the power of the second argument.

Example-3 Calling a user-defined function with arguments

We already have seen how we can call a built-in method by passing arguments. In this section, we will first create a user-defined function that can take multiple arguments and then will call that function by providing the required arguments.

// java main class public class Main < // java main method public static void main(String[] args) < // calling user defined method by providing java arguments System.out.println("The sum of two number is :"+ myFunction(2, 4)); >// user defined method public static Integer myFunction(Integer num1, Integer num2) < // returns the sum of two numbers return num1 + num2; >> 
The sum of two number is :6

Notice that in the above example, we created a new function with two parameters, and then we called the function inside our main method by providing the required arguments.

Java command-line arguments

Command Line Argument in Java is the information that is passed to the program when it is executed. The information passed is stored in the string array passed to the main() method and it is stored as a string. It is the information that directly follows the program’s name on the command line when it is running. You can read more about the functioning of the java main method from the article on the java main method. In this section, we will take various examples and see how we can pass arguments to the java main function from the terminal.

Example-1 Finding the factorial of a number by passing to the main method

Now let us take an example and see how we can run the main method of the java class by passing arguments. See the example below, where we passed the argument from the command line to the main method of the java class, and then it returns the factorial value of that number.

// Java main method class Main < // java main method public static void main(String[] args)< // Integer type variables int x , y = 1; // storing the first argument from the main method in a variable int n = Integer.parseInt(args[0]); // using for loop to find the factoial for(x = 1; x// printing the factorial System.out.println("The factorial is :" +y); > >

Java arguments main method

So here what we did was, first we call the java class ( file), and then after a space, we provide the argument. Now out program takes this argument and prints the factorial value.

Читайте также:  Search method in python

Example-2 Finding the Sum of two numbers by using command line

We can also provide multiple arguments to the main method of java class using the command line. In this section, we will provide two numbers as arguments to the main method and then prints the sum of those two numbers. See the example below:

// Java main class class Main < // java main method public static void main(String[] args)< // stroing the argumets in interger typed variables int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); // finding the sum of the two java arguments int sum = x + y; // printing the sume System.out.println("The sum is" +sum); >>

Java main method arguments

Notice that we get the sum of the two numbers that we had provided as arguments to the main method. We use space between multiple arguments.

Example-3 Providing String typed arguments to the Java main method

Now let us provide string typed arguments to the java main method and then without any conversion to any datatype let us print the string values. See the example below, where we provide three arguments to the main method and then print all those arguments in one line.

// Java main class class Main < // java main method public static void main(String[] args)< // storing the arguments in string typed variables String string1 = args[0]; String string2 = args[1]; String string3 = args[2]; // printing the string System.out.println(string1+" "+string2+" "+string3); >>

java main method

Notice that we successfully print the three arguments in one line using plus operator. You can read more about the java string concatenation from the article on java string concatenation.

Summary

A java argument is a value passed to a function when the function is called. Whenever any function is called during the execution of the program there are some values passed with the function. In this tutorial, we learned about java arguments. We covered the basic syntax of calling a function by passing different types of arguments. We also discussed the difference between java arguments and java parameters. At the same time, we also solve various examples by calling the java built-in method and passing arguments.

We also learned how we can use the command line to pass java arguments to the java main method. Moreover, we solved various examples and passed different types of arguments to our main method using the command line. In a nutshell, this tutorial covers everything that you need to know in order to start working with java arguments, calling a method along with passing arguments or passing arguments to the main method of java programming language.

Further Reading

Didn’t find what you were looking for? Perform a quick search across GoLinuxCloud

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Читайте также:  Первая html-страница

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can either use the comments section or contact me form.

Thank You for your support!!

Leave a Comment Cancel reply

Java Tutorial

  • Set Up Java Environment
    • Set Up Java on Linux
    • Set up Java with BlueJ IDE
    • Set up Java with VSC IDE
    • Set up Java with Eclipse IDE
    • Java Multiline Comments
    • Java Variables
    • Java Global Variables
    • Java Date & Time Format
    • Different Java Data Types
    • Java Booleans
    • Java Strings
    • Java Array
    • Java Byte
    • Java convert list to map
    • Java convert double to string
    • Java convert String to Date
    • Java convert Set to List
    • Java convert char to int
    • Java convert long to string
    • Java Operators Introduction
    • Java Boolean Operators
    • Java Relational Operators
    • Java Arithmetic Operators
    • Java Bitwise Operators
    • Java Unary Operators
    • Java Logical Operators
    • Java XOR (^) Operator
    • Java Switch Statement
    • Java If Else Statement
    • Java While Loop
    • Java For / For Each Loop
    • Java Break Continue
    • Java Nested Loops
    • Java throw exception
    • Java Try Catch
    • Java Accessor and Mutator Methods
    • Java main() Method
    • IndexOf() Java Method
    • Java ListIterator() Method
    • Java create & write to file
    • Java read file
    • Java Parameter
    • Java Argument
    • Java Optional Parameters
    • Java Arguments vs Parameters
    • Java Arrays.asList
    • Java HashSet
    • Java Math
    • Java HashMap vs Hashtable vs HashSet
    • Java LinkedList
    • Linked List Cycle
    • Java List vs LinkedList
    • Java ArrayList vs LinkedList

    Источник

    Command-Line Arguments

    A Java application can accept any number of arguments from the command line. This allows the user to specify configuration information when the application is launched.

    The user enters command-line arguments when invoking the application and specifies them after the name of the class to be run. For example, suppose a Java application called Sort sorts lines in a file. To sort the data in a file named friends.txt , a user would enter:

    When an application is launched, the runtime system passes the command-line arguments to the application’s main method via an array of String s. In the previous example, the command-line arguments passed to the Sort application in an array that contains a single String : «friends.txt» .

    Echoing Command-Line Arguments

    The Echo example displays each of its command-line arguments on a line by itself:

    The following example shows how a user might run Echo . User input is in italics.

    java Echo Drink Hot Java Drink Hot Java

    Note that the application displays each word — Drink , Hot , and Java — on a line by itself. This is because the space character separates command-line arguments. To have Drink , Hot , and Java interpreted as a single argument, the user would join them by enclosing them within quotation marks.

    java Echo "Drink Hot Java" Drink Hot Java

    Parsing Numeric Command-Line Arguments

    If an application needs to support a numeric command-line argument, it must convert a String argument that represents a number, such as «34», to a numeric value. Here is a code snippet that converts a command-line argument to an int :

    int firstArg; if (args.length > 0) < try < firstArg = Integer.parseInt(args[0]); >catch (NumberFormatException e) < System.err.println("Argument" + args[0] + " must be an integer."); System.exit(1); >>

    parseInt throws a NumberFormatException if the format of args[0] isn’t valid. All of the Number classes — Integer , Float , Double , and so on — have parseXXX methods that convert a String representing a number to an object of their type.

    Источник

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