Data Representation Classes, and the Java API

Similar documents
Using Classes and Objects

Using Classes and Objects

Data Representation and Applets

Data Representation and Applets

Using Classes and Objects

Data Representation and Applets

Applets and the Graphics class

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

Data Representation and Applets

2: Basics of Java Programming

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:

ECE 122 Engineering Problem Solving with Java

Using Classes and Objects. Chapter

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

Chapter. Let's explore some other fundamental programming concepts

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

CSC 1051 Data Structures and Algorithms I

Data Conversion & Scanner Class

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

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

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

Formatting Output & Enumerated Types & Wrapper Classes

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

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CMPT 125: Lecture 3 Data and Expressions

Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

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

What did we talk about last time? Examples switch statements

Lecture 3: Variables and assignment

Introduction to Arrays

Selection and Repetition Revisited

Selection and Repetition

Algorithms in everyday life. Algorithms. Algorithms and Java basics: pseudocode, variables, assignment, and interactive programs

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Programming with Java

Basics of Java Programming variables, assignment, and input

CSC 1051 Data Structures and Algorithms I

Java I/O and Control Structures Algorithms in everyday life

Java I/O and Control Structures

Algorithms and Conditionals

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

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

Selection and Repetition

Selection and Repetition Revisited

Chapter 2: Data and Expressions

CS-201 Introduction to Programming with Java

CSC 1051 Algorithms and Data Structures I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

CSC 1051 Villanova University. CSC 1051 Data Structures and Algorithms I. Course website:

Chapter 2: Data and Expressions

Selection Statements and operators

Chapter 2. Elementary Programming

Primitive Data Types: Intro

CSC 1051 Data Structures and Algorithms I

Selection Statements and operators

Java Bootcamp - Villanova University. CSC 2014 Java Bootcamp. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

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

Full file at

CS313D: ADVANCED PROGRAMMING LANGUAGE

AP Computer Science A

COMP Primitive and Class Types. Yi Hong May 14, 2015

CHAPTER 4 MATHEMATICAL FUNCTIONS, CHARACTERS, STRINGS

Operators and Expressions

Chapter 2 ELEMENTARY PROGRAMMING

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

Java Primer 1: Types, Classes and Operators

AYBUKE BUYUKCAYLI KORAY OZUYAR MUSTAFA SOYLU. Week 21/02/ /02/2007 Lecture Notes: ASCII

Classes and Objects Part 1

Variables, Constants, and Data Types

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

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

Discussion. Why do we use Base 10?

Packages & Random and Math Classes

More Programming Constructs -- Introduction

Declaration and Memory

Program Elements -- Introduction

Name: Checked: Access the Java API at the link above. Why is it abbreviated to Java SE (what does the SE stand for)?

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

COMP Computer Basics. Yi Hong May 13, 2015

Java Module Lesson 2A Practice Exercise

The type of all data used in a C (or C++) program must be specified

CEN 414 Java Programming

CSC 1051 Data Structures and Algorithms I. Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University

Using Java Classes Fall 2018 Margaret Reid-Miller

Example: Tax year 2000

Full file at

Java Classes: Math, Integer A C S L E C T U R E 8

Chapter 2 Elementary Programming

Eng. Mohammed S. Abdualal

AP Computer Science A

Introduction to Programming Using Java (98-388)

IT 1204 Section 2.0. Data Representation and Arithmetic. 2009, University of Colombo School of Computing 1

Two Types of Types. Primitive Types in Java. Using Primitive Variables. Class #07: Java Primitives. Integer types.

Important Java terminology

Module 2 - Part 2 DATA TYPES AND EXPRESSIONS 1/15/19 CSE 1321 MODULE 2 1

Control flow, conditionals, boolean expressions, block statements, nested statements. Course website:

H212 Introduction to Software Systems Honors

Define a method vs. calling a method. Chapter Goals. Contents 1/21/13

Computational Expression

Transcription:

Data Representation Classes, and the Java API CSC 1051 Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website: http://www.csc.villanova.edu/~map/1051/ Some slides in this presentation are adapted from the slides accompanying Java Software Solutions by Lewis & Loftus

Overview Binary representation Data types revisited Type conversions, casts The Java API classes Math class Random class String class

Review Data Representation Computers store all information digitally, using binary codes: numbers text images audio video program instructions 9278 9279 9280 9281 9282 9283 9284 9285 9286 01110100

Why Binary Numbers? Simplest way to represent digital information: Electronic circuits: high/low voltage Magnetic devices (eg hard drive): positive/negative Optical devices (eg DVD): light reflected/not reflected due to microscopic grooves A binary digit is called a bit - binary digit A byte is a group of eight bits

Binary codes 1 bit 0 1 2 bits 00 01 10 11 Each additional bit doubles the number of possible codes 3 bits 000 001 010 011 100 101 110 111 4 bits 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111

Binary Codes How many codes? 1 bit? 2 bits? 3 bits? 4 bits? 5 bits? How many codes of N bits? How many bits are needed to represent 64 items? How many bits are needed to represent 80 items? How many bits are needed to represent each of the 50 states (so that each state corresponds to a unique code)?

Storage requirements examples If a code requires 5 bits, a document consisting of 4000 such codes will require a total of: 5 x 4000 = 20,000 bits how many bytes is that? If a code requires 8 bits (i.e., a byte), a document consisting of 2000 such codes will require 2000 bytes. how many bits is that? If a code requires 32 bits, a program that needs to store 2000 such codes will require bits or bytes.

Storage Capacity Every memory device has a storage capacity, indicating the number of bytes it can hold Unit Symbol Number of Bytes kilobyte KB 2 10 = 1024 megabyte MB 2 20 (over one million) gigabyte GB 2 30 (over one billion) terabyte TB 2 40 (over one trillion) petabyte PB 2 50 (a whole bunch)

Numeric Primitive Data The difference between the numeric primitive types is their size and the values they can store: Type Storage Min Value Max Value byte short int long 8 bits 16 bits 32 bits 64 bits -128-32,768-2,147,483,648 < -9 x 10 18 127 32,767 2,147,483,647 > 9 x 10 18 float double 32 bits 64 bits +/- 3.4 x 10 38 with 7 significant digits +/- 1.7 x 10 308 with 15 significant digits

Characters in Java Characters, including spaces, digits, and punctuation are represented by numeric codes H i, H e a t h e r. 72 105 44 32 72 101 97 116 104 101 114 46 The ASCII (American Standard Code for Information Interchange) character set uses eight bits per character, allowing for 256 unique characters 01110100 ASCII 00000000 01110100 UNICODE The Unicode character set extends ASCII to sixteen bits per character, allowing for 65,536 unique characters.

Characters in Java A char variable stores a single character Character literals are delimited by single quotes: 'a' 'X' '7' '$' ',' '\n' Note the difference between a primitive character variable, which holds only one character, and a String object, which can hold multiple characters char grade = 'A'; char terminator = ';', separator = ' ', newline = '\n'; char letter = 't'; char next = letter++; // 'u'

Automatic type conversion Values of different types can be combined in an assignment or an expression Example: int dollars = 5; double money = dollars + 2.50; System.out.println(dollars + " dollars"); These are all examples of widening conversions, i.e, smaller data type è larger data type

Converting from one type to another Widening conversions small data type è larger one eg: int è double 32 bits è 64 bits Narrowing conversions large data type è smaller one eg: double è int 64 bits è 32 bits narrowing conversions can lose information! narrowing conversions cannot happen automatically (for example, through assignment)

Casting Casting forces a change of type, even if information is lost Can be used for both widening and narrowing conversion To cast, put the type in parentheses in front of the value to be converted: int total = 5; double result = (double) total / 2; int answer = (int) result + 4; double angle = 0; // 0 radians int x = (int)(math.cos(angle) * 300); (cast has higher precedence than arithmetic operators)

Data Conversion Widening Conversions Narrowing Conversions

How to use cast? Forcing floating point division between int expressions int qp = 35; int credits = 10; double gpa = (double) qp / credits; int qp = 35; int credits = 10; gpa should be 3.5? double gpa = (double) (qp / credits);

How to use cast? Scaling a double and converting to int double gpa = 3.2; int gpapercent = (int) (gpa / 4) * 100; gpapercent should be 80? double gpa = 3.2; int gpapercent = (int) ((gpa / 4) * 100);

char ó int Conversion A char variable is stored as its unicode representation char ó int conversion: convert between char and its unicode. e.g.: t ó 116 increment and decrement of char variables takes you up and down in alphabetical order (codes are in numeric sequence) char letter = 't'; int lettercode = letter; // 116 (code for 't ) char next = letter++; // 'u' int nextcode = next; // 117 (code for 'u ) char nextalt = (char) nextcode; // 'u // narrowing conversion - requires cast char whatsthis = (char) ('A' + 3); //??? int num = (int) (letter 'p'); //???

The Java class library or Java API (Application Programming Interface)

Packages For purposes of accessing them, classes in the Java API are organized into packages These often overlap with specific APIs Examples: Package java.lang java.util java.text java.net javafx.scene.shape javafx.scene.control Purpose imported automatically, includes String and Math classes General support Utilities Text utilities (eg formatting) Network communication Graphical shapes GUI controls Copyright 2017 Pearson Education, Inc.

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, and then use just the class name import java.util.scanner; To import all classes in a particular package, you can use the * wildcard character import java.util.*; Copyright 2017 Pearson Education, Inc.

The Math Class The Math class is part of the java.lang package and contains methods for mathematical functions No need to import anything! The Math class methods are static Static methods are invoked through the class name value = Math.cos(phi) + Math.sqrt(delta); See Quadratic.java

Some methods from the Math class this slide excerpted from http://www.cs.princeton.edu/courses/archive/fall13/cos126/lectures/02-basics.pdf

The Random Class Part of the java.util package, so import it import java.util.random; Create a Random object named gen: Random gen = new Random(); Use Random method nextint()to generate a random number: int a = gen.nextint(4); // integer in range [0,1,2,3]

What is a random number? Anyone who considers arithmetical methods of producing random digits is, of course, in a state of sin. - John Von Neumann God does not play dice. - Albert Einstein The Random class provides methods that generate pseudorandom numbers

Summary: Generating pseudorandom numbers Random gen = new Random(); int a = gen.nextint(4); // integer in range [0,1,2,3] int b = gen.nextint(4) + 1; //int in range [1,2,3,4] int c = gen.nextint(); // int in range[-2147483648 2147483647] float d = gen.nextfloat(); //float in range [0,1),eg: 0.4589 double e = Math.random(); //double in range [0,1),eg: 0.4589 int f = (int) (Math.random() * 4); // integer in range [0,1,2,3] (same as a, above) See also RandomNumbers.java Math class method

Try this: 1) Randomly generated 4-digit code 2) Randomly generated 4-letter code Random gen = new Random();

Example: counting snake eyes // Roll two dice 100,000 times and count how many // times you roll snake eyes, i.e., two 1 s. Random gen = new Random(); int trial = 0, count = 0; while (trial < 100000) { } int die1 = gen.nextint(6) + 1; int die2 = gen.nextint(6) + 1; if (die1 == 1 && die2 == 1) trial++; count++; // snake eyes System.out.println ("Probablility of snake eyes = " + (double)count/100000);

Monte Carlo simulation example: approximate the value of π final long MAXPOINTS = 100000000; // number of random points long count = 0; long incirclecount = 0; // counts points inside circle double x, y; // points in interval (0,1) Random toss = new Random(); while (count < MAXPOINTS) { x = toss.nextdouble(); // toss y = toss.nextdouble(); if ((x*x + y*y) < 1) // inside unit circle incirclecount ++; count++; } double mypi = 4.0 * incirclecount / MAXPOINTS; System.out.println("Value of pi = " + mypi ); System.out.println("Math.PI = " + Math.PI + ");

The Strings Class Strings are objects defined by the String class "This is a string literal." "123 Main Street" "X" the String class has many methods that can be used to process text. Examples: finding the length of a string finding the char at a certain position of a string producing an all-caps version of a string

Invoking String Methods 0 1 2 3 4 name B e t s y String name = "Betsy"; As with other kinds of objects, we use the dot operator to invoke a String s methods: int numofcharsinname = name.length(); method in String class numofcharsinname

More String Methods String name = "Betsy"; name 0 1 2 3 4 B e t s y char initial = name.charat(0); initial String newname = name.replace('s', 't'); newname String capsname = name.touppercase(); capsname 0 1 2 3 4 0 1 2 3 4 int comp = name.compareto(newname); comp a.compareto(b) Compare strings, alphabetically: a>b è positive a=b è zero a<b è negative See also textbook example StringMutation.java

Example: Palindrome tester Problem: Input a string, determine whether it is a palindrome, i.e.: first char is the same as last char 2nd char is the same as 2nd last char and so on How to express this as an algorithm? How to implement it? str 0 1 2 3 4 R A D A R

http://www.csc.villanova.edu/~map/1051/chap05/palindrometester.java (Example from Chapter 5) System.out.println ("Enter a potential palindrome:"); str = scan.nextline(); left = 0; right = str.length() - 1; while (str.charat(left) == str.charat(right) && left < right) { left++; Sample Run right--; Enter a potential palindrome: } radar palindrome if (left < right) System.out.println ("NOT a palindrome"); Test another palindrome (y/n)? y else Enter a potential palindrome: System.out.println ("palindrome"); able was I ere I saw elba palindrome. Test another palindrome (y/n)? y Enter a potential palindrome: abracadabra NOT a palindrome. Test another CSC 1051 M.A. palindrome Papalaskari, Villanova (y/n)? University n

Declaring Variables, revisited Examples of variable declarations: int count = 0; double mpg; String title; Graphics page; Color aquamarine; Scanner scan; A class name can be used as a type to declare an object reference variable The object itself must be created separately

Creating Objects We have already seen something like this: Scanner scan = new Scanner (System.in); The new operator calls the Scanner constructor, which is a special method that sets up the object Variable refers to a Scanner object Constructing a new object is called instantiation an instance of the Scanner class

Creating Objects Another example: String title = new String ("Java Software Solutions"); The new operator calls the String constructor, which is a special method that sets up the object Variable refers to a String object Constructing a new object is called instantiation an instance of the String class

The String Class is SPECIAL! Exception to the use of new operator: Because strings are so common, we don't have to use the new operator to create a String object String title = new String ("Java Software Solutions"); String title = "Java Software Solutions"; This is special syntax that works only for strings

Wrapper classes Wrapper classes Integer, Double, Char, etc Useful constants, eg, Integer.MAX_VALUE Create objects of corresponding type (learn about this later) Static methods to convert between types, eg: Double.parseDouble("3.14") Integer.parseInt("54") etc System.out.print("Enter account number"); String line = scan.nextline(); // eg: 23 88 24 nospaces = line.replaceall(" ",""); // remove spaces int number = Integer.parseInt(noSpaces);// store as int

More Java Classes Formatting NumberFormat DecimalFormat many others Text processing Web development 3D Graphics Animation Scientific applications Multi-precision artithmetic Vendor specific APIs (eg Twitter or Facebook) Graphical user interface development (next week) and Much, much more!