answers

advertisement
Unit 3 – Classes, Objects and Methods – Practice Quiz / Homework
Identifiers:
Circle each of the following that are valid identifiers:
hElLoWoRlD
3pigs
return
_tricky
ALL_CAPS
num5
far out
value
surprise!
Data Types and Assignment Statements:
For each of the following write one or two lines of code to declare and initialize or construct the
variable/object.
An integer named favorite which will be set to 42.
int favorite = 42;
A decimal number named totalMoney which will be initialized to $2.54
double totalMoney = 2.54;
A Turtle named sue.
Turtle sue = new Turtle( );
A Rectangle named mySpace with that is 40x60, with the top-left corner at (120, 50).
Rectangle mySpace = new Rectangle(120, 50, 40, 60);
Methods:
For each of the following, write a method header (the one line of code that would start the method
when it is declared within a class.)
A method named increaseSpeed, which receives no parameters and increases the instance
variable speed by one.
public void increaseSpeed( )
A method called getAge which returns the integer value of age.
public int getAge( )
A method named calcSum that receives two decimal numbers and returns their sum.
public double calcSum(double n1, double n2)
A constructor method for the SpaceShip class that receives its destination as a String when it is
constructed.
public SpaceShip(String dest)
Using the API: (You will need to look at the API online to answer these questions.)
Name two methods you could use from the Scanner class.
Many possible answers.
What import statement would be needed to use the Color class?
import java.awt.Color;
Can a File object be constructed without giving the constructor any parameters?
NO
What data type is returned when you call the startsWith method from a String object?
boolean
What is the difference between a public and private variable?
What is the difference between a class and an object?
What are two different ways to put a comment into java code?
//
/*
*/
What is an IDE?
Write a class using java that meets the following specification: (use a separate sheet of paper.)






The name of the class will be ScoreKeeper
There will be two private instance variables
o teamName which is a String
o score which is an integer
Provide a constructor which receives the team’s name as a parameter. Initialize teamName to
that value and set score to zero.
Provide an accessor method called getScore which returns the value of score.
Provide a method called changeName which receives a String and changes teamName to that
value.
Provide a method called addToScore which receives an integer and increases the value of score
by that much.
public class ScoreKeeper
{
private String teamName;
private int score;
public ScoreKeeper(String name)
{
teamName = name;
score = 0;
}
public int getScore()
{
return score;
}
public void changeName(String newName)
{
teamName = newName;
}
public void addToScore(int amount)
{
score = score + amount;
}
}
Download