0% found this document useful (0 votes)
5 views66 pages

S2

Uploaded by

Dany Merhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views66 pages

S2

Uploaded by

Dany Merhej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 66

INTRODUCTION TO

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.

• The plus sign (+) in lines 13–14 is called a string concatenation


operator. It combines 2 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 (+) in lines 13–14 concatenate strings into a longer string, which
is then displayed in the output
3
The + operator
• 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");

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

• 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.
9
Some examples of variable declarations
• 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;

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;

• An assignment statement can be used as an expression in


Java.
x = y + 1; // Assign the addition of y and 1 to x
area = radius * radius * 3.14159; // Compute area

11
Declaring and Initializing
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

12
Named Constants
• A named constant is an identifier that represents a
permanent value.

• The syntax for declaring a constant is


final datatype CONSTANTNAME = VALUE;
Examples:
final double PI = 3.14159;
final int SIZE = 3;

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.

• Integers are stored precisely. Therefore, calculations with


integers yield a precise integer result.
19
Exponent Operations
• The Math.pow(a, b) method can be used to
compute 𝑎𝑏 .The pow method is defined in the
Math class in the Java API.
• Here a and b are parameters for the pow method
that receive the actual values used to invoke the
method. For example
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
20
Number Literals
• A literal is a constant value that appears directly in the
program.
For example, 34, 1000000, and 5.0 are literals in the
following statements:
int i = 34;
long x = 1000000;
double d = 5.0;
boolean result = true;
char capitalC = 'C';
byte b = 100;
short s = 10000;
int i = 100000;
21
Integer Literals
• An integer literal can be assigned to an integer variable as
long as it can fit into the variable.
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,


• To denote an integer literal of the long type, append it with
the letter L.
22
Floating-Point Literals
• Floating-point literals are written with a decimal point, For
example, 5.0
• By default, a floating-point literal is treated as a double
type value, not a float value.
• You can make a number a float by appending the letter f or
F, and make a number a double by appending the letter d
or D.
100.2f or 100.2F 100.2d or 100.2D

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

– Adjacent to a decimal point in a floating point literal


float pi1 = 3_.1415F;

– 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.

• The currentTimeMillis method in the System class returns


the current time in milliseconds since the midnight, January
1, 1970 GMT. (1970 was the year when the Unix operating
system was formally introduced.)

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

long k = i * 3 + 4; range increases

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

totalPayment = monthlyPayment × numberOfYears × 12 38


Problem: Computing Loan Payments

39
Problem: Computing Loan Payments

Run

40
Character Data Type
• In addition to processing numeric values, you can process
characters in Java.

• The character data type, char, is used to represent a single


character.

• A character literal is enclosed in single quotation marks.


Consider the following code:
char letter = 'A'; // assigns character A to the char variable
// letter
char numChar = '4'; // assigns digit character 4 to the char
// variable numChar

41
Character Data Type
• Caution

– A string literal must be enclosed in quotation marks (" ")

– A character literal is a single character enclosed in single


quotation marks (' ').

Therefore, "A" is a string, but 'A' is a character.

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:

both assign character A to the char variable letter.

Unicode \u03b1 \u03b2 \u03b3 for three Greek letters

𝛼 𝛽 𝛼

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.

• To overcome this problem, Java uses a special notation,


called an escape character, to represent special characters.
It consists of a backslash \ followed by a character or a
character sequence
System.out.println("He said \"Java is fun\"");

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

• When a floating-point value is cast into a char, the


floating-point value is first cast into an int, which is then
cast into a char.

• When a char is cast into a numeric type, the character’s


Unicode is cast into the specified numeric type:
49
Casting between char and Numeric Types
• Implicit casting can be used if the result of a casting fits
into the target variable. Otherwise, explicit casting must be
used.
For example, since the Unicode of 'a' is 97, which is within
the range of a byte, these implicit castings are fine

• The following casting is incorrect, because the Unicode


\uFFF4 cannot fit into a byte:

• To force this assignment, use explicit casting, as follows


50
Casting between char and Numeric Types
• All numeric operators can be applied to char operands.
1. A char operand is automatically cast into a number if the other
operand is a number.

2. If the other operand is a string, the character is concatenated


with the string.

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

• So the new message is "Welcome to Java and Java is fun".

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.

• To force i + j to be executed first, enclose i + j in the


parentheses, as follows:
System.out.println("i + j is " + ( i + j));

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.

• Alternatively, you can obtain input from an “input dialog


box” by invoking the method JOptionPane.showInputDialog.

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

2. JOptionPane.showInputDialog (null, x, y, JOptionPane.QUESTION_MESSAGE);


x is a string for the prompting message
y is a string for the title of the input dialogbox title

String input = JOptionPane.showInputDialog(null,"Enter a year:", “Example 2.2 Input (int)",


JOptionPane.QUESTION_MESSAGE); 61
Converting Strings to Integers
• The input returned from the input dialog box is a string. If you enter a
numeric value such as 123, it returns “123”. To obtain the input as a
number, you have to convert a string
into a number. 123

1. To convert a string into an int value, use Integer.parseInt


String intString = JOptionPane.showInputDialog("Enter an input");
Int intValue=Integer.parseInt(intString);
where intString is a numeric string such as 123.
2. To convert a string into double value, use Double.parseDouble
String doubleString = JOptionPane.showInputDialog("Enter an input");
double doubleValue=Double.parseDouble(doubleString);
where doubleString is a numeric string such as 123.45.
• The Integer and Double classes are both included in the java.lang
62
package, and thus they are automatically imported.
Problem: Computing Loan Payments Using Input
Dialogs
• Same as the preceding program, except that the input is entered
from the input dialogs the output is displayed in an output dialog.

63
Problem: Computing Loan Payments Using Input
Dialogs

Run
64
Additional reading
• Popular Java IDEs:
http://www.cs.armstrong.edu/liang/intro9e/idesupplement.html

1. NetBeans Open Source by Sun


2. Eclipse Open Source by IBM

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

You might also like