File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes If for beginners Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "If for beginners" Watch "If for beginners" New topic

If for beginners

Paul Roberts

Joined: Sep 26, 2011
Posts: 11
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

Joined: Oct 13, 2005
Posts: 46432
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
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

Joined: Oct 02, 2003
Posts: 11957

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

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
Paul Roberts

Joined: Sep 26, 2011
Posts: 11
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

Joined: Oct 13, 2005
Posts: 46432
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.
I agree. Here's the link:
subject: If for beginners
It's not a secret anymore!