S2
S2
JAVA PROGRAMMING
Chapter 2: Elementary Programming in java1
Writing a Simple Program
Run
2
The + operator
• The plus sign (+) has two meanings: one for addition and the other
for concatenating (combining) strings.
4
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use
• Example
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble(); 5
Reading Input from the Console
Run
6
Reading Input from the Console
Run 7
Identifiers
• An identifier is a sequence of characters that consist of
letters, digits, underscores _, and dollar signs $.
• Identifiers are for naming variables, constants, methods,
classes, and packages. Descriptive identifiers make
programs easy to read
• 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, “Java Keywords,” for a list of
reserved words).
• An identifier cannot be true, false or null
• An identifier can be of any length.
• Since Java is case sensitive, area, Area, and AREA are all
8
different identifiers
Variables
int x; // Declare x to be an
// integer variable;
double radius; // Declare radius to
// be a double variable;
char a; // Declare a to be a
// character variable; 10
Assignment Statements
• An assignment statement designates a value for a variable.
x = 1; // Assign 1 to x;
radius = 1.0; // Assign 1.0 to radius;
a = 'A'; // Assign 'A' to a;
11
Declaring and Initializing
int y = 1; // Assign 1 to variable y
12
Named Constants
• A named constant is an identifier that represents a
permanent value.
13
Naming Conventions
• Use lowercase for variables and methods. If a name
consists of several words, concatenate them into one,
making the 1st word lowercase and capitalizing 1st first
letter of each subsequent word—for example, the variables
radius and area and the method showMessageDialog.
• Capitalize the first letter of each word in a class name—for
example, the class names ComputeArea, System, and
JOptionPane.
• Capitalize every letter in a constant, and use underscores
between words — for example, the constants PI and
MAX_VALUE. 14
Numeric Data Types
• Java has six numeric types for integers and floating-
point numbers with operators +, -, *, /, and %.
15
Numeric Data Operations
16
Integer Division
5 / 2 yields an integer 2.
5.0 / 2 yields a double value 2.5
5 % 2 yields 1
(the remainder of the division)
17
Problem: Displaying Time
• Write a program that obtains minutes from seconds
Run 18
NOTE
• 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.
23
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.
24
Using Underscore Characters in Numeric Literals
• In Java SE 7 and later, any number of underscore characters
(_) can appear anywhere between digits in a numerical
literal. This feature improves the readability of your code.
For example:
long creditCardNumber = 1234_5678_9012_3456L;
long socialSecurityNumber = 999_99_9999L;
float pi = 3.14_15F;
long hexBytes = 0xFF_EC_DE_5E;
long hexWords = 0xCAFE_BABE;
long maxLong = 0x7fff_ffff_ffff_ffffL;
byte nybbles = 0b0010_0101;
long bytes = 0b11010010_01101001_10010100_10010010;
25
Using Underscore Characters in Numeric Literals
• You can place underscores only between digits;
• You cannot place underscores in the following places:
– At the beginning or end of a number
int x1 = _52; // This is an identifier, not a numeric literal
– Prior to an F or L suffix
long socialSecurityNumber1 = 999_99_9999_L;
int x5 = 0_x52; // Invalid: cannot put underscores in the 0x radix prefix
http://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html
26
How to Evaluate an Expression
• you can safely apply the arithmetic rule for evaluating a
Java expression
3 + 4 * 4 + 5 * (4 + 3) - 1
(1) inside parentheses first
3 + 4 * 4 + 5 * 7 – 1
(2) multiplication
3 + 16 + 5 * 7 – 1
(3) multiplication
3 + 16 + 35 – 1
(4) addition
19 + 35 – 1
(5) addition
54 - 1
(6) subtraction
53
27
Problem: Converting Temperatures
• Write a program that converts a Fahrenheit degree to
Celsius using the formula:
5
𝑐𝑒𝑙𝑠𝑖𝑢𝑠 = 𝑓𝑎ℎ𝑟𝑒𝑛ℎ𝑒𝑖𝑡 − 32
9
Run28
Problem: Displaying Current Time
• Write a program that displays current time in GMT in the
format hour:minute:second such as 1:45:19.
29
Problem: Displaying Current Time
Run 30
Augmented Assignment Operators
31
Increment and Decrement Operators
32
Increment and Decrement Operators
33
Numeric Type Conversion -Conversion Rules
• Consider the following statements:
byte i = 100; byte, short, int, long, float, double
double d = i * 3.1 + k / 2;
• When performing a binary operation involving 2 operands
of different types, Java automatically converts the operand
based on the following rules:
1. If one of the operands is double, the other is converted into double.
2. Otherwise, if one of the operands is float, the other is converted into
float.
3. Otherwise, if one of the operands is long, the other is converted into
long.
4. Otherwise, both operands are converted into int. 34
Type Casting
• You can always assign a value to a numeric variable whose type
supports a larger range of values;
• You cannot, however, assign a value to a variable of a type with a
smaller range unless you use type casting.
• Casting is an operation that converts a value of one data type into a
value of another data type.
• Casting a type with a small range to a type with a larger range is
known as widening a type.
• Casting a type with a large range to a type with a smaller range is
known as narrowing a type.
• Java will automatically widen a type, but you must narrow a type
explicitly. byte, short, int, long, float, double
range increases
35
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)
• What is wrong?
int x = 5 / 2.0; byte, short, int, long, float, double
range increases
36
Problem: Keeping Two Digits After Decimal Points
• Write a program that displays the sales tax of 6% with two
digits after the decimal point.
Run37
Problem: Computing Loan Payments
• This program lets the user enter
1. the annual interest rate,
2. number of years,
3. and loan amount
and computes
1. monthly payment.
2. total payment.
loanAmount × monthlyInterestRate
monthlyPayment =
1
1−
1 + monthlyInterestRate numberOfYears×12
39
Problem: Computing Loan Payments
Run
40
Character Data Type
• In addition to processing numeric values, you can process
characters in Java.
41
Character Data Type
• Caution
42
Character Data Type : Ascii - Unicode
• Java supports Unicode, an encoding scheme established by
the Unicode Consortium to support the interchange,
processing, and display of written texts in the world’s
diverse languages.
• A 16-bit Unicode takes 2 bytes. It is written in four
hexadecimal digits preceded by \u, that run from \u0000 to
\uFFFF.
• Most computers use ASCII (American Standard Code for
Information Interchange), a 7-bit encoding scheme for
representing all uppercase and lowercase letters, digits,
punctuation marks, and control characters.
• Unicode includes ASCII code, with \u0000 to \u007F
43
corresponding to the 128 ASCII characters.
Character Data Type : Ascii - Unicode
• You can use ASCII characters such as 'X', '1', and '$' in a
Java program as well as Unicodes.
• For example, the following statements are equivalent:
𝛼 𝛽 𝛼
44
Appendix B: ASCII Character Set
• ASCII Character set is a subset of the Unicode from \u0000
to \u007f
45
Appendix B: ASCII Character Set
• ASCII Character set is a subset of the Unicode from \u0000
to \u007f
46
Escape Characters
• System.out.println("He said "Java is fun"");
Compile error: the compiler thinks the 2nd quotation
character is the end of the string and does not know what
to do with the rest of the characters.
47
Escape Characters
48
Casting between char and Numeric Types
• A char can be cast into any numeric type, and vice versa.
• When an integer is cast into a char, only its lower 16 bits of
data are used; the other part is ignored. For ex.:
51
Problem: Monetary Units
• This program lets the user enter the amount in decimal
representing dollars and cents and output a report listing
the monetary equivalent in:
1. single dollars,
2. quarters (25 cents) ,
3. dimes (10 cents),
4. nickels (5 cents),
5. and pennies (1 cent).
Your program should report maximum number of dollars,
then the maximum number of quarters, and so on, in this
order.
52
Problem: Monetary Units
53
Problem: Monetary Units
Run
54
The String Type
• A string is a sequence of characters. To represent a string of
characters, use the data type called “String”.
String message = "Welcome to Java";
• String is a predefined class in the Java library, just like the classes
System, JOptionPane, and Scanner.
• The String type is not a primitive type. It is a reference type. Any
Java class can be used as a reference type for a variable.
• Reference data types will be discussed in Chap 8, Objects and Classes.
All you need to know now is
– how to declare a String variable,
– how to assign a string to the variable,
– and how to concatenate strings.
55
String Concatenation
56
String Concatenation
• If i = 1 and j = 2, what is the output of the following
statement?
System.out.println("i + j is " + i + j);
The output is "i + j is 12" because "i + j is " is concatenated
with the value of i first.
57
Reading a string from the console
• To read a string from the console, invoke the next() method
on a Scanner object.
• The following example reads 3 strings from the keyboard
58
The String Type: whitespace characters
• The next() method reads a string that ends with a
whitespace character. The characters ' ', \t, \f, \r, or \n are
known as whitespace characters.
• You can use the nextLine() method to read an entire line of
text. The nextLine() method reads a string that ends with
the Enter key pressed. For example, the following
statements read a line of text.
59
Getting Input from Input Dialogs
• You can obtain input from the console.
60
Getting Input from Input Dialogs
• There are several ways to use the showInputDialog
method.
1. JOptionPane.showInputDialog(x);
where x is a string for the prompting message
String input = JOptionPane.showInputDialog("Enter an input");
63
Problem: Computing Loan Payments Using Input
Dialogs
Run
64
Additional reading
• Popular Java IDEs:
http://www.cs.armstrong.edu/liang/intro9e/idesupplement.html
65
Homework
• Study all materials in chapter 2 from the textbook
• Do ( preferably using eclipse) exercises:
2.1, 2.6, 2.8, 2.14, 2.15, 2.17, 2.26
from chapter 2
• Make a power point presentation and run the
solutions for your exercise from within the slides.
66