6/4/01 2. Programming with Objects 2.1 Names 2.2 Objects and Classes 2.3 using Objects 2.4 Arithmetic Expressions 2.5 Parameters and Input 2.6 Getting.

Slides:



Advertisements
Similar presentations
L2:CSC © Dr. Basheer M. Nasef Lecture #2 By Dr. Basheer M. Nasef.
Advertisements

 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
Data Types in Java Data is the information that a program has to work with. Data is of different types. The type of a piece of data tells Java what can.
©2004 Brooks/Cole Chapter 2 Variables, Values and Operations.
Aalborg Media Lab 21-Jun-15 Software Design Lecture 2 “ Data and Expressions”
Program Elements We can now examine the core elements of programming (as implemented in Java) We focuse on: data types variable declaration and use, constants.
Chapter Day 4. © 2007 Pearson Addison-Wesley. All rights reserved2-2 Agenda Day 4 Return Signed Contracts Questions from last Class?? Problem set 1 Posted.
ECE122 L3: Expression Evaluation February 6, 2007 ECE 122 Engineering Problem Solving with Java Lecture 3 Expression Evaluation and Program Interaction.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie June 27, 2005.
Fundamental Programming Structures in Java: Comments, Data Types, Variables, Assignments, Operators.
Primitive Types Java supports two kinds of types of values – objects, and – values of primitive data types variables store – either references to objects.
Review Java.
1 Expressions, Operators Expressions Operators and Precedence Reading for this class: L&L, 2.4.
CSci 142 Data and Expressions. 2  Topics  Strings  Primitive data types  Using variables and constants  Expressions and operator precedence  Data.
Expressions, Data Conversion, and Input
Introduction to Java Appendix A. Appendix A: Introduction to Java2 Chapter Objectives To understand the essentials of object-oriented programming in Java.
Simple Programs from Chapter 2 Putting the Building Blocks All Together (corresponds with Chapter 2)
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Primitive Types, Strings, and Console I/O Chapter 2.1 Variables and Values Declaration of Variables Primitive Types Assignment Statement Arithmetic Operators.
Chapter 2 Basic Elements of Java. Chapter Objectives Become familiar with the basic components of a Java program, including methods, special symbols,
Outline Questions / Review Predefined Objects Variables Primitive Data Arithmetic Expressions Interactive Programs Decision Making Assignments.
Introduction to Programming David Goldschmidt, Ph.D. Computer Science The College of Saint Rose Java Fundamentals (Comments, Variables, etc.)
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Assignment Statements Operator Precedence. ICS111-Java Programming Blanca Polo 2 Assignment, not Equals  An assignment statement changes the value of.
Copyright © 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Java Software Solutions Foundations of Program Design Sixth Edition by Lewis.
CIS 260: App Dev I. 2 Programs and Programming n Program  A sequence of steps designed to accomplish a task n Program design  A detailed _____ for implementing.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 2 Basic Elements of Java.
 2000 Prentice Hall, Inc. All rights reserved. 1 Chapter 2 - Introduction to Java Applications Outline 2.1Introduction 2.2A Simple Program: Printing a.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Java™ How to Program, 10/e © Copyright by Pearson Education, Inc. All Rights Reserved.
Computing with C# and the.NET Framework Chapter 2 C# Programming Basics ©2003, 2011 Art Gittleman.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Copyright Curt Hill Variables What are they? Why do we need them?
A Simple Java Program //This program prints Welcome to Java! public class Welcome { public static void main(String[] args) { public static void main(String[]
Programming in Java (COP 2250) Lecture 4 Chengyong Yang Fall, 2005.
Operators and Expressions. 2 String Concatenation  The plus operator (+) is also used for arithmetic addition  The function that the + operator performs.
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
By Mr. Muhammad Pervez Akhtar
Creating a Java Application and Applet
Doing math In java.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
 2005 Pearson Education, Inc. All rights reserved Introduction to Classes and Objects.
Java Programming: From Problem Analysis to Program Design, Second Edition 1 Lecture 1 Objectives  Become familiar with the basic components of a Java.
Chapter 2: Basic Elements of Java J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Chapter 2: Data and Expressions. Variable Declaration In Java when you declare a variable, you must also declare the type of information it will hold.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Data and Expressions. Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration.
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.
© 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.
3 Introduction to Classes and Objects.
Introduction to Classes and Objects
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
Primitive Data Types August 28, 2006 ComS 207: Programming I (in Java)
2.5 Another Java Application: Adding Integers
Multiple variables can be created in one declaration
Computing with C# and the .NET Framework
Java Programming: From Problem Analysis to Program Design, 4e
Escape Sequences What if we wanted to print the quote character?
Chapter 2 Edited by JJ Shepherd
Chapter 2 - Introduction to Java Applications
Chapter 2: Basic Elements of Java
Expressions and Assignment
Unit 3: Variables in Java
Presentation transcript:

6/4/01 2. Programming with Objects 2.1 Names 2.2 Objects and Classes 2.3 using Objects 2.4 Arithmetic Expressions 2.5 Parameters and Input 2.6 Getting Started with Applets and Events

6/4/01 Objectives Name objects and other Java entities Build a class to define objects Use methods to invoke other behavior Use arithmetic expressions to compute value Input in a dialog Use an import statement Get started with applet and events

6/4/ Names Objects can communicate by calling each other’s responsibilities by names Names of objects, their data and responsibilities are called identifiers ::= { | digit} ::= a..z | A..Z | _ | $ ::= 0..9 Keywords are reserved identifiers for special uses

6/4/01 The (7-bit) ASCII character set contains 128 characters The (8-bit) Extended ASCII character set contains 256 characters In general, an n-bit character set contains 2 characters. Java uses a 16-bit character set called Unicode that may contain at most characters Unicode contains ASCII code as a subset, and characters of many countries n

6/4/01 Valid Identifiers savings, textLabel, rest_stop_12, x, I3, _test, $soup Not valid Identifiers 4you // Starts with a number x< y// Includes an illegal character, < top-gun // Includes an illegal character, - int // Reserved, see below Figure 2.2 Valid and Invalid Java identifiers

6/4/01

2.2 Objects and Classes We can think of an object as a collection of services that we can tell it to perform for us A class defines a type of objects public class Vending { // variables, methods, and constructors } Java’s style starts class names with an uppercase character Starts comment with // (through end of line), or enclose it with /* and */

6/4/01 Java entity Use class define a type of object instance variable define object state instance method define object behavior constructor provide object identity Figure 2.4 Java constructs for defining objects

6/4/01 Variables and their values define the state of an object A variable can hold either a primitive type or an object reference Primitive types include byte, short, int, long, float, double, char, and boolean Java uses 32-bit (signed) integers. The range is -2,147,483,648 to 2,147,483,647 Accessibility can be controlled by modifiers public, private or protected

6/4/01 Instance variables are those defined in a class without the static modifier Constructors have the same name as the class A constructor allocates space for the instance variables and may also initialize their values A constructor may have formal parameters Default constructor is one without parameters. A constructor doesn’t return any value

6/4/01 Methods specify the responsibilities, or behaviors, of the objects Instance methods are those defined without the static modifier A method has a header and a body The header specifies the type, the name, a list of parameters, and other modifiers The body contains the details to accomplish the designed responsibility or behavior The body contains a series of declarations and statements

6/4/01 Consider the statement: quarters = quarters + numberOfQuarters ;

6/4/01 Packages Example: package vend; Java organizes classes into packages A package name corresponds to a directory of the host file system Java style starts a package name with lowercase letter The package statement must be the first non- comment line in the program The import statement

6/4/01 Some of the packages in the standard class library are: PackagePurpose java.lang General support java.applet Creating applets for the web java.awt Graphic and GUI javax.swing Additional graphic capabilities java.net Network communication java.util Utilities

6/4/01 The assignment statement The return statement A string is a sequence of characters. Constant strings are enclosed in double quotes, e.g. “three blind mice”. The String class The void keyword Unified Modeling Language (UML) object diagram.

6/4/01 Figure 2.6 A Vending1 instance ___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney

6/4/ Using Objects A variable whose type is a class is a reference variable to an object Vending1 byTheDoor = new Vending1(10,15); Reference variable byTheDoor holds the address of the newly created Vending1 object The decalaration Vending1 machineA; Creates a reference variable referring to no object at this point (with value null )

6/4/01 Figure 2.7 A reference variable of type Vending1 ___________:Vending1 quarters = 10 candyBars = 15 enterMoney selectMoney byTheDoor

6/4/01 null machineA Figure 2.8 A null reference

6/4/01 An instance method must be invoked via an object reference Need testing (or driver) class to create objects and invoke their methods Special method in driver class: public static void main(String[] args) { // code goes here }; Class methods - declared with static Java interpreter invokes the class method main to start executing a Java program

6/4/01 Figure 2.9 After executing byTheDoor.enterMoney(3) ___________:Vending1 quarters = 13 candyBars = 15 enterMoney selectMoney byTheDoor

6/4/01 Figure 2.10 After executing byTheDoor.selectCandy() ___________:Vending1 quarters = 13 candyBars = 14 enterMoney selectMoney byTheDoor

6/4/01 Local variables: those declared inside a method Output statement: System.out.print(“Have a nice day ”); System.out.println(12345); System is a class defined in java.lang package, and out is one of its class variable, a reference to a PrintStream object The PrintStream class has many methods including print and println

6/4/ Arithmetic Expressions An expression is a combination of operators and operands Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % If either or both operands are floating point, the result is floating point.

6/4/01 Operation Math notation Java (constants) Java (variables) Addition a + b score1 + score2 Subtraction a - b bats - gloves Multiplication ab 12 * 17 twelve * dozens Division a/b 7 / 3 total / quantity Remainder r in a=qb+r 43 % 5 cookies % people Negation -a -6 -amount Figure 2.13 Java arithmetic operations

6/4/01 Operator Precedence Operators can be combined into complex expressions result = total + count / max - offset; Operators have a well-defined precedence which determines the order of evaluation Multiplication, division, and remainder are evaluated prior to addition, subtraction and string concatenation Arithmetic operators with same precedence are evaluated from left to right Parentheses can be use to change the order

6/4/ * 5 Figure 2.14 Multiplication gets its operands first

6/4/01 * 5 (3 + 4) Figure 2.15 Compute within parentheses first

6/4/01 Increment & Decrement Operators The increment and decrement operators are unary The increment operator ( ++ ) adds one to its operand The decrement operator ( -- ) subtracts one from its operand The statement count++; is essentially equivalent to count = count + 1;

6/4/01 The increment and decrement operators can be applied in prefix form (before the variable) or postfix form (after the variable) ExpressionOperationValue of Expression count++ add 1 old value ++count add 1 new value count--subtract 1 old value --countsubtract 1 new value When used alone in a statement, prefix and postfix forms make no difference Have different effect in larger expressions

6/4/01 Figure 2.16 Expression a) and equivalent expression b) then 3 + x x++ a.b. 3 + x++

6/4/01 Figure 2.17 Expression a) and equivalent expression b) then ++x 3 + x a.b x

6/4/01 Assignment Operators Often we perform an operation on a variable, then store the result back into that variable Java provides assignment operators to simplifies the notations OperatorExampleEquivalent To += x += y x = x + y -= x -= y x = x - y *= x *= y x = x * y /= x /= y x = x / y %= x %= y x = x % y

6/4/01 Parameters A method may have a list of (formal) parameters Another method calls it by providing a matching list of arguments (or actual parameters) Argument-parameter matching is the primary mechanism for the calling method to pass data to the called method Java always passed arguments by value, meaning that the called method receives the values of the arguments Changing value of a parameter has no effect on the correspond argument

6/4/01 v.enterMoney Figure 2.19 The enterMoney “machine” Arguments Return Value 2, 2, 1 75

6/4/01 v :Vending2 quarters = 20 dimes = 20 nickels = 20 candy = 10 enterMoney selectCandy test before v :Vending2 quarters = 22 dimes = 22 nickels = 21 candy = 10 enterMoney selectCandy test after Figure 2.20 The state change from enterMoney

6/4/01 Figure 2.21 Memory usage cube aNumber 12 x value 0 After the call then 17 During the call main result Before the call to cube(x)

6/4/01 Message and Input Dialogs Output can be displayed in a popup message dialog rather than a console window JOptionPane.showMessageDialog(null, “hi there”); The JOptionPane class is in javax.swing import javax.swing.JOptionPane; The showInputDialog method of JOptionPane pops up a window that accepts input from the user String s = JOptionPane.showInputDialog (“How many quarters deposited? “); int q = Integer.parseInt(s);

6/4/01 Figure 2.23 Package diagram default TestVending2 //other classes in //the same //directory Javax.swing JOptionPane > vend Vending1 >

6/4/01 Colors and Coordinate Systems A picture to be displayed is broken down into pixels, and each pixel is stored separately Each pixel can be identified using a two- dimensional coordinate system In Java, each pixel can be represented by three numbers between 0 and 225, the RGB value, that specify the intensity of the three primary colors When referring to a pixel in a Java program, we use a coordinate system with the origin in the upper left corner

6/4/01 Figure 2.26 Coordinates, in pixels, for 400 by 300 window x (0,0) (0,299) (399,0) (399,299) y

6/4/01 Applets runs on a browser or applet viewer Any applet always extends the Applet class The Applet class provides a standard interface between the applets and their environment We override the paint method of the Applet class to handle the paint events A Graphics object can be used to write strings or draw pictures An applet is part of a web page