Beruflich Dokumente
Kultur Dokumente
Memory Allocation
Declaration of a primitive data type prepares
memory to store a value of that type.
int num1;
variable name memory allocated to store an integer (4 bytes)
num1
12
0x0010
memory address
When a value is assigned to the variable num1, the value is stored at that memory location.
4
Memory Allocation
Declaration of a reference data type
prepares memory to store a memory address.
String s1;
variable name
s1
"Hello"
0x4h12
The memory address of the object will be stored in the space allocated for s1. memory address
5
Comparing Strings
A variable that is declared for a reference
data type only refers to a memory location for an object. "hi" s1 0x4h12 String s1 = new String("hi");
String s2 = new String("hi"); System.out.println(s1 == s2);
returns false because it is comparing the memory addresses 0x4h12 and 0x3121 0x4h12
s2 s3
0x3121
"hi"
0x3121
0x3121
returns true because it is comparing the memory addresses 0x3121 and 0x3121 (both s2 and s3 refer to the same object) returns true because the String method equals is used to compare Strings. 6
Declaring a String
Strings can be used to store names, titles, etc. We can declare a String data type by giving it a
variable name:
String name;
String Objects
When you declare a String using:
String subjectCode = new String(JSI1026");
String Methods
Assume that we have declared the String object: public int length()
returns the length of the String:
String Methods
public String toLowerCase()
returns a String that is the calling String converted to lowercase.
subjectCode.toLowerCase() returns the String jsi1026" Similarly for the method toUpperCase() public String trim() removes leading and trailing whitespace:
String whiteString = new String(" Lots of WhiteSpace "); 11 whiteString.trim() returns the String "Lots of WhiteSpace"
whiteString
L o t s
0 1 2 3 4 5 6 7
o f
8 9 1 0
Wh i t e S p a c e
11 1 2 1 3 1 4 1 5 1 6 1 7 1 8 1 9 2 0 2 1 2 2 2 3
positions of characters
Exercise
Consider the methods:
public int length() Returns the length of this string. public char charAt(int pos) Returns the character at the
specified index.
H a p p y N e w
Y e a r
15
Exercise
Write a program that asks for the user's name
and gender. If the gender is l' or L' then display "Halo Tuan XXX" or "Halo Nona XXX Sample run 1:
Please enter name: Lina Please enter gender: P Halo Nona Lina
Sample run 2:
Please enter name: Joko Please enter gender: L Halo Tuan Joko
16