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.

Slides:



Advertisements
Similar presentations
Animation Mrs. C. Furman. Animation  We can animate our crab by switching the image between two pictures.  crab.png and crab2.png.
Advertisements

©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Chapter 41 Defining Classes and Methods Chapter 4.
Bellevue University CIS 205: Introduction to Programming Using C++ Lecture 3: Primitive Data Types.
CIS 234: Using Data in Java Thanks to Dr. Ralph D. Westfall.
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. Topics  Applets  Classes used for graphics Graphics Point Dimension.
CMT Programming Software Applications
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Java Syntax Primitive data types Operators Control statements.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 5 Applets and Graphics.
A Simple Applet. Applets and applications An applet is a Java program that runs on a web page –Applets can be run from: Internet Explorer Netscape Navigator.
Copyright 2006 by Pearson Education 1 Building Java Programs Supplement 3G: Graphics.
A Simple Applet.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
1 Drawing Shapes and Text With Applets. 2 Drawing in the paint method import java.awt.*;// access the Graphics object import javax.swing.*;// access to.
Variables Chapter 9 - Student Naming, data types, instance variables, math and conversions.
Introduction to Programming Prof. Rommel Anthony Palomino Department of Computer Science and Information Technology Spring 2011.
©2007 · Georges Merx and Ronald J. NormanSlide 1 Chapter 3 The Structure and Syntax of Java.
Java Primitives The Smallest Building Blocks of the Language (corresponds with Chapter 2)
***** SWTJC STEM ***** Chapter 2-2 cg Identifiers - Naming Identifier, the name of a Java programming component. Identifier naming rules... Must.
C Tokens Identifiers Keywords Constants Operators Special symbols.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CPS120: Introduction to Computer Science Variables and Constants Lecture 8 - B.
Java Data Types. Primitive Data Types Java has 8 primitive data types: – char: used to store a single character eg. G – boolean: used to store true or.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
TCU CoSc Introduction to Programming (with Java) Variables and Methods.
CPS120: Introduction to Computer Science
Java Structure import java_packages; class JavaClass { member variables declarations; void otherMethod( ) { } public static void main(String[]
1 A Simple Applet. 2 Applets and applications An application is an “ordinary” program Examples: Notepad, MS Word, Firefox, Halo, etc. An applet is a Java.
(c)2009 by E.S. Boese. All Rights Reserved. Classes Chapter 13 – Lecture Slides 1 Got class?
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
 Character set is a set of valid characters that a language can recognise.  A character represents any letter, digit or any other sign  Java uses the.
CS346 Javascript -3 Module 3 JavaScript Variables.
Java Classes, Objects, and Events: A Preview JavaMethods An Introduction to Object-Oriented Programming Maria Litvin Gary Litvin Copyright © 2003 by Maria.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
A variable is a storage location for some type of value. days 102 taxrate 7.75 int days = 102; double taxrate = 7.75; char grade = ‘A’; boolean done.
Copyright Curt Hill Variables What are they? Why do we need them?
Java Programming, Second Edition Chapter Two Using Data Within a Program.
CS100A, Fall 1998 Key Concepts 1 These notes contain short definitions of the basic entities that make up a Java program, along with a description of the.
School of Computer Science & Information Technology G6DICP - Lecture 4 Variables, data types & decision making.
(c)2006 E.S.Boese All Rights Reserved.1 Drawing Shapes and Text Chapter 2 – Lecture Slides.
VISUAL C++ PROGRAMMING: CONCEPTS AND PROJECTS Chapter 2A Reading, Processing and Displaying Data (Concepts)
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Variables and Methods Chapter 3 – Lecture Slides.
CPS120: Introduction to Computer Science Variables and Constants.
© 2007 Pearson Addison-Wesley. All rights reserved2-1 Character Strings A string of characters can be represented as a string literal by putting double.
 Variables are nothing but reserved memory locations to store values. This means that when you create a variable you reserve some space in memory. 
Sudeshna Sarkar, IIT Kharagpur 1 Programming and Data Structure Sudeshna Sarkar Lecture 3.
Primitive Data Types. int This is the type you are familiar with and have been using Stores an integer value (whole number) between -2,147,483,648 (-2.
Basic Data Types อ. ยืนยง กันทะเนตร คณะเทคโนโลยีสารสนเทศและการสื่อสาร มหาวิทยาลัยพะเยา Chapter 4.
Introducing, the JFrame Gives us a work area beside System.out.println.
Lecture 3: More Java Basics Michael Hsu CSULA. Recall From Lecture Two  Write a basic program in Java  The process of writing, compiling, and running.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
© 2004 Pearson Addison-Wesley. All rights reserved August 27, 2007 Primitive Data Types ComS 207: Programming I (in Java) Iowa State University, FALL 2007.
Chapter 02 Data and Expressions.
Chapter 2 Basic Computation
“Form Ever Follows Function” Louis Henri Sullivan
Yanal Alahmad Java Workshop Yanal Alahmad
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
Computer Science 3 Hobart College
IDENTIFIERS CSC 111.
Starting JavaProgramming
Variables ICS2O.
An overview of Java, Data types and variables
Chapter # 2 Part 2 Programs And data
Chap 2. Identifiers, Keywords, and Types
Variables and Constants
Presentation transcript:

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.

(c) 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;

(c) 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!

(c) 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

(c) 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

(c) by Elizabeth Sugar Boese 6 Characters Data type: char Enclose with single quotes char initial = ‘E’; char code = ‘!’; Escape sequences char singlequote = ‘\’’;

(c) by Elizabeth Sugar Boese 7 Boolean One of two values  true  false boolean isOn = false; boolean available = true;

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.

(c) 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

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.

(c) 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

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.

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.

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.

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.

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.

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.

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.

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.

Summary Variables Scope: instance variables vs. local variables Method Structure Purpose of methods 20 (c) 2008 by E.S.Boese. All Rights Reserved.