Tutorial 07 - Tutorial
Tutorial 07 - Tutorial
Section A
1. String is a primitive data type. True or False?
2. Briefly describe the immutability of a string, and give one example:
String is not a primitive data type. False.
1. Using a string literal, write a program to reverse every character in the string.
String w = sc.nextLine();
System.out.print(w.charAt(i-1));
2. What is the output of the following code segments if the input is “University Kebangsaan
Malaysia”?
String str = sc.nextLine();
System.out.print(str.charAt(str.length()-1));
3. What is the output of the following code segments if the input is “University Kebangsaan
Malaysia”?
String str = sc.next();
System.out.print(str.length()-1);
Output : 9 (because str.length is the length of the string.) But, I have a question for this (29).
4. What is the output of the following code segments if the input is “Star Wars”?
String str = sc.nextLine(); int
k = str.indexOf(' ');
String newstr = str.substring(0, k);
System.out.print(newstr);
Output : Star
5. What is the output of the following code segments if the input is “Star Wars”?
String str = sc.nextLine(); char
ch = str.charAt(1);
System.out.print(ch);
Output : t
6. What is the output of the following code segments if the input is “kebangsaan”? strOrig =
sc.nextLine();
String strNew = strOrig.replaceAll("[an]", "");
System.out.println(strNew);
kebgs
7. What is the output of the following code segments if the input is “kebangsaan”? strOrig =
sc.nextLine();
String strNew2 = strOrig.replace("b","B");
System.out.println(strNew2);
System.out.println(str.length());
System.out.println(str.toUpperCase());
switch(str.charAt(i)) {
}
System.out.println(freq2);
switch(str.charAt(i)) {
case '1' :
case '2' :
case '3' :
case '4' :
case '5' :
case '6' :
case '7' :
case '8' :
case '9' :
case '0': freq1++;
break;
default : freq2++;
}
}
System.out.println(freq1);
switch(str.charAt(i)) {
default : freq2++;
}
}
System.out.println(freq1);
f. Replace all character ‘a’ in str to ‘*’ and store the new string in str2.
System.out.println(str2);
g. Remove all vowels in str and store the new string in str2.
}
System.out.println(str2);
}
2. Write code segments that reads 12-digit Mykad number and display the person's gender.
If the last digit is even number, then the person’s gender is female and otherwise is male.
For example, if the input is 971225561234 then the output is ‘Female’.
String m = sc.nextLine();
if(str.CharAt(m.length-1) % 2 ==0) {
System.out.println("Female");
}
else
System.out.println("Male");
If(str.CharAt(str.length-1) % 2 ==0){