COMP-202 Unit 8: Basics of Using Objects
|
|
- Evan Briggs
- 6 years ago
- Views:
Transcription
1 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,...)
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 We know that a class can be a collection of related methods; such a class is sometimes called a method library The Math class from the Java Standard Class Library is perhaps the best example of a class which has such a role We know that a class can define a record type A class which has this role specifies a number of fields We can then declare variables whose type is a class which has this role, allocate records of this type, and store their addresses in memory in these variables 2
3 Introduction (2) Each of these records has all the fields specified by the class Objects are an extension of records Classes which define a record type can specify behaviors in addition to fields These behaviors are implemented by declaring methods in the class which defines the record type Alternatively, we can think of records as degenerate objects Full-fledged objects have attributes (implemented using fields) and behaviors, while records only have attributes 3
4 Introduction (3) In the programs that we have written, we have created objects When we write Scanner keyboard = new Scanner(System.in); we create a new object which belongs to class Scanner We have also requested that these objects perform certain behaviors; we do this by invoking a method on the object nextint() is a method; when we write keyboard.nextint() in a statement, we invoke the nextint() method on the Scanner object whose address in memory is stored in variable keyboard println() is also a method; when we write System.out.println(), we invoke the println() method on the PrintStream object whose address in memory is stored in variable System.out 4
5 Object-Oriented Programming (1) The idea behind object-oriented programming is to organize our programs as a series of objects which interact with each other by requesting that they perform certain behaviors This enables us to write code which is more maintainable than if we deal only with the methods and records we have seen so far For now, we will learn How to create and use objects which belong to classes that other people have written How to call methods on these objects Later, we will learn How to extend our own record types to turn them into full-fledged object types 5
6 Part 1: Basics of Classes, Objects, and Methods
7 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 7
8 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 So far, what we have seen as records were really degenerate objects which only had attributes, and no behaviors 8
9 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 9
10 Classes: Categories of Objects Objects can be divided in categories Each such category is represented by a class The class 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 This is an extension of the idea that a class can define a type of record 10
11 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 11
12 Objects: Behavior The behavior of the objects that belong to a class is specified by the methods declared 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 12
13 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 13
14 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 14
15 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 15
16 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 Finally: No human being can fly, so the Human class does not define a fly behavior Therefore, trying to request that a Human object fly would not work 16
17 Physical World Analogy (4) On the other hand, you can still request that an object that belongs to a class which does define a fly behavior (like an object belonging to class Bird or Bat) to fly 17
18 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 18
19 Objects and Abstraction We know that 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 We do not need to know how the object keeps track of its attributes internally, nor which statements are in the methods implementing its behaviors This is just like we don't really have to think about how the engines of our cars work in order to drive them Again, this enables us to 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 19
20 Part 2: Creating and Using Objects
21 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 21
22 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 22
23 The Account Class: Behaviors (1) This Account class also defines the following methods for all Account objects: public Account(int number): A constructor, which creates a new Account object with the specified number, and a balance of $0 public Account(int number, double initialamount): Another constructor, which creates a new Account object with the specified number, and immediately deposits initialamount into the Account public int getnumber(): Retrieves the account number of an Account object public double getbalance(): Retrieves the balance of an Account object 23
24 The Account Class: Behaviors (2) public boolean isopen(): Retrieves whether the Account object is open or not; returns true if the Account is open, false if it is not public 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 public 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 public 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 24
25 The Account Class: Behaviors (3) public 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 public String tostring(): Produces a textual representation of an Account object suitable for display using System.out.println() 25
26 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: public 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 public 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 26
27 Object Variables We know that a class name can be used like a type in a variable declaration to declare a reference variable Account scroogeaccount; The above statement is a variable declaration The name of the variable is scroogeaccount The type of the variable is Account However, just like with records, this variable declaration does not create any object; it merely declares a variable that can keep track of an object in memory Such a variable stores the address in memory where the object is stored, not the object itself It is like any other reference variable 27
28 Creating Objects (1) Creating objects and creating records are very similar operations We use the new operator to create an object, just like when we create a record The difference is that we can specify optional actual parameters between the parentheses scroogeaccount = new Account(12345); Actual parameters (if necessary) 28
29 Creating Objects (2) We have seen something like this before: keyboard = new Scanner(System.in); 29
30 Calling Constructors (1) 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 Basically, we can overload a constructor like we can overload methods Constructor are very similar to methods, but they are technically not methods 30
31 Calling Constructors (2) Just like methods, constructors can be defined to take any number of parameters: 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 The actual parameters passed to a constructor follow the same syntactic and semantic rules as the actual parameters passed during a call to a regular method They are expressions separated by commas The regular parameter passing mechanisms apply for each parameter type (primitive or reference) Creating an object is called instantiation, because an object is an instance of a particular class 31
32 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, as if we were accessing a record field; the syntax is the following: variablename.methodname(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() 32
33 Invoking Methods on Objects (2) This is unlike what we have seen so far Up until now, we invoked most methods by specifying the name of a class in front of the. operator, not the name of a variable However, we have seen some examples of invoking a method on an object by specifying the name of a variable in front of the. operator: int value = keyboard.nextint(); boolean same = s1.equals(s2); int result = s1.compareto(s2); 33
34 Invoking Methods on Objects (3) 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 Even though the target is not passed as an actual parameter to the method, it acts like one in many ways In particular, a method call can change the state of the target object For example, the deposit() method changes the value of the balance attribute of the object on which it is called Otherwise, methods called against objects work the same way as the methods we declared and called earlier 34
35 Invoking Methods on Objects (4) The main difference is that instead of writing the name of a class in front of the. operator, we write the name of a variable containing the address of an object Method invoked using this syntax (variable name in front of the. operator) are called instance methods Method invoked using the syntax we saw before (class name in front of the. operator) are called class methods or static methods 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 35
36 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 36
37 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 37
38 Object Attributes In most cases, it is not possible to access the attributes of an object like we access the fields of a record (that is, using the. operator) This is because the internal details of an object are hidden In a well-designed program, only the methods declared inside a class can access the attributes of objects which belongs to that class Methods declared in all other classes MUST manipulate the object by calling public methods on it Although this appears overly restrictive at first glance, it makes the overall program easier to maintain (especially we change the internal details of the objects which belong to a class) 38
39 Objects and Reference Types (1) Object types are basically record types, and therefore behave like them in most respects: A variable whose type is an object type does not store the object itself; it stores the address where the object is stored in memory Declaring a variable whose type is an object type does not allocate the object itself; if it is necessary to allocate a new object, this must be done in a separate step using the new operator The assignment operator (=) evaluates the expression on the right, and copies the address it produces in the variable on the left; it does not allocate a new object Objects can be aliased; if you change the state of the object through one of its aliases, the change will be reflected by its other aliases 39
40 Objects and Reference Types (2) The equality (==) and inequality (!=) operator compare the addresses on each side for (in)equality, not the state of the objects stored in memory at the addresses on each side When an object is passed to a method as an actual parameter, the actual parameter and the formal parameter become aliases When your program can no longer access an object, the memory it occupies is reclaimed by the garbage collector You can assign null to any object variable Specifying a variable which contains null as the target of an instance method call will result in a NullPointerException 40
41 The equals() Method (1) Remember that for all reference types (including arrays, record types, and object types), the == and!= operator verify whether the variables on both sides refer to the same object 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 41
42 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 42
43 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 43
44 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 44
45 Class / Static Methods In Java, many 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 The methods we wrote earlier in the course are like this; such methods are class methods or static methods 45
46 Invoking Class / Static Methods As we know, to invoke a class method, we use the following syntax: classname.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 46
47 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 47
48 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 48
49 The tostring() Method (2) You can also call the tostring() method on an object explicitly to generate a text representation of the object: String text = scroogeaccount.tostring(); 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 49
50 Documentation Most classes come with documentation which describes the constructors, methods, and class constants defined in the class 50
51 Reading Documentation (1) The 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 51
52 Reading Documentation (2) If the method is listed as static, it is a class method (constructors cannot be static); if the method is not listed as static, it is an instance method 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 method description specifies what the method does, and what each parameter (as well as the return value) represents 52
53 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 53
54 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 54
55 Part 3: The String Class and String Objects
56 Strings in Java (1) In Java, every character string is an object which belongs to the String class The String class is defined in the Java Standard Class Library which is part of all Java development environments This class defines all the methods that can be called using String objects as targets 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 56
57 Strings in Java (2) In particular, we do not have to use the new operator to create a String object; 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 57
58 Strings in Java (3) Despite this, the String type is still a reference type 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 This is why 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 58
59 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. 59
60 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. 60
61 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 (this depends on how the class is implemented) 61
62 String Indexing (1) Just like with arrays, 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' 62
63 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 63
64 IndexOutOfBoundsDemo.java public class IndexOutOfBoundsDemo { public static void main(string[] args) { String s; } } s = "hello"; System.out.println("Attempting to retrieve the " + "character at position " + s.length() + " of " + "String " + s); System.out.println("The character at position " + s.length() + " of String " + s + ": " + s.charat(s.length())); 64
65 Reading Exception Output 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:10) More details on the problem Index we tried to access and caused the crash 65
66 Array Length and String Length When we retrieve the length of an array, we access its length field Because we are accessing a field, we MUST NOT write parentheses after the word length We therefore write myarray.length, where myarray is a variable whose type is an array type However, when we retrieve the length of a String, we call its length() method Because we are calling a method, we MUST write parentheses after the word length We therefore write mystring.length(), where mystring is a variable of type String 66
67 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? 67
68 Part 4: The Java Standard Library 68
69 The Java Standard Class Library As we know, there is a Java standard class library that is part of any Java development environment, which provides a number of useful classes that we can use to write programs 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 69
70 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 70
71 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 71
72 Implicit import Declarations All classes of the java.lang package are automatically imported into all programs Classes String and System are part of the java.lang package That's why we didn't have to explicitly import the System or String classes in earlier programs 72
73 The Scanner Class (1) The Scanner class is part of the Java standard class library It is part of the java.util package; therefore, you must import it in the classes that you write that use it, or use the fully qualified name when declaring Scanner variables It provides several methods for converting the bytes read from various sources (keyboard, files) into primitive values and Strings A Scanner object assumes that white space (delimiters) separates elements of the input (tokens) Delimiters may be different when reading different types of data 73
74 The Scanner Class (2) Watch out, especially when trying to read a String with nextline() immediately after reading a numeric value from the keyboard Constructors provided by the Scanner class take as input an objects representing the source we want to read from; so far, we have only read from System.in, an InputStream object representing the keyboard Later in the course, we will see how to create Scanner objects which read from a file on disk instead of the keyboard 74
75 Scanner Methods (1) Some methods defined in class Scanner: public Scanner(InputStream source): (Constructor) Constructs a new Scanner that produces values scanned from the specified input stream. public Scanner(File source): (Constructor) Constructs a new Scanner that produces values scanned from the specified file. public Scanner(String source): (Constructor) Constructs a new Scanner that produces values scanned from the specified string. public String next(): Finds and returns the next complete token from this Scanner. public String nextline(): Advances this Scanner past the current line and returns the input that was skipped. 75
76 Scanner Methods (2) public double nextdouble(): Scans the next token of the input as a double. public int nextint(): Scans the next token of the input as an int. public long nextlong(): Scans the next token of the input as a long. public String nextboolean(): Scans the next token of the input into a boolean value and returns that value. public boolean hasnext(): Returns true if this Scanner has another token in its input. public boolean hasnextline(): Returns true if there is another line in the input of this Scanner. 76
77 Scanner / Strings: Exercise Complete the main() method of the PrintNames class by adding code that does the following: Prompts the user to enter his / her first name and reads it from the keyboard Prompts the user to enter his / her last name and reads it from the keyboard Displays the full name of the user on one line, with the first name followed by the last name Performs the above steps until the user enters an empty line when prompted to enter his / her first name Can you think of more than one way to check whether the user entered an empty line? 77
78 PrintNames.java import java.util.scanner; public class PrintNames { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in); } } // Add your code here 78
79 (Pseudo-)Random Numbers (1) Computers are deterministic This means that whenever a program in a given state receives a given input, the output will always be the same Because of this, generating truly random numbers with a computer is very hard, if not impossible Therefore, we have to settle for generating pseudo-random numbers Pseudo-random number generators perform a series of complicated calculations, based on an initial seed value, and produce some values One of these values is the random number returned, the other is stored and used to generate the next random number when one is needed 79
80 (Pseudo-)Random Numbers (2) Numbers generated using pseudo-random number generators appear to be randomly selected They pass statistical randomness tests However, because of the deterministic nature of computers, whenever you use a given algorithm to generate pseudo-random numbers and initialize it with a fixed seed, you will generate the same number sequence 80
81 The Random Class (1) The Random class is part of the java.util package It provides methods that generate pseudo-random numbers: public Random(): (Constructor) Creates a new pseudo-random number generator, with an initial seed very likely to be distinct from any other Random object initialized by another invocation of this constructor. public Random(long seed): (Constructor) Creates a new pseudorandom number generator with the specified seed. public double nextdouble(): Returns a random number between 0.0 (inclusive) and 1.0 (exclusive). public int nextint(): Returns a random number that ranges over all possible int values (positive and negative). 81
82 The Random Class (2) public int nextint(int n): Returns a random number in the range 0 to n
83 RandomNumber.java import java.util.random; public class RandomNumber { public static void main(string args[]) { Random generator = new Random(); int i; float f; } } i = generator.nextint(10); // 0-9 f = generator.nextfloat(); // System.out.println("The randomly generated integer is: " + i); System.out.println("The randomly generated real number is: " + f); 83
84 RandomSequence.java (1 / 2) import java.util.random; import java.util.scanner; public class RandomSequence { public static void main(string[] args) { Scanner keyboard = new Scanner(System.in);; Random generator; final int MAX = 100; long seed; int number; System.out.print("Enter a seed : "); seed = keyboard.nextlong(); System.out.print("How many values do you want to " + "generate: "); number = keyboard.nextint(); System.out.println(); // Continued on next slide 84
85 RandomSequence.java (2 / 2) } } // Continued from previous slide System.out.print("Here are " + number + " pseudo-random " + "numbers from 0 - " + (MAX - 1) + ": "); generator = new Random(seed); for (int i = 0; i < number; i++) { System.out.print(generator.nextInt(MAX) + " "); } System.out.println(); What happens: when you run this program twice with the same seed? when you run this program twice with different seeds? 85
86 Formatting Output (1) The DecimalFormat class can be used to format a floating point value in generic ways It is defined in package java.text For example, you can specify that the number is to be printed to three decimal places First you have to create an object of the class DecimalFormat For that, you use the constructor of the DecimalFormat class The constructor takes a String that represents a pattern (for example, indicating three decimal places) Patterns can be quite complex 86
87 Formatting Output (2) You can call the format() method on a DecimalFormat object; it takes as input a floating point number and returns a String representation of that number in the appropriate format 87
88 Formatting Output: Exercise 1 Make the following modifications to the SimpleCircle class you completed in an earlier exercise: Change its name to FormattedCircle Change the code displaying the results so that the program displays the results with a maximum of 3 digits after the decimal point: the appropriate pattern is "0.###" Once it works properly, experiment by replacing the above pattern with the following: "0.#####". How does the output change? 88
89 More on Formatting Output (1) The NumberFormat class has class methods that return certain formatter objects: getcurrencyinstance(): Returns a formatter object that formats values as currencies getpercentinstance(): Returns a formatter object that formats values as percentages Each formatter object has a method called format(); calling this method with a numeric value as parameter returns a String representation of the value in the appropriate format Class NumberFormat is also part of the java.text package 89
90 More on Formatting Output (2) Example: NumberFormat formatter = NumberFormat.getCurrencyInstance(); String s = formatter.format(100); // s is now "$100.00" The formatters returned by the getcurrencyinstance() and getpercentinstance() methods format their input in a way which depends on the locale of the computer on which the program runs The locale consists of all the location / country / language dependent settings Therefore, two computers with two different locales running the same program may display differently-formatted output 90
91 Formatting Output: Exercise 2 Complete the main() method of the Taxes class by adding code that does the following: Computes the GST and the PST to be paid on the price entered by the user; note that the PST is calculated on the sum of the price before taxes and the GST to be paid on that price Computes the total price to be paid Displays the GST amount, the PST amount, and the total with appropriate messages for each value; all of these values should be formatted as currencies by using an appropriate formatter object 91
92 Taxes.java import java.util.scanner; public class Taxes { public static void main(string args[]) { Scanner keyboard = new Scanner(System.in); final double GST = 0.05; final double PST = 0.075; double price; } } System.out.print("Enter the price of the item: "); price = keyboard.nextdouble(); // Add your code here 92
93 Wrapper Classes Remember that there are two categories of data in Java: primitive data and objects We use wrapper classes to manage primitive data as objects Each wrapper class represents a particular primitive type Integer everest = new Integer(8850); We have just "wrapped" the primitive integer value 8850 into an object referenced by the everest variable This is useful to store primitive data in container classes We will cover container classes when we cover arrays All wrapper classes are part of the java.lang package: Byte, Short, Integer, Long, Float, Double, Character, Boolean 93
94 Integer Methods (1) Some methods defined in class Integer: Integer(value): (Constructor) Constructs a newly allocated Integer object that represents the specified int value. byte bytevalue(): Returns the value of this Integer as a byte. double doublevalue(): Returns the value of this Integer as a double. float floatvalue(): Returns the value of this Integer as a float. int intvalue(): Returns the value of this Integer as an int. long longvalue(): Returns the value of this Integer as a long. static int parseint(string s): Parses the String argument as a signed decimal integer 94
95 Integer Methods (2) static String tobinarystring(int i): Returns a String representation of the integer argument as an unsigned integer in base 2. Example: String s = "500"; int number = Integer.parseInt(s); // number now contains the int value
96 Java Library Reference All the details of all classes defined in the Java library can be found here: Java 6: Java 5: Do not hesitate to consult this reference to do your assignments 96
97 Part 5: Exercises 97
98 Exercises (1) 1) Write a Java class called KillWhiteSpace, which defines a main() method that asks the user to enter a String s, and displays a new String consisting of all the characters in s, but with the leading and trailing white space removed. In addition, every sequence of spaces within the String is reduced to one space only. You MUST NOT use any methods defined in the String class other than charat() and length(). 98
99 Exercises (2) 2) Write a Java class called OccursAnywhere, which defines a main() method that asks the user to enter two Strings, superstring and substring, and displays whether or not substring occurs anywhere in superstring. You MUST NOT use any method defined in the String class other than chartat() and length(). 99
COMP-202 Unit 5: Basics of Using Objects
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...) Introduction
More informationWe 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 informationA 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 informationCOMP 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 informationClasses 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 informationCOMP-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 informationCONTENTS: 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 informationUsing Classes and Objects. Chapter
Using Classes and Objects 3 Chapter 5 TH EDITION Lewis & Loftus java Software Solutions Foundations of Program Design 2007 Pearson Addison-Wesley. All rights reserved Using Classes and Objects To create
More informationFaculty 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 informationObjectives 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 informationFull 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 informationPackages & 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 informationECE 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 informationECE 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 informationChapter 3: Using Classes and Objects
Chapter 3: Using Classes and Objects CS 121 Department of Computer Science College of Engineering Boise State University August 21, 2017 Chapter 3: Using Classes and Objects CS 121 1 / 51 Chapter 3 Topics
More informationUsing 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 informationAssoc. 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 informationSTUDENT 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 informationFaculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2009) - All Sections Final Examination Wednesday, April 29, 2009 Examiners: Mathieu Petitpas
More informationExample: 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 informationFormatting Output & Enumerated Types & Wrapper Classes
Formatting Output & Enumerated Types & Wrapper Classes Quick review of last lecture September 8, 2006 ComS 207: Programming I (in Java) Iowa State University, FALL 2006 Instructor: Alexander Stoytchev
More informationMore on variables and methods
More on variables and methods Robots Learning to Program with Java Byron Weber Becker chapter 7 Announcements (Oct 12) Reading for Monday Ch 7.4-7.5 Program#5 out Character Data String is a java class
More informationChap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,
Chap. 3 Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L, 3.1 3.6 1 From last time: Account Declaring an Account object: Account acct1 = new Account
More informationCSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1
CSCI 2010 Principles of Computer Science Basic Java Programming 1 Today s Topics Using Classes and Objects object creation and object references the String class and its methods the Java standard class
More informationLast 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 informationFaculty 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 informationConditional Programming
COMP-202 Conditional Programming Chapter Outline Control Flow of a Program The if statement The if - else statement Logical Operators The switch statement The conditional operator 2 Introduction So far,
More informationMidterms 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 informationText User Interfaces. Keyboard IO plus
Text User Interfaces Keyboard IO plus User Interface and Model Model: objects that solve problem at hand. User interface: interacts with user getting input from user giving output to user reporting on
More informationCHAPTER 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 informationUsing 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 informationCHAPTER 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 informationFaculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Foundations of Computing (Fall 2012) - All Sections Midterm Examination November 7th, 2012 Examiners: Daniel Pomerantz [Sections
More information12/22/11. Java How to Program, 9/e. public must be stored in a file that has the same name as the class and ends with the.java file-name extension.
Java How to Program, 9/e Education, Inc. All Rights Reserved. } Covered in this chapter Classes Objects Methods Parameters double primitive type } Create a new class (GradeBook) } Use it to create an object.
More informationObjects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal
Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal Lesson Goals Understand objects and classes Understand Encapsulation Learn about additional Java classes The
More informationUsing Classes and Objects
Using Classes and Objects CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: www.csc.villanova.edu/~map/1051/ Today
More informationVariables and Assignments CSC 121 Spring 2017 Howard Rosenthal
Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal Lesson Goals Understand variables Understand how to declare and use variables in Java Programs Learn how to formulate assignment statements
More informationUsing APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI
Outline Chapter 3 Using APIs 3.1 Anatomy of an API 3.1.1 Overall Layout 3.1.2 Fields 3.1.3 Methods 3.2 A Development Walkthrough 3.2.1 3.2.2 The Mortgage Application 3.2.3 Output Formatting 3.2.4 Relational
More informationCOMP 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 informationLecture 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 informationCS 112 Introduction to Programming
CS 112 Introduction to Programming Summary of Methods; User Input using Scanner Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu Admin
More informationCOP 3330 Final Exam Review
COP 3330 Final Exam Review I. The Basics (Chapters 2, 5, 6) a. comments b. identifiers, reserved words c. white space d. compilers vs. interpreters e. syntax, semantics f. errors i. syntax ii. run-time
More informationCSE 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 informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2009) - All Sections Final Examination Wednesday, December 16, 2009 Examiners: Mathieu Petitpas
More informationCSCI 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 informationFaculty 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 informationCreating 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 informationReview 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 informationJava How to Program, 10/e. Copyright by Pearson Education, Inc. All Rights Reserved.
Java How to Program, 10/e Education, Inc. All Rights Reserved. Each class you create becomes a new type that can be used to declare variables and create objects. You can declare new classes as needed;
More informationFaculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202B - Introduction to Computing I (Winter 2010) - All Sections Midterm Examination Thursday, March 11, 2010 Examiners: Milena Scaccia
More informationCOMP-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 informationUniversity 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 informationDefining 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 informationObjects 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 informationComputational Expression
Computational Expression Variables, Primitive Data Types, Expressions Janyl Jumadinova 28-30 January, 2019 Janyl Jumadinova Computational Expression 28-30 January, 2019 1 / 17 Variables Variable is a name
More informationing execution. That way, new results can be computed each time the Class The Scanner
ing execution. That way, new results can be computed each time the run, depending on the data that is entered. The Scanner Class The Scanner class, which is part of the standard Java class provides convenient
More informationFirst 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 informationECE 122. Engineering Problem Solving with Java
ECE 122 Engineering Problem Solving with Java Lecture 5 Anatomy of a Class Outline Problem: How do I build and use a class? Need to understand constructors A few more tools to add to our toolbox Formatting
More informationProgramming 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 informationAppendix 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 informationCOMP 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 informationChapter 4 Classes in the Java Class Libraries
Programming Fundamental I ACS-1903 Chapter 4 Classes in the Java Class Libraries 1 Random Random The Random class provides a capability to generate pseudorandom values pseudorandom because the stream of
More informationJava Input/Output. 11 April 2013 OSU CSE 1
Java Input/Output 11 April 2013 OSU CSE 1 Overview The Java I/O (Input/Output) package java.io contains a group of interfaces and classes similar to the OSU CSE components SimpleReader and SimpleWriter
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
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 informationH212 Introduction to Software Systems Honors
Introduction to Software Systems Honors Lecture #04: Fall 2015 1/20 Office hours Monday, Wednesday: 10:15 am to 12:00 noon Tuesday, Thursday: 2:00 to 3:45 pm Office: Lindley Hall, Room 401C 2/20 Printing
More informationAny serious Java programmers should use the APIs to develop Java programs Best practices of using APIs
Ananda Gunawardena Java APIs Think Java API (Application Programming Interface) as a super dictionary of the Java language. It has a list of all Java packages, classes, and interfaces; along with all of
More informationComputer Science 145 Midterm 1 Fall 2016
Computer Science 145 Midterm 1 Fall 2016 Doodle here. This is a closed-book, no-calculator, no-electronic-devices, individual-effort exam. You may reference one page of handwritten notes. All answers should
More informationChapter 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 informationBasic 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 informationCS 211: Existing Classes in the Java Library
CS 211: Existing Classes in the Java Library Chris Kauffman Week 3-2 Logisitics Logistics P1 Due tonight: Questions? Late policy? Lab 3 Exercises Thu/Fri Play with Scanner Introduce it today Goals Class
More informationCOE 212 Engineering Programming. Welcome to Exam I Tuesday November 11, 2014
1 COE 212 Engineering Programming Welcome to Exam I Tuesday November 11, 2014 Instructors: Dr. Bachir Habib Dr. George Sakr Dr. Joe Tekli Dr. Wissam F. Fawaz Name: Student ID: Instructions: 1. This exam
More informationMidterms 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 informationComputer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name:
Computer Science 300 Sample Exam Today s Date 100 points (XX% of final grade) Instructor Name(s) (Family) Last Name: (Given) First Name: CS Login Name: NetID (email): @wisc.edu Circle your Lecture: Lec001
More informationProject 1. Java Data types and input/output 1/17/2014. Primitive data types (2) Primitive data types in Java
Java Data types and input/output Sharma Chakravarthy Information Technology Laboratory (IT Lab) Computer Science and Engineering Department The University of Texas at Arlington, Arlington, TX 76019 Email:
More informationInput. Scanner keyboard = new Scanner(System.in); String name;
Reading Resource Input Read chapter 4 (Variables and Constants) in the textbook A Guide to Programming in Java, pages 77 to 82. Key Concepts A stream is a data channel to or from the operating system.
More informationLecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4
Assignments Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4 Lecture 6 Complete for Lab 4, Project 1 Note: Slides 12 19 are summary slides for Chapter 2. They overview much of what we covered but are not complete.
More informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2008) Midterm Examination Tuesday, November 4, 2008 Examiners: Mathieu Petitpas [Section 1] 18:30
More informationJava Coding 3. Over & over again!
Java Coding 3 Over & over again! Repetition Java repetition statements while (condition) statement; do statement; while (condition); where for ( init; condition; update) statement; statement is any Java
More informationCSC 1051 Algorithms and Data Structures I. Midterm Examination October 11, Name: KEY
CSC 1051 Algorithms and Data Structures I Midterm Examination October 11, 2018 Name: KEY Question Value Score 1 20 2 20 3 20 4 20 5 20 TOTAL 100 Please answer questions in the spaces provided. If you make
More informationA Quick and Dirty Overview of Java and. Java Programming
Department of Computer Science New Mexico State University. CS 272 A Quick and Dirty Overview of Java and.......... Java Programming . Introduction Objectives In this document we will provide a very brief
More informationLearning objectives: Enhancing Classes. CSI1102: Introduction to Software Design. More about References. The null Reference. The this reference
CSI1102: Introduction to Software Design Chapter 5: Enhancing Classes Learning objectives: Enhancing Classes Understand what the following entails Different object references and aliases Passing objects
More informationExample: Tax year 2000
Introductory Programming Imperative Programming I, sections 2.0-2.9 Anne Haxthausen a IMM, DTU 1. Values and types (e.g. char, boolean, int, double) (section 2.4) 2. Variables and constants (section 2.3)
More informationBasic 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 informationLab5. Wooseok Kim
Lab5 Wooseok Kim wkim3@albany.edu www.cs.albany.edu/~wooseok/201 Question Answer Points 1 A or B 8 2 A 8 3 D 8 4 20 5 for class 10 for main 5 points for output 5 D or E 8 6 B 8 7 1 15 8 D 8 9 C 8 10 B
More informationClasses and Objects Miscellany: I/O, Statics, Wrappers & Packages. CMSC 202H (Honors Section) John Park
Classes and Objects Miscellany: I/O, Statics, Wrappers & Packages CMSC 202H (Honors Section) John Park Basic Input/Output Version 9/10 2 Printing to the Screen In addition to System.out.print() (and println()):
More informationWeiss Chapter 1 terminology (parenthesized numbers are page numbers)
Weiss Chapter 1 terminology (parenthesized numbers are page numbers) assignment operators In Java, used to alter the value of a variable. These operators include =, +=, -=, *=, and /=. (9) autoincrement
More informationEntry 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 informationSTUDENT 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 informationData 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 informationboolean, 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 informationFull file at
Chapter 2 Console Input and Output Multiple Choice 1) Valid arguments to the System.out object s println method include: (a) Anything with double quotes (b) String variables (c) Variables of type int (d)
More informationLecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4
Assignments Lecture 6 Complete for Project 1 Reading: 3.1, 3.2, 3.3, 3.4 Summary Program Parts Summary - Variables Class Header (class name matches the file name prefix) Class Body Because this is a program,
More informationFull file at
Chapter 1 Primitive Java Weiss 4 th Edition Solutions to Exercises (US Version) 1.1 Key Concepts and How To Teach Them This chapter introduces primitive features of Java found in all languages such as
More informationJava Review. Java Program Structure // comments about the class public class MyProgram { Variables
Java Program Structure // comments about the class public class MyProgram { Java Review class header class body Comments can be placed almost anywhere This class is written in a file named: MyProgram.java
More informationAn Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal
An Introduction To Writing Your Own Classes CSC 123 Fall 2018 Howard Rosenthal Lesson Goals Understand Object Oriented Programming The Syntax of Class Definitions Constructors this Object Oriented "Hello
More informationCSI Introduction to Software Design. Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) x 6277
CSI 1102 Introduction to Software Design Prof. Dr.-Ing. Abdulmotaleb El Saddik University of Ottawa (SITE 5-037) (613) 562-5800 x 6277 elsaddik @ site.uottawa.ca abed @ mcrlab.uottawa.ca http://www.site.uottawa.ca/~elsaddik/
More informationJava 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 informationFaculty of Science COMP-202A - Introduction to Computing I (Fall 2011) - All Sections Midterm Examination
First Name: Last Name: McGill ID: Section: Faculty of Science COMP-202A - Introduction to Computing I (Fall 2011) - All Sections Midterm Examination Monday, October 31, 2011 Examiners: Daniel Pomerantz
More informationCS 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 informationWentworth 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