Post on 05-Jan-2016
Chapter 5 © copyright Janson Industries 2014 1
Java Variables
▮ Types of variables
▮ Creating, modifying and displaying
▮ Comparing
▮ Converting between types
▮ TextField
Non-graded Assg
Chapter 5 © copyright Janson Industries 2014 2
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 3
▮ 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
Variables
Chapter 5 © copyright Janson Industries 2014 4
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 5
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 6
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 7
Values▮ Calculated values can be assigned
using standard operators: +, -, *, /. Ex:
▮ When dividing two integers, decimal remainder truncated
▮ Dividing float and integer, integer “promoted” to float
▮ Standard order of operator precedence
int counter;counter = counter + 1; counter++; ++counter;
Chapter 5 © copyright Janson Industries 2014 8
Values▮ Use PRINT
System.out.print(“The answer is: ”);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
▮ To get same result
System.out.print(“The answer is: ”);System.out.print(answer);
System.out.println(“The answer is: ” + answer);
+ concatenates
text or variables
Chapter 5 © copyright Janson Industries 2014 9
Pre/Post Inc/Decrement▮ Standalone Pre/Post expressions (+
+counter; counter++;) do the same thing
▮ Within a larger expression they are different
▮ Result is: Counter = 1
Counter = 2
Counter = 2
Counter = 3
int counter = 1;
System.out.println("Counter = " + counter);
System.out.println("Counter = " + ++counter);
System.out.println("Counter = " + counter++);
System.out.println("Counter = " + counter);
Chapter 5 © copyright Janson Industries 2014 10
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 = counter + 1;
System.out.println("Counter = " + counter);
System.out.println("Counter = " + counter);
counter = counter + 1;
System.out.println("Counter = " + counter);
Chapter 5 © copyright Janson Industries 2014 11
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 12Look at documentation to see required parms
Chapter 5 © copyright Janson Industries 2014 13
To raise 12 to the fourth power:
double answer; answer = Math.pow(12, 4);
Chapter 5 © copyright Janson Industries 2014 14
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 a value later
Chapter 5 © copyright Janson Industries 2014 15
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 16
Referenced Types
▮ You can declare a referenced variable for a class and then “instantiate” and assign the object to the variable
▮ Assuming Customer is a java class, the variable cust points to a Customer object that contains the values
Customer cust;
cust = new Customer(“Joe”, “1 Main St.”,
“Enid, OK 65654”);
Chapter 5 © copyright Janson Industries 2014 17
For example: String
▮ If we set the value of a to 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 object with “Joe” is
placed in memory and b = B2
a = new String(“Joe”);
A B C
1 Joe
2 Joe
3
ab
Chapter 5 © copyright Janson Industries 2014 18
For example: String▮ If we change the value of a
▮ A String object with the value “Art” is placed in memory
▮ a = C3 and the first Joe is not referenced
a = new String(“Art”);
A B C
1 Joe
2 Joe
3 Art
ab
Chapter 5 © copyright Janson Industries 2014 19
String
▮ However if we define c as equal to a:
▮ c = C3
A B C
1 Joe
2 Joe
3 Art
abc
String c = a;
Chapter 5 © copyright Janson Industries 2014 20
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
▮ There are now two String objects▮ One with the text “Art” the other “Joe”
String c = "Art";
c = “Joe”;
Chapter 5 © copyright Janson Industries 2014 21
String▮ However, using the shortcut (i.e. not explicitly creating a new object) will not necessarily result in a
new object
▮ Only one object with text “Art”
▮ Two objects with text “Art”
String c = "Art";
String b = “Art”;
String c = "Art";
String b = new String(“Art”);
Chapter 5 © copyright Janson Industries 2014 22
String▮ Even this…
▮ ..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)
String b = new String(“Art”);
String c = "Art";
Chapter 5 © copyright Janson Industries 2014 23
Reference Variables
▮ If two Customer variables created as follows:
▮ How many objects are there?Customer cust1 = new Customer(“Walmart”);
Customer cust2 = new Customer(“Walmart”);
Chapter 5 © copyright Janson Industries 2014 24
Reference Variables
▮ 2 objects exist
A B C
1 Walmart
2
3 Walmart
cust1 cust2
Chapter 5 © copyright Janson Industries 2014 25
Reference Variables
▮ If the following statements are also executed:
▮ How many objects are there?
▮ How many objects are referenced?cust1 = new Customer(“Target”);
cust2.setCustName(“Sam’s”);
Chapter 5 © copyright Janson Industries 2014 26
Reference Variables
▮ 3 objects exist, 2 are referenced
▮ For an alternative explanation of variables:
▮ http://www.javaranch.com/campfire/StoryCups.jsp
A B C
1 Walmart
2 Target
3 Sam’s
cust1 cust2
Chapter 5 © copyright Janson Industries 2014 27
Null Pointer Exception
A B C
2 Target
3
cust1 cust2
Customer cust1, cust2;
cust1 = new Customer(“Target”);
cust2.setCustName(“Sam’s”);
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at packageName.className.methodName(fileName.java:lineNumber)
▮ Occurs when using a reference variable that is not assigned to an object (pointer is null)
Chapter 5 © copyright Janson Industries 2014 28
Primitive Variables ▮ Defining these two integers:
▮ Results in a memory allocation of:int a = 1; int b = 2;
A B C
1 1
2 2
3
Chapter 5 © copyright Janson Industries 2014 29
Primitives
▮ If we change the value of a
▮ The value 1 is replaced with 3
a = 3;
A B C
1 3
2 2
3
Chapter 5 © copyright Janson Industries 2014 30
Referenced Types
▮ Proof: Printing Customer variable c would result in memory address (hash code)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);
Chapter 5 © copyright Janson Industries 2014 31
Chapter 5 © copyright Janson Industries 2014 32
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 33
We’ll prove it!
Chapter 5 © copyright Janson Industries 2014 34
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 35
Inserts new toString method that calls Object's (the superclass’) toString method
Chapter 5 © copyright Janson Industries 2014 36
We’ll change to return customer name
Chapter 5 © copyright Janson Industries 2014 37
When we run CustApp and print the Customer variable c
Try it: change Customer and CustApp
Chapter 5 © copyright Janson Industries 2014 38
Another Example
ObjecttoString
PersontoString
NametoString
Person is an objectName is an objectPerson has a name
is a is a
has a
Chapter 5 © copyright Janson Industries 2014 39
Inheritance Example
// Name.java
public class Name extends Object {
String first;
String last;
String middle;
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; }
}
▮ We’ll create classes called Name and Person
Method Overloading
Chapter 5 © copyright Janson Industries 2014 40
Example
// Person.java
public class Person extends Object { int age; Name name;
public Person() { age = 0; }
public Person(int a, String f, String l) { name = new Name(f, l);
age = a; }
public Person(int a, String f, String l, String m){name = new Name(f, l, m);age = a;
} }
Person “has a” name
Person “is an”object
Chapter 5 © copyright Janson Industries 2014 41
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 42
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: " + newPerson1);
outputLabel2.setText("The new person is: " + newPerson2);
outputLabel3.setText("The new person is: " + newPerson3);
} Uses the default toString method to display
Example
Chapter 5 © copyright Janson Industries 2014 43
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();
}
}
Example
Chapter 5 © copyright Janson Industries 2014 44
Example
PersonFrame Person Name
PersonFrame has a Person object (actually 3)Person has a Name object
When we run PersonFrame and click the button...
has a
has a
Chapter 5 © copyright Janson Industries 2014 45
Yuck!
Referenced variables hold an address not info!
Chapter 5 © copyright Janson Industries 2014 46
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 47
Example
public void actionPerformed(ActionEvent e) {
outputLabel1.setText("The new person is: " + newPerson1);
outputLabel2.setText("The new person is: " + newPerson2);
outputLabel3.setText("The new person is: " + newPerson3);
} }
▮ Now when we try to print the newPerson variables:
▮ The Object class’ toString method (which would print out the address) is overridden by the Person toString method
Chapter 5 © copyright Janson Industries 2014 48
Example
▮ The Person toString method tries to concatenate the Name object
▮ Fortunately, we overrode the Object class’ toString method in the Name class also
//Person
: : :
public String toString() {
return (name + ". Who is " + age + " years old." ) ; }
Chapter 5 © copyright Janson Industries 2014 49
Better?
Chapter 5 © copyright Janson Industries 2014 50
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 51
Example
▮ In PersonFrame (specialized type of Frame, aka a subclass of Frame) we created 3 instances/objects of type Person:
▮ In Person, we created an instance/object of type Name
Person newPerson1 = new Person(32, "John", "Smith");
Person newPerson2 = new Person(27, "Mary", "Jones", “Jo");
Person newPerson3 = new Person(42, "John", "Public", "Q");
name = new Name(f, l);
Chapter 5 © copyright Janson Industries 2014 52
Inheritance Example
ObjecttoString
PersontoString
NametoString
Person is an Object (subclass of Object)Name is an Object (subclass of Object)
Both inherited toString
is a is a
Chapter 5 © copyright Janson Industries 2014 53
Inheritance Example
Frame is a Component (subclass of Component)PersonFrame is a Frame (subclass of Frame)
Frame inherits setLayout, what does PersonFrame inherit?
is a
is a
ComponentsetLayout
PersonFramesetLayout getTitle
Frame setLayout getTitle
Chapter 5 © copyright Janson Industries 2014 54
Composition Example
PersonFrame Person Name
PersonFrame has a PersonPerson has a Name
PersonFrame invokes Person's toString method
Person invokes Name's toString method
has a
has a
Chapter 5 © copyright Janson Industries 2014 55
Comparison Operators▮ < less than▮ > greater than▮ >= greater than or equal to▮ <= less than or equal to▮ == equal▮ != not equal
▮ Order of precedence: relational then
equality
Relational
Operators
EqualityOperators
Chapter 5 © copyright Janson Industries 2014 56
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 57
Converting Types
▮ Primitives can be converted to a larger type by simply equating/assigning it
▮ To convert from larger to smaller, use a “cast” operationlong a; int b = 1; char c = ‘2’;
a = b;
b = c;
Chapter 5 © copyright Janson Industries 2014 58
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 59
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);
▮ Casting and = do not work
▮ String class has static methods (.valueOf) that convert many primitives to strings
Chapter 5 © copyright Janson Industries 2014 60
▮ Use the String valueOf methods to convert primitive types to Strings
▮ Notice no byte valueOf
Chapter 5 © copyright Janson Industries 2014 61
Converting Types
▮ There are also a series of “Wrapper” classes for primitives
▮ Wrapper classes contain useful methods for manipulating primitives
byte Byteint Integerdouble Double : : : :
Chapter 5 © copyright Janson Industries 2014 62
▮ For example, each “Wrapper” class has a toString method that does the same thing as String’s valueOf
Chapter 5 © copyright Janson Industries 2014 63
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);
Primitives to Strings
Chapter 5 © copyright Janson Industries 2014 64
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 65
Strings to Chars
▮ Use a String method called .charAt(#)
▮ A is set to 1
char a;
String c = “123”;
a = c.charAt(0);
Chapter 5 © copyright Janson Industries 2014 66
Converting between types
▮ Assuming int a, double b, String c
LargerPrimitiv
e
SmallerPrimitiv
eb = a;
SmallerPrimitiv
e
LargerPrimitiv
ea = (int) b;
StringPrimitive
c = String.valueOf(a);c = Double.toString(b);
Primitive
Stringa = Integer.parseInt(c);
Chapter 5 © copyright Janson Industries 2014 67
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 68
Defining Components
▮ As always, must import classes (not shown) then define the components:
▮ Then add to the frame:
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);
add(custNameLabel); add(custNameTF); add(custAddrLabel);add(custAddrTF);
Chapter 5 © copyright Janson Industries 2014 69
Defining Properties
▮ Of course you will want to define their properties (e.g. text) either when created
▮ Or after creating using the “setters”
Label custNameLabel = new Label("Enter the customer name:");
Label custNameLabel = new Label();: : : : : :custNameLabel.setText(“Enter the customer name:”);
Chapter 5 © copyright Janson Industries 2014 70
Positioning▮ To set position, turn off the default layout
scheme:
▮ Specify the components size and location with either the setSize and setLocation methods or the setBounds method
setLayout(null);
custNameLabel.setSize(160,10); custNameLabel.setLocation(5,35); custNameTF.setSize(200,20); custNameTF.setLocation(162,30); custAddrLabel.setBounds(5,100,75,75);custAddrTF.setBounds(162,100,75,75);
Chapter 5 © copyright Janson Industries 2014 71
Positioning
custNameLbl.setSize(155,10);custNameTF.setSize(200,20); custNameTF.setLocation(162,30);
custAddrLb.setBounds(5,100,75,75);
custAddrTF.setBounds(162,100,75,75);
custNameLbl.setLocation(5,35);
Chapter 5 © copyright Janson Industries 2014 72
Defining Components▮ Lots of other commonly set properties:
▮ Alignment▮ Font style▮ 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); add(l1); add(l2); add(l3);
How does label know “stuff” is text
not a variable?
Chapter 5 © copyright Janson Industries 2014 73
Putting it all together in a new visual class called Sale
Chapter 5 © copyright Janson Industries 2014 74
Change size to 300, 229 and layout to null
Chapter 5 © copyright Janson Industries 2014 75
Defined 5 labels, 4 text fields, and 1 buttonRename, align
Enable Close button - How? (Hint: 2 steps)
Chapter 5 © copyright Janson Industries 2014 76
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 77
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 78
Non-graded Exercise
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("");
Sale saleTest = new Sale();
private int qty;
private double price, cost;
Chapter 5 © copyright Janson Industries 2014 79
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 80
Chapter 5 © copyright Janson Industries 2014 81
Chapter 5 © copyright Janson Industries 2014 82
Non-graded Assg
▮ Export Sale.java
▮ Send as an email attachment to wsjavaws@yahoo.com
Chapter 5 © copyright Janson Industries 2014 83
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