Transcript Java

Java Variables
▮ Types of variables
▮ Creating, modifying and displaying
▮ Comparing
▮ Converting between types
▮ TextField
Non-graded Assg
Chapter 5
© copyright Janson Industries 2014
1
Variables
▮ Used to access data (and objects) in
classes
▮ Variables are declared. That means
defining the variable’s:
▮ Identifier (name)
▮ Type
▮ Java’s basic variable types are called
Primitive Data Types
Chapter 5
© copyright Janson Industries 2014
2
Variables
▮ Two types: Primitive & Referenced
▮ Primitive variables:
▮ Hold a value
▮ Type names begin with lowercase letters
▮ Referenced variables:
▮ Hold the storage location of an object
▮ Type names begin with uppercase letters
Chapter 5
© copyright Janson Industries 2014
3
Primitive Data Types
▮ boolean: true or false (default is false)
▮ char: single character, use single quotes
▮ byte: 8 bit whole number (-128 to 127)
▮ short: 16 bit whole number (32,767 max)
▮ int: 32 bit whole number (2**31 max)
▮ long: 64 bit whole number
▮ float: floating point (7 decimal place max)
▮ double: double precision (15 dec places)
Chapter 5
© copyright Janson Industries 2014
4
Variable Name Rules
▮ Must begin with a character
▮ Can be made of letters, numbers, _, or $
▮ No
▮ Special characters (%, #, @, etc.)
▮ Spaces
▮ Reserved words (new, class, static, etc.)
▮ Are case sensitive!!
Chapter 5
© copyright Janson Industries 2014
5
Defining and Assigning
▮ Primitive data type then variable name
▮ int numberOfDependents;
▮ char gender, maritalStatus;
▮ A value can be assigned when the variable
is declared:
▮ float taxRate = .28;
▮ Or a value can be assigned later:
▮ numberOfDependents = 2;
Chapter 5
© copyright Janson Industries 2014
6
Values
▮ Calculated values can be assigned using
standard operators: +, -, *, /. Ex:
int counter;
counter = counter + 1; counter++; ++counter;
▮ When dividing two integers, decimal
remainder truncated
▮ Dividing float and integer, integer
“promoted” to float
▮ Standard order of operator precedence
Chapter 5
© copyright Janson Industries 2014
7
Values
▮ Use PRINT
System.out.print(“The answer
answer is:
is: ”);
”);
System.out.print(“The
System.out.print(answer);
System.out.print(answer);
▮ Assuming answer is boolean with value
of true, results in:
The answer is: true
▮ Or PRINTLN. Does a carriage return so
System.out.println(“The answer is: ” + answer);
▮ To get same result
Chapter 5
© copyright Janson Industries 2014
+ concatenates
text or variables8
Pre/Post Inc/Decrement
▮ Standalone Pre/Post expressions
(++counter; counter++;) do the same thing
▮ Within a larger expression they are different
int counter = 1;
System.out.println("Counter
System.out.println("Counter
System.out.println("Counter
System.out.println("Counter
▮ Result is:
Chapter 5
Counter
Counter
Counter
Counter
=
=
=
=
=
=
=
=
"
"
"
"
+
+
+
+
counter);
++counter);
counter++);
counter);
1
2
2
3
© copyright Janson Industries 2014
9
Pre/Post Inc/Decrement
▮ To do the same thing without Pre/Post
expressions requires more coding
int counter = 1;
System.out.println("Counter
counter = counter + 1;
System.out.println("Counter
System.out.println("Counter
counter = counter + 1;
System.out.println("Counter
Chapter 5
= " + counter);
= " + counter);
= " + counter);
= " + counter);
© copyright Janson Industries 2014
10
Values
▮ Some math functions are performed with
java supplied methods not operators
▮ These methods are stored in the Math class
▮
▮ Math is part of java.lang package
▮ No need to import or declare Math
because java.lang automatically imported
▮ To invoke a static method
▮ Classname.methodName(parms)
Chapter 5
© copyright Janson Industries 2014
11
Look at documentation to see required parms
Chapter 5
© copyright Janson Industries 2014
12
To raise 12 to the fourth power:
double answer;
answer = Math.pow(12, 4);
Chapter 5
© copyright Janson Industries 2014
13
Referenced Types
▮ String & StringBuffer are examples
▮ StringBuffer provides more flexibility when
manipulating Strings
▮ Class name then variable name
▮ String name, address, phoneNumber;
▮ StringBuffer nameSB;
▮ Like primitives, you can assign a value
when declaring the variable or assign
one later
Chapter 5
© copyright Janson Industries 2014
14
Reference Types
▮ Have to create and assign an object to a
reference variable
▮ Object created with the “new” keyword
▮ String name = new String(“Joe”);
▮ StringBuffer nameSB = new StringBuffer(“Joe”);
▮ Alternative for String objects (not
recommended)
▮ String name = “Joe”;
Chapter 5
© copyright Janson Industries 2014
15
Referenced Types
▮ You can declare a referenced variable for a
class and then “instantiate” and assign the
object to the variable
Customer cust;
cust = new Customer(“Joe”, “1 Main St.”,
“Enid, OK 65654”);
▮ Assuming Customer is a java class, the
variable cust points to a Customer object
that contains the values
Chapter 5
© copyright Janson Industries 2014
16
For example: String
▮ If we set the value of a to Joe
a = new String(“Joe”);
▮ A String object with the text “Joe” is
placed in memory and a = A1
▮ If we then set b to “Joe”, a 2nd String
A
B
C
object with “Joe” is
1 Joe
placed in memory
2
Joe
and b = B2
3
Chapter 5
© copyright Janson Industries 2014
a
b
17
For example: String
▮ If we change the value of a
a = new String(“Art”);
▮ A String object with the value “Art” is
placed in memory
1
2
3
A
Joe
B
C
Joe
a
b
Art
▮ a = C3 and the first Joe is not referenced
Chapter 5
© copyright Janson Industries 2014
18
String
▮ However if we define c as equal to a:
String c = a;
▮ c = C3
1
2
3
Chapter 5
A
Joe
B
C
Joe
Art
© copyright Janson Industries 2014
a
b
c
19
Strings
▮ Are immutable (unchangeable)
▮ Assigning a new value to a String variable
creates a new String object
▮ It does not change any existing String object
that the variable references
String c = "Art";
c = “Joe”;
▮ There are now two String objects
▮ One with the text “Art” the other “Joe”
Chapter 5
© copyright Janson Industries 2014
20
String
▮ However, using the shortcut (i.e. not
explicitly creating a new object) will not
necessarily result in a new object
String c = "Art";
String b = “Art”;
▮ Only one object with text “Art”
String c = "Art";
String b = new String(“Art”);
▮ Two objects with text “Art”
Chapter 5
© copyright Janson Industries 2014
21
String
▮ Even this…
String b = new String(“Art”);
String c = "Art";
▮ ..results in two objects with text “Art”
▮ Beware of the shortcut
▮ This is also why StringBuffers are better
▮ Their value can be changed (more on this
later)
Chapter 5
© copyright Janson Industries 2014
22
Reference Variables
▮ If two Customer variables created as
follows:
Customer cust1 = new Customer(“Walmart”);
Customer cust2 = new Customer(“Walmart”);
▮ How many objects are there?
Chapter 5
© copyright Janson Industries 2014
23
Reference Variables
1
2
3
A
Walmart
B
Walmart
C
cust1
cust2
▮ 2 objects exist
Chapter 5
© copyright Janson Industries 2014
24
Reference Variables
▮ If the following statements are also
executed:
cust1 = new Customer(“Target”);
cust2.setCustName(“Sam’s”);
▮ How many objects are there?
▮ How many objects are referenced?
Chapter 5
© copyright Janson Industries 2014
25
Reference Variables
1
2
3
A
Walmart
B
C
Target
Sam’s
cust1
cust2
▮ 3 objects exist, 2 are referenced
▮ For an alternative explanation of variables:
▮ http://www.javaranch.com/campfire/StoryCups.jsp
Chapter 5
© copyright Janson Industries 2014
26
Null Pointer Exception
▮ Occurs when using a reference variable that
is not assigned to an object (pointer is null)
Customer cust1, cust2;
cust1 = new Customer(“Target”);
cust2.setCustName(“Sam’s”);
A
2
3
B
C
Target
cust1
cust2
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
Chapter 5
© copyright Janson Industries 2014
27
at packageName.className.methodName(fileName.java:lineNumber)
Primitive Variables
▮ Defining these two integers:
int a = 1; int b = 2;
▮ Results in a memory allocation of:
1
2
A
1
B
C
2
3
Chapter 5
© copyright Janson Industries 2014
28
Primitives
▮ If we change the value of a
a = 3;
▮ The value 1 is replaced with 3
1
2
A
3
B
C
2
3
Chapter 5
© copyright Janson Industries 2014
29
Referenced Types
▮ Proof: Printing Customer variable c would
result in memory address (hash code)
Chapter 5
Customer c = new Customer();
c.setContactPerson("Joe Samaritan");
c.setContactPhone("555-3333");
c.setCustName("Kindness Foods");
c.setShipToStreet("1 Milk of St.");
c.setShipToCity("Human");
c.setShipToState("ME");
c.setShipToZip("03234");
System.out.println(c);
© copyright Janson Industries 2014
30
Chapter 5
© copyright Janson Industries 2014
31
Why address?
▮ Because that is the value of the reference
variable
▮ If you wanted to see the Customers name, use
c.getName()
▮ Actually the Customer object's toString
method is invoked when println executed
▮ “Hey, we didn’t code a Customer.toString()
method!”
▮ toString inherited from Object class
▮ Object.toString returns address of an object
Chapter 5
© copyright Janson Industries 2014
32
We’ll prove it!
Chapter 5
© copyright Janson Industries 2014
33
In Customer, click Source, then
Override/Implement Methods
Click toString and specify it as the first method
after the class variables, then click OK
Chapter 5
© copyright Janson Industries 2014
34
Inserts new toString method that calls Object's
(the superclass’) toString method
Chapter 5
© copyright Janson Industries 2014
35
We’ll change to return customer name
Chapter 5
© copyright Janson Industries 2014
36
When we run CustApp and print
the Customer variable c
Try it: change Customer and CustApp
Chapter 5
© copyright Janson Industries 2014
37
Another Example
Object
toString
is a
Person
toString
is a
Name
has a
toString
Person is an object
Name is an object
Person has a name
Chapter 5
© copyright Janson Industries 2014
38
Inheritance Example
▮ We’ll create classes called Name and Person
// Name.java
public class Name extends Object {
String first;
String last;
String middle;
Method
Overloading
public Name(String f, String l)
{
first = f; last = l; middle = “ “;}
public Name(String f, String l, String m)
{
first = f; last = l; middle = m; }
}
Chapter 5
© copyright Janson Industries 2014
39
Example
// Person.java
public class Person extends Object {
int age;
Name name;
public Person() {
Person “is an”object
age = 0; }
public Person(int a, String f, String l) {
name = new Name(f, l);
Person “has a” name
age = a;
}
public Person(int a, String f, String l, String m){
name = new Name(f, l, m);
age = a;
}
}
Chapter 5
© copyright Janson Industries 2014
40
Example
▮ PersonFrame will instantiate 3 Person objects
// PersonFrame.java
import java.awt.*;
import java.awt.event.*;
public class PersonFrame extends Frame implements
WindowListener, ActionListener {
Button showButton = new Button("Show");
Label outputLabel1 = new Label();
Label outputLabel2 = new Label();
Label outputLabel3 = new Label();
Person newPerson1 = new Person(32, "John", "Smith");
Person newPerson2 = new Person(27, "Mary", "Jones", “Jo");
Person newPerson3 = new Person(42, "John", "Public", "Q");
Chapter 5
© copyright Janson Industries 2014
41
Example
public PersonFrame()
{ setLayout(null); this.setSize(500, 400);
showButton.setBounds(275,300,50,25);
outputLabel1.setBounds(112,200,350,15);
outputLabel2.setBounds(112,215,350,15);
outputLabel3.setBounds(112,230,350,15);
add(showButton); this.setVisible(true);
showButton.addActionListener(this);
addWindowListener(this);
add(outputLabel1);add(outputLabel2);add(outputLabel3); }
public void actionPerformed(ActionEvent e)
outputLabel1.setText("The new person is:
outputLabel2.setText("The new person is:
outputLabel3.setText("The new person is:
}
Chapter 5
{
" + newPerson1);
" + newPerson2);
" + newPerson3);
Uses the default
toString
method to display
© copyright Janson
Industries 2014
42
Example
public void windowActivated(WindowEvent e) {}
public void windowClosed(WindowEvent e) {}
public void windowClosing(WindowEvent e) {
this.dispose();
}
public void windowDeactivated(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public static void main(String args[]) {
PersonFrame pf = new PersonFrame();
}
}
Chapter 5
© copyright Janson Industries 2014
43
Example
PersonFrame
has
a
Person
has
a
Name
PersonFrame has a Person object (actually 3)
Person has a Name object
When we run PersonFrame and click the button...
Chapter 5
© copyright Janson Industries 2014
44
Yuck!
Referenced variables hold an address not info!
Chapter 5
© copyright Janson Industries 2014
45
Example
▮ We’ll override the inherited toString functions
for both Name and Person
//Name
:
:
:
public String toString() {
if (middle.equals(" ")) return ( first + " " + last);
else if (middle.length() == 1) return (first + " " +
middle + ". " + last);
else return (first + " " + middle + " " + last);}
//Person
:
:
:
public String toString() {
return (name + ". Who is " + age + " years old." );}
Chapter 5
© copyright Janson Industries 2014
46
Example
▮ Now when we try to print the newPerson variables:
public void actionPerformed(ActionEvent e)
outputLabel1.setText("The new person is:
outputLabel2.setText("The new person is:
outputLabel3.setText("The new person is:
}
}
{
" + newPerson1);
" + newPerson2);
" + newPerson3);
▮ The Object class’ toString method (which would
print out the address) is overridden by the Person
toString method
Chapter 5
© copyright Janson Industries 2014
47
Example
▮ The Person toString method tries to concatenate
the Name object
//Person
:
:
:
public String toString() {
return (name + ". Who is " + age + " years old." ) ; }
▮ Fortunately, we overrode the Object class’
toString method in the Name class also
Chapter 5
© copyright Janson Industries 2014
48
Better?
Chapter 5
© copyright Janson Industries 2014
49
Example
▮ We overrode (the inherited) Object class' toString
method by defining toString methods for both
Person and Name
▮ We accessed the Person and Name classes'
toString methods in PersonFrame through
composition (i.e. PersonFrame “has a” Person)
Chapter 5
© copyright Janson Industries 2014
50
Example
▮ In PersonFrame (specialized type of Frame, aka a
subclass of Frame) we created 3 instances/objects
of type Person:
Person newPerson1 = new Person(32, "John", "Smith");
Person newPerson2 = new Person(27, "Mary", "Jones", “Jo");
Person newPerson3 = new Person(42, "John", "Public", "Q");
▮ In Person, we created an instance/object of type
Name
name = new Name(f, l);
Chapter 5
© copyright Janson Industries 2014
51
Inheritance Example
Object
toString
is a
is a
Person
toString
Name
toString
Person is an Object (subclass of Object)
Name is an Object (subclass of Object)
Both inherited toString
Chapter 5
© copyright Janson Industries 2014
52
Inheritance Example
Component
setLayout
is a
Frame
setLayout
getTitle
is a
PersonFrame
setLayout
getTitle
Frame is a Component (subclass of Component)
PersonFrame is a Frame (subclass of Frame)
Chapter 5
© copyright Janson Industries 2014
53
Frame
inherits setLayout,
what does PersonFrame inherit?
Composition Example
PersonFrame
has
a
Person
has
a
Name
PersonFrame has a Person
Person has a Name
PersonFrame invokes Person's toString method
Person invokes Name's toString method
Chapter 5
© copyright Janson Industries 2014
54
Comparison Operators
▮<
▮>
▮ >=
▮ <=
▮ ==
▮ !=
less than
greater than
greater than or equal to
less than or equal to
equal
not equal
Relational
Operators
Equality
Operators
▮ Order of precedence:
relational then equality
Chapter 5
© copyright Janson Industries 2014
55
Comparison Operators
▮ Comparisons result in a boolean value
(true or false)
▮ You can assign the result of a
comparison to a boolean variable
boolean isOvertime = (hours > 40);
Chapter 5
© copyright Janson Industries 2014
56
Converting Types
▮ Primitives can be converted to a larger
type by simply equating/assigning it
long a; int b = 1; char c = ‘2’;
a = b;
b = c;
▮ To convert from larger to smaller, use a
“cast” operation
Chapter 5
© copyright Janson Industries 2014
57
Casting
▮ Converts a larger primitive type to a
smaller primitive type
▮ General syntax:
type1Variable = (type1Name) type2Variable
long a; int b = 1; char c = ‘2’;
b = (int)a;
c = (char)b;
Chapter 5
© copyright Janson Industries 2014
58
Primitives to Strings
▮ Casting and = do not work
▮ String class has static methods (.valueOf)
that convert many primitives to strings
long a = 1;
int b = 2;
char c = ‘c’;
String d, e, f;
d = String.valueOf(a);
e = String.valueOf(b);
f = String.valueOf(c);
Chapter 5
© copyright Janson Industries 2014
59
▮ Use the String valueOf methods to
convert primitive types to Strings
▮ Notice no byte valueOf
Chapter 5
© copyright Janson Industries 2014
60
Converting Types
▮ There are also a series of “Wrapper”
classes for primitives
byte
int
double
: :
Byte
Integer
Double
: :
▮ Wrapper classes contain useful methods
for manipulating primitives
Chapter 5
© copyright Janson Industries 2014
61
▮ For example, each “Wrapper” class has a
toString method that does the same thing as
String’s valueOf
Chapter 5
© copyright Janson Industries 2014
62
Primitives to Strings
long a = 1;
int b = 2;
char c = ‘c’;
String d, e, f;
d = Long.toString(a);
e = Integer.toString(b);
f = Character.toString(c);
Chapter 5
© copyright Janson Industries 2014
63
Strings to Primitives
▮ The parseXXX methods (of each Wrapper
class) convert Strings to primitive types
int a;
long b;
String c = “1”;
a = Integer.parseInt(c);
b = Long.parseLong(c);
Chapter 5
© copyright Janson Industries 2014
64
Strings to Chars
▮ Use a String method called .charAt(#)
char a;
String c = “123”;
a = c.charAt(0);
▮ A is set to 1
Chapter 5
© copyright Janson Industries 2014
65
Converting between types
▮ Assuming int a, double b, String c
Larger
Primitive
Smaller
b = a;
Primitive
Smaller
Primitive
Larger
a = (int) b;
Primitive
c = String.valueOf(a);
Primitive
c = Double.toString(b);
String
Primitive
Chapter 5
String
a = Integer.parseInt(c);
© copyright Janson Industries 2014
66
GUI Interface Components
▮ TextField: entry field to hold and display
text defined by the programmer or user
▮ Usually used in conjunction with a label
that defines the text to be entered
Chapter 5
© copyright Janson Industries 2014
67
Defining Components
▮ As always, must import classes (not
shown) then define the components:
Label custNameLabel = new Label("Enter the customer name:");
TextField custNameTF = new TextField(25);
Label custAddrLabel = new Label("Enter the customer
address:");
TextField custAddrTF = new TextField(25);
▮ Then add to the frame:
add(custNameLabel);
add(custNameTF);
add(custAddrLabel);
add(custAddrTF);
Chapter 5
© copyright Janson Industries 2014
68
Defining Properties
▮ Of course you will want to define their
properties (e.g. text) either when created
Label custNameLabel = new Label("Enter the customer name:");
▮ Or after creating using the “setters”
Label custNameLabel = new Label();
:
:
:
:
:
:
custNameLabel.setText(“Enter the customer name:”);
Chapter 5
© copyright Janson Industries 2014
69
Positioning
▮ To set position, turn off the default layout
scheme:
setLayout(null);
▮ Specify the components size and location
with either the setSize and setLocation
methods or the setBounds method
custNameLabel.setSize(160,10);
custNameLabel.setLocation(0,35);
custNameTF.setSize(200,20);
custNameTF.setLocation(162,30);
custAddrLabel.setBounds(0,100,75,75);
custAddrTF.setBounds(162,100,75,75);
Chapter 5
© copyright Janson Industries 2014
70
Positioning
custNameLbl.setLocation(5,35);
custNameLbl.setSize(155,10);
custNameTF.setSize(200,20);
custNameTF.setLocation(162,30);
custAddrTF.setBounds(162,100,75,75);
custAddrLb.setBounds(5,100,75,75);
Chapter 5
© copyright Janson Industries 2014
71
Defining Components
▮ Lots of other commonly set properties:
▮ Alignment
How does label know
“stuff” is text not a
▮ Font style
variable?
▮ Font size
setLayout(null);
Label l1 = new Label("stuff");
l1.setBounds(15,50,155,20);
Label l2 = new Label("stuff", Label.RIGHT);
l2.setBounds(15,80,155,20);
Label l3 = new Label("stuff");
l3.setAlignment(Label.CENTER);
l3.setBounds(15,110,155,20);
Chapter 5
© copyright Janson Industries 2014
72
add(l1); add(l2);
add(l3);
Putting it all together in a
new visual class called Sale
Chapter 5
© copyright Janson Industries 2014
73
Change size to 300, 229 and
layout to null
Chapter 5
© copyright Janson Industries 2014
74
Defined 5 labels, 4 text fields, and 1 button
Rename, align
Enable Close button - How? (Hint: 2 steps)
Chapter 5
© copyright Janson Industries 2014
75
When data is entered and the calc button is
clicked, the total should be calculated and
displayed (as above) and the text fields blanked
out
Chapter 5
© copyright Janson Industries 2014
76
Non-graded Exercise
▮ Need three primitives to hold qty, price
and cost
▮ When button clicked:
▮ Retrieve qty and price, calculate cost with a
6.5% sales tax
▮ Build result message and place in result label
▮ Blank out other text fields
▮ What method holds this logic?
Chapter 5
© copyright Janson Industries 2014
77
Non-graded Exercise
private int qty;
private double price, cost;
qty = Integer.parseInt(qtyTF.getText());
price = Double.parseDouble(priceTF.getText());
cost = price * qty * 106.5;
msgLbl.setText("The cost of this " +
"transaction is: $" + cost);
custNameTF.setText("");
itemNameTF.setText("");
qtyTF.setText("");
priceTF.setText("");
Chapter 5
Sale saleTest = new Sale();
© copyright Janson Industries 2014
78
Non-graded Exercise
▮ If tested now nothing appears: why?
▮ If run and press button nothing happens:
why?
▮ If price and qty entered, get wrong result:
why?
Chapter 5
© copyright Janson Industries 2014
79
Chapter 5
© copyright Janson Industries 2014
80
Chapter 5
© copyright Janson Industries 2014
81
Non-graded Assg
▮ Export Sale.java
▮ Send as an email attachment to
[email protected]
Chapter 5
© copyright Janson Industries 2014
82
Points to Remember
▮ Primitive variables contain a value
▮ Referenced variables contain an address
▮ Use toString(), casting, and Wrapper
class methods to convert between types
▮ TextFields can be used for input and
output
Chapter 5
© copyright Janson Industries 2014
83