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

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

Chapter 4: Writing Classes
Chapter 41 Defining Classes and Methods Chapter 4.
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.
Chapter Day 5. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 5 Questions from last Class?? Problem set 1 Posted  Introduction on developing.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
©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.
Aalborg Media Lab 28-Jun-15 Software Design Lecture 8 “Arrays”
Chapter 4: Writing Classes Presentation slides for Java Software Solutions Foundations of Program Design Third Edition by John Lewis and William Loftus.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
A Simple Applet.
Chapter 3 Using Classes and Objects. 2 Creating Objects  A variable holds either a primitive type or a reference to an object  A class name can be used.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
11 Chapter 5 METHODS. 22 INTRODUCTION TO METHODS A method is a named block of statements that performs a specific task. Other languages use the terms.
Introduction to Methods
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
COMP More About Classes Yi Hong May 22, 2015.
TCU CoSc Introduction to Programming (with Java) Getting to Know Java.
Comp 248 Introduction to Programming Chapter 4 - Defining Classes Part A Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia.
Computer Science [3] Java Programming II - Laboratory Course Lab 6: Introduction to Java Applets Sample Applets from the Java Simple Java Applet: Drawing.
CSM-Java Programming-I Spring,2005 Introduction to Objects and Classes Lesson - 1.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
More with Methods (parameters, reference vs. value, array processing) Corresponds with Chapters 5 and 6.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Introduction to Java and Object-Oriented Programming AJSS Computer Camp Department of Information Systems and Computer Science Ateneo de Manila University.
Chapter 5: Enhancing Classes
JAVA Tokens. Introduction A token is an individual element in a program. More than one token can appear in a single line separated by white spaces.
Classes CS 21a: Introduction to Computing I First Semester,
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.
CPS120: Introduction to Computer Science Decision Making in Programs.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 2: Variables & Data Types.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
MSc Workshop - © S. Kamin, U.Reddy Lect 4 - Events - 1 Lecture 4 – Event Handling r Painting r Event types r Catching different event types.
Procedural programming in Java Methods, parameters and return values.
Applications Development
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
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.
TCU CoSc Introduction to Programming (with Java) Java Language Overview.
Variables and Methods Chapter 3 – Lecture Slides.
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.
Methods Awesomeness!!!. Methods Methods give a name to a section of code Methods give a name to a section of code Methods have a number of important uses.
CSIS 113A Lecture 5 Functions. Introduction to Functions  Building Blocks of Programs  Other terminology in other languages:  Procedures, subprograms,
CMSC 104, Section 301, Fall Lecture 18, 11/11/02 Functions, Part 1 of 3 Topics Using Predefined Functions Programmer-Defined Functions Using Input.
 2003 Prentice Hall, Inc. All rights reserved. 1 Chapter 3 - Introduction to Java Applets Will not cover Section 3.7 Thinking About Objects: Identifying.
Tarik Booker CS 242. What we will cover…  Functions  Function Syntax  Local Variables  Global Variables  The Scope of Variables  Making Functions.
Introducing, the JFrame Gives us a work area beside System.out.println.
Chapter 5 Introduction to Defining Classes Fundamentals of Java.
Chapter 02 Data and Expressions.
Information and Computer Sciences University of Hawaii, Manoa
Chapter 5: Enhancing Classes
“Form Ever Follows Function” Louis Henri Sullivan
Chapter 4: Writing Classes
2.5 Another Java Application: Adding Integers
Chapter 3: Using Methods, Classes, and Objects
JavaScript: Functions.
Chapter 4: Writing Classes
Constructor Laboratory /12/4.
Defining methods and more arrays
Object Oriented Programming in java
Defining Classes and Methods
Corresponds with Chapter 5
Presentation transcript:

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

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.

Variables Declaration Graphics 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”); Declaration includes the data type and a variable name. Assignment changes the value of a variable.. 3 Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.

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

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.

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.

Methods 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); return type of void designates the method doesn’t return anything g is called a “parameter”. Its type is a Graphics object, which has methods such as drawString that we can call paint is the name of the method 7

Method Types Method Types: There are two slightly different forms of methods in Java. (1)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: void methodName(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 }

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

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 ) { int diff; diff = n1 - n2; return diff; } 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 10 Slide created by: Professor Elizabeth Boese, “An Introduction to Programming with Java Applets”, Jones and Bartlett Publishers.

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) 11

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?

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? 13

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 14

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