CSE 215lab - 3
CSE 215lab - 3
Objective:
To learn different kinds String & Math class method
Java Strings:
String Concatenation
The ‘+’ operator can be used between strings to combine them. This is called concatenation:
John Doe
If you add a number and a string, the result will be a string concatenation:
public class Main {
public static void main(String[] args) {
String x = "10";
int y = 20;
String z = x + y;
System.out.println(z);
}
}
1020
Strings - Special Characters
Suppose we want to print this:
String txt = "We are the so-called "Vikings" from the north.";
To print quotation marks inside a string, we will need a special character: backslash escape
character (/).
public class Main {
public static void main(String[] args) {
String txt = "We are the so-called \"Vikings\" from the north.";
System.out.println(txt);
}
}
We are the so-called "Vikings" from the north.
String Methods
A String in Java is actually an object, which contain methods that can perform certain operations on
strings. The String class has a set of built-in methods that you can use on strings.
equals() Compares two strings. Returns true if the strings are equal, and false boolean
if not
indexOf() Returns the position of the first found occurrence of specified int
characters in a string
replace() Searches a string for a specified value, and returns a new string String
where the specified values are replaced
substring(startIndex) Returns a new string object from specified startIndex to end of the String
given string
substring(begIndex, returns a new String object containing the substring of the given String
endIndex) string from specified startIndex to endIndex.
floor(x) Returns the value of x rounded down to its nearest integer double
Task:
1) Compute the area of a hexagon using the following formula:
For example, for s1 = “apple” and s2=”app” , display the following output:
“The string “apple” starts with “app”.
3) Given a string, find the index of the second last occurrence of any vowel. For example, if your
string is “corresponding” , then return the index of ‘o’ which is the second last vowel (after ‘i’).
4) * (Take Home Task) Modify task 2 to check if two strings s1 and s2 are equal, or equal after
ignoring cases, or if s1 starts or ends with s2 (and vice versa), or if s2 is substring of s2 (or vice
versa). If none of these happen, display an appropriate message.
5.
(a) Generate two random numbers, lower and upper, within the range 1-1000. Random numbers
in Java can be generated by using the method Math.random().
e.g. To generate a random integer between min and max range:
int randNumber = (int)(min + Math.random() * (max – min + 1));
N.B. The (int) on the right hand side of the assignment operator is called type-casting.
(b) Write a program which will use while loop to print all the integers between lower and upper
which are divisible by 5 or 8 in descending order to the console in one line.