In a source file, put a class. In a class, put methods. In a method, put statements.
What goes in a source file
A source file (a file with the .java extension) typically holds one class definition. The
class is a piece of your program, and the class must go within a pair of curly braces.
public class Dog {
}What goes in a class
A class has one or more methods. In the Dog class, the bark method will hold instructions
for how the dog will bark. Your methods must be declared inside a class (within the curly braces
of the class).
public class Dog { void bark() {
}}What goes in a method
Inside your method, write your instructions for how that method should be performed. Method code is basically a set of statements, and you can think of a method like a function or procedure.
public class Dog { void bark() { statement1; statement2; }}Anatomy of a class
When the JVM starts running, it looks for the class you give it at the command line, then it starts looking for a specially written method:
public static void main(String[] args) { // code goes here}The JVM runs everything within the curly braces of the main method. Every Java app has to have
at least one class, and at least one main method (not one main per class, just one main per
application):
public class MyFirstApp { public static void main(String[] args) { System.out.print("I Rule!"); }}public— so everyone can access itclass— definition of a classMyFirstApp— the name of the classstatic— we’ll get there latervoid— the return type of the method;voidmeans it has no return valuemain— the name of the methodString[] args— arguments to the method; this method must be given an array of Strings, and the array will be calledargsSystem.out.print— print to the standard output the string “I rule”
Notes
A Java source file ends with the .java extension, and a compiled bytecode file ends with the
.class extension. In every Java program, you must have only one top-level public class, and
that class has to match the name of the source file.
Let’s say you have a source file with multiple classes in it. When you compile the code, the JVM
creates bytecode .class files for each class in your source file. To avoid any confusion here,
the JVM is designed to treat the class that has the same name as your source file as the entry
point to your application.