2. BYTE FROM COMPUTING HISTORY
James Gosling is known as
the ‘Father of the Java
programming language’.
Listen to an interview.
https://mappingthejourney.com/single-post/2017/06/29/episode-3-interview-with-james-gosling-father-of-java/ 2
3. GOALS FOR TODAY’S CLASS
Lecture & Demo in JGRASP
•Introduction to Objects and Classes
•Working with Constructors and
Methods
•Using the Debugger; zipping a project
•Using Style Guidelines
3
6. PROBLEM STATEMENT
Create a program for a car. The program must simulate the
attributes of the car and its fuel operations.
We decide to
1. Create a Car class (note capital first letter).
2. Store fuel capacity and amount (in gallons).
3. Give the user a way to update, or set the fuel and capacity.
4. Give the user a way to read, or get the current fuel level and
cost for filling up the tank.
6
In Java, only Class names are capitalized!
Class definitions are meant to model real-world entities, such as a car or
an employee. This makes code design easier to understand.
7. DESIGNING OUR SOLUTION
Diagram: UML - Unified Modeling Language
7
Car class
Variables & Type
Constructors
Methods with type
of input & output
Note
camelCase
naming
conventions!
8. DEMO IN JGRASP - Car PROJECT
• Using the Canvas and Interaction pane
in jGRASP
• Running Main method
• Calling Constructors and Methods with
Parameters and Arguments
• Using the Debugger
8
9. REVIEW: WORKING WITH CONSTRUCTORS
9
A class may define
several
constructors with
different parameter
types.
Initialize variable
in constructor
Declare
private
variable
Create a new
Car instance in
main method
10. REVIEW: WORKING WITH METHODS
Mutator methods
modify object -
changing object's
internal data.
Accessor methods
access object's
data but do not
modify internal
data.
Notice return
types!
10
arguments
parameter
Methods have
return type or
void
Invoke
methods on
Car object
from main
11. REVIEW: USING 2 CLASSES
11
The dotted line means CarMain
uses an instance of Car.
Attributes
of a Car
Public
Methods
Why two classes?
Car encapsulates
data about each
specific car.
CarMain deals
with the various
cars and prints info.
12. REVIEW: USING 2 CLASSES
12
This diagram is the design
of the code
Car object #2
10.0
5.0
This diagram shows the
objects that are created when
the program is run.
The program could deal with any number of cars. Data for each specific
car is contained in a Car object. This keeps the code modular and easier
to work with. Car main manages all Car objects.
Car object #1
13.5
5.0
CarMain object
myCar
yourcar
13. CLICKER QUESTION 1
Select the statement to declare and create a new object of type
Bus named bus1
1
3
A. Bus bus1;
B. Bus bus1 = new Bus();
C. Bus = new bus1;
D. bus1 = new Bus();
14. CLICKER QUESTION 1 ANSWER
Select the statement to declare and create a new object of type
Bus named bus1
1
4
A. Bus bus1; Declares variable bus1 for an object, but does not create an object.
B. Bus bus1 = new Bus();
C. Bus = new bus1;incorrect syntax
D. bus1 = new Bus(); incorrect syntax
15. CLICKER QUESTION 2
Call the
incrementCount()
method on a Bus
object named bus1
1
5
A. Bus
A. Bus.incrementCount();
B. bus1.incrementCount;
C. bus1.incrementCount();
D. Bus.bus1.incrementCount();
16. CLICKER QUESTION 2 ANSWER
Call the
incrementCount()
method on a Bus
object named bus1
16
A. Bus
A. Bus.incrementCount();
B. bus1.incrementCount;
C. bus1.incrementCount();
D. Bus.bus1.incrementCount();
Object name comes before
the period.
Method being called on that
object comes after the
period.
17. CLICKER QUESTION 3
Choose the correct statement
A. printHistogram has 3 parameters and void return type
B. setBinValue has no parameters and int return type
C. setNumberOfBins has no parameters and void return type
D. getBinValue has 1 parameter and int return type 17
18. CLICKER QUESTION 3 ANSWER
Choose the correct statement
A. printHistogram has 3 parameters and void return type has no params
B. setBinValue has no parameters and int return type has params & void return
C. setNumberOfBins has no parameters and void return type has param
D. getBinValue has 1 parameter and int return type
18
19. HOW DO I ZIP MY PROJECT?
19
Do NOT use other packages
to zip your project!
20. HOW DO I UPLOAD IN GRADESCOPE?
1. Make sure you have consented in Moodle to using Gradescope.
2. You will receive an email informing you that Gradescope is ready
for your upload.
3. You have multiple opportunities to upload your zip file before the
deadline. There is also a grace period if you forget!
4. Visit office hours or ask your question in Piazza if you need help
with Project 1.
DEMO: Uploading a zip file in Gradescope.
20
21. RULES & STYLE GUIDES FOR YOUR PROJECT
We’ll use Table 2.14.1: Sample style guide from zyBook Chapter
2.14 as our guide for all projects!
In JGrasp “Settings->Font->CSD” tab check that
AutoIndent and SoftTabs have a tick mark and Tab size is set
to 3 spaces.
21
22. GOOD CODE FORMATTING THINK-PAIR-SHARE
22
Version 1
Version 2
In jGRASP:
Java “keywords” in purple.
String literals in green.
Comments in orange.
How many changes can
you spot?
23. CS121 KEY IDEAS
• Be able to solve problems by writing Java code.
• This involves a lot of steps that do not involve coding!
1. Understanding the problem.
2. Designing a procedure to solve it.
3. Coding a solution.
4. Testing the code and debugging it.
• Software is a shared asset- it is developed in teams.
•Write code with the awareness that another person will be reading
and modifying it. 23
24. 24
1. Make sure you have a clear idea
of what problem you need to
solve.
2. Plan a solution: what are the
steps needed to solve the
problem?
3. Work out the solution on paper
(or some form other than
coding).
4. Then begin writing code.
5. Note: when software is
properly engineered coding is
about 16% of the total
development time.
6. The rest is design and testing
CODING GUIDELINES
25. Week 2 TODO List:
• Register your iClicker in Moodle.
• Complete zyBook chapter 2 exercises.
• Join us on Piazza - check the email invite!
• Attend Lab 2 on Friday - make sure you have jUnit
installed. See Moodle for the Installation notes.
• Start Project 1 early! Upload often in Gradescope.
25
Give your consent to use Gradescope - see Moodle.
Join us on Piazza!
27. GOALS FOR TODAY’S CLASS
Demo in JGRASP
•How to use debugger
Lecture
•Using Variables
•Rules for Identifiers and Style Guidelines
2
28. DEBUGGER FEATURES
• The Debugger allows you to control
program execution.
• You can see the values of variables.
• Useful to find bugs in your code.
• Debugger a major feature of all
development environments
3
29. USING THE DEBUGGER IN JGRASP
To learn more about the control buttons see:
https://jgrasp.org/tutorials187/06_Debugger.pdf 4
breakpoint- stops
execution.
shows values of
variables.
bug icon- runs in
debug mode.
control
buttons.
30. REVIEW: USING 2 CLASSES
5
This diagram is the design
of the code
Car object #2
10.0
5.0
This diagram shows the
objects that are created when
the program is run.
The program could deal with any number of cars. Data for each specific
car is contained in a Car object. This keeps the code modular and easier
to work with. Car main manages all Car objects.
Car object #1
13.5
5.0
CarMain object
myCar
yourCar
31. OBJECTS IN THE DEBUGGER
6
Two Car objects
were created on
lines 13 and 16:
32. OBJECTS IN THE DEBUGGER
7
Two Car objects
and the data they
contain.
33. OBJECTS IN THE DEBUGGER
8
fuelAmount value
changed in Object
by calling setFuel
method.
34. OBJECTS IN THE DEBUGGER
9
Executing line 22
prints to the
console.
35. OBJECTS IN THE DEBUGGER
10
Executing line 22
prints to the
console.
36. THE SALARY PROJECT:
Goal: Create a program that reads a user's input value for hourly
wage and calculates the monthly and annual salary.
Plan:
1. We use the Scanner to get the input we need.
2. We process the input (wage, hours per week, weeks per year).
3. We output the monthly and annual salary.
We have the first draft that works somewhat.
Demo: SalaryProject
Note the problems as we walk through the code.
11
37. MODIFICATIONS AND TEST
1. We need to get the user
input for some variables.
2. Some variables need to
be initialized and will not
change. These are
constants.
3. Is the salary calculation
correct?
12
Test your
code!!!!!
38. DEMO HOW TO FIX PROGRAMMING ERRORS
We’ll use the Debugger in JGrasp and manually
inspect code for SalaryProject.
There is a bug in this code.
1- Understand what the code should do.
2- Run the code and see if it is correct.
3- Use the debugger to view code as it executes.
4- Find the bug, stop debugger, fix code and test.
13
40. BEST PRACTICE ADVICE
• Use the debugger to see values during
execution.
• Comment out unused code.
• Delete unused code when you have finished.
• Keep your code clean and easy to read and
understand.
15
41. REVIEW: VARIABLES
Assignment statements: create a variable and assign a
value to it.
int num = 450;
• LHS has to be a variable, RHS has to resolve to a value.
16
value
assignment
operator
data
type variable
name
RHSLHS
“Declaration” of the variable
“num” with data type “int”.
It also assigns the value 450 to
that variable.
42. CLICKER QUESTION #1
int someNumber = 10;
int someNumber = 12;
After executing these statements:
A. Value of someNumber is 10
B. Value of someNumber is 12
C. Value of someNumber is “12”
D. Error assigning value
17
43. CLICKER QUESTION #1 ANSWER
18
int someNumber = 10;
int someNumber = 12;
After executing these statements:
A. Value of someNumber is 10.
B. Value of someNumber is 12
C. Value of someNumber is “12”
D. Error assigning value - variable someNumber is already defined
Use the Interactions pane
in JGrasp to test code!
44. REVIEW: VARIABLES IN JAVA
19
Notice that you declare a variable only once,
but can use it as much as necessary once it’s declared.
You cannot re-declare a variable:
int a = 450;
int a = 450;
int a = 22;
declaration OK
re-declaration Not OK
You can re-assign a variable:
int a = 450;
a = 22; re-assignment OK
45. CLICKER QUESTION #2
After executing this statement:
int numPeople;
System.out.println (numPeople);
numPeople = 5;
A. Value of numPeople is 0
B. Value of numPeople is 5
C. Value of numPeople is “0”
D. Error 20
46. CLICKER QUESTION #2 ANSWER
After executing this statement:
int numPeople;
System.out.println (numPeople);
numPeople = 5;
A. Value of numPeople is 0
B. Value of numPeople is 5
C. Value of numPeople is “0”
D. Error 21
47. JAVA RULES FOR IDENTIFIERS
1. An identifier must:
1. be a sequence of letters (a-z,
A-Z), underscore (_), dollar signs
($), and digits (0-9)
2. start with a letter, underscore, or
dollar sign
2. Are case sensitive (upper and lower
case letters differ).
3. Cannot be a Java reserved word.
22
Color
coded by
jGRASP
Test in jGRASP interaction pane
48. CLICKER QUESTION #3
23
Which of the following are
valid identifiers:
1. num Employees
2. numEmployees
3. num_Employees
4. NumEmployees
5. __numEmployees
6. numEmployees!
Answers
A. 1, 2, 3, 4, 5, 6
B. 2, 3, 4, 5
C. 1, 6
D. 2, 3
49. CLICKER QUESTION #3 ANSWERS
24
Which of the following are valid
identifiers:
1. num Employees space not allowed
2. numEmployees Ok
3. num_Employees Ok
4. NumEmployees Ok not recommended
5. __numEmployees Ok not
recommended
6. numEmployees! !not allowed
Answers
A. 1, 2, 3, 4, 5,
6
B. 2, 3, 4, 5
C. 1, 6
D. 2, 3,
52. CLICKER QUESTION #4
Which one of the following arithmetic precedence
rules are correct for the expression given?
A. Evaluation always occurs left to right
B. Items within parentheses ( ) are evaluated first
C. The order of operations is +, =, *, /, %
D. Evaluation always occurs right to left
27
53. CLICKER QUESTION #4 ANSWER
Which of the following arithmetic precedence rules are
correct for the expression given?
A. Evaluation always occurs left to right
B. Items within parentheses ( ) are evaluated first
C. The order of operations is +, =, *, /, %
D. Evaluation always occurs right to left
28
54. RULES & STYLE GUIDES FOR IDENTIFIERS
We’ll use Table 2.14.1: Sample style guide from zyBook Chapter
2.14 as our guide for all projects!
In JGrasp “Settings->Font->CSD” tab check that
AutoIndent and SoftTabs have a tick mark and Tab size
is set to 3 spaces.
29
55. CLICKER QUESTION #5 STYLE GUIDELINES
Which of the following is the recommended style
guide for Variable and Method names?
A. They should be enclosed in braces { }
B. They are camelCase, starting with lowercase
C. They are single-letter names
D. They can start with a capital letter and have
_underscore
30
56. CLICKER QUESTION #5 ANSWER
Which of the following is the recommended style
guide for Variable and Method names?
A. They should be enclosed in braces { }
B. They are camelCase, starting with lowercase
C. They are single-letter names
D. They can start with a capital letter and have
_underscore
Options C and D would still compile
31
57. UPLOADING PROJECTS - TIPS
Watch for these errors when uploading your project in
Gradescope!
1. Uploading only the jGRASP project (gpj) file.
2. Uploading the starter code and not the finished
project.
3. Uploading the project in the last minute.
4. Zipping the file from another package.
32
58. REMINDER: THE JAVA API HELP RESOURCE
Freely available for you! You can use the classes and methods
without knowing how they are implemented. No need to import
java.lang classes. 33
Use of Scanner requires
import
java.util.Scanner;
59. SUMMARY
• Use the debugger to remove coding errors
• Use the style guide to improve readability of the code.
• Pay attention to the rules for java identifiers.
• Know the precedence rules for arithmetic operators
34
60. Week 2 TODO List:
• Register your iClicker in Moodle.
• Complete zyBook chapter 2 exercises.
• Attend Lab 2 on Friday.
• Download Lab code before coming to lab- save time!
• Upload Project 1 in Gradescope before the deadline.
3
5