Title: CS 303E
1CS 303E
- Lecture 3
- A First Java Program
- L O Chapter 2
If you can't write it down in English, you can't
code it.-Peter Halpern, Brooklyn, New York
2Syntax and Semantics
- Syntax
- Form or grammar.
- Will give syntax rules for the language.
- THIS PART IS FRUSTRATING!!
- Semantics
- Meaning.
- What a particular element of the language causes
to happen. - THIS PART IS CHALLENGING!!
3English is Easier than Java
- Git over here and tale mee where libary is at.
- The meaning can still be determined if the syntax
is not perfect. Not so in programming languages. - Kitty get over here and fast.
- The meaning of this statement?
4Variables
- Variable
- A place in memory that holds a value that may be
altered - Declared to have a name and type
- e.g., int fahrenheit
- Declare variable for age and another for number
of credit hours - Name variables to minimize confusion about the
semantics of the statement.
5Declaring a Variable
- int numDaysLeftInSemester
- What is the variables type?
- What is the variables name?
- In memory 4 bytes used for an int.
?
numDaysLeftInSemester
6Literals and Expressions
- Literal
- A constant e.g., 5, 9, 3.14159
- Like arithmetic expressions in algebra, except
use - for multiplication, / for division, and
- Java variable names may be long.
- PMDAS Precedence is
- parentheses, inner most first
- multiplication and division,
- addition and subtraction.
7Assignment
- Assignment Statement
- Syntax ltvariablegt ltexpressiongt
- ltvariablegt and ltexpressiongt are to be replaced
by the name of a variable and an expression. - Examples
- X X 5 // Mathematicians leaping to
their feet in protest - centigrade (fahrenheit - 32) 5 / 9
- A A B
- A AB
- Semantics Find the value of the expression and
place the value in the variable.
8More on Assignment Statements
- First source of problems
- Cant put square peg in round hole
- Cant get in the club without the right ID
- int myHappinessLevel
- myHappinessLevel 106
- //Large assignment given
- myHappinessLevel 0.05
? 106
9More on Variable Names
- Variable names should be long enough to aid in
the understanding of the meaning or semantics of
the program, but no longer. - x y - (y z)
- netPay grossPay - (grossPay taxRate)
10Window Objects
- lttypegt ltnamegt ltaddTypegt (ltinitial valuegt,
- ltrowgt, ltcolumngt, ltwidthgt, ltheightgt)
- Label degreesFahrenheitLabel
- addLabel ("Degrees Fahrenheit",1,1,1,1)
- IntegerField degreesFahrenheitField
- addIntegerField (0,1,2,1,1)
- Label degreesCentigradeLabel
- addLabel ("Degrees Centigrade",2,1,1,1)
- IntegerField degreesCentigradeField
- addIntegerField (0,2,2,1,1)
- Button convertButton
- addButton ("Convert",3,1,2,1)
- WINDOW OBJECTS ARE SIMILAR TO VARIABLES. THEY
TAKE UP SPACE IN MEMORY.
11Window Object Dissected
- IntegerField ageField
- addIntegerField (21,3,2,1,1)
- Initial value
- Row
- Column
- Width
- Height
12Where in the Window?
- IntegerField ageField addIntegerField (21, 3,
2, 1, 1) - IntegerField x addIntegerField(0, 1, 1, 1, 1)
- IntegerField y addIntegerField(12, 2, 3, 1, 1)
1 2 3 column
1 2 3 row
13Methods
- Method calls (What is the Window Object?)
- fahrenheit degreesFahrenheitField.getNumber()
- degreesCentigradeField.setNumber (centigrade)
- Method definition
- public void buttonClicked (Button buttonObj)
- fahrenheit degreesFahrenheitField.getNumber()
- centigrade (fahrenheit - 32) 5 / 9
- degreesCentigradeField.setNumber (centigrade)
-
- Messages another terminology. When a method is
called or invoked it sends a message to the object
14Methods in Action
- public class FahrenheitToCentigrade
- The main program is called FahrenheitToCentigrade
- When the program is run a FahrenheitToCentigrade
object is created. This object contains numerous
Windows objects. - How do the they communicate?
- Methods and messages!!
15Messages and Methods in Action
degreesFahrenheitField.getNumber() // sends
message
Code for the method resides here. (how does an
IntegerField getNumber?)
Object Type IntegerField Object Name
degreesFahrenheitField
16Edit, Compile, Run
- Steps in creating and running a program
- Edit -- write the program with an editor.
- Compile -- translate into byte code.
- Run -- JVM executes the byte code.
- If there are errors, repeat. You will never have
an error. (Gales of laughter now follow.)
17The Edit, Compile, Run Visual
Program Design
Java Libraries
MyProg.java
Byte Code Produced Here
Java Libraries
MyProg.class
Program Input
Program is run by a Java Virtual Machine
Program Output
18Errors
- Syntax errors -- caught by the compiler.
- Run-time errors -- caught when the program is
run. - Semantic errors -- caught by the programmer.
- Program runs but doesnt do what you wanted.
19Syntax Error
- Forgetting a semicolon on int fahrenheit
- Sometimes not so helpful
20Runtime Error
- Divide by zero is classic example.
- Change FahrenheitToCentigrade and add a variable
for the divisor.
21Semantic Errors
- The hardest to find and fix
- Right after pushing convert.
- Not so much!
22FahrenheitToCentigrade Program, text p.
15 import java.awt. import BreezyGUI. public
class FahrenheitToCentigrade extends GBFrame
Label degreesFahrenheitLabel addLabel
("Degrees Fahrenheit",1,1,1,1) IntegerField
degreesFahrenheitField addIntegerField
(0,1,2,1,1) Label degreesCentigradeLabel
addLabel ("Degrees Centigrade",2,1,1,1)
IntegerField degreesCentigradeField
addIntegerField (0,2,2,1,1) Button
convertButton addButton
("Convert",3,1,2,1) (continued on next slide)
23FahrenheitToCentigrade Program (continued)
int fahrenheit int centigrade public
void buttonClicked (Button buttonObj)
fahrenheit degreesFahrenheitField.getNumber()
centigrade (fahrenheit - 32) 5 / 9
degreesCentigradeField.setNumber (centigrade)
public static void main (String args)
Frame frm new FahrenheitToCentigrade()
frm.setSize (200, 150)
frm.setVisible (true)
24Window Design
- See Fig. 2.3, text p. 20.
- Remember
- lttypegt ltnamegt ltaddTypegt (ltinitial valuegt,
- ltrowgt, ltcolumngt, ltwidthgt, ltheightgt)
- So far we have
- Label
- IntegerField
- Button
- Many more to come.
25CS 303E
- Lecture 4
- Java Basics 1
- Chapter 3
- Once a person has understood the way variables
are used in programming,(s)he has understood the
quintessence of programming. -Dijkstra
26Case 3.1 -- Area of Circle
- Makes simple transformations from program
FahrenheitToCentigrade. - If you can reuse your code in this class, do it!
- Type double numbers, DoubleField boxes.
- Extraordinarily similar to what?
27Request and Analysis
- Request
- write a program that computes the area of a
circle. - Design
- Area of circle ?r2
- get radius from user
- compute and display area
28Area of Circle Design
- get radius
- area 3.14 radius radius
- display area with 2 digits after the decimal
point - Again, input - process - output.
- concerns?
29Elements of the GUI
- Label radiusLabel addLabel
("Radius",1,1,1,1) - DoubleField radiusField
- addDoubleField (0,1,2,1,1)
- Label areaLabel addLabel ("Area",2,1,1,1)
- DoubleField areaField addDoubleField
(0,2,2,1,1) - Button computeButton
- addButton ("Compute",3,1,2,1)
- Remember initial value, row, column, width,
height
30The Guts of Button Clicked
- public void buttonClicked (Button buttonObj)
- radius radiusField.getNumber()
- area 3.14 radius radius
- areaField.setNumber (area)
- areaField.setPrecision(2)
-
- What is areaField.setPrecision(2) ????
31Case 3.2 -- Income Tax
- More simple transformations from program
FahrenheitToCentigrade. - Analysis a little more in depth.
- flat tax rate of 20, 10,000 standard deduction,
2,000 deduction for each dependent, - Must know something about figuring taxes to do
this or must ask requestor to clarify.
32Income Tax Program
- Type int and double variables, IntegerField and
DoubleField boxes. - An additionl box for input. (2 inputs)
- Get both inputs for computation.
- Yet again
- input - process - output
- Look at program in JBuilder.
33Income Tax Program Variables
- int grossIncome
- int numberOfDependents
- double taxableIncome
- double incomeTax
- Double is a data type. Floating point numbers
3.14, 12.232301, 0.000001
34Income Tax Button Clicked
- public void buttonClicked (Button buttonObj)
- grossIncome grossIncomeField.getNumber()
- numberOfDependents numberOfDependentsField.
getNumber() - taxableIncome
- grossIncome - 10000 - numberOfDependents
2000 - incomeTax taxableIncome 0.20
- incomeTaxField.setNumber (incomeTax)
- incomeTaxField.setPrecision (0)
-
- Is the taxable income variable necessary?
35Constants
- What do the numbers 10000, 2000, and 0.20
represent in the income tax program? - These numbers should be declared as constants.
- final int STANDARD_DEDUCTION 10000
- final int DEPENDENT_DEDUCTION 2000
- final double TAX_RATE 0.20
36Constants
- Constants share some similarities with variables.
- they have a data type
- they take up space in memory
- The major differences is constants cannot be
changed in the program.
0.20
TAX_RATE 12 causes syntax error
TAX_RATE
37Binary Represenation
- Bits , bytes.
- Integers, floating point numbers, characters,
Strings and other data, and instructions - All are represented in binary using bits, short
for binary digit, 1s and 0s - Memory -- an array of bytes.
- ?Self Test
- How much memory to store a picture 20 by 30
pixels, each pixel can be 1 of 256 possible
colors.
38Variable Names
- Reserved words -- cant use these for variable
names. Java already has a meaning for them. - Not that many of them.
- abstract default if private throwboolean
do implements protected throwsbreak double
import public transientbyte else
instanceof return trycase extends int
short voidcatch final interface static
volatilechar finally long
super whileclass float native
switchconst for new synchronizedcontinue
goto package this
39Varaiable Names Continued
- Identifier -- a name. Composed of letters,
digits, _ and and beginning with a letter
or _. - Dont use .
- Upper- and lower-case letters are considered
different. Case sensitive. - Common practice to capitalize the first letter of
each word in a variable name except the first - Constant names all caps with _ between words
40Valid or not?
- just_in_time c1212 int
- class num my_happiness_factor TANJ
- x battingAverage classTime
- X 5bestTimes gross
- totalIncome totalGold _total_time
- TotalIncome public tax
- variable 1time money
- 5 aVariableToHoldMoneySpentSoFar
41Variable Names Continued
- "Make things as simple as possible--but no
simpler. - A. Einstein - Meaningful variable names make a program easier
to understand and maintain. One of the major
principles of this course. - incomeTax versus it
- totalArea versus ta
- studentNumber versus theNumberAssignedT
oThisStudent
42Expressions
- Operator precedence -- see p. 45.
- Unary - is precedence 2 (omitted).
- x -3 -4
- means modulo
- The remainder from integer division.
- Go back to second grade, 21 ? 5 4 r 1
- 21 / 5 4
- 21 5 1
- Integer vs. floating point /
- integer division truncates the result
- floating point gives a floating point answer
43Unary plus and minus
- Expression Value Better
- Unary minus
- 3 4 12 (3) (4)
- 3 4 12 3 (4)
- 3 4 12 3 ( (4))
- Unary plus
- 3 4 12 3 (4)
44Increment and Decrement
- Operator Equivalent Called
- x x x 1 postfix increment
- x x x 1 prefix increment
- x x x 1 postfix decrement
- x x x 1 prefix decrement
- Too confusing, DONT DO IT!
- z 2 x ? z 2 x x
- z 2 x ? x z 2 x
- Write code that is easy to understand and
maintain
45Extended Assignment Operators
- Operator Equivalent
- sum x sum sum x
- diff x diff diff x
- product x product product x
- quot / x quot quot / x
- rem x rem rem x
- Confusing
- int a 1, b 2
- a b 3 b 5 a 6
46Expressions PracticeValue of variables after
each statement?
int x int y int z 12 //yes, this is allowed
and encouraged! final int MAX_UNITS 15 double
a 2.5 x z 2 5 y 5 y y
MAX_UNITS z y 7 x 2 MAX_UNITS z x
15 / 4 - 2 y 15 / (4 - 2) x a
47Data Types Revisted
- Numeric types
- int, double, and others
48Numeric Types (p. 124)
- Type Storage Range
- byte 1 byte 128 to 127
- short 2 bytes 32,768 to 32,767
- int 4 bytes 2,147,483,648 to 2,147,483,647
- long 8 bytes 9,223,372,036,854,775,808 to
- 9,223,372,036,854,775,807
- float 4 bytes ?3.40282347x1038 to
- ? 1.40239846x10-45
- double 8 bytes ? 1.79769313486231570x10308
to - ? 4.94065645841246544x10-324
49Mixed-Mode Operations
Java converts the value of a less inclusive
type (like int) to a more inclusive type (like
double) before performing an operation int i
5 double d 3.5 System.out.println (d
i) // Displays 8.5
50CS 303E
- Lecture 5
- Java Basics 2
- Chapter 3
"In a way, staring into a computer screen is
like staring into an eclipse. It's brilliant and
you don't realize the damage until its too
late."- Bruce Sterling
51BreezyGUI Window Objects
- Pages 48 - 51 in Lambert and Osborne.
- Window objects must have
- type, name, initial value, location, extent
- types so far are
- Label, IntegerField, Button, DoubleField
- lttypegt ltnamegt ltaddTypegt (ltinitial valuegt,
- ltrowgt, ltcolumngt, ltwidthgt, ltheightgt)
52BreezyGUI Methods
- These calls require window_object.method_name
- fahrenheit degreeFahrenheitField.getNumber()
- Some return a value (e.g., getNumber),
- some dont (e.g. setNumber).
- Some require a parameter or argument (besides the
window object), which goes in the parentheses. - someField.setNumber (number)
53BreezyGUI Methods
- Some methods require multiple parameters
- someObject.someMethod(param1, param2, paramn)
- Multiple parameters must have the right number,
order, and type. - Wrong number or type leads to syntax error
- Wrong order may lead to syntax or semantic error
- List of BreezyGUI methods on page 51.
54Strings
- String is a type, similar to int and double.
- String is an object type like BreezyGUI window
objects, int and double are primitives. - String literals -- use double quotes
- Hi there! My name is Raoul. -- any characters
- -- the empty string.
- 453 is a string, 453 is an int.
55Strings
- String variables
- String status
-
- String customer Bill
-
- String firstName, lastName
56String Concatenation
- concatenates Strings
- String firstName Maria
-
- String lastName Ruiz
-
- String name firstName lastName
-
- // name Maria Ruiz
- \n is the newline character (one character)
- String name Jose Garcia\n
57Number String Converts
- int a 5, b 6
- String result a " plus " b " equals "
(a b) - // result 5 plus 6 equals 11
- Conversion of a number to a String occurs with
- number String or String number.
- number number still does addition.
- (a b) above is needed to make this addition,
not String concatenation. What happens if no
parenthesis?
58Message Boxes
- BreezyGUI provides message boxes
- messageBox (Hey there!)
- Pops up a separate window called a message box
containing the text provided as an argument. - String line1 Top line.\n
- String line2 Bottom line.
- messageBox (line1 line2)
- Message box contains 2 lines.
59Message Box
60Message Box Behavior
- Message Boxes are modal.
- Nothing can be done in the original window until
the message box is acknowledged by closing it ?
clicking x in upper right corner. - Too many message boxes make for a very annoying
program. Use sparingly.
61Text Fields
- TextField -- BreezyGUI window component type
containing one line of String data. - Declared like other window components
- TextField ltnamegt addTextField (ltinitial valuegt,
ltrowgt, ltcolgt, ltwidthgt, ltheightgt) - Methods
- name.getText() -- returns String
- name.setText (aString) -- sets field content.
62Case 3.3 - Vital Statistics
- import java.awt.
- import BreezyGUI.
- public class VitalStatistics extends GBFrame
- Label nameLabel addLabel ("Name",1,1,1,1)
- TextField nameField addTextField
("",1,2,1,1) - Label heightLabel addLabel
("Height",2,1,1,1) - IntegerField heightField
- addIntegerField (0,2,2,1,1)
- Label weightLabel addLabel
("Weight",3,1,1,1) - IntegerField weightField
- addIntegerField (0,3,2,1,1)
- Button displayButton
- addButton ("Display",4,1,2,1)
- // What will window look like?
63Window Layout
64 String name, outputString int height,
weight public void buttonClicked (Button
buttonObj) name nameField.getText()
height heightField.getNumber() weight
weightField.getNumber() outputString
"Name " name "\n"
"Height " height " inches\n"
"Weight " weight " pounds\n"
messageBox (outputString) // how many
lines of text in message box? public static
void main(String args) Frame frm new
VitalStatistics() frm.setSize (200, 150)
frm.setVisible(true)
65System.out.println
- System.out.println (expression) // with newline
- System.out.print (expression) // without
newline - Prints the value of expression to the DOS window.
- Expression is converted to a String if it is
not one. - Useful for debugging.
66Debugging in JBuilder and Codewarrior
- System.out.println statements are very useful
- May also step through program
- F8 Step Over
- F7 Trace Into
- Setting Breakpoints can halt execution at a
statement in the program. - Contents of variables and objects may be examined
67Assignment 2
68Mixed-Mode Assignment
Java converts the value of a less inclusive type
to a more inclusive type before performing an
assignment, but not vice versa int i
5 double d 3.5 d i System.out.println (d)
// Displays 5.0 i d //
Syntax error System.out.println (i)