1

In my Java course, I was given a multithread server client project to take a look at. I understand most of the project except this part in the client:

public static void main( String args[] )
{
  Client application; 

  if ( args.length == 0 )
     application = new Client( "127.0.0.1" ); 
  else
     application = new Client( args[ 0 ] ); 

  application.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
  application.runClient(); 
}

In particular I don't understand the meaning behind the args checking. Why do we do it? For example if args is 0 we connect to the localhost, but what happens in the else is eluding me. I know that args contains the supplied command-line arguments as an array of String objects, but that doesn't help me much. So any explanation is welcomed :)

pesho
  • 111
  • 1
  • 9
  • you can pass arguments to Java applications when you execute them. See http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html you can also look up "Command line arguments java" in a search engine. – ug_ Jan 28 '15 at 12:40

4 Answers4

2

Array of Strings is passing as a parameter to your program (it could be done during launch of a program), e.g - java ClientApp, it could accept some parameters, like this java ClientApp 192.168.0.1, so 192.168.0.1 will be element with index 0 in args[] array.

For more info check official documentation - http://docs.oracle.com/javase/tutorial/essential/environment/cmdLineArgs.html

Mysterion
  • 9,050
  • 3
  • 30
  • 52
1

"args" is an array including parameters passed by the user, when starting the app. If args.length (the size of the array "args") is zero, (no parameters passed) the default value "127..." will be used. If its greater than zero, the first parameter will be used as the address instead:

java -jar myProgram.jar 192.168.0.1

Stefan
  • 12,108
  • 5
  • 47
  • 66
1

See: What is "String args[]"? parameter in main method Java

The else clause uses the first command-line argument and passes it to the Client constructor. This allow you to specify the host that the client should connect to on the command-line.

Community
  • 1
  • 1
Mike Tunnicliffe
  • 10,674
  • 3
  • 31
  • 46
1

I would say that the client's IP address is expected as a command line argument, and if one isn't supplied then by default the localhost is connected to. :-)

vipluv
  • 607
  • 5
  • 8