Java Reference
In-Depth Information
Working with JDK 7
Anapplicationconsistsofaclasswithanentry-pointmethodnamed
main
.Althougha
andtothinkofamethodasanamedsequenceofinstructionsthatareexecutedwhenthe
method is called.
Listing 1-1
introduces you to your first application.
Listing 1-1.
Greetings from Java
class HelloWorld
{
public static void main(String[] args)
{
System.out.println("Hello, world!");
}
}
simpleapplication.Italsodeclaresamethodnamed
main
withinthisclass.Whenyou
runthisapplication,andyouwilllearnhowtodososhortly,itisthisentry-pointmethod
that is called and its instructions that are executed.
The
main()
methodincludesaheaderthatidentifiesthismethodandablockofcode
locatedbetweenanopenbracecharacter(
{
)andaclosebracecharacter(
}
).Aswellas
naming this method, the header provides the following information:
•
public
: This reserved word makes
main()
visible to the startup code that
callsthismethod.If
public
wasn'tpresent,thecompilerwouldoutputaner-
ror message stating that it could not find a
main()
method.
•
static
:Thisreservedwordcausesthismethodtoassociatewiththeclassin-
steadofassociatingwithanyobjectscreatedfromthisclass.Becausethestar-
tupcodethatcalls
main()
doesn'tcreateanobjectfromtheclassinorderto
callthismethod,itrequiresthatthemethodbedeclared
static
.Althoughthe
compiler willnotreportanerrorif
static
ismissing,itwillnotbepossible
to run
HelloWorld
, which will not be an application if the proper
main()
method doesn't exist.
•
void
: This reserved word indicates that the method doesn't return a value. If
youchange
void
toatype'sreservedword(e.g.,
int
)andtheninsertastate-