Introduction toProgrammingIntroduction toProgramming
Writing Java Beginning JavaProgramsWriting Java Beginning JavaPrograms
Review of Lab 1Review of Lab 1
Built-in TypesBuilt-in Types
Integer typesInteger types
No decimal pointNo decimal point
integer math-op integer yields an integerinteger math-op integer yields an integer
byte, short, int, longbyte, short, int, long
Real typesReal types
Have decimal pointHave decimal point
real math-op real yields realreal math-op real yields real
float, doublefloat, double
Review of lab ContinuedReview of lab Continued
Java VariablesJava Variables
AttributesAttributes
NameName
TypeType
ValueValue
Specifies where data is stored in memorySpecifies where data is stored in memory
Java requires that variable be declared before it canbe used.Java requires that variable be declared before it canbe used.
Declaration Form:Declaration Form:
Type variable-name;Type variable-name;
Can only declare once!Can only declare once!
Review of Lab 1Review of Lab 1
What is wrong?What is wrong?
int firstNum 0;int firstNum 0;
int firstNum firstNum 1;int firstNum firstNum 1;
What does the operator in Java mean?What does the operator in Java mean?
What is the type of the result ofWhat is the type of the result of
double total, price;double total, price;
int amt;int amt;
total price amt;total price amt;
What is wrong withWhat is wrong with
amt total/price;amt total/price;
Review of Lab ContinuedReview of Lab Continued
Variable Naming ConventionsVariable Naming Conventions
Start with letter or follow with any number ofletters, digits, or _Start with letter or follow with any number ofletters, digits, or _
Names are case sensitiveNames are case sensitive
Convention – variable names start with lowercase letter.Convention – variable names start with lowercase letter.
Names should be meaningful.Names should be meaningful.
salessales
noItemsnoItems
qtyOnHandqtyOnHand
Camel notation
The Semicolon RuleThe Semicolon Rule
Always end Java statement with asemicolon!Always end Java statement with asemicolon!
Be careful! The interaction pane does notrequire semicolon after each statement.Be careful! The interaction pane does notrequire semicolon after each statement.
In program typed into the definition pane,Java does.In program typed into the definition pane,Java does.
In the interaction pane, typing semicolon afterstatement does not show the value of theresult.  Leaving the semicolon off does.In the interaction pane, typing semicolon afterstatement does not show the value of theresult.  Leaving the semicolon off does.
The Semicolon RuleThe Semicolon Rule
Always end Java statement with asemicolon!Always end Java statement with asemicolon!
The code pad in BlueJ requires semicolonafter each Java statement.The code pad in BlueJ requires semicolonafter each Java statement.
If you forget the semicolon, you will get anerror in code pad reminding you that asemicolon is required.If you forget the semicolon, you will get anerror in code pad reminding you that asemicolon is required.
Object VariablesObject Variables
Java is an Object-oriented programming language.Java is an Object-oriented programming language.
We work mostly with objects.We work mostly with objects.
However, built-in numeric types are not objects.ie. int, float, double, However, built-in numeric types are not objects.ie. int, float, double, 
Strings are objects.Strings are objects.
String myName;String myName;
myName is reference to string objectmyName is reference to string object
Objects must be created before they are assigned.Objects must be created before they are assigned.
myName has the initial value of null (it does notreference string object)myName has the initial value of null (it does notreference string object)
Much more on this later.Much more on this later.
Classes and ObjectsClasses and Objects
Classes are templates that define what objectslook like and how they behave.Classes are templates that define what objectslook like and how they behave.
An object is an instantiations of classAn object is an instantiations of class
Class names in Java should start with capitalletter.Class names in Java should start with capitalletter.
Turtle is classTurtle is class
It defines object methods that let you use Turtleobject.It defines object methods that let you use Turtleobject.
//create turtle object from the Turtle class//create turtle object from the Turtle class
   Turtle myTurtle new Turtle(myWorld);   Turtle myTurtle new Turtle(myWorld);
Class name definesthe type
Makes anew object
Constructor:Method thatinitializes anew obj.
Object (Instance) MethodsObject (Instance) Methods
The behavior of an object is defined by themethods that belong to the method.The behavior of an object is defined by themethods that belong to the method.
Each instance of an object has it own copyof all the methods defined in the object’sclass that are not Class Methods.Each instance of an object has it own copyof all the methods defined in the object’sclass that are not Class Methods.
Turtle turtle1 new Turtle(myWorld);Turtle turtle1 new Turtle(myWorld);
Turtle turtle2 new Turtle(myWorld);Turtle turtle2 new Turtle(myWorld);
turtle1.turnRight();  turtle2.turnRight();turtle1.turnRight();  turtle2.turnRight();
Note: both turtles have a turnRight method
Class MethodsClass Methods
Some classes have methods that belong to theclass and not an instance of the class.Some classes have methods that belong to theclass and not an instance of the class.
java.Mathjava.Math
Class that defines math functions to useClass that defines math functions to use
Would not want multiple math objects that eachimplement an abs method.Would not want multiple math objects that eachimplement an abs method.
Class methods are methods that belong to only theclass and hence there is only one copy of themethod for all objects of the class.Class methods are methods that belong to only theclass and hence there is only one copy of themethod for all objects of the class.
int myVal Math.abs(-12);int myVal Math.abs(-12);
Basic Java ProgramBasic Java Program
// if you have to add import statements put// if you have to add import statements put
//them here//them here
public class CS1Test {public class CS1Test {
  public static void main(String [] args) {  public static void main(String [] args) {
     // put you Java program statements here     // put you Java program statements here
  }  }
}}
You will see what this is for in minute.You will see what this is for in minute.
Working With TurtlesExample of using classesWorking With TurtlesExample of using classes
Get world for our turtle to live inGet world for our turtle to live in
World csExWorld new World();World csExWorld new World();
Put turtle in our worldPut turtle in our world
Turtle ourTurtle new Turtle(csExWorld);Turtle ourTurtle new Turtle(csExWorld);
Check the state of our turtleCheck the state of our turtle
System.out.println(ourTurtle);System.out.println(ourTurtle);
System.out.println(ourTurtle.toString());System.out.println(ourTurtle.toString());
Parameterthatspecifiesthe worldto put theturtle in.
Talking to TurtleTalking to Turtle
When we want an object to do somethingwe send it message.When we want an object to do somethingwe send it message.
Make the turtle wander aroundMake the turtle wander around
ourTurtle.forward(20);ourTurtle.forward(20);
ourTurtle.turnLeft();ourTurtle.turnLeft();
ourTurtle.forward(40);ourTurtle.forward(40);
ourTurtle.turn(45);ourTurtle.turn(45);
ourTurtle.forward(65);ourTurtle.forward(65);
How Do Know What Turtles CanDo?How Do Know What Turtles CanDo?
The set of methods that define what classcan do is called an API (Application ProgramInterface).The set of methods that define what classcan do is called an API (Application ProgramInterface).
Java defines special format called JavaDocfor presenting APIs.Java defines special format called JavaDocfor presenting APIs.
You can find link to the doc on thedesktop of the lab machines and atC:\JavaDocumentation\Intro2CS\doc\index.html.You can find link to the doc on thedesktop of the lab machines and atC:\JavaDocumentation\Intro2CS\doc\index.html.
Problem: Draw squareProblem: Draw square
Describe how the turtle will travel in square.Describe how the turtle will travel in square.
Program Code:Program Code:
//draw side one//draw side one
ourTurtle.forward(100);ourTurtle.forward(100);
// turn 90 deg counterclockwise// turn 90 deg counterclockwise
ourTurtle.turnLeft();ourTurtle.turnLeft();
// draw side two// draw side two
ourTurtle.forward(100);ourTurtle.forward(100);
// turn 90 deg counterclockwise// turn 90 deg counterclockwise
ourTurtle.turnLeft();ourTurtle.turnLeft();
// draw side three// draw side three
ourTurtle.forward(100);ourTurtle.forward(100);
//turn 90 degrees counterclockwise//turn 90 degrees counterclockwise
ourTurtle.turnLeft();ourTurtle.turnLeft();
// draw side four// draw side four
ourTurtle.forward(100);ourTurtle.forward(100);
Reusing CodeReusing Code
What if we wanted to draw secondsquare?What if we wanted to draw secondsquare?
We would have to retype the code secondtime.We would have to retype the code secondtime.
Not good! Is not there better way?Not good! Is not there better way?
Define method that draws square.Define method that draws square.
We can invoke it every time we need todraw square.We can invoke it every time we need todraw square.
The drawSquare MethodThe drawSquare Method
public void drawSquare() {public void drawSquare() {
//draw side one//draw side one
this.forward(100);this.forward(100);
// turn 90 deg counterclockwise// turn 90 deg counterclockwise
this.turnLeft();this.turnLeft();
// draw side two// draw side two
this.forward(100);this.forward(100);
// turn 90 deg counterclockwise// turn 90 deg counterclockwise
this.turnLeft();this.turnLeft();
// draw side three// draw side three
this.forward(100);this.forward(100);
//turn 90 degrees counterclockwise//turn 90 degrees counterclockwise
this.turnLeft();this.turnLeft();
// draw side four// draw side four
this.forward(100);this.forward(100);
}}
}
Body of the method
Parenthesesrequired
Opening and Closing BraceRequired
1.Open the Turtle.java filefound in C:\intro-prog-java\bookClasses
2.Put the method definition atthe bottom of the classwhere the documentationdirects.
3.Create a World, a Turtle,and draw a square.
How do we draw two squares?How do we draw two squares?
Call drawSquare() twice.Call drawSquare() twice.
What happened?What happened?
Cannot call drawSquare again it will draw over topthe square we have drawn.Cannot call drawSquare again it will draw over topthe square we have drawn.
Need to move the Turtle before we draw again.Need to move the Turtle before we draw again.
How? Look at documentationHow? Look at documentation
Pen upPen up
Move to new positionMove to new position
Pen downPen down
ParametersParameters
How do we draw squares of different sizes?How do we draw squares of different sizes?
Observation: Each time we draw square weneed to change the 100 to the size we want.Observation: Each time we draw square weneed to change the 100 to the size we want.
This could generate lot of almost identicalmethods.This could generate lot of almost identicalmethods.
Use parameter to specify the width.Use parameter to specify the width.
public void drawSquare(int width) … }public void drawSquare(int width) … }
Change 100 to widthChange 100 to width
Call as:Call as:
ourTurtle.drawSquare(50);ourTurtle.drawSquare(50);
Draw the squares in Different ColorsDraw the squares in Different Colors
Back to the documentationBack to the documentation
public void setColor(java.awt.Color color)public void setColor(java.awt.Color color)
Need Color object found in java.awt packageNeed Color object found in java.awt package
Must import this package to use itMust import this package to use it
Find information in Java 1.5 API DocumentationFind information in Java 1.5 API Documentation
InvokeInvoke
ourTurtle.setColor(Color.BLUE);ourTurtle.setColor(Color.BLUE);
Draw blue square.Draw blue square.
How do you …?How do you …?
Save the program?Save the program?
Put it in CSTurtleTest classPut it in CSTurtleTest class
Hide the turtle?Hide the turtle?
Draw the squares at an angle to thewindow?Draw the squares at an angle to thewindow?