0% found this document useful (0 votes)
75 views

Chapter 2 - Elementary Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
75 views

Chapter 2 - Elementary Programming

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 61

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:

1. Read in the circle’s radius.

2. Compute the area using the following formula:

area = radius * radius * p


• 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. The outline of the program would look like this:

public class ComputeArea {

// Details to be given later

}
As you know, every Java program must have a main method where program
execution begins. The program is then expanded as follows:

public class ComputeArea {

public static void main(String[] args) {

// Step 1: Read in radius

// Step 2: Compute area

// Step 3: Display the area

}
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"

• Use + to print a string and an expression's value together.


• System.out.println("Grade: " + (95.1 + 71.9) / 2);
• The plus sign (+) has two meanings: one for addition and the other for
concatenating (combining) strings.

• 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:

System.out.println("Introduction to Java Programming,

by Y. Daniel Liang");

• To fix the error, break the string into separate substrings, and use the
concatenation operator (+) to combine them:

System.out.println("Introduction to Java Programming, " +

"by Y. Daniel Liang");


Identify and fix the errors in the following code:
public class Test {

public void main(string[] args) {

double i = 50.0;

double k = i + 50.0;

double j = k + 1;

System.out.println("j is " + j + " and k is " + k);

}
Reading Input from the Console

Scanner input = new Scanner(System.in);

double radius = input.nextDouble();


ComputeAreaWithConsoleInput.java
import java.util.Scanner; // Scanner is in the java.util package
public class ComputeAreaWithConsoleInput {
public static void main(String[] args) {
// 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 * 3.14159;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
ComputeAverage.java
import java.util.Scanner; // Scanner is in the java.util package
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);
}
Identifiers
• Identifiers are the names that identify the elements such as classes,
methods, and variables in a program.
Variables
• variable: A piece of the computer's memory that is given a name and type, and
can store a value.
• Variables are used to represent values that may be changed in the program.
// compute the first operation
num1 = 20;
sum = num1 + 10;
System.out.println(sum);

// compute the second operation


num1 = 30;
sum = num1 + 10;
System.out.println(sum);
• 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
• If variables are of the same type, they can be declared together, as follows:
datatype variable1, variable2, ..., variablen;
The variables are separated by commas. For example,
int i, j, k; // Declare i, j, and k as int variables
• 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;
• This is equivalent to the next two statements:
int count;
count = 1;
• You can also use a shorthand form to declare and initialize variables of the same
type together. For example,
int i = 1, j = 2;
Tip

• A variable must be declared before it can be assigned a value. A variable declared


in a method must be assigned a value before it can be used. Whenever possible,
declare a variable and assign its initial value in one step. This will make the
program easy to read and avoid programming errors.
• Identify and fix the errors in the following code:
1 public class Test {
2 public static void main(String[] args) {
3 int i = k + 2;
4 System.out.println(i);
5 }
6 }
Expressions
• expression: A value or operation that computes a value.
• Examples: 1 + 4 * 5
(7 + 2) * 6 / 3
42
"Hello, world!"
• The simplest expression is a literal value.
• A complex expression can use operators and parentheses.
Assignment Statements and 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;
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

• 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 Test.

■ Capitalize every letter in a constant, and use underscores between words—for


example, the constants PI and MAX_VALUE.

• It is important to follow the naming conventions to make your programs easy to


read.
Reading Numbers from the Keyboard
• 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 to read a number of the byte, short, int, long, and float
type.
Methods for Scanner Objects
Method Description

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.


Here are examples for reading values of various types from the keyboard:
1 Scanner input = new Scanner(System.in);
2 System.out.print("Enter a byte value: ");
3 byte byteValue = input.nextByte();
5 System.out.print("Enter a short value: ");
6 short shortValue = input.nextShort();
8 System.out.print("Enter an int value: ");
9 int intValue = input.nextInt();
11 System.out.print("Enter a long value: ");
12 long longValue = input.nextLong();
14 System.out.print("Enter a float value: ");
15 float floatValue = input.nextFloat();
Numeric Operators

• The operators for numeric data types include the standard


arithmetic operators: addition (+), subtraction (–),
multiplication (*), division (/), and remainder (%), as shown in
Table 2.3. The operands are the values operated by an
operator.
Numeric Operators
Name Meaning Example Result

+ Addition 34 + 1 35

- Subtraction 34.0 – 0.1 33.9

* Multiplication 300 * 30 9000

/ Division 1.0 / 2.0 0.5

% 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();

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");
}
Evaluating Expressions and Operator Precedence
• precedence: Order in which operators are evaluated.
• Generally operators evaluate left-to-right.
1 - 2 - 3 is (1 - 2) - 3 which is -4

• But * / % have a higher level of precedence than + -


1 + 3 * 4 is 13

6 + 8 / 2 * 3
6 + 4 * 3
6 + 12is 18

• Parentheses can force a certain order of evaluation:


(1 + 3) * 4 is 16

• Spacing does not affect order of evaluation


• Java expressions are evaluated in the same way as arithmetic expressions.
Precedence questions
• What values result from the following expressions?
•9 / 5
• 695 % 20
•7 + 6 * 5
•7 * 6 + 5
• 248 % 100 / 5
•6 * 3 - 9 / 4
• (5 - 7) * 4
• 6 + (18 % (17 - 12))
Precedence examples
•1 * 2 + 3 * 5 % 4 •1 * 2 + 3 * 5 % 4
• \_/ • \_/
| |
2 + 3 * 5 % 4 2 + 3 * 5 % 4
• \_/ • \_/
| |
2 + 15 % 4 2 + 15 % 4
• \___/ • \___/
| |
2 + 3 2 + 3
• \________/ • \________/
| |
5 5
Real number example
• 2.0 * 2.4 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 2.25 * 4.0 / 2.0
• \___/
|
4.8 + 9.0 / 2.0
• \_____/
|
4.8 + 4.5
• \____________/
|
9.3
Mixing types
• When int and double are mixed, the result is a double.
• 4.2 * 3 is 12.6

• The conversion is per-operator, affecting only its operands.


• 7 / 3 * 1.2 + 3 / 2  2.5 + 10 / 3 * 2.5 - 6 / 4
• \_/  \___/
| |
2 * 1.2 + 3 / 2 2.5 + 3 * 2.5 - 6 / 4
 \_____/
• \___/
| |
2.4 + 3 / 2 2.5 + 7.5 - 6 / 4
 \_/
• \_/
| |
2.4 + 1 2.5 + 7.5 - 1
 \_________/
• \________/
| |
3.4 10.0 - 1
 \______________/
|
9.0 (not 9!)
• 3 / 2 is 1 above, not 1.5.
Augmented(increased) 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;
• 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;

• The += is called the addition assignment operator. Table 2.4 shows


other augmented assignment operators.
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


The augmented assignment operator is performed last after all the other
operators in the expression are evaluated. For example,

x /= 4 + 5.5 * 1.5;

is same as

x = x / (4 + 5.5 * 1.5);

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.
Increment and Decrement Operators
Operator Name Description Example (assume i = 1)

++var preincrement Increment var by 1, and use the int j = ++i;


new var value in the statement // j is 2, i is 2

var++ postincrement Increment var by 1, but use the int j = i++;


original var value in the statement // j is 1, i is 2

——var predecrement Decrement var by 1, and use the int j = ——i;


new var value in the statement // j is 0, i is 0

var—— postdecrement Decrement var by 1, and use the int j = i——;


original var value in the statement // j is 1, i is 0
• Here are additional examples to illustrate the differences between the prefix form
of ++ (or ——) and the postfix form of ++ (or −−). Consider the following code:

• In this case, i is incremented by 1, then the old value of i is used in the


• If i++ is replaced by ++i as follows,

• i is incremented by 1, and the new value of i is used in the multiplication. Thus


newNum becomes 110.
• Here is another example:
double x = 1.0;

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.

• Widening Conversion: Widening conversion happens automatically when you


assign a value of a smaller data type to a variable of a larger data type. This is also
known as implicit type casting. Java ensures that there is no data loss when you
perform a widening conversion.
• For example, assigning an int value to a long variable in Java:

int myIntValue = 42;

long myLongValue = myIntValue; // Widening 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:

double myDoubleValue = 3.14;

int myIntValue = (int) myDoubleValue; // Narrowing conversion


• In this example, the double value 3.14 is explicitly cast to an int value
using the (int) casting operator. The resulting int value will be 3, since
the decimal portion of the double value is truncated when it is cast to
an integer value.

• It is important to note that when you perform a narrowing conversion,


you should ensure that the value being converted will not exceed the
range of the destination data type. If the value being converted
exceeds the range of the destination data type, it will result in data loss
or an overflow exception.
Caution

• Casting is necessary if you are assigning a value to a variable of a smaller type


range, such as assigning a double value to an int variable. A compile error will
occur if casting is not used in situations of this kind. However, be careful when
using casting, as loss of information might lead to inaccurate results.

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 i = (int)d; // i becomes 4, but d is still 4.5


Note:- In Java, an augmented expression of the form x1 op= x2 is implemented as
x1 = (T)(x1 op x2), where T is the type for x1. Therefore, the following code is
correct.

int sum = 0;

sum += 4.5; // sum becomes 4 after this statement

sum += 4.5 is equivalent to sum = (int)(sum + 4.5).


Note
• To assign a variable of the int type to a variable of the short or byte type, explicit
casting must be used. For example, the following statements have a compile error:
int i = 1;
byte b = i; // Error because explicit casting is required
• Case Study: Counting Monetary Units

• 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");

• Write a println statement to produce this output:


/ \ // \\ /// \\\
Answers
• Output of each println statement:
a b c
\\
'
"""
C:
he is a student

• println statement to produce the line of output:


System.out.println("/ \\ // \\\\ /// \\\\\\");
Questions
• What println statements will generate this output?
This quote is from
Irish poet Oscar Wilde:

"Music makes one feel so romantic


- at least it always gets on one's nerves –
which is the same thing nowadays."

• What println statements will generate this output?


A "quoted" String is
'much' better if you learn
the rules of "escape sequences."

Also, "" represents an empty String.


Don't forget: use \" instead of " !
'' is not the same as "
Answers
• println statements to generate the output:
System.out.println("This quote is from");
System.out.println("Irish poet Oscar Wilde:”);
System.out.println();
System.out.println("\"Music makes one feel so romantic");
System.out.println("- at least it always gets on one's
nerves -");
System.out.println("which is the same thing nowadays.\"");
• println statements to generate the output:
System.out.println("A \"quoted\" String is");
System.out.println("'much' better if you learn");
System.out.println("the rules of \"escape sequences.\"");
System.out.println();
System.out.println("Also, \"\" represents an empty
String.");
System.out.println("Don't forget: use \\\" instead
of \" !");

You might also like