Ohad Barzilay and Oranit Dror

Similar documents
Object-Oriented Programming with Java

תוכנה 1 3 תרגול מס' מערכים ומבני בקרה

תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Array Creation and Initialization. Loop through Arrays

תוכנה 1 מערכים. Array Creation and Initialization. Array Declaration. Loop through Arrays. Array Creation and Initialization

Discover how to get up and running with the Java Development Environment and with the Eclipse IDE to create Java programs.

CS Programming I: Arrays

String. Other languages that implement strings as character arrays

- Thus there is a String class (a large class)

Introduction to Programming Using Java (98-388)

CS 112 Introduction to Computing II. Wayne Snyder Computer Science Department Boston University

Pace University. Fundamental Concepts of CS121 1

Definition: Data Type A data type is a collection of values and the definition of one or more operations on those values.

Intro to Strings. Lecture 7 COP 3252 Summer May 23, 2017

STRINGS AND STRINGBUILDERS. Spring 2019

Computer Programming, I. Laboratory Manual. Final Exam Solution

Computer Science II (20082) Week 1: Review and Inheritance

High Performance Computing

This exam is open book. Each question is worth 3 points.

Computer Science II Data Structures

Index COPYRIGHTED MATERIAL

Strings and Arrays. Hendrik Speleers

Exam 1 Prep. Dr. Demetrios Glinos University of Central Florida. COP3330 Object Oriented Programming

array Indexed same type

Array. Array Declaration:

Lecture Notes: ESC 101

INDEX. A SIMPLE JAVA PROGRAM Class Declaration The Main Line. The Line Contains Three Keywords The Output Line

CSE 341 Section Handout #6 Cheat Sheet

1 If you want to store a letter grade (like a course grade) which variable type would you use? a. int b. String c. char d. boolean

Java Fundamentals (II)

Page 1

Programming Languages. Function-Closure Idioms. Adapted from Dan Grossman's PL class, U. of Washington

Handout 7. Defining Classes part 1. Instance variables and instance methods.

CO Java SE 8: Fundamentals

The Sun s Java Certification and its Possible Role in the Joint Teaching Material

More on Strings. Lecture 10 CGS 3416 Fall October 13, 2015

Selected Questions from by Nageshwara Rao

Testing Driven Development. Advanced Programming

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

Intro to Strings. Lecture 7 CGS 3416 Spring February 13, Lecture 7 CGS 3416 Spring 2017 Intro to Strings February 13, / 16

Lecture Notes CPSC 224 (Spring 2012) Today... Java basics. S. Bowers 1 of 8

Center for Computation & Louisiana State University -

Java s String Class. in simplest form, just quoted text. used as parameters to. "This is a string" "So is this" "hi"

Program Fundamentals

Initializers: Array initializers can be used with class base types as well. The elements of the initializer can be expressions (not just constants).

CHAPTER 7 OBJECTS AND CLASSES

Syntax and Variables

Brief Summary of Java

Birkbeck (University of London) Software and Programming 1 In-class Test Mar 2018

Object-Oriented Programming. Topic 2: Fundamental Programming Structures in Java

ECSE 321 Assignment 2

CS251L REVIEW Derek Trumbo UNM

Building Java Programs

Data Types. 9. Types. a collection of values and the definition of one or more operations that can be performed on those values

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

CSE1710. Big Picture. Today is last day covering Ch 6. Tuesday, Dec 02 is designated as a study day. No classes. Thursday, Dec 04 is last lecture.

CSI33 Data Structures

Building Java Programs

Asks for clarification of whether a GOP must communicate to a TOP that a generator is in manual mode (no AVR) during start up or shut down.

Language Features. 1. The primitive types int, double, and boolean are part of the AP

Building Java Programs

Mid Term Exam 1. Programming I (CPCS 202) Instructor: M. G. Abbas Malik Date: Sunday November 3, 2013 Total Marks: 50 Obtained Marks:

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

5/23/2015. Core Java Syllabus. VikRam ShaRma

Programming with Java

Class definition. complete definition. public public class abstract no instance can be created final class cannot be extended

Java Programming Language Mr.Rungrote Phonkam

BM214E Object Oriented Programming Lecture 8

Lab 14 & 15: String Handling

CS113: Lecture 3. Topics: Variables. Data types. Arithmetic and Bitwise Operators. Order of Evaluation

Java Foundations: Unit 3. Parts of a Java Program

COMP 110/L Lecture 13. Kyle Dewey

Getting started with Java

1 Shyam sir JAVA Notes

Building Java Programs. Chapter 2: Primitive Data and Definite Loops

Midterm I - CSE11 Fall 2013 CLOSED BOOK, CLOSED NOTES 50 minutes, 100 points Total.

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

Binghamton University. CS-140 Fall Problem Solving. Creating a class from scratch

CSC 1214: Object-Oriented Programming

Mutable and Immutable Objects

Java Identifiers, Data Types & Variables

In Java there are three types of data values:

AP Computer Science Chapter 10 Implementing and Using Classes Study Guide

Lecture 14. Dynamic Memory Allocation

Operators and Expressions

C++ Programming Assignment 3

Types, Operators and Expressions

CHAPTER 7 OBJECTS AND CLASSES

C212 Early Evaluation Exam Mon Feb Name: Please provide brief (common sense) justifications with your answers below.

Question 1 [20 points]

TEST (MODULE:- 1 and 2)

For instance, we can declare an array of five ints like this: int numbers[5];

Fall 2017 CISC124 9/16/2017

BITG 1113: Array (Part 2) LECTURE 9

Computer Science II (20073) Week 1: Review and Inheritance

CMIS 102 Hands-On Lab

Data abstractions: ADTs Invariants, Abstraction function. Lecture 4: OOP, autumn 2003

CS 149. Professor: Alvin Chao

Solutions to Quiz 1 (October 25, 2017)

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: Java Static Methods. Recap: Decomposition Example. Recap: Static Method Example

Transcription:

The String Class Represents a character string (e.g. "Hi") Implicit constructor: String quote = "Hello World"; string literal All string literals are String instances Object has a tostring() method More details in JDK 5.0 documentation http://java.sun.com/j2se/1.5.0/docs/

String Immutability Strings are constants String s = " Tea "; s = s.trim(); s = s.replace('t', 'S'); s 1 2 3 " Tea " A string reference may be set: String s = "Tea"; s = "Sea"; "Tea" s 1 2 "Sea" "Tea" "Sea"

String Interning Avoids duplicate strings String[] array = new String[1000]; for (int i=0 ; i<1000 ; i++) { array[i] = "Hello world"; 1 2 "Hello world" array 1000 An immutable string. Thus, can be shared.

String Interning (cont.) The String class has a static private pool of internal strings. mystring.intern() implementation: s pool : if mystring.equals(s) == true return s; else add mystring to the pool return mystring; equals: compares characters ==: compares references

String Interning (cont.) All string literals and string-valued constant expressions are interned. string literals "Hello" "World" "Hello" + "World" String Pool string-valued constant expression

String Interning (cont.) If: String s1 = "ab"; String s2 = "ab" + "ab"; String s3 = "aba" + "b"; s1 String s4 = s1 + s1; String s5 = s1 + s1; String s6 = s1 + "ab"; s2, s3 Then: s4.equals(s2) is true (s4 == s2) is false (s4 == s5) is false (s2 == s3) is true (s2 == s6) is false (s4.intern() == s2) is true (s4.intern() == s5.intern()) is true s4 s5 s6 "ab" "abab" "abab" "abab" "abab"

String Constructors Use implicit constructor: String s = "Hello"; (string literals are interned) Instead of: String s = new String("Hello"); (causes extra memory allocation)

Substrings Substrings are created without copying String.substring() is very efficient String smile = "smile"; String mile = "smile".substring(1,4); "smile" smile mile

The StringBuffer Class Represents a mutable character string Main methods: append() & insert() accept data of any type If: sb = new StringBuffer("123") Then: sb.append(4) is equivalent to sb.insert(sb.length(), 4). Both yields "1234"

The Concatenation Operator (+) String conversion and concatenation: "Hello " + "World" is "Hello World" "19" + 8 + 9 is "1989" Conversion by tostring() Concatenation by StringBuffer String x = "19" + 8 + 9; is compiled to the equivalent of: String x = new StringBuffer().append("19"). append(8).append(9).tostring();

StringBuffer vs. String Inefficient version using String: public static String duplicate(string s, int times) { String result = s; for (int i=1; i<times; i++) { result = result + s; return result; A new String object is created each time

StringBuffer vs. String (cont.) More efficient version with StringBuffer: public static String duplicate(string s, int times) { StringBuffer result = new StringBuffer(s); for (int i=1; i<times; i++) { result.append(s); return result.tostring(); no new Objects

StringBuffer vs. String (cont.) Much more efficient version: public static String duplicate(string s, int times) { StringBuffer result = new StringBuffer(s.length() * times); for (int i=0; i<times; i++) { result.append(s); return result.tostring(); created with the correct capacity

StringBuffer vs. StringBuilder StringBuilder class provides an API compatible with StringBuffer, but with no guarantee of synchronization. This class is designed for use as a drop-in replacement for StringBuffer in places where the string buffer was being used by a single thread (as is generally the case). Where possible, it is recommended that this class be used in preference to StringBuffer as it will be faster under most implementations.

Arrays Array: A fixed-length data structure for storing multiple values of the same type Example: An array of odd numbers: Indices (start from 0) 0 1 2 3 4 5 6 7 odds: 1 3 5 7 9 11 13 15 The type of all elements is int odds.length = 8 The value of the element at index 4 is 9: odds[4] == 9

Array Declaration An array is denoted by the [] notation Examples: int[] odds; int odds[]; // legal but discouraged String[] names; int[][] matrix; // an array of arrays matrix:

Array Creation and Initialization What is the output of the following code: int[] odds = new int[8]; for (int i=0 ; i < odds.length ; i++) { System.out.print(odds[i] + " "); odds[i] = 2*i+1; System.out.print(odds[i] + " "); Output: Array creation: all elements get the default value for their type (0 for int) 0 1 0 3 0 5 0 7 0 9 0 11 0 13 0 15

Array Creation and Initialization Creating and initializing small arrays with a-priori known values: int[] odds = {1,3,5,7,9,11,13,15; String months[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"; Jan months: String Pool

Loop through Arrays By promoting the array's index: for (int i=0 ; i < months.length ; i++) { System.out.println(months[i]); In Java 5.0: for (String month: months) { System.out.println(month); The variable month is assigned the next element in each iteration

Manipulating arrays The class has methods for sorting and searching arrays e.g. In the class:

Copying Arrays Naïve copy: int vec1[] = {1,2,3; int vec2[] = {8,7,6,5; vec1 = vec2; Doing it by hand is 8,7,6,5 1,2,3 inefficient vec2 arraycopy(vec2, 0, vec1, 0, 3); will replace 1,2,3 in vec1 with 8,7,6 vec1

Manipulating arrays (cont.) What is the output of the following code: int[] odds = {1,3,5,7,9,11,13,15; int[] newodds = new int[8]; System.arraycopy(odds, 1, newodds, 1, 7); for (int odd: odds) { System.out.print(odd + " "); Output: 0 3 5 7 9 11 13 15

Reading command line arguments class CommandLineDemo { public static void main(string args[]) { for (int i=0; i<args.length; i++) System.out.println("Argument number " + (i+1) + " is : " + args[i]); > java CommandLineDemo Apple Box Car Argument number 1 is : Apple Argument number 2 is : Box Argument number 3 is : Car

2 Dimensional Arrays There are no 2D arrays in Java but you can build array of arrays: char[] board[] = new char[3][]; for (int i = 0; i<3; i++) board[i] = new char[3]; Or equivalently: char[] board[] = new char[3][3]; board

2 Dimensional Arrays (con t) Building a Tic-Tac-Toe board: for (int i = 0; i < 3; i++) for (int j = 0; j < 3; j++) board[i][j] = (i + j) % 2 == 0? 'x' : 'o'; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { System.out.print(board[i][j] + " "); System.out.println(" ");