Sunday, 22 April 2018

Java - Basic Syntaxes

1.1  Revision

The steps in writing a Java program is illustrated as follows:
JavaBasics_Process.png
Step 1: Write the source codes (.java) using a programming text editor (such as Notepad++, Textpad, gEdit) or an IDE (such as Eclipse or NetBeans).
Step 2: Compile the source codes (.java) into Java portable bytecode (.class) using the JDK compiler ("javac").
Step 3: Run the compiled bytecode (.class) with the input to produce the desired output, using the Java Runtime ("java").

Java Basics

This chapter explains the basic syntaxes of the Java programming language. I shall assume that you could write some simple Java programs. (Otherwise, read "Introduction To Java Programming for First-time Programmers".)
To be a proficient programmer, you need to master two things: (1) the syntax of the programming language, and (2) the API libraries associated with the language.
You may also try the "Exercises on Java Basics".

1.  Basic Syntaxes

1.1  Revision

The steps in writing a Java program is illustrated as follows:
JavaBasics_Process.png
Step 1: Write the source codes (.java) using a programming text editor (such as Notepad++, Textpad, gEdit) or an IDE (such as Eclipse or NetBeans).
Step 2: Compile the source codes (.java) into Java portable bytecode (.class) using the JDK compiler ("javac").
Step 3: Run the compiled bytecode (.class) with the input to produce the desired output, using the Java Runtime ("java").
Below is a simple Java program that demonstrates the three basic programming constructs: sequentialloop, and conditional.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*
 * Sum the odd numbers and the even numbers from a lowerbound to an upperbound
 */
public class OddEvenSum {  // Save as "OddEvenSum.java"
   public static void main(String[] args) {
      int lowerbound = 1, upperbound = 1000;
      int sumOdd  = 0;    // For accumulating odd numbers, init to 0
      int sumEven = 0;    // For accumulating even numbers, init to 0
      int number = lowerbound;
      while (number <= upperbound) {
         if (number % 2 == 0) {  // Even
            sumEven += number;   // Same as sumEven = sumEven + number
         } else {                // Odd
            sumOdd += number;    // Same as sumOdd = sumOdd + number
         }
         ++number;  // Next number
      } 
      // Print the result
      System.out.println("The sum of odd numbers from " + lowerbound + " to " + upperbound + " is " + sumOdd);
      System.out.println("The sum of even numbers from " + lowerbound + " to " + upperbound + "  is " + sumEven);
      System.out.println("The difference between the two sums is " + (sumOdd - sumEven));
   }
}
The expected outputs are:
The sum of odd numbers from 1 to 1000 is 250000
The sum of even numbers from 1 to 1000  is 250500
The difference between the two sums is -500

1.2  Comments

Comments are used to document and explain your codes and your program logic. Comments are not programming statements. They are ignored by the compiler and have no consequences to the program execution. Nevertheless, comments are VERY IMPORTANT for providing documentation and explanation for others to understand your programs (and also for yourself three days later).
There are two kinds of comments in Java:
  1. Multi-Line Comment: begins with a /* and ends with a */, and can span multiple lines.
  2. End-of-Line (Single-Line) Comment: begins with // and lasts till the end of the current line.
I recommend that you use comments liberally to explain and document your codes. During program development, instead of deleting a chunk of statements irrevocably, you could comment-out these statements so that you could get them back later, if needed.

1.3  Statements and Blocks

Statement: A programming statement is the smallest independent unit in a program, just like a sentence in the English language. It performs a piece of programming action. A programming statement must be terminated by a semi-colon (;), just like an English sentence ends with a period. (Why not ends with a period like an English sentence? This is because period crashes with decimal point - it is hard for the dumb computer to differentiate between period and decimal point in the early days of computing!)
For examples,
// Each of the following lines is a programming statement, which ends with a semi-colon (;)
int number1 = 10;
int number2, number3=99;
int product;
product = number1 * number2 * number3;
System.out.println("Hello");
Block: A block is a group of statements surrounded by a pair of curly braces { }. All the statements inside the block is treated as one single unit. Blocks are used as the body in constructs like class, method, if-else and for-loop, which may contain multiple statements but are treated as one unit (one body). There is no need to put a semi-colon after the closing brace to end a compound statement. Empty block (i.e., no statement inside the braces) is permitted. For examples,
// Each of the followings is a "complex" statement comprising one or more blocks of statements.
// No terminating semi-colon needed after the closing brace to end the "complex" statement.
// Take note that a "complex" statement is usually written over a few lines for readability.
if (mark >= 50) {
   System.out.println("PASS");
   System.out.println("Well Done!");
   System.out.println("Keep it Up!");
}
 
if (number == 88) {
   System.out.println("Got it!"); 
} else { 
   System.out.println("Try Again!"); 
}
 
i = 1;
while (i < 8) {
   System.out.print(i + " ");
   ++i; 
}
 
public static void main(String[] args) {
   ...statements... 
}

1.4  White Spaces and Formatting Source Codes

White SpacesBlanktab and newline are collectively called white spaces. Java, like most of the computing languages, ignores extra white spaces. That is, multiple contiguous white spaces are treated as a single white space.
You need to use a white space to separate two keywords or tokens to avoid ambiguity, e.g.,
int sum=0;       // Cannot write intsum=0. Need at least one white space between "int" and "sum"
double average;  // Again, need at least a white space between "double" and "average"
Additional white spaces and extra lines are, however, ignored, e.g.,
// same as above
int  sum 
 =  0      ;

   double  average  ;
Formatting Source Codes: As mentioned, extra white spaces are ignored and have no computational significance. However, proper indentation (with tabs and blanks) and extra empty lines greatly improves the readability of the program. This is extremely important for others (and yourself three days later) to understand your programs.
For example, the following one-line hello-world program works. But can you read and understand the program?
public class Hello{public static void main(String[] args){System.out.println("Hello, world!");}}
Braces: Java's convention is to place the beginning brace at the end of the line, and align the ending brace with the start of the statement.
Indentation: Indent each level of the body of a block by an extra 3 (or 4) spaces.
/*
 * Recommended Java programming style
 */
public class ClassName {      // Place the beginning brace at the end of the current line
   public static void main(String[] args) {  // Indent the body by an extra 3 or 4 spaces for each level
   
      // Use empty line liberally to improve readability
      // Sequential statements
      statement;
      statement;
   
      // Conditional statement
      if (test) {
         statements;
      } else {
         statements;
      }
      
      // loop
      init;
      while (test) {
         statements;
         update;
      }
   }
}   // ending brace aligned with the start of the statement

No comments:

Post a Comment

Java - Operations

3.1  Arithmetic Operators Java supports the following arithmetic operators: Operator Description Usage Exampl...