What's the meaning of args.length? [duplicate] - java

This question already has answers here:
What Exacly (args.length>0) means?
(6 answers)
Closed 8 years ago.
recently i've come across this piece of code and i really want to understand when and how to use this args.length
import java.util.*;
class Average
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int choice;
int a=0,min=0,max=0,x;
int n = args.length;
System.out.println("1-Sum");
System.out.println("2-Average");
System.out.println("3-Minimum");
System.out.println("4-Maximum");
System.out.println("enter your choice");
choice = sc.nextInt();
for(int i=0;i<n;i++)
{
a+=Integer.parseInt(args[i]);
}
switch(choice)
{
case 1: System.out.println("The sum is :" +a/n);
break
case 2: System.out.println("The Average is :" +a/n);
break
case 3: for(int i=0;i<n-1;i++)
{
x=Integer.parseInt(args[i]);
if(x<Integer.parseInt(args[i+1]))
min=x;
else min=Integer.parseInt(args[i+1]);
}
System.out.println("The minimum is :" +min);
break;
case 4: for(int i=0;i<n-1;i++)
{
x=Integer.parseInt(args[i]);
if(x>Integer.parseInt(args[i+1]))
max = x;
else max=Integer.parseInt(args[i+1]);
}
System.out.println("The maximum is :" +max);
break;
}
}
}

The main() method is initial point where java program execution starts. That's why the main() method is public, static and void. The parameters passed to main() method are String args[] i.e a String array. It is not necessarily the variable name can be only args, it can be any variable name i.e String names[].
Now, why args.length is zero, when no arguments passed:
When any java program is run from command line, it is run as java ProgName.
The command line arguments are passed to java program as java ProgName Arg1 Arg2.
Here in this example, two arguments are passed to java program ProgName. It is simple that, the arguments are passed to java program is the same way we run a command with parameters on any operating system. The arguments are passed along with command just by separator character as "space".
Java Interpreter interprets these arguments and pass to main() method of java program.
When we pass arguments to java program from command line it is stored in the args[] String Array. As here two arguments are passed, while running java program args[0] and args[1] will be allowed, but args[2] will not. Same way if no arguments are passed, so java will not even allow args[0].
Java interprets the command line arguments as String array, as if we pass 2 arguments it is an array with args[0], args[1], if we pass 4 arguments it is an array with args[0], args[1], args[2], args[3] and when no arguments are passed it is still an String array object with no elements.
Thus, even when we do not pass any command line arguments to java program, still the args.length is equal to Zero - (0).

When you run a program, you can run the program passing command-line arguments. If the main method is:
public static void main(String args[])
the arguments will be received in the array of String called args. Now, regarding your question:
What does args.length mean?
It's the value of the built-in property length from arrays, which will be its fixed size. Note that arrays in Java are a special kind of objects.

args.length is the number of elements in the args[] array. The args[] array contains the parameters passed to the main function from the command line.

It is the number of elements in the args array, that was defined in public static main(String[] args).

Related

Can anybody tell what error or where am i going wrong in code?

I am getting error while taking input with Integer.parseInt(args[0]); error is in args section i know i can change it to scanner but i want to know this method.
Can anybody point out or show the solution to my problem?
class NegativeOutputException extends Exception{
private final int ex;
NegativeOutputException(int a){
ex = a;
}
public String toString(){
return "NegativeOutputException!("+ex+")";
}
}
public class practice6_creating_custom_exception {
public static void main(String args[]){
int x = Integer.parseInt(args[0]);//Error Here argument at position one
int y = Integer.parseInt(args[1]);//argument at position two
//argument at position twenty one which doesn't exsist
int a;
try{
a = x * y;
if(a < 0)
throw new NegativeOutputException(a);
System.out.println("Output >>" + a);
}
catch(NegativeOutputException e){
System.out.println("Caught >>" + e);
}
}
}
Output::
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at practice6_creating_custom_exception.main(practice6_creating_custom_exception.java:21)
Process finished with exit code 1
It gives you a java. lang.ArrayIndexOutOfBoundsException because you are trying to access a position in an empty array.
parseInt() is not used for taking inputs in such a case you need to use Scanner
For your case, you need first take input (by using Scanner) and then assign it to an integer variable, directly parsing the argument array will not provide the input.
Scanner sc = new Scanner();
int x = sc.nextInt(); //Scans the next token of the input as an int
parseInt() function -
The parseInt() method parses a value as a string and returns the first integer.
Source
Scanner Class -
Scanner object holds the address of InputStream object present in the
System class. Input Stream object of system class reads data from the
keyboard which is byte stream/byte form. The Scanner class converts
this read byte into a specific data type.
Source
The parseInt() function cannot read data from the input stream which is byte stream/byte form, hence you cannot directly parse the args[] array and assign it to an integer variable as it is empty since it is not yet scanned.
If you are looking for different ways of taking input in Java then here they are:
Using Buffer Reader Class,
Using Scanner Class,
Using Console Class,
Using Command Line Argument,
Source
Most probably you are simply not passing any arguments.
One way to pass arguments to the main method in Java is with the command to run the application in terminal. You can simply add the arguments after the java command to run the application separating them with a space. If you want the user to input the data, then you should use Scanner instead.
In your case, navigate to the folder where your java file sits and run the following:
java practice6_creating_custom_exception 0 1
In this example, 0 and 1 are the arguments you are passing.
If you are using an IDE then this can usually be done in the run configurations.
Side note, you might need to compile the application before running it and the command for that is the following:
javac practice6_creating_custom_exception.java

.class expected (Newbie on java) [duplicate]

This question already has an answer here:
What does "error: '.class' expected" mean and how do I fix it
(1 answer)
Closed 11 months ago.
I don't know why this cannot run, the error on "num = Integer.parseInt (args[]) ;"
class CommandLine {
public static void main (String args [])
{
int num ;
num = Integer.parseInt (args[]) ;
if (num>=100)
{
} else {
System.out.println("Number is less than 100");
}
}
}
In order to use args[], you need to pass a command-line argument when you run the class. For example, if you are running from command prompt, you will need to do something like this:
java CommandLine 100
In your code, you could do something like this
class CommandLine {
public static void main (String args[]) {
int num = Integer.parseInt (args[0]) ;
if (num>=100)
{
System.out.println("You entered ");
} else {
System.out.println("Number is less than 100");
}
}
}
Which will result in displaying You entered 100 on the console. If you are running from an IDE like Eclipse, you will need to set up the command-line argument through the "Run Configurations" menu. Then, you enter (space-separated) arguments in the "Program arguments" text area.
In IntelliJ, you do the same through the "Modify run configuration" menu
The argument array args[] in a class' main method is built by the JVM. It is a string of command-line arguments that are passed to the executed class. The JVM parses out the command line instruction and will gather any and all values after the class name and will create that args array. If you pass nothing to the program, then the array will be empty.
An command-line instruction like
java MyClass Hello World Welcome to Java
builds a String array with 5 values.

How do I set the size of the array my command line arguments will be stored in?

I basically want to store my user input in an array of size 3. When I seem to put 3 in the main (String [3] args), it doesn't seem to do what I want. How do I resolve this issue?
If it helps, the exercise is asking me to: Fill in the class method main of class Ex4 with code that
create an array of size 3 containing strings and fills it with command line arguments.
Thanks.
public class Ex4 {
public static void main(String[] args)
{
if (args.length == 1)
{
System.out.println(args[0]);
}
else if (args.length == 2 || args.length == 3)
{
System.out.println(args[0]);
System.out.println(args[1]);
}
else
System.out.println("Too many arguments");
}
}
You can't control the size of the array passed to the main method. It will automatically be allocated with the size of the arguments passed to the program.
You get it backwards.
You define the size of that array implicitly, by the number of arguments that you pass when starting the JVM.
At runtime, within your Java code you can only check the actual length of that array. For example to give an error message to the user telling him about the required number of arguments and their meaning.

incompatible types: java.util.lang.String cannot be converted to stringdemo.String

I am new to Java and about halfway through my first Java course. This weeks lab assignment instructions are:
Create a New Project named StringDemo
Write a method called backward() that accepts a String object as an argument and displays its contents backward. For instance, if the string argument is “gravity” the method should display -“ytivarg”. Demonstrate the method in a program that asks the user to input a string and then passes it to the method.
Write a method called wordCount() that accepts a String object as an argument and returns the number of words it contains. In this case, we will assume blank spaces separate words. For instance, if the argument is “Four score and seven years ago” the method should return the number 6. Demonstrate the method in a program that asks the user to input a string and then passes it to the method. The number of words in the string should be displayed on the screen. (Hint: the split() String method could be useful.)
I am currently on problem 2, but I am receiving this error on my keyboard input line:
incompatible types: java.util.lang.String cannot be converted to
stringdemo.String
Can someone please tell me how to correct this?
Thank you.
import java.util.*;
public class StringDemo {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
String input;
// Create a Scanner object for keyboard input
Scanner keyboard = new Scanner(System.in);
// Get user input
System.out.print("Enter a word or phrase to be reversed: ");
input = keyboard.nextLine();
// Reverse the input using StringBuilder
StringBuilder input1 = new StringBuilder();
input1.append(input);
input1 = input1.reverse();
for (int i = 0; i < input1.length(); i++)
System.out.print(input1.charAt(i));
}
}
You need to remove or rename your stringdemo.String class. Java linking rules dictate that classes in the same package are matched before the language classes, which means your
String input;
is being interpreted as
stringdemo.String input;
and not as
java.lang.String input;

why testing args.length?

I'm a Java beginner and I'm confused about testing args.length at the begining of many codes, and why it's never gets higher than 0 in any of my codes?
import java.net.Socket;
import java.net.UnknownHostException;
import java.io.IOException;
public class LowPortScanner {
public static void main(String[] args) {
String host = "localhost";
if (args.length > 0) {
host = args[0];
}
for (int i = 1; i < 1024; i++) {
try {
Socket s = new Socket(host, i);
System.out.println("There is a server on port " + i + " of "
+ host);
}
catch (UnknownHostException ex) {
System.err.println(ex);
break;
}
catch (IOException ex) {}
} // end for
} // end main
} // end PortScanner
You have to inputs to main mathod from Command prompt.
like below
java LowPortScanner TEST1 TEST2
Because if it is not tested then an exception would be thrown because host = args[0]; would illegal.
However, this doesn't look like it's going to help much, an empty or null host looks like it would cause further problems.
If the length of args is always 0, then be sure you're actually passing in parameter arguments.
If there are no command arguments the args[0] will fail. This is why it must be protected.
It depends on how you invoke the Java class file. In command prompt or bash shell:
java LowPortScanner Argument1
typing the above line in the command prompt/bash will cause the argument count to increase to 1. (because Argument1 is one argument, after the class file LowPortScanner)
java LowPortScanner Argument1 Argument2
the above line will make argument count to increase to 2.
hence args.length will be 2 in the second case and 1 in the first case.
If you are calling your program from CMD or bash you can asign ARGuments it like
java LowPortScanner google.com
Then "google.com" is your args[0]. When your program supports commandline attributes it is recommended to test if the given arguments are corret.
The variable String[] args hold all the parameter pass to the program thorough command line if you are not passing any argument then the length of args become 0. Now it's better to check it's length before accessing it other wise there is chance to get ArrayIndexOutOfBoundsException if it's size is 0
args in public static void main(String[] args is the String array of arguments passed from command line.
java LowPortScanner argument1 argument2
if you try the above command args.length will return 2.
As far as question of checking the length it is done for java programs which can take command line arguments and if arguments are not passed then they prompt for input.
if(args.length >0 ){
//proceed using passed arguments
}else{
//proceed with some default value
}
You are running your program using java LowPortScanner hence no arguments are passed and args.length is always zero.
Moreover if you don't pass any argument and use host=args[0] you will get ArrayIndexOutOfBoundsException.

Categories