Java Reference
In-Depth Information
Working with JDK 7
Anapplicationconsistsofaclasswithanentry-pointmethodnamed main .Althougha
properdiscussionofclassesandmethodsmustwaituntil Chapter2 , itsufficesfornow
to just think of a class as a factory for creating objects (also discussed in Chapter 2 ) ,
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!");
}
}
Listing1-1 declaresaclassnamed HelloWorld thatprovidesaframeworkforthis
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-
 
Search WWH ::




Custom Search