1 / 15

TCU CoSc 10403 Introduction to Programming (with Java)

TCU CoSc 10403 Introduction to Programming (with Java). Variables and Methods. Java Identifiers. Identifiers are the words a programmer uses to identify particular items in a program.

dusan
Download Presentation

TCU CoSc 10403 Introduction to Programming (with Java)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. TCU CoSc 10403 Introduction to Programming (with Java) Variables and Methods

  2. Java Identifiers • Identifiers are the words a programmer uses to identify particular items in a program. • They may be used to name a variable (e.g. studentName), a class (e.g., HelloWorld or Lab2), or a method (e.g., paint or init). • Most identifiers have no predefined meaning except as specified by the programmer. • Rules & Naming Conventions • There are rules and naming conventions that are discussed in great detail in Chapter 6 • Suffice it to say that when you create (instantiate) an object or create a variable to do arithmetic with – it MUST be declared. • Java allows the creation of variables to hold integer values, real values, boolean values, and characters (these are called primitive data types). ***Note: Java is case sensitive. The identifier xyz is not the same as XYZ.

  3. Declaration includes the data type and a variable name. Variables • DeclarationGraphics g; int numCourses; // integer values double salesTax; // floating pt number Color myColor = new Color(50,100,150); • 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 ); • Objects Student tom = new Student(“Tom Jones”); or Student tom; tom = new Student(“Tom Jones”); Assignment changes the value of a variable.. Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.

  4. Scope: 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 ); } } Instance Variable vs. Local Variable Instance variable: declared inside the class Local variable : declared inside a method Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.

  5. Real World Example of a Method • If you have ever used a recipe to prepare a meal – you may have advanced to a step in the recipe only to find that you need to refer to another recipe for something that you need for the meal (say a sauce that is explained on a different page). • This way of writing has an import analogue in programming – called methods in Java. • The nice thing about this is that important details about the sauce (i.e., ingredients, preparation time, etc.) can be hidden from the current recipe. • The same is true for programming – regardless of the language being used.

  6. Methods • In the context of programming - a method is a list (sequence) of statements to be performed. • Methods are used in all programming languages. They are called different names (e.g., procedures, subroutines, functions, subprograms, etc.). In Java – they are methods. • But they all do the same thing – namely, when they are called (invoked) they run and execute the statements that are enclosed within them. (e.g., the paint() method). • They are provided in programming languages as a means of decomposing large programs of statements into smaller ones – ones that are more easy to manage and to develop.

  7. return type of void designates the method doesn’t return anything Methods paint is the name of the method • Example public void paint( Graphics g ) { . . . //executable statements } • Has it’s own scope braces { } • 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 parameters with a comma paint ( Graphics g ) Student (“John Doe”, 20, “Freshman”); Color (50, 100, 150); g is called a “parameter”. Its type is a Graphicsobject, which has methods such as drawString that we can call

  8. Method Types Method Types: • There are two slightly different forms of methods in Java. • The first receives whatever arguments it is passed, executes the statements in its body, and returns control of the program where it was first invoked – nothing is passed back! These take the form: voidmethodName(list of arguments) { list of declarations, statements, and inner classes } (2) The second receives whatever arguments it is passed, executes the statements in its body, and returns control of the program where it was first invoked – but passes back some information. These take the form: returnTypeName methodName(list of arguments) { list of declarations, statements, and inner classes return expression //must be same type as returnTypeName }

  9. Method – Flow of Control • You will recall that the init()method is invoked by the system when you submit the bytecode to the interpreter • A call to a method places the “called” method into execution. • When the “called” method reaches the end (or a return statement) – control is passed by to the “calling” method (just as though there was no interruption in the execution flow of the invoking method).

  10. Method call that returns a value The # 2 gets copied into variable num1, the # 7 gets copied into the variable num2 The value9gets returned to where the program called this method 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 ) { int diff; diff = n1 - n2; return diff; } } The # 2 gets copied into variable n1, the # 7 gets copied into the variable n2 The value -5gets returned to where the program called this method Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.

  11. Why Use Methods? • Code is easier to read: • Program decomposition – • step-wise-refinement • top-down design • Repeated code: • For access by other objects: • Events: (we’ll discuss later)

  12. // 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 } } Why Have Methods? Which code is easier to figure out how to add a new window? 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 ); } }

  13. Why Have Methods? // 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 ); } } 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 ); } } Which program would be easier to use to create a full-size checkerboard?

  14. 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

  15. Summary • Variables • Scope: instance variables vs. local variables • Method Structure • Purpose of methods

More Related