Java Variables Types of variables Creating modifying and
Java Variables ▮ Types of variables ▮ Creating, modifying and displaying ▮ Comparing ▮ Converting between types ▮ Text. Field Non-graded Assg Chapter 5 © copyright Janson Industries 2017 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 2017 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 2017 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 2017 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 2017 5
Defining and Assigning ▮ Primitive data type then variable name ▮ int number. Of. Dependents; ▮ char gender, marital. Status; ▮ A value can be assigned when the variable is declared: ▮ float tax. Rate =. 28; ▮ Or a value can be assigned later: ▮ number. Of. Dependents = 2; Chapter 5 © copyright Janson Industries 2017 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/double and integer, integer “promoted” to float/double ▮ Standard order of operator precedence Chapter 5 © copyright Janson Industries 2017 7
Values ▮ Use PRINT System. out. print(“The answer is: ”); System. out. print(“The 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 2017 + concatenates text or variables 8
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 ▮ Result is: Chapter 5 Counter = = 1 2 2 3 = = © copyright Janson Industries 2017 " " + + counter); ++counter); counter++); counter); 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 Chapter 5 = " + counter); © copyright Janson Industries 2017 10
Values ▮ Some math functions are performed with java supplied static 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. method. Name(parms) Chapter 5 © copyright Janson Industries 2017 11
Look at documentation to see required parms Chapter 5 © copyright Janson Industries 2017 12
To raise 12 to the fourth power: double answer; answer = Math. pow(12, 4); Chapter 5 © copyright Janson Industries 2017 13
Referenced Types ▮ String & String. Buffer are examples ▮ String. Buffer provides more flexibility when manipulating Strings ▮ Class name then variable name ▮ String name, address, phone. Number; ▮ String. Buffer name. SB; ▮ Like primitives, you can assign a value when declaring the variable or assign a value later Chapter 5 © copyright Janson Industries 2017 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”); ▮ String. Buffer name. SB = new String. Buffer(“Joe”); ▮ Alternative for String objects (not recommended) ▮ String name = “Joe”; Chapter 5 © copyright Janson Industries 2017 15
Referenced Types ▮ You can declare a referenced variable 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 2017 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 = A 1 ▮ If we then set b to “Joe”, a 2 nd String A B C object with “Joe” is 1 Joe placed in memory 2 Joe and b = B 2 3 Chapter 5 © copyright Janson Industries 2017 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 = C 3 and the first Joe is not referenced Chapter 5 © copyright Janson Industries 2017 18
String ▮ However if we define c as equal to a: String c = a; ▮ c = C 3 1 2 3 Chapter 5 A Joe B C Joe Art © copyright Janson Industries 2017 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 2017 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 2017 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 String. Buffers are better ▮ Their value can be changed (more on this later) Chapter 5 © copyright Janson Industries 2017 22
Reference Variables ▮ If two Customer variables created as follows: Customer cust 1 = new Customer(“Walmart”); Customer cust 2 = new Customer(“Walmart”); ▮ How many objects are there? Chapter 5 © copyright Janson Industries 2017 23
Reference Variables 1 2 3 A Walmart B Walmart C cust 1 cust 2 ▮ 2 objects exist Chapter 5 © copyright Janson Industries 2017 24
Reference Variables ▮ If the following statements are also executed: cust 1 = new Customer(“Target”); cust 2. set. Cust. Name(“Sam’s”); ▮ How many objects are there? ▮ How many objects are referenced? Chapter 5 © copyright Janson Industries 2017 25
Reference Variables 1 2 3 A Walmart B C Target Sam’s cust 1 cust 2 ▮ 3 objects exist, 2 are referenced ▮ For an alternative explanation of variables: ▮ http: //www. javaranch. com/campfire/Story. Cups. jsp Chapter 5 © copyright Janson Industries 2017 26
Null Pointer Exception ▮ Occurs when using a reference variable that is not assigned to an object (pointer is null) Customer cust 1, cust 2; cust 1 = new Customer(“Target”); cust 2. set. Cust. Name(“Sam’s”); A 2 3 B C Target cust 1 cust 2 Exception in thread "AWT-Event. Queue-0" java. lang. Null. Pointer. Exception Chapter 5 © copyright Janson Industries 2017 27 at package. Name. class. Name. method. Name(file. Name. java: line. Number)
Primitive Variables ▮ Defining these two integers: int a = 1; int b = 2; ▮ Results in a memory allocation of: 1 2 3 Chapter 5 A 1 B C 2 © copyright Janson Industries 2017 28
Primitives ▮ If we change the value of a a = 3; ▮ The value 1 is replaced with 3 1 2 3 Chapter 5 A 3 B C 2 © copyright Janson Industries 2017 29
Another Example public class Main { public static void main(String[] args) { int. Var = 1; String string. Var = "text"; System. out. println("Int: " + int. Var + ", String: " + string. Var); alter. Int(int. Var); alter. String(string. Var); System. out. println("Int: " + int. Var + ", String: " + string. Var); } public static void alter. Int(int var) { var = var + 100; } public static void alter. String(String var) { var = var + " is altered!"; } Chapter 5 © copyright Janson Industries 2017 } 30
Another Example Chapter 5 © copyright Janson Industries 2017 31
public class Main { public static void main(String[] args) { My. Object my. Object = new My. Object(); But this … System. out. println("My. Object name: " + my. Object. get. Name()); alter(my. Object); System. out. println("My. Object name: " + my. Object. get. Name()); create. New. Object(my. Object); System. out. println("My. Object name: " + my. Object. get. Name()); } private static void alter(My. Object my. Object) { my. Object. set. Name("Altered name!"); } } private static void create. New. Object(My. Object my. Object) { my. Object = new My. Object(); public class My. Object { my. Object. set. Name("-"); private String name = "none"; } public void set. Name(String s){ name = s; } Chapter 5 public String get. Name(){ return name; © copyright Janson Industries 2017 }} 32
… results in Chapter 5 © copyright Janson Industries 2017 33
Referenced Types ▮ Printing Customer variable c would result in memory address (hash code) Chapter 5 Customer c = new Customer(); c. set. Contact. Person("Joe Samaritan"); c. set. Contact. Phone("555 -3333"); c. set. Cust. Name("Kindness Foods"); c. set. Ship. To. Street("1 Milk of St. "); c. set. Ship. To. City("Human"); c. set. Ship. To. State("ME"); c. set. Ship. To. Zip("03234"); System. out. println(c); © copyright Janson Industries 2017 34
Chapter 5 © copyright Janson Industries 2017 35
Why address? ▮ Because that is the value of the reference variable ▮ If you wanted to see the Customers name, use c. get. Cust. Name() ▮ Actually the Customer object's to. String method is invoked when println executed ▮ “Hey, we didn’t code a Customer. to. String() method!” ▮ to. String was inherited from Object class ▮ Object. to. String returns address of an object Chapter 5 © copyright Janson Industries 2017 36
We’ll prove it! Chapter 5 © copyright Janson Industries 2017 37
In Customer, click Source, then Override/Implement Methods Click to. String and specify it as the first method after the class variables, then click OK Chapter 5 © copyright Janson Industries 2017 38
Inserts new to. String method that calls Object's (the superclass’) to. String method Chapter 5 © copyright Janson Industries 2017 39
We’ll change to return customer name Chapter 5 © copyright Janson Industries 2017 40
When we run Cust. App and print the Customer variable c Try it: change Customer and Cust. App Chapter 5 © copyright Janson Industries 2017 41
Another Example Object is a Person to. String is a Name has a to. String Person is an object/class Name is an object/class Person has a name Chapter 5 © copyright Janson Industries 2017 42
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 2017 43
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 2017 44
Example ▮ Person. Frame will instantiate 3 Person objects // Person. Frame. java import java. awt. *; import java. awt. event. *; public class Person. Frame extends Frame implements Window. Listener, Action. Listener { Button show. Button = new Button("Show"); Label output. Label 1 = new Label(); Label output. Label 2 = new Label(); Label output. Label 3 = new Label(); Person new. Person 1 = new Person(32, "John", "Smith"); Person new. Person 2 = new Person(27, "Mary", "Jones", “Jo"); Person new. Person 3 = new Person(42, "John", "Public", "Q"); Chapter 5 © copyright Janson Industries 2017 45
Example public Person. Frame() { set. Layout(null); this. set. Size(500, 400); show. Button. set. Bounds(275, 300, 50, 25); output. Label 1. set. Bounds(112, 200, 350, 15); output. Label 2. set. Bounds(112, 215, 350, 15); output. Label 3. set. Bounds(112, 230, 350, 15); add(show. Button); this. set. Visible(true); show. Button. add. Action. Listener(this); add. Window. Listener(this); add(output. Label 1); add(output. Label 2); add(output. Label 3); } public void action. Performed(Action. Event e) output. Label 1. set. Text("The new person is: output. Label 2. set. Text("The new person is: output. Label 3. set. Text("The new person is: } Chapter 5 { " + new. Person 1); " + new. Person 2); " + new. Person 3); © copyright Janson Industries 2017 Uses the default to. String method to display 46
Example public void window. Activated(Window. Event e) {} public void window. Closing(Window. Event e) { this. dispose(); } public void window. Deactivated(Window. Event e) {} public void window. Deiconified(Window. Event e) {} public void window. Iconified(Window. Event e) {} public void window. Opened(Window. Event e) {} public static void main(String args[]) { Person. Frame pf = new Person. Frame(); } } Chapter 5 © copyright Janson Industries 2017 47
Example Person. Frame has a Person has a Name Person. Frame has a Person object (actually 3) Person has a Name object When we run Person. Frame and click the button. . . Chapter 5 © copyright Janson Industries 2017 48
Yuck! Referenced variables hold an address not info! Chapter 5 © copyright Janson Industries 2017 49
Example ▮ We’ll override the inherited to. String functions for both Name and Person //Name : : : public String to. String() { if (middle. equals(" ")) return ( first + " " + last); else if (middle. length() == 1) return (first + " " + middle + ". " + last); else return (first + " " + middle + " " + last); } //Person : : : public String to. String() { return (name + ". Who is " + age + " years old. " ); } Chapter 5 © copyright Janson Industries 2017 50
Example ▮ Now when we try to print the new. Person variables: public void action. Performed(Action. Event e) output. Label 1. set. Text("The new person is: output. Label 2. set. Text("The new person is: output. Label 3. set. Text("The new person is: } } { " + new. Person 1); " + new. Person 2); " + new. Person 3); ▮ The Object class’ to. String method (which would print out the address) is overridden by the Person to. String method Chapter 5 © copyright Janson Industries 2017 51
Example ▮ The Person to. String method tries to concatenate the Name object //Person : : : public String to. String() { return (name + ". Who is " + age + " years old. " ) ; } ▮ Fortunately, we overrode the Object class’ to. String method in the Name class also Chapter 5 © copyright Janson Industries 2017 52
Better? Chapter 5 © copyright Janson Industries 2017 53
Example ▮ We overrode (the inherited) Object class' to. String method by defining to. String methods for both Person and Name ▮ Person. Frame accessed the Person and Name classes' to. String methods through composition (i. e. Person. Frame “has a” Person) Chapter 5 © copyright Janson Industries 2017 54
Example ▮ In Person. Frame (specialized type of Frame, aka a subclass of Frame) we created 3 instances/objects of type Person: Person new. Person 1 = new Person(32, "John", "Smith"); Person new. Person 2 = new Person(27, "Mary", "Jones", “Jo"); Person new. Person 3 = 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 2017 55
Inheritance Example Object to. String is a Person to. String Name to. String Person is an Object (subclass of Object) Name is an Object (subclass of Object) Both inherited to. String Chapter 5 © copyright Janson Industries 2017 56
Inheritance Example Component set. Layout is a Frame set. Layout get. Title is a Person. Frame set. Layout get. Title Frame is a Component (subclass of Component) Person. Frame is a Frame (subclass of Frame) Chapter 5 © copyright Janson Industries 2017 57 Frame inherits set. Layout, what does Person. Frame inherit?
Composition Example Person. Frame has a Person has a Name Person. Frame invokes Person's to. String method Person invokes Name's to. String method Chapter 5 © copyright Janson Industries 2017 58
Comparison Operators ▮ ▮ ▮ < > >= <= == != less 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 2017 59
Comparison Operators ▮ Comparisons result in a boolean value (true or false) ▮ You can assign the result of a comparison to a boolean variable boolean is. Overtime = (hours > 40); Chapter 5 © copyright Janson Industries 2017 60
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 2017 61
Casting ▮ Converts a larger primitive type to a smaller primitive type ▮ General syntax: type 1 Variable = (type 1 Name) type 2 Variable long a; int b = 1; char c = ‘ 2’; b = (int)a; c = (char)b; Chapter 5 © copyright Janson Industries 2017 62
Primitives to Strings ▮ Casting and = do not work ▮ String class has static methods (. value. Of) that convert many primitives to strings long a = 1; int b = 2; char c = ‘c’; String d, e, f; d = String. value. Of(a); e = String. value. Of(b); f = String. value. Of(c); Chapter 5 © copyright Janson Industries 2017 63
▮ Use the String value. Of methods to convert primitive types to Strings Chapter 5 ▮ Notice no byte value. Of © copyright Janson Industries 2017 64
Converting Types ▮ There 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 2017 65
▮ For example, each “Wrapper” class has a to. String method that does the same thing as String’s value. Of Chapter 5 © copyright Janson Industries 2017 66
Primitives to Strings long a = 1; int b = 2; char c = ‘c’; String d, e, f; d = Long. to. String(a); e = Integer. to. String(b); f = Character. to. String(c); Chapter 5 © copyright Janson Industries 2017 67
Strings to Primitives ▮ The parse. XXX methods (of each Wrapper class) convert Strings to primitive types int a; long b; String c = “ 1”; a = Integer. parse. Int(c); b = Long. parse. Long(c); Chapter 5 © copyright Janson Industries 2017 68
Strings to Chars ▮ Use a String method called. char. At(#) char a; String c = “ 123”; a = c. char. At(0); ▮ a is set to 1 Chapter 5 © copyright Janson Industries 2017 69
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. value. Of(a); Primitive c = Double. to. String(b); String Primitive Chapter 5 String a = Integer. parse. Int(c); © copyright Janson Industries 2017 70
GUI Interface Components ▮ Text. Field: 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 2017 71
Defining Components ▮ As always, must import classes (not shown) then define the components: Label cust. Name. Label = new Label("Enter the customer name: "); Text. Field cust. Name. TF = new Text. Field(25); Label cust. Addr. Label = new Label("Enter the customer address: "); Text. Field cust. Addr. TF = new Text. Field(25); ▮ Then add to the frame: add(cust. Name. Label); add(cust. Name. TF); add(cust. Addr. Label); add(cust. Addr. TF); Chapter 5 © copyright Janson Industries 2017 72
Defining Properties ▮ Of course you will want to define their properties (e. g. text) either when created Label cust. Name. Label = new Label("Enter the customer name: "); ▮ Or after creating using the “setters” Label cust. Name. Label = new Label(); : : : cust. Name. Label. set. Text(“Enter the customer name: ”); Chapter 5 © copyright Janson Industries 2017 73
Positioning ▮ To set position, turn off the default layout scheme: set. Layout(null); ▮ Specify the components size and location with either the set. Size and set. Location methods or the set. Bounds method cust. Name. Label. set. Size(160, 10); cust. Name. Label. set. Location(5, 35); cust. Name. TF. set. Size(200, 20); cust. Name. TF. set. Location(162, 30); cust. Addr. Label. set. Bounds(5, 100, 75); cust. Addr. TF. set. Bounds(162, 100, 75); Chapter 5 © copyright Janson Industries 2017 74
Positioning cust. Name. Lbl. set. Location(5, 35); cust. Name. Lbl. set. Size(155, 10); cust. Name. TF. set. Size(200, 20); cust. Name. TF. set. Location(162, 30); cust. Addr. TF. set. Bounds(162, 100, 75); cust. Addr. Lb. set. Bounds(5, 100, 75); Chapter 5 © copyright Janson Industries 2017 75
Defining Components ▮ Lots of other commonly set properties: ▮ Alignment How does label know “stuff” is text not a ▮ Font style variable? ▮ Font size set. Layout(null); Label l 1 = new Label("stuff"); l 1. set. Bounds(15, 50, 155, 20); Label l 2 = new Label("stuff", Label. RIGHT); l 2. set. Bounds(15, 80, 155, 20); Label l 3 = new Label("stuff"); l 3. set. Alignment(Label. CENTER); l 3. set. Bounds(15, 110, 155, 20); Chapter 5 © copyright Janson Industries 2017 76 add(l 1); add(l 2); add(l 3);
Putting it all together in a new visual class called Sale Chapter 5 © copyright Janson Industries 2017 77
Change size to 300, 229 and layout to null Chapter 5 © copyright Janson Industries 2017 78
Defined 5 labels, 4 text fields, and 1 button Rename, align Enable Close button - How? (Hint: 2 steps) Chapter 5 © copyright Janson Industries 2017 79
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 2017 80
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 2017 81
Non-graded Exercise private int qty; private double price, cost; qty = Integer. parse. Int(qty. TF. get. Text()); price = Double. parse. Double(price. TF. get. Text()); cost = price * qty * 106. 5; msg. Lbl. set. Text("The cost of this " + "transaction is: $" + cost); cust. Name. TF. set. Text(""); item. Name. TF. set. Text(""); qty. TF. set. Text(""); price. TF. set. Text(""); Chapter 5 Sale sale. Test = new Sale(); © copyright Janson Industries 2017 82
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 2017 83
Chapter 5 © copyright Janson Industries 2017 84
Chapter 5 © copyright Janson Industries 2017 85
Non-graded Assg ▮ Export Sale. java ▮ Send as an email attachment to wsjavaws@yahoo. com Chapter 5 © copyright Janson Industries 2017 86
Points to Remember ▮ Primitive variables contain a value ▮ Referenced variables contain an address ▮ Use to. String(), casting, and Wrapper class methods to convert between types ▮ Text. Fields can be used for input and output Chapter 5 © copyright Janson Industries 2017 87
- Slides: 87