LIWA

Basic structure of a class in java

ICSE Class 9 · Computer Applications · Chapter 5

What this chapter covers

Key points

Questions answered

What is meant by the basic structure of a Java program? Name its parts in order.
The basic structure is the standard arrangement of the parts of a program. In order, they are: comments describing the program, the import statement (when `Scanner` is used), the class header, and the class body containing the `main()` method with its statements.
Define a class header and a class body.
A class header is the first line of a class definition, made up of the keyword `class` and the class name, as in `class Bill`. A class body is everything enclosed between the opening and closing curly braces that follow the header.
Why is the `main()` method needed in a program that is to be run?
Execution of a Java program begins at the first statement of `main()` and ends at its closing brace. Without `main()`, the class can be compiled but there is no starting point from which to run it as a program.
Under what condition must a Java file have the same name as its class? What would the file be called for `public class Marks`?
A file must have exactly the same name as its class when the class is declared `public`. The file for `public class Marks` must be saved as `Marks.java`.
What is a comment? Why are comments called non-executable?
A comment is a note written in a program for human readers. It is called non-executable because the compiler ignores it, so it is not converted into byte code and has no effect when the program runs.
Give one example each of a single-line comment and a multi-line comment.
`// finds the area of a circle` is a single-line comment. `/* Program to find the area of a circle, written for Class IX */` is a multi-line comment, and it may be spread over several lines.
The syllabus says that `public`, `static` and `String args[]` are default in nature. Explain the purpose of each.
`public` is an access specifier that lets the Java Virtual Machine, which is outside the class, call `main()`. `static` lets `main()` be called through the class without first creating an object. `String args[]` is the parameter that receives words typed when the program is started. In the ICSE short form `void main()`, these may be left out.
Why can `void` not be left out of the header of `main()`?
`void` is the return type of the method, showing that `main()` returns no value. Every method header in Java must state a return type, so `void` is written in both the short and the full form of the header.