Unformatted text preview:

1Lecture 4Strings and ArraysStrings• Objects which encapsulate a fixed number of character values stored in a particular order• String – class predefined in the Java Development Kit (JDK), in the java.lang package– The java.lang package is loaded by default, no import statement is needed• Characters that can appear in Strings:– Letters (in any alphabet): “abc”– Digits: “123” != 123– Special characters: “.,;:><~`\/|{}+=_-()*&^%$#@!”– Escape sequences: “ \n \t \b \\ \” “• Note. It is character codes that are stored in memory !2Strings in memory• The simplified view is that a String occupies a contiguous area in the memory, in which each character occupies a locationString s = “ABCD”;• The reality is that the String variable is a separate entity, which contains a reference to the memory area that contains the characters• When passing Strings as parameters to methods, it is the reference that is passed– PassParam.javaA B C DsA B C Ds== vs. equals()• The operation == checks whether the references are equal, i.e. whether the two strings refer to the same location of memory• The methods String.equals() checks whether two Strings have the same content, i.e. the references are to areas in the memory that contain the same sequences of characters– String.equalsIgnoreCase();String s1 = new String(“ABCD”);String s2 = s1;String s3 = new String(s1);A B C DA B C Ds1s2s33Undefined, null, “”• If a String is declared, but not defined, it contains an undefined reference– String s;– Cannot be used without a value assigned !• null indicates an explicit reference to nothing ☺• “” is the empty String?sssString literal constants• Sequences of characters that appear between double quotes• The compiler creates a constant poolwhere it stores all the constants that appear in a program (not only Strings, but other types too)String s1 = “ABCD”;String s2 = “AB” + “CD”;String s3 = “A” + “BCD”;String s4 = new String(“ABCD”);A B C DA B C DConstant pools1s2s3s44Intern-ing Strings• Strings created at run-time (following String operations) are not in the constant pool– Consequence: You need to use equals() rather than ==for comparisons to other Strings• A new String can be added to the constant poolwith intern()– Advantage: in the future, == can be used for comparisons; this can increase efficiency, if many comparisons are needed.–Note. intern() uses equals() to check if the String is already in the pool; if many new Strings appear, intern-ing them may reduce efficiencyAccess to String characters• The length of a String (i.e. number of characters) is given by String.length()• The characters of a String are indexed with values between 0 and length() – 1• Individual characters of a String can be read with String.charAt(int index)String s = “ABCD”;for(int i = 0; i < s.length() – 1; i++)c.out.print(s.charAt(i));– StringIndexOutOfBoundsException– Access.java, BadAccess.javaA B C D0123Output: ABCD5Common operations on Strings• Lexicographic comparison– int String.compareTo(String other)• Lookup– int String.indexOf(int ch)– int String.indexOf(int ch, int fromIndex)– int String.indexOf(String other)– int String.indexOf(String other , int fromIndex)• They return the index in the String of the character or String that is looked up, or –1 if there is no match– lastIndex() searches backwards– startsWith(), endsWith() are more specific, and return boolean– Lookup.javaString immutability• Strings are immutable: their content cannot be changed !• Operations that apparently change String content in fact create new StringsString s = new String(“ABCD”);s = s + “EF”;// s references a different memory areaA B C DA B C DA B C DE Fss6“Changing” String contentString s = “abcdef”; // “abcdef”s = “A” + s.substring(1); // “Abcdef”s = s.substring(0, s.length( ) – 1) + "F“; // “AbcdeF”s = s.substring(0, 2) + “C” + s.substring(3); // “AbCdeF”s = s.replace(‘e’, ‘m’); // “AbCdmF”s = “ “ + s.concat(“t “); // “ AbCdmFt ”s = s.trim(); // “AbCdmFt”s = s.toLowerCase(); // “abcdmft”s = s.toUpperCase(); // “ABCDMFT”PassParam.java – methods that “change” String content should be functions !ExtractSubstrings.java“Changing” String content• The actual content does not change !• The apparent change in content is in fact a change of the reference• Methods that “change” String content should be functions that return a String reference !PassParam.java – passing Strings as parameters to methodsChangeString.java – test methods that “change”(reverse) Strings7Other useful tools• StringTokenizer – identifies tokens (substring) in String, based on delimiters– countTokens(), hasMoreTokens(), nextToken()• Conversion to array of characters– toCharArray(), getChars(…), getBytes()• Conversion from array of characters– copyValueOf()StringBuffer and efficiency• It is inefficient to repeatedly change String content by creating new Strings• StringBuffer comes to rescue:– Its constructor can take a String (to make a copy of the String to be modified)– StringBuffer has insert() and append() methods– StringBuffer.toString() returns a String when changes are done– Ex: Put the alphabet in a String – MillionChars.java8Conversions to String• byte b = 1 ;• short s = 2 ;• int i = 3 ;• long l = 4L ;• float f = 1.234F• double d = 4.321 ;• char c = 'A' ;• String bstr = "" + b ;• String sstr = "" + s ;• String istr = "" + i ;• String fstr = "" + f ;• String dstr = "" + d ;• String cstr = "" + c ;• String bstr = (new Byte(b)).toString( );• String sstr = (new Short(s)).toString( );• String istr = (new Integer(i)).toString( );• String lstr = (new Long(l)).toString( );• String fstr = (new Float(f)).toString( );• String dstr = (new Double(d)).toString( );• String cstr = (new Character(c)).toString( );• For classes of objects, the toString() method needs to be defined to allow concatenation to a String– Pt p = new Pt(100,100) ;– c.out.println("Point p = " + p) ;Conversions from String• These conversions are also possible thanks to class methods provided by the "wrapper" classes.– String bstr = "12" ;– String sstr = "123" ;– String istr = "123456" ;– String lstr = "123456789L" ;– String fstr = "1.234F" ;– String dstr = "4.321" ;–


View Full Document

Rutgers University ECE 202 - Lecture 4 Strings and Arrays

Download Lecture 4 Strings and Arrays
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Lecture 4 Strings and Arrays and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Lecture 4 Strings and Arrays 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?