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

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

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

Classes and Objects Part 1

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

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

Chapter. Let's explore some other fundamental programming concepts

COMP-202 Unit 5: Basics of Using Objects

Using Classes and Objects. Chapter

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

Chapter 2: Data and Expressions

COMP 202 Java in one week

Chapter 2: Data and Expressions

Using Classes and Objects

Full file at

Using Java Classes Fall 2018 Margaret Reid-Miller

COMP-202 Unit 8: Basics of Using Objects

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

COMP 202. Java in one week

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

CSCI 2010 Principles of Computer Science. Basic Java Programming. 08/09/2013 CSCI Basic Java 1

2: Basics of Java Programming

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

Chap. 3. Creating Objects The String class Java Class Library (Packages) Math.random() Reading for this Lecture: L&L,

Packages & Random and Math Classes

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

ECE 122 Engineering Problem Solving with Java

Lecture Set 2: Starting Java

Lecture Set 2: Starting Java

Chapter 2 ELEMENTARY PROGRAMMING

Computational Expression

Formatting Output & Enumerated Types & Wrapper Classes

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

Object-Based Programming. Programming with Objects

Data Conversion & Scanner Class

Chapter 2: Data and Expressions

CIS 1068 Design and Abstraction Spring 2017 Midterm 1a

Chapter 2 Elementary Programming

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

Programming with Java

CMPT 125: Lecture 3 Data and Expressions

Basic Computation. Chapter 2

Basic Computation. Chapter 2

ECE 122. Engineering Problem Solving with Java

ECE 122. Engineering Problem Solving with Java

First Java Program - Output to the Screen

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

H212 Introduction to Software Systems Honors

AP Computer Science A

ing execution. That way, new results can be computed each time the Class The Scanner

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

Constants. Why Use Constants? main Method Arguments. CS256 Computer Science I Kevin Sahr, PhD. Lecture 25: Miscellaneous

Introduction to Java (All the Basic Stuff)

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

Lecture 6. Assignments. Java Scanner. User Input 1/29/18. Reading: 2.12, 2.13, 3.1, 3.2, 3.3, 3.4

Objects and Classes -- Introduction

Primitive Data Types: Intro

Lecture 6. Assignments. Summary - Variables. Summary Program Parts 1/29/18. Reading: 3.1, 3.2, 3.3, 3.4

Java Basic Introduction, Classes and Objects SEEM

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

Lesson 02 Data Types and Statements. MIT 12043, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

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

CMSC131. Introduction to your Introduction to Java. Why Java?

Lesson 02 Data Types and Statements. MIT 11053, Fundamentals of Programming By: S. Sabraz Nawaz Senior Lecturer in MIT Department of MIT FMC, SEUSL

Getting started with Java

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

What did we talk about last time? Examples switch statements

More on variables and methods

Section 2: Introduction to Java. Historical note

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 26, Name: Key

Variables and Assignments CSC 121 Spring 2017 Howard Rosenthal

CEN 414 Java Programming

Important Java terminology

A Quick and Dirty Overview of Java and. Java Programming

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination February 25, Name: KEY A

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

Program Elements -- Introduction

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

CS 302: Introduction to Programming

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

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

Reading Input from Text File

2 rd class Department of Programming. OOP with Java Programming

4 WORKING WITH DATA TYPES AND OPERATIONS

Elementary Programming. CSE 114, Computer Science 1 Stony Brook University

Java Basic Introduction, Classes and Objects SEEM

Using APIs. Chapter 3. Outline Fields Overall Layout. Java By Abstraction Chapter 3. Field Summary static double PI

Chapter 2. Elementary Programming

Elementary Programming

Using Classes and Objects

Chapter 3: Using Classes and Objects

STUDENT LESSON A10 The String Class

12/22/11. Java How to Program, 9/e. Help you get started with Eclipse and NetBeans integrated development environments.

Introduction to Java Unit 1. Using BlueJ to Write Programs

Chapter 1 Introduction to java

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

CSC 1051 Algorithms and Data Structures I. Midterm Examination October 7, Name:

Objects and Classes 1: Encapsulation, Strings and Things CSC 121 Fall 2014 Howard Rosenthal

More Things We Can Do With It! Overview. Circle Calculations. πr 2. π = More operators and expression types More statements

Transcription:

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 entity that has data and methods so far, we haven t seen data, only methods examples: teller machine objects that allow to withdraw money, make money transfers etc. calculator objects that allows to perform addition, division, etc. Scanner objects allow to read in data from the keyboard COMP 202 Objects and Built in Libraries 2

Classes and Objects Each object belongs to a class Examples teller machine objects belong to the class TellerMachine A scanner object belongs to the class Scanner All objects of a class have the same methods Scanner objects have nextint(), nextdouble(), TellerMachine objects have withdraw, A class can be seen as a blueprint which describes the general behavior of a set of similar objects That is, the class used to define an object can be thought of as the type of an object COMP 202 Objects and Built in Libraries 3

About Libraries Programming languages come with many modules: Editor To help you write the program Compiler To validate your syntax and convert you text file into an executable file Syntax & Semantics Rules that define how you write sentences and spell words in that language Libraries Pre built classes and objects with methods that you can use in your program (this is nice since you do not need to write this code, someone else has done this for you). Libraries come with the compiler you buy or you can download them from the web (some free, some not). COMP 202 Objects and Built in Libraries 4

System.out System.out is a variable that points to an object that belongs to the class System System.out has been predefined and set up for us as part of the Java standard class library. println is a method that has been implemented by someone else. We don t care what actions or statements are actually executed. We only need to know what it is supposed to do and what the input is. System.out.println ( This is a long message to print in a single line."); object variable method Information provided to the method (parameters) COMP 202 Objects and Built in Libraries 5

The DOT Operator Java uses the period as a membership designation. For example: System.out.println( My output ); The DOT Operator The DOT operator invokes the println method of the object to which the variable out points to. COMP 202 Objects and Built in Libraries 6

Important 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 We don't have to know the internals of the println method in order to invoke it; we only need to know what it does but not the individual steps/actions needed to accomplish this Therefore, we can write complex software without having to know how parts of it actually work. COMP 202 Objects and Built in Libraries 7

Strings vs. Characters Characters are a single letter or symbol: char x = a ; char y = % ; Strings are many characters concatenated: String s = Bob Smith ; char is a built in type String is a library object COMP 202 Objects and Built in Libraries 8

The String Object Every character string is an object in Java. hello, world, The behavior of string objects is defined by the String class Every string literal, delimited by double quotation marks, represents a String object Since strings are so common, the Java programming language provides us with some form of syntactic sugar that allows us to use strings nearly in a way we use primitive data types. However, there are important differences between primitive data types and String objects and we have to aware of them. COMP 202 Objects and Built in Libraries 9

String concatenation The string concatenation operator (+) is used to append one string to the end of another hello + world results in a new string hello world A string literal cannot be broken across two lines in a program COMP 202 Objects and Built in Libraries 10

Facts.java public class Facts { public static void main(string[] args) { String firstname = "Bob"; String lastname = "Smith"; String fullname; fullname = firstname + " " + lastname; System.out.println("His name is: " + fullname); System.out.println("Tel. prefix: " + 514); System.out.println("Tel. prefix: 514"); } } What is the output? COMP 202 Objects and Built in Libraries 11

The + operator The function that the + operator performs depends on the type of the information on which it operates If both operands are strings, it performs string concatenation if one is a string and one is a number it converts the number into its string representation then it concatenates both strings if one is a string and one is an arithmetic expression it evaluates the arithmetic expression and converts the results into a string representation then it concatenates both strings 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 202 Objects and Built in Libraries 12

Addition.java public class Addition { public static void main(string[] args) { int x = 5, y = 2, sum = 0; String s = "The Sum is "; } } sum = x + y; s = s + sum; System.out.println(s); System.out.println("The result is:" + x + y); System.out.println("The result is:" + (x+y)); What is the output? COMP 202 Objects and Built in Libraries 13

Escape Sequences What if we wanted to print a double quote character? The following line would confuse the compiler because it would interpret the second quote as the end of the string 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 202 Objects and Built in Libraries 14

Escape Sequences Some Java escape sequences: Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash COMP 202 Objects and Built in Libraries 15

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 When I look at you\n\t I do not know what to do"); } What does this print out? COMP 202 Objects and Built in Libraries 16

Creating Objects A variable: either holds a primitive type, or it holds a reference/pointer to an object A class name can be used like a type to declare a reference variable String name Scanner scan; No object has been created with this declaration A reference variable holds the address of an object The object itself must be created separately COMP 202 Objects and Built in Libraries 17

Creating Objects We use the new operator to create an object name = new String ("Sparky the clown"); This calls the String constructor, which is a special method that sets up the object scan = new Scanner (System.in); Creating an object is called instantiation, because an object is an instance of a particular class COMP 202 Objects and Built in Libraries 18

String special Because strings are so common, we don't have to use the new operator to create a String object name = "Sparky the clown"; This is special syntax that only works for strings COMP 202 Objects and Built in Libraries 19

Methods Once an object has been instantiated, we can use the dot operator to invoke its methods int length; length = name.length(); length = scan.nextint(); Many methods have return values length() returns an integer value the return value can be assign to a variable recall nextint() method of the Scanner class returns an integer value nextdouble() method of the Scanner class returns a double value Many methods need input values System.out.println( Hello World ); requires input of type String COMP 202 Objects and Built in Libraries 20

Primitive data vs. objects: Declaration int num; creates a variable that holds an integer value that is, allocates main memory cells which are accessed via the variable num String name; reserve space for an object variable that is, allocates main memory cells which will contain the reference to an object (once the object is created) Initially, both variables don t contain any data num name COMP 202 Objects and Built in Libraries 21

Primitive data vs. objects: Assignment I num = 42; writes 42 into the cells referred to by num name = new String( James Gosling ); a string object is created; it uses some memory cells the variable name holds the address of the memory cell that contains the string object we say the object variable is a pointer to the real object num name 42 James Gosling COMP 202 Objects and Built in Libraries 22

Primitive data: Assignment II int num1 = 5; int num2 = 7; num1 num2 num2 = num1; num1 num2 5 7 5 5 COMP 202 Objects and Built in Libraries 23

Objects: Assignment II String name1 = Ada, Countess of Lovelace ; String name2 = Grace Murray Hopper ; name1 name2 name2 = name1; name1 name2 Ada, Countess of Lovelace Grace Murray Hopper Ada, Countess of Lovelace Grace Murray Hopper COMP 202 Objects and Built in Libraries 24

String Methods The String class has several methods that are useful for manipulating strings, ex: Method Meaning Result String(String str) Creates a string object Reference char charat(int index) Get char at index char int compareto(string str) Is str the same? 0 if same boolean equals(string str) Is str the same? boolean boolean equalsignorecase(string str) int length() Number of characters int String replace(char oldchar, char newchar) Find oldchar and replace String String substring(int offset, int endindex) Cutout part of string String String tolowercase() Convert to lowercase String String touppercase() Convert to uppercase String None of the methods changes the string object on which the method is called index: position of a character in a string (starting with 0) COMP 202 Objects and Built in Libraries 25

StringMutate.java public class StringMutate { public static void main(string[] args) { String s = new String("This is a sentence"); String s2 = s, s3 = "Bob"; String temp; int answer; answer = s.compareto(s2); System.out.println("answer = "+ answer); temp = s.substring(2,3); System.out.println("temp: "+ temp); s3 = s3.replace('b','c'); System.out.println("s3: "+ s3); } } What is in answer, temp and s3? COMP 202 Objects and Built in Libraries 26

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 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 202 Objects and Built in Libraries 27

Packages The classes of the Java standard class library are organized into packages Some of the packages in the standard class library are: Package java.lang java.applet (java.awt javax.swing java.net java.util Purpose General support (e.g., contains System and String) Creating applets for the web Graphics and graphical user interfaces) Additional graphics capabilities and components Network communication Utilities COMP 202 Objects and Built in Libraries 28

The import Declaration When you want to use a class from a package, you could use its fully qualified name java.util.scanner Or you can import the class, then just use the class name import java.util.scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*; COMP 202 Objects and Built in Libraries 29

No import for java.lang All classes of the java.lang package are automatically imported into all programs That's why we didn't have to explicitly import the System or String classes in earlier programs COMP 202 Objects and Built in Libraries 30

The Scanner Class The Scanner class is part of the Java standard class library Part of the java.util package Contains several methods for reading input values for various types from various sources (keyboard, file) A Scanner object assumes that white space (delimiters) separates elements of the input (tokens) COMP 202 Objects and Built in Libraries 31

The Scanner class so far Scanner scan = new Scanner(System.in); scan is an object variable Constructor takes as input the source we want to read; keyboard so far after creation of Scanner object, scan points to this object int number1 = scan.nextint(); double number2 = scan.nextdouble(); Keyboard COMP 202 Objects and Built in Libraries 32

Some methods of the Scanner class Scanner (InputStream source) Scanner (File source) Scanner (String source) String next () String nextline () double nextdouble () float nextfloat () int nextint () long nextlong () short nextshort () String nextboolean () Boolean hasnext () COMP 202 Objects and Built in Libraries 33

Printing names import java.util.scanner; public class PrintNames { public static void main(string[] args) { String firstname, lastname; boolean done = false; Scanner scan = new Scanner(System.in); } } while(!done) { System.out.println("enter first name (\"done\" exits)"); firstname = scan.nextline(); if (firstname.equals("done")) done = true; else { System.out.println("enter last name:"); lastname = scan.nextline(); System.out.println("The full name is " + firstname + " " + lastname); } } What does this print out? COMP 202 Objects and Built in Libraries 34

Random Numbers pseudo random number generator performs a series of complicated calculations, based on an initial seed value, and produces a number these numbers appear as being randomly selected Random() constructor float nextfloat() returns a random number between 0.0 (incl.) and 1.0 (excl.) int nextint() returns a random number that ranges over all possible int values (positive and negative) int nextint(int num) returns a random number in the range 0 to num 1 COMP 202 Objects and Built in Libraries 35

RandomNumber.java import java.util.random; public class RandomNumber { public static void main(string args[]) { Random generator = new Random(); int num1; float num2; num1 = generator.nextint(10); // 0 9 num2 = generator.nextfloat(); // 0.0 1.0 System.out.println("num1: "+ num1 +", num2: "+ num2); } } COMP 202 Objects and Built in Libraries 36

Class Methods Some methods can be invoked through the class name, instead of through an object of the class that is, we do not need to declare an object variable and create an object before calling these methods These methods are called class methods or static methods The Math class contains many static methods, providing various mathematical functions, such as absolute value, trigonometry functions, square root, power, PI (see Chapter 3 for more methods) temp = Math.cos(90) + Math.sqrt(delta); COMP 202 Objects and Built in Libraries 37

Circle import java.util.scanner; public class Circle { public static void main (String [] args) { double radius, circumference, area; Scanner scan = new Scanner(System.in); } } // read in the radius System.out.println("Enter radius:"); radius = scan.nextdouble(); // perform calculation circumference = 2 * Math.PI * radius; area = Math.pow(radius,2) * Math.PI; System.out.println("The circumference is: " + circumference); System.out.println("The area is: " + area); COMP 202 Objects and Built in Libraries 38

Formatting Output The DecimalFormat class can be used to format a floating point value in generic ways For example, you can specify that the number 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 (e.g., indicating three decimal places) The DecimalFormat object has a method called format that takes as input a floating point number and returns a string with the specified information in the appropriate format COMP 202 Objects and Built in Libraries 39

Circle formatted import java.util.scanner; import java.text.decimalformat; public class Circle { } public static void main (String [] args) { } double radius, circumference, area; Scanner scan = new Scanner(System.in); DecimalFormat f = new DecimalFormat("0.###"); // read in the radius System.out.println("Enter radius:"); radius = scan.nextdouble(); // perform calculation circumference = 2 * Math.PI * radius; area = Math.pow(radius,2) * Math.PI; System.out.println("The circumference is: " + f.format(circumference)); System.out.println("The area is: " + f.format(area)); COMP 202 Objects and Built in Libraries 40