Unit 3: Discussion - Part 2
No unread replies.No replies.
Question
Read the lecture for Chapter 3, and then answer the following:
Chapter 3 introduces us to the String class. It shows some of the methods one can apply to this type of variable (i.e. length(), toLowerCase(), substring(), indexOf(), etc). This class has many more, all described in the Java documentation. Review these methods and present an example of their usage, properly written in Java code. Explain the purpose of your code and show a screen capture of the program running.
/****************************************StringExample.java********************************/
import java.util.Arrays;
public class StringExample {
public static void main(String[] args) {
/*
* Following method are very useful
in the String
*/
String example = "Hello, How are
you?";
// return the length of
string
System.out.println("String length
is: " + example.length());
// return the string in lower
case
System.out.println("String in lower
case: " + example.toLowerCase());
// return the string in upper
case
System.out.println("String in upper
case: " + example.toUpperCase());
// return the index of char in
string
System.out.println("String index of
perticular character: " + example.indexOf('w'));
// return the char present on
index
System.out.println("Char present on
index: " + example.charAt(9));
// return the substring
System.out.println("Sub string :" +
example.substring(0, 4));
// split method
System.out.println("String array
splitted by perticular char" +
Arrays.toString(example.split(",")));
// return the char array
System.out.println("Char array: " +
Arrays.toString(example.toCharArray()));
// return true or false if string
matched
System.out.println("String matched:
" + example.equals("Hello"));
// return true or false if string
matched with ignoring upper case or lower case
System.out.println("String mathed:
" + example.equalsIgnoreCase("hello, how are you?"));
// return true or false if string
contains some part of string which is given
System.out.println("String
contains: " + example.contains("Hello"));
// return true if string matches
some part of string
System.out.println("String match: "
+ example.matches("are"));
// to concating the string
System.out.println("String
concated: " + example.concat(" I'm fine!"));
}
}
/*********************************output************************************/
String length is: 19
String in lower case: hello, how are you?
String in upper case: HELLO, HOW ARE YOU?
String index of perticular character: 9
Char present on index: w
Sub string :Hell
String array splitted by perticular char[Hello, How are you?]
Char array: [H, e, l, l, o, ,, , H, o, w, , a, r, e, , y, o, u,
?]
String matched: false
String mathed: true
String contains: true
String match: false
String concated: Hello, How are you? I'm fine!
Please let me know if you have any doubt or modify the answer, Thanks :)
Get Answers For Free
Most questions answered within 1 hours.