Chapter Two Java Basic
Chapter Two Java Basic
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. An algorithm describes how a problem is solved by listing the actions
that need to be taken and the order of their execution. Algorithms 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 = radius * radius * pi
3. Display the result.
When you code—that is, when you write a program—you translate an algorithm into a program.
You already know that 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.
E Java program must have a main method where program execution begins.
The program needs to read the radius entered by the user from the keyboard. This raises two
important issues:
Reading the radius.
Storing the radius in the program.
Let’s address the second issue first. In order to store the radius, the program needs to declare a
symbol called a variable. A variable represents a value stored in the computer’s memory.
Rather than using x and y as variable names, choose descriptive names: in this case, radius for
radius, and area for area. To let the compiler know what radius and area are, specify their data
types. That is the kind of data stored in a variable, whether integer, real number, or something else.
This is known as declaring variables. Java provides simple data types for representing integers,
real numbers, characters, and Boolean types. These types are known as primitive data types or
fundamental types.
Page 1 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
Reading input from the console enables the program to accept input from the user.
In 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.
Java uses System.out to refer to the standard output device and System.in to the standard input
device. By default, the output device is the display monitor and the input device is the keyboard.
To perform console output, you simply use the println method to display a primitive value or a
string to the console. Console input is not directly supported in Java, but you can use the Scanner
class to create an object to read input from System.in, as follows:
Scanner input = new Scanner(System.in);
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. 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:
double radius = input.nextDouble();
This statement reads a number from the keyboard and assigns the number to radius.
Page 2 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
The Scanner class is in the java.util package. There are two types of import statements: specific
import and wildcard import. The specific import specifies a single class in the import statement.
For example, the following statement imports Scanner from the package java.util.
Import java.util.Scanner;
The wildcard import imports all the classes in a package by using the asterisk as the wildcard. For
example, the following statement imports all the classes from the package java.util.
import java.uitl.*;
Identifiers
Identifiers are the names that identify the elements such as classes, methods, and variables in a
program.
As you see in example 2, area and radius 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.
An identifier cannot be true, false, or null.
Page 3 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
Variables are used to represent values that may be changed in the program. Variables are used to
store values to be used later in a program. They are called variables because their values can be
changed.
In the program in example 2, radius and area are variables of the double type. You can assign
any numerical value to radius and area, and the values of radius and area can be reassigned.
Variables are for representing data of a certain type. To use a variable, you declare it by telling the
compiler its name as well as what type of data it can store. The variable declaration tells the
compiler to allocate appropriate memory space for the variable based on its data type.
The syntax for declaring a variable is
datatype variableName;
Here are some examples of variable declarations:
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
Assignment Statements and Assignment Expressions
An assignment statement designates a value for a variable. An assignment statement can be used
as an expression in Java.
After a variable is declared, you can assign a value to it by using an assignment statement. In Java,
the equal sign (=) is used as the assignment operator. The syntax for assignment statements is as
follows: variable = expression;
An expression represents a computation involving values, variables, and operators that, taking
them together, evaluates to a value. For example, consider the following code:
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
Page 4 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
Named Constants
A named constant is an identifier that represents a permanent value. The value of a variable may
change during the execution of a program, but a named constant,or simply constant, represents
permanent data that never changes. Here is the syntax for declaring a constant:
final datatype CONSTANTNAME = value;
A constant must be declared and initialized in the same statement. The word final is a Java
keyword for declaring a constant.
Naming Conventions
Sticking with the Java naming conventions makes your programs easy to read and avoids errors.
Make sure that you choose descriptive names with straightforward meanings for the variables,
constants, classes, and methods in your program. As mentioned earlier, names are case sensitive.
Listed below are the conventions for naming variables, methods, and classes.
Use lowercase for variables and methods. If a name consists of several words, concatenate
them into one, making the first word lowercase and capitalizing the first letter of each
subsequent word—for example, the variables radius and area and the method print.
Capitalize the first letter of each word in a class name—for example, the class names
ComputeArea and System.
Capitalize every letter in a constant, and use underscores between words—for example, the
constants PI and MAX_VALUE.
Numeric Data Types
Java has six numeric types for integers and floating-point numbers with operators +, -, *, /, and
%.
Numeric Types
Every data type has a range of values. The compiler allocates memory space for each variable or
constant according to its data type. Java provides eight primitive data types for numeric values,
characters, and Boolean values. This section introduces numeric data types and operators.
Java uses four types for integers: byte, short, int, and long and two types for floating-point
numbers: float and double.
Reading Numbers from the Keyboard
Page 5 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
You know how to use the nextDouble() method in the Scanner class to read a double value
from the keyboard. You can also use the methods listed in Table belowto read a number of the
byte, short, int, long, and float type.
nextByte() reads an integer of the byte type.
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.
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;
Increment and Decrement Operators
The increment operator (++) and decrement operator (– –) are for incrementing and
decrementing a variable by 1.
The ++ and —— are two shorthand operators for incrementing and decrementing a variable by 1.
These are handy because that’s often how much the value needs to be changed in many
programming tasks. For example, the following code increments i by 1 and decrements j by 1.
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
Page 6 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
As you see, the effect of i++ and ++i or i—and --i are the same in the preceding examples.
However, their effects are different when they are used in statements that do more than just
increment and decrement.
Page 7 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
A program that converts a Fahrenheit degree to Celsius using the formula celsius = (5/9
)(fahrenheit - 32).
Page 8 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
Page 9 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
if (radius >= 0) {
area = radius * radius * PI;
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
The block braces can be omitted if they enclose a single statement. For example, the following
statements are equivalent.
Two-Way if-else Statements : An if-else statement decides the execution path based on whether
the condition is true or false.
A one-way if statement performs an action if the specified condition is true. If the condition is
false, nothing is done. But what if you want to take alternative actions when the condition is false?
You can use a two-way if-else statement. The actions that a two-way if-else statement specifies
differ based on whether the condition is true or false. Here is the syntax for a two-way if-else
statement:
if (boolean-expression) {
statement(s)-for-the-true-case;
}
else {
statement(s)-for-the-false-case;
}
Nested if and Multi-Way if-else Statements: An if statement can be inside another if statement to
form a nested if statement. For example, the following is a nested if statement:
if (i > k) {
if (j > k)
System.out.println("i and j are greater than k");
}
else
Page 10 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
2. Switch statement
A switch statement executes statements based on the value of a variable or an expression. Overuse
of nested if statements makes a program difficult to read. Java provides a switch statement to
simplify coding for multiple conditions.
This statement checks to see whether the status matches the value 0, 1, 2, or 3, in that order. If
matched, the corresponding tax is computed; if not matched, a message is displayed.
Here is the full syntax for the switch statement:
Page 11 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
Page 12 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
So, how do you solve this problem? Java provides a powerful construct called a loop that controls
how many times an operation or a sequence of operations is performed in succession. Using a loop
statement, you simply tell the computer to display a string a hundred times without having to code
the print statement a hundred times.
Loops are constructs that control repeated executions of a block of statements. The concept of
looping is fundamental to programming. Java provides three types of loop statements: while loops,
do-while loops, and for loops.
The while Loop
A while loop executes statements repeatedly while the condition is true.
The syntax for the while loop is:
The part of the loop that contains the statements to be repeated is called the loop body. A one-time
execution of a loop body is referred to as an iteration (or repetition) of the loop. Each loop contains
Page 13 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
In this example, you know exactly how many times the loop body needs to be executed because
the control variable count is used to count the number of executions. This type of loop is known
as a counter-controlled loop.
The do-while Loop
A do-while loop is the same as a while loop except that it executes the loop body first and then
checks the loop continuation condition. The do-while loop is a variation of the while loop. Its
syntax is:
do {
// Loop body;
Statement(s);
} while (loop-continuation-condition);
The loop body is executed first, and then the loop-continuation-condition is evaluated. If the
evaluation is true, the loop body is executed again; if it is false, the do-while loop terminates.
The difference between a while loop and a do-while loop is the order in which the loop-
continuation-condition is evaluated and the loop body executed. You can write a loop using
either the while loop or the do-while loop.
Page 14 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
A for loop generally uses a variable to control how many times the loop body is executed and when
the loop terminates. This variable is referred to as a control variable. The initialaction often
initializes a control variable, the action-after-each-iteration usually increments or decrements the
control variable, and the loop-continuation-condition tests whether the control variable has reached
a termination value. For example, the following for loop prints Welcome to Java! a hundred times:
Page 15 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
You can use a for loop, a while loop, or a do-while loop, whichever is convenient. The while loop
and for loop are called pretest loops because the continuation condition is checked before the loop
body is executed. The do-while loop is called a posttest loop because the condition is checked after
the loop body is executed. The three forms of loop statements—while, do-while, and for—are
expressively equivalent; that is, you can write a loop in any of these three forms.
Jumping Statement
Break Statement
Break statement is one of the several control statements Java provide to control the flow of the
program. As the name says, Break Statement is generally used to break the loop of switch
statement. Please note that Java does not provide Go To statement like other programming
languages e.g. C, C++.
Break statement has two forms labeled and unlabeled.
Unlabeled Break statement
This form of break statement is used to jump out of the loop when specific condition occurs. This
form of break statement is also used in switch statement.
public class test{
public static void main(String args[])
{
for(int var =0; var < 5 ; var++)
{
System.out.println("Var is : " + var);
if(var == 3)
break;
}
}
}
In above break statement example, control will jump out of loop when var becomes 3.
Labeled Break Statement
Page 16 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
The unlabeled version of the break statement is used when we want to jump out of a single loop
or single case in switch statement. Labeled version of the break statement is used when we want
to jump out of nested or multiple loops.
For example,
public class test{
public static void main(String args[])
{
Outer:
for(int var1=0; var1 < 5 ; var1++)
{
for(int var2 = 1; var2 < 5; var2++)
{
System.out.println("var1:" + var1 + ", var2:" + var2);
if(var1 == 3)
break Outer;
}
}
}
}
Continue Statement
Continue statement is used when we want to skip the rest of the statement in the body of the loop
and continue with the next iteration of the loop.
There are two forms of continue statement in Java.
1. Unlabeled Continue Statement
2. Labeled Continue Statement
Unlabeled Continue Statement
This form of statement causes skips the current iteration of innermost for, while or do while loop.
For example,
public class test{
public static void main(String args[])
{
for(int var1 =0; var1 < 5 ; var1++)
{
if(var1 == 2)
continue;
Page 17 of 18
UoG, CNCS, Computer Science Department: Object Oriented programming | By: Abebe Alemu
System.out.println("var1:" + var1 );
}
}
}
In above example, when var2 becomes 2, the rest of the inner for loop body will be skipped.
Labeled continue statement skips the current iteration of the loop marked with the specified
label. This form is used with nested loops.
For example,
}
}
}
}
Page 18 of 18