Strings - Strings in Java 1. String compare Since Strings...

Info iconThis preview shows pages 1–3. Sign up to view the full content.

View Full Document Right Arrow Icon
Strings in Java 1. String compare Since Strings are variable length, the Java compiler doesn't know how much room to allocate to a String field in your program. (Unlike an int field, which is 4 bytes, a String might be thousands of bytes.) So, in Java, a String is a separate object, and the compiler puts a pointer to it (4 bytes), called an "object reference" in Java, in your program. So when you say String name = "Alice B Toklas"; the compiler puts a 4-byte field called name in your program that contains the address of the Java String object who's data field is "Alice B Toklas". Then, when you later in your program say name = "Bubba"; the compiler replaces the address in the name field with the address of the Bubba String object. (The Alice String object is probably garbage- collected.) The answer to the question "How long is the name field?" is "4 bytes". Always 4 bytes. The length of a pointer field. The same as an int field. Now, if we have two int fields: int x = 5; int y = 7; and we use the expression if (x == y) . ..
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full DocumentRight Arrow Icon
we of course expect the compiler to generate code to compare the contents of the x field to the contents of the y field. Now, if we have two String fields: String input = keyboard.readLine(); String stopString = "EXIT"; and we use the expression if (input == stopString) . .. guess what? Yup. The compiler generates code which compares the contents of the fields, which compares the address of the input String object to the address of the stopString object. This is no-doubt NOT what we want to do! So the String class (since it is a separate piece of code - an object at
Background image of page 2
Image of page 3
This is the end of the preview. Sign up to access the rest of the document.

This note was uploaded on 01/25/2010 for the course ECE 309 taught by Professor Bowman during the Spring '09 term at N.C. State.

Page1 / 5

Strings - Strings in Java 1. String compare Since Strings...

This preview shows document pages 1 - 3. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online