Download Chapter 2

Document related concepts
no text concepts found
Transcript
Chapter 2
Data Types, Input, and Output
Go
Section 1 - Java Data Types
Go
Section 2 - Declaring and Initializing Variables
Go
Section 3 - Arithmetic Operators & Assignment Statements
Go
Section 4 - Using Scanner Objects and Concatenation
Go
Section 5 - Syntax and Compile-Time Errors
Go
Section 6 – Introduction to Calling Methods
Go
Section 7 - Simple Graphics Programs
Chapter 2 - Section 1
Java Data Types
2
2.1 Primitive Data Types
Java has two different kinds of data types or data values. They are
primitive data types and object data types.
Primitive data types. These are low-level data types. They are:
•
int - an integer, in other words, a whole number like any of the
following …. -2, -1, 0, 1, 2, …..
•
double - a floating-point number, real number (4.2876 or -7.53)
•
boolean - holds only one of two values: true or false
•
char - any one character on the keyboard, whether it is an
alphabetical letter, symbol, or number as in ‘A’, ‘k’, ‘$’, ‘#’, or ‘8’.
A char value always has single quotes around it. So ‘8’ is a
char and is considered text, but 8 is an int that can be used in a
mathematical calculation.
3
2.1 Object Data Types
Object data types. These are high-level data types. Examples are:
•
String - one or more characters that can make up letters,
words, phrases or sentences. Each value is surrounded by
double quotes as in … “KCD Bearcats”. (Not the same as char)
•
Scanner - an object that can read data values from the
keyboard or from files.
•
Color - an object that has red, green, and blue components that
together identify a specific color.
•
JApplet - a window object that can contain a drawing surface
and GUI components. Remember, GUI stands for Graphical
User Interface.
4
2.1 Java’s Six Primitive Numeric Data Types
•
There are four other numeric data types besides int and double, but
we will not use them. However, there are all six numeric types. The
two primary integer data types are:
–
int
(a 32 bit integer - 4 bytes)
–
long
(a 64 bit integer - 8 bytes)
The two primary floating-point data types are:
–
float (a 32 bit floating-point - 4 bytes)
–
double (a 64 bit floating-point - 8 bytes)
Each uses a different number of bytes for storage and each has a different
range of values. We will use only int and double in this class. If you’re
interested, more on these data types can be found at:
Java’s Primitive Data Types
5
2.1 Int and Double Storage Requirements
Data Type
Storage Requirements
Range of Values
int
4 bytes
-2,147,483,648 to 2,147,483,647
double
8 bytes
-1.79769313486231570E+308 to
1.79769313486231570E+308
These are the only two storage requirements you need to be familiar
with. You don’t need to memorize the values.
When we declare an int variable, 4 bytes of memory are allocated.
This is 32 bits … meaning we can have many 32 different
combinations of 1s and 0s. In fact, there are 4,294,967296 possible
combinations. If we divide this number in half, then we get
2,147,483,648. Half of the int range is set aside for negative values
and half of the values are used to represent 0 or positive values.
6
2.1 Char and Boolean Data Types
Most programmers very seldom use the char data type, because the
String data type can be one character or many characters. However,
it is nice that this primitive data type exists, as it can be useful in some
applications. However, we won’t use the char data type.
The boolean data type is much more useful, because many programs
have operations that need to be performed if a condition is true and
other operations that need to be performed if a condition is false.
Programmers use boolean variables and boolean values a lot while
writing code.
7
2.1 The String Object Data Type
String data values are similar to char data values, however, String
values can hold as many characters as needed. Remember that a
char data value can hold only one character. A String value is an
object data type, not a primitive data type. However, a String
variable’s declaration and initialization looks similar:
String phrase = “Java Rules”;
Most objects are constructed but String objects are
special and this line of code constructs and initializes.
Note that instead of single quotes that are used for char values, double
quotes are used for String values.
The line of code above creates a String object that is referred to by the
variable phrase and the String object contains the value “Java
Rules”.
8
2.1 Scanner and Color Object Data Types
We mentioned briefly some other object data types, including
Scanner and Color object data types. Objects of these classes
must be formally constructed first before they can be used.
They are constructed using the Java keyword named new.
Briefly here is how you do it:
Scanner reader = new Scanner (System.in);
Color myColor = new Color (red, green, blue);
9
Chapter 2 - Section 2
Declaring and Initializing Variables
10
2.2 Primitive and Object Variables
•
The Java syntax (rules) for using variables that hold primitive data
types differs for variables that hold object data types:
–
Primitive variables are declared and initialized. They are not
constructed.
–
Object variables are declared and then an object is constructed
for the variable to refer to.
•
Important points to remember about any variable:
–
The value a variable holds may change while a program is
running.
–
A variable’s type cannot change while a program is running. If
you declare a variable to be of type int, then you can’t change it
to type double somewhere else in the program.
11
2.2 A Variable Identifies a Memory Address
Programs use variables to temporarily store values so the values can
then be used while the program is running.
A variable identifies a memory address (memory location) in RAM
memory where a value can be stored.
A variable is considered to be a nickname for the memory address.
A programmer gets to decide on the names of variables. By picking
meaningful names, the code becomes more understandable.
We can think of a variable as a small box that holds a value.
X
Y
name
an int variable
a double variable
a string variable
12
2.2 Int & Double Variables
When you need to use primitive data values in a program, you can
“create” variables to store the values in by declaring them without
giving them an initial value.
int z;
declare z to be a variable of type int
int x;
declare x to be a variable of type int
double pi;
declare pi to be a variable of type double
double num;
declare num to be a variable of type double
To declare a variable, you write its data type first, like int or double,
and then you write the variable name.
13
2.2 The Java Assignment Operator
We call the = sign … the assignment operator.
We use the assignment operator in Java to create assignment
statements.
Assignment statements are equations that only store a value in one
direction. The value or expression on the right side of the =
operator is stored in a variable on the left side of the = operator.
The assignment operator can be used to give a variable an initial value
as in …
int totalPoints = 0;
double kilometers = 1.0;
direction of storage: right to left
direction of storage: right to left
14
2.2 Int & Double Primitive Data Types
When you declare variables you can also initialize them (give them an
initial value) when they are declared.
int z = 10;
declare z as an int and initialize to 10
int x = 15;
declare x as an int and initialize to 15
double pi = 3.14159;
declare pi as an int and initialize to 3.14159
double num = 32.47;
declare num as an int and initialize to 32.47
Notice that we initialize the variables above by using the = sign and
placing a value on the right side of the = sign. This stores the value
on the right side of the = sign into the variable on the left side.
15
2.2 Char and Boolean Variables
A char value is only one character. So a char variable can hold only
one character. The character can be an alphabetical letter,
numeric digit, or a symbol. For example, the following are all valid
declarations and initializations:
char letter = ‘A’;
char digit = ‘8’;
char symbol = ‘#’;
Note: all char values must be
surrounded with single quotes to
designate that they are char values.
Don’t use double quotes!
A boolean variable can hold only one of two values: true or false
boolean done = false;
boolean good = true ;
Note: the values true and false do NOT
have double quotes around them!
16
2.2 Declaring and Using String Variables
String variables are variables that are used to store words, phrases, or
even sentences. Why do we call them String? Because if you string
together one or more letters, you have either a word, a phrase, or a
sentence. Here are some examples.
String letter = “A”;
String word = “Java”;
String phrase = “Cool Java Code”;
String sentence = “Java is the best language available!”;
Again, Strings are not like simple int, double, char or boolean primitive
values. Strings are what we call object values. They use up more
memory than primitve variables and methods can be called that
perform operations on them.
17
2.2 The Names of Java Classes
In Java, the name of a class always has the first letter capitalized. For
example, the String class defines objects of type String, so the ‘S’
is capitalized.
In Java, there are a number of kinds of classes. Right now you just
need to know that there are two kinds of Java classes:
1.
A class that is a “driver program” that has a main method that you
can run and see some kind of output. An example, is the Rocket
program. The class declaration line was: public class Rocket
2.
A class that is a “model class” that defines or models a type of
object, like String. This kind of class is not a driver program and
you cannot run it to see output of any kind. The purpose is only to
define a type of object … its characteristics and behavior.
18
Chapter 2 - Section 3
Java’s Arithmetic Operators
and
Assignment Statements
19
2.3 Java’s 5 Arithmetic Operators
Primitive data types may be combined in expressions with Java operators.
Java has 5 mathematical operators:
Addition is represented by the + sign.
Subtraction is represented by the - sign.
Multiplication is represented by the * sign.
Division is represented by the / sign.
Mod is represented by the % sign. Mod gives the remainder of int division.
(You’ll be amazed at how much you will use mod)
These operators can be used in Java “equations”. However in Java, we call
equations … assignment statements. We call them assignment
statements because they are assigning a value to a variable.
20
2.3 Assignment Statements with Arithmetic
Operators
Here is an example where all in one line of code, the variable is celsius
is declared and initialized using a full fledged assignment statement
that has an equation in it that uses Java’s arithmetic operators:
double fahrenheit = 212.0;
double celsius = ( fahrenheit - 32.0 ) * 5.0 / 9.0;
The variable celsius will have 100.0 stored in it.
The above line of code uses three different mathematical operators
and ( ).
Here is another assignment statement:
double area = 3.14159 * radius * radius;
21
Chapter 2 - Section 4
Using Scanner Objects to Receive
Input from the Keyboard
and Concatenation
22
2.4 The Scanner Object Data Type
The Scanner data type is an object data type, not a primitive data type.
A Scanner object allows us to read data input from the keyboard.
Before we can do that we must construct an object of the Scanner
class and declare a variable to refer to that object. Here is how we
do that:
Scanner reader = new Scanner (System.in);
In this line we use the name of the class Scanner twice. The Scanner
variable is reader and we use System.in, because the keyboard is
the default input device for a Scanner object. The word new
indicates that an object is being constructed … new is a special
Java “reserved word” and cannot be used as a variable or for any
other purpose. So, new is used to create or construct objects.
23
2.4 Assigning the Scanner Variable
If we want to construct a Scanner object in a program, we must first
import Java’s Scanner class with the line:
import java.util.Scanner; // goes above the class declaration line
Then, inside the main method, we can construct the Scanner object.
Scanner reader = new Scanner (System.in);
Did you notice the assignment operator in the line of code? This is
what lets us make reader refer to the newly constructed Scanner
object.
24
2.4 Constructing a Scanner Object with new
In the line of code :
Scanner reader = new Scanner(System.in);
the name of the class Scanner is used twice.
The first part of the line:
Scanner reader
declares reader to be an object variable of type Scanner. We need to
do this or reader can’t refer to the Scanner object we construct.
The second part of the line:
new Scanner(System.in);
constructs the Scanner object and “attaches it” to the keyboard.
The assignment operator = makes reader refer to the Scanner object.
25
2.4 General Form for Constructing Objects
•
In programming, the process of constructing an object is called
instantiation.
•
In general, constructing or instantiating an object takes the general
form:
<Name of Class> <variable> = new <Name of Class> (<parameters>);
You can see that the line of code below follows this form:
Scanner reader = new Scanner (System.in);
You can think of reader as something that is “scanning the keyboard
waiting to receive input”.
26
2.4 Reading Different Data from the Keyboard
Scanner reader = new Scanner (System.in);
System.out.print(“Enter your name and press return: ”);
String name = reader.nextLine();
System.out.print(“Enter your age and press return: ”);
int age = reader.nextInt();
System.out.print(“Enter your gpa and press return: ”);
double gpa = reader.nextDouble();
Notice when we prompt the user, we use a print statement NOT a
println statement. This tells the user when to enter data. We can
receive different kinds of input using reader. We use the object
variable reader to “call the method nextLine() to receive a String
value from the keyboard. We can also use the same reader
variable to “call the method nextInt() to receive an integer and we
can use reader to “call the method nextDouble() to receive a
floating-point value from the keyboard.
27
2.4 Echoing the Input from the Keyboard
We can now “echo the input” (print the information back to the screen
that was entered) by using some println statements. In each line,
we will print a literal string (something in double quotes) and the
value contained in a variable. We use a plus sign to concatenate
the literal string value and the value stored in the variable together
to make a larger string that is then printed.
System.out.println(“Your name is: ” + name);
System.out.println(“Your age is: ” + age);
System.out.println(“Your gpa is: ” + gpa);
Notice that there are no double quotes around the variables name,
age, and gpa because they are variables and a space has been
added before the final double quotes ” for spacing.
28
2.4 The DistanceConverter Program
package ch02;
import java.util.Scanner;
public class DistanceConverter
{
public static void main (String[] args)
{
Scanner reader = new Scanner(System.in);
double miles;
double kilometers;
System.out.print("Enter the number of kilometers: ");
kilometers = reader.nextDouble();
miles = kilometers * 0.621371192237334;
System.out.println("The number of miles equivalent to " +
kilometers + " kilometers is: " + miles);
}
}
Note the key Scanner lines identified by the red arrows.
29
2.4 Concatenation Inside a Println Statement
Here is an example of concatenating numerous items as one parameter:
System.out.println (kilometers + " kilometers is equivalent to " + miles + " miles.");
In Java, the plus + symbol doubles as the addition operator and the
concatenation operator. Concatenate means to put or join together. So
we can simply concatenate any number of items that we want to output to
the screen. Here the code concatenates four items together:
The value stored in the variable kilometers
The literal String value … " kilometers is equivalent to "
The value stored in the variable miles
The literal String value … " miles."
When Java executes this it doesn’t print the name of the variables kilometers and miles
but rather retrieves the value in the variables and then prints them.
30
2.4 Concatenating Numerous Items
Some other things to mention about this line of code:
System.out.println (kilometers + " kilometers is equivalent to " + miles + " miles.");
Notice there are NO double quotes around the variables. You never
place double quotes around any variable … only literal string
values.
Also, notice the blank spaces at the beginning and end of some literal
string values. This keeps the numbers from being jammed up
against the words when it is all displayed to the screen.
31
2.4 More about Import Statements
In the DistanceConverter.java code you saw that the first line after
the package declaration was an import statement:
import java.util.Scanner;
This tells Eclipse where to find a class that will be used during the
program. The class may be either in a Java library file or another
file you have in a folder. The import statement contains the path
name of where to find the class.
The import statement tells us that the Scanner class is found in a
sub-package folder named util that is in the java package folder.
Now you know enough that you can finish the second half of the
DistanceConverter.java program!
32
Chapter 2 Section 5
Syntax and Compile-Time
Errors
33
2.5 Syntax Errors
Syntax errors keep a program from compiling and running until the
errors are corrected. Examples are:
•
forgetting to place a semicolon after Java lines that need it
•
forgetting one of the two ( ) when calling a method like println.
•
forgetting to place double quotes where they are needed.
•
misspelling Java key words like print, println, System, public, and
class.
Syntax errors are a form of compile-time errors. A syntax error will
keep your program from compiling and running.
34
2.5 Compile-Time Errors
Some errors are not syntax errors. They are just compile-time errors.
Here are some examples:
•
not storing the class in a file with the same name.
•
trying to store a data value of one type in a variable of another
type.
•
leaving out the opening or ending curly brace for a method.
If you try to run a program that has syntax or compile-time errors, a
compiler like Eclipse will halt the process and display error
messages in the console window that …
•
indicates the type of error detected
•
35
indicates the file and line number where the error was detected
2.5 How Eclipse Points Out Errors
•
Eclipse will …
1.
2.
3.
•
describe the error in the source code window
tell the line of code where the error is
suggest a solution to the error when you mouse over the bad code.
Eclipse displays a red circle with an X in it to the left of any line that
has a syntax error.
•
Eclipse will display a red box with an X in it for any line that has a
compile-time error.
•
You can …
–
–
mouse over the red circle or red box and a message will pop-up
that describes the error.
click on the red circle or red box and then choose an option of
how to correct it. This saves time if you choose the correct fix,
then the error will be corrected automatically for you.
36
2.5 The Readability of Code
It is important for your code to be readable by others. In the real world,
programmers are on software teams as they develop and maintain
software. So everyone must be able to read your code!
Programmers have developed a standard for how code should be
formatted.
•
•
The main factors that determine whether code is readable or not are
–
Spacing (referring to extra blank lines that space things out)
–
Indentation (referring to tabs or indentions on a specific line)
–
meaningful variable names … taxableIncome instead of ti.
Spacing and Indentation are just for programmer readability. The
compiler ignores any kind of spacing and indentation. It just checks
to make sure that everything is syntactically correct (spelled
correctly)!
37
2.5 Eclipse Auto Indenting
Eclipse assists you with indenting segments of code as you type by
automatically properly indenting your next line, but if you place too
many tabs or blank spaces in the wrong place so that the code’s
appearance is not consistent, then you can select all of your code
and then “auto indent” it.
On a Windows computer, select all code by typing Control “a” and then
type Control “i”.
On an Apple computer, select all code by typing Command “a” and
then type Command “i”.
These two steps will auto indent your code. It won’t however, delete
extra blank lines so if you have too many you will have to delete
those yourself.
38
Chapter 2 – Section 6
Calling Methods
39
2.6 Why are there Java Methods?
Many times the same code needs to be executed over and over again
in a program. Instead of writing the code over and over again, we
just write it once and put it in a method. A synonym for a method
is an operation. Then, anytime we want to execute or run that
code, we just call the method and pass it what it needs and it will
do the work for us.
This not only saves time for programmers who are writing a program,
but if the method and possibly other methods are put in their own
class, then those methods can be called from any program! This
is one of the most important aspects of any programming
language. Some languages call methods procedures or functions.
40
2.6 Method Calls with Parameters
Consider the following line of code:
System.out.println(“Hello World!”);
•
System is a class and out is an object of that class that
knows how to display or print characters in a console or terminal
window.
•
println is the name of the method (operation) being executed.
•
“Hello World”, inside the parentheses, is the parameter of
what needs to be printed. Here the parameter is a string (string of
characters) that make up the words “Hello World”. Notice they
appear in quotation marks. This tells Java to print to the screen
the literal string value “Hello World”. The parameter could be a
variable that contains a value instead of a literal string value in
double quotes.
41
2.6 General Rule of Calling Methods
The general form for calling methods is:
<name of object> . <name of method> (<parameters>)
A message may require zero, one, or numerous parameters. Here
are some examples:
To print a blank line, we can use System.out.println(); without any
parameters in the ( ).
To print “Hello World”, we need only one parameter the literal string
value “Hello World” in the parenthesis …
System.out.println(“Hello World!”);
Some methods are not called with an object, so in that case the name
of the method is just used.
42
2.6 The Method Selector is the Period
The Method selector operator is the period . It is placed between System,
out, and either print or println in output statements as seen here …
System . out . println (kilometers + " kilometers is equivalent to " …
and it is placed between System and in when we construct a new Scanner
object that reads input from the keyboard.
Scanner reader = new Scanner(System.in);
It is always placed between an object variables’ name and the name of a
method that is being called. Below, the object variable is reader and the
methods being called are nextInt(), nextDouble(), and nextLine().
System.out.println(“Enter an integer: ”);
int num1 = reader.nextInt();
System.out.println(“Enter a floating-point number: ”);
double num2 = reader.nextDouble();
System.out.println(“Enter your name: ”);
String name = reader.nextLine();
43
2.6 Calling nextInt() and nextDouble()
In these two input lines, we use the Scanner variable reader to call the
nextInt() and nextDouble() methods.
int num1 = reader.nextInt();
double num2 = reader.nextDouble();
Notice there are no parameters
to pass nextInt or nextDouble so
the ( ) are empty.
First, we wish to read an integer from the keyboard, so we call nextInt() and
the method returns us an int value that we store in the int variable num1.
Second, we wish to read a floating-point number from the keyboard, so we call
nextDouble() and the method returns us an double value that we store in
the double variable num2.
When a program runs and it encounters a line like reader.nextInt() or
nextDouble(), the program will pause and wait for something to be
entered from the keyboard. Once the user enters a value and presses
return, the program continues and the value is stored in the input variable
and then the other lines of code in the program are executed.
44
2.6 Summary of Simple and Object Variables
In the DistanceConverter.java program, simple variables like
kilometers and miles each hold a single floating-point number.
Object variables like reader and System.out hold references to
objects.
Object variables are used to call methods or as programmers like to
say “send messages to objects” … reader.nextDouble() sends the
message “get me the next floating point number” from the keyboard.
In summary, to write effective Java programs, a programmer does not
need to have detailed knowledge of the inner workings of any
object, he or she just needs to know how to construct objects and
how to send messages to the object by calling methods.
45
Chapter 2 Section 7
Simple Graphics Programs
46
2.7 JApplet Windows
Windows have numerous properties.
•
Width and heigh
•
Ability to be dragged or resized by the user
The code for applet windows is located in the class JApplet,
which is imported from the package javax.swing. To use this
class you need to import it with the statement:
import javax.swing.JApplet;
47
2.7 AppletWindow1.java Code
This code produces an empty window that is 300 pixels wide
and 200 pixels high.
package ch02;
import javax.swing.JApplet;
public class AppletWindow1 extends JApplet
{
private static final long serialVersionUID = 1L;
public void init()
{
resize(300, 200);
}
}
48
2.7 AppletWindow1.java Output
The output will look something like this.
An applet window is really just an empty container that we can draw
and paint on or fill with other objects.
49
2.7 The Graphics Context g
You can draw or paint in an applet window by using the
object g, which is formally called the graphics context.
You can think of g as both a pencil that can draw and a
paint brush that can paint. You can set the color of g so
that it will draw with a specific color or paint with a
specific color.
50
2.7 Using Java’s Colors
In Java, there is a Color class that defines various Color constants
and allows you to create your own colors. To use Color constants
in your code, you must import the Color class by including:
import java.awt.Color;
To change the current drawing and painting color to red, use the
paint brush g to call the setColor() method as follows:
g.setColor(Color.red);
Note the dot “.” between g (an object) and setColor (a method) and
in parenthesis since red is a color constant of the Color class we
must use Color.red with a capital C .
51
2.7 Java’s Default Color Constants
Color Constant
RGB Value Construction
Color.red
new Color (255, 0, 0)
Color.green
new Color (0, 255, 0)
Color.blue
new Color (0, 0, 255)
Color.yellow
new Color (255, 255, 0)
Color.cyan
new Color (0, 255, 255)
Color.magenta
new Color (255, 0, 255)
Color.orange
new Color (255, 200, 0)
Color.pink
new Color (255, 175, 175)
Color.black
new Color (0, 0, 0)
Color.white
new Color (255, 255, 255)
Color.gray
new Color (128, 128, 128)
Color.lightGray
new Color (192, 192, 192)
Color.darkGray
new Color (64, 64, 64)
If you were going to construct these colors by yourself, you would
use the 3 integer values in the parenthesis.
52
2.7 AppletWindow2.java Code
// This code produces an empty, pink panel.
// Note if you try to add a second panel to this JFrame, then you won't see them both unless you
// specify what region of the default BorderLayout you are adding the panel to.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class AppletWindow2 extends JApplet
{
public void init()
{
resize(800, 600);
}
public void paint(Graphics g)
{
super.paint(g);
g.setColor(Color.pink);
g.fillRect(0, 0, 800, 600);
}
}
53
2.7 Customized Colors
You can construct a customized color if the color you need is not one of the
Color constants seen on the previous slide.
You can construct a new Color object by using three int values between 0 and
255 with:
Color aColor = new Color(redValue, greenValue, blueValue);
In this code, redValue, greenValue, blueValue must be integer values.
You would then use the code:
g.setColor(aColor);
( don’t use Color.aColor in () )
Here is an actual example:
Color brown = new Color(164, 84, 30);
g.setColor(brown );
(don’t use Color.brown in () )
54
2.7 AppletWindow2.java Code Modified
// This code produces an empty, midnight blue colored panel using the Color Constructor code.
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.*;
public class AppletWindow2 extends JApplet
{
public void init()
{
resize(800, 600);
}
public void paint(Graphics g)
{
super.paint(g);
Color myColor = new Color (51, 0, 153);
g.setColor(myColor);
g.fillRect(0, 0, 800, 600);
}
}
55
Now we’re ready to start the
GeometryApplet program.
Information about the
Java Coordinate System and
the Individual Drawing and Painting
Commands are Contained in a
Separate Online Presentation named
Java Graphics
56