5

I am trying to run a java calculator application from command line. the parameters are as follows : operator operand1 operand2. I can successfully run the java program for + and - .
e.g.
java calc + 2 4
java calc - 10 4

But when I try to run
java * 2 5

System.out.println(args[0]);
System.out.println(args[1]);
System.out.println(args[2]);

gives output:
.classpath
.project
.settings

I found out by trial and error that using single quotes( '*' ) solved my problem. SO i have two questions now.
1. Is using single quotes the right way to do it? (java calc '*' 2 5 )
2. What is the meaning of * in the java command line? (I've tried to find this on internet but didn't find much help)

Thanks, Punit

Gadenkan
  • 1,691
  • 2
  • 17
  • 29

2 Answers2

12

It's not Java, it's the shell (cmd if you're on Windows) you are using that interprets * as "all files and folders in the current directory".

So when your write:

java calc * 2 5

You will actually give your program the following arguments:

java calc file_1 file_2 ... file_n 2 5

Where file_1 ... file_n are all files (and folders) in the current directory).

If you do not want your shell to interpret * as all files you need (as you have noticed) to quote that argument.

dacwe
  • 41,465
  • 11
  • 110
  • 135
  • 1
    it should be " (double quoute) not ' (single quote). – reader_1000 Sep 16 '11 at 07:30
  • 1
    @reader_1000: Good point as this was a "windows-only" question! (Other shells need other characters to quote or escape it.. For instance `sh` uses `\*`.) – dacwe Sep 16 '11 at 08:05
  • I'm sorry for not mentioning which OS i was using. I'm using windows. And in windows cmd using double quote ( " ) still gives me the same error. Using single quote( ' ) though works fine. And as @dacwe rightly pointed out the escape sequence is different for different platforms. Thanks guys for the answer and comments :) – Gadenkan Sep 16 '11 at 11:13
1

If you quote your command arguments, the shell will not expand them to filenames. '*' has no special meaning to java it is the shell that processes this input.

stacker
  • 64,199
  • 27
  • 132
  • 206