A First Look at Java
Chapter 2
1/29 & 2/2
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Assignment• See my website for the new assignment.
Chapter Topics
A Simple Java Program• Identifiers• Displaying Text
CommentsData Types
• Primitive Types• Reference Types
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Chapter Topics
Variables• Declarations• Assignments
Simple Input From the KeyboardConstants
• Unnamed Constants• Named Constants
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Objectives
After studying this chapter, you should be able to:• Create valid Java identifiers• Write Java statements that display text• Describe the primitive data types int,
double, char, and boolean• Declare variables and assign them values• Read numbers and characters from the
keyboard
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Displaying Text
Two commands• System.out.println
outputs newline character after the output• System.out.print
leaves the cursor on the same line.
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Displaying Text
System.out.print(“Black”);
System.out.println(“bird”);
System.out.println(“sings.”);
Output:
Blackbird
sings.
|
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Comments
Documents the programComments
• Begin line with double slash // Ends with the end of the line.
• Span multiple lines between slash-star combination./* . . . . . . */
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
A Simple Java Program
An online friend lives in Calgary. She always tells me the temperature up there in degrees Celsius. I wrote a program to convert the temperature to Fahrenheit.
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
public class CtoF {
/** This program converts Celsius to Fahrenheit. */
public static void main(String[] args) { double cel = 20; double fahr;
fahr = 1.8 * cel + 32.0; System.out.println(fahr +
" degrees Fahrenheit"); }//end main method
}//end CtoF class
A Simple Java Program
Note definition of a class• Begins and ends with brace{ … }
Note declaration of main methodpublic static void main(String[] args)
• Also begins and ends with brace
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Identifiers
Examples: public, main, CtoF, celNames of things within the program
Made up of letters, digits, underscore, and $ Must not start with a digit Case sensitive
Categories Names you invent Names chosen by another programmer Identifiers part of the Java language
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Valid Identifiers?
taxes2013
_gold_mines
99bottles
money$
main
News
two#
ConventionsClass names begin with upper caseMethod names and begin with lower caseBraces
Each on its own line (optional)eclipse puts it on the line with the heading
Always in pairsEnd brace commented(optional)
Lines within braces indentedSkip lines for readability (white space)
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Primitive TypesData that is a primitive type has a single
simple value.Examples: individual characters,
numbers, boolean values– 'Q', 55.78, true
Are not objects
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Primitive Types
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Typical Primitive Types int• integer, positive/negative counting
numbers. • 1, -10, 0, 20000
double• Numbers with a decimal part• 1.5, -9.0, 3.14159, 0.0
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Typical Primitive Types char• Holds just one character• 'z', '*', '2'
boolean• true or false
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Reference TypesCan contain multiple pieces of dataMay also have methods that operate on
those valuesExample – String
“Hello”Contains 5 characters
Name of the class is the data typeCalled a “class type” or “reference type”
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Variables
Used to store a piece of dataStores it at a certain memory location Identifier used to name variable• Should begin with lower case letter• Subsequent words use upper case• Should be meaningful
Example: salesTaxRate
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Variables
Must be declared –Data type– Identifier
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Assignment Statement
Assignment gives a variable a valueSyntax
variable = expression ; • Expression evaluated• Value stored in memory location specified by
variable
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Assignment StatementFigure 2-3 Note values before, after
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Variables in a Program
Figure 2-4 Effects of sequence of assignments
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Reference Variable
String str = “Hello”;
Notes on Output
+ operator in print statements Add numbers• (5+6)
Concatenate Strings.• "to" + "day" --> "today"• 15 + " inches" --> 15 inches
• Strings that span multiple lines
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Questions
• What are the rules for writing an identifier (name) in Java?
• What primitive type would you use to store the weight of a car in tons?
• On which side of the = does the variable in an assignment statement belong?
Try a Program
Write a program that sets a variable to a person's name and another variable to their former age. It will output their name and their new age on their birthday. Sample output:
John is 21 today.
Another Example
Write a program to find the sales tax on an item. Assign the cost of the item to a variable. Set a price variable to cost of the item. Output the item's name and the tax.
Scanner and Constants2/5/15 & 2/9/15
Keyboard InputUse Scanner class from Java Class
Library
Must use import statement: import java.util.Scanner;
Next, create Scanner object Scanner keyboard = new Scanner(System.in);
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Package name Class name
Keyboard Input
Keyboard is an object which can perform methods.
Use method to receive data from keyboard, store in variable• int x = keyboard.nextInt();• String word = keyboard.next();
•Let’s change the Age program so that it asks the user for the name and age.
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Other Scanner Methods
double rate = keyboard.nextDouble();String words = keyboard.nextLine();
//program to give new age on a birthday.import java.util.Scanner;
public class Birthday {public static void main(String[] args) {
String name;int age;//Create a ScannerScanner kbd = new Scanner(System.in);
//Input nameSystem.out.print("Name?");name = kbd.nextLine();
//Input age.System.out.print("Age?");age = kbd.nextInt();age = age + 1;
System.out.println(name + " is " + age + " today.");
kbd.close();}
}
Constants
ConstantsUnnamed constants
• Literal values – integers, floating-point, boolean
E format may be used for doubles• 1.5e2 --> 150• 8e4 - decimal maybe left off, still a double• 5.1e-4 = ?
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
ConstantsNamed constants
• Similar to declaring variables, but values can't be changed.
• Use reserved word final• Gives descriptive name, avoids typing
mistakes• All caps by convention
final double TAX = .06;final int DOZEN = 12;final boolean NOT_DONE = false;
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Participation Input and Constants
• Write a program to input the cost of a car in dollars. Output the sales tax on the car.
• Tax rate is 6% Use a constant.
1. Input cost – use a Scanner
2. Find tax
3. Output tax
I'll submit the program.
Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010
Use of Math class
For the programming assignment you will need to use Math.sqrt( ) and Math.PI.
Questions
• What type of object is used to handle input?
• What package does the Scanner belong to?
• What how is a constant different from other variables?