string an example of reference data type. 2 primitive data types the eight java primitive data...
TRANSCRIPT
STRINGSTRINGAN EXAMPLE OF REFERENCE AN EXAMPLE OF REFERENCE
DATA TYPEDATA TYPE
22
Primitive Data TypesPrimitive Data Types The eight Java primitive data types are:The eight Java primitive data types are:
bytebyte shortshort intint longlong floatfloat doubledouble charchar booleanboolean
We can use the following operators with primitive data We can use the following operators with primitive data types:types: arithmetic operators: *, /, %, +, -arithmetic operators: *, /, %, +, - relational operators: >, >=, <, <=, ==, !=relational operators: >, >=, <, <=, ==, != logical operators: !, &&, || logical operators: !, &&, ||
33
Primitive vs Reference Data TypesPrimitive vs Reference Data Types
A Primitive type is one that holds a simple, A Primitive type is one that holds a simple, indecomposable value, such as:indecomposable value, such as: a single numbera single number a single charactera single character
A Reference type is a type for a A Reference type is a type for a classclass:: it can hold objects that have data and methods it can hold objects that have data and methods
Reference data types are stored in memory Reference data types are stored in memory differently from primitive data types.differently from primitive data types.
44
Memory AllocationMemory Allocation
Declaration of a primitive data type prepares Declaration of a primitive data type prepares memory to store a value of that type.memory to store a value of that type.
int num1; num10x0010
memory address
memory allocated to store an integer (4 bytes)
variable name
int num1 = 12;
When a value is assigned to the variable num1, the value is stored at that memory location.
12
55
Memory AllocationMemory Allocation Declaration of a Declaration of a referencereference data type data type
prepares memory to store a prepares memory to store a memory addressmemory address..
String s1; s10x0010
memory address
memory allocated to store an memory address
variable name
The new operator allocates memory to store the actual object.
s1 = new String("Hello"); 0x4h12
"Hello"
The memory address of the object will be stored in the space allocated for s1.
0x4h12
memory address
66
Comparing StringsComparing Strings
A variable that is declared for a reference A variable that is declared for a reference data type only data type only refersrefers to a memory location to a memory location for an object. for an object.
String s1 = new String("hi"); s1
s2
0x4h12
0x3121
"hi"
"hi"0x3121
0x4h12
returns false because it is comparingthe memory addresses 0x4h12 and 0x3121
String s3 = s2;
s3 0x3121
returns true because it is comparing the memory addresses 0x3121 and 0x3121 (both s2 and s3 refer to the same object)
String s2 = new String("hi");
System.out.println(s1 == s2);
System.out.println(s2 == s3)
System.out.println(s1.equals(s2) returns true because the String method equals is used to compare Strings.
77
The The StringString Data Type Data Type
A A String String type is an example of a reference data type is an example of a reference data type.type.
A string is defined as a sequence of characters.A string is defined as a sequence of characters. Examples of String literals:Examples of String literals:
" " (space, not the character ' ')" " (space, not the character ' ') "" (empty String)"" (empty String) "a""a" "HELLO" "HELLO" "This is a String""This is a String" "\tThis is also a String\n""\tThis is also a String\n"
88
Declaring a StringDeclaring a String
Strings can be used to store names, titles, etc.Strings can be used to store names, titles, etc. We can declare a String data type by giving it a We can declare a String data type by giving it a
variable name:variable name: String name;String name;
We can also initialize the variable upon We can also initialize the variable upon declaration:declaration: String subjectCode = “JSI1026";String subjectCode = “JSI1026";
Because String is a class type, the correct way Because String is a class type, the correct way to declare it is to use the to declare it is to use the newnew operator: operator: String subjectCode = String subjectCode = newnew String(“JSI1026"); String(“JSI1026");
99
String ObjectsString Objects
When you declare a String using:When you declare a String using: String subjectCode = String subjectCode = newnew String(“JSI1026"); String(“JSI1026");
The String The String subjectCodesubjectCode refers to a String refers to a String objectobject. .
String String objectsobjects have have data : they hold a sequence of charactersdata : they hold a sequence of characters methods : the data can be manipulated in a certain methods : the data can be manipulated in a certain
way.way.
We will look at some of the more common We will look at some of the more common methods associated with Strings.methods associated with Strings.
1010
String MethodsString Methods Assume that we have declared the String object:Assume that we have declared the String object:String subjectCode = String subjectCode = newnew String(“JSI1026"); String(“JSI1026");
public int public int lengthlength()() returns the length of the String:returns the length of the String: subjectCode.subjectCode.lengthlength()() returns the value 6 returns the value 6
public booleanpublic boolean equalsequals((AnotherStringAnotherString)) checks if the calling string is equal to checks if the calling string is equal to AnotherStringAnotherString subjectCode.subjectCode.equalsequals(“JSI1029") (“JSI1029") returnsreturns falsefalse
public boolean public boolean equalsIgnoreCaseequalsIgnoreCase((AnotherStringAnotherString)) checks if it is equal to checks if it is equal to AnotherStringAnotherString, , considering lowercase and considering lowercase and
uppercase letters to be equal.uppercase letters to be equal. subjectCode.subjectCode.equalsIgnoreCaseequalsIgnoreCase(“jsi1026")(“jsi1026")
returns returns truetrue
1111
String MethodsString Methods public String public String toLowerCasetoLowerCase()()
returns a String that is the calling String converted to returns a String that is the calling String converted to lowercase.lowercase.
subjectCode.toLowerCase()subjectCode.toLowerCase() returns the returns the String String “jsi1026"“jsi1026"
Similarly for the method Similarly for the method toUpperCasetoUpperCase()() public String public String trimtrim()() removes leading and removes leading and
trailing whitespace:trailing whitespace:String whiteString = new String(" Lots of WhiteSpace String whiteString = new String(" Lots of WhiteSpace ");");
whiteString.trim()whiteString.trim() returns the String returns the String "Lots of WhiteSpace""Lots of WhiteSpace"
1212
public char charAt(int public char charAt(int PositionPosition)) returns the character at returns the character at PositionPosition.. whiteString.whiteString.charAt(6)charAt(6) returnsreturns 's' 's'
public Stringpublic String substringsubstring(int (int StartStart)) returns a String beginning from returns a String beginning from StartStart whiteString.substring(11)whiteString.substring(11) returns returns "WhiteSpace ""WhiteSpace "
public String public String substringsubstring(int (int Start, Start, int int EndEnd) ) returns a String beginning atreturns a String beginning at Start Start up until just beforeup until just before EndEnd whiteString(3,7) whiteString(3,7) returnsreturns "Lots" "Lots"
public int public int indexOfindexOf(String (String A_StringA_String) ) returns the first position ofreturns the first position of A_StringA_String if found,if found, -1 -1 if not found.if not found. indexOf("it")indexOf("it") returns 13 returns 13
LL oo tt ss oo ff WW hh ii tt ee SS pp aa cc ee00 11 22 33 44 55 66 77 88 99 11
001111
1122
1133
1144
1155
1166
1177
1188
1199
2200
2211
2222
2233
positions of characters
whiteString
1313
(More) String Methods(More) String Methods public intpublic int compareTo(compareTo(A_StringA_String))
compares the string tocompares the string to A_StringA_String lexicographically lexicographically and returns a –ve number if the calling string comes and returns a –ve number if the calling string comes first, 0 if they are equal and a +ve number if first, 0 if they are equal and a +ve number if A_StringA_String comes first. comes first.
public boolean endsWith(public boolean endsWith(A_StringA_String)) returns returns truetrue if the string ends with if the string ends with A_String, A_String, false false otherwise.otherwise.
public boolean startsWith(public boolean startsWith(A_StringA_String)) returns returns truetrue if the string starts with if the string starts with A_StringA_String.. see example: see example: StringExamples.javaStringExamples.java
1414
Example – the String classExample – the String class
Let's consider some of the String methods we Let's consider some of the String methods we have considered previously:have considered previously: public boolean equals(String anotherString) public boolean equals(String anotherString) public boolean equalsIgnoreCase(String public boolean equalsIgnoreCase(String
otherString)otherString)
String s1 = new String("Hello"); // String objects s1String s2 = new String("hello"); // and s2 created System.out.println("Two strings equal " + s1.equals(s2));System.out.print("Ignoring case: "+ s1.equalsIgnoreCase(s2));
the method is invokedby the String object s1.
1515
ExerciseExercise
Consider the methods:Consider the methods: public int length()public int length()
Returns the length of this string.Returns the length of this string.
public char charAt(int pos)public char charAt(int pos) Returns the character at the Returns the character at the specified index.specified index.
Write a program that displays the Write a program that displays the String "Happy New Year", one String "Happy New Year", one character per line.character per line.
Happy
New
Year
see NewYearGreeting.java
1616
ExerciseExercise Write a program that asks for the user's name Write a program that asks for the user's name
and gender. If the gender is ‘l' or ‘L' then display and gender. If the gender is ‘l' or ‘L' then display "Halo Tuan "Halo Tuan XXXXXX" or "Halo Nona " or "Halo Nona XXXXXX“ “
Sample run 1:Sample run 1:Please enter name: LinaPlease enter name: Lina
Please enter gender: PPlease enter gender: P
Halo Nona LinaHalo Nona Lina
Sample run 2:Sample run 2:Please enter name: Joko Please enter name: Joko
Please enter gender: LPlease enter gender: L
Halo Tuan JokoHalo Tuan Joko