Introduction
A computer program, or a program, is a sequence of statements whose objective is to accomplish a task. Programming is a process of planning and creating a program. Learning a programming language requires direct interaction with the tools. You must have a fundamental knowledge of the language, and you must test your programs on the computer to make sure that each program does what it is supposed to do.
The Basics of a Java Program
A programming language is a set of rules, symbols, and special words. The syntax rules of a language determine which instructions are valid. The semantic rules determine the meaning of the instructions. Together these rules enable you to write programs to solve problems.
The smallest individual unit of a program written in any programming language is called a token. Java’s tokens are divided into special symbols, word symbols, and identifiers.
Special Symbols
The following are special symbols in Java.
+ - * /
. ; ? ,
<= != == >=
The first row of symbols includes mathematical symbols for addition, subtraction, multiplication, and division. In Java, commas are used to separate items in a list. Semicolons are used to end a Java statement. The symbols in the third row are used for comparisons.
Word Symbols
Word symbols are called reserved words or keywords. Examples include int, float, double, char, void, public, static, throws, return.
Identifiers
Identifiers are names of things, such as variables, constants, and methods, that appear in programs. A Java identifier consists of letters, digits, the underscore character ( _), and the dollar sign ($), and must begin with a letter, underscore, or the dollar sign.
Data Types
The objective of a Java program is to manipulate data. A Data type is a set of values together with a set of operations. Only certain operations can be performed on a particular type of data.
Primitive Data Types
There are three primitive data types: integral, floating-point, and boolean.
The integral data type deals with integers, or numbers without a decimal part. It is classified into five categories: char, byte, short, int, long. The int data type can represent integers between
-2147483648 and 2147483647. The data type short is used to represent integers between –32768 and 32767.
-2147483648 and 2147483647. The data type short is used to represent integers between –32768 and 32767.
The floating-point data type deals with decimal numbers.
The boolean data type deals with logical values.
int Data Type
Positive integers do not have to have a + sign in front of them. No commas are used within an integer.
char Data Type
The char data type is used to represent single characters such as letters, digits, and special symbols. It can represent any key on your keyboard. Each character represented is enclosed within single quotation marks. Only one symbol can be placed between the single quotation marks.
Java uses the Unicode character set, which contains 65536 values numbered 0 to 65535. Each of the 65536 values of the Unicode character set represents a different character. Each character has a predefined ordering, which is called a collating sequence, in the set. This is used when you compare characters.
boolean Data Type
The data type boolean has only two values: true and false. These are called the logical (Boolean) values. The central purpose of this data type is to manipulate logical (Boolean) expressions.
An expression that evaluates to true or false is called a logical (Boolean) expression.
Floating-Point Data Types
The floating-point data type deals with decimal numbers. To represent real numbers, Java uses a form of scientific notation called floating-point notation.
The data types float and double are used to manipulate decimal numbers. Floats represent any real number between –3.4E+38 and 3.4E+38. The memory allocated for the float data type is 4 bytes. Doubles are used to represent any real number between –1.7E+308 and 1.7E+308. The memory allocated for the double data type is 8 bytes.
The maximum number of significant digits in float values is 6 or 7, while the maximum number of significant digits in double values is 15.
Arithmetic Operators and Operator Precedence
There are five arithmetic operators:
+ addition
- subtraction
* multiplication
/ division
% mod (modulus) operator
You can use these operators with both integral and floating-point data types. Integral division truncates any fractional part; there is no rounding.
An arithmetic expression is constructed by using arithmetic operators and numbers. The numbers in the expression are called operands. Moreover, the numbers used to evaluate an operator are called the operands for that operator. Operators that have only one operand are called unary operators. Operators that have two operands are called binary operators.
Order of Precedence
Java uses operator precedence rules to determine the order in which operations are performed to evaluate the expression. According to the order of precedence rules for arithmetic operators, *, /, and % have a higher level of precedence than + and -.
Because arithmetic operators are evaluated from left to right, unless parentheses are present, the associativity of arithmetic operators is said to be from left to right.
Since the char data type is also an integral data type, Java allows you to perform arithmetic operations on char data.
Expressions
If all operands in an expression are integers, the expression is called an integral expression. If all operands in an expression are floating-point numbers, the expression is called a floating-point or decimal expression.
Evaluating an integral or a floating-point expression is straightforward. When operators have the same precedence, the expression is evaluated from left to right. To avoid confusion you can always use parentheses to group operands and operators.
Mixed Expressions
An expression that has operands of different data types is called a mixed expression. A mixed expression contains both integers and floating-point numbers.
1. When evaluating an operator in a mixed expression:
a. If the operator has the same types of operands (that is, both are integers or both are floating-point numbers), the operator is evaluated according to the type of the operand. Integer operands yield an integer result; floating-point numbers yield a floating-point number result.
b. If the operator has both types of operands (that is, one is an integer and the other is a floating-point number), during calculation the integer is changed to a floating-point number with the decimal part of zero, and then the operator is evaluated. The result is a floating-point number.
2. The entire expression is evaluated according to the precedence rules. The multiplication, division, and modulus operators are evaluated before the addition and subtraction operators. Operators having the same level of precedence are evaluated from left to right. Grouping is allowed for clarity.
Type Conversion (Casting)
When a value of one data type is automatically changed to another data type, implicit type coercion has occurred. To avoid implicit type coercion, Java provides for explicit type conversion through the use of a cast operator. The cast operator, also called the type conversion or type casting, takes the following form:
(dataTypeName) expression
First, the expression is evaluated. Its value is then converted to a value of the type specified by dataTypeName.
When using the cast operator to convert a floating-point (decimal) number to an integer, you simply drop the decimal part of the floating-point number.
You can also use cast operators to explicitly convert char data values into int data values, and int data values into char data values. To convert char data values into int data values, you use a collating sequence.
The class String
A string is a sequence of zero or more characters. Strings in Java are enclosed in double quotation marks.
To process strings effectively, Java provides the class String. The class String contains various operations to manipulate a string. A string that contains no characters is called a null or empty string.
The position of the first character is 0, the position of the second character is 1, and so on. The length of a string is the number of characters in it.
Input
Storing data in the computer’s memory is a two-step process:
1. Instruct the computer to allocate memory.
2. Include statements in the program to put the data into the allocated memory.
Allocating Memory with Named Constants and Variables
When you instruct the computer to allocate memory, you tell it what names to use for each memory location, and what type of data to store in those memory locations. Knowing the location of data is essential because data stored in one memory location might be needed at several places in the program. It is also critical to know whether your data must remain fixed throughout program execution or whether it should change.
A named constant is a memory location whose content is not allowed to change during program execution.
Declaration statements allocate memory. The syntax to declare a named constant is:
static final dataType IDENTIFIER = value;
In Java, static and final are both reserved words. The reserved word final specifies that the value stored in the identifier is fixed and cannot be changed. The reserved word static may or may not appear when a named constant is declared.
Using a named constant to store fixed data, rather than using the data value itself, has one major advantage. If the fixed data changes, you do not need to edit the entire program and change the old value to the new value. Instead, you can make the change at just one place, recompile the program, and execute it using the new value throughout. In addition, by storing a value and referring to that memory location whenever the value is needed, you avoid typing the same value again and again and you prevent typos.
Memory cells whose contents can be modified during program execution are called variables. The syntax for declaring one variable or multiple variables is:
dataType identifier1, identifier2, ..., identifierN;
Putting Data into Variables
The two common ways to place data into a variable are:
1. Use an assignment statement.
2. Use input (read) statements.
Assignment Statement
The assignment statement takes the following form:
variable = expression;
The value of the expression should match the data type of the variable.
The expression on the right side is evaluated, and its value is assigned to the variable (and thus to a memory location) on the left side.
A variable is initialized the first time a value is placed in the variable. In Java, = (the equals sign) is called the assignment operator. The associativity of the assignment operator is said to be from right to left.
Saving and Using the Value of an Expression
To save the value of an expression and use it in a later expression, do the following:
1. Declare a variable of the appropriate data type. For example, if the result of the expression is an integer, declare an int variable.
2. Use the assignment statement to assign the value of the expression to the variable that was declared. This action saves the value of the expression into the variable.
3. Wherever the value of the expression is needed, use the variable holding the value.
Declaring and Initializing Variables
When a variable is declared, Java might not automatically put a meaningful value into it. If you declare a variable and then use it in an expression without first initializing it, when you compile the program you are likely to get an error. Therefore Java allows you to initialize variables while they are being declared.
Input (Read) Statement
To put data into variables from the standard input device, we first create an input stream object and associate it with the standard input device. The following statement accomplishes this:
static Scanner console = new Scanner(System.in);
This statement creates the input stream object console and associates it with the standard input device.
The object console reads the next input as follows:
- console.nextInt(): retrieves that integer, if the value of this expression is that integer.
- console.nextDouble(): retrieves that floating-point number, if the value of this expression is that floating-point number.
- console.next(): retrieves the next input as a string, if the value of this expression is the next input string.
- console.nextLine(): retrieves the next input as a string until the end of the line, if the value of this expression is the next input line.
If the next input cannot be expressed as an appropriate number, then the expressions console.nextInt() and console.nextDouble() will cause the program to terminate with an error message.
Variable Initialization
Consider the following declaration:
int feet;
You can initialize the variable feet to a value of 35 either by using the assignment statement:
feet = 35;
or by executing the following statement and entering 35 during program execution:
feet = console.nextInt();
If you use the assignment statement to initialize feet, then you are stuck with the same value each time the program runs unless you edit the source code, change the value, recompile, and run. By using an input statement, each time the program runs, you are prompted to enter a value, and the value entered is stored in feet. Therefore, a read statement is much more versatile than an assignment statement.
Reading a Single Character
Suppose the next input is a single printable character, say A, and ch is a char variable. To input A into ch, you can use the following statement:
ch = console.next().charAt(0);
where console is as declared before.
Increment and Decrement Operators
Java provides the increment operator, ++, which increases the value of a variable by 1, and the decrement operator, --, which decreases the value of a variable by 1. Increment and decrement operators each have two forms, pre and post. The syntax of the increment operator is:
Pre-increment: ++variable
Post-increment: variable++
The syntax of the decrement operator is:
Pre-decrement: --variable
Post-decrement: variable--
The pre-increment adds 1 to the variable before the expression is evaluated, while the post-increment adds 1 to the variable after the expression is evaluated. Similarly, the pre-decrement subtracts 1 from the variable before it is evaluated in an expression, while post-decrement subtracts the value 1 from the variable after the expression is evaluated.
Strings and the Operator +
The operator + can be used to concatenate two strings, as well as a string and a numeric value or a character.
Example:
String str;
str = "Sunny";
str = str + " Day";
The final value in str is “Sunny Day”
Output
In Java, output on the standard output device is accomplished by using the standard output object System.out. The object System.out has access to two methods, print and println, to output a string on the standard output device.
The syntax to use the object System.out and the methods print and println is:
System.out.print(stringExp);
System.out.println(stringExp);
These are output statements. The expression is evaluated, and its value is printed at the current insertion point on the output device.
In an output statement, if expression consists of only one string or a single constant value, then expression evaluates to itself. If expression consists of only one variable, then expression evaluates to the value of the variable.
The statement:
System.out.println();
only positions the insertion point at the beginning of the next line. On the screen, the insertion point is where the cursor is.
In Java, \ is called the escape character and \n is called the newline escape sequence. When \n is encountered in the string, the insertion point is positioned at the beginning of the next line. Note also that \n may appear anywhere in the string.
The following escape sequences exist in Java:
\n Newline: Insertion point moves to the beginning of the next line
\t Tab: Insertion point moves to the next tab stop
\b Backspace: Insertion point moves one space to the left
\r Return: Insertion point moves to the beginning of the current line
\\ Backslash: Backslash is printed
\' Single quotation: Single quotation mark is printed
\" Double quotation: Double quotation mark is printed
Method flush
The output generated by the methods print and println first goes into an area in the computer called a buffer. When the buffer is full, the output is sent to the output device. You can use the method flush associated with System.out to empty the buffer even if it is not full.
Packages, Classes, Methods and the Import Statement
A package is a collection of related classes. Every package has a name.
The term class is used to create Java programs—either application or applet; it is used to group a set of related operations; and it is used to allow users to create their own data types. Each of these operations is implemented using the Java mechanism of methods.
A method is a set of instructions designed to accomplish a specific task.
To make use of the existing classes, methods, and identifiers, you must specify the packages that contain the appropriate information using the reserved word import and importing the contents of the package into the program as follows:
import packageName.*;
Creating a Java Application Program
The basic unit of a Java program is called a class. A Java application program is, therefore, a collection of one or more classes.
A method is a set of instructions designed to accomplish a specific task. Some predefined or standard methods such as nextInt, print, and println are already written and are provided as part of the system. But to accomplish most tasks, programmers must learn to write their own methods.
One of the classes in a Java application program must have the method called main. Moreover, there can be only one method main in a Java program. If a Java application program has only one class, it must contain the method main.
Statements to declare memory spaces (named constants and variables), statements to create input stream objects, statements to manipulate data (such as assignments), and statements to input and output data will be placed within the class. Statements to declare named constants and input stream objects are usually placed outside the method main, and statements to declare variables are usually placed within the method main. Statements to manipulate data, and input and output statements are placed within the method main.
The syntax of a class to create a Java application program is:
public class ClassName
{
classMembers
}
where ClassName is a user-defined Java identifier; classMembers consists of data members and methods (such as the method main). In Java, public and class are reserved words.
The general syntax of the method main is:
public static void main(String[] args)
{
statement1
.
.
.
statement
}
The import statements and the program statements constitute the Java source code. This source code must be saved in a file, called a source file that has the name extension .java. The name of the class and the name of the file containing the Java program must be the same.
public static void main(String[] args) is called the heading of the method main.
The statements enclosed between curly braces ({ and }) form the body of the method main. The body of the method main contains two types of statements: Declaration statements and Executable statements. Declaration statements are used to declare things such as variables. Executable statements perform calculations, manipulate data, create output, accept input, and so on. Variables or identifiers can be declared anywhere in the program, but must be declared before they can be used.
Skeleton of a program:
import statements if any
public class ClassName
{
declare named constants and/or stream objects
public static void main(String[] args)
{
variable declaration
executable statements
}
}
Programming Style and Form
Using the proper structure makes a Java program easier to understand and modify. It is frustrating trying to follow, and perhaps modify, a program that is syntactically correct, but has no structure.
Syntax
The syntax rules of a language tell what is legal and what is illegal. Errors in syntax are detected during compilation.
When a program is typed, errors are almost unavoidable. Therefore, when the program is compiled, you most likely will see syntax errors. It is possible that a syntax error at a particular place might lead to syntax errors in several subsequent statements. It is common for the omission of a single character to cause four or five error messages. However, when the first syntax error is removed and the program is recompiled, subsequent syntax errors caused by the first syntax error may disappear. Therefore, you should correct syntax errors in the order in which the compiler lists them.
Use of Blanks
In Java, you use one or more blanks to separate numbers when data is input. Blanks are also used to separate reserved words and identifiers from each other and from other symbols.
Use of Semicolons, Braces, and Commas
All Java statements must end with a semicolon. The semicolon is also called a statement terminator.
Braces can be regarded as delimiters, because they enclose the body of a method and set it off from other parts of the program.
Commas are used to separate items in a list.
Semantics
The set of rules that gives meaning to a language is called semantics.
Naming Identifiers
Consider the following set of statements:
final double CENTIMETERS_PER_INCH = 2.54;
double centimeters;
double inches;
centimeters = inches * CENTIMETERS_PER_INCH;
The identifiers such as CENTIMETERS_PER_INCH, are usually called self-documenting identifiers. Self-documenting identifiers can make comments less necessary.
The rules that Java programmers traditionally follow to name named constants, variables and classes are as follows:
- An identifier used to name a named constant is all uppercase. If the identifier is a run-together-word, then the words are separated with the underscore character.
For example:
final double CENTIMETERS_PER_INCH = 2.54;
final int INCHES_PER_FOOT = 12;
- An identifier used to name a variable is lowercase. If the identifier is a run-together-word, then the first letter of each word, except the first word, is uppercase.
For example:
double salary;
int firstNumber;
- An identifier used to name a class is all lowercase with the first letter of each word in uppercase. For example, Welcome and MakeChange.
Prompt Lines
Part of good documentation is the use of clearly written prompts so that users will know what to do when they interact with a program. Prompt lines are executable statements that inform the user what to do. In a program, whenever users must provide input, you must include the necessary prompt lines. Furthermore, these prompt lines should include as much information as possible about what input is acceptable.
Documentation
A well-documented program is easier to understand and modify, even a long time after you originally write it. You use comments to document programs. Comments should appear in a program to explain the purpose of the program, identify who wrote it, and explain the purpose of particular statements.
Comments
Single line comments begin with //, can be placed anywhere in the line, and everything after the // is ignored by the compiler. Multiple line comments are enclosed between /* and */. The compiler ignores anything that appears between /* and */.
Form and Style
In practice, Java’s rules give it a great degree of freedom. The clarity of the rules of syntax and semantics frees you to adopt formats that are pleasing to you and easier to understand.
Your programs should be properly indented and formatted. To document the variables, programmers typically declare one variable per line. Also, always put a space before and after an operator.
More on Assignment Statements
In general, using the compound operator *=, you can rewrite the simple assignment statement
variable = variable * (expression);
as
variable *= expression;
Similar conventions apply to the other arithmetic compound operators. For example, using the compound operator +=, you can rewrite the simple assignment statement
variable = variable + (expression);
as
variable += expression;
The compound assignment statement lets you write simple assignment statements in a concise fashion by combining an arithmetic operator with an assignment operator.
Programming Example: Convert Length
This program converts measurements in feet and inches into centimeters using the formula that 1 inch is equal to 2.54 centimeters. It uses the following steps to come up with the final code solution.
- Problem Analysis and Algorithm Design
- Declaring Variables
- Stating Named Constant
4. Main Algorithm
- Putting it all together and producing final code
The main algorithm for this program is:
- Prompt the user for the input. (Without a prompt line, the user will stare at a blank screen and not know what to do.)
- Get feet.
- Prompt the user to enter a value for inches.
- Get inches.
- Echo the input—output what the program read as input. (Without this step, after the program has executed, you will not know what the input was.)
- Find the length in inches.
- Output the length in inches.
- Convert the length to centimeters.
- Output the length in centimeters.
Programming Example: Make Change
Given any amount of change expressed in cents, this program computes the number of half-dollars, quarters, dimes, nickels, and pennies to be returned, returning as many half-dollars as possible, then quarters, dimes, nickels, and pennies, in that order. It uses the steps outlined in the last section to come up with the following algorithm and then displays the final java code solution.
Main Algorithm:
- Prompt the user for the input.
- Get the input.
- Echo the input by displaying the entered change on the screen.
- Compute and print the number of half-dollars.
- Calculate the remaining change.
- Compute and print the number of quarters.
- Calculate the remaining change.
- Compute and print the number of dimes.
- Calculate the remaining change.
- Compute and print the number of nickels.
- Calculate the remaining change.
- Print the remaining change.