Docsity

Lecture Notes on Miscellany - Objected-Oriented Program I | CMSC 131, Study notes of Computer Science

Toggle sidebar
bg1
CMSC 131: Chapter 21 (Supplement)
CMSC 131: Chapter 21 (Supplement)
Miscellany
Miscellany
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
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.
pf3
pf4
pf5
pf8
pf9

Partial preview of the text

Download Lecture Notes on Miscellany - Objected-Oriented Program I | CMSC 131 and more Study notes Computer Science in PDF only on Docsity!

CMSC 131: Chapter 21 (Supplement)CMSC 131: Chapter 21 (Supplement)

Miscellany Miscellany

MiscellanyMiscellany

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 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.

StringBufferStringBuffer

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 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.

Java Memory LayoutJava 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: ExampleCall 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: ExampleCall 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 RevisitedOperators 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 OperatorsBitwise 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)

Shift OperatorsShift 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

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 OperatorConditional 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 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.