131
Chapter 2 Java Fundamentals 1

Chapter 2 Java Fundamentals

  • Upload
    urbano

  • View
    92

  • Download
    4

Embed Size (px)

DESCRIPTION

Chapter 2 Java Fundamentals. Contents. The Parts of a Java Program The print and println Methods, and the Java API Variables and Literals Primitive Data Types Arithmetic Operators Combined Assignment Operators Conversion between Primitive Types Creating Named Constraints with final. - PowerPoint PPT Presentation

Citation preview

Page 1: Chapter 2 Java Fundamentals

1

Chapter 2Java Fundamentals

Page 2: Chapter 2 Java Fundamentals

2

Contents1. The Parts of a Java Program2. The print and println Methods, and the

Java API3. Variables and Literals4. Primitive Data Types5. Arithmetic Operators6. Combined Assignment Operators7. Conversion between Primitive Types8. Creating Named Constraints with final

Page 3: Chapter 2 Java Fundamentals

3

Contents9. The String Class10.Scope11.Comments12.Programming Style13.Reading Keyboard Input14.Dialog Box

Page 4: Chapter 2 Java Fundamentals

4

1. The Parts of a Java Program Problem

Write a Java program to display a message (Programming is great fun!) on the screen.

Page 5: Chapter 2 Java Fundamentals

5

1. The Parts of a Java Program (Cont’d) Run eclipse Create a new Java project

Enter the project name: MyFirstProject

Create a new Java class: Enter the class name: Simple

This will create a source code file Simple.java

Enter the code

Page 6: Chapter 2 Java Fundamentals

6

1. The Parts of a Java Program (Cont’d)

Page 7: Chapter 2 Java Fundamentals

7

1. The Parts of a Java Program (Cont’d) Run the program

Page 8: Chapter 2 Java Fundamentals

8

1. The Parts of a Java Program (Cont’d) Line 1:

//This is a simple Java program // :

marks the beginning of a comment. The compiler ignores everything from the

double-slash to the end of the line. You can type anything you want.

Comments help explain what’s going on.

Page 9: Chapter 2 Java Fundamentals

9

1. The Parts of a Java Program (Cont’d) Line 2:

A blank line Programmers often insert blank lines

in programs to make them easier to read.

Line 3:public class Simple This is a class header, and it marks

the beginning of a class definition.

Page 10: Chapter 2 Java Fundamentals

10

1. The Parts of a Java Program (Cont’d)

A Java program must have at least one class definition.

public: public is a Java keyword must be written in all lowercase letters public is an access specifier, and it

controls where the class may be accessed from. The public specifier means access to the class is unrestricted (the class is “open to the public”).

Page 11: Chapter 2 Java Fundamentals

11

1. The Parts of a Java Program (Cont’d)

class: a Java keyword, must be written in

lowercase letter. indicates the beginning of a class

definition. Simple:

Simple is the class name which is made up by the programmer. Programmer-defined names may be written in lowercase letters, uppercase letters, or a mixture of both.

Page 12: Chapter 2 Java Fundamentals

12

1. The Parts of a Java Program (Cont’d)

public class Simple tell the compiler that a public accessible class

named Simple is being defined. We can create more than one class in a file,

but we may only have one public class per Java file.

When a Java file has a public class, the name of the public class must be the same as the name of the file (without the .java extension).

Java is a case-sensitive language.Public ≠ public ≠ puBlic ≠ pUblic …

Page 13: Chapter 2 Java Fundamentals

13

1. The Parts of a Java Program (Cont’d) Line 4:

{ is a left brace, or an opening brace, and is

associated with the beginning of the class definition.

All programming statements that are parts of class are enclosed in a set of braces. In line 9, we will have the closing brace.

Everything between the two braces is the body of the class named Simple.

Page 14: Chapter 2 Java Fundamentals

14

1. The Parts of a Java Program (Cont’d)

Page 15: Chapter 2 Java Fundamentals

15

1. The Parts of a Java Program (Cont’d) Line 5:

public static void main(String[] args) a method header, the beginning of a

method. main is a name of the method. Every

Java program must have a method named main. The main method is the starting point of an application.

Name of the method

Page 16: Chapter 2 Java Fundamentals

16

1. The Parts of a Java Program (Cont’d) Line 6:

{ This opening brace belongs to the main

method. Every opening brace must have a accompanying closing brace.

We will have a closing brace in line 8 that corresponds with this opening brace.

Everything between these braces is the body of the main method.

Page 17: Chapter 2 Java Fundamentals

17

1. The Parts of a Java Program (Cont’d) Line 7:

System.out.println("Programming is great fun!");

This line is a statement. It displays a message on the screen. The message, “Programming is great fun!”, is printed without the quotation marks.

The group of characters inside the quotation marks is called a string literal.

There is a semicolon at the end of this line. Semicolon marks end of a statement in Java.

Page 18: Chapter 2 Java Fundamentals

18

1. The Parts of a Java Program (Cont’d)

Not every line of code ends with a semicolon: Comments do not have to end with a semicolon Class headers and method headers do not end

with a semicolon. The brace characters, { and }, are not

statements, so we do not place a semicolon after them.

Lines 8 and 9 contain the closing braces for main method and the class definition.

Page 19: Chapter 2 Java Fundamentals

19

1. The Parts of a Java Program (Cont’d) Java is a case-sensitive language. All Java program must be stored in a file

with a name that ends with .java Comments are ignored by the compiler. A .java file may contain many classes,

but may only have one public class. If a .java file has a public class, the

class must have the same name as the file.

Page 20: Chapter 2 Java Fundamentals

20

1. The Parts of a Java Program (Cont’d) Every Java application program must

have a method named main. For every brace, or opening brace,

there must be a corresponding right brace, or closing brace.

Statements are terminated with semicolons. This does not include comments, class headers, method headers, or braces.

Page 21: Chapter 2 Java Fundamentals

21

2. The print and println Methods, and Java API The print and println methods

are used to display text output. are parts of the Java API (Application

Programmer Interface). API is a collection of prewritten classes and

methods for performing specific operations. The console

Standard output: the monitor Standard input: the keyboard

Page 22: Chapter 2 Java Fundamentals

22

2. The print and println Methods, and Java API System.out.println("Programming is great fun!");

Hierarchical Relationship among the System class, the out object, and the print and println methods

Page 23: Chapter 2 Java Fundamentals

23

2. The print and println Methods, and Java API The System class is part of the java API. It has

member objects and methods for performing system-level operations, such as sending output to the console.

The out object is a member of the System class. It provides methods for sending output to the screen.

The print and println methods are members of the out object. They actually perform the work of writing characters on the screen.

We use the period to separate System, out and print or println. The period is pronounced “dot”.

Page 24: Chapter 2 Java Fundamentals

24

2. The print and println Methods, and Java API The value that is to be displayed on

the screen is places inside the parentheses. This value is known as an argument.System.out.println(“King Arthur”);

The println method is that after it displays its message, it advances the cursor to the beginning of the next line.

Page 25: Chapter 2 Java Fundamentals

25

2. The print and println Methods, and Java API

Page 26: Chapter 2 Java Fundamentals

26

The print Method The print method

part of the System.out object. serves a purpose to display output on

the screen. does not advance the cursor to the

next line after its message is displayed.

Page 27: Chapter 2 Java Fundamentals

27

The print Method

Page 28: Chapter 2 Java Fundamentals

28

The print Method

Page 29: Chapter 2 Java Fundamentals

29

The print Method There are two ways to fix the Unruly program:

use println method ? use escape sequences to separate the output into

different lines An escape sequence starts with the

blackslash character (\), and is followed by one or more control characters.

The escape sequence that causes the output cursor to go to the next line is \n

\n is called the newline escape sequence.

Page 30: Chapter 2 Java Fundamentals

30

The print Method

Page 31: Chapter 2 Java Fundamentals

31

The print Method

Page 32: Chapter 2 Java Fundamentals

32

Common Escape Sequences See table 2-2

\n New line \t Horizontal Tab \b backspace \r Return \\ Backslash \’ Single quote \” Double quote

Page 33: Chapter 2 Java Fundamentals

33

3. Variables and Literals A variable is a named storage

location in the computer’s memory.

A literal is a value that is written into the code of a program.

Page 34: Chapter 2 Java Fundamentals

34

3. Variables and Literals (Cont’d)

Page 35: Chapter 2 Java Fundamentals

35

3. Variables and Literals (Cont’d) Line 7:

int value; Variable declaration Variables must be declared before

they can be used. A variable declaration tells the

compiler the variable’ name the type of data the variable will hold

variable’s name

data type

Page 36: Chapter 2 Java Fundamentals

36

3. Variables and Literals (Cont’d) Line 9:

value=5; Assignment statement The equal sign = is an operator that

stores the value on its right (5) into the variable named on its left (value).

After this line executes, the value variable will contain the value 5.

Page 37: Chapter 2 Java Fundamentals

37

3. Variables and Literals (Cont’d)

Page 38: Chapter 2 Java Fundamentals

38

3. Variables and Literals (Cont’d) Line 11:

System.out.println(value); The method println will display the

variable’s contents on the console. There are no quotation marks around

variable value Compare with System.out.println(“value”);

Page 39: Chapter 2 Java Fundamentals

39

Display Multiple Items with the + Operator The + operator is used with strings:

String concatenation operatorSystem.out.println(“This is ” + “one string.”);

This is one string. The + operator can be used to

concatenate the contents of a variable to a string

number = 5;System.out.println(“The value is ” + number);

The value is 5

Page 40: Chapter 2 Java Fundamentals

40

Display Multiple Items with the + Operator (Cont’d) A string literal cannot begin on one

line and end on anotherSystem.out.println(“Enter a value that is

greater than zero and less than 10.”); Breaking the argument up into smaller

string literals, and use the + operatorSystem.out.println(“Enter a value that” + “

is greater than zero and less “ + “than 10.”);

Error

Page 41: Chapter 2 Java Fundamentals

41

Display Multiple Items with the + Operator (Cont’d)

Page 42: Chapter 2 Java Fundamentals

42

Identifiers Identifier

A programmer-defined name. Do not use any of the Java keywords

for identifiers. Represents some element of a

program. Variable names, class names, name of

methods, …

Page 43: Chapter 2 Java Fundamentals

43

Identifiers (Cont’d) Should choose names that give an

indication of what they are used for, what the purpose is

For example Number of ordered items

int x; not goodint itemsOrdered;

Page 44: Chapter 2 Java Fundamentals

44

Identifiers (Cont’d) There are some rules with all

identifiers: The first character must be one of the

letters a-z, A-Z, _, $ After the first character, we can use

letters a-z, A-Z, digits 0-9, _, $ Uppercase and lowercase characters are

distinct. Identifiers cannot include spaces

Page 45: Chapter 2 Java Fundamentals

45

Identifiers (Cont’d)Variable Name Legal or Illegal ?dayOfWeek Legal3dGraph Illegaljune1997 Legalmixture#3 Illegalweek day Illegal

Page 46: Chapter 2 Java Fundamentals

46

Identifiers (Cont’d) Variable Names

It is standard practice to begin variable names with a lowercase letter

Capitalize the first the first letter of each subsequent word.

int itemOdered;

Page 47: Chapter 2 Java Fundamentals

47

Identifiers (Cont’d) Class Names

It is standard practice to begin variable names with a uppercase letter

Capitalize the first letter of each subsequent word.

public class PayRoll

Page 48: Chapter 2 Java Fundamentals

48

4. Primitive Data Types Each variable has a data type,

which is the type of data that the variable can hold.

Selecting the proper type for variables is important

amount of memory the way the variable formats and

stores data

Page 49: Chapter 2 Java Fundamentals

49

4. Primitive Data Types (Cont’d) Primitive data types for numeric

dataData Type

Size Range

byte 1 byte Integers in the range of -128 to +127short 2

bytesIntegers in the range of -32,768 to +32,767

int 4 bytes

Integers in the range of -2,147,483,648 to +2,147,483,647

long 8 bytes

Integers in the range of -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

float 4 bytes

Floating-point numbers in the range of ±3.4×10-38 to ±3.4×1038 , with 7 digits of accuracy

double 8 bytes

Floating-point numbers in the range of ±1.7×10-308 to ±1.7×10308 , with 15 digits of accuracy

Integer Data Types

Floating-Point Data Types

Page 50: Chapter 2 Java Fundamentals

50

4. Primitive Data Types (Cont’d) General format of a variable declaration

DataType VariableName; DataType : name of the data type VariableName : name of the variable Examples:

byte inches;int speed;short month;float salesComission;double distances;

Page 51: Chapter 2 Java Fundamentals

51

4. Primitive Data Types (Cont’d) Combining variables of the same

data typeint length;int width;int area;

int length, width, area;

Page 52: Chapter 2 Java Fundamentals

52

Integer Literals Do not embed commas in numeric

literals.int number;number = 1,257,649; //ERROR !number = 1257649;

We can force an integer literal to be treated as long

57 be treated as int value 57L, 57l be treated as long values

Page 53: Chapter 2 Java Fundamentals

53

Floating-Point Literals Java assumes floating-point literals

such as 29.75, 1.76, … to be of double data type.float number;number = 25.5; //Error !

float number;number = 25.5F;number = 25.5f;

Page 54: Chapter 2 Java Fundamentals

54

Scientific and E Notation Floating-point literals can be

represented in scientific notation. 47,281.97 4.728197×104

Java uses E notation to represent values in scientific notation.

Decimal Notation

Scientific Notation

E Notation

247.91 2.4791×102 2.4791E20.00072 7.2×10-4 7.2E-42,900,000 2.9×106 2.9E6

Page 55: Chapter 2 Java Fundamentals

55

The boolean Data Type The boolean data type allows us

to create variables that hold one of two possible values:truefalse

Variables of boolean data type are useful for evaluation conditions that are either true or false.

Page 56: Chapter 2 Java Fundamentals

56

The boolean Data Type (Cont’d)

Page 57: Chapter 2 Java Fundamentals

57

The char Data Type The char data type is used to store

characters. A variable of the char data type can

hold one character at a time. Character literals

‘A’, ‘B’, ‘a’, ‘s’, … Characters are internally represented

by numbers (Unicode) ‘A’ : 65 ‘B’: 66 …

Page 58: Chapter 2 Java Fundamentals

58

The char Data Type (Cont’d) Characters and how they are

stored in memory

Page 59: Chapter 2 Java Fundamentals

59

The char Data Type (Cont’d)

Page 60: Chapter 2 Java Fundamentals

60

The char Data Type (Cont’d)

Page 61: Chapter 2 Java Fundamentals

61

Variable Assignment and Initialization Variable assignment

Using = assignment operator The operand on the left side of the =

operator must be a variable. The value in right side of the = operator

is assigned to the variable in left side.int unitSold;unitSold = 12;12 = unitSold; //ERROR !

Page 62: Chapter 2 Java Fundamentals

62

Variable Assignment and Initialization (Cont’d) Initialization

We may also assign values to variables as part of the declaration statementint month = 2, days = 28;int flightNum = 89, travelTime, departure = 10;

Page 63: Chapter 2 Java Fundamentals

63

Variables Hold Only One Value at a Time A variable can hold only one

value at a time. When we assign a new value to a

variable, the new value replaces the variable’s previous contents.

Page 64: Chapter 2 Java Fundamentals

64

5. Arithmetic Operator There are three types of

operators: Unary

Requires only a single operand-5 -number (negative

operator) Binary

Requires two operands Ternary

Requires three operands

Page 65: Chapter 2 Java Fundamentals

65

5. Arithmetic Operator (Cont’d) Common operators

Operator

Meaning Type Example

+ Addition Binary total = cost + tax;- Subtraction Binary cost = total – tax;* Multiplicatio

nBinary tax = cost * rate;

/ Division Binary salePrice = original / 2;% Modulus Binary remainder = value % 3;

Page 66: Chapter 2 Java Fundamentals

66

Integer Division When both operands of a division

statement are integers, the statement will result in integer division.

The result of the integer division will be an integer.

double parts; double parts;parts = 17 / 3; parts = 17.0 / 3;

parts is assigned the

value 5.0

parts is assigned the value

5.666666666667

Page 67: Chapter 2 Java Fundamentals

67

Operator Precedence Precedence of arithmetic

operators (highest to lowest) - (unary negation) * / % + -outcome = 12 + 6 / 3 = 12 + 2 = 14

Page 68: Chapter 2 Java Fundamentals

68

Operator Precedence (Cont’d) Associativity of arithmetic

operatorsOperator Associativity- (unary negation) Right to left* / % Left to right+ - Left to right

Expression Value5 + 2 * 410 / 2 – 38 + 12 * 2 – 44 + 17 % 2 – 16 – 3 * 2 + 7 – 1

Page 69: Chapter 2 Java Fundamentals

69

Grouping with Parentheses To force some operations to be

performed before othersExpression Value(5 + 2) * 410 / (5 – 3)8 + 12 * (6 – 2)(4 + 17) % 2 – 1

Page 70: Chapter 2 Java Fundamentals

70

The Math class Math class is a member of Java

API. The Math.pow method

Rising a number to a powerresult = Math.pow(4.0, 2.0); // 42

The Math.sqrt method accepts a double value as its

argument and returns the square root of the value.result = Math.sqrt(9.0); //

9.0

Page 71: Chapter 2 Java Fundamentals

71

6. Combined Assignment Operators The combined assignment

operators combine the assignment operator with the arithmetic operators.

x += 5;

x = x + 5;

1. Add 5 to x2. The resut is then

assigned to x

equivalent to

Page 72: Chapter 2 Java Fundamentals

72

6. Combined Assignment Operators (Cont’d) Combined assignment operators

Operator Example Usage Equivalent To+= x += 5; x = x + 5;-= y -= 2; y = y – 2;*= z *= 10; z = z * 10;/= a /= b; a = a / b;%= c %= 3; c = c % 3;

Page 73: Chapter 2 Java Fundamentals

73

7. Conversion between Primitive Data Types Before a value can be stored in a

variable, the value’s data type must be compatible with the variable’s data type.

Java performs some conversions between data types automatically, but does not perform any conversion that can result in the loss of data;

Page 74: Chapter 2 Java Fundamentals

74

7. Conversion between Primitive Data Types (Cont’d)int x;double y = 2.5;x = y; //ERROR ! Possible loss

precisionint x;short y = 2;x = y;// OK

Page 75: Chapter 2 Java Fundamentals

75

7. Conversion between Primitive Data Types (Cont’d) In assignment statements where values of lower-

ranked data types are stored in variables of hight-ranked data types, Java automatically converts the lower-ranked value to the higher-ranked type. (widening conversion)

Primitive data type ranking double Highest Rank float long int short byte Lowest Rank

double x;int y = 10;x = y; //widening conversion

Page 76: Chapter 2 Java Fundamentals

76

Cast Operators A narrowing conversion is the

conversion of a value to a lower-ranked type.

Narrowing conversions can cause a loss of data, Java does not automatically perform them.

The cast operator lets you manually convert a value, even if it is a narrowing conversion.

Page 77: Chapter 2 Java Fundamentals

77

Cast Operators (Cont’d) Cast operators are unary

operators that appear as a data type name enclosed in a set of parentheses.int x;double y = 2.5;x = (int)y; // x = 2;

cast operator

Page 78: Chapter 2 Java Fundamentals

78

Cast Operators (Cont’d)int pie = 10, people = 4;double piesPerPerson;piesPerPerson = pie / people;

piesPerPerson = (double)pie / people;

piesPerPerson = pie / (double)people;

piesPerPerson = (double)(pie / people);

2.0

2.5

2.5

2.0

Page 79: Chapter 2 Java Fundamentals

79

Mixed Integer Operations With arithmetic operations on

int, byte, and short variables: Values of the byte or short data

types are temporarily converted to int value.

The result will always be an int.short x = 10, y = 20, z;z = x + y; //causes an error

x + y results an int number

Page 80: Chapter 2 Java Fundamentals

80

Other Mixed Mathematical Expressions1. If one of an operator’s operands is a double, the

value of the other operand will be converted to a double. The result of the expression will be a double.

2. If one of an operator’s operands is a float, the value of the other operand will be converted to a float. The result of the expression will be a float.

3. If one of an operator’s operands is a long, the value of the other operand will be converted to a long. The result of the expression will be a long.

Page 81: Chapter 2 Java Fundamentals

81

8. Creating Named Constants with final The final keyword can be used in

a variable declaration to make the variable a named constant.

Named constants are initialized with a value, and that value cannot change during the execution of the program

Page 82: Chapter 2 Java Fundamentals

82

8. Creating Named Constants with final (Cont’d)amount = balance * 0.069;

final double INTEREST_RATE = 0.069;amount = balance * INTEREST_RATE; The Math.PI Named Constant

is assigned the value 3.1415926535897323845

is an approximation of the mathematical value pi.

area = Math.PI * radius * radius;

Interest rate

Page 83: Chapter 2 Java Fundamentals

83

9. The String Class String literals are enclosed in double

quotation marks.“Hello World” “Joe Mahoney”

Java does not have a primitive data type for storing strings in memory.

The String class Allows you to create objects for holding strings. Has various methods that allow you to work

with strings.

Page 84: Chapter 2 Java Fundamentals

84

9. The String Class (Cont’d) Objects are created from classes. Declare a variable of the String class

String name; A class type variable does not hold the actual data

item. It holds the memory address of the data item. name is a class type variable, holds the memory address of

a String object. When a class type variable holds the address of an

object, it is said that the variable references the object.

Class type variables are known as reference variables.

Page 85: Chapter 2 Java Fundamentals

85

9. The String Class (Cont’d) Creating a String object

String name;name = “Joe Mahoney”; String object is created in memory with the

value “Joe Mahoney” stored in it. The address of that object is stored in the name

variable.

Page 86: Chapter 2 Java Fundamentals

86

9. The String Class (Cont’d) Class type variables

String name;name = “Joe Mahoney”;

Primitive type variablesint number;number = 25;

Page 87: Chapter 2 Java Fundamentals

87

9. The String Class (Cont’d)

Page 88: Chapter 2 Java Fundamentals

88

9. The String Class (Cont’d) String provides numerous

methods for working with strings. To call a method means to

execute it.ReferenceVariable.method(arguments…)String name;name = “Tony Gaddis”;int stringSize;stringSize = name.length();

length method of String is called

Page 89: Chapter 2 Java Fundamentals

89

A few String class methods charAt(index)

index is an int value and specifies a character position in the string. The first character in the string is at position 0.

The method return the character at the index position.

length() Returns the number of characters in

the string.

Page 90: Chapter 2 Java Fundamentals

90

A few String class methods toLowerCase()

Returns a new string that is the lowercase equivalent of the string contained in the calling method.

toUpperCase() Returns a new string that is the

uppercase equivalent of the string contained in the calling method.

Page 91: Chapter 2 Java Fundamentals

91

A few String class methods

Page 92: Chapter 2 Java Fundamentals

92

10. Scope Every variable has a scope. A variable’s scope is the part of

the program that has access to the variable.

Variables can not be accessed by statements that are outside the scope.

Variables that are declared inside a method are called local variables.

Page 93: Chapter 2 Java Fundamentals

93

10. Scope (Cont’d) A local variable’s scope begins at the variable’s

declaration and ends at the end of the method in which the variable is declared.

Page 94: Chapter 2 Java Fundamentals

94

10. Scope (Cont’d) We can not have two local variables with

the same name in the same scope.

Page 95: Chapter 2 Java Fundamentals

95

11. Comments Comments are notes of

explanation. Comments are parts of the program,

but the compiler ignores them. They are intended for people who

may be reading the source code Documented programs will make

your life easier.

Page 96: Chapter 2 Java Fundamentals

96

11. Comments (Cont’d) Three ways to comment in Java

Single-line comments Using two forward slashes // Everything from // to the end of the line is

ignored. Multi-line comments

Multi-line comments start with /* and end with */.

Everything between /* and */ is ignored.

Page 97: Chapter 2 Java Fundamentals

97

11. Comments (Cont’d) Documentation Comments

Documentation comments can be read and processed by a program named javadoc.

The javadoc program reads Java source code files and generates HTML files that document the source code.

If the source code files contain any documentation comments, the information in the comments becomes part of the HTML documentation.

Page 98: Chapter 2 Java Fundamentals

98

11. Comments (Cont’d) Any comment that starts with /** and

ends with */ is considered a documentation comments.

Normally we write a documentation comment

before a class header, giving brief description of the class

before a method header, giving brief description of the method.

Run javadoc javadoc SourceFile.java

Page 99: Chapter 2 Java Fundamentals

99

11. Comments (Cont’d) Generating javadoc in eclipse

Project \Generate Javadoc … Enter Javadoc command

C:\Program Files\Java\jdk1.6.0_10\bin\javadoc.exe

Use standard doclet

Page 100: Chapter 2 Java Fundamentals

100

12. Programming Style Programming Style refers to the

way a programmer uses Spaces, Indentations, Blank lines, Punctuations to arrange a program’s source code.

This program is syntactically correct and is very difficult to read:

Page 101: Chapter 2 Java Fundamentals

101

12. Programming Style (Cont’d)

Page 102: Chapter 2 Java Fundamentals

102

12. Programming Style (Cont’d) A common programming style is

to indent all lines inside a set of braces

To handle statements that are too long to fit in one line:

Extra spaces are inserted at the beginning of statement’s second, third … lines, which indicate that they are continuations.

Page 103: Chapter 2 Java Fundamentals

103

12. Programming Style (Cont’d)

Extra spaces

Extra spaces

Page 104: Chapter 2 Java Fundamentals

104

12. Programming Style (Cont’d) Declaration of multiple variables

of the same type with a single statement

To write each variable name on a separate line with a comment explaining the variable’s purpose.

int fahrenheit, //Fahrenheit temperature centigrade, //Centigrade temperature kelvin; //Kelvin temperature

Page 105: Chapter 2 Java Fundamentals

105

13. Reading Keyboard Input System.in is an object

Standard input device Is used to read keystrokes Reads input only as byte values

Is not very useful because programs normally requires values of other data types

Objects of the Scanner class can be used to read input from the keyboard.

Reads input from a source such as System.in Provides methods to retrieve the input formatted

as primitive values or strings.

Page 106: Chapter 2 Java Fundamentals

106

The Scanner object The Scanner class is not automatically

available to Java programs. Using import statement to tell the compiler

where in the Java library to find the Scanner class

import statement must be placed near the beginning of the file, before any class definition

import java.util.Scanner;

Page 107: Chapter 2 Java Fundamentals

107

The Scanner object (Cont’d) Create the Scanner object and

connect it to the System.in object.Scanner keyboard;keyboard = new Scanner(System.in); new

a Java keyword is used to create an object in memory

Page 108: Chapter 2 Java Fundamentals

108

The Scanner object (Cont’d)

Scanner keyboard = new Scanner(System.in);

The = operator assigns the address of the Scanner object to the keyboard

variable.

This declares a variable named keyboard . The

variable can reference an object of the Scanner class.

This creates a Scanner object in memory. The object

will read input from System.in

Page 109: Chapter 2 Java Fundamentals

109

The Scanner object (Cont’d) The Scanner class has methods

for reading strings, bytes, integers, long integers, short integers, float and doubles.int number;Scanner keyboard;keyboard = new Scanner(System.in);System.out.println(“Enter an integer:”);number = keyboard.nextInt();

Page 110: Chapter 2 Java Fundamentals

110

The Scanner object (Cont’d) Some of the Scanner methods

byte nextByte(): returns input as a byte.

double nextDouble(): returns input as a double.

float nextFloat(): returns input as a float.

int nextInt(): returns input as an int.

Page 111: Chapter 2 Java Fundamentals

111

The Scanner object (Cont’d)

String nextLine(): returns input as a String.

long nextLong(): returns input as a long.

short nextShort(): returns input as a short.

Page 112: Chapter 2 Java Fundamentals

112

The Scanner object (Cont’d) Problem: User’s gross pay

Write a Java program to calculate the gross pay of a user. The program allows user to enter user’s name, hours worked, pay rate, and display the user’s gross pay on the console.

Page 113: Chapter 2 Java Fundamentals

113

User’s gross pay Display “What is your name?”. Input user’s name. → Store in a variable Display “How many hours did you work?”. Input hours. → Store in a variable Display “How much do you get paid per

hour?”. Input rate. → Store in a variable Calculate the user’s gross pay and store in a

variable Display user’s name and gross pay

Page 114: Chapter 2 Java Fundamentals

114

User’s gross pay

Page 115: Chapter 2 Java Fundamentals

115

User’s gross pay

Page 116: Chapter 2 Java Fundamentals

116

Reading a Character The Scanner class does not have a

method for reading a single character. To read a single character using the

Scanner class:1. Use the nextLine method of the Scanner

class to read a string from the keyboard.2. Use the charAt method of the String

class to extract the first character of the string.

Page 117: Chapter 2 Java Fundamentals

117

Reading a Character (Cont’d)String input; //To hold a line of inputchar answer; // To hold a single character

Scanner keyboard; keyboard = new Scanner(System.in);

System.out.println(“Are you having fun? (Y/N)”);input = keyboard.nextLine(); // Get a line of

inputanswer = input.charAt(0); // Get the first character

Page 118: Chapter 2 Java Fundamentals

118

Mixing Calls to nextLine with calls to Other Scanner Methods When we call one of the Scanner

class’s methods to read a primitive value, then call the nextLine method to read a string → The string is not read

Because the Scanner class’s methods to read a primitive value left a newline character in the keyboard buffer.

Page 119: Chapter 2 Java Fundamentals

119

Mixing Calls to nextLine with calls to Other Scanner Methods

Page 120: Chapter 2 Java Fundamentals

120

Mixing Calls to nextLine with calls to Other Scanner Methods

Page 121: Chapter 2 Java Fundamentals

121

Mixing Calls to nextLine with calls to Other Scanner Methods To fix the problem

Insert the nextLine method to consume, or remove, the newline character that remains in the keyboard buffer.

Page 122: Chapter 2 Java Fundamentals

122

14. Dialog Boxes A dialog box is a small graphical

window that displays a message or requests input.

The JOptionPane class allows you to quickly display a dialog box

Display dialog: To display a message Input dialog: To request input

Page 123: Chapter 2 Java Fundamentals

123

Display Message Dialogs The showMessageDialog method

is used to display a message dialog

JOptionPane.showMessageDialog(null, “Hello World”);

Page 124: Chapter 2 Java Fundamentals

124

Display Input Dialog The showInputDialog method is

used to display an input dialogString name;name = JOptionPane.showInputDialog(“Enter your name”);

The name variable will reference the string value entered in the text field.

Text field

Page 125: Chapter 2 Java Fundamentals

125

Converting String Input to Numbers Because the showInputDialog

method always returns the user’s input as a String, even if the user enters numeric data

We must convert the input string to a numeric value if the string represents numeric data.

Page 126: Chapter 2 Java Fundamentals

126

Converting String Input to Numbers (Cont’d) Methods for converting strings to

numbers Byte.parseByte

Convert a string to a bytebyte num;Num = Byte.parseByte(str);

Double.parseDouble Convert a string to a double

Page 127: Chapter 2 Java Fundamentals

127

Converting String Input to Numbers (Cont’d)

Float.parseFloat Convert a string to a float

Integer.parseInteger Convert a string to an int

Long.parseLong Convert a string to a long

Short.parseShort Convert a string to a short

Page 128: Chapter 2 Java Fundamentals

128

PayrollDialog Write the Payroll program using

dialogs to get user’s input and display user’s information.

Page 129: Chapter 2 Java Fundamentals

129

PayrollDialog

Page 130: Chapter 2 Java Fundamentals

130

PayrollDialog

Page 131: Chapter 2 Java Fundamentals

131