IT 201 Module 2

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 17

Module 2 1

Introduction to Java Programming

SUBJECT : IT 101

DESCRIPTION : Introduction to Computing

PREPARED BY : MR. ALEX B. GUIRIGAY

Module 2
TITLE: Elementary Programming

OVERVIEW
Elementary programming covers some basic programming command and techniques. It tackles some of the built-
packages included in the installation of java. It also discusses about variables, constants, numeric data types and others.

OBJECTIVES
After the students read this module, they should be able to:

• write Java programs to perform simple computations;


• obtain input from the console using the Scanner class;
• use identifiers to name variables, constants, methods, and classes;
• use variables to store data;
• program with assignment statements and assignment expressions;
• use constants to store permanent data;
• name classes, methods, variables, and constants by following their naming conventions;
• explore Java numeric primitive data types: byte, short, int, long, float, and double;
• read a byte, short, int, long, float, or double value from the keyboard;
• perform operations using operators +, -, *, /, and %;
• perform exponent operations using Math.pow(a, b);
• write integer literals, floating-point literals, and literals in scientific notation;
• write and evaluate numeric expressions;
• obtain the current system time using System.currentTimeMillis();
• use augmented assignment operators;
• distinguish between postincrement and preincrement and between postdecrement and predecrement;
• cast the value of one type to another type;
• describe the software development process and apply it to develop the loan payment program;
• write a program that converts a large amount of money into smaller units; and
• avoid common errors and pitfalls in elementary programming.

DISCUSSION
Writing a Simple Program
Writing a program involves designing a strategy for solving the problem and then using a programming language to
implement that strategy.

Let’s first consider the simple problem of computing the area of a circle. How do we write a program for solving this
problem?

Writing a program involves designing algorithms and translating algorithms into programming instructions, or code.

Algorithm ➔ describes how a problem is solved by listing the actions that need to be taken and the order of their
execution.
Module 2 2
Introduction to Java Programming

 can help the programmer plan a program before writing it in a programming language.
 Algorithms can be described in natural languages or in pseudocode (natural language mixed with some
programming code).

The algorithm for calculating the area of a circle can be described as follows:

1. Read in the circle’s radius.


2. Compute the area using the following formula: area = pi * (radius * radius)
3. Display the result.

Tip: It’s always a good practice to outline your program (or its underlying problem) in the form of an algorithm before
you begin coding.

When you code—that is, when you write a program—you translate an algorithm into a program.

Sample Program # 1: ComputeArea.java


Description: A program that compute and display the area of a circle.

Code:

Line Code
No.
1 package chapter_2_ElementaryProgramming;

2 public class ComputeArea {

3 public static void main(String[] args) {


4 double radius; // Declare radius
5 double area; // Declare area

6 // Assign a radius
7 radius = 20; // radius is now 20

9 // Compute area
10 area = 3.14159 * (radius * radius);

11 // Display results
12 System.out.println("The area for the circle of radius " + radius + " is " + area);
13 }
14 }

Output:

The area for the circle of radius 20.0 is 1256.636

Explanations:
Line 1: package Module2;
This line tells the you that your program is currently in a package named Module2.

Line 2: public class ComputeArea {


Every Java program begins with a class definition in which the keyword class is followed by the class name.
Assume that you have chosen ComputeArea as the class name. The outline of the program would look like this:

public class ComputeArea {

//Details to be given later

Note that after the name of the class, it should be followed by open and close braces ({}).
Module 2 3
Introduction to Java Programming

Line 3: public static void main(String[] args) {


public: It is an Access modifier, which specifies from where and who can access the method. Making the
main() method public makes it globally available. It is made public so that JVM can invoke it from outside the
class as it is not present in the current class.

static: It is a keyword which is when associated with a method, makes it a class related method. The main()
method is static so that JVM can invoke it without instantiating the class. This also saves the unnecessary wastage
of memory which would have been used by the object declared only for calling the main() method by the JVM.

void: It is a keyword and used to specify that a method doesn’t return anything. As main() method doesn’t
return anything, its return type is void. As soon as the main() method terminates, the java program terminates
too. Hence, it doesn’t make any sense to return from main() method as JVM can’t do anything with the return
value of it.

main: It is the name of Java main method. It is the identifier that the JVM looks for as the starting point of the
java program. It’s not a keyword.

(String[] args): It stores Java command line arguments and is an array of type java.lang.String class.
Here, the name of the String array is args but it is not fixed and user can use any name in place of it.

Lines 4 and 5:

double radius; // Declare radius


double area; // Declare area

Declaration of variables. Here, we declare variables radius and area as double. By default, their values are zero
(0) or blank.

Line 7: radius = 20;

Here in this line, we declare the new value of radius as 20. So, from 0, its new value is 20.

Now, since that we now have the value of radius, we can now compute the area of the circle considering its
formula is: a = pi(r2)

Line 10: area = 3.14159 * (radius * radius);

Computation for the area.

area = 3.14159 * (20 * 20);

area = 3.14159 * (400);

area = 1,256.636

Line 12: System.out.println("The area for the circle of radius " + radius + " is " + area);

This line means that the computer (System) is going to display (println) the result of the computation in the
monitor (out) the string (The area for the circle of radius), plus the value of the radius (20) and the value
of the area (1,256.636).

Thus, the output of the program is:

The area for the circle of radius 20.0 is 1256.636

Built-in Packages
Java API has many pre-written classes to help programmers manage input, database, etc.
Module 2 4
Introduction to Java Programming

Some of the Java built-in packages:


• java.awt: Contains classes for creating user interfaces and for painting graphics and images. Classes like Button,
Color, Event, Font, Graphics, Image etc are part of this package.
• java.io: Provides classes for system input/output operations. Classes like BufferedReader, BufferedWriter, File,
InputStream, OutputStream, PrintStream, Serializable etc are part of this package.
• java.lang: Contains classes and interfaces that are fundamental to the design of Java programming language. Classes
like String, StringBuffer, System, Math, Integer etc are part of this package.
• java.net: Provides classes for implementing networking applications. Classes like Authenticator, HttpCookie, Socket,
URL, URLConnection, URLEncoder, URLDecoder etc are part of this package.
• java.sql: Provides the classes for accessing and processing data stored in a database. Classes like Connection,
DriverManager, PreparedStatement, ResultSet, Statement etc are part of this package.
• java.util: Contains the collections framework, some internationalization support classes, properties, random number
generation classes. Classes like ArrayList, LinkedList, HashMap, Calendar, Date, TimeZone etc are part of this
package.

Importing Packages
Two ways to import packages:

1. import specific class


Syntax:
import packagename.classname;

Example:
import java.util.Scanner;

2. import the whole package


Syntax:
import packagename.*;

Example:
Import java.util.*;

Reading Input from the Console


From the previous program, the radius is fixed in the source code. To use a different radius, you have to modify the
source code and recompile it. Obviously, this is not convenient, so instead you can use the Scanner class for console
input.

Syntax:

Scanner <variable name> = new Scanner(System.in);

Example:

Scanner user_input = new Scanner(System.in);

The syntax new Scanner(System.in) creates an object of the Scanner type. The syntax Scanner user_input
declares that user_input is a variable whose type is Scanner. The whole line Scanner user_input = new
Scanner(System.in); creates a Scanner object and assigns its reference to the variable input. An object may
invoke its methods. To invoke a method on an object is to ask the object to perform a task. You can invoke the
nextDouble() method to read a double value as follows:
Module 2 5
Introduction to Java Programming

double radius = input.nextDouble();

This statement reads a number from the keyboard and assigns the number to radius.

Sample Program # 2: ComputeAreaWithConsoleInput.java


Description: a program that accepts value of the radius and computes the area of a circle.

Code:

Line Code
No.
1 package chapter_2_ElementaryProgramming;

2 import java.util.Scanner; // Scanner is in the java.util package

3 public class ComputeAreaWithConsoleInput {

4 public static void main(String[] args) {


// Create a Scanner object
5 Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


6 System.out.print("Enter a number for radius: ");
7 double radius = input.nextDouble();

// Compute area
9 double area = radius * radius * 3.14159;

// Display results
10 System.out.println("The area for the circle of radius " + radius + " is " + area);
11 }
12 }

Output:

Enter a number for radius: 2


The area for the circle of radius 2.0 is 12.56636

Explanations:
Here in this program, we have a new set of codes:
• line 2 ➔ import java.util.Scanner;
• line 5 ➔ Scanner input = new Scanner(System.in);
• line 7 ➔ double radius = input.nextDouble();

Line 2 includes (import) the java library named (util) that has the command used to input values (Scanner) to be
used in the program.

To get user input we need to use something called a scanner. A scanner is a data-type/object just like Strings and
Ints.

Before you can use the Scanner class in a program, you must import it.

Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc.
and strings. It is the easiest way to read input in a Java program, though not very efficient if you want an input
method for scenarios where time is a constraint like in competitive programming.

This line is very important once you are going to input values to the console.
Module 2 6
Introduction to Java Programming

Line 5 is the declaration of the new variable input. It uses the newly included Scanner command and assigned it to
the variable input. You can use any variable you want to assign to Scanner (e.g. Scanner num1, Scanner name,
Scanner age, etc.).

The syntax new Scanner(System.in); creates an object of the Scanner type. The syntax Scanner input declares
that input is a variable whose type is Scanner. The whole line Scanner input = new Scanner(System.in);
creates a Scanner object and assigns its reference to the variable input.

This only means that you are going to input new value to the computer (System.in) using the new Scanner variable
which is the (input).

Line 6 displays a string "Enter a number for radius: " to the console. This is known as prompt, because it
directs the user to enter an input.

Line 7 is the command used to input value to the variable input. This statement reads a number from the keyboard and
assigns the number to radius. After the user enters a number and presses the Enter key, the program reads the
number and assigns it to radius.

Different types of user input:

1. nextLine() ➔ used for string 6. nextBoolean() ➔ used for logical answers true or
2. nextInt() ➔ used for whole numbers false
3. nextShort()➔ used for whole numbers 7. nextDouble() ➔ used for fractional numbers
4. nextLong()➔ used for whole numbers 8. nextFloat() ➔ used for fractional numbers
5. nextByte() ➔ used for whole numbers

Sample Program # 3: DifferentTypesOfInput.java


Description: A program that shows how to use some of the different types of input.

Code:

Package chapter_2_ElementaryProgramming;

import java.util.Scanner;

public class DifferentTypesOfUserInput {

public static void main(String[] args) {


Scanner differentInputs = new Scanner(System.in);
String name;
int age;
double grade;
boolean gender;

System.out.print("Enter your name: ");


name = differentInputs.nextLine();

System.out.print("Enter your age: ");


age = differentInputs.nextInt();

System.out.print("Are you male (true/false)? ");


gender = differentInputs.nextBoolean();

System.out.print("Enter your grade: ");


grade = differentInputs.nextDouble();
Module 2 7
Introduction to Java Programming

System.out.println("\nYour name is " + name);


System.out.println("You are " + age + " years old.");
System.out.println("Are you a male? " + gender);
System.out.println("Your grade is " + grade);
}
}
Output:

Enter your name: Juan


Enter your age: 25
Are you male (true/false)? true
Enter your grade: 1.4

Your name is Juan


You are 25 years old.
Are you a male? true
Your grade is 1.4

Sample Program # 4: ComputeAverage.java


Description: A program that lets you input multiple values to variables.

Code:

Line Code
No.
1 package Module2;
2 import java.util.Scanner;

3 public class ComputeAverage {

4 public static void main(String[] args) {


// Create a Scanner object
5 Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


6 System.out.print("Enter three numbers: ");
7 double number1 = input.nextDouble();
8 double number2 = input.nextDouble();
9 double number3 = input.nextDouble();

// Compute average
10 double average = (number1 + number2 + number3) / 3;

// Display results
9 System.out.println("The average of " + number1 + " " + number2 + " " +
number3 + " is " + average);
10 }
11 }

Output 1:

Enter three numbers: 1 2 3


The average of 1.0 2.0 3.0 is 2.0

Output 2:

Enter three numbers: 1


Module 2 8
Introduction to Java Programming

2
3
The average of 1.0 2.0 3.0 is 2.0

Identifiers
Identifiers are the names that identify the elements such as classes, methods, and variables in a program.

Difference between Identifier and Variable


Both an identifier and a variable are the names allotted by users to a particular entity in a program. The identifier is
only used to identify an entity uniquely in a program at the time of execution whereas, a variable is a name given to a
memory location, that is used to hold a value.

Example:

package Module2;
import java.util.Scanner;

public class ComputeAverage {

public static void main(String[] args) {


// Create a Scanner object
Scanner input = new Scanner(System.in);

// Prompt the user to enter three numbers


System.out.print("Enter three numbers: ");
double number1 = input.nextDouble();
double number2 = input.nextDouble();
double number3 = input.nextDouble();

// Compute average
double average = (number1 + number2 + number3) / 3;

// Display results
System.out.println("The average of " + number1 + " " + number2 + " " + number3 + " is
" + average);
}
}

Legend:

Texts in Black are examples of identifiers while texts in Red are examples of variables.

As you see from the previous sample program, ComputeAverage, main, input, number1, number2, number3, and so
on are the names of things that appear in the program. In programming terminology, such names are called identifiers.

All identifiers must obey the following rules:

• An identifier is a sequence of characters that consists of letters, digits, underscores (_), and dollar signs ($).
• An identifier must start with a letter, an underscore (_), or a dollar sign ($). It cannot start with a digit.
• An identifier cannot be a reserved word. (See Appendix A for a list of reserved words.)
• An identifier cannot be true, false, or null.
• An identifier can be of any length.

Examples:

Correct: A4, ComputeArea, area, radius, and print

Wrong: 2A, d+4

Note: Java is CASE SENSITIVE. So, area, Area and AREA are all different identifiers.
Module 2 9
Introduction to Java Programming

Variables
Variables are used to represent values that may be changed in the program.

Syntax for declaring a variable:

Datatype variablename;

Examples:

int count; // Declare count to be an integer variable


double radius; // Declare radius to be a double variable
double interestRate; // Declare interestRate to be a double variable

If variables are of the same type, they can be declared together. The above example declares both radius and
interestRate as double. And so, we can make it this way:

double radius, interestRate;

Separated only by commas.

Variables often have initial values. You can declare a variable and initialize it in one step. Consider, for instance, the
following code:

int count = 1;

is the same as:

int count;
count = 1;

or

int num1 = 20, num2 = 40, average = ((num1 + num2)/2);

is the same as:


int num1, num2, average;
num1 = 20;
num2 = 40;
average = ((num1 + num2)/2);

Assignment Statements and Assignment Operators


An assignment statement designates a value for a variable. An assignment statement can be used as an expression in
Java.

Syntax for Assignment Statement:


variable = expression;

An expression represents a computation involving values, variables, and operators that, taking them together, evaluates
to a value.

Examples:
int y = 1; // Assign 1 to variable y
double radius = 1.0; // Assign 1.0 to variable radius
int x = 5 * (3 / 2); // Assign the value of the expression to x
x = y + 1; // Assign the addition of y and 1 to x
double area = radius * radius * 3.14159; // Compute area

Note: In mathematics, x = 2 * x + 1 denotes an equation. However, in Java, x = 2 * x + 1 is an assignment statement that


evaluates the expression 2 * x + 1 and assigns the result to x.
Module 2 10
Introduction to Java Programming

Named Constants
A named constant is an identifier that represents a permanent value.

Syntax:

final datatype CONSTANTNAME = value;

Sample Program # 5: ComputeAreaWithConstant.java


Description: A program that demonstrates how to use constants.

Code:

package Module2;
import java.util.Scanner;

public class ComputeAreaWithConstant {

public static void main(String[] args) {


final double PI = 3.14159; // Declare a constant

// Create a Scanner object


Scanner input = new Scanner(System.in);

// Prompt the user to enter a radius


System.out.print("Enter a number for radius: ");
double radius = input.nextDouble();

// Compute area
double area = radius * radius * PI;

// Display result
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}

Output:

Enter a number for radius: 5


The area for the circle of radius 5.0 is 78.53975

There are three benefits of using constants:

1. You don’t have to repeatedly type the same value if it is used multiple times;
2. If you have to change the constant value (e.g., from 3.14 to 3.14159 for PI), you need to change it only in a single
location in the source code; and
3. A descriptive name for a constant makes the program easy to read.

Numeric Data Types and Operations


Reading Numbers from the Keyboard
Table 1: Methods for Scanner Objects
Method Description
nextByte() reads an integer of the byte type.
Module 2 11
Introduction to Java Programming

nextShort() reads an integer of the short type.


nextInt() reads an integer of the int type.
nextLong() reads an integer of the long type.
nextFloat() reads a number of the float type.
nextDouble() reads a number of the double type.

Examples:

Scanner input = new Scanner(System.in);


System.out.print("Enter a byte value: ");
byte byteValue = input.nextByte();

System.out.print("Enter a short value: ");


short shortValue = input.nextShort();

System.out.print("Enter an int value: ");


int intValue = input.nextInt();

System.out.print("Enter a long value: ");


long longValue = input.nextLong();

System.out.print("Enter a float value: ");


float floatValue = input.nextFloat();

If you enter a value with an incorrect range or format, a runtime error would occur. For example, you enter a value 128
for line 3, an error would occur because 128 is out of range for a byte type integer.

Sample Program # 4: DisplayTime.java

Description: A program that counts how many minutes in the number of seconds entered.

Code:

package Module2;
import java.util.Scanner;

public class DisplayTime {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);
// Prompt the user for input
System.out.print("Enter an integer for seconds: ");
int seconds = input.nextInt();

int minutes = seconds / 60; // Find minutes in seconds


int remainingSeconds = seconds % 60; // Seconds remaining
System.out.println(seconds + " seconds is " + minutes +
" minutes and " + remainingSeconds + " seconds");
}
}

Output:

Enter an integer for seconds: 150


150 seconds is 2 minutes and 30 seconds

The nextInt() method (line 8) reads an integer for seconds. Line 10 obtains the minutes using seconds / 60. Line
11 (seconds % 60) obtains the remaining seconds after taking away the minutes.
Module 2 12
Introduction to Java Programming

Exponent Operations
The Math.pow(a, b) method can be used to compute ab. The pow method is defined in the Math class in the Java
API. You invoke the method using the syntax Math.pow(a, b) (e.g., Math.pow(2, 3)), which returns the result of
ab (23). Here, a and b are parameters for the pow method and the numbers 2 and 3 are actual values used to invoke the
method. For example,

System.out.println(Math.pow(2, 3)); // Displays 8.0


System.out.println(Math.pow(4, 0.5)); // Displays 2.0
System.out.println(Math.pow(2.5, 2)); // Displays 6.25
System.out.println(Math.pow(2.5, -2)); // Displays 0.16

Numeric Literals
A literal is a constant value that appears directly in a program.

For example, 34 and 0.305 are literals in the following statements:

int numberOfYears = 34;


double weight = 0.305;

Integer Literals
An integer literal can be assigned to an integer variable as long as it can fit into the variable. A compile error will occur if
the literal is too large for the variable to hold. The statement byte b = 128, for example, will cause a compile error,
because 128 cannot be stored in a variable of the byte type. (Note that the range for a byte value is from –128 to
127.)

Floating-Point Literals
Floating-point literals are written with a decimal point. By default, a floating-point literal is treated as a double type
value. For example, 5.0 is considered a double value, not a float value. You can make a number a float by appending the
letter f or F, and you can make a number a double by appending the letter d or D. For example, you can use 100.2f or

100.2F for a float number, and 100.2d or 100.2D for a double number.

Note: The double type values are more accurate than the float type values.

For example,

System.out.println("1.0 / 3.0 is " + 1.0 / 3.0);

Displays

1.0 / 3.0 is 0.3333333333333333 (16 digits)

While

System.out.println("1.0F / 3.0F is " + 1.0F / 3.0F);

Displays

1.0F / 3.0F is 0.33333334 (8 digits)

Note: A float value has 7 to 8 number of significant digits and a double value has 15 to 17 number of significant digits.
Module 2 13
Introduction to Java Programming

Scientific Notation
Floating-point literals can be written in scientific notation in the form of a * 10b. For example, the scientific notation for
123.456 is 1.23456 * 102 and for 0.0123456 is 1.23456 * 10-2. A special syntax is used to write scientific notation
numbers. For example, 1.23456 * 102 is written as 1.23456E2 or 1.23456E+2 and 1.23456 * 10-2 as 1.23456E-2. E
(or e) represents an exponent and can be in either lowercase or uppercase.

Sample Program # 6: FahrenheitToCelcius.java


Description: A program that converts from Fahrenheit to Celcius.

Code:

package Module2;
import java.util.Scanner;

public class FahrenheitToCelcius {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

System.out.print("Enter a degree in Fahrenheit: ");


double fahrenheit = input.nextDouble();

// Convert Fahrenheit to Celsius


double celsius = (5.0 / 9) * (fahrenheit - 32);
System.out.println("Fahrenheit " + fahrenheit + " is " +
celsius + " in Celsius");
}
}

Output:

Enter a degree in Fahrenheit: 97.6


Fahrenheit 97.6 is 36.44444444444444 in Celsius

Augmented Assignment Operators


The operators +, -, *, /, and % can be combined with the assignment operator to form augmented operators.

Very often the current value of a variable is used, modified, and then reassigned back to the same variable. For example,
the following statement increases the variable count by 1:

count = count + 1;

is the same as

count += 1;

The += is called the addition assignment operator.

Table 2: Augmented Assignment Operators


Operator Name Example Equivalent
+= Addition Assignment i += 8 i = i + 8
-= Subtraction Assignment i -= 8 i = i - 8
*= Multiplication Assignment i *= 8 i = i * 8
/= Division Assignment i /= 8 i = i / 8
%= Remainder Assignment i %= 8 i = i % 8
Module 2 14
Introduction to Java Programming

Caution: There are no spaces in the augmented assignment operators. For example, + = should be +=.

Increment and Decrement Operators


The increment operator (++) and decrement operator (––) are for incrementing and decrementing a
variable by 1.

Examples:

int i = 3, j = 3;
i++; // i becomes 4
j--; // j becomes 2

i++ is pronounced as i plus plus and i—— as i minus minus. These operators are known as postfix increment (or
postincrement) and postfix decrement (or postdecrement), because the operators ++ and —— are placed after the
variable. These operators can also be placed before the variable. For example,

int i = 3, j = 3;
++i; // i becomes 4
--j; // j becomes 2

++i increments i by 1 and ——j decrements j by 1. These operators are known as prefix increment (or preincrement)
and prefix decrement (or predecrement).

Table 3: Increment and Decrement Operators


Operator Name Description Example (assume i = 1)
++var Preincrement Increment var by 1, and use the new var int j = ++i; // j is 2, i is 2
value in the statement
int j = i++; // j is 1, i is 2
var++ Postincrement Increment var by 1, but use the original var
value in the statement
Decrement var by 1, and use the new var int j = --i; // j is 0, i is 0
--var Predecrement value in the statement
int j = i--; // j is 1, i is 0
Decrement var by 1, and use the original var
var-- postdecrement value in the statement

Numeric Type Conversion


Floating-point numbers can be converted into integers using explicit casting.

Can you perform binary operations with two operands of different types? Yes. If an integer and a floating-point number
are involved in a binary operation, Java automatically converts the integer to a floating-point value. So, 3 * 4.5 is
same as 3.0 * 4.5.

The syntax for casting a type is to specify the target type in parentheses, followed by the variable’s name or the value to
be cast. For example, the following statement

System.out.println((int)1.7);

displays 1. When a double value is cast into an int value, the fractional part is truncated. The following statement

System.out.println((double)1 / 2);
Module 2 15
Introduction to Java Programming

displays 0.5, because 1 is cast to 1.0 first, then 1.0 is divided by 2. However, the statement

System.out.println(1 / 2);

displays 0, because 1 and 2 are both integers and the resulting value should also be an integer.

Sample Program # 7: SalesTax.java


Description:

Code:

package Module2;
import java.util.Scanner;

public class SalesTax {

public static void main(String[] args) {


Scanner input = new Scanner(System.in);

System.out.print("Enter purchase amount: ");


double purchaseAmount = input.nextDouble();

double tax = purchaseAmount * 0.06;


System.out.println("Sales tax is $" + (int)(tax * 100) / 100.0);
}
}

Output:

Enter purchase amount: 197.55


Sales tax is $11.85

The variable purchaseAmount is 197.55 (line 7). The sales tax is 6% of the purchase, so the tax is evaluated as
11.853 (line 9). Note that

tax * 100 is 1185.3

(int)(tax * 100) is 1185

(int)(tax * 100) / 100.0 is 11.85

So, the statement in line 10 displays the tax 11.85 with two digits after the decimal point.

Common Errors and Pitfalls


Common elementary programming errors often involve undeclared variables, uninitialized variables, integer overflow,
unintended integer division, and round-off errors.

Common Error 1: Undeclared/Uninitialized Variables and Unused Variables


A variable must be declared with a type and assigned a value before using it. A common error is not declaring a variable
or initializing a variable. Consider the following code:

double interestRate = 0.05;


double interest = interestrate * 45;
Module 2 16
Introduction to Java Programming

This code is wrong, because interestRate is assigned a value 0.05; but interestrate has not been declared and
initialized. Java is case sensitive, so it considers interestRate and interestrate to be two different variables.

If a variable is declared, but not used in the program, it might be a potential programming error. So, you should remove
the unused variable from your program. For example, in the following code, taxRate is never used. It should be
removed from the code.

double interestRate = 0.05;


double taxRate = 0.05;
double interest = interestRate * 45;
System.out.println("Interest is " + interest);

If you use an IDE such as Eclipse and NetBeans, you will receive a warning on unused variables.

Common Error 2: Integer Overflow


Numbers are stored with a limited number of digits. When a variable is assigned a value that is too large (in size) to be
stored, it causes overflow. For example, executing the following statement causes overflow, because the largest value
that can be stored in a variable of the int type is 2147483647. 2147483648 will be too large for an int value.

int value = 2147483647 + 1;


// value will actually be -2147483648

Likewise, executing the following statement causes overflow, because the smallest value that can be stored in a variable
of the int type is -2147483648. -2147483649 is too large in size to be stored in an int variable.

int value = -2147483648 - 1;


// value will actually be 2147483647

Java does not report warnings or errors on overflow, so be careful when working with numbers close to the maximum or
minimum range of a given type.

When a floating-point number is too small (i.e., too close to zero) to be stored, it causes underflow. Java approximates it
to zero, so normally you don’t need to be concerned about underflow.

Common Error 3: Round-off Errors


A round-off error, also called a rounding error, is the difference between the calculated approximation of a number and
its exact mathematical value. For example, 1/3 is approximately 0.333 if you keep three decimal places, and is
0.3333333 if you keep seven decimal places. Since the number of digits that can be stored in a variable is limited, round-
off errors are inevitable. Calculations involving floating-point numbers are approximated because these numbers are not
stored with complete accuracy. For example,

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);

displays 0.5000000000000001, not 0.5, and

System.out.println(1.0 - 0.9);

displays 0.09999999999999998, not 0.1. Integers are stored precisely. Therefore, calculations with integers yield a
precise integer result.

Common Error 4: Unintended Integer Division


Java uses the same divide operator, namely /, to perform both integer and floating-point division. When two operands
are integers, the / operator performs an integer division. The result of the operation is an integer. The fractional part is
truncated. To force two integers to perform a floating-point division, make one of the integers into a floating-point
number. For example, the code in (a) displays that average is 1 and the code in (b) displays that average is 1.5.
Module 2 17
Introduction to Java Programming

int number1 = 1; int number1 = 1;


int number2 = 2; int number2 = 2;
double average = (number1 + number2) / 2; double average = (number1 + number2) / 2.0;
System.out.println(average); System.out.println(average);
A B

Common Pitfall 1: Redundant Input Objects


New programmers often write the code to create multiple input objects for each input. For example, the following code
reads an integer and a double value.

Scanner input = new Scanner(System.in);


System.out.print("Enter an integer: ");
int v1 = input.nextInt();

Scanner input1 = new Scanner(System.in);


 Bad Code
System.out.print("Enter a double value: ");
double v2 = input1.nextDouble();

The code is not wrong, but inefficient. It creates two input objects unnecessarily and may lead to some subtle errors.
You should rewrite the code as follows:

Scanner input = new Scanner(System.in);


System.out.print("Enter an integer: ");
int v1 = input.nextInt();
System.out.print("Enter a double value: ");
 Good Code
double v2 = input.nextDouble();

EVALUATION
Programming
Make a program that will let you input all of the types of different inputs.

1. nextLine() 3. nextShort() 5. nextByte() 7. nextDouble()


2. nextInt() 4. nextLong() 6. nextBoolean() 8. nextFloat()

REFERENCE
1. Y. Daniel Liang: Intro to Java Programming, Comprehensive Version (10th Edition); Pearson Education, Inc.,: 2015
2. Barry Burd: Java for Dummies 5th Edition; Wiley Publishing Inc.,: 2011
3. J. Gosling, et. Al.: The Java Language Specification Java SE 7 th Edition: Oracle America Inc.,: 2011
4. https://www.geeksforgeeks.org/understanding-public-static-void-mainstring-args-in-java/

You might also like