Download presentation
Presentation is loading. Please wait.
Published byClementine Chandler Modified over 8 years ago
1
Variables and Methods Chapter 3 – Lecture Slides 1(c) 2008 by E.S.Boese. All Rights Reserved. Variables vary... After all, change is the status quo.
2
(c) 2005-2008 by Elizabeth Sugar Boese 2 Variables Variable is data that is referenced by a named identifier Variables need to be declared before you reference it Variable declaration includes: data type variable name Examples: JButton submit; JTextField tf_state;
3
(c) 2005-2008 by Elizabeth Sugar Boese 3 Variables - names Descriptive of the data it represents Using the alphabet is not acceptable: a, b, c, d, e; nor is a1, a2, a3, a4 Lists of images in something like a slideshow can be named img1, img2, img3, etc. No spaces allowed within a variable name Convention is to begin variable names with a lower case letter and separate each word in the variable name by capitalizing subsequent words: - firstName, lastName, midtermGrade, labGrade Abbreviations are good, but be consistent: - tempFreq, hitFreq, qtyCount, qtyOfShirts Cannot use a Java keyword for a variable name No spaces in names!
4
(c) 2005-2008 by Elizabeth Sugar Boese 4 Java Keywords Reserved words Not to memorize, but take notice; which ones do you already recognize? abstractcontinuefornewswitch assert defaultgoto packagesynchronized booleandoifprivatethis breakdoubleimplementsprotectedthrow byteelseimportpublicthrows caseenum instanceofreturntransient catchextendsintshorttry charfinalinterfacestaticvoid classfinallylongstrictfp volatile const floatnativesuperwhile
5
(c) 2005-2008 by Elizabeth Sugar Boese 5 Data Types There are 8 primitive data types We will only be concerned with the most common ones: int, double, char and boolean Note that these are the primitive data types; we also use a lot of objects as well. Examples of objects are: JButton, String, JTextField, JPanel, Font, etc data type description number of bits used to represent the number integers byte Byte-length integer8-bit short Short integer16-bit int Integer32-bit long Long integer64-bit reals float Single-precision floating point32-bit double Double-precision floating point64-bit char A single character16-bit Unicode character boolean holds either the value true or false 1-bit
6
(c) 2005-2008 by Elizabeth Sugar Boese 6 Characters Data type: char Enclose with single quotes char initial = ‘E’; char code = ‘!’; Escape sequences char singlequote = ‘\’’;
7
(c) 2005-2008 by Elizabeth Sugar Boese 7 Boolean One of two values true false boolean isOn = false; boolean available = true;
8
Variables Declaration Graphics g; int numCourses; // integer values double salesTax; // floating pt number Initialization – assignment for the first time Assignment name = “Cookie Monster”; numCourses = 4; salesTax = 4.75; Variable Reference String myName; myName = “Java Guru”; g.drawString( myName, 0, 12 ); Declaration includes the data type and a variable name. Assignment changes the value of a variable.. 8 (c) 2008 by E.S.Boese. All Rights Reserved.
9
(c) 2005-2008 by Elizabeth Sugar Boese 9 Variables Instance variables Declared at the top of a class Data available to the entire class Local variables Declared within a method Data only available within the method Includes method parameters
10
Scope: Instance Variable vs. Local Variable Instance Variable vs. Local Variable import javax.swing.*; import java.awt.*; public class ColorEx extends JApplet { String favColor; String ski; public void paint( Graphics g ) { favColor = “Favorite color”; ski = “Love 2 ski”; g.setColor( Color.RED ); g.drawString( favColor, 30, 45 ); g.setColor( new Color( 12,34,52) ); g.drawString( ski, 30, 53 ); } import javax.swing.*; import java.awt.*; public class ColorEx extends JApplet { public void paint( Graphics g ) { String favColor = “Favorite color”; String ski = “Love 2 ski”; g.setColor( Color.RED ); g.drawString( favColor, 30, 45 ); g.setColor( new Color( 12,34,52) ); g.drawString( ski, 30, 53 ); } local : declared inside a method instance : declared inside the class 10 (c) 2008 by E.S.Boese. All Rights Reserved.
11
(c) 2005-2008 by Elizabeth Sugar Boese 11 Scope Check out the enclosing squigglys You cannot declare two variables of the same name at the same scope level Any variable declared strictly within the scope of another with the same name will shadow the outer named variable Most variables are declared at the top of the class – called instance variables, so we can reference them throughout all the methods in the class
12
Methods Example public void paint( Graphics g ) Within the class squigglys { } Has it’s own scope squigglys { } Statements in method only run when the method is called/invoked Parameters (none or multiple) listed in parenthesis Each must specify the data type and a variable name Separate multiple ones with a comma e.g. ( Graphics g ) return type of void designates the method doesn’t return anything g is a type of Graphics object, which has methods such as drawString that we can call paint is the name of the method 12 (c) 2008 by E.S.Boese. All Rights Reserved.
13
Method call that returns a value import java.awt.*; import javax.swing.*; public class Calculate extends JApplet { public void paint (Graphics g ) { int addition = getAdd( 2, 7 ); String added = "2 + 7 = " + addition; g.drawString ( added, 0, 12 ); String subtracted = "2 - 7 = " + getSubtract( 2, 7 ); g.drawString ( subtracted, 0, 24 ); } public int getAdd( int num1, int num2 ) { return num1 + num2; } public int getSubtract( int n1, int n2 ) { return n1 - n2; } The # 2 gets copied into variable num1, the # 7 gets copied into the variable num2 The value 9 gets returned to where the program called this method The # 2 gets copied into variable n1, the # 7 gets copied into the variable n2 The value -5 gets returned to where the program called this method 13 (c) 2008 by E.S.Boese. All Rights Reserved.
14
3 Types of Method calling 1. Within a class add( panel ); 2. In another class (type 1) Example: in the Graphics class g.drawString(“Hi”, 20, 10 ); (where g is from the Graphics class, e.g., public void paint( Graphics g ) 3. In another class (type 2) x = 22 + Math.abs( y ); 14 (c) 2008 by E.S.Boese. All Rights Reserved.
15
Why Have Methods? Code Easier to read: Repeated code: For access by other objects: Events: (we’ll discuss later) 15 (c) 2008 by E.S.Boese. All Rights Reserved.
16
Why Have Methods? import java.awt.*; import javax.swing.*; public class House extends JApplet { public void paint (Graphics g ) { g.setColor( Color.pink ); g.fillRect ( 100,100,200,200 ); g.setColor( Color.black ); Polygon poly = new Polygon( ); poly.addPoint(100,100); poly.addPoint(200,50); poly.addPoint(300,100); g.fillPolygon(poly); g.setColor( Color.blue ); g.fillRect ( 200,230,40,70); g.fillRect ( 120,150,20,30); g.fillRect ( 150,150,20,30); g.fillRect ( 200,150,20,30); g.fillRect ( 230,150,20,30); g.setColor( Color.black ); g.fillRect ( 400,130,30,170 ); g.setColor( Color.green ); g.fillOval( 370,80,100,100 ); g.fillRect ( 0,295,500,5 ); } // Code Easier to read: with methods import java.awt.*; import javax.swing.*; public class HouseMethods extends JApplet { int WINDOW_WIDTH = 20; int WINDOW_HEIGHT = 30; public void paint (Graphics g ) { paintHouse( g ); paintLandscape( g ); } public void paintHouse( Graphics grph ) { grph.setColor( Color.pink ); grph.fillRect ( 100,100,200,200 ); grph.setColor( Color.black ); Polygon poly = new Polygon(); poly.addPoint(100,100); poly.addPoint(200,50); poly.addPoint(300,100); grph.fillPolygon(poly); grph.setColor( Color.blue ); grph.fillRect ( 200,230,40,70); paintWindow( grph, 120, 150 ); paintWindow( grph, 150, 150 ); paintWindow( grph, 200, 150 ); paintWindow( grph, 230, 150 ); } public void paintWindow( Graphics gp, int x, int y ) { gp.setColor( Color.blue ); gp.fillRect ( x, y, WINDOW_WIDTH, WINDOW_HEIGHT ); } public void paintLandscape( Graphics g ) { g.setColor( Color.black );// tree g.fillRect ( 400,130,30,170 ); g.setColor( Color.green ); g.fillOval( 370,80,100,100 ); g.fillRect ( 0,295,500,5 );// grass } Which code is easier to figure out how to add a new window? 16 (c) 2008 by E.S.Boese. All Rights Reserved.
17
Why Have Methods? import javax.swing.*; import java.awt.*; public class NeedMethods extends JApplet { public void paint( Graphics g ) { // row 1 g.fillRect( 20,20, 10,10 ); g.fillRect( 40,20, 10,10 ); g.fillRect( 60,20, 10,10 ); g.fillRect( 80,20, 10,10 ); g.fillRect( 100,20, 10,10 ); // row 2 g.fillRect( 30,30, 10,10 ); g.fillRect( 50,30, 10,10 ); g.fillRect( 70,30, 10,10 ); g.fillRect( 90,30, 10,10 ); g.fillRect( 110,30, 10,10 ); } // Repeated code using a method: import javax.swing.*; import java.awt.*; public class NeedMethods2 extends JApplet { public void paint( Graphics g ) { drawRows( g, 20, 20 ); drawRows( g, 30, 30 ); } public void drawRows( Graphics graphics, int x, int y ) { graphics.fillRect( x,y, 10,10 ); graphics.fillRect( x+20, y, 10, 10 ); graphics.fillRect( x+40, y, 10, 10 ); graphics.fillRect( x+60, y, 10, 10 ); graphics.fillRect( x+80, y, 10, 10 ); } Which program would be easier to use to create a full-size checkerboard? 17 (c) 2008 by E.S.Boese. All Rights Reserved.
18
Why Have Methods? For access by other objects: Graphics gr gr.drawString( gr.fillRect( gr.setColor( If these weren’t methods, we wouldn’t be able to draw anything! 18 (c) 2008 by E.S.Boese. All Rights Reserved.
19
Why Have Methods? Events Events in Java are triggered when: User selects a button/checkbox/item in list/etc. User moves/drags the mouse User types a key Timer expires More… Each event automatically calls a particular method to handle the type of event that occurred. We’ll discuss events in more detail later 19 (c) 2008 by E.S.Boese. All Rights Reserved.
20
Summary Variables Scope: instance variables vs. local variables Method Structure Purpose of methods 20 (c) 2008 by E.S.Boese. All Rights Reserved.
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.