Passing string arguments java

Java Method Arguments

What does this mean? How do I change a parameter? This short tutorial will help you figure out how parameter passing in Java works and will help you avoid some common mistakes.

First let’s get the terminology straight. The terms «arguments» and «parameters» are used interchangeably; they mean the same thing. We use the term formal parameters to refer to the parameters in the definition of the method. In the example that follows, x and y are the formal parameters.

We use the term actual parameters to refer to the variables we use in the method call. In the following example, length and width are actual parameters.

// Method definition public int mult(int x, int y) < return x * y; >// Where the method mult is used int length = 10; int width = 5; int area = mult(length, width);

Pass-by-value means that when you call a method, a copy of each actual parameter (argument) is passed. You can change that copy inside the method, but this will have no effect on the actual parameter. Unlike many other languages, Java has no mechanism to change the value of an actual parameter. Isn’t this very restrictive? Not really. In Java, we can pass a reference to an object (also called a «handle»)as a parameter. We can then change something inside the object; we just can’t change what object the handle refers to.

Читайте также:  How to end program in python

Passing Primitive Types

Java has eight primitive data types: six number types, character and boolean. When any variables of these data types are passed as parameters to a method, their values will not change. Consider the following example:

public static void tryPrimitives(int i, double f, char c, boolean test) < i += 10; //This is legal, but the new values c = 'z'; //won't be seen outside tryPrimitives. if(test) test = false; else test = true; >

int ii = 1; double ff = 1.0; char cc = ‘a’; boolean bb = false; tryPrimitives(ii, ff, cc, bb); System.out.println(«ii = » + ii + «, ff = » + ff + «, cc = » + cc + «, bb figure3.gif» HEIGHT=194 WIDTH=426 ALIGN=RIGHT> What’s really happening here? When Java calls a method, it makes a copy of its actual parameters and sends the copies to the method where they become the formal parameters. Then when the method returns, those copies are discarded and the variables in the main code are the same as before.

Passing Object References

What if an argument to a method is an object reference? We can manipulate the object in any way except we cannot make the reference refer to a different object. Suppose we have defined the following class: class Record
public static void tryObject(Record r)

In some other code we can create an object of our new class Record , set its fields, and call the method tryObject .

Record Record(); id.num = 2; id.name = "Barney"; tryObject(id); System.out.println(id.name + " " + id.num);

Note that the object’s instances variables are changed in this case. Why? The reference to id is the argument to the method, so the method cannot be used to change that reference; i.e., it can’t make id reference a different Record . But the method can use the reference to perform any allowed operation on the Record that it already references.

Side Note: It is often not good programming style to change the values of instance variables outside the object. Normally, the object would have a method to set the values of its instance variables.

We cannot however make the object parameter refer to a different object by reassigning the reference or calling new on the reference. For example the following method would not work as expected:

public void createRecord(Record r, int n, String name)

We can still encapsulate the initialization of the Record in a method, but we need to return the reference.

public Record createRecord(int n, String name)

Passing Strings

When we write code with objects of class String, it can look as if strings are primitive data types. For example, when we assign a string literal to a variable, it looks no different than, say, assigning an number to an int variable. In particular, we don’t have to use new . In fact, a string is an object, not a primitive. A new is required, and Java does it behind the scenes. It creates a new object of class String and initializes it to contain the string literal we have given it.

String str = "This is a string literal.";

Because str is an object we might think that the string it contains might be changed when we pass str as a parameter to a method. Suppose we have the method tryString :

public static void tryString(String s)
tryString(str); System.out.println(«str This is a string literal.» Why is this? Maybe this picture will help you understand what goes on behind the scenes. It is important to remember what Java does when it assigns a string literal to an object. A different String object is created and the reference variable is set to point to the newly created object. In other words the value of the formal parameter, s, has changed, but this does not affect the actual parameter str. In this example, s pointed to the string object that contains «This is a string literal». After the first statement of the method executes, s points to the new string, but str has not changed. Like other objects, when we pass a string to a method, we can in principle, change things inside the object (although we can’t change which string is referenced, as we just saw). However, this capability is not useful with string because strings are «immutable». They cannot be changed because the String class does not provide any methods to modify its local variables.

Questions

A: Pass-by-value in Java means B: Given the following method: public void swap(int x, int y)

int p = 20; int q = 15; swap(p, q);

We have to use a bit of a trick to write a swap routine that works.

Return values

Okay, so how do we change the values of variables inside methods? One way to do it is simply to return the value that we have changed. In the simple example below, we take two integers, a and b , as parameters and return a to the power of b .

public static int power(int a, int b)

int number = 2; int exponent = 4; number = power(number, exponent); System.out.println("New value of number is " + number);

Since methods should be designed to be simple and to do one thing, you will often find that returning a value is enough, and that you don’t need to change the value of any parameters to the method. Note that this does not help us write a swap method because a method can only return one value, and to write swap we need to change the value of two variables.

Question


public int tryPrimitives(int x, int y)

int p = 1; int q = 2; int r = 5; r = tryPrimitives(p, q);

Passing Arrays

Arrays are references. This means that when we pass an arrays as a parameter, we are passing its handle or reference. So, we can change the contents of the array inside the method.

public static void tryArray(char[] b)
char[] a = ; tryArray(a); System.out.println(«a[0] = » + a[0] + «, a[1] = » + a[1] + «, a[2] a[0] = x, a[1] = y, a[2] = z».

Question

D: Given the following method: public void differentArray(float[] x)

float[] xx = new float[100]; x[0] = 55.8f; differentArray(xx); System.out.println(«x[0] webtutor.zip» CODE=»Question.class» CODEBASE=»http://www.dgp.utoronto.ca/webtutor/bin/» WIDTH=400 HEIGHT=210>

Summary

That, combined with an understanding of the different between primitives and references and careful tracing will allow you to understand any Java method calls.

Источник

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.

Источник

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.

Источник

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