Introduction To Computers and Programming
Lecture 2: Your first program
Professor: Evan Korth
New York University
Errors
• syntax error – Can be picked up by the compiler.
Your program will not compile and the compiler
will try to communicate the location of the error to
you.
• run time or logical error – The compiler cannot
pick up the error because the program is perfectly
legal Java. However, the program does not run as
intended.
2.2
A First Program in Java: Printing a
Line of Text
• Application
– Program that executes using the java interpreter
• Sample program
– Show program, then analyze each line
1 // HelloWorld.java
public class HelloWorld
{
// main method begins execution of Java application
public static void main( String args[] )
{
System.out.println( Hello World!" );
} // end method main
} // end class Welcome1
 Prentice Hall, Inc. All rights reserved.
2.2
1
A First Program in Java: Printing a
Line of Text
// Fig. 2.1: Welcome1.java
– Comments start with: //
(style)
• Comments ignored during program execution
• Document and describe code
• Provides code readability
– Traditional comments: /* ... */
/* This is a traditional
comment. It can be
split over many lines */
• Common error: When using traditional blocks always
remember to close the comment.
– Javadoc comments: /** ... */
/** This is a special type of comment used
by the javadoc command to automatically
create html documentation of classes,
methods and variables */
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Begins body of class declaration for class Welcome1
• Every Java program has at least one user-defined class
• Keyword: words reserved for use by Java
– class keyword followed by class name
– Keywords can only be used for intended purpose(s)
• Modifier: defines attributes of classes, methods and variables
– public tells the compiler which methods can access the
method it modifies. For now, all methods will be declared
public.
• Naming classes: capitalize every word (style)
– SampleClassName
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Name of class called identifier
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value, button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
• Try to use identifiers that “tell the story” of the program.
– For now, use public keyword
• Certain details not important now
• Mimic certain features, discussions later
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
4
A Simple Program: Printing a Line of
Text
public class Welcome1 {
– Saving files
• File name must be class name with .java extension
• Welcome1.java
– Left brace {
• Begins body of every class
• Right brace ends class declaration (line 13)
7
public static void main( String args[] )
– Part of every Java application
• Applications begin executing at main
– Parenthesis indicate main is a method
– Java applications contain one or more methods
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
7
A Simple Program: Printing a Line of
Text
public static void main( String args[] )
• Exactly one method must be called main
– Methods can perform tasks and return information
• void means main returns no information
– More on this later in the semester
• For now, mimic main's first line for subsequent programs
8
{
– Left brace begins body of method declaration for main
method
• Ended by right brace } (line 11)
• Note: Two different acceptable styles in this program.
However, it is bad style to mix these in one program.
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.2
9
A Simple Program: Printing a Line of
Text
System.out.println( "Welcome to Java Programming!" );
– Instructs computer to perform an action
• Prints string of characters
– String - series characters inside double quotes
• White-spaces in strings are not ignored by compiler
– System.out
• Standard output object
• Print to command window (i.e., MS-DOS prompt)
– Method System.out.println
• Displays line of text
• Argument inside parenthesis
– This line known as a statement
• A statement is an instruction or a method call
– An instruction is the smallest executable entity within a
programming language
• Statements must end with semicolon ;
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
blocks
• Any code enclosed between braces is called a
block.
• In the previous program there were two blocks.
– The class block (a block is required for a class)
– The method block (a block is required for a method)
• These are just two types of blocks. We will see
others later in the semester.
• Good Programming Habit: Get into the habit of
adding the right brace as soon as you enter the left
brace (then fill in between).
 Prentice Hall, Inc. All rights reserved.
2.2
A Simple Program: Printing a Line of
Text
• Executing a program
– Type java Welcome1
• Interpreter loads .class file for class Welcome1
• .class extension omitted from command
– Interpreter calls method main
Fig. 2.2
Executing Welcome1 in a Microsoft Windows 2000 Command Prompt.
 Prentice Hall, Inc. All rights reserved.
2.3
Modifying Our First Java Program
• Modifying programs
– Welcome2.java (Fig. 2.3) produces same output as
Welcome1.java (Fig. 2.1)
– Using different code
9
10
System.out.print( "Welcome to " );
System.out.println( "Java Programming!" );
– Line 9 displays “Welcome to ” with cursor remaining on
printed line
– Line 10 displays “Java Programming! ” on same line with
cursor on next line
 Prentice Hall, Inc. All rights reserved.
2.3
Modifying Our First Java Program
• Newline characters (\n)
– Interpreted as “special characters” by methods
System.out.print and System.out.println
– Indicates cursor should be on next line
– Welcome3.java (Fig. 2.4)
9
System.out.println( "Welcome\nto\nJava\nProgramming!" );
– Line breaks at \n
• Usage
– Can use in System.out.println or
System.out.print to create new lines
• System.out.println(
"Welcome\nto\nJava\nProgramming!" );
 Prentice Hall, Inc. All rights reserved.
2.3
Modifying Our First Java Program
Escape characters
– Backslash ( \ )
– Indicates special characters be output
Esc a p e
De sc rip tio n
se q ue nc e
\n
Newline. Position the screen cursor at the beginning of the
next line.
\t
Horizontal tab. Move the screen cursor to the next tab stop.
\r
Carriage return. Position the screen cursor at the beginning of
the current line; do not advance to the next line. Any
characters output after the carriage return overwrite the
characters previously output on that line.
\\
Backslash. Used to print a backslash character.
\"
Double quote. Used to print a double-quote character. For
example,
System.out.println( "\"in quotes\"" );
displays
"in quotes"
Fig. 2.5 So m e c o m m o n e sc a p e se q ue nc e s.
 Prentice Hall, Inc. All rights reserved.
2.4
Displaying Text in a Dialog Box
• Display
– Most Java applications use windows or a dialog box
• We have used the command window
– Class JOptionPane allows us to use dialog boxes
• Packages
– Set of predefined classes for us to use
– Groups of related classes called packages
• Group of all packages known as Java class library or Java
applications programming interface (Java API)
– JOptionPane is in the javax.swing package
• Package has classes for using Graphical User Interfaces (GUIs)
 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1// //
Fig.
2.6:
Welcome4.java
Fig.
2.6:
Welcome4.java
// Printing multiple lines in a dialog box.
2 // Printing multiple lines in a dialog box
3// import
javax.swing.JOptionPane; // import class JOptionPane
Java packages
4import javax.swing.JOptionPane; // program uses JOptionPane
5 public class Welcome4 {
public class Welcome4 {
6
public static void main( String args] )
// main method begins execution of Java application
7
{
public static void main( String args[] )
8
JOptionPane.showMessageDialog(
{
JOptionPane.showMessageDialog(
9
null, "Welcome\nto\nJava\nProgramming!" );
null, "Welcome\nto\nJava\nProgramming!" );
10
11
12
System.exit(
0 );
terminate
application
with window
System.exit(
0 );// //
terminate
the program
}
} // end method main
} // end class Welcome4
Outline
Welcome4.java
1. import
declaration
2. Class Welcome4
2.1 main
2.2
showMessageDial
og
2.3 System.exit
Program Output
 Prentice Hall, Inc.
All rights reserved.
2.4
Displaying Text in a Dialog Box
– Lines 1-2: comments as before
4
// Java packages
– Two groups of packages in Java API
– Core packages
• Begin with java
• Included with Java 2 Software Development Kit
– Extension packages
• Begin with javax
5
– import declarations
import javax.swing.JOptionPane;
// program uses OptionPane
• Used by compiler to identify and locate classes used in Java
programs
• Tells compiler to load class JOptionPane from
javax.swing package
 Prentice Hall, Inc. All rights reserved.
2.4
Displaying Text in a Dialog Box
– Lines 6-11: Blank line, begin class Welcome4 and main
12
13
JOptionPane.showMessageDialog(
null, "Welcome\nto\nJava\nProgramming!" );
– Call method showMessageDialog of class
JOptionPane
• Requires two (or more) arguments
• Multiple arguments separated by commas (,)
• For now, first argument always null
• Second argument is string to display
– showMessageDialog is a static method of class
JOptionPane
• static methods called using class name, dot (.) then method
name
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
2.4
Displaying Text in a Dialog Box
– All statements end with ;
• A single statement can span multiple lines
• Cannot split statement in middle of identifier or string
– Executing lines 12 and 13 displays the dialog box
• Automatically includes an OK button
– Hides or dismisses dialog box
• Title bar has string Message
 Prentice Hall, Inc. All rights reserved.
2.4
15
Displaying Text in a Dialog Box
System.exit( 0 );
// terminate application with window
– Calls static method exit of class System
• Terminates application
– Use with any application displaying a GUI
• Because method is static, needs class name and dot (.)
• Identifiers starting with capital letters usually class names
– Argument of 0 means application ended successfully
• Non-zero usually means an error occurred
– Class System part of package java.lang
• No import declaration needed
• java.lang automatically imported in every Java program
– Lines 17-19: Braces to end Welcome4 and main
 Prentice Hall, Inc. All rights reserved.
Variables
Variables
• Variable: a small piece or “chunk” of data.
• Variables enable one to temporarily store data
within a program, and are therefore very useful.
Note: variables are not persistent. When you exit
your program, the data is deleted. To create
persistent data, you must store it to a file system.
Data Types
• Every variable must have two things: a data type and a
name.
• Data Type: defines the kind of data the variable can hold.
– For example, can this variable hold numbers? Can it
hold text?
– Java supports several different data types. We are only
going to look at a few today.
Java’s (primitive) Data Types
• integers: the simplest data type in Java. Used to
hold positive and negative whole numbers, e.g. 5,
25, -777, 1. (Java has several different integer
types)
• Floating point: Used to hold fractional or decimal
values, e.g. 3.14, 10.25. (Java has two different
floating point types)
• chars: Used to hold individual characters, e.g. 'c',
'e', '1', '\n'
• boolean: Used for logic.
• We will explore each one in detail later this
semester.
Bucket Analogy
• It is useful to think of a variable as a bucket of
data.
• The bucket has a unique name, and can only hold
certain kinds of data.
200
balance
balance is a variable
containing the value
200, and can contain
only integers.
Memory Concepts
• Variable names correspond to locations in the
computer’s primary memory.
• Every variable has a name, a type and a value.
• When a value is placed in a memory location the
value replaces the previous value in that location
(called destructive read-in)
• A variable’s value can just be used and not
destroyed (called non-destructive read-out)
Variable Declaration
• Before you use a variable, you must declare it. (Not all
languages require this, but Java certainly does.)
• Examples:
/* Creates an integer variable */
int number;
/* Creates two double variables */
double price, tax;
/* Creates a character variable */
char letter;
semi-colon
data type
identifier
2.2
Rules for identifiers
• Series of characters consisting of letters, digits,
underscores ( _ ) and dollar signs ( $ )
• Does not begin with a digit, has no spaces
• Examples: Welcome1, $value, _value,
button7
– 7button is invalid
• Java is case sensitive (capitalization matters)
– a1 and A1 are different
– Try to use identifiers that “tell the story” of the program.
• Cannot use reserved words
• Try not to redefine identifiers used elsewhere.
 Prentice Hall, Inc. All rights reserved.
(modified by Evan Korth)
Reserved Words (added to previous definition of identifiers)
• Certain words have special meaning in Java and cannot be
used as identifiers. These words are called reserved words.
• So far we have seen the following reserved words:
–
–
–
–
–
–
int
public
import
static
void
class
• We will see a complete list of reserved words soon.
• Use of the words null, true and false is also prohibited.
Example 1: Basic Arithmetic
/* Illustrates Integer Variables */
public class Sample {
public static void main(String args[])
Variable Declarations
{
int x;
Variable Name
int y;
int z;
semicolon
Data Type
x = 5;
y = 10;
z = x + y;
Assignment Statements
System.out.println ("x:
System.out.println ("y:
System.out.println ("z:
} // end method main
} // end class Sample
" + x);
" + y);
" + z);
x:
y:
z:
5
10
15
Assignment Statements
• Assignment statements enable one to assign (initial or not)
values to variables or perform basic arithmetic.
x = 5;
y = 10;
z = x + y;
• Here, we simply initialize x and y and store their sum
within the variable z.
Note: If you forget to initialize your variables, the
variable may contain any value. This is referred to as a
garbage value. Hence, always initialize your variables!
Java enforces this rule; but, not all languages do.
Assignment Operator
• =
• Read the assignment operator as “GETS” not
“EQUALS!”
• This is an assignment of what’s on the right side
of = to a variable on the left
• eg sum = integer1 + integer2;
– Read this as, “sum gets integer1 + integer2”
– integer1 and integer2 are added together and stored in sum
Printing Variables
• To print a variable, use the System.out.print or
System.out.println statement as you would for a
string.
System.out.print (x);
System.out.println (x);
System.out.println ("x:
" + x);
Here the “addition” that
is performed is string
concatenation.
Initialization
• When you declare a primitive variable, you do not
know the value stored in that variable until you
place something there. The language specification
does not guarantee any initial value.
• Until the user initializes the value, the value stored
in that memory is called a garbage value.
• Java will not allow you to use the garbage value in
a calculation or for output. If it is possible that a
variable has not been initialized when you try to
use it, you will get a compilation error.
• So you must initialize the variable before you use
it on the right hand side of a calculation or output
it to the screen.
Good Programming Style




Choose meaningful variable names to make your
program more readable. For example, use income,
instead of num.
Stick to lower-case variable names. For example, use
income, instead of INCOME. Variables that are all
capitals usually indicate a constant (more on this
soon.)
Use "proper case" for all words after the first in a
variable name. For example, instead of
totalcommissions, use totalCommissions.
Avoid redefining identifiers previously defined in the
Java API.
Revisit Errors
Syntax Errors
• Caused when the compiler cannot recognize a
statement.
• These are violations of the language
• The compiler normally issues an error message to
help the programmer locate and fix it
• Also called compile errors or compile-time errors.
• For example, if you forget a semi-colon, you will
get a syntax error.
Run-time Errors
• The compiler cannot pick up on runtime errors.
Therefore they happen at runtime.
• Runtime errors fall into two categories.
– Fatal runtime errors: These errors cause your program to
crash.
– Logic errors: The program can run but the results are not
correct.
2.5
Another Java Application: Adding
Integers
• Upcoming program
– Use input dialogs to input two values from user
– Use message dialog to display sum of the two values
 Prentice Hall, Inc. All rights reserved.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Fig. 2.9: Addition.java
// Addition program that displays the sum of two numbers.
// Java packages
import javax.swing.JOptionPane;
Outline
Addition.java
// program uses JOptionPane
1. import
public class Addition {
name and
// main method begins executionDeclare
of Javavariables:
application
public static void main( String args[] )
{
String firstNumber;
// first string entered by user
String secondNumber; // second string entered by user
int number1;
int number2;
int sum;
type.
// first number to add
Input
first integer
// second
number
to add as a String,
// sum to
offirstNumber.
number1 and number2
2.1 Declare variables
(name and type)
assign
// read in first number from user as a String
firstNumber = JOptionPane.showInputDialog( "Enter first integer" );
// read in second number from user as a String
secondNumber =
JOptionPane.showInputDialog( "Enter second integer" );
2. class Addition
3.
showInputDialog
4. parseInt
5. Add numbers, put
result in sum
Convert strings to integers.
// convert numbers from type StringAdd,
to type
placeint
result
number1 = Integer.parseInt( firstNumber );
number2 = Integer.parseInt( secondNumber );
// add numbers
sum = number1 + number2;
in sum.
 Prentice Hall, Inc.
All rights reserved.
33
34
35
36
37
38
39
40
41
// display result
JOptionPane.showMessageDialog( null, "The sum is " + sum,
"Results", JOptionPane.PLAIN_MESSAGE );
System.exit( 0 );
Outline
// terminate application with window
} // end method main
} // end class Addition
Program output
 Prentice Hall, Inc.
All rights reserved.
2.5
Another Java Application: Adding
Integers
Messa g e d ia lo g typ e
Ic o n
Desc rip tio n
JOptionPane.ERROR_MESSAGE
Displays a dialog that indicates an error
to the user.
JOptionPane.INFORMATION_MESSAGE
Displays a dialog with an informational
message to the user. The user can simply
dismiss the dialog.
JOptionPane.WARNING_MESSAGE
Displays a dialog that warns the user of a
potential problem.
JOptionPane.QUESTION_MESSAGE
Displays a dialog that poses a question to
the user. This dialog normally requires a
response, such as clicking on a Yes or a
No button.
JOptionPane.PLAIN_MESSAGE
Displays a dialog that simply contains a
message, with no icon.
Fig. 2.12 JOptionPane c o nsta nts fo r m essa g e d ia lo g s.
 Prentice Hall, Inc. All rights reserved.
no icon
CPAC
Mathematical Operators
Professor: Evan Korth
New York University
Basic Mathematical Operators
Java
Operation
Addition
Arithmetic Algebraic Java
Operator
Expression Expression
+
a+b
a+b
Subtraction
-
a–b
a–b
Multiplication
*
ab
a*b
Division
/
a/b
a/b
Modulus
%
a mod b
a%b
Each of the operators in the table are binary operators. A binary operator acts
on two operands
Integer Division - The Problem
• Suppose you have the following code:
int x;
x = 7 / 4;
• Using a calculator, the answer is 1.75.
• But x can only hold integer values. 1.75 is clearly
not an integer value.
Integer Division - Solution
• To understand the solution, you need to remember
your 3rd Grade Math (really.)
1
4
7
4
3
The answer: 1 remainder 3
• 7/4 = 1 (Integer Division)
• 7%4 = 3 (Modulus Division)
Example: Integer Division
// Integer and Modulus Division
public class DivMod
{
public static void main( String args[] )
{
int x = 5, y = 10;
System.out.println ("5 / 10: " + x/y);
System.out.println ("5 % 10: " + x%y);
}
}
5 / 10: 0
5 % 10: 5
Modulus Division (cont.)
• Second Example:
5/10 = 0
5%10 = 5
1
0
0
5
0
5
• No matter what, your answers must be integers.
Odd / Even Numbers
• Modulus division can also be used to determine
whether a number is odd or even.
• Just divide by 2. If the remainder (modulus) is 0,
the number is even.
• Examples:
– 10 % 2 = 0. Hence 10 is even.
– 11 % 2 = 1. Hence 11 is odd.
Common Programming Error: Dividing by zero
is
normally undefined on computer systems and
generally results in a fatal error.
Operator Precedence
Operator Precedence
• Here’s another problem. What’s the answer to this?
x = 7 + 3 * 6;
• Two Options (depending on the order of operations):
Perform addition first: 7 + 3 = 10  10
* 6 = 60
Perform multiplication first: 3*6 =18 
7+18 = 25
• Which option is correct? Clearly, we cannot have this kind
of ambiguity.
Operator Precedence
• Operator precedence represent rules for evaluating
mathematical expressions.
• Every programming language has similar rules.
Operator(s)
()
Operation(s)
Parentheses
*, /, or %
Multiplication
Division
Modulus
Addition
Subtraction
+ or -
 Prentice Hall, Inc. All rights reserved.
Order of evaluation (precedence)
Evaluated first. If the parentheses are nested, the
expression in the innermost pair is evaluated first. If there
are several pairs of parentheses “on the same level” (i.e.,
not nested), they are evaluated left to right.
Evaluated second. If there are several, they are
evaluated left to right.
Evaluated last. If there are several, they are
evaluated left to right.
Operator Precedence
• Hence, option #2 is always correct (multiplication
is performed first):
x = 7 + 3 * 6;
Evaluates to x = 7 + 18 = 25
• Example: Find the average of three variables a, b
and c
• Do not use: a + b + c / 3
• Use: (a + b + c ) / 3
Parentheses
• Are your friends
• Are your really good friends
• Because with them you can ensure expressions
are evaluated as you expect
• Can avoid mistakes with operator precedence
(one less thing to think about)
– e.g. y
y
– e.g. y
y
=
=
=
=
m * x + b
(m * x) +
a * b * b
(((a * b)
;
b;
+ c * b – d;
* b) + (c * b)) – d;
Floating Point Data Types
double Data Type
• Data type that can hold numbers with fractional
values
– e.g. 3.14, 98.6
• Doubles can be used to represent many values:
– Money (but see warning below)
– distance
– weight, etc.
double Example
// Double Example Program
public class Double
{
public static void main( String args[] )
{
double var1, var2, var3, sum;
var1 = 87.25;
var2 = 92.50;
var3 = 96.75;
sum = var1 + var2 + var3;
System.out.println ("Sum:
}
}
" + sum);
Sum: 276.5
Numeric type ranges in Java
Integers
byt e
shor t
i nt
l ong
8 bits
16 bits
32 bits
64 bits
-128
-32768
-2,147,483,648
-9,223,372,036,854,770,000
127
32767
2,147,483,647
9,223,372,036,854,770,000
Floating point values
float
double
32 -3.40282347E+38
64 -1.79769313486231570E+308
3.40282347E+38
1.79769313486231570E+308
Example: Find an Average
• Suppose you want to determine a student’s
average.
int totalTests = 4;
double average = 90+92+95+100/ totalTests;
Rules of Promotion
• Promotion: when mixing integers and doubles, all
the values are promoted to doubles.
• In our average example, there are several ways to
force promotion, and get the right answer of
94.25:
1. change totalTests to a double:
double totalTests = 4.0;
double average = (90+92+95+100)/ totalTests;
2. Cast a lhs value to a double:
constants
final int TOTAL_GRADES
= 4;
• Used to avoid “magic numbers” in code.
– Only need to change in one place
• If not, best case must search entire code, worst case you miss a
few occurrences.
– Choose meaningful names for your constants as you would
for any other identifier
• Unlike variables, you cannot change the value of a
symbolic constant.
• Should be in ALL CAPS (style).
more on casting
• In an assignment statement, you can assign a value
of a “less expressive” type to a variable which is
“more expressive”. For example:
– int gets byte
– double gets int
– double gets float
• You must explicitly cast a value of a “more
expressive” type to a variable which is “less
expressive”. For example:
–
–
–
–
byte gets (byte) int
int gets (int) double
float gets (float) double
If you do not explicitly cast these values, you will have a
syntax error in Java.
Warning about floating point values
• Floats may be represented differently from what
you think by the computer
– E.g. 1.9 to you may be 1.89999999999999999999999
– 1.9 will not necessarily equal 1.9!
• In critical calculations for the same reason
– E.g. .1 added 10 times often will not add up to 1
– Use long integers instead and keep track of where your
decimal point is (e.g. $1.75 should be stored as 175)
char data type
char data type
•
•
•
•
•
•
•
•
Java allows us to store "single" character values.
char character = 'a'; // not the same as "a";
char character = '7';
char newline = '\n';
char tab = '\t';
char space = ' ';
The characters are actually stored as integers (ascii values).
See http://asciitable.com/
• Note: chars use single quotes. We have seen that
Strings use double quotes.
ASCII Table
Source: Liang
char arithmetic
• Given:
char letter = 'a';
• The following code:
letter = (char) (letter + 1);
• Would result in letter storing a 'b' character.
• If we add or subtract two char values, the result is
an int value.
– For example 'c' – 'a' would result in the value 2.
Reading char values from the user
• You should use charAt(0) to parse the
character from user input.
• For example:
char c;
String cAsString;
cAsString = JOptionPane.showInputDialog
(null, "Enter a character");
c = cAsString.charAt(0);
• Will grab the first character from the user's input.
Casting between char and int values
• A char uses 16 bits of memory.
– You can implicitly cast a char to an int
char c = 'a';
int i = c;
– You must explicitly cast an int to a char
int i = 65;
char = (char) i;
• Note: Even though chars are equal to shorts in the
amount of memory they use, they do not hold the
same values (shorts can hold negative integers).
Warning about numeric digit characters
• The value of a the single digit numeric characters
are not equivalent to the values themselves. In
fact the ASCII value of '0' is 48, '1' is 49, …, '9' is
57.
• How do you think we could convert a numeric
char to an int?
CPAC
Boolean type; if statement
Professor: Evan Korth
New York University
Boolean values
• Java provides a type just for true and false
evaluation.
• Named after George Boole, the English
mathematician who published “An investigation
into the Laws of Thought” in 1854 which began
Boolean logic.
• Any Boolean expression will evaluate to either
true or false.
Relational Operators
Operator
Meaning
>
Greater than
<
Less than
>=
<=
Greater than or equal
to
Less than or equal to
==
Equal to
!=
Not Equal to
 Prentice Hall, Inc. All rights reserved.
Example
import javax.swing.JOptionPane;
public class BoolTest
{
public static void main(String[] args)
{
boolean boolVar;
}
}
boolVar: false
boolVar = false;
System.out.println ("boolVar: " + boolVar);
boolVar: true
int a = 10;
int b = 10;
boolVar = ( a == b);
System.out.println ("boolVar: " + boolVar);
false
System.out.println (a == b);
System.out.println (a != b);
System.out.println (a < b);
System.out.println (a <= b);
System.out.println (a > b);
System.out.println (a >= b);
false
true
false
true
true
Equality v. Assignment
• Remember Gets not Equals!
( grade = 100 )
Will not evaluate to true or false
• In this case, we are using a single = character.
(We really want to use ==)
Introduction to Problem Solving with Computers
• Before writing a program:
– Have a thorough understanding of the problem
– Carefully plan an approach for solving it
• While writing a program:
– Know what “building blocks” are available
– Use good programming principles
Algorithms
• Computing problems
– All can be solved by executing a series of actions in a
specific order
• Algorithm: procedure in terms of
– Actions to be executed
– The order in which these actions are to be executed
• Program control
– Specify order in which statements are to executed
• Examples of problems:
– Determining the class average for a final exam
– Sorting a list of names in alphabetical order
 Prentice Hall, Inc. All rights reserved.
Pseudocode
• Pseudocode
– Artificial, informal language that helps us develop
algorithms
– Similar to everyday English
– Not actually executed on computers
– Helps us “think out” a program before writing it
• Easy to convert into a corresponding Java program
• Consists only of executable statements
– For example, declarations and import statements are not
used in pseudocode.
 2000 Prentice Hall, Inc. All rights reserved.
What is a “Flow Chart?”
• A flow chart is a visual tool that helps you
understand the flow of your program.
– Graphical representation of program structure
• Different shapes have different meaning.
Flow Chart Basics 1
Connector
symbol
flow
line
Diamonds
(decision symbol)
contain
conditions
Rectangles represent
statements of work.
For example:
flow
line
System.out.println();
Control Structures
Control Structures
• Control the flow of a program
• Normally, in Java, statements are executed in
sequential order
• Control structures allow the programmer to
specify that a statement other than the next be
executed
– i.e. programmer can control what’s executed in which order
Three Basic Control Structures
• All programs can be written with just these types
of structures
– Sequence structure
• Statements run one after the other
– Selection structure
• Depending on a condition, do one thing; otherwise, do
something else
• Examples in Java: if, if else, and switch.
– Repetition structure
• Repeat some actions over and over
• Examples in Java: for loops, while loops, and do/while loops.
The if structure
• Pseudocode:
if some Boolean expression is true
do this
• Example:
if ( x == y )
{
System.out.println(" x is equal to y!" ) ;
}
• Every procedural / OO programming language has
some form of an if statement.
Another if example
if ( temperature >= 85 )
{
System.out.println( "It is hot out!" );
}
if Flow Chart
temperature >=85
false
true
print “It is hot”
if with a twist: if else
• Pseudocode:
if some Boolean expression is true
do this
otherwise
do something else
• Example:
if ( grade >= 65 )
System.out.println( "You passed!" );
else
System.out.println( "You failed!" );
if/else Flow Chart
False
True
grade
>=60
Print “You
failed”
Print “You
passed”
Blocks
• To run several lines of code together,
you must include them within a block
• For example:
if ( grade >= 60 )
{
System.out.println ( "You passed!" );
System.out.println ( "Congratulations!" );
}
Indentation
• Everything within the block of code (even if it is
an implicit block because we only use one
statement) should be indented
– helps you see the block at a quick glance.
• Avoid writing code like this:
if (grade >= 65) {
System.out.println("You passed!!!\n");
System.out.println ("Congratulations!\n");
}
• This is valid Java code, but it is not easy to view
the block: bad style
Common error: misplaced semi-colon
• Remember, Java requires that you use a semicolon
to terminate a statement.
• A complete if statement is formed as follows:
if (boolean expression)
Statement or block of code;
• Therefore, if you place a semicolon after the
conditional as in
if (boolean expression);
Statement or block of code;
The compiler will interpret the semicolon as a null statement. In other
words, nothing will happen if the expression evaluates to true and the
statement of block of code will be executed whether or not the boolean
expression is true.
Example
import javax.swing.JOptionPane;
public class PassFail
{
public static void main(String[] args)
{
int grade;
String gradeAsString;
gradeAsString = JOptionPane.showInputDialog(null,"What is your grade?");
grade = Integer.parseInt (gradeAsString);
/* find out if grade is passing */
if ( grade >= 65 )
{
System.out.println ( "You passed!!!" );
System.out.println ( "Congratulations!" );
}
else
{
System.out.println ("You failed!");
}
System.exit (0);
}
}
Java Provides a shortcut if/else operator:
• This is Java’s only ternary operator (i.e. it takes three operands)
System.out.println ( (sales > 100) ? "Federal Express" : "US Mail");
The
conditional
Statement.
? shortcut operator
True
Option
colon
False
Option
nested if statements
• When one if/else structure is contained
inside another if/else structure it is called
a nested if/else.
if (grade > 60)
{
if (grade > 70)
System.out.println("You passed");
else
System.out.println("You passed but need a tutor");
}
else
System.out.println("You failed");
else if
• Usually you try to nest within the else statement. Note
the indentation.
if (grade > 70)
System.out.println("You passed");
else if (grade > 60)
System.out.println("You passed but need a tutor");
else
System.out.println("You failed");
Choosing the flavor of your if
•
When you have multiple possible branches, you
can have any of the following situations:
1. You want to execute exactly one of the branches
2. You want to execute zero or one of the branches
3. You want to execute zero or more branches
•
1–c
2–b
Which would be appropriate for each of the
3–a
situations above:
a) A series of ifs
b) A series of if / else ifs ending with an else if
c) A series of if / else ifs ending with an else
Using boolean variables as flags
• You may want to use boolean variables to hold the
value of a boolean expression.
• For example:
boolean passed = (grade >= 65)
• Then you can use the variable later in a
conditional statement:
if (passed)
System.out.println ("You passed");
else
System.out.println ("You failed");
&& - Logical AND
((boolean exp a) && (boolean exp b))
• When using the and operator (&&), both
expression a and b must be true for the compound
statement to be true.
truth table
F A LS E
TR U E
F A LS E
F A LS E
F A LS E
TR U E
F A LS E
TR U E
• For example:
((total > 50) && (status == 0))
|| - Logical OR
((boolean exp a) || (boolean exp b))
• When using the or operator (||), at least one
expression a or b must be true for the compound
statement to be true.
truth table
F A LS E
TR U E
•
F A LS E
F A LS E
TR U E
TR U E
TR U E
TR U E
For example:
((total > 50) || (status == 0))
^ - Exclusive OR
((boolean exp a) ^ (boolean exp b))
• When using the exclusive or operator (^), at least
one expression a or b must have opposite Boolean
values for the compound statement to be true.
truth table
FALSE
TRUE
•
FALSE
FALSE
TRUE
TRUE
TRUE
FALSE
For example:
((person1 == 1) ^ (person2 == 1))
logical negation !
!(a)
• Reverses the truth or falsity of expression a
Boolean expression
• ! has high precedence so you must use parenthesis
• You can avoid using the logical negation by
expressing the condition differently with an
appropriate relational operator. However, in the
case of complex expressions, it is sometimes
easier to use negation.
• Note: its a unary operator
Unconditional vs. Conditional Boolean
Operators
• Java provides us with a second “and” operator and
a second “or” operator.
• The unconditional operators guarantee that both
expressions will be evaluated
• In this class, you should just use the conditional
operators.
switch Multiple-Selection Structure
• Used when testing a variable or expression for
EQUALITY (ie no >, <, >=, <= tests) separately
for each of the constant integral values it may
assume.
• Preferred over if else in situations where you are
testing the same expressions for equality with
many different values.
• Allows you to perform different actions for each
value.
switch Multiple-Selection Structure
switch (expression) {
case value1:
action(s);
break;
keyword switch
expression can be a variable or
a more complicated expression
case value2:
action(s);
break;
…
default:
actions(s);
break;
}
could use more than one case;
if the same actions are required
actions within a single case do
not need brackets
the default case will be executed
in the event that no other case is
The switch Multiple-Selection Structure
• Flowchart of the switch structure
case a
true
case a action(s)
break
false
case b
true
case b action(s)
break
false
.
.
.
case z
true
case z action(s)
break
false
default action(s)
 2000 Prentice Hall, Inc.
All rights reserved.
beware of “fall through”
• If you forget to use the break keyword between
cases, unexpected things may happen.
• Once a case tests true, all the statements following
that case, will be executed until the next break.
• Experienced programmers may use this on
purpose. For this class we will rarely use fall
though.
Style Considerations
Initialization (revisited)
• When you declare a primitive variable, you do not
know the value stored in that variable until you
place something there. The language specification
does not guarantee any initial value.
• Until the user initializes the value, the value stored
in that memory is called a garbage value.
• Java will not allow you to use the garbage value in
a calculation or for output. If it is possible that a
variable has not been initialized when you try to
use it, you will get a compilation error.
• So you must initialize the variable before you use
it on the right hand side of a calculation or output
it to the screen.
Principle of Proximity
• Advanced tip for initialization
• Initialize your variables close to where you use
them if possible
– Avoid mistakes about value when using late in code
(something modified it?)
Line Continuations
• Pick good spots to break up a long line
– Break so it’s obvious from reading a line there should be more
• E.g.
if ( (totalSaleBeforeTax > 100) &&
(isPreferredCustomer) )
System.out.print("");
– Note, the dangling && should alert reader to a break
Braces
• Whenever adding a left brace to denote a block or
method start, add the right brace right away and
then fill between them
• Put a comment after the right brace!
if ( MyGrade < YourGrade )
{
} /* end if (MyGrade < YourGrade) */
else
{
} /* end else of (MyGrade < YourGrade) */
} /* end program */
• Use curly braces even if you only have one
statement as the body of a control structure.
indentation
• Place the brace associated with a control
statement (or method / class header) on the next
line, indented to the same level as the control
statement.
• Statements within the braces are indented to the
next level.
• For example:
public class
{
public static void main…
…
}
HW submissions
• For this class you should have a comment like the
following:
/**********************************
* [GENERAL INTRODUCTION WITH THE
* TITLE OF YOUR PROGRAM]
* Written by [YOUR NAME]
* Date: [MONTH DAY, YEAR]
* NYU ID: [YOUR N-NUMBER]
**********************************/
• Outside of class you should also have a similar
comment describing your .java file.
Assignment Operators
• Given the following:
x = 2;
x = x + 1;
System.out.println ("x: " + x);
• There are actually several ways to rewrite this
more concisely.
Short Cut Operator
• One option is to use the += operator
x = 2;
x += 1; // same as x = x + 1;
System.out.println ("x: " + x);
• There are similar operators for *, -, /.%
–
–
–
–
x
x
x
x
=
=
=
=
x
x
x
x
*
–
/
%
5
5;
5;
5;
is
is
is
is
equivalent
equivalent
equivalent
equivalent
to
to
to
to
x
x
x
x
*=
-=
/=
%=
5;
5;
5;
5;
• Good Practice: place a space before and after your
short cut operators.
Increment Operator
• A second option is to use an increment operator:
x++
Post-Increment Operator
++x
Pre-Increment Operator
• Both operators will increment x by 1, but they do
have subtle differences.
Pre v. Post Increment
• PostIncrement Operator (x++):
– use the current value of x in the expression.
Then, increment by 1.
• PreIncrement Operator (++x):
– Increment x by 1. Then, use the new value of x
in the expression.
How about a real example?
// Preincrementing v. PostIncrementing
public class PrePost
{
public static void main (String[] args)
{
Post Increment
int c = 5;
Output:
System.out.println (c);
5
System.out.println (c++);
System.out.println (c);
5
System.out.println();
6
c = 5;
System.out.println (c);
System.out.println (++c);
5
System.out.println (c);
6
}
}
Pre Increment
 2000 Prentice Hall, Inc. All rights reserved.
6
Modified by Evan Korth
Pre v. Post Decrement
• PostDecrement Operator (x--):
– use the current value of x in the expression.
Then, decrease by 1.
• PreDecrement Operator (--x):
– Decrease x by 1. Then, use the new value of x
in the expression.
• Good practice: Place unary operators
directly next to their operands, with no
intervening spaces.
Introduction to While Loops
While Loops
• While Loop: Keep repeating an action while some
condition remains true.
• Examples:
– Every Stairmaster Machine contains a while
loop (end condition is based on mode used).
• while the person is still climbing, keep
displaying the status, e.g. number of stairs
climbed, calories burned, etc.
– Keep prompting for book orders until the user
is done.
while loop (continued)
• For example (in pseudocode)
while (some Boolean expression is true)
{
do this (again and again...)
}
Parts of a While Loop
•
Every while loop will always contain three main
elements:
1) Priming: initialize your variables.
2) Testing: test against some known condition.
3) Updating: updates part (or all) of the
expression that is tested.
Simple While Loop
public class While1
{
public static void main (String args[])
{
1. Priming
int index = 1;
while (index <= 10)
2. Test Condition
{
System.out.println ("Index: " + index);
index++;
Index: 1
3. Update: In this
}
Index: 2
case, you can use
}
either the pre or post
Index: 3
}
increment operator.
...
Index:
8
Index:
9
Index:
10
While Loop Flowchart
1. Priming
Set index=1
2. Test
index
<= 10
FALSE
TRUE
3. Print value of
index
Update index++
Infinite Loop
• Infinite Loop: A loop that never ends.
– Generally, you want to avoid these!
– There are special cases, however, when you do
want to create infinite loops on purpose.
• Common Exam Questions:
– Given a piece of code, identify the bug in the
code.
– You may need to identify infinite loops.
Infinite Loop Example #1
public class While2
{
public static void main (String args[])
{
int index = 1;
while (index <= 10)
{
System.out.println ("Index: " + index);
}
Index:
}
Index:
}
Here, I have deleted part 3:
The update statement (index++).
1
1
Index:
1
Index:
1
Index:
1
…
[forever]
Infinite Loop, Example #2
public class While3
{
public static void main (String args[])
{
int index = 1;
while (index >= 0)
{
System.out.println ("Index: " + index);
index++;
Index:
}
Here, I have changed Index:
}
Index:
}
Part 2: the test
condition.
1
2
3
Index:
4
Index:
5
…
[forever]
While Loops: Examples
While Loop Example
• Specification for the program:
– Find the first power of 2 larger than 1000.
• For example: 2, 4, 8, 16, 32, etc. are powers of 2.
– Which is the first power of 2 larger than 1000?
– Finding the answer to this requires some kind of a while
loop.
– Let’s see how…
 2000 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
While Loop Example
• Example:
int product = 2;
while ( product <= 1000 )
product = 2 * product;
product <= 1000
false
 2000 Prentice Hall, Inc. All rights reserved.
true
product = 2 * product
public class PowerOfTwoOver1000
{
public static void main (String args[])
{
int product = 2;
while ( product <= 1000 )
product = 2 * product;
System.out.println (product);
}
}
 2000 Prentice Hall, Inc. All rights reserved.
Sentinels
Sentinel-controlled repetition
• Counter Controlled Repetition:
– Simply means that we use a counter to tell you when to stop
repeating a statement or group of statements
– The examples from last class were counter-controlled
repetition
• However, what if we want the user or the input to
decide when to end the program?
– Use a sentinel
Understanding Sentinels
• Sentinel: a special value that indicates the “end of
data entry.”
• Also known as signal value, dummy value, or flag
value
• For example:
–
–
–
–
-1 means end of data.
0 means end of data.
"END" means ends of data
Depends on the specific application you are building.
• With a sentinel, we have an indefinite repetition,
because the number of repetitions is unknown at
the time we write the program (or start the loop).
 2000 Prentice Hall, Inc. All rights reserved.
Modified by Evan Korth
Using Sentinels
• How are they used?
– Programmer picks a value that would never be encountered
for normal data
– User enters normal data and then when done, enters the
sentinel value
• The loop will stop when seeing the sentinel
valueFor example, if entering age for people,
could pick a sentinel of –1
• No one would expect to be –1 year old.
• Good practice is to remind the user in each
iteration of the loop what the sentinel value is
– For example: System.out.println
(" Enter age of current resident or –1 to end" );
/*
A sentinel controlled loop */
/*
A simple census taker */
import javax.swing.JOptionPane;
public class Sentinel
{
public static void main(String [] args)
{
int currentAge = 0 ;
String currentAgeAsString;
/*
priming */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident:
") ;
currentAge = Integer.parseInt (currentAgeAsString);
/* testing:
keep going until input is sentinel value */
while (currentAge != -1)
{
/* do some calculations with age, e.g. AVERAGE */
/*updating: get the next value from the user */
currentAgeAsString = JOptionPane.showInputDialog ("Enter age of resident:
currentAge = Integer.parseInt (currentAgeAsString);
}
System.exit (0);
}
}
") ;
Good Programming tips
• Pick a sentinel value that you are CERTAIN will
never be confused with normal data
• Style: Remind user each iteration what the sentinel
is
• Y2K-like problem
– Programmers often used 9999 as a sentinel to end a loop
– Worry that on September 9, 1999 (sometimes abbreviated
9999) programs would erroneously stop executing before
they were supposed to.
Case Study: Nested Control
Structures
Nested control structures
• Problem
– A college has a list of test results (1 = pass, 2 = fail) for 10
students
– Write a program that analyzes the results
• If more than 8 students pass, print "Raise Tuition"
• Notice that
– The program must process 10 test results
• Counter-controlled loop will be used
– Two counters can be used
• One for number of passes, one for number of fails
– Each test result is a number—either a 1 or a 2
• If the number is not a 1, we assume that it is a 2

2003
Prentice
Prentice
Hall,
Hall,
Inc.Inc.
AllAll
rights
rights
reserved.
reserved.
do/while Loop
The do/while Repetition Structure
• The do/while repetition structure
– Similar to the while structure
– Condition for repetition tested after the body of the loop is
performed
• All actions are performed at least once
– Format:
do {
statement(s);
} while ( condition );
4.8
The do/while Repetition Structure
• Flowchart of the do/while repetition structure
action(s)
true
condition
false
public class DoWhileTest
{
public static void main(String args[])
{
int counter;
counter = 1;
do
{
System.out.println ("counter: "+ counter);
counter ++;
} while (counter <= 10);
}
}
Common Errors
• In general you should avoid using floating point
types as control variables
– Why?
• Using a semi-colon after the while statement
• One off errors
– Try to make your conditions in the form <= not <
• Avoid code like counter < 11 or counter < 10
– There are times when we will break this rule
• arrays
• Strings
For Loops
For loops
• Another type of loop in Java is the for loop.
• It is very good for definite loops
• All the parts (priming, testing and updating) are in
one place.
• format:
for (prime expression; test expression; update expression)
• Since the expressions are all in one place, many
people prefer for to while when the number of
iterations is known.
Basic For Loop Syntax
• for loops are good for creating definite
loops.
int counter;
1. Priming: Set
the start value.
2. Test Condition:
Set the stop value.
3. Update: Update the
value.
for (counter =1;counter <= 10;counter++)
System.out.println (counter);
Note that each section is
separated by a semicolon.
for Loop Flowchart
1: Priming
Set counter=1
2: Test
counter
<= 10
FALSE
TRUE
Body: print counter
3: Update counter++;
Infinite Loop
• You can still end up with an infinite loop when
using for loops
for (counter = 0; counter <= 10; counter--)
For Loop Variations
• The limit can be a variable:
for ( i = 1; i <= limit; i++)
– This counts from 1 to limit
• Update may be negative:
for (i = 100; i >= 1; i--)
– This counts from 100 to 1.
• Update may be greater than 1:
for (i = 100; i >= 5; i -= 5)
– This counts from 100 to 5 in steps of 5
Good Programming Practices
• Do not change the value of the counter variable in your
loop.
– Do not attempt to manually adjust it to force an exit
– Can cause subtle errors that are difficult to catch
– Instead change your logic
• Do not put other expressions in the for control structure
– Manipulations of other variables should appear before or within
the body of the loop depending on whether or not you want to
repeat them
• Put a blank line before and after each major control
structure
• Try to limit nesting to three levels, if possible
– More than three levels of indentation can get confusing
• Limit the for control header to one line if possible
break and continue
break;
We have seen the keyword break used in a switch
statement:
switch (userInput) {
case 1:
userInput++;
break;
}
You can also use break inside of a for, while or
do/while loop to immediately exit from the loop.
Example of break use
public class Break
{
public static void main (String [] args)
{
int x;
for ( x = 1 ; x <= 10; x++)
{
if (x == 5)
break;
System.out.println("The number is : " + x);
} /* end for x = 1... */
}
}
continue
Continue is a statement which can be used inside a
for, while or do/while loop in order to skip the rest
of the remaining code in the loop, and start the
next iteration.
Example of continue
public class Continue
{
public static void main (String [] args)
{
int x;
for ( x = 1 ; x <= 10; x++)
{
if (x == 5)
continue ;
System.out.println("The number is : " + x);
} /* end for x = 1... */
}
}
Nested For Loops
• It is also possible to place a for
loop inside another for loop.
Outer Loop
int rows, columns;
Output:
**********
**********
**********
**********
for (rows = 1; rows <= 5; rows++)
**********
{
for (columns=1; columns<=10; columns++)
System.out.print ("*");
System.out.println ();
Inner Loop
}
Nested For Loops, Example #2
Output:
*
int rows, columns;
Outer Loop
**
***
****
for (rows=1; rows<=5; rows++)
*****
{
for (columns=1; columns<=rows; columns++)
Inner Loop System.out.print ("*");
System.out.println ();
}
Java Keywords
Ja va Keyw ord s
abstract
assert
boolean
break
case
catch
char
class
default
do
double
else
final
finally float
for
implements import
instanceof int
long
native
new
package
protected public
return
short
strictfp
super
switch
synchronized
throw
throws
transient try
volatile
while
Keywords that are reserved, but not currently used
const
goto
Fig. 4.2 Ja va keyw o rd s.
 2003 Prentice Hall, Inc. All rights reserved.
byte
continue
extends
if
interface
private
static
this
void
Structured Programming:
Summary
Summary
• Sequence
– Statement follow one another
• Selection Structures
–
–
–
–
if
if/else
if/else if/else
switch
• Repetition Structures
– while
– do/while
– for