File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

If for beginners

 
Paul Roberts
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I was trying out the following code as a complete newcomer to Java in particular and programming in general.

As I understand it args refers to the name I have given to the public class file, in this case sgra. So if the figure to the right of '>' is 5 or greater it shouldn't print hello, however it does. If you have any light you can shed upon this dark matter it would be much appreciated.
 
Campbell Ritchie
Sheriff
Pie
Posts: 47244
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

I am afraid you have misunderstood args.
When you compile that class and run it, you can do so like this
myPrompt:> javac sgra.java
myPrompt:> java sgra This is the command-line arguments array, which you call args inside your class
. . . whatever you write after the name of the class passes on to the main method, divided into an array of Strings. In the main method you call it args.
You print "Hello" regardless, because that line is not inside the if test.
More information here, under "command-line arguments".
 
fred rosenberger
lowercase baba
Bartender
Pie
Posts: 12017
24
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
your code will always print "hello", as Campbell pointed out.

'args' holds the list of arguments. If on the command like you type this:

c:\>java sgra

you have no arguments, so args is empty.

if you type this:
c:\>java sgra this has four arguments

args will be an array of strings. It will have four elements that look like this:
args[0] = this
args[1] = has
args[2] = four
args[3] = arguments

with your code, if you type in MORE than nine arguments, you will get something else printed. try this:
c:\>java sgra this has a whole boatload of arguments passed into it so i should see something else printed

 
Paul Roberts
Greenhorn
Posts: 11
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for that people. It's good to know what was wrong with the example and I feel I am one angstrom unit further along with my understanding. :-)
 
Campbell Ritchie
Sheriff
Pie
Posts: 47244
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Paul Roberts wrote:Thanks for that people. . . .
You're welcome

By the way: use the icons on the left to insert smilies; they work better than hand-written smilies.
 
Don't get me started about those stupid light bulbs.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic