hts.StevenWood.com

Simple Program

Home ] Up ] Machine Code ] [ Simple Program ] Assignment 2-2 ] Syntax Errors ] Logic Errors ] Assignment ][ Last Page ]

Structure of a Simple Java Program


 

Basic code must be included in every Java program in order for it to work. Using the HelloWorldApp as an example, we can see what is involved in programming a basic Java program.

    class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("Hello World!");
        }
    }

    The class must have these 3 sections:

    1. word "class"
    2. the name of the class
    3. the beginning "{" and ending "}" points of the class

 

    class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("Hello World!");
        }
    }

    The "main( )" method - an entry point into our program must have these parts:

    1. the method access type & scope ( in this case "public" & "static")
    2. the method return type (in this case "void")
    3. the name of the method must be main(  ) and the parameters the method takes
    4. the beginning "{" and ending "}" points of the method
      the programming code  inside the method

 

    class HelloWorldApp {
        public static void main(String[] args) {
            System.out.println("Hello World!");
        }
    }
 

The "main" method is a key part of any program written in Java.  When the Java interpreter executes a Java application, it starts by calling the class's main method . The main method then calls all the other method and executes lines of code required to run your application.  If you try to run the Java interpreter on a class that does not have a main method , the interpreter refuses to run your program and displays an error message (except for Java applets, which have a different starting point).

The application could also have made use of another method named print().  Code and execute the following application and compare the output. There is often more than one way to achieve a result in Java. How does the print() method differ from the println() method? Hint: you will need this for Assignment 2-1

    class HelloWorldApp2 {
        public static void main(String[] args) {
            System.out.print("Hello");
            System.out.println(" World!" );
        }
    }
 

 

Home ] Up ] Machine Code ] [ Simple Program ] Assignment 2-2 ] Syntax Errors ] Logic Errors ] Assignment ][Last Page]
All material on this site is copyright © 1997- by Steven Wood or as credited. All right reserved. Use of this site indicates you agreement with the  terms of use.
Send comments or questions to about this page.
Every attempt has been made to credit work under copyright. If there are any claims that copyright has been missed please contact the .
+SDG+