COMP-202 Unit 5: Basics of Using Objects

Size: px
Start display at page:

Download "COMP-202 Unit 5: Basics of Using Objects"

Transcription

1 COMP-202 Unit 5: Basics of Using Objects CONTENTS: Concepts: Classes, Objects, and Methods Creating and Using Objects Introduction to Basic Java Classes (String, Random, Scanner, Math...)

2 Introduction (1) As we know, there are three possible roles for a class in Java We know that a class can be the starting point for a program Any class that defines a main() method has this role So far, all the classes that we have written have had this role, and only this role However, a class can also have two other roles It can be a collection of related methods, which are lists of statements that have a name, that perform a task, and that can be executed by invoking them It can define a category of objects, and specify what the objects that belong to this category look like and how they behave COMP Basics of Using Objects 2

3 Introduction (2) In the classes that we write, we can use the classes that have one (or both) of these two other roles We can create and use objects that belong to these classes We can call or invoke the methods defined in these classes by writing a single statement; when we do this, the statements that the method consists of are executed COMP Basics of Using Objects 3

4 Introduction (3) We have already created objects and invoked methods in the programs that we have written When we write Scanner keyboard = new Scanner(System.in); we create a new object which belongs to class Scanner nextint() is a method; when we write keyboard.nextint() in a statement, we invoke the nextint() method on the Scanner object that the variable keyboard keeps track of, and the statements that this method consists of are executed println() is also a method; when we write System.out.println(), we invoke the println() method on the PrintStream object that the variable System.out keeps track of, and the statements that it consists of are executed COMP Basics of Using Objects 4

5 Using Objects and Methods (1) Classes, objects, and methods are powerful tools They enable us to have the programs we write use the lists of statements someone else has written This has the potential to greatly reduce our workload; someone else has already written parts of the program for us Learning how to use classes, objects, and methods will enable us to write larger, more interesting programs For now, we will learn How to create and use objects which belong to classes that other people have written How to call methods that other people have written COMP Basics of Using Objects 5

6 Using Objects and Methods (2) Later, we will learn How to write our own classes which define our own categories of objects How to write our own methods that we (or someone else) can invoke in our programs COMP Basics of Using Objects 6

7 Part 1: Basics of Classes, Objects, and Methods

8 Objects (1) In object-oriented programming languages like Java, objects represent individual and identifiable items or entities These items or entities can be real or conceptual They have a well-defined purpose and function in the problem domain In a computer-based system, an object may stand for itself Entities like files, network connections, windows, and menu items can be represented using objects Objects in computer-based systems may also represent realworld entities In a traffic simulation program, cars, streets, and intersections could all be represented using objects COMP Basics of Using Objects 8

9 Objects (2) The distinction between objects that represent themselves and those representing real-world entities is not always clear-cut Are bank accounts real-world entities or simply objects in a computer program? When an object represents a real-world entity, it is an abstraction of this entity Not everything about the real-world entity is represented by the object What is represented and what is not depends on the application or system, as well as the functionality we want them to have Objects have attributes and behavior COMP Basics of Using Objects 9

10 Object Examples Some things that could be represented by objects: Professor Cuthbert Calculus, scientist, living in Marlinspike Hall Uncle Scrooge's bank account at Duckburg bank A network connection to server on port 80 COMP Basics of Using Objects 10

11 Java Program Structure Revisited As we have seen before, in the Java programming language: A program consists of one or more classes All our programs so far have only consisted of one class we wrote ourselves, with some help from a few classes provided by the Java environment (Scanner, System, String, and PrintStream, in particular) COMP Basics of Using Objects 11

12 Classes: Categories of Objects A class can also define a category of objects It specifies what objects that belong to that category "look" like, and how they "behave" In a general way, all objects that belong to a given class "look" similar and "behave" in a similar manner We can also think of a class as a model or a blueprint which describes the general "appearance" and "behavior" of all objects that belong to this class, and from which we can create the objects that belong to this class COMP Basics of Using Objects 12

13 Objects: Attributes The "appearance" of the objects that belong to a class is determined by the attributes defined in that class The class defines attributes that all objects that belong to this class will have However, the value of each attribute can differ from one object to the next, even if both objects belong to the same class The appearance of an object (its attributes and their values) at a given point in time is sometimes called the state of this object COMP Basics of Using Objects 13

14 Objects: Behavior The behavior of the objects that belong to a class is specified by the methods defined in that class; we invoke one of these methods on an object when we want the latter to act in a certain way All objects that belong to a class have the general behaviors specified by the methods defined in that class However, the exact behavior of an object when a given method is invoked on it may depend on the state of the object COMP Basics of Using Objects 14

15 Objects: Instances of Classes An object is an instance of a class Thus, it is an entity which belongs to the category defined by a class, and which looks and behaves according to the definition of that class Each object belongs to one class When we create an object, we must specify the class to which it belongs The process of creating an object is sometimes called instantiation COMP Basics of Using Objects 15

16 Physical World Analogy (1) If one were to represent human being as classes and objects, then we could define a Human class This class could define attributes and behavior which every human being has For example, every human being has a name, a gender, a date of birth, a height, a weight, eye / hair / skin colors,... Therefore, all of these could be attributes defined in our Human class Also, every human being can walk, talk, eat, and sleep, so these could be the behaviors defined in our Human class, represented as methods COMP Basics of Using Objects 16

17 Physical World Analogy (2) Every human being would be an object that belongs to class Human, a separate instance of our Human class Although all of us have a name, a gender, a date of birth, and so on, these might vary from one person to the next Although everyone can walk, talk, and eat, some of us perform these tasks differently from others, depending on our attributes (for example, your height and weight may affect how fast you walk) Therefore: Both the object representing Jane Doe and the object representing Joe Bleau have a weight attribute However, the value of the weight attribute of the object representing Joe Bleau may not be the same as the weight attribute of the object representing Jane Doe COMP Basics of Using Objects 17

18 Physical World Analogy (3) Also: Both the object representing Joe Bleau and the object representing Jane Doe can walk They both have a walk behavior because they both belong to class Human, and the Human class defines that all objects that belong to it have a walk behavior However, Jane Doe might walk faster than Joe Bleau because she is lighter than him COMP Basics of Using Objects 18

19 Object Identity In addition to attributes and behaviors, objects also have identity Identity is the property that distinguishes an object from all others It is always possible to distinguish two objects, even if they have the same attributes Think of identical twins; even though they have the same DNA, they are different human beings An object's name or reference should not be confused with its identity COMP Basics of Using Objects 19

20 Side Note: Abstraction An abstraction hides (or ignores) details An object is abstract in that we don't really have to think about its internal details in order to use it Just like we don't really have to think about how the engines of our cars work in order to drive them We do not have to know how a method works in order to invoke it We need to know what it does and what it needs in order to do it, but not how it does it Therefore, we can write complex software without having to know how parts of it actually work We just have to know what they do when we use them COMP Basics of Using Objects 20

21 Libraries (1) Libraries are sets of pre-written, already-compiled code fragments that you can use in your program Libraries are like sets of lemmas in mathematics: We use lemmas to help us prove theorems; we can assume that the lemma is true without having to prove it Likewise, we use libraries to help us write programs; we can assume that the library does what its documentation tells us it will do without having to write code ourselves to do it Libraries are useful because you do not need to write code that does what the library does, someone else has done this for you COMP Basics of Using Objects 21

22 Libraries (2) Some libraries are included with the compiler you use; you can obtain other libraries from the Web Some libraries are free (as in "free speech", as in "free food", or both), others are not COMP Basics of Using Objects 22

23 Part 2: Creating and Using Objects

24 The Account Class Let us suppose that someone has already written an Account class that we can use in a program that manages bank accounts We will use this class to illustrate how to create and use objects Note that this Account class is not included with the Java environment; you have to download it separately in order to use it Also note that it looks and behaves the way it does because the person who wrote it chose to have it look and behave this way With the proper knowledge, you could write an Account class that looks and behaves differently; we will cover this later in the course COMP Basics of Using Objects 24

25 The Account Class: Attributes All objects that belong to the Account class have the following attributes: An account number, which uniquely identifies the account A balance, which keeps track of the amount of money stored in the account A status, which keeps track of whether the account is open or closed COMP Basics of Using Objects 25

26 The Account Class: Behaviors (1) This Account class also defines the following methods for all Account objects: Account(int number): A constructor, which creates a new Account object with the specified number, and a balance of $0 Account(int number, double initialamount): Another constructor, which creates a new Account object with the specified number, and immediately deposits initialamount into the Account int getnumber(): Retrieves the account number of an Account object double getbalance(): Retrieves the balance of an Account object boolean isopen(): Retrieves whether the Account object is open or not; returns true if the Account is open, false if it is not COMP Basics of Using Objects 26

27 The Account Class: Behaviors (2) boolean deposit(double amount): Deposits the specified amount into the Account, updating its balance; returns true if the withdrawal is successful, false if it fails boolean withdraw(double amount): Withdraws the specified amount from an Account object, updating its balance; returns true if the withdrawal is successful, false if it fails boolean close(): Closes an Account object, so that it is no longer possible to withdraw money from it or deposit money into it; returns true if the Account is successfully closed, false if it fails to close the Account boolean equals(object o): Compares an Account object to another object o for equality; an Account object is equal to this other object o if this other object also belongs to the Account class, and has the same number, balance, and status COMP Basics of Using Objects 27

28 The Account Class: Behaviors (3) String tostring(): Produces a textual representation of an Account object suitable for display using System.out.println() COMP Basics of Using Objects 28

29 The Account Class: Behaviors (4) The Account class also defines behaviors which affect all existing Account objects all at once rather than one individual Account object: static double getfee(): Retrieves the fee currently charged to an Account object when a withdrawal is performed; this fee is the same for all Account objects, and therefore can always be retrieved, regardless of whether any Account objects currently exist static void setfee(double newfee): Sets the fee charged to an Account objects when a withdrawal is performed to newfee; this fee is the same for all Account objects, and therefore can always be set, regardless of the number any Account objects currently exist COMP Basics of Using Objects 29

30 Reference Types We know that there are two broad kinds of types in Java: primitive types and reference types We have already covered primitive types Reference types are closely related to classes and objects Each class which defines a category of objects also defines a reference type We can declare variables whose types are reference types, just like we declare variables whose types are primitive types COMP Basics of Using Objects 30

31 Reference Variables (1) A class name can be used like a type in a variable declaration to declare a reference variable; that is, a variable whose type is a reference type Account scroogeaccount; The above statement is a variable declaration The name of the variable is scroogeaccount The type of the variable is Account However, this variable declaration does not create any object; it merely declares a variable that can keep track of an object in memory COMP Basics of Using Objects 31

32 Primitive vs. Reference Types (1) When declaring a variable, memory cells are allocated whether the type of the variable is a primitive type or a reference type What differs is the nature of what will be stored in those cells The declaration int number; creates a variable that holds a value of type int The int value is stored directly in the memory cells that are allocated when the variable number is declared COMP Basics of Using Objects 32

33 Primitive vs. Reference Types (2) On the other hand, the declaration Account scroogeaccount; creates a reference variable No object is created The object will not be stored in the memory cells that are allocated when the variable scroogeaccount is declared Instead, what will be stored in those cells is the reference to the object; the location, or address, in memory where the object is stored once it is created We have seen something like this before: Scanner keyboard; Initially, variables of both kinds do not contain any data COMP Basics of Using Objects 33

34 Creating Objects (1) Declaring a reference variable is a separate operation from creating the object whose address in memory will be stored in that reference variables We use the new operator to create an object: scroogeaccount = new Account(12345); Constructor invocation: same name as the class We have also seen something like this before: Inputs to constructor (if necessary) keyboard = new Scanner(System.in); COMP Basics of Using Objects 34

35 Creating Objects (2) The line scroogeaccount = new Account(12345); invokes an Account constructor A constructor is a special list of instructions that are executed when the new operator is used; its purpose is to initialize an object A class may define more than one constructor All constructors for a given class have the same name as that class They are distinguished by the number and types of inputs they accept The object will be contained in somewhere in memory, and the reference variable (scroogeaccount) will contain its location in memory (or its address) COMP Basics of Using Objects 35

36 Creating Objects (3) Constructors can be defined to take any number of inputs (also called parameters or arguments): one, many, or none at all However, it is the person who writes a class that decides how many parameters each constructor takes, and the types of these parameters Creating an object is called instantiation, because an object is an instance of a particular class COMP Basics of Using Objects 36

37 Reference Types: Initialization The assignment number = 42; writes the value 42 into the memory cells allocated to variable number On the other hand, when the assignment scroogeaccount = new Account(12345); is executed, the following happens: A new Account object is created; it uses some memory cells The variable scroogeaccount gets assigned the address of the memory cells that contain the Account object We say that the contents of the reference variable is a reference or a pointer to the real object COMP Basics of Using Objects 37

38 Primitive Types: Assignment Consider the following code fragment: int i1, i2 = 8; i1 = 6; i2 = i1; When the last line of the above fragment is executed, the contents of variable i1 is copied into i2 Because the type of these variables is a primitive type, the respective contents of these variables are their actual values Thus, the value of i1 is copied into i2 If the value of i2 is modified afterwards, the value of i1 stays the same COMP Basics of Using Objects 38

39 Primitive Types In Memory int i1, i2 = 8; // Line 1 i1 = 6; // Line 2 i2 = i1; // Line 3 Line 1: i1 i2 8 Line 2: i1 6 i2 8 Line 3: i1 6 i2 6 COMP Basics of Using Objects 39

40 Reference Types: Assignment Now, consider the following code fragment: Account a1, a2 = new Account(12345); a1 = new Account(67890); a1 = a2; When the last line of the above fragment is executed, the contents of variable a2 is copied into variable a1 However, because the type of these variables is a reference type, the respective contents of these variables are the addresses of objects in memory, not the objects themselves Thus, the address stored in a2 is copied into a1 There is still only one object involved here, but its address in memory is stored in two different variables COMP Basics of Using Objects 40

41 Reference Types In Memory Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 1: a /$0 a2 Line 2: a /$ /$0 a2 Line 3: a /$ /$0 a2 COMP Basics of Using Objects 41

42 Invoking Methods on Objects (1) When invoking a method on an object, we must specify a reference variable which contains the address in memory of the object on which we want to invoke the method This can be done using the. operator; the syntax is the following: variable.method(parameters) This does not apply when using the new operator Therefore, if we want to call the getnumber() method on the Account object that the reference variable a1 (of type Account) refers to, we write: a1.getnumber() COMP Basics of Using Objects 42

43 Invoking Methods on Objects (2) The object on which the method is called is often referred to as the target of the method call In the previous example, the target of the call to the getnumber() method is the Account object whose address is stored in variable a1 COMP Basics of Using Objects 43

44 The. Operator (1) Java uses the period as membership designation For example: scroogeaccount.deposit( ); The. operator In the above example, the. indicates that we want to invoke the deposit() method on the scroogeaccount object In general, the. operator is used to indicate that we want to access a member (either a behavior or an attribute) of an object or class COMP Basics of Using Objects 44

45 The. Operator (2) Consider the following code fragment: Account scroogeaccount = new Account(12345); Account donaldaccount = new Account(67890); To retrieve the account number from Account object scroogeaccount, we invoke the getnumber() method on it like this: scroogeaccount.getnumber(); To retrieve the account number from Account object donaldaccount, we invoke the getnumber() method on it like this: donaldaccount.getnumber(); This works only for objects, not primitive types COMP Basics of Using Objects 45

46 Invoking Methods in General (1) Many methods return values when invoked For example, when invoked on an Account object, the getnumber() method returns a value that has type int, the getbalance() method returns a value of type double,... These are called return values; the type of the value returned by a method is called its return type Return values can be assigned to a variable of an appropriate type Account scroogeaccount = new Account(12345); int number = scroogeaccount.getnumber(); // getnumber() returns an int // This int is assigned to int variable // number COMP Basics of Using Objects 46

47 Invoking Methods in General (2) Return values can also be used in expressions: Account scrooge1 = new Account(12345); Account scrooge2 = new Account(67890); double totalmoney = scrooge1.getbalance() + scrooge2.getbalance(); Many methods require parameters / arguments: The behavior of the method depends on the input values For example, the deposit() method needs one parameter: the amount of money to be deposited in the account A class may define multiple methods with the same name: each of the different versions of this method may take different numbers of parameters, and these parameters may be of different types COMP Basics of Using Objects 47

48 Invoking Methods in General (3) Any expression that can be used on the right side of an assignment statement can be passed as a parameter to a method, as long as the type of the expression is assignment-convertible to the parameter type the method expects When an expression is passed as a parameter to a method, the expression is evaluated first, and its value is passed to the method: int dollars = ; Account scroogeaccount = new Account(12345); scroogeaccount.deposit(3 * dollars); // OK! // scroogeaccount now contains $ COMP Basics of Using Objects 48

49 Invoking Methods in General (4) The person who writes a class decides: which methods will be defined in this class what each method will be called how many parameters each method will accept what the types of these parameters will be for each method the type of the value that each method will return The only methods we can invoke on an object are those defined in the class that the object belongs to If you try to invoke any other method on this object, the compiler will report an error COMP Basics of Using Objects 49

50 Aliases (1) When the address in memory of one object is stored in two or more different variables, we say that the variables are aliases We need to be careful when working with aliases Aliasing has side-effects that we need to be aware of Because the variables contain the address in memory of the same object, the result of invoking a method on the object using one of its aliases will be reflected through the other aliases In particular, if you invoke a method which changes the state of the object on one of the aliases, the other aliases will reflect the change COMP Basics of Using Objects 50

51 Aliases (2) To "de-alias" the variables, we simply need to store the address of a different object in one of them by using an assignment statement Note that aliasing is only a property of reference types; it is not a property of primitive types COMP Basics of Using Objects 51

52 Alias Example Consider the following code fragment: Account a1 = new Account(12345); Account a2 = a1; a1.deposit(100.0); double balance = a2.getbalance(); What will be the value of variable balance after the last line in the above fragment is executed? The answer is: (?!?) Because a1 and a2 are aliases for the same object, any change to the object via one of its aliases will be reflected through the other alias COMP Basics of Using Objects 52

53 Aliases in Memory (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 a1.deposit(100.0); // Line 3 double balance = a2.getbalance(); // Line 4 Line 1: a /$0 Line 2: a /$0 a2 COMP Basics of Using Objects 53

54 Aliases in Memory (2) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 a1.deposit(100.0); // Line 3 double balance = a2.getbalance(); // Line 4 Line 3: a /$100 a2 Line 4: a /$100 a2 balance COMP Basics of Using Objects 54

55 Comparing Objects Among the comparison operators, only == and!= are defined for reference types If you try to compare two reference variables using <, <=, >, or >=, the compiler will report an error Moreover, when used to compare reference variables, the == and!= operators check whether the two reference variables refer to the same object in memory In other words, for reference variables, the == and!= operators check whether the addresses stored in them are the same In yet other words, the == and!= operators check whether two reference variables are aliases for the same object But two different objects, stored at different addresses, can have the same state COMP Basics of Using Objects 55

56 Comparing Objects Using == (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 boolean b = (a1 == a2); // Line 3 Line 1: a /$0 Line 2: a /$0 a2 Line 3: a /$0 a2 b true COMP Basics of Using Objects 56

57 Comparing Objects Using == (2) Account a1 = new Account(12345); // Line 1 Account a2 = new Account(12345); // Line 2 boolean b = (a1 == a2); // Line 3 Line 1: a /$0 Line 2: a /$ /$0 a2 Line 3: a /$ /$0 a2 b false COMP Basics of Using Objects 57

58 The equals() Method (1) To determine whether two reference variables refer to (perhaps different) objects which have the same state, we use the equals() method The equals() method returns a value of type boolean which can be used in an expression or stored in a variable Account a1 = new Account(12345); Account a2 = new Account(12345); boolean b = (a1.equals(a2)); // b gets assigned true COMP Basics of Using Objects 58

59 The equals() Method (2) If the two reference variables refer to the same object in memory, the equals() method will return true as well This is because an object has the same state as itself The equals() method works for all reference variables (of any object type), but exactly what it does and what it compares depends on the classes of the objects Check the documentation for details Do not use the == and!= operators to compare objects that belong to any class unless you really want to check whether two reference variables are aliases for the same object This is one of the most common mistakes COMP Basics of Using Objects 59

60 Using the equals() Method (1) Account a1 = new Account(12345); // Line 1 Account a2 = a1; // Line 2 boolean b = (a1.equals(a2)); // Line 3 Line 1: a /$0 Line 2: a /$0 a2 Line 3: a /$0 a2 b true COMP Basics of Using Objects 60

61 Using the equals() Method (2) Account a1 = new Account(12345); // Line 1 Account a2 = new Account(12345); // Line 2 boolean b = (a1.equals(a2)); // Line 3 Line 1: a /$0 Line 2: a /$ /$0 a2 Line 3: a /$ /$0 a2 b true COMP Basics of Using Objects 61

62 Class / Static Methods In Java, most methods require an object in order to work That is, they require that an object be specified when they are invoked, and the method is invoked on that object For example, it makes no sense to try to invoke the deposit() method without specifying which Account object we want to deposit money into However, there are methods which do not work on an object, and thus do not require an object to be specified when they are invoked That is, we do not need to declare a reference variable and create an object before calling these methods These methods are called class methods or static methods COMP Basics of Using Objects 62

63 Invoking Class / Static Methods To invoke a class method, we use the following syntax: class.method(parameters); This syntax works only for class methods Therefore, if we want to retrieve the current withdrawal fee, we could do so by calling the getfee() method like this: Account.getFee(); The withdrawal fee exists regardless of the number of Account objects which exist at a given point in the program, and therefore can always be retrieved or changed We do not need to declare a reference variable of type Account and assign it the address of an Account object in order to invoke the getfee() method COMP Basics of Using Objects 63

64 Class / Static Constants In addition to class methods, some classes define class constants To use a class constant, we use the following syntax class.constant The Account class defines one constant, which represents the ID number of the bank in which Accounts are opened: BANK_ID_NUMBER Therefore, if we wish to use this constant in an expression, we would write Account.BANK_ID_NUMBER COMP Basics of Using Objects 64

65 The null Literal Value Sometimes, we want a reference variable to contain a special value to indicate that the variable intentionally does not contain the address in memory of a valid object The literal value null can be used for this purpose Like the boolean literals true and false, null is not technically a reserved word, but you cannot use it for any purpose other than as a literal value for reference variables A reference variable containing the value null is sometimes said to "point nowhere" In memory diagrams, null is often represented with a ground symbol COMP Basics of Using Objects 65

66 Using null One can assign null to a reference variable like one assigns an int literal like 42 to a variable of type int Account a1; a1 = null; One can check whether or not a reference variable contains the value null like one checks whether or not a variable of type int contains any value represented by an int literal like 42 if (a1 == null) { // do something } else { // do something else } COMP Basics of Using Objects 66

67 null-related Caveats The address stored in a reference variable is always either the address in memory of a valid object, or null In Java, you cannot store an arbitrary memory address in a reference variable, nor manipulate memory addresses directly If you attempt to call a method using a reference variable which contains null, your program will crash: Account a1 = null; a1.deposit(100.0); // a1 contains null: crash! When this occurs, the error message will mention that the program threw a NullPointerException The error message should also mention which line in your program caused the latter to crash COMP Basics of Using Objects 67

68 NullPointerDemo.java 1 public class NullPointerDemo { 2 public static void main(string[] args) { 3 Account a = null; 4 5 System.out.println("Attempting to retrieve the account " 6 + "number of a null Account..."); 7 System.out.println("The number of this account is: " + 8 a.getnumber()); 9 } 10 } What will happen if we run this program? COMP Basics of Using Objects 68

69 Reading Exception Output (1) The program's output: Attempting to retrieve the account number of a null Account... Exception in thread "main" java.lang.nullpointerexception ` at NullPointerDemo.main(NullPointerDemo.java:7) Method where the problem occurred File where the problem occurred Line number where the problem occurred Nature of the problem COMP Basics of Using Objects 69

70 Garbage Collection When there are no more reference variables containing the address of an object, the object can no longer be accessed by the program It is useless, and therefore called garbage Java performs automatic garbage collection periodically When garbage collection occurs, all the memory allocated to store garbage objects is made available so it be allocated to store new objects In other languages, the programmer has the responsibility for performing garbage collection Always ensure you do not lose the last reference to an object you still need COMP Basics of Using Objects 70

71 Garbage Collection in Memory (1) Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 1: a /$0 a2 Line 2: a /$ /$0 a2 COMP Basics of Using Objects 71

72 Garbage Collection in Memory (2) Account a1, a2 = new Account(12345); // Line 1 a1 = new Account(67890); // Line 2 a2 = a1; // Line 3 Line 3: a /$ /$0 a2 Garbage After Garbage Collection: a /$0 a2 COMP Basics of Using Objects 72

73 The tostring() Method (1) You can display the object whose address is stored in a reference variable just like you can display the value of a primitive variable The following code fragment will display the Account object whose address is stored in variable scroogeaccount: System.out.println("Scrooge's bank account: " + scroogeaccount); In the above line, the tostring() method is invoked automatically on the Account object whose address is stored in variable scroogeaccount The tostring() method produces a text representation of the target account COMP Basics of Using Objects 73

74 The tostring() Method (2) Like the equals() method, the tostring() method works for all reference variables (of any object type), but exactly what it does and what it displays depends on the class of the target object Check the documentation of each class for details COMP Basics of Using Objects 74

75 Documentation Most classes come with documentation which describes the constructors, methods, and class constants defined in the class COMP Basics of Using Objects 75

76 Reading Documentation (1) The class constants (which are fields, but not all fields are class constants), constructors, and methods are listed in separate sections Reading field descriptions: A field listed as static final is a class constant The type listed in the left column is the type of the constant Reading constructor and method descriptions: The left column specifies the method's return type (constructors do not have return values or return types) and modifiers If the method / constructor is listed as protected, you cannot call it; circumstances in which you could call it are beyond the scope of this course COMP Basics of Using Objects 76

77 Reading Documentation (2) If the method is listed as static, it is a class method (constructors cannot be static) If the return type of a method is listed as void, that means the method does not return values The right column lists the name of the method or constructor, as well as the parameters it accepts; for example: Account(int number, double initialamount) is a constructor that accepts as parameters a value of type int and one of type double (in that order) The parameter names are not important (for now); what matters is the types of the parameters, and their order The method description specifies what the method does, and what each parameter (as well as the return value) represents COMP Basics of Using Objects 77

78 Classes and Objects: Exercise (1) Familiarize yourself with the Bank and Account classes by reading the relevant documentation Write a program which consists of one class called BankManager. This class should define a main() method which does the following: Displays a menu to the screen with the following options: create an account, view an account, deposit, withdraw, close an account, change the withdrawal fee, and exit Reads the option chosen by the user COMP Basics of Using Objects 78

79 Classes and Objects: Exercise (2) Takes the appropriate action depending on the option chosen by the user; for example, if the user chooses the withdrawal option, it should prompt the user for an account number and an amount, read these values from the keyboard, and deposit the amount in the appropriate account Repeat the above steps as long as the user does not choose the exit option The program must display appropriate messages depending on the success or failure of the user's actions Use a Bank object to keep track of the various Account objects created by the user COMP Basics of Using Objects 79

80 Part 3: The String Class and String Objects

81 Strings vs. Characters (1) Characters are a single letter or symbol: char c1 = 'a'; char c2 = '%'; Strings are series of concatenated characters: String s = "Cuthbert Calculus"; Concatenation means that a block of one or more characters is appended to the end of another block of one or more characters: The concatenation of "a" and "b" is "ab"; likewise, the concatenation of "ab" and "cd" is "abcd" COMP Basics of Using Objects 81

82 Strings vs. Characters (2) char is a built-in, primitive type String is a reference type and a class defined in the class library that comes with the Java compiler and virtual machine Every character string is an object in Java "Hello", "world",... The behavior of character string objects is defined by the String class Every String literal, delimited by double quotation marks ("), is represented by a String object COMP Basics of Using Objects 82

83 Strings in Java (1) Because Strings are so common, the Java programming language provides us with some syntactic sugar that allows us to use Strings almost in the same way we use primitive types However, there are important differences between primitive data types and String objects Strings are objects, and therefore, they are stored in memory like all other objects That is, a variable of type String contains the address in memory where the String object is located, not the String object itself This implies that the = operator makes two String variables become aliases for the same String object It also implies that the == and!= operators check whether two String variables are aliases (or not) for the same String object COMP Basics of Using Objects 83

84 Strings in Java (2) You should always use the equals() method to see if two String objects are equal, unless you are really sure of what you are doing; not doing this is a common source of errors COMP Basics of Using Objects 84

85 String Concatenation The string concatenation operator (+) is used to append one String to the end of another "hello " + "world" results in a new String This new String will be "hello world" It can also be used to append the String representation of a number to any regular String: int count = 3; String title = "The " + count + " Little" + " Pigs"; System.out.println(title); // Displays "The 3 Little Pigs" COMP Basics of Using Objects 85

86 String Caveat A String literal cannot be broken across two lines of source code by inserting and end-of-line sequence in it If you really need to split a String literal across two lines in your program, break the original literal into two smaller String literals and combine them with the concatenation operator The following code fragment causes an error: "This is a very long literal that spans two lines" // Incorrect! However, the following code fragment is legal: "These are two shorter literals " + "that are on separate lines" // OK COMP Basics of Using Objects 86

87 Facts.java public class Facts { public static void main(string[] args) { String firstname = "Cuthbert"; String lastname = "Calculus"; String fullname; } } fullname = firstname + " " + lastname; System.out.println("His name is: " + fullname); System.out.println("Phone number: (" ") " "-" ); What is the output? COMP Basics of Using Objects 87

88 Concatenation and Mixing Types The plus operator (+) is also used for arithmetic addition The function that the + operator performs depends on the type of the information on which it operates Strings are considered to have higher precision than numeric types If both operands are of type String, or if one is of type String and the other is numeric, the + operator performs string concatenation (after "promoting" the numeric operand, if any, to type String) If both operands are numeric, it adds them The + operator is evaluated left to right Parentheses can be used to force the operation order COMP Basics of Using Objects 88

89 Addition.java public class Addition { public static void main(string[] args) { int x = 5; int y = 2; int sum = 0; String message = "The sum is "; } } sum = x + y; message = message + sum; System.out.println(message); What is the output? COMP Basics of Using Objects 89

90 Trick Question (1) What will be the output of the following code fragment? System.out.println("The sum of 5 and 3 is " ); The answer is: The sum of 5 and 3 is 53 (?!?) Explanation: The + operator is evaluated from left to right Thus, it is first applied to "The sum of 5 and 3 is " and the int literal 5 to form the String "The sum of 5 and 3 is 5" Then, we apply the + operator to the result from the previous concatenation operation and the int literal 3 to get "The sum of 5 and 3 is 53" COMP Basics of Using Objects 90

91 Trick Question (2) What will be the output of the following code fragment? System.out.println( " is the sum of " + "5 and 3"); The answer is: 8 is the sum of 5 and 3 (?!?) Explanation: Again, the + operator is evaluated from left to right Thus, it is first applied to the int literals 5 and 3; both of these have numeric type, so addition is performed and the sum is 8 Then, the + operator is applied to the result of the addition and the String literal " is the sum of "; the sum is converted from int to String and concatenated with the String literal COMP Basics of Using Objects 91

92 Trick Question (3) Finally, the String literal "5 and 3" is concatenated to the String "8 is the sum of " to form the String "8 is the sum of 5 and 3" Lesson: When in doubt, use parentheses COMP Basics of Using Objects 92

93 Escape Sequences What if we wanted to print a double quotation mark? The following line would confuse the compiler because it would interpret the second double quotation mark as the end of the String literal: System.out.println("I said "Hello" to you."); An escape sequence is a series of characters that represents a special character An escape sequence begins with a backslash character (\), which indicates that the character that follows should be treated in a special way: System.out.println("I said \"Hello\" to " + "you."); COMP Basics of Using Objects 93

94 Java Escape Sequences Some escape sequences in Java: Escape sequence Meaning \b \t \n \r \" \' \\ Backspace Tab New line (line feed) Carriage return Double quotation mark (String) Single quotation mark (char) Backslash COMP Basics of Using Objects 94

95 Poem.java public class Poem { public static void main(string[] args) { System.out.println("Roses are red,"); System.out.println("\t Violets are blue"); System.out.println("\t This poem " + "sucks\n\t I wish it were a haiku"); } } What does this display? COMP Basics of Using Objects 95

96 Haiku.java public class Haiku { public static void main(string[] args) { System.out.print("\t Windows Vista crashed."); System.out.print("\n\t I am the Blue Screen " + "of Death.\n"); System.out.println("\t No one hears your screams."); } } What does this display? COMP Basics of Using Objects 96

97 Creating String Objects Because String objects are so common, we do not have to use the new operator to create one; we can simply assign a String literal to a String variable String name; name = "Cuthbert Calculus"; This is special syntax that works only for String objects COMP Basics of Using Objects 97

98 String Methods (1) The String class defines several methods which you may use to manipulate String objects. Here are some of them: String(String original): (Constructor) Initializes a newly created String object so that it represents the same sequence of characters as the argument; in other words, the newly created String is a copy of the argument String. char charat(int index): Returns the char value at the specified index. int compareto(string anotherstring): Compares two strings lexicographically. boolean equals(object anobject): Compares this String to the specified object. COMP Basics of Using Objects 98

99 String Methods (2) boolean equalsignorecase(string anotherstring): Compares this String to another String, ignoring case considerations. int length(): Returns the length of this String. String replace (char oldchar, char newchar): Returns a new String resulting from replacing all occurrences of oldchar in this String with newchar. String substring(int beginindex, int endindex): Returns a new String that is a substring of this String. String tolowercase(): Converts all of the characters in this String to lower case using the rules of the default locale. String touppercase(): Converts all of the characters in this String to upper case using the rules of the default locale. COMP Basics of Using Objects 99

100 Immutability String objects are immutable This means that once a String object is created, its state cannot change None of the String methods can change the state of a String object, nor can any other method defined in any other class This has to do with the way the String class is implemented Methods that seem to change a String object in fact create a new String object from the original target String However, you can always change the reference stored in a String variable to make it refer to a different String object (unless the variable is final) Note that objects belonging to other classes can be immutable as well COMP Basics of Using Objects 100

101 String Indexing (1) The i th character in a String has index i - 1 In other words: If you want to recover the first character of String variable s, you must use s.charat(0), not s.charat(1) More generally, if you want to recover the i th character of String variable s, you must use s.charat(i-1), not s.charat(i) Consequently, the last character of a String variable s has index s.length() 1 Example: String s1 = "Hello world!" char c = s1.charat(4); // c contains the character 'o', not 'l' COMP Basics of Using Objects 101

102 String Indexing (2) If you attempting to access the character in a String located at an invalid index (either negative, or greater than or equal to the number of characters in the String), your program will crash: String s = "hello"; char c = s.charat(5); // String s contains 5 characters, so // the valid indices for s are 0-4 // inclusive: crash! When this occurs, the error message will mention that the program threw a StringIndexOutOfBoundsException The error message should also mention which line in your program caused the latter to crash COMP Basics of Using Objects 102

103 IndexOutOfBoundsDemo.java 1 public class IndexOutOfBoundsDemo { 2 public static void main(string[] args) { 3 String s; 4 5 s = "hello"; 6 7 System.out.println("Attempting to retrieve the " + 8 "character at position " + s.length() + " of String " + 9 s); 10 System.out.println("The character at position " + 11 s.length() + " of String " + s + ": " + 12 s.charat(s.length())); 13 } 14 } COMP Basics of Using Objects 103

104 Reading Exception Output (2) The program's output: Attempting to retrieve the character at position 5 of String hello Exception in thread "main" java.lang. StringIndexOutOfBoundsException: String index out of range: 5 at java.lang.string.charat(string.java:687) at IndexOutOfBoundsDemo.main(IndexOutOfBoundsDemo.java:9) More details on the problem Index we tried to access and caused the crash COMP Basics of Using Objects 104

105 ObfuscatedHaiku.java public class ObfuscatedHaiku { public static void main(string args[]) { String s1 = new String("\t Windows Vista crashed."); String s2 = "\t Windows Vista crashed."; String today = "\t Caturday \t"; boolean answer; answer = s1.equals(s2) && s1!= s2; today = today.substring(2, 10); today = today.replace('c', 'S'); if (answer && today.equals("saturday") ) { System.out.println(s1 + "\n\t I am the" + " Blue Screen of Death."); System.out.println("\t No one hears your screams."); } } } What is the value of answer? What is today? Will we see a haiku? COMP Basics of Using Objects 105

106 Part 4: The Java Standard Library

107 Class Libraries A class library is a collection of classes that we can use when developing programs There is a Java standard class library that is part of any Java development environment These classes are not part of the Java language per se, but we rely on them heavily The System class, the Scanner class, and the String class are part of the Java standard class library Other class libraries can be obtained through third party vendors, or you can create them yourself COMP Basics of Using Objects 107

108 Packages The classes of the Java standard class library are organized into packages Some of the packages in the Java standard class library are: Package java.lang java.util java.io java.awt javax.swing Purpose General support (contains String and System) Utilities Input and output facilities Graphical user interfaces (old style) Graphical user interfaces (new style) java.net Networking COMP Basics of Using Objects 108

109 The import Declaration When you want to use a class from a package, you could use its fully qualified name: java.util.scanner keyboard = new java.util.scanner(system.in); Or you can import the class, then just use the class name: import java.util.scanner; // Class and method declarations... Scanner keyboard = new Scanner(System.in); To import all classes in a particular package, you can use the * wildcard character: import java.util.*; An import declaration must always be placed before the class declaration COMP Basics of Using Objects 109

COMP-202 Unit 8: Basics of Using Objects

COMP-202 Unit 8: Basics of Using Objects COMP-202 Unit 8: Basics of Using Objects CONTENTS: Concepts: Classes and Objects Creating and Using Objects Introduction to Basic Java Classes (String, Scanner, ArrayList,...) Introduction (1) As we know,

More information

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string

COMP 202. Built in Libraries and objects. CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Built in Libraries and objects CONTENTS: Introduction to objects Introduction to some basic Java libraries string COMP 202 Objects and Built in Libraries 1 Classes and Objects An object is an

More information

A variable is a name for a location in memory A variable must be declared

A variable is a name for a location in memory A variable must be declared Variables A variable is a name for a location in memory A variable must be declared, specifying the variable's name and the type of information that will be held in it data type variable name int total;

More information

We now start exploring some key elements of the Java programming language and ways of performing I/O

We now start exploring some key elements of the Java programming language and ways of performing I/O We now start exploring some key elements of the Java programming language and ways of performing I/O This week we focus on: Introduction to objects The String class String concatenation Creating objects

More information

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays

CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types. COMP-202 Unit 6: Arrays CONTENTS: Array Usage Multi-Dimensional Arrays Reference Types COMP-202 Unit 6: Arrays Introduction (1) Suppose you want to write a program that asks the user to enter the numeric final grades of 350 COMP-202

More information

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation

COMP-202 Unit 8: Defining Your Own Classes. CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation COMP-202 Unit 8: Defining Your Own Classes CONTENTS: Class Definitions Attributes Methods and Constructors Access Modifiers and Encapsulation Defining Our Own Classes (1) So far, we have been creating

More information

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it

Last Class. Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it Last Class Introduction to arrays Array indices Initializer lists Making an array when you don't know how many values are in it public class February4{ public static void main(string[] args) { String[]

More information

Classes and Objects Part 1

Classes and Objects Part 1 COMP-202 Classes and Objects Part 1 Lecture Outline Object Identity, State, Behaviour Class Libraries Import Statement, Packages Object Interface and Implementation Object Life Cycle Creation, Destruction

More information

Packages & Random and Math Classes

Packages & Random and Math Classes Packages & Random and Math Classes Quick review of last lecture September 6, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev Objects Classes An object

More information

Example: Computing prime numbers

Example: Computing prime numbers Example: Computing prime numbers -Write a program that lists all of the prime numbers from 1 to 10,000. Remember a prime number is a # that is divisible only by 1 and itself Suggestion: It probably will

More information

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods COMP-202 Unit 2: Java Basics CONTENTS: Using Expressions and Variables Types Strings Methods Assignment 1 Assignment 1 posted on WebCt and course website. It is due May 18th st at 23:30 Worth 6% Part programming,

More information

Using Java Classes Fall 2018 Margaret Reid-Miller

Using Java Classes Fall 2018 Margaret Reid-Miller Using Java Classes 15-121 Fall 2018 Margaret Reid-Miller Today Strings I/O (using Scanner) Loops, Conditionals, Scope Math Class (random) Fall 2018 15-121 (Reid-Miller) 2 The Math Class The Math class

More information

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions

COMP-202 Unit 2: Programming Basics. CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions COMP-202 Unit 2: Programming Basics CONTENTS: The Java Programming Language Variables and Types Basic Input / Output Expressions Conversions Part 1: The Java Programming Language The Java Programming Language

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI

CSCI 2010 Principles of Computer Science. Data and Expressions 08/09/2013 CSCI CSCI 2010 Principles of Computer Science Data and Expressions 08/09/2013 CSCI 2010 1 Data Types, Variables and Expressions in Java We look at the primitive data types, strings and expressions that are

More information

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Review Chapters 1 to 4. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Review Chapters 1 to 4 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor:

More information

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on:

Data and Expressions. Outline. Data and Expressions 12/18/2010. Let's explore some other fundamental programming concepts. Chapter 2 focuses on: Data and Expressions Data and Expressions Let's explore some other fundamental programming concepts Chapter 2 focuses on: Character Strings Primitive Data The Declaration And Use Of Variables Expressions

More information

COMP 202 Java in one week

COMP 202 Java in one week CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator COMP 202 Java in one week The Java Programming Language A programming language

More information

2 rd class Department of Programming. OOP with Java Programming

2 rd class Department of Programming. OOP with Java Programming 1. Structured Programming and Object-Oriented Programming During the 1970s and into the 80s, the primary software engineering methodology was structured programming. The structured programming approach

More information

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals

CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals CSE 1223: Introduction to Computer Programming in Java Chapter 2 Java Fundamentals 1 Recall From Last Time: Java Program import java.util.scanner; public class EggBasketEnhanced { public static void main(string[]

More information

Creating and Using Objects

Creating and Using Objects Creating and Using Objects 1 Fill in the blanks Object behaviour is described by, and object state is described by. Fill in the blanks Object behaviour is described by methods, and object state is described

More information

COMP 202. Java in one week

COMP 202. Java in one week COMP 202 CONTENTS: Basics of Programming Variables and Assignment Data Types: int, float, (string) Example: Implementing a calculator Java in one week The Java Programming Language A programming language

More information

First Java Program - Output to the Screen

First Java Program - Output to the Screen First Java Program - Output to the Screen These notes are written assuming that the reader has never programmed in Java, but has programmed in another language in the past. In any language, one of the

More information

Objects and Classes -- Introduction

Objects and Classes -- Introduction Objects and Classes -- Introduction Now that some low-level programming concepts have been established, we can examine objects in more detail Chapter 4 focuses on: the concept of objects the use of classes

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University April 21, 2015 Chapter 2: Data and Expressions CS 121 1 / 53 Chapter 2 Part 1: Data Types

More information

"Hello" " This " + "is String " + "concatenation"

Hello  This  + is String  + concatenation Strings About Strings Strings are objects, but there is a special syntax for writing String literals: "Hello" Strings, unlike most other objects, have a defined operation (as opposed to a method): " This

More information

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2

CONTENTS: Compilation Data and Expressions COMP 202. More on Chapter 2 CONTENTS: Compilation Data and Expressions COMP 202 More on Chapter 2 Programming Language Levels There are many programming language levels: machine language assembly language high-level language Java,

More information

St. Edmund Preparatory High School Brooklyn, NY

St. Edmund Preparatory High School Brooklyn, NY AP Computer Science Mr. A. Pinnavaia Summer Assignment St. Edmund Preparatory High School Name: I know it has been about 7 months since you last thought about programming. It s ok. I wouldn t want to think

More information

Chapter 2: Data and Expressions

Chapter 2: Data and Expressions Chapter 2: Data and Expressions CS 121 Department of Computer Science College of Engineering Boise State University January 15, 2015 Chapter 2: Data and Expressions CS 121 1 / 1 Chapter 2 Part 1: Data

More information

Chapter. Let's explore some other fundamental programming concepts

Chapter. Let's explore some other fundamental programming concepts Data and Expressions 2 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Data and Expressions Let's explore some

More information

Defining Classes and Methods

Defining Classes and Methods Defining Classes and Methods Chapter 4 Chapter 4 1 Basic Terminology Objects can represent almost anything. A class defines a kind of object. It specifies the kinds of data an object of the class can have.

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu (Using the Scanner and String Classes) Anatomy of a Java Program Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual jump

More information

Primitive vs Reference

Primitive vs Reference Primitive vs Reference Primitive types store values Reference types store addresses This is the fundamental difference between the 2 Why is that important? Because a reference type stores an address, you

More information

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2

Java Foundations: Introduction to Program Design & Data Structures, 4e John Lewis, Peter DePasquale, Joseph Chase Test Bank: Chapter 2 Java Foundations Introduction to Program Design and Data Structures 4th Edition Lewis TEST BANK Full download at : https://testbankreal.com/download/java-foundations-introduction-toprogram-design-and-data-structures-4th-edition-lewis-test-bank/

More information

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input Lecture 5, Thu Jan 19 2006 based on slides by Kurt Eiselt http://www.cs.ubc.ca/~tmm/courses/cpsc111-06-spr

More information

STUDENT LESSON A10 The String Class

STUDENT LESSON A10 The String Class STUDENT LESSON A10 The String Class Java Curriculum for AP Computer Science, Student Lesson A10 1 STUDENT LESSON A10 The String Class INTRODUCTION: Strings are needed in many programming tasks. Much of

More information

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

Strings. Strings and their methods. Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics Strings Strings and their methods Produced by: Dr. Siobhán Drohan Department of Computing and Mathematics http://www.wit.ie/ Topics list Primitive Types: char Object Types: String Primitive vs Object Types

More information

COMP 202 Java in one week

COMP 202 Java in one week COMP 202 Java in one week... Continued CONTENTS: Return to material from previous lecture At-home programming exercises Please Do Ask Questions It's perfectly normal not to understand everything Most of

More information

CMPT 125: Lecture 3 Data and Expressions

CMPT 125: Lecture 3 Data and Expressions CMPT 125: Lecture 3 Data and Expressions Tamara Smyth, tamaras@cs.sfu.ca School of Computing Science, Simon Fraser University January 3, 2009 1 Character Strings A character string is an object in Java,

More information

Lecture Notes for CS 150 Fall 2009; Version 0.5

Lecture Notes for CS 150 Fall 2009; Version 0.5 for CS 150 Fall 2009; Version 0.5 Draft! Do not distribute without prior permission. Copyright 2001-2009 by Mark Holliday Comments, corrections, and other feedback appreciated holliday@email.wcu.edu Chapter

More information

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process

Entry Point of Execution: the main Method. Elementary Programming. Learning Outcomes. Development Process Entry Point of Execution: the main Method Elementary Programming EECS1021: Object Oriented Programming: from Sensors to Actuators Winter 2019 CHEN-WEI WANG For now, all your programming exercises will

More information

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods

Learning objectives: Objects and Primitive Data. Introduction to Objects. A Predefined Object. The print versus the println Methods CSI1102 Introduction to Software Design Chapter 2: Objects and Primitive Data Learning objectives: Objects and Primitive Data Introducing objects and their properties Predefined objects: System.out Variables

More information

Computer Science is...

Computer Science is... Computer Science is... Bioinformatics Computer scientists develop algorithms and statistical techniques to interpret huge amounts of biological data. Example: mapping the human genome. Right: 3D model

More information

CS 152: Data Structures with Java Hello World with the IntelliJ IDE

CS 152: Data Structures with Java Hello World with the IntelliJ IDE CS 152: Data Structures with Java Hello World with the IntelliJ IDE Instructor: Joel Castellanos e-mail: joel.unm.edu Web: http://cs.unm.edu/~joel/ Office: Electrical and Computer Engineering building

More information

Objectives of CS 230. Java portability. Why ADTs? 8/18/14

Objectives of CS 230. Java portability. Why ADTs?  8/18/14 http://cs.wellesley.edu/~cs230 Objectives of CS 230 Teach main ideas of programming Data abstraction Modularity Performance analysis Basic abstract data types (ADTs) Make you a more competent programmer

More information

Last Class. More on loops break continue A bit on arrays

Last Class. More on loops break continue A bit on arrays Last Class More on loops break continue A bit on arrays public class February2{ public static void main(string[] args) { String[] allsubjects = { ReviewArray, Example + arrays, obo errors, 2darrays };

More information

Computer Science is...

Computer Science is... Computer Science is... Machine Learning Machine learning is the study of computer algorithms that improve automatically through experience. Example: develop adaptive strategies for the control of epileptic

More information

AP Computer Science A

AP Computer Science A AP Computer Science A 1st Quarter Notes Table of Contents - section links Click on the date or topic below to jump to that section Date : 9/8/2017 Aim : Java Basics Objects and Classes Data types: Primitive

More information

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method

Appendix 3. Description: Syntax: Parameters: Return Value: Example: Java - String charat() Method Appendix 3 Java - String charat() Method This method returns the character located at the String's specified index. The string indexes start from zero. public char charat(int index) index -- Index of the

More information

Table of Contents Date(s) Title/Topic Page #s. Abstraction

Table of Contents Date(s) Title/Topic Page #s. Abstraction Table of Contents Date(s) Title/Topic Page #s 9/10 2.2 String Literals, 2.3 Variables and Assignment 34-35 Abstraction An abstraction hides (or suppresses) the right details at the right time An object

More information

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing

Java Programming. MSc Induction Tutorials Stefan Stafrace PhD Student Department of Computing Java Programming MSc Induction Tutorials 2011 Stefan Stafrace PhD Student Department of Computing s.stafrace@surrey.ac.uk 1 Tutorial Objectives This is an example based tutorial for students who want to

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time

Tester vs. Controller. Elementary Programming. Learning Outcomes. Compile Time vs. Run Time Tester vs. Controller Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG For effective illustrations, code examples will mostly be written in the form of a tester

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Final Examination Thursday, December 11, 2008 Examiners: Mathieu Petitpas [Section 1] 14:00

More information

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java Lecture Set 2: Starting Java 1. Java Concepts 2. Java Programming Basics 3. User output 4. Variables and types 5. Expressions 6. User input 7. Uninitialized Variables 0 This Course: Intro to Procedural

More information

2: Basics of Java Programming

2: Basics of Java Programming 2: Basics of Java Programming CSC 1051 Algorithms and Data Structures I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/

More information

Elementary Programming

Elementary Programming Elementary Programming EECS1022: Programming for Mobile Computing Winter 2018 CHEN-WEI WANG Learning Outcomes Learn ingredients of elementary programming: data types [numbers, characters, strings] literal

More information

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008)

Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008) Chapter 29: String and Object References Bradley Kjell (Revised 06/15/2008) In previous chapters, methods were called with parameters that were primitive data types. This chapter discusses how to use object

More information

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops

CONTENTS: While loops Class (static) variables and constants Top Down Programming For loops Nested Loops COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

COMP-202 More Complex OOP

COMP-202 More Complex OOP COMP-202 More Complex OOP Defining your own types: Remember that we can define our own types/classes. These classes are objects and have attributes and behaviors You create an object or an instance of

More information

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

Assoc. Prof. Dr. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved. Assoc. Prof. Dr. Marenglen Biba Laboratory Session: Exercises on classes Analogy to help you understand classes and their contents. Suppose you want to drive a car and make it go faster by pressing down

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Walter Savitch Frank M. Carrano Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers

More information

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics COMP-202 Unit 1: Introduction Announcements Did you miss the first lecture? Come talk to me after class. If you want

More information

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination

Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Midterm Examination Tuesday, November 3, 2009 Examiners: Mathieu Petitpas

More information

Midterms Save the Dates!

Midterms Save the Dates! University of British Columbia CPSC 111, Intro to Computation Alan J. Hu Errors (Using the Scanner and String Classes) Anatomy of a Java Program Readings This Week s Reading: Ch 3.1-3.8 (Major conceptual

More information

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading

COMP 202. More on OO. CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading COMP 202 CONTENTS: static revisited this reference class dependencies method parameters variable scope method overloading More on OO COMP 202 Objects 3 1 Static member variables So far: Member variables

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects Outline Problem: How do I create multiple objects from a class Java provides a number of built-in classes for us Understanding

More information

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java ECE 122 Engineering Problem Solving with Java Lecture 4 Creating and Using Objects Outline Problem: How do I create multiple objects from a class Java provides a number of built-in classes for us Understanding

More information

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan

COSC 123 Computer Creativity. Introduction to Java. Dr. Ramon Lawrence University of British Columbia Okanagan COSC 123 Computer Creativity Introduction to Java Dr. Ramon Lawrence University of British Columbia Okanagan ramon.lawrence@ubc.ca Key Points 1) Introduce Java, a general-purpose programming language,

More information

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 3

Object oriented programming. Instructor: Masoud Asghari Web page:   Ch: 3 Object oriented programming Instructor: Masoud Asghari Web page: http://www.masses.ir/lectures/oops2017sut Ch: 3 1 In this slide We follow: https://docs.oracle.com/javase/tutorial/index.html Trail: Learning

More information

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements

COMP-202 Unit 4: Programming With Iterations. CONTENTS: The while and for statements COMP-202 Unit 4: Programming With Iterations CONTENTS: The while and for statements Introduction (1) Suppose we want to write a program to be used in cash registers in stores to compute the amount of money

More information

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Expressions and Data Types CSC 121 Spring 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types

More information

BM214E Object Oriented Programming Lecture 8

BM214E Object Oriented Programming Lecture 8 BM214E Object Oriented Programming Lecture 8 Instance vs. Class Declarations Instance vs. Class Declarations Don t be fooled. Just because a variable might be declared as a field within a class that does

More information

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper

ICSE Class 10 Computer Applications ( Java ) 2014 Solved Question Paper 1 of 10 05-11-015 16:1 ICSE J Java for Class X Computer Applications ICSE Class 10 Computer Applications ( Java ) 014 Solved Question Paper ICSE Question Paper 014 (Solved) Computer Applications Class

More information

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections

Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections Introduction to Java Chapters 1 and 2 The Java Language Section 1.1 Data & Expressions Sections 2.1 2.5 Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Introduce the Java programming

More information

Programming with Java

Programming with Java Programming with Java Data Types & Input Statement Lecture 04 First stage Software Engineering Dep. Saman M. Omer 2017-2018 Objectives q By the end of this lecture you should be able to : ü Know rules

More information

JAVA: A Primer. By: Amrita Rajagopal

JAVA: A Primer. By: Amrita Rajagopal JAVA: A Primer By: Amrita Rajagopal 1 Some facts about JAVA JAVA is an Object Oriented Programming language (OOP) Everything in Java is an object application-- a Java program that executes independently

More information

Last Class. While loops Infinite loops Loop counters Iterations

Last Class. While loops Infinite loops Loop counters Iterations Last Class While loops Infinite loops Loop counters Iterations public class January31{ public static void main(string[] args) { while (true) { forloops(); if (checkclassunderstands() ) { break; } teacharrays();

More information

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics

Wentworth Institute of Technology. Engineering & Technology WIT COMP1000. Java Basics WIT COMP1000 Java Basics Java Origins Java was developed by James Gosling at Sun Microsystems in the early 1990s It was derived largely from the C++ programming language with several enhancements Java

More information

! definite loop: A loop that executes a known number of times. " The for loops we have seen so far are definite loops. ! We often use language like

! definite loop: A loop that executes a known number of times.  The for loops we have seen so far are definite loops. ! We often use language like Indefinite loops while loop! indefinite loop: A loop where it is not obvious in advance how many times it will execute.! We often use language like " "Keep looping as long as or while this condition is

More information

CS112 Lecture: Primitive Types, Operators, Strings

CS112 Lecture: Primitive Types, Operators, Strings CS112 Lecture: Primitive Types, Operators, Strings Last revised 1/24/06 Objectives: 1. To explain the fundamental distinction between primitive types and reference types, and to introduce the Java primitive

More information

Basic Computation. Chapter 2

Basic Computation. Chapter 2 Basic Computation Chapter 2 Outline Variables and Expressions The Class String Keyboard and Screen I/O Documentation and Style Variables Variables store data such as numbers and letters. Think of them

More information

Notes from the Boards Set BN19 Page

Notes from the Boards Set BN19 Page 1 The Class, String There are five programs in the class code folder Set17. The first one, String1 is discussed below. The folder StringInput shows simple string input from the keyboard. Processing is

More information

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while

boolean, char, class, const, double, else, final, float, for, if, import, int, long, new, public, return, static, throws, void, while CSCI 150 Fall 2007 Java Syntax The following notes are meant to be a quick cheat sheet for Java. It is not meant to be a means on its own to learn Java or this course. For that you should look at your

More information

Math Modeling in Java: An S-I Compartment Model

Math Modeling in Java: An S-I Compartment Model 1 Math Modeling in Java: An S-I Compartment Model Basic Concepts What is a compartment model? A compartment model is one in which a population is modeled by treating its members as if they are separated

More information

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. !

! Rest of Chap 2 ! 2.3-4, ! Rest of Chap 4 ! ! Things that do not vary. ! unlike variables. ! will never change. ! University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner Objects, Methods, Parameters, Input! Rest of Chap 2! 2.3-4, 2.6-2.10! Rest of Chap 4! 4.3-4.7 Reading This Week

More information

STUDENT LESSON A5 Designing and Using Classes

STUDENT LESSON A5 Designing and Using Classes STUDENT LESSON A5 Designing and Using Classes 1 STUDENT LESSON A5 Designing and Using Classes INTRODUCTION: This lesson discusses how to design your own classes. This can be the most challenging part of

More information

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness.

CS-140 Fall Binghamton University. Methods. Sect. 3.3, 8.2. There s a method in my madness. Methods There s a method in my madness. Sect. 3.3, 8.2 1 Example Class: Car How Cars are Described Make Model Year Color Owner Location Mileage Actions that can be applied to cars Create a new car Transfer

More information

CS 231 Data Structures and Algorithms, Fall 2016

CS 231 Data Structures and Algorithms, Fall 2016 CS 231 Data Structures and Algorithms, Fall 2016 Dr. Bruce A. Maxwell Department of Computer Science Colby College Course Description Focuses on the common structures used to store data and the standard

More information

Pace University. Fundamental Concepts of CS121 1

Pace University. Fundamental Concepts of CS121 1 Pace University Fundamental Concepts of CS121 1 Dr. Lixin Tao http://csis.pace.edu/~lixin Computer Science Department Pace University October 12, 2005 This document complements my tutorial Introduction

More information

6.001 Notes: Section 8.1

6.001 Notes: Section 8.1 6.001 Notes: Section 8.1 Slide 8.1.1 In this lecture we are going to introduce a new data type, specifically to deal with symbols. This may sound a bit odd, but if you step back, you may realize that everything

More information

COMP-202 Unit 4: Programming with Iterations

COMP-202 Unit 4: Programming with Iterations COMP-202 Unit 4: Programming with Iterations Doing the same thing again and again and again and again and again and again and again and again and again... CONTENTS: While loops Class (static) variables

More information

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes

Entry Point of Execution: the main Method. Elementary Programming. Compile Time vs. Run Time. Learning Outcomes Entry Point of Execution: the main Method Elementary Programming EECS2030: Advanced Object Oriented Programming Fall 2017 CHEN-WEI WANG For now, all your programming exercises will be defined within the

More information

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved.

Chapter 5: Arrays. Chapter 5. Arrays. Java Programming FROM THE BEGINNING. Copyright 2000 W. W. Norton & Company. All rights reserved. Chapter 5 Arrays 1 5.1 Creating and Using Arrays A collection of data items stored under a single name is known as a data structure. An object is one kind of data structure, because it can store multiple

More information

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination

Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2013) - All Sections Midterm Examination November 11th, 2013 Examiners: Jonathan Tremblay [Sections

More information

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA

TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA 1 TOPIC 2 INTRODUCTION TO JAVA AND DR JAVA Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson, and instructor materials prepared

More information

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a Spring 2017 Name: TUID: Page Points Score 1 28 2 18 3 12 4 12 5 15 6 15 Total: 100 Instructions The exam is closed book, closed notes. You may not use a calculator, cell phone, etc. i Some API Reminders

More information

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6

Using Classes and Objects Chapters 3 Creating Objects Section 3.1 The String Class Section 3.2 The Scanner Class Section 2.6 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 CMPT 125/125 SFU Burnaby, Fall 2013 2 Scope Creating

More information

CHAPTER 7 OBJECTS AND CLASSES

CHAPTER 7 OBJECTS AND CLASSES CHAPTER 7 OBJECTS AND CLASSES OBJECTIVES After completing Objects and Classes, you will be able to: Explain the use of classes in Java for representing structured data. Distinguish between objects and

More information

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal

Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Expressions and Data Types CSC 121 Fall 2015 Howard Rosenthal Lesson Goals Understand the basic constructs of a Java Program Understand how to use basic identifiers Understand simple Java data types and

More information