Structure of a Java program

Structure of a Java program A program in Java is a set of class declarations. A class cannot contain statements directly, but can contain the declarat...
Author: Tracey Hamilton
0 downloads 1 Views 46KB Size
Structure of a Java program A program in Java is a set of class declarations. A class cannot contain statements directly, but can contain the declarations of methods, which contain declarations and statements (ended with ;). A method implements a subprogram (in a way similar to functions and procedures in languages like C and Pascal). An object is an instance of a class. A Java program can be seen as a collection of objects satisfying certain requirements and interacting through functionalities made public (as in abstract data types). Let us write a simple Java program that prints the string (or sequence of characters) Ciao! on the video terminal. We need a Java Virtual Machine (that is an interpreter for Java). In these notes we will refer to JDK (Java Development Kit), a very basic Java programming environment. After creating a directory where we put the files containing our first exercises in Java, using a text editor we open a file Ciao.java in which we write the following program: class Ciao { public static void main (String[] args) { System.out.println("Ciao!"); } } Note that the name of the class coincides with that of the file. The Java standard convention is to have only one class in a file and the name of the file is the name of the class plus the suffix .java. Let us comment the program above. We said that a Java program is made of a collection of classes. Here we have only one class whose declaration starts with the reserved word class followed by the name (identifier) of the class Ciao and a parenthesis (which will be matched by a parenthesis at the end of the class declaration). The class Ciao contains a method, called main. In Java each method can be called (invoked) from within another method. Thus, an initial method is needed to start the execution of a program. Such a method is the method main, which must be general enough. The heading of the method main is public static void main (String[] args) and is always like this1 . The method main is characterized by the following properties: - is public (denoted by the reserved word public), i.e. it is visible from any point of the program: - is static (denoted by the reserved word static), because at the beginning of a program objects have not yet been created; - does not return anything (denoted by the reserved word void), because there is no other method calling the method main to which main can return a value; - the input data are seen as an array of strings (objects of the built-in class String). We will go back to the input data later. Note that in the above program no input data are used. Once the file has been saved, from the shell it is possible to compile the source code in the file Ciao.java by means of the command javac as follows: javac Ciao.java 1

In some textbooks it is written String argv[] inside the brackets. In Java the type array of String can also be denoted with the square brackets written after the array identifier (args or argv in this case), but it si advised not to use this notation and is instead suggested to write the type in a compact manner, that is String[]. As regards the use of args or argv, in these notes args will be used. However, as this is just the name (identifier) of the formal parameter of the method main, one can choose any legal identifier.

The compilation phase is successful (the Java code is syntactically correct) and the machine waits for another command. Whenever the Java compiler signals some error situations, one needs to understand where the errors are located and which are the modifications to be made. Once the corrections have been saved, the file Ciao.java can be compiled again. If the compilation is successful, one can see that the directory contains a file Ciao.class that has been generated by the compiler and represents the Bytecode program (to see the Bytecode one can use the command javap -c Ciao). It is now possible to run the program by means of the command java followed by the file name (without suffix) as follows: java Ciao If there are no runtime errors (and this is the case), Ciao! is printed on the video terminal and we get a new prompt on a new line. This is due to the fact that in the statement System.out.println("Ciao!"); there is a call to the method println of the (built-in) class PrintStream on the field out of the class System, which prints the string (enclosed between the two " symbols) that appears inside the brackets and then a new line. If we use the method print instead of println, the same string Ciao! is printed, but there is no new line.

Polymorphism and overloading Say what gets printed by the following program: class ProvaStampa { public static void main (String[] args) { System.out.println("start"); System.out.print("abc"); System.out.print(1); System.out.println(); } } Note that both methods print and println are used in various manners: we have the same method name, but the parameters are in different number and/or of different type. The method is said overloaded . More generally, the method is said to be polymorphic. Many built-in methods in Java are polymorphic to work in a different way on several different types. A classic example of polymorphic operator is + which is used to denote addition on integers (int), real numbers (float, double), etc., and string concatenation. For example, given the following Java program: class Stampa { public static void main (String[] args) { System.out.println("abc"); System.out.println(1+3); System.out.print("hello, "); System.out.print("world!"); System.out.println(); System.out.println("ab"+"cdef"); System.out.println("34"+"ciao"); System.out.println(34+"ciao"); System.out.println(7+3+"hip"); System.out.println(7+"hip"+3); System.out.println(7+(3+"hip")); } }

after compiling it with javac Stampa.java, the execution by means of the command java Stampa yields the following output: abc 4 hello, world! abcdef 34ciao 34ciao 10hip 7hip3 73hip Note that, if at least one parameter of the operator + is a string, then the other parameters are also considered as strings (we recall that in Java the operator + is left associative). N.B. Each Java method is followed by brackets ( ), even though the method has no (explicit) parameters.

Abstracting on input data Suppose we write a Java program which computes and prints the addition of two integer numbers. For example, if we want to add the numbers 7 and 4, we can write: class Somma1 { public static void main (String[] args) { System.out.println(7+4); } } The call to the method println with the actual parameter given by the expression 7+4 is executed by first evaluating the expression 7+4, which results in 11, and then such a value gets printed on the video terminal. However, once more we have not taken advantage of the possibility of providing input data, possibly different at each execution of the program. The two values to be given as input to the program are denoted through args[0] and args[1], respectively the first and second element of the array args (as we will see later, the elements of a monodimensional array can be singled out through an index starting from 0). We can think of writing the following program: class Conc { public static void main (String[] args) { System.out.println(args[0]+args[1]); } } Once the compilation has been carried out, the program is run by giving as input a sequence of values as required by the program. In this case the program expects two values to be added, thus we should provide two numbers, that are simply written one after the other by separating them with a blank space: java Conc 7 4 The result that gets printed is not, however, 11, but 74. Indeed, we must recall that the input to the program (or to the method main) is an array of strings, thus the two input values 7 and 4 are considered as strings and consequently the operation that is applied (denoted by the polymorphic operator +) is string concatenation. It follows that the result is the string 74. Let us test the program:

java Conc abc defg abcdefg java Conc "abc" "defg" abcdefg java Conc abc 11 abc11 java Conc 13 65 1365 java Conc Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0 at Conc.main(Conc.java:3) java Conc ab Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at Conc.main(Conc.java:3) java Conc ab cd ef abcd In order to add two input values, which are always seen as strings, we need to transform such values into integers by means of the method parseInt of the class Integer. We thus change the program into the following: class Somma { public static void main (String[] args) { int x = Integer.parseInt(args[0]); int y = Integer.parseInt(args[1]); System.out.println(x+y); } } A similar conversion must be carried out if we want to add two decimal numbers: class SommaDouble { public static void main (String[] args) { double x = Double.parseDouble(args[0]); double y = Double.parseDouble(args[1]); System.out.println(x+y); } } In this case we have: javac SommaDouble.java java SommaDouble 3.5 7.4 10.9 while, when using the program Conc, we have: javac Conc.java java Conc 3.5 7.4 3.57.4

Exercises 1. Write a Java program that, given as input the base and the height of a rectangle, prints its area. class AreaRett { public static void main (String[] args) { double b = Double.parseDouble(args[0]); double a = Double.parseDouble(args[1]); System.out.println(b*a); } } 2. Write a Java program that, given as input the base and the height of a triangle, prints its area. class AreaTriang { public static void main (String[] args) { double b = Double.parseDouble(args[0]); double a = Double.parseDouble(args[1]); System.out.println((b*a)/2); } }

Suggest Documents