Chapter 2 - Elementary Programming
Chapter 2 - Elementary Programming
2.1 Introduction
• The focus of this chapter is on learning elementary
programming techniques to solve problems.
• In Chapter 1 you learned how to create, compile, and run very
basic Java programs. Now you will learn how to solve problems by
writing programs. Through these problems, you will learn
elementary programming using primitive data types, variables,
constants, operators, expressions, and input and output.
2.2 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. 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:
}
As you know, every Java program must have a main method where program
execution begins. The program is then expanded as follows:
}
LISTING 2.1 ComputeArea.java
1. public class ComputeArea {
2. public static void main(String[] args) {
3. double radius; // Declare radius
4. double area; // Declare area
5. // Assign a radius
6. radius = 20; // radius is now 20
7. // Compute area
8. area = radius * radius * 3.14159;
9. // Display results
10. System.out.println("The area for the circle of radius " + radius + " is " + area);
11. }
12. }
String concatenation
• string concatenation: Using + between a string and another value to make a
longer string.
"hello" + 42 is "hello42"
1 + "abc" + 2 is "1abc2"
"abc" + 1 + 2 is "abc12"
1 + 2 + "abc" is "3abc"
"abc" + 9 * 3 is "abc27"
"1" + 1 is "11"
4 - 1 + "abc" is "3abc"
• The plus sign (+) in lines 10 is called a string concatenation operator. It combines
two strings into one. If a string is combined with a number, the number is
converted into a string and concatenated with the other string.
• Therefore, the plus signs (+) concatenate strings into a longer string, which is
then displayed in the output.
Caution
• A string cannot cross lines in the source code. Thus, the following statement
would result in a compile error:
by Y. Daniel Liang");
• To fix the error, break the string into separate substrings, and use the
concatenation operator (+) to combine them:
double i = 50.0;
double k = i + 50.0;
double j = k + 1;
}
Reading Input from the Console
variable = expression;
int y = 1; // Assign 1 to variable y
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
Named Constants
• A named constant is an identifier that represents a permanent value.
final datatype CONSTANTNAME = value;
• A constant must be declared and initialized in the same statement.
ComputeAreaWithConstant.java
import java.util.Scanner; // Scanner is in the java.util System.out.print("Enter a number for radius: ");
package
double radius = input.nextDouble();
public class ComputeAreaWithConstant {
// Compute area
public static void main(String[] args) {
double area = radius * radius * PI;
final double PI = 3.14159; // Declare a // Display result
constant
System.out.println("The area for the circle of radius " +
// Create a Scanner object
radius + " is " + area);
Scanner input = new Scanner(System.in);
}
// Prompt the user to enter a radius
}
Naming Conventions
• Sticking with the Java naming conventions makes your programs easy to
read and avoids errors
■ Capitalize the first letter of each word in a class name—for example, the class
names ComputeArea and Test.
+ Addition 34 + 1 35
% Remainder 20 % 3 2
• The program obtains minutes and remaining seconds from an amount of time in seconds. For
example, 500 seconds contains 8 minutes and 20 seconds.
DisplayTime.java
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();
6 + 8 / 2 * 3
6 + 4 * 3
6 + 12is 18
• 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;
• Java allows you to combine assignment and addition operators using
an augmented (or compound) assignment operator. For example, the
preceding statement can be written as
count += 1;
-= Subtraction
assignment
i -= 8 i=i–8
*= Multiplication
assignment
i *= 8 i=i*8
x /= 4 + 5.5 * 1.5;
is same as
x = x / (4 + 5.5 * 1.5);
Caution
double y = 5.0;
double z = x– – + (++y);
• After all three lines are executed, y becomes 6.0, z becomes 7.0, and x
becomes 0.0.
Numeric Type Conversions
• Numeric type casting in Java is the process of converting a value of one numeric
data type to another. Java supports two types of numeric type casting: widening
conversion and narrowing conversion.
In this example, the int value 42 is automatically cast to a long value and
assigned to the variable myLongValue. The widening conversion happens
automatically, without the need for any explicit casting operator.
• Narrowing Conversion: Narrowing conversion is used when you need to convert a
value of a larger data type to a smaller data type. This is also known as explicit
type casting. Narrowing conversion can result in data loss or precision loss, so it
should be used with caution.
• In Java, you can perform a narrowing conversion by using a casting operator. For
example, to cast a double value to an int value:
Note:- Casting does not change the variable being cast. For example, d is not
changed after casting in the following code:
double d = 4.5;
int sum = 0;
• This section presents a program that breaks a large amount of money into smaller
units. Suppose you want to develop a program that changes a given amount of
money into smaller monetary units. The program lets the user enter an amount
as a double value representing a total in dollars and cents, and outputs a report
listing the monetary equivalent in the maximum number of dollars, quarters,
dimes, nickels, and pennies, in this order, to result in the minimum number of
coins.
Here are the steps in developing the program:
1. Prompt the user to enter the amount as a decimal number, such as 11.56.
2. Convert the amount (e.g., 11.56) into cents (1156).
3. Divide the cents by 100 to find the number of dollars. Obtain the remaining cents using
the cents remainder 100.
4. Divide the remaining cents by 25 to find the number of quarters. Obtain the remaining
cents using the remaining cents remainder 25.
5. Divide the remaining cents by 10 to find the number of dimes. Obtain the remaining
cents using the remaining cents remainder 10.
6. Divide the remaining cents by 5 to find the number of nickels. Obtain the remaining
cents using the remaining cents remainder 5.
7. The remaining cents are the pennies.
8. Display the result.
Strings and escape
sequences
Strings
• String: A sequence of text characters.
• Starts and ends with a " (quotation mark character).
• The quotes do not appear in the output.
• Examples:
"hello"
"This is a string. It's very long!“
String a = "hello";
System.out.println(a);
• Restrictions:
• May not span multiple lines.
"This is not
a legal String."
• May not contain a " character.
"This is not a "legal" String either."
Escape sequences
• escape sequence: A special sequence of characters used to
represent certain special characters in a string.
\t tab character
\n new line character
\" quotation mark character
\\ backslash character
• Example:
System.out.println("\\hello\nhow\
tare \"you\"?\\\\");
• Output:
\hello
how are "you"?\\
Questions
• What is the output of the following println statements?
System.out.println("\ta\tb\tc");
System.out.println("\\\\");
System.out.println("'");
System.out.println("\"\"\"");
System.out.println("C:\nhe\ is a student");