L02 ElementaryProgramming
L02 ElementaryProgramming
1
Contents
Identifiers
Variables
Declaring Variables and Data Types (Java’s Primitive Types)
Assignments and Assignment Compatibility
Type Casting
Arithmetic Operators
Pre and Post Increment and Decrement Operators
Scientific Notation and “double-precision” values
Constants
Character Data Type and Unicode
Classes, Methods and the main Method
HelloWorld.java, ComputeArea.java, ChangeMaker.java
Reading Input from the Console and Packages in Java
Software engineering basics
2
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Identifiers
What’s an Application Programming Interface (API)?
a library of code identifiers/names to use
What are identifiers/names used for?
For Variables, Classes, and Methods
They come from 2 sources:
the Oracle (or someone else’s) Java API
your own classes, variables, and methods
Identifiers (Names) –Why name them?
they are your data and commands, and you’ll need to reference
them elsewhere in your program
int myVariable = 5; // Declaration
myVariable = myVariable + 1; // Using the variable
3
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Rules for Identifiers
Should contain only letters, numbers, & '_'
'$' is allowed, but only for special use
Cannot begin with a digit!
Although it is legal, do not begin with ‘_’ (underscore)
Uppercase and lowercase letters are considered to be
different characters (Java is case-sensitive)
Examples:
Legal: myVariable, my_class, my4Var
Illegal: 4myVariable, my class, my!Var,
@#$myClass
4
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Common Java Naming Conventions
Variables & Methods start with lower case letters:
radius, getRadius
Classes start with upper case letters: Circle
Variables and Class identifiers should generally be nouns:
radius, Circle
Method identifiers should be verbs: getRadius
Use Camel notation: GeometricObject,
getRadius
Use descriptive names: Circle, radius, area
area = PI * radius * radius;
5
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Variables
In a program, the variables store data
All Java variables must have a declared type
A variable’s type determines:
what kind of value the variable can hold
how much memory to reserve for that variable
char letter;
int i;
double area;
String s;
Object o;
6
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Data Types
There are 2 categories of types in Java (and most other
modern programming languages):
Primitive type variables store single pieces of data:
int i = 1; i 1
18
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Arithmetic Operators
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo/Remainder (integer operands only)
int x = 5;
int y = 10;
int z = 2;
int num1 = (x + y) * z;
System.out.println(num1); 30
19
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Division
Integer division:
8/3 = 2 (the quotient)
Double division (if at least an operand
is a double):
8.0/3.0 = 2.666666666666667
8.0/3 = 2.666666666666667
8/3.0 = 2.666666666666667
20
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Division
Division examples (evaluate full expression first, then
assignment):
double average = 100.0/8.0; //12.5
average = 100.0/8; //12.5
average = 100/8; //12.0
int sumGrades = 100/8; //12
sumGrades = 100.0/8.0; //ERROR
sumGrades = (int)100.0/8.0; //ERROR
sumGrades = (int)(100.0/8.0); //12
int fifty_percent = 50/100; //0
double fiftyPercent = 50/100; //0.0
fiftyPercent = 50.0/100.0; //0.5
21
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Rules of precedence
Standard PEMDAS order of operations:
Multiplication and division (*/) have higher precedence over
addition and subtraction (+-)
int x = 5;
int y = 10;
int z = 2;
int num1 = x + y * z;
System.out.println(num1); 25
My Advice: avoid rules of precedence and,whenever in doubt,
go with explicit use of parentheses.
int r2d2c3po = 3 * 4 + 5 / 6; 12
int r2d2c3po2 = (3 * (4 + 5))/ 6; 4
22
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Arithmetic Operators
The modulo/remainder % operator
Produces division remainders
int remainder = 10 % 6;
System.out.println(remainder); 4
23
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Arithmetic Operators
++ Increment by one
-- Decrement by one
+= Increment by specified amount
-= Decrement by specified amount
*= Multiply by specified amount
/= Divide by specified amount
int x = 5, y = 15, z = 25;
x = x + 1;
y++;
z += 1;
System.out.println(x); 6
System.out.println(y); 16
System.out.println(z); 26
24
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Pre and Post Increment and
Decrement Operators
int i = 10; Same effect as
int newNum = 10 * (++i); i = i + 1;
int newNum = 10 * i;
Results in: i=11
newNum = 110
int i = 10;
i = i++ + i++;
// 10(i=11) + 11(i=12) = 21
System.out.println(i); // 21
int y = 5;
y -= y++ - --y;
// y = 5 - (5(y=6) - (y=5)5) = 5 - (5 - 5) = 5 - 0 = 5
System.out.println(y); // 5
Notes:
y -= val; IS y = y - val;
26
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Scientific Notation
Floating-point literals can also be specified
in scientific notation:
E (or e) represents an exponent of the
base and it can be either in lowercase or
uppercase
Examples
1.23456e+2 = 1.23456e2 = 123.456
1.23456e-2 = 0.0123456
27
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
“double-precision” values
double values are represented internally as 64-bit “double-
precision” values, according to the IEEE 754 standard
(https://en.wikipedia.org/wiki/IEEE_754-2008_revision):
That is, floating point numbers are represented internally as
sums of binary (base-2) fractions/negative powers of 2 (e.g.,
0.5 = 2-1 , 0.75 = 2-1 + 2-2).
But many/most decimal fractions (e.g, 1/10=0.1) cannot be
represented exactly as binary fractions, so in many/most cases the
internal representation of a floating-point number is an approximation
of the actual value.
System.out.println(1 - 0.1 - 0.1 - 0.1);
0.70000001
28
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Constants
final datatype CONSTANTNAME = VALUE;
Examples:
final double PI = 3.14159;
final int SIZE; // assignment can be later
SIZE = 3; // GOOD
SIZE = 4; // ILLEGAL if changed again
Convention (i.e., style): UPPERCASE letters are
used for constants (because FORTRAN did not have
constants, so developers used uppercase only to
communicate that the identifier is a constant)
29
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Character Data Type
char letter = 'A';
char numChar = '4';
30
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Character Data Type
• Java characters use Unicode UTF-16 bit encoding
• chars can be assigned Unicode codes:
char letter = '\u0041'; // Unicode for 'A'
char numChar = '\u0034'; // Unicode for '4'
Unicode takes two bytes preceded by \u, expressed in four
hexadecimal numbers that run from '\u0000' to '\uFFFF'.
Unicode can represent 65535 + 1 characters.
• Examples:
Unicode \u03b1 \u03b2 \u03b3 for three Greek
letters
31
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Casting between char and
Numeric Types
int i = 'a'; // Same as int i = (int)'a';
// i is 97
char c = 97; // Same as char c = (char)97;
// c is 'a'
32
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Character Data Type
The increment and decrement operators can also
be used on char variables to get the next or
preceding Unicode character.
- the following statements display character b:
char ch = 'a';
System.out.println(++ch);
33
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Escape Sequences for Special Characters
Description Escape Sequence Unicode
Tab \t \u0009
Linefeed \n \u000A
Backslash \\ \u005C
Single Quote \' \u0027
Double Quote \" \u0022
34
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Classes
A program is defined by using one or more classes
public class ClassName {
// implementation
}
35
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Methods
A method is a sequence of statements that performs a
sequence of operations.
public static void print(String arg) {
// implementation
}
-It is used by invoking the method with arguments.
System.out.print("Welcome to Java!");
36
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
The main Method
The main method provides the control of program flow.
public class ClassName {
public static void main(String[] args) {
// ClassName PROGRAM’S POINT OF ENTRY
// THIS PROGRAM’S INSTRUCTIONS
// START HERE
}
}
ClassName is executable because it has a main method
we can compile and then run it
Not all classes require main methods
only those classes that initiate program execution require a main method
37
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Example programs: HelloWorld.java
/**
* HelloWorld is a Java application
* that simply displays "Hello World!" in the
* Java console.
*/
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
// Statement above displays "Hello, World!"
}
}
38
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Computing the Area of a Circle:
public class ComputeArea {
public static void main(String[] args) {
double radius; // Declare radius
double area; // Declare area
// Assign a radius
radius = 20; // New value is radius
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle"
+ " of radius " + radius + " is " + area);
}
}
39
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
public class ComputeArea { allocate memory
/** Main method */ for radius
public static void main(String[] args) {
double radius; radius no value
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);
}
}
40
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius no value
double radius;
double area; area no value
// Assign a radius
radius = 20; allocate memory
for area
// Compute area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
41
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
public class ComputeArea { assign 20 to radius
/** 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);
}
}
42
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
compute area and assign it
// Compute area to variable area
area = radius * radius * 3.14159;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
43
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Trace a Program Execution
public class ComputeArea {
/** Main method */ memory
public static void main(String[] args) {
radius 20
double radius;
double area; area 1256.636
// Assign a radius
radius = 20;
// Display results
System.out.println("The area for the circle of radius " +
radius + " is " + area);
}
}
44
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
import java.util.Scanner;
ChangeMaker.java
public class ChangeMaker {
public static void main(String[] args) {
int change, rem, qs, ds, ns, ps;
System.out.print("Input change amount (1-99): ");
Scanner input = new Scanner(System.in);
change = input.nextInt();
qs = change / 25;
rem = change % 25;
ds = rem / 10;
rem = rem % 10;
ns = rem / 5;
rem = rem % 5;
ps = rem;
System.out.print(qs + " quarters,"
+ ds + " dimes,");
System.out.println(ns + " nickels and"
+ ps + " pennies");
}
45
} (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Reading Input from the Console
1. Create a Scanner object
Scanner input = new Scanner(System.in);
2. Use the methods nextByte(), nextShort(),
nextInt(), nextLong(), nextFloat(),
nextDouble(), nextBoolean() or next() to obtain a
byte, short, int, long, float, double, boolean
or String (up to the first white space) value. For example,
System.out.print("Enter a double value: ");
Scanner input = new Scanner(System.in);
double d = input.nextDouble();
Scanner is in the Java package java.util
- start your program with:
46
import java.util.Scanner;
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Packages in Java
To make types easier to find and use, to avoid naming conflicts, and to
control access, programmers bundle groups of related types into
packages.
The types that are part of the Java platform are members of various
packages that bundle classes by function: fundamental classes are
in java.lang, classes for reading and writing (input and output) are
in java.io and java.util, and so on.
You can put your types in packages too.
To create a package, you choose a name for the package and put
a package statement with that name at the top of every source file that
contains the types (e.g., classes, interfaces). In file Circle.java:
package edu.stonybrook.cse114;
public class Circle {
...
47 } (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Packages in Java
To use a public package member from outside its
package, you must do one of the following:
Import the package member
import java.util.Scanner;
Import the member's entire package
import java.util.*;
Refer to the member by its fully qualified name
java.util.Scanner input =
new java.util.Scanner(System.in);
48
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Packages in Java
Packages appear to be hierarchical, but they are not.
Importing java.awt.* imports all of the types in the java.awt package,
but it does not import java.awt.color, java.awt.font, or any
other java.awt.xxxx packages.
If you plan to use the classes and other types in java.awt.color as well
as those in java.awt, you must import both packages with all their files:
import java.awt.*;
import java.awt.color.*;
50
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Example: ChangeMaker
Problem:
you have to give someone change
what coins do you give that person?
Requirements:
takes user input
displays the change breakdown as output
51
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
ChangeMaker
1. Understand and Define the Problem
ask user for input
US coins (quarter, dime, nickel, penny)
max change: 99¢
display the minimum number of coins (output)
What’s involved?
interview users
What are their expectations?
What data do they need to access?
write a requirements analysis report
52
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
ChangeMaker
2. Determine Input and Output
Typed input by user: amount of change requested (an
integer between 1 and 99)
Printed output:
Number of quarters given
Number of dimes given
Number of nickels given
Number of pennies given
53
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
ChangeMaker
3. Design an algorithm
How many quarters?
subtract the maximum number of quarters X 25c from the total
How many dimes?
subtract the maximum number of dimes X 10c from remaining total
How many nickels?
subtract the maximum number of nickels X 5c from remaining total
How many pennies?
the remaining total
54
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
ChangeMaker
3. Design an algorithm (cont.)
Pseudocode:Use div and mod (remainder operator)
User Inputs originalAmount
numQuarters=originalAmount div 25
remainder =originalAmount mod 25
numDimes =remainder div 10
remainder =remainder mod 10
numNickels = remainder div 5
remainder =remainder mod 5
numPennies =remainder
Output numQuarters
Output numDimes
Output numNickels
Output numPennies
55
(c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
4. Implement (code) the solution
import java.util.Scanner;
public class ChangeMaker {
public static void main(String[] args) {
int change, rem, qs, ds, ns, ps;
System.out.print("Input change amount (1-99): ");
Scanner input = new Scanner(System.in);
change = input.nextInt();
qs = change / 25;
rem = change % 25;
ds = rem / 10;
rem = rem % 10;
ns = rem / 5;
rem = rem % 5;
ps = rem;
System.out.print(qs + " quarters," + ds + " dimes,");
System.out.println(ns + " nickels and" + ps + " pennies");
56
} (c) Pearson Education, Inc. & Paul Fodor (CS Stony Brook)
Extend ChangeMaker to include dollars
Suppose amount is 11.56
int remainingAmount = (int)(amount * 100); remainingAmount 1156
// Find the number of one dollars
int numberOfOneDollars = remainingAmount / 100; remainingAmount
remainingAmount = remainingAmount % 100; initialized