main() method on the exam
You can expect to see questions related to the main()
method on the certification exam. Make sure that you remember that it has the public
and static
modifiers and the void
return type.
Also, remember that its argument is of the String[]
type.
You may also be asked a question on how command line arguments are accessed.
Remember that args[0]
references the first argument that is passed to the program. This is different from C and C++ programs where args[1]
references the first command line argument.
In Java, you need to have a method named main in at least one class.
In the following example, the class Building is being used by the class TestBuilding .
public class Building {
private int numPeople;
public Building() {
numPeople = 0;
}
public Building (int initPeople) {
numPeople = initPeople;
}
public void setPeople(int peopleSize){
numPeople=peopleSize;
}
public int getPeople(){
return numPeople;
}
public String toString() {
return "Number of people in this building is " + numPeople + " ";
}
}
public class TestBuilding{
public static void main(String [] args){
Building school = new Building(220); // 220 people in school
Building starbucks = new Building(37);
Building dentistOffice = new Building(); // default to zero
// accessor
System.out.println("School: " + school.getPeople() );
// mutator
starbucks.setPeople(40);
school.setPeople(221);
System.out.println("School: " + school.getPeople());
System.out.println("Starbucks: " + starbucks.getPeople());
System.out.println("Dentist: " + dentistOffice.getPeople());
// toString
System.out.println("Print school, again, but with toString:");
System.out.println( school.toString() ); // explicit toString
System.out.println( school ); // implicit toString
}
}