Our First Java Application
As we briefly hinted before, programs in Java are written in source code (which are plain text, human-readable files) that is processed by a compiler (in the case of Java, javac) to produce the Java bytecode in class files. The class files containing Java bytecode are, then, fed to a program called java, which contains the Java interpreter/JVM that executes the program that we wrote:
Figure 1.2: The process of compilation in Java
Syntax of a Simple Java Program
Like all programming languages, the source code in Java must follow particular syntaxes. Only then, will the program compile and provide accurate results. Since Java is an object-oriented programming language, everything in Java is enclosed within classes. A simple Java program looks similar to this:
public class Test { //line 1 public static void main(String[] args) { //line 2 System.out.println("Test"); //line 3 } //line 4 } //line 5
Every java program file should have the same name as that of the class that contains main (). It is the entry point into the Java program.
Therefore the preceding program will compile and run without any errors only when these instructions are stored in a file called Test.java.
Another key feature of Java is that it is case-sensitive. This implies that System.out.Println will throw an error as it is not capitalized correctly. The correct instruction should be System.out.println.
main() should always be declared as shown in the sample. This is because, if main() is not a public method, it will not be accessed by the compiler, and the java program will not run. The reason main() is static is because we do not call it using any object, like you would for all other regular methods in Java.
Note
We will discuss these the public and static keywords later in this book, in greater depth.
Comments are used to provide some additional information. The Java compiler ignores these comments.
Single line comments are denoted by // and multiline comments are denoted by /* */.
Exercise 1: A Simple Hello World Program
Right-click the src folder and select New | Class.
Enter HelloWorld as the class name, and then click OK.
Enter the following code within the class:
public class HelloWorld{ public static void main(String[] args) { // line 2 System.out.println("Hello, world!"); // line 3 } }
Run the program by clicking on Run | Run 'Main'.
The output of the program should be as follows:
Hello World!
Exercise 2: A Simple Program for Performing Simple Mathematic Operations
Right-click the src folder and select New | Class.
Enter ArithmeticOperations as the class name, and then click OK.
Replace the code inside this folder with the following code:
public class ArithmeticOperations { public static void main(String[] args) { System.out.println(4 + 5); System.out.println(4 * 5); System.out.println(4 / 5); System.out.println(9 / 2); } }
Run the main program.
The output should be as follows:
9 20 0 4
In Java, when you divide an integer (such as 4) by another integer (such as 5), the result is always an integer (unless you instruct the program otherwise). In the preceding case, do not be alarmed to see that 4 / 5 gives 0 as a result, since that's the quotient of 4 when divided by 5 (you can get the remainder of the division by using a % instead of the division bar).
To get the result of 0.8, you would have to instruct the division to be a floating-point division instead of an integer division. You can do that with the following line:
System.out.println(4.0 / 5);
Yes, this does mean, like most programming languages, there is more than one type of number in Java.
Exercise 3: Displaying Non-ASCII Characters
Right-click the src folder and select New | Class.
Enter ArithmeticOperations as the class name, and then click OK.
Replace the code in this folder with the following code:
public class HelloNonASCIIWorld { public static void main(String[] args) { System.out.println("Non-ASCII characters: ☺"); System.out.println("∀x ∈ ℝ: ⌈x⌉ = −⌊−x⌋"); System.out.println("π ≅ " + 3.1415926535); // + is used to concatenate } }
Run the main program.
The output for the program should be as follows:
Non-ASCII characters: ☺ ∀x ∈ ℝ: ⌈x⌉ = −⌊−x⌋ π ≅ 3.1415926535
Activity 1: Printing the Results of Simple Arithmetic Operations
To write a java program that prints the sum and the product of any two values, perform the following steps:
Create a new class.
Within main(), print a sentence describing the operation on the values you will be performing along with the result.
Run the main program. Your output should be similar to the following:
The sum of 3 + 4 is 7 The product of 3 + 4 is 12
Note
The solution for this activity can be found on page 304.
Getting Input from the User
We previously studied a program that created output. Now, we are, going to study a complementary program: a program that gets input from the user so that the program can work based on what the user gives the program:
import java.io.IOException; // line 1 public class ReadInput { // line 2 public static void main(String[] args) throws IOException { // line 3 System.out.println("Enter your first byte"); int inByte = System.in.read(); // line 4 System.out.println("The first byte that you typed: " + (char) inByte); // line 5 System.out.printf("%s: %c.%n", "The first byte that you typed", inByte); // line 6 } // line 7 } // line 8
Now, we must dissect the structure of our new program, the one with the public class ReadInput. You might notice that it has more lines and that it is apparently more complex, but fret not: every single detail will be revealed (in all its full, glorious depth) when the time is right. But, for now, a simpler explanation will do, since we don't want to lose our focus on the principal, which is taking input from the user.
First, on line 1, we use the import keyword, which we have not seen yet. All Java code is organized in a hierarchical fashion, with many packages (we will discuss packages in more detail later, including how to make your own).
Here, hierarchy means "organized like a tree", similar to a family tree. In line 1 of the program, the word import simply means that we will use methods or classes that are organized in the java.io.Exception package.
On line 2, we, as before, create a new public class called ReadInput, without any surprises. As expected, the source code of this program will have to be inside a source file called ReadInput.java.
On line 3, we start the definition of our main method, but, this time, add a few words after the closing parentheses. The new words are throws IOException. Why is this needed?
The short explanation is: "Because, otherwise, the program will not compile." A longer version of the explanation is "Because when we read the input from the user, there may be an error and the Java language forces us to tell the compiler about some errors that our program may encounter during execution."
Also, line 3 is the line that's responsible for the need of the import in line 1: the IOException is a special class that is under the java.io.Exception hierarchy.
Line 5 is where the real action begins: we define a variable called inByte (short for "byte that will be input"), which will contain the results of the System.in.read method.
The System.in.read method, when executed, will take the first byte (and only one) from the standard input (usually, the keyboard, as we already discussed) and give it back as the answer to those who executed it (in this case, we, in line 5). We store this result in the inByte variable and continue the execution of the program.
With line 6, we print (to the standard output) a message saying what byte we read, using the standard way of calling the System.out.println method.
Notice that, for the sake of printing the byte (and not the internal number that represents the character for the computer), we had to use a construct of the following form:
An open parenthesis
The word char
A closing parenthesis
We use this before the variable named inByte. This construct is called a type cast and will be explained in much more detail in the lessons that follow.
On line 7, we use a different way to print the same message to the standard output. This is meant to show you how many tasks may be accomplished in more than one way and that there is "no single correct" way. Here, we use the System.out.println function.
The remaining lines simply close the braces of the main method definition and that of the ReadInput class.
Some of the main format strings for System.out.printf are listed in the following table:
There are many other formatting strings and many variables, and you can find the full specification on Oracle's website.
We will see some other common (modified) formatted strings, such as %.2f (which instructs the function to print a floating-point number with exactly two decimal digits after the decimal point, such as 2.57 or -123.45) and %03d (which instructs the function to print an integer with at least three places possibly left filled with 0s, such as 001 or 123 or 27204).
Exercise 4: Reading Values from the User and Performing Operations
To read two numbers from the user and print their product, perform the following steps:
Right-click the src folder and select New | Class.
Enter ProductOfNos as the class name, and then click OK.
Import the java.io.IOException package:
import java.io.IOException;
Enter the following code within the main() to read integers:
public class ProductOfNos{ public static void main(String[] args){ System.out.println("Enter the first number"); int var1 = Integer.parseInt(System.console().readLine()); System.out.println("Enter the Second number"); int var2 = Integer.parseInt(System.console().readLine());
Enter the following code to display the product of the two variables:
System.out.printf("The product of the two numbers is %d", (var1 * var2)); } }
Run the program. You should see an output similar to this:
Enter the first number 10 Enter the Second number 20 The product of the two numbers is 200
Well done, this is your first Java program.