02-Elementary Programming
02-Elementary Programming
COM 116
Elementary Programming
2
Last Lecture we have
■ Previous lecture, we learned the components of Java program. We
write a program, compile and run it. You learned difference of two
statements;
• System.out.println("5+7");
• System.out.println(5+7);
■ Yes, the first one prints character data (or string) and the second
prints numeric data.
3
Motivations
■ In the preceding lecture, you learned how to create, compile, and
run a Java program.
■ Starting from this chapter, you will learn how to solve practical
problems programmatically. Through these problems, you will learn
Java primitive data types and related subjects, such as variables,
constants, data types, operators, expressions, and input and
output.
4
Anatomy of a Java Program
■ Class name
■ Main method
■ Statements
■ Statement terminator
■ Reserved words
■ Comments
■ Blocks
5
Escape Sequences
In System.out.print statement, it can be used escape sequences.
6
Escape Sequences
■ What if we wanted to print a double quote character?
■ The following line would confuse the compiler because it would interpret
the second quote as the end of the string
System.out.println ("I said "Hello" to you.");
7
Let’s Write a Simple Program
■ First, we should solve the problem simply.
■ The solution, we name it as an algorithm.
■ Lastly, we code the algorithm in programming language.
8
Let’s Write a Simple Program
■ Algorithm is a plan for programmer in order to code.
■ Let’s code a simple program that computes area of circle.
9
Let’s Write a Simple Program
■ PROBLEM: Read radius and compute area of circle.
■ ALGORITHM of area of circle:
1. Read radius
2. Compute area using the formulas:
alan = yarıçap x yarıçap x p
3. Print the result
10
Let’s Write a Simple Program
public class ComputeArea {
11
Let’s Write a Simple Program
public class ComputeArea
{
public static void main(String[] args)
{
// 1. Assign a value to radius
12
Let’s Write a Simple Program
public class ComputeArea
{
public static void main(String[] args)
{
double radius;
double area;
// 1. Assign a value to radius
radius=20;
area=radius*radius*3.14159;
13
Let’s Write a Simple Program
This program computes the area of the circle.
ComputeArea Note: Clicking the green button displays the source code
with interactive animation. You can also run the code in
a browser. Internet connection is needed for this button.
Run
Note: Clicking the blue button runs the code from
Windows. If you cannot run the buttons, see
IMPORTANT NOTE: If you cannot run the buttons, see
liveexample.pearsoncmg.com/slide/javaslidenote.doc.
14
Trace a Program Execution allocate memory for
public class ComputeArea { radius
/** Main method */
public static void main(String[] args) { radius no value
double radius;
double area;
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
15
Trace a Program Execution
public class ComputeArea { memory
/** Main method */
public static void main(String[] args) { radius no value
double radius;
double area;
area no value
// Assign a radius
radius = 20;
allocate memory
// Compute area
for area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
16
Trace a Program Execution
assign 20 to radius
public class ComputeArea {
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area no value
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
17
Trace a Program Execution
public class ComputeArea { memory
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and
// Compute area
assign it to variable area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
18
Trace a Program Execution
public class ComputeArea { memory
/** Main method */
public static void main(String[] args) { radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
// Compute area
area = radius * radius * 3.14159; print a message to the
console
// Display results
System.out.println("The area for the circle of radius " + radius + " is " + area);
}
}
19
Compute Area of Circle with Different Radius Values
■ Let’s learn how to read data from console now.
20
Reading a Value from Console
1. Create a Scanner object.
■ Scanner input = new Scanner(System.in);
ComputeAreaWithConsoleInput Run
▪ double d = input.nextDouble();
ComputeAverage Run
21
Implicit Import and Explicit Import
No difference.
22
Let’s Write a Simple Program
import java.util.Scanner;
public class ComputeArea {
Please enter radius of circle:
public static void main(String[] args) { 20
double radius;
double area; Radius of circle : 20.0 and area: 1256.636
// 1. Read radius
System.out.println("Please enter radius of circle: ");
Scanner input = new Scanner(System.in);
radius = input.nextDouble();
// 3. Print result
System.out.println("Radius of circle : " + radius + " and area: " + area);
}
}
23
System.out.println()
• System.out.println("Radius of circle
: " + radius + " and area: " + area);
• We use + operator when printing a message:
• (+) operator has two meaning: It merges character data. Performs
addition operation with numeric data.
• If used both character and numeric data while printing, the
numeric data is converted into character data.
24
Variables
• What is a variable?
• The name of some location of memory used to hold a data value
• Different types of data require different amounts of memory. The compiler’s job is to reserve sufficient
memory
• Variables need to be declared once
• Variables are assigned values, and these values may be changed later
• Each variable has a type, and operations can only be performed between compatible types
3 width
4 height
• Example 12 area
int width = 3;
int height = 4;
int area = width * height;
6 3 width
width = 6;
area = width * height; 4 height
24 12 area
25
Java Data Types
primitive reference
26
Primitive and Reference Types
char letter;
String title;
letter
String book;
letter = ‘J’;
book = title;
27
Primitive and Reference Types
char letter;
String title;
letter
String book;
title
letter = ‘J’;
book = title;
28
Primitive and Reference Types
char letter;
String title;
letter
String book;
title
letter = ‘J’;
29
Primitive and Reference Types
char letter;
String title;
letter ‘J’
String book;
title
letter = ‘J’;
30
Declaring (Creating) Variables
■ To create a variable, you must specify the type and assign it a
value:
Syntax
type variable = value;
32
Variables
//Compute the first area
radius = 1.0;
area = radius * radius * 3.14159;
System.out.println(“The area is : " + area + " for radius “+ radius);
33
Attention
■ Java is case sensitive. Therefore, the variables shown below are
different from each other.
■ int carpimdegeri;
■ int carpimDegeri;
■ int carPimdeGeri;
34
Declaring Variables
int x; // Declare x to be an
// integer variable;
char a; // Declare a to be a
// character variable;
35
Assignment Statements
x= 1; // Assign 1 to x
radius = 1.0; // Assign 1.0 to radius
a = ‘A'; // Assign 'A' to a
36
Declaring and Initializing in One Step
int x = 1;
double d = 1.4;
37
Named Constants
In order to define a named constant, we put final keyword in front of
variable.
General usage:
final datatype CONSTANTNAME = VALUE;
Examples:
final double PI = 3.14159;
final int SIZE = 3;
38
Naming Conventions
■ Choose meaningful and descriptive names.
■ Variables and method names:
■ Use lowercase. If the name consists of several words,
concatenate all in one, use lowercase for the first word, and
capitalize the first letter of each subsequent word in the name.
For example, the variables radius and area, and the method
computeArea.
39
Naming Conventions
■ Class names:
■ Capitalize the first letter of each word in the name. For example, the class name
ComputeArea.
■ Constants:
■ Capitalize all letters in constants, and use underscores to connect words. For example,
40
Numerical Data Types
41
Sizes of Integral Java Types
byte 8 bits
short 16 bits
int 32 bits
long 64 bits
42
Reading Numbers from the Keyboard
Scanner input = new Scanner(System.in);
int value = input.nextInt();
43
Numeric Operators
44
Integer Division
■ +, -, *, /, and %
■ 5 / 2 yields an integer 2.
45
Remainder Operator
Remainder is very useful in programming. For example, an even number % 2 is always
0 and an odd number % 2 is always 1. So you can use this property to determine
whether a number is even or odd. Suppose today is Saturday and you and your
friends are going to meet in 10 days. What day is in 10 days? You can find that
day is Tuesday using the following expression:
46
ATTENTION
■ 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.
47
Exponent Operations
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
In next chapter, we will learn it more.
48
Number Literals
■ A literal is a constant value that appears directly in the program.
For example, 34, 1,000,000, and 5.0 are literals in the following
statements:
int i = 34;
long x = 1000000;
double d = 5.0;
49
Integer Literals
■ An integer literal can be assigned to an integer variable as long as it can fit
into the variable. A compilation error would occur if the literal were too large
for the variable to hold. For example, the statement byte b = 1000 would
cause a compilation error, because 1000 cannot be stored in a variable of the
byte type.
■ An integer literal is assumed to be of the int type, whose value is between -
231 (-2147483648) to 231–1 (2147483647). To denote an integer literal of the
long type, append it with the letter L or l. L is preferred because l (lowercase
L) can easily be confused with 1 (the digit one).
50
Floating-Point Literals
■ There are two types;
■ Float, Example 100.2f or 100.2F
51
double vs. float
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);
52
Scientific Notation
■ Floating-point literals can also be specified in scientific notation, for
example, 1.23456e+2, same as 1.23456e2, is equivalent to 123.456, and
1.23456e-2 is equivalent to 0.0123456. E (or e) represents an exponent
and it can be either in lowercase or uppercase.
53
Arithmetic Expressions
is translated into:
54
How to Evaluate an Expression
■ Though Java has its own way to evaluate an expression behind the
scene, the result of a Java expression and its corresponding
arithmetic expression are the same. Therefore, you can safely apply
the arithmetic rule for evaluating a Java expression.
55
Augmented Assignment Operators
56
Increment and Decrement Operators
57
Increment and Decrement Operators
58
Increment and Decrement Operators
■ Using increment and decrement operators makes expressions
short, but it also makes them complex and difficult to read. Avoid
using these operators in expressions that modify multiple variables,
or the same variable for multiple times such as this: int k = ++i + i.
59
Assignment Expressions and Assignment Statements
■Prior to Java 2, all the expressions can be used as statements. Since Java 2,
only the following types of expressions can be statements:
■ variable op= expression; // Where op is +, -, *, /, or %
■ ++variable;
■ variable++;
■—variable;
■variable--;
60
Numeric Type Conversion
■ Consider the following statements:
■ byte i = 100;
■ long k = i * 3 + 4;
■ double d = i * 3.1 + k / 2;
61
Conversion Rules
■ When performing a binary operation involving two operands of
different types, Java automatically converts the operand based on
the following rules:
62
Type Casting
Implicit casting
double d = 3; (type widening)
Explicit casting
int i = (int)3.0; (type narrowing)
int i = (int)3.9; (Fraction part is truncated)
63
Data Conversion
64
Data Conversions
■ Sometimes it is convenient to convert data from one type to another
■ For example, we may want to treat an integer as a floating point value
during a computation
■ Conversions must be handled carefully to avoid losing information
■ Widening conversions are safest because they tend to go from a small data
type to a larger one (such as a short to an int)
■ Narrowing conversions can lose information because they tend to go from a
large data type to a smaller one (such as an int to a short)
65
Data Conversions
■ In Java, data conversions can occur in three ways:
■ assignment conversion
■ arithmetic promotion
■ casting
■ Assignment conversion occurs when a value of one type is assigned to a
variable of another
■ Only widening conversions can happen via assignment
■ Arithmetic promotion happens automatically when operators in
expressions convert their operands
66
Data Conversions
■ Casting is the most powerful, and dangerous, technique for
conversion
■ Both widening and narrowing conversions can be accomplished by
explicitly casting a value
■ To cast, the type is put in parentheses in front of the value being
converted
■ For example, if total and count are integers, but we want a
floating point result when dividing them, we can cast total:
result = (float) total / count;
67
Casting in an Augmented Expression
• 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
68
Common Errors and Pitfalls
■ Common Error 1: Undeclared/Uninitialized Variables and Unused
Variables
■ Common Error 2: Integer Overflow
■ Common Error 3: Round-off Errors
■ Common Error 4: Unintended Integer Division
■ Common Error 5: Redundant Input Objects
69
Common Error 1: Undeclared/Uninitialized Variables and Unused
Variables
70
Common Error 2: Integer Overflow
int value = 2147483647 + 1;
// value will actually be -2147483648
71
Common Error 3: Round-off Errors
System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1);
System.out.println(1.0 - 0.9);
72
Common Error 4: Unintended Integer Division
73
Common Pitfall 1: Redundant Input Objects
Scanner input = new Scanner(System.in);
System.out.print("Enter an integer: ");
int v1 = input.nextInt();
74
Homework
• Read 2 numeric data for arithmetic operations below. Do
the division, output to the console.
Example:
Enter 2 integers: 100 20
Multiplication of integers is : 5
75
Summary
• As a result, we learned variables. We get input and store it
in variables.
• We can calculate simple formulas.
• We learned data types.
• Next week, we will continue.
• Study the Chapter from your textbook. Run Java programs
through your Internet browser.
• Happy programming!
76