Lecture 5
Lecture 5
Lecture 5 – Switch,
String Operations & Static Methods
Output:
2nd
But why?
3rd
2th n is 2 so shouldn't it print out only "2nd"?
The switch statement
int n = 2;
switch (n) {
case 1:
System.out.println("1st");
case 2:
System.out.println("2nd");
case 3:
System.out.println("3rd");
default:
System.out.println(n + "th");
}
Output:
2nd
3rd It turns out that it is called a switch for this reason.
2th
The switch statement
int n = 2;
switch (n) {
case 1:
System.out.println("1st");
case 2:
System.out.println("2nd");
case 3:
System.out.println("3rd");
default:
System.out.println(n + "th");
}
Output:
2nd
The first case that is equal to n turns the switch on.
3rd
From that point, every statement is executed regardless of case.
2th
The switch statement
int n = 2; // a hard-coded value
switch (n) {
case 1:
System.out.println("1st");
break;
case 2:
System.out.println("2nd");
break;
case 3:
System.out.println("3rd");
break;
default:
System.out.println(n + "th");
}
"C:\\Temp\\Secret.txt" C:\Temp\Secret.txt
String comparison
• Use String.equals() method to compare 2 Strings
(case-sensitive)
String s = "Hello";
boolean b1 = s.equals("Hello"); // true
boolean b2 = s.equals("hello"); // false
Output:
3
-1
-1
0
More String operations
Method name Description
Tests if a string starts with the specified
startsWith(prefix)
prefix.
Tests if a string ends with the specified
endsWith(suffix)
suffix.
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Cars";
int order = s1.compareTo(s2); // -1, s1 < s2 by 1
int order2 = s1.compareTo(s3); // -2, s1 < s3 by 2
int order3 = s3.compareTo(s1); // 2, s3 > s1 by 2
Output:
Correct use:
Incorrect use:
int x = Scanner.nextInt();
Notes on the methods we use
• Some familiar static methods:
– Math.sqrt(), Math.pow(), Integer.parseInt()
• A static method is called from the name of the
class that contains it.
• Some familiar non-static methods:
– Scanner.nextInt(), String.substring(), String.charAt()…
• A non-static method is called from an instance of the
class that contains it.
Notes on the methods we use
• Within a class, methods can be called using only the
method name (without class name or instance).
– In a static method (or static context), we can only
directly call other static methods.
– In a non-static method, we can call both static and non-
static methods by name.
• The main method is static, so it can only call other
static methods within the same class.
– That's why, for the time being, for simplicity, all methods
that we create will be static.
Return
• To run/trigger a method, write its name like so:
getPositiveInt(); // as a statement
int a = getPositiveInt(); // as an expression
System.out.println(getPositiveInt()); // expression
int b = 5 + getPositiveInt(); // expression
Output:
51
Method (receiver)
Usage:
Example: isVowel()
• A vowel is one of a, e, i, o, u and y:
Example: isVowel()
Example: sqrt()
Example: code re-use