Post on 17-Jan-2016
CS303E The First Java Program 1
CS 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
CS303E The First Java Program 2
Syntax 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!!
CS303E The First Java Program 3
English 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?
CS303E The First Java Program 4
VariablesVariable
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.
CS303E The First Java Program 5
Declaring a Variable
int numDaysLeftInSemester;
What is the variable’s type?
What is the variable’s name?
In memory 4 bytes used for an int.
?numDaysLeftInSemester
CS303E The First Java Program 6
Literals and Expressions Literal
A constant: e.g., 5, 9, 3.14159
Like arithmetic expressions in algebra, except use* for multiplication, / for division, andJava variable names may be long.
PMDAS: Precedence is: parentheses, inner most first multiplication and division, addition and subtraction.
CS303E The First Java Program 7
AssignmentAssignment Statement:Syntax: <variable> = <expression>;
<variable> and <expression> 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 / 9A = A * B;
A = AB;Semantics: Find the value of the expression and place the value
in the variable.
CS303E The First Java Program 8
First source of problems Can’t put square peg in round hole Can’t get in the club without the right ID
int myHappinessLevel;
myHappinessLevel = 106;
//Large assignment given
myHappinessLevel = 0.05;
More on Assignment Statements
myHappinessLevel
? 106
CS303E The First Java Program 9
More 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);
CS303E The First Java Program 10
Window Objects<type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>);
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.
CS303E The First Java Program 11
Window Object Dissected
IntegerField ageField = addIntegerField (21,3,2,1,1);
Initial value =Row = Column =Width =Height =
CS303E The First Java Program 12
Where 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
row
1 2 3 column
CS303E The First Java Program 13
Methods
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
CS303E The First Java Program 14
Methods 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!!
CS303E The First Java Program 15
Messages and Methods in Action
FahrenheitToCentigradeObject
degreesFahrenheitFieldObject
degreesFahrenheitField.getNumber(); // sends message
Object Type = IntegerFieldObject Name = degreesFahrenheitField
Code for the method resides here. (how does an IntegerField getNumber?)
CS303E The First Java Program 16
Edit, 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.)
CS303E The First Java Program 17
The Edit, Compile, Run Visual
EDIT
Compile
RUN
Program Design
MyProg.java
Java Libraries
MyProg.class
Program Input
Java Libraries
Program Output
Byte CodeProduced Here
Program is run by aJava Virtual Machine
CS303E The First Java Program 18
Errors
Syntax errors -- caught by the compiler.
Run-time errors -- caught when the program is run.
Semantic errors -- caught by the programmer.
Program runs but doesn’t do what you wanted.
CS303E The First Java Program 19
Syntax Error Forgetting a semicolon on int
fahrenheit
Sometimes not so helpful
CS303E The First Java Program 20
Runtime Error Divide by zero is classic example. Change FahrenheitToCentigrade and add a
variable for the divisor.
CS303E The First Java Program 21
Semantic Errors The hardest to find and fix
Right after pushing convert.– Not so much!
CS303E The First Java Program 22
FahrenheitToCentigrade 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)
CS303E The First Java Program 23
FahrenheitToCentigrade 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); } }
CS303E The First Java Program 24
Window Design
[See Fig. 2.3, text p. 20.]
Remember:<type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>);
So far we have:• Label• IntegerField• Button
Many more to come.
CS303E The First Java Program 25
CS 303ELecture 4
Java Basics 1Chapter 3
Once a person has understood the way variables are used in programming,(s)he has understood the quintessence of programming.
-Dijkstra
CS303E The First Java Program 26
Case 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?
CS303E The First Java Program 27
Request 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
CS303E The First Java Program 28
Area of Circle Design
get radius area = 3.14 * radius * radius display area with 2 digits after the decimal
point• Again, input - process - output.• concerns?
CS303E The First Java Program 29
Elements 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
CS303E The First Java Program 30
The 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); ????
CS303E The First Java Program 31
Case 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.
CS303E The First Java Program 32
Income 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.
CS303E The First Java Program 33
Income 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
CS303E The First Java Program 34
Income 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?
CS303E The First Java Program 35
Constants
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;
CS303E The First Java Program 36
Constants 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.
TAX_RATE
0.20 TAX_RATE = 12; causes syntax error
CS303E The First Java Program 37
Binary RepresenationBits , 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.
CS303E The First Java Program 38
Variable Names Reserved words -- can’t 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 synchronized
continue goto packagethis
CS303E The First Java Program 39
Varaiable Names Continued Identifier -- a name. Composed of letters, digits, ‘_’ and
‘$’ and beginning with a letter or ‘_’. Don’t 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
CS303E The First Java Program 40
Valid or not?just_in_time c1212 int
class num my_happiness_factor TANJ
x battingAverage classTime
X 5bestTimes gross%
total+Income totalGold _total_time
TotalIncome public tax&
variable 1time money$
5 aVariableToHoldMoneySpentSoFar
CS303E The First Java Program 41
Variable 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 theNumberAssignedToThisStudent
CS303E The First Java Program 42
Expressions 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
CS303E The First Java Program 43
Unary 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)
CS303E The First Java Program 44
Increment and DecrementOperator Equivalent Called
x ++; x = x + 1; postfix increment++ x; x = x + 1; prefix incrementx – –; x = x – 1; postfix decrement– – x; x = x – 1; prefix decrement
Too confusing, DON’T 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
CS303E The First Java Program 45
Extended Assignment Operators
Operator Equivalentsum += 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;
CS303E The First Java Program 46
Expressions 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;
CS303E The First Java Program 47
Data Types Revisted
Numeric types:
int, double, and others
less inclusive more inclusive
byte short int long float double
integers floating point
CS303E The First Java Program 48
Numeric Types (p. 124)Type Storage Rangebyte 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.40282347x10+38 to 1.40239846x10-45
double 8 bytes 1.79769313486231570x10+308 to 4.94065645841246544x10-324
CS303E The First Java Program 49
Mixed-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
CS303E The First Java Program 50
CS 303E
Lecture 5
Java Basics 2
Chapter 3
"In a way, staring into a computer screen is likestaring into an eclipse. It's brilliant and you don't realize the damage until its too late."- Bruce Sterling
CS303E The First Java Program 51
BreezyGUI 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
<type> <name> = <addType> (<initial value>, <row#>, <column#>, <width>, <height>);
CS303E The First Java Program 52
BreezyGUI Methods
These calls require window_object.method_name:
fahrenheit = degreeFahrenheitField.getNumber(); Some return a value (e.g., getNumber), some don’t (e.g. setNumber). Some require a parameter or argument (besides the
window object), which goes in the parentheses. someField.setNumber (number);
CS303E The First Java Program 53
BreezyGUI 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.
CS303E The First Java Program 54
Strings
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.
CS303E The First Java Program 55
Strings
String variables:String status;
String customer = “Bill”;
String firstName, lastName;Several objects in one declaration,like any other type.
String given aninitial value.
String with noinitial value.
CS303E The First Java Program 56
String 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”;
CS303E The First Java Program 57
Number + 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?
CS303E The First Java Program 58
Message 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.
CS303E The First Java Program 59
Message Box
CS303E The First Java Program 60
Message 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.
CS303E The First Java Program 61
Text FieldsTextField -- BreezyGUI window component type
containing one line of String data.Declared like other window components:TextField <name> = addTextField (<initial value>,
<row#>, <col#>, <width>, <height>);Methods:name.getText() -- returns Stringname.setText (aString) -- sets field content.
CS303E The First Java Program 62
Case 3.3 - Vital Statisticsimport 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?
CS303E The First Java Program 63
Window Layout
CS303E The First Java Program 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); } }
CS303E The First Java Program 65
System.out.printlnSystem.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.
CS303E The First Java Program 66
Debugging 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
CS303E The First Java Program 67
Assignment 2
Handed out today
CS303E The First Java Program 68
Mixed-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.0i = d; // Syntax errorSystem.out.println (i);