University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Input Lecture 7, Wed Jan 20 2010

Slides:



Advertisements
Similar presentations
Java Programming Strings Chapter 7.
Advertisements

Chapter 2: Using Objects Part 1. To learn about variables To understand the concepts of classes and objects To be able to call methods To learn about.
 2005 Pearson Education, Inc. All rights reserved Introduction.
1 Chapter 2 Introduction to Java Applications Introduction Java application programming Display ____________________ Obtain information from the.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input Lecture 5, Thu Jan
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Strings, Parameters Lecture 6, Mon Jan 18.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design Lecture 6, Tue Jan
CMT Programming Software Applications
Chapter 3 Using Classes and Objects. Creating Objects A variable holds either a primitive type or a reference to an object A class name can be used as.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Static Methods, Conditionals Lecture 15, Mon Feb 8.
Java Intro. Strings “This is a string.” –Enclosed in double quotes “This is “ + “another “ + “string” –+ concatenates strings “This is “ “ string”
Chapter 2 storing numbers and creating objects Pages in Horstmann.
Fundamental Programming Structures in Java: Strings.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Constants, Objects, Strings Lecture 4, Tue Jan
Strings as objects Strings are objects. Each String is an instance of the class String They can be constructed thus: String s = new String("Hi mom!");
Chapter 2  Using Objects 1 Chapter 2 Using Objects.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Conditionals II Lecture 11, Thu Feb
COMP 110 Introduction to Programming Mr. Joshua Stough September 10, 2007.
University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Class Design Lecture 8, Fri Jan
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
1 The First Step Learning objectives write Java programs that display text on the screen. distinguish between the eight built-in scalar types of Java;
***** SWTJC STEM ***** Chapter 3-1 cg 36 Java Class Libraries & API’s A class library is a set of classes that supports the development of programs. Java.
1 Chapter 2 JAVA FUNDAMENTALS CONT’D. 2 PRIMITIVE DATA TYPES Computer programs operate on data values. Values in Java are classified according to their.
Week #2 Java Programming. Enable Line Numbering in Eclipse Open Eclipse, then go to: Window -> Preferences -> General -> Editors -> Text Editors -> Check.
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.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
EXAM 1 REVIEW. days until the AP Computer Science test.
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.
A First Look at Java Chapter 2 1/29 & 2/2 Imagine! Java: Programming Concepts in Context by Frank M. Carrano, (c) Pearson Education - Prentice Hall, 2010.
Using Data Within a Program Chapter 2.  Classes  Methods  Statements  Modifiers  Identifiers.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Methods in Java. Program Modules in Java  Java programs are written by combining new methods and classes with predefined methods in the Java Application.
College Board A.P. Computer Science A Topics Program Design - Read and understand a problem's description, purpose, and goals. Procedural Constructs.
Can we talk?. In Hello World we already saw how to do Standard Output. You simply use the command line System.out.println(“text”); There are different.
Chapter 2 Using Objects. Types A type defines a set of values and the operations that can be carried out on the values Examples: 13 has type int "Hello,
1 Principles of Computer Science I Prof. Nadeem Abdul Hamid CSC 120 – Fall 2005 Lecture Unit 2 - Using Objects.
Outline Character Strings Variables and Assignment Primitive Data Types Expressions Data Conversion Interactive Programs Graphics Applets Drawing Shapes.
CSC 1051 M.A. Papalaskari, Villanova University Everyday objects: Strings and Wrappers CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari.
Using Classes and Objects Chapters 3 Creating Objects – Section 3.1 The String Class – Section 3.2 The Scanner Class – Section 2.6 Instructor: Scott Kristjanson.
CSE 1201 Object Oriented Programming Using Classes and Objects.
Copyright 2010 by Pearson Education 1 Building Java Programs Chapter 2 Lecture 2-1: Expressions and Variables reading:
CSC 1051 – Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
Announcements Quiz 1 Next Monday. int : Integer Range of Typically –2,147,483,648 to 2,147,483,647 (machine and compiler dependent) float : Real Number.
Chapter 2 Using Objects. Chapter Goals To learn about variables To understand the concepts of classes and objects To be able to call methods To be able.
Introduction to Java Applications Part II. In this chapter you will learn:  Different data types( Primitive data types).  How to declare variables?
A Sample Program public class Hello { public static void main(String[] args) { System.out.println( " Hello, world! " ); }
Java – Variables and Constants By: Dan Lunney. Declaring Variables All variables must be declared before they can be used A declaration takes the form:
1 Predefined Classes and Objects Chapter 3. 2 Objectives You will be able to:  Use predefined classes available in the Java System Library in your own.
CS 106 Introduction to Computer Science I 09 / 10 / 2007 Instructor: Michael Eckmann.
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.
CS 106 Introduction to Computer Science I 01 / 24 / 2007 Instructor: Michael Eckmann.
CS0007: Introduction to Computer Programming Primitive Data Types and Arithmetic Operations.
Coming up Implementation vs. Interface The Truth about variables Comparing strings HashMaps.
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.
University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Class Design II Lecture 7, Thu Jan
1 reading: 3.3 Using objects. Objects So far, we have seen: methods, which represent behavior variables, which represent data (categorized by types) It.
(Dreaded) Quiz 2 Next Monday.
Chapter 7 User-Defined Methods.
Building Java Programs
String class.
Yanal Alahmad Java Workshop Yanal Alahmad
Primitive Types Vs. Reference Types, Strings, Enumerations
INPUT STATEMENTS GC 201.
Chapter 7: Strings and Characters
CSS 161 Fundamentals of Computing Introduction to Computers & Java
Introduction to Classes and Methods
Know for Quiz Everything through Last Week and Lab 7
Introduction to Java Programming
Presentation transcript:

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner 1 Objects, Input Lecture 7, Wed Jan borrowing from slides by Kurt Eiselt

2 News n Midterm location announced: FSC 1005 n for both Feb 28 and Mar 22 midterms n Assignment 1 out n due Wed 3 Feb at 5pm, by electronic handin

3 Recap: Classes, Methods, Objects n Class: complex data type n includes both data and operations n programmers can define new classes n many predefined classes in libraries n Method: operations defined within class n internal details hidden, you only know result n Object: instance of class n entity you can manipulate in your program

4 Recap: Declare vs. Construct Object n Variable declaration does not create object n creates object reference n Constructor and new operator creates object somewhere in memory n constructors can pass initial data to object n Assignment binds object reference to created object n assigns address of object location to variable public static void main (String[] args) { String firstname; firstname = new String (“Kermit"); }

5 Recap: Declare vs. Construct Object firstname String object “Kermit” expression on right side of assignment operator bind variable to expression on right side of assignment operator

6 Recap: Objects vs. Primitives n references int favoriteNum Frog object Frog favoriteFrog 42 int famousNum 42 Frog famousFrog n vs. direct storage boolean isMuppet true String frogName String object “Kermit”

7 Recap: Objects vs. Primitives n references int favoriteNum Frog object Frog favoriteFrog 999 int famousNum 42 Frog famousFrog boolean isMuppet false String frogName String object “Kermit” n vs. direct storage

8 Recap: API Documentation n Online Java library documentation at n textbook alone is only part of the story n let’s take a look! n Everything we need to know: critical details n and often many things far beyond current need n Classes in libraries are often referred to as Application Programming Interfaces n or just API

9 Recap: Some Available String Methods public String toUpperCase(); Returns a new String object identical to this object but with all the characters converted to upper case. public int length(); Returns the number of characters in this String object. public boolean equals( String otherString ); Returns true if this String object is the same as otherString and false otherwise. public char charAt( int index ); Returns the character at the given index. Note that the first character in the string is at index 0.

10 Recap: More String Methods public String replace(char oldChar, char newChar); Returns a new String object where all instances of oldChar have been changed into newChar. public String substring(int beginIndex); Returns new String object starting from beginIndex position public String substring( int beginIndex, int endIndex ); Returns new String object starting from beginIndex position and ending at endIndex position Hello KermitFrog substring(4, 7) “o K” up to but not including endIndex char:

11 String firstname = "Alphonse"; char thirdchar = firstname.charAt(2); object method parameter Recap: Methods and Parameters n Methods are how objects are manipulated n pass information to methods with parameters n inputs to method call n tell charAt method which character in the String object we're interested in n methods can have multiple parameters n API specifies how many, and what type n two types of parameters n explicit parameters given between parens n implicit parameter is object itself

12 Recap: Return Values n Methods can have return values n Example: charAt method result n return value, the character 'n', is stored in thirdchar String firstname = "kangaroo"; char thirdchar = firstname.charAt(2); n Not all methods have return values n No return value indicated as void return value object method parameter

13 Recap: Constructors and Parameters n Many classes have more than one constructor, taking different parameters n use API docs to pick which one to use based on what initial data you have animal = new String(); animal = new String("kangaroo");

14 Classes, Continued n A class has a name. n A class should describe something intuitively meaningful. Why did someone create this class? n A class describes the data stored inside objects in the class. (Nouns) n A class describes the legal operations that can be done to the data. (Verbs) n Example in Book: java.awt.Rectangle

15 Primitive Types vs. Classes Objects belong to classes E.g., you are a UBC Student Values belong to types. E.g., 3 is an int, is a double MethodsOperators: +, -, … Can be arbitrarily complex Simplest things, e.g., int Written by other programmers or by you Pre-defined in Java ClassesPrimitive Types

16 Objects Belong to Classes n Just as 1, 2, and 3 are all integers, you are all objects of the class UBCStudent! n You each have names, ID numbers, etc. n Each is unique person, but all are students n Social organizations example: n Ballroom Dance Club n Ski Club n CSSS n Etc. n Sometimes called “instances” of a class.

17 Class Libraries n Before making new class yourself, check to see if someone else did it already n libraries written by other programmers n many built into Java n Examples (built into Java) n BigInteger (java.math.BigInteger) lets you compute with arbitrarily big integers. n Date (java.util.Date) lets you get the current time. n Calendar (java.util.Calendar) does fancy date computations.

18 Example: BigInteger import java.math.BigInteger; // Tell Java to use standard BigInteger package public class GetRichQuick { public static void main(String[] args) { BigInteger salary = new BigInteger(" "); BigInteger stockOptions = new BigInteger(" "); BigInteger profitPerShare = new BigInteger("314159"); BigInteger optionCompensation = stockOptions.multiply(profitPerShare); BigInteger totalCompensation = salary.add(optionCompensation); System.out.println("Total Compensation = $" + totalCompensation.toString()); }

19 BigInteger Constructors import java.math.BigInteger; // Tell Java to use standard BigInteger package public class GetRichQuick { public static void main(String[] args) { BigInteger salary = new BigInteger(" "); BigInteger stockOptions = new BigInteger(" "); BigInteger profitPerShare = new BigInteger("314159"); BigInteger optionCompensation = stockOptions.multiply(profitPerShare); BigInteger totalCompensation = salary.add(optionCompensation); System.out.println("Total Compensation = $" + totalCompensation.toString()); }

20 Literals n With the primitive types, how do you create values with that type? E.g., how do we create integer values? 1. You type some digits, like 3, or You combine integer-valued things with operators that work on integers, e.g., 3+42*(a-b)

21 Literals n With the primitive types, how do you create values with that type? E.g., how do we create integer values? 1. You type some digits, like 3, or You combine integer-valued things with operators that work on integers, e.g., 3+42*(a-b) n A bunch of digits are an integer literal. n It’s the basic way to create an integer value

22 More Literals n How about a value of type double? 1. You type a bunch of digits with a decimal point, and optionally the letter e or E followed by an exponent 2. You can combine doubles with operators that work on doubles.

23 More Literals n How about a value of type double? 1. You type a bunch of digits with a decimal point, and optionally the letter e or E followed by an exponent 2. You can combine doubles with operators that work on doubles. Those are literals!

24 Long Literals n How about values of type long? 1. You type a bunch of digits followed by the letter l or L 2. You combine previously created longs

25 Literals – General Pattern n To create values of a primitive type: 1. There’s some way to type a literal 2. There are operators that create values of the given type.

26 Literals for Classes? n Classes are like primitive types, except they can be defined any way you like, and they can be much more complex. n How to create a value (an object) of a given class? 1. Invent some way to type a literal??? 2. Operators that create objects of that class (methods).

27 Constructors! n A constructor is the equivalent of a literal for a class. It’s how you create a new object that belongs to that class. n Examples: new BigInteger(“999999”) new Rectangle(10, 20, 30, 40) new UBCStudent(“Joe Smith”, ,…)

28 Constructor Syntax n The reserved word new n Followed by the name of the class n Followed by an open parenthesis ( n Followed by an parameters (information needed to construct the object) n Followed by a closing parenthesis )

29 Using Constructors n Use a constructor just as you’d use a literal. Example: n For the int type: int a = 3; n For the BigInteger class: BigInteger a = new BigInteger(“3”);

30 Primitive Types vs. Classes Objects belong to classes E.g., you are a UBC Student Values belong to types. E.g., 3 is an int, is a double ConstructorsLiterals MethodsOperators: +, -, … Can be arbitrarily complex Simplest things, e.g., int Written by other programmers or by you Pre-defined in Java ClassesPrimitive Types

31 What about String ? n Is String a primitive type? Is it a class? n String is a class, but it’s a special class! n Automatically imported n Built-in literals, e.g., “This is a String literal.” n + operator for concatenation n But it also has many other methods, that you can call, just like for any ordinary class…

32 String Example – Constructor Syntax public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname = new String (“Kermit"); lastname = new String (“the Frog"); System.out.println("I am not " + firstname + " " + lastname); }

33 String Example - Literal Syntax public class StringTest { public static void main (String[] args) { String firstname; String lastname; firstname= “Kermit”; lastname= “the Frog”; System.out.println("I am not " + firstname + " " + lastname); } String is the only class that supports both literals and constructors!

34 Escape Characters n How can you make a String that has quotes? n String foo = “oh so cool”; n String bar = “oh so \”cool\”, more so”; n Escape character: backslash n general principle

35 Keyboard Input n Want to type on keyboard and have Java program read in what we type n store it in variable to use later n Want class to do this n build our own? n find existing standard Java class library? n find existing library distributed by somebody else? n Scanner class does the trick n java.util.Scanner n nicer than System.in, the analog of System.out

36 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example

37 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n Import Scanner class from java.util package

38 Importing Packages n Collections of related classes grouped into packages n tell Java which packages to keep track of with import statement n again, check API to find which package contains desired class n No need to import String, System.out because core java.lang packages automatically imported

39 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n Declare string variable to store what user types in

40 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n Use Scanner constructor method to create new Scanner object named scan n could be named anything, like keyboardStuff or foo

41 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n Prompt user for input

42 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n nextLine method reads all input until end of line n returns it as one long string of characters

43 import java.util.Scanner; public class Echo { public static void main (String[] args) { String message; Scanner scan = new Scanner (System.in); System.out.println ("Enter a line of text: "); message = scan.nextLine(); System.out.println ("You entered: \"" + message + "\""); } Scanner Class Example n Print out the message on the display

44 Scanner Class Example n Let’s try running it