Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String.

Similar documents
Getting started with Java

Object Oriented Programming: In this course we began an introduction to programming from an object-oriented approach.

JAC444 - Lecture 1. Introduction to Java Programming Language Segment 4. Jordan Anastasiade Java Programming Language Course

Programming refresher and intro to C programming

PROGRAMMING FUNDAMENTALS

Chapter 3: Operators, Expressions and Type Conversion

Index COPYRIGHTED MATERIAL

COMP-202. Recursion. COMP Recursion, 2011 Jörg Kienzle and others

USING LIBRARY CLASSES

JAVA OPERATORS GENERAL

Introduction to Programming (Java) 4/12

COMP 202 Recursion. CONTENTS: Recursion. COMP Recursion 1

Introduction to Programming Using Java (98-388)

Full file at

Decisions in Java IF Statements

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

PIC 20A Number, Autoboxing, and Unboxing

cis20.1 design and implementation of software applications I fall 2007 lecture # I.2 topics: introduction to java, part 1

CSC 1214: Object-Oriented Programming

String. Other languages that implement strings as character arrays

Operators and Expressions

Expressions & Flow Control

Chapter 2 Using Data. Instructor s Manual Table of Contents. At a Glance. Overview. Objectives. Teaching Tips. Quick Quizzes. Class Discussion Topics

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

Basic operators, Arithmetic, Relational, Bitwise, Logical, Assignment, Conditional operators. JAVA Standard Edition

Array. Prepared By - Rifat Shahriyar

Outline. Parts 1 to 3 introduce and sketch out the ideas of OOP. Part 5 deals with these ideas in closer detail.

Full file at

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

C08c: A Few Classes in the Java Library (II)

CMSC131. A Simple Problem?

Summer Final Exam Review Session August 5, 2009

Prof. Navrati Saxena TA: Rochak Sachan

VARIABLES AND TYPES CITS1001

Java characters Lecture 8

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

Topics. Chapter 5. Equality Operators

ECE 122 Engineering Problem Solving with Java

Infix to Postfix Conversion

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

Zheng-Liang Lu Java Programming 45 / 79

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

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

1 Epic Test Review 2 Epic Test Review 3 Epic Test Review 4. Epic Test Review 5 Epic Test Review 6 Epic Test Review 7 Epic Test Review 8

COMP519 Web Programming Lecture 12: JavaScript (Part 3) Handouts

Java Identifiers, Data Types & Variables

Java provides a rich set of operators to manipulate variables. We can divide all the Java operators into the following groups:

School of Computer Science CPS109 Course Notes 5 Alexander Ferworn Updated Fall 15

COMP-202. Recursion. COMP Recursion, 2013 Jörg Kienzle and others

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

Jump Statements. The keyword break and continue are often used in repetition structures to provide additional controls.

Ruby: Objects and Dynamic Types

Lecture Set 4: More About Methods and More About Operators

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

Full file at

Programming with Java

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

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

B.V. Patel Institute of BMC & IT, UTU 2014

Variables, Constants, and Data Types

CITS1001 exam 2013 SAMPLE SOLUTIONS O cial cover page to be substituted here. May 10, 2013

Bits, Words, and Integers

Building Java Programs

Java enum, casts, and others (Select portions of Chapters 4 & 5)

More on variables and methods

Operators. Java operators are classified into three categories:

LAB A Translating Data to Binary

String is one of mostly used Object in Java. And this is the reason why String has unique handling in Java(String Pool). The String class represents

CS Week 5. Jim Williams, PhD

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

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

Java Intro 3. Java Intro 3. Class Libraries and the Java API. Outline

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

COMP-202: Foundations of Programming. Lecture 2: Variables, and Data Types Sandeep Manjanna, Summer 2015

SECTION II: LANGUAGE BASICS

Stacks and Queues. David Greenstein Monta Vista

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

Advanced Java Concepts Unit 3: Stacks and Queues

Unit 2: Java in the small. Prepared by: Dr. Abdallah Mohamed, AOU-KW

CS112 Lecture: Characters and Strings

Types and Expressions. Chapter 3

Strings. Strings, which are widely used in Java programming, are a sequence of characters. In the Java programming language, strings are objects.

JAVA REVIEW cs2420 Introduction to Algorithms and Data Structures Spring 2015

Fall 2017 CISC124 9/16/2017

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

Java Bytecode (binary file)

Building Java Programs

AP CS Unit 7: Interfaces Exercises 1. Select the TRUE statement(s).

CMPT 125: Lecture 3 Data and Expressions

Course information. Petr Hnětynka 2/2 Zk/Z

ESc101 : Fundamental of Computing

Formatting Output & Enumerated Types & Wrapper Classes

Lab 14 & 15: String Handling

Object Oriented Methods : Deeper Look Lecture Three

CIS3023: Programming Fundamentals for CIS Majors II Summer 2010

Tha Java Programming Language

Join the course group CS230-S18! Post questions, answer them if you know the answer!

CIS 110: Introduction to Computer Programming

Lecture Set 4: More About Methods and More About Operators

Transcription:

CMSC 131: Chapter 21 (Supplement) Miscellany Miscellany Today we discuss a number of unrelated but useful topics that have just not fit into earlier lectures. These include: StringBuffer: A handy class for dealing with strings whose contents can vary dynamically. Java s Stack Data Structure: One of the simplest data structures in Java s class library. Java s Method Call Stack: How does Java keep track of local variables and parameter when methods are called? StringBuffer The problem with Strings: Strings are immutable objects. This means that once constructed it is not possible to change its contents. Example: Form a string by repeated concatenation: char[ ] c = { 'H', 'e', 'l', 'l', 'o' ; String s = ""; for ( int i = 0; i < c.length; i++ ) s += c[i]; This is quite inefficient because it produces one entirely new String object for each new assignment to s. Q: What is a more efficient way to do this? Ans: Store s as an expandable array of chars. (Double its size whenever we run out of space.) Cast the final array to a String. StringBuffer: Java offers just such a structure for you.

StringBuffer StringBuffer: A mutable representation of a string, which provides efficient methods for modifying the contents. Some StringBuffer Methods: StringBuffer( ) Constructs an empty string buffer. append( ) - Converts the argument into a string, and appends it to the end of the string buffer. (Possible arguments include boolean, char, double, float, int, long, Object, and char[ ].) charat( int index ) - Returns the character at the specified index. length( ) Returns the number of characters in the buffer. tostring( ) - Returns a String representation of the buffer. Example: StringBuffer b = new StringBuffer( ); b.append( 99.5 ); b.append( '%' ); b.append( " pure" ); System.out.println( b ); StringBuffer: Example Example: A method getwords which is given a string and strips off spaces and punctuation, converts words to lower-case, and outputs a string with the results. Java Class Library Utilities: String split: Splits a string about a given regular expression pattern. [abc] matches characters a, b, c. [abc]* matches 0 or more repetitions of these characters. [abc]+ matches 1 or more repetitions of these characters. To remove punctuation we split about 1 or more occurrences of space, comma, period, question mark: split( "[,.?]+" ) String tolowercase: Returns an equivalent lower-case string. String valueof: Produces a String representation of an object.

StringBuffer: Example public static String getwords( String s ) { String[ ] words = s.split( "[,.?]+"); StringBuffer buffer = new StringBuffer( ); for ( int i = 0; i < words.length; i++ ) { buffer.append( words[i].tolowercase( ) ); if ( i < words.length-1 ) buffer.append( " " ); return String.valueOf( buffer ); public static void getwordstest( ) { String s1 = "Do you wake up in the morning feeling sleepy and grumpy?"; System.out.println ( "[" + getwords( s1 ) + "]" ); String s2 = "Then you must be Snow White."; System.out.println ( "[" + getwords( s2 ) + "]" ); Stacks Stack: A stack is an abstract data structure for storing a collection of items. Items can be inserted into the stack and removed from the stack, but the rule is the most recent item inserted is the first item to be removed. (Last in, first out) Intuition: Think of it like a stack of plates in a restaurant. Items: can be inserted (or pushed) onto the top of the stack. can be removed (or popped) off of the top of the stack. insertions/removals from other positions are not allowed. Stack Operations Stack Operations: An abstract (mathematical) stack supports: push(x): inserts item x at the top of the stack pop( ): removes the item at the top of the stack (if one exists) and returns its value. top( ): returns the value of the item at the top of the stack, without removing it. empty( ): returns true if the stack is empty Java s Stack class: (in java.util) Java provides a Stack, with the following corresponding operations. Stack( ): creates an empty stack push( Object x ): pushes x on the stack pop( ): pops the stack and returns its value. (Exception if empty) peek( ): returns (without removal) the top value of the stack. (Exception if empty) empty( ): returns true if the Stack is empty.

Java Memory Layout Memory Layout: We mentioned before that Java splits memory into two major sections: Local storage: This is where your local variables (including parameters) are stored. Heap: This is where all objects (created by new) are stored. Q: When one method calls another, how does Java save all the local variables until returning? Java Call Stack: The local variables for each method are stored on a stack. whenever a new method is called, its local variables (including parameters) are pushed onto the stack when the method returns, the local variables are popped off the stack (and hence are no longer accessible). Call Stack: Example public class CallStack { public static int numberlowercase( String thestr ) { int count = 0; for ( int i = 0; i < thestr.length( ); i++ ) if ( Character.isLowerCase( thestr.charat( i ) ) ) count++; return count; public static void stats( String str ) { int total = str.length( ); int lower = numberlowercase( str ); System.out.println( "String: " + str ); System.out.println( "Total count: " + total ); System.out.println( "Lower case count: " + lower ); public static void main( String[ ] args ) { CallStack.stats( "Que Bueno!" );

Call Stack: Example public static int numberlowercase( String thestr ) { int count = int i = public static void stats( String str ) { int total = int lower = numberlowercase( str ); public static void main( String[ ] args ) { CallStack.stats( "Que Bueno!" ); (Figure omitted) Operators Revisited Operators: We discussed various operators (+, -, *, <, ==, &&, ) earlier this semester. We omitted discussion of a few. Bitwise operators: Operate on values as binary numbers. Conditional operator: An if-then-else operator. Bitwise Operators: Recall that all quantities are stored as binary numbers in memory. For example: int x = 1037; // binary: 0010000001101 filled out to 32 bits char c = y ; // binary: 0000001111001 filled out to 16 bits boolean b = true; // binary: 1 You are not required to know how these conversions are performed. (It is covered in later courses.) Java s bitwise operators act on these binary representations. Bitwise Operators Java supports the standard bit operators: ~a: complement of a a & b: and (1 if both a and b are 1) a b: or (1 if either a and b are 1) a ^ b: exclusive or (1 if either a or b is 1, but not both)

Bitwise Operators Java s bitwise operators can be applied to any integral type: char, byte, short, int, long to Boolean When applied to integral types, the operations are applied bitwise: int a = 45; // a = 00101101 int b = 14; // b = 00001110 int c = a & b; // c = (00101101 & 00001110) = 00001100 (= 12) 00101101 00101101 00101101 & 00001110 00001110 ^ 00001110 00001100 00101111 00100011 Who uses these: They are used in often hardware-related tasks (device management) and have other surprising uses. (E.g.: Using exclusive-or you can swap to integers without a temporary.) Shift Operators Another common operation involves shifting bits left or right. a << b: Shift a left by b positions a >> b: Shift a right by b positions (filling with the sign bit) a >>> b: Shift a right by b positions (filling with 0 s) Notes: a must be integral type (byte, short,, long). b should be a nonnegative integral type. Sign bit: Because there is no - sign in binary, Java encodes negative numbers using a method called 2 s-complement representation. We will not discuss this, but a key element is that the leftmost bit, called the sign bit, is: 0 for positive numbers 1 for negative numbers We often want to keep the sign bit unchanged when shifting.

Shift Operators Example: Rather than use 32-bit int s, we use a 10-bit example. int a = // a = 1100101101 int b = 3; int c = a << b; // c = 0101101000 int d = a >> b; // d = 1111100101 int e = a >>> b; // e = 0001100101 int f = // f = 0100101101 int g = f >> b; // g = 0000100101 Conditional Operator Conditional Operator: This is a handy operator, which acts like a little if-then-else statement within an expression. boolean-condition? true-value : false-value Example: Absolute value method. If the argument x is negative, then return x, otherwise return x. Without conditional: public static int absvalue1( int x ) { if ( x < 0 ) return -x; else return x; With the conditional operator: you can put the whole expression on one line. public static int absvalue2( int x ) { return ( x < 0? -x : x );

Conditional Operator Example: Set max to the maximum of x and y. double max = (x > y)? x : y ; Example: If String s is zero, then set x to 0.0, and otherwise set it to 3*(z + 13.2): String s = double z = double x = s.equals( zero )? 0.0 : 3*(z + 13.2); ArrayList The Problem with Arrays: Resizing: Arrays are not suitable for situations where the size of the array changes frequently. Appending to an Array: if we reach the maximum capacity of an array and we need to add an element, we have to create a new array, copy over elements, and add the desire element. ArrayList: A class in the Java class library that implements a resizable array. It is part of the java.util package, and therefore an appropriate import statement is required. An ArrayList holds generic Object references. Each element is: a reference to any class object or array any primitive type, by first putting it in a wrapper, such as Integer. When an element is removed from the array, you must explicitly cast it back to its original type.

ArrayList Methods Some of ArrayList methods: ArrayList( ): Initializes an array list of size 0. add( Object obj ): Adds the object to the end of the array. (Automatically expands the array if needed.) add( int i, Object obj ): Adds the object at position i (and shifts remaining objects down to make room). The following return and object of type Object or Object[ ]. You must cast to the original type: remove( int i ): Removes the element at index i. (Shifts the remaining elements to close the gap.) get( int i ): Returns a reference to the element at index i. toarray( ): Returns a (standard) array with all the elements. clear( ): removes all the elements from ArrayList. size( ): returns the number of elements in ArrayList. ArrayList Example Here is an example using an ArrayList of Strings: ArrayList a = new ArrayList( ); a.add( new String( "Bob" ) ); // [Bob] a.add( new String( "Carol" ) ); // [Bob, Carol] a.add( 1, new String( "Ted" ) ); // [Bob, Ted, Carol] System.out.println( a.size( ) ); // prints: 3 String x = a.get( 2 ); // illegal: cannot convert Object to String String y = (String) a.get( 2 ); // okay: returns "Carol" a.clear( ); // clear it out System.out.println( a.size( ) ); // prints: 0