A string is a sequence of characters. In Java, a string is an object.
The String class has 11 constructors and more than 40 methods for manipulating strings. (Click here to see List of String methods)
Use a syntax:
String newString = new String(stringLiteral);
stringLiteral is a sequence of characters enclosed inside double quotes. For example:
String message = new String("Save the world! ");
Java treats a string as an object. So, the following statement is valid:
String message = "make a better place ";
You can also create a string from an array of characters. For example:
char[] charArray = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n', 'i', 'n', 'g'};
string message = new String(charArray);
A String object is immutable, meaning that its contents cannot be changed.
For example:
String s = "Java";
s = "C++";
The first statement creates a String object with content "Java" and assigns its reference to s.
The second statement creates new String object with the content "C++" and assigns its reference to s.
The first String object still exists after the assignment, but it can no longer be assessed, because variable s now points to the new object.
Since strings are immutable and are ubiquitous in programming, to improve efficiency and save memory, the JVM uses a unique instance for string literals with the same character sequence.
Such an instance is called interned. For example:
String str1 = "Hello World";
String str2 = new String "Hello World";
String str3 = "Hello World";
System.out.println("str1 == str2 is " + (str1 == str2));
System.out.println("str1 == str3 is " + (str1 == str3));
the output will be:
str1 == str2 is false
str1 == str3 is true
because, str1 and str3 refer to the same interned string "Hello World", therefore str1 == str3 is true.
However str1 == str2 is false because str1 and str2 are two different string objects, even though they have the same contents.
a) method equals
To find out whether two strings variables have the same contents, use method equals:
if (str1.equals(str2))
System.out.println("str1 and str2 have the same contents");
else
System.out.println("str1 and str2 are not equal");
Write a program that will count the words in sentences.
Scanner sc = new Scanner(System.in);
String str = " ";
int count = 0;
while (!str.equals("#")){
str = sc.next();
count++;
}
System.out.println("Number of words: " + count);
Let say the input is:
We’re a happy family #
Then, the output will be:
Number of words: 5
b) method compareTo
Example:
if (str1.compareTo(str2))
System.out.println("str1 and str2 have the same contents");
else
System.out.println("str1 and str2 are not equal");
If using operator ==:
if (str1 == str2)
System.out.println("str1 and str2 are the same object");
else
System.out.println("str1 and str2 are different object");
The operator == checks only whether str1 and str2 refer to the same object; it does not tell you whether str1 and str2 contain the same contents.
2. Get The String's Length
You can get the length of a string by invoking its length() method. For example:
int lenStr = str.length();
Example:
import java.util.Scanner;
public class StrLength{
public static void main(String[] args){
String str = "We’re a happy family";
int lenStr = str.length();
System.out.println("The string length is " + lenStr);
}
}
The output is:
The string length is 20
3. Retrieve a Specific Character in a String
Use charAt(index) method to retrieve a specific character in a string, for example:
str = "try hard";
System.out.println(str.charAt(0)+ " and " + str.charAt(5));
Then, the output will be :
t and a
String is an array of char. Thus, the first index of string is index 0 and the last index is str.length-1.
Write a program that counts the number of times vowels appear in a given string.
String str = "java is the best";
int count = 0;
for (int x=0; x<str.length(); x++){
switch (str.charAt(x)) {
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++; break;
default: // no count increment
}
}
System.out.println("Number of vowels: " + count);
The output:
Number of vowels: 5
Write a program that prompts the user to enter a string and reports whether the string is a palindrome. One solution is to check whether the first character in the string is same as the last character. If so, check whether the second character is the same as the second-to-last character. This process continues until a mismatch is found or all the characters in the string are checked, except for the middle character if the string has an odd number of characters.
To implement this idea, we can use two variables, say low and high, to denote the position of two characters at the beginning and the end in a string s.
public class Palindrome{
public static void main(String[] args) {
String s = "racecar";
if (isPalindrome(s))
System.out.println(s + " is a palindrome.");
else
System.out.println(s + " is not a palindrome.");
}
// method isPalindrome
public static boolean isPalindrome(String s){
int low = 0;
int high = s.length()-1;
while (low < high){
if (s.charAt(low) != s.charAt(high))
return false; // not a palindrome
low++;
high--;
}
return true;
}
}
The output will be:
racecar is a palindrome.
4. Combining the Strings
Use concat method to concatenate two strings. For example:
String str1 = "Save the world! ";
String str2 = "make a better place.";
String str3 = str1.concat(str2);
So, your output will be:
Save the world! make a better place.
You can also use '+' operator, for example:
String str1 = "Hello ";
String str2 = "World";
String str3 = str1 + str2;
Your output will be:
Hello World
5. Obtaining substrings
Use substring method, for example:
String message = "Welcome to Java".substring(0, 11) + "HTML";
The string message now becomes "Welcome to HTML", because the substring(0,11) will retrieve substring from index 0 till 11 which is "Welcome to ". Then it concatenate with string "HTML".
Example:
String message = "Welcome to Java";
System.out.println("The massage is " + message);
message = message.substring(0, 11) + "HTML";
System.out.println("The new massage is " + message);
Your output will be:
The message is Welcome to Java
The new message is Welcome to HTML
The toLowerCase method is used to convert the string to lowercase and toUpperCase method is used to convert the string to uppercase letter.
Example:
String newStr = "Welcome".toLowerCase();
System.out.println(newStr);
System.out.println("Welcome".toUpperCase());
The output will be:
welcome
WELCOME
The trim() method will eliminates leading and trailing spaces.
Example:
System.out.println(" Welcome");
System.out.println(" Welcome".trim());
The output will be:
Welcome
Welcome
The replace method are provided to replace a character or a substring in the string with a new character or a new substring.
Example:
System.out.println("Welcome".replace('e','A'));
str = "Welcome".replaceFirst("e", "AB");
System.out.println(str);
System.out.println("Welcome".replace("e", "AB"));
System.out.println("Welcome".replace("el", "AB"));
The output will be:
WAlcomA
WABlcome
WABlcomAB
WABcome
public class DropVowel {
public static void main(String args[])
{
String str1, str2;
Scanner sc = new Scanner(System.in);
System.out.print("Enter a String : ");
str1 = sc.nextLine();
str2 = str1.replaceAll("[aeiouAEIOU]", "");
System.out.print("The new string : " + str2.trim());
}
}
The output will be:
Enter a String : Happy Birthday To You
The new string : Hppy Brthdy T Y
The split method can be used to extract tokens from a string with the specified delimiters.
Example:
String[] message = "One#Two#Three".split("#",0);
for (int i=0; i<message.length; i++)
System.out.print(message[i] + " ");
will displays
One Two Three
Example: Count the Number of Words Using Splitting
public class CountWords2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String words = "One Two Three Four";
int countWords = words.split("\\s").length;
System.out.println(countWords);
}
}
The output:
4
The matches method is very similar to the equals method. For example; the following two statements both evaluate to true.
"Java".matches("Java");
"Java".equals("Java");
However, the matches method is more powerful. it can match not only a fixed string, but also a set of strings that follow a pattern. For example; the following statements all evaluate to true.
"Java is fun".matches("Java.*")
"Java is cool".matches("Java.*")
"Java is powerful".matches("Java.*")
"Java.*" in the statements describes a string pattern that begins with Java followed by any zero or more characters.
11. Finding a Character or a Substring in a String
The indexOf and lastIndexOf methods to find a character or a substring in a string.
For example:
"Welcome to Java".indexOf('W') returns 0.
"Welcome to Java".indexOf('o') returns 4.
"Welcome to Java".indexOf('o', 5) returns 8.
"Welcome to Java".indexOf("come") returns 3.
"Welcome to Java".indexOf("Java", 5) returns 11.
"Welcome to Java".indexOf("java", 5) returns -1.
"Welcome to Java".lastIndexOf('W') returns 0.
"Welcome to Java".lastIndexOf('o') returns 8.
"Welcome to Java".lastIndexOf('o', 5) returns 4.
"Welcome to Java".lastIndexOf("come") returns 3.
"Welcome to Java".lastIndexOf("Java", 5) returns -1.
"Welcome to Java".lastIndexOf("java", 5) returns -1.
12. Conversion between Strings and Arrays
Strings are not arrays, but a string can be converted into an array and vice versa. To convert a string to an array of characters, use the toCharArray method. For example, the following statement converts the string "Java" to an array.
char[] chars = "Java".toCharArray();
So, chars[0] is 'J', chars[1] is 'a', chars[2] is 'v', and chars[3] is 'a'.
The static valueOf method can be used to convert an array of characters into a string.
int num = 30;
System.out.println(num + 10);//add num with 10
String s1=String.valueOf(num); // convert into string
System.out.println(s1+10);//concatenating string with 10
The output will be:
40
3010
java.lang.Character
+Character(value: char)
+charValue(): char
+compareTo(anotherCharacter: Character): int
+equals(anotherCharacter: Character): boolean
+isDigit(ch: char): boolean
+isLetter(ch: char): boolean
+isLetterOrDigit(ch: char): boolean
+isLowerCase(ch: char): boolean
+isUpperCase(ch: char): boolean
+toLowerCase(ch: char): char
+toUpperCase(chL char): char
Example: The Shift Cypher
In cryptography, the shift cipher is also known as Caesar's cipher, Caesar's code or Caesar shift. It is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For example, with a left shift of 3, D would be replaced by A, E would become B, and so on. The method is named after Julius Caesar, who used it in his private correspondence.
The transformation can be represented by aligning two alphabets; the cipher alphabet is the plain alphabet rotated left or right by some number of positions. For instance, here is a Caesar cipher using a left rotation of three places, equivalent to a right shift of 23 (the shift parameter is used as the key):
Plain: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Cipher: XYZABCDEFGHIJKLMNOPQRSTUVW
When encrypting, a person looks up each letter of the message in the "plain" line and writes down the corresponding letter in the "cipher" line.
Plaintext: THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG
Ciphertext: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD
Write a program to encrypt the plain text into cypher text.
public class ShiftCypher {
public static void main(String[] args) {
String plainText = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
String msg = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // the original sequence
String code = "XYZABCDEFGHIJKLMNOPQRSTUVW"; // the new sequence
String secretText = ""; // the encrypted text
for (int i=0; i<plainText.length(); i++) {
boolean dontEncode = true;
for (int j=0; j<msg.length(); j++) {
if (plainText.charAt(i) == msg.charAt(j)) {
secretText = secretText + code.charAt(j);//encrypt each char
dontEncode = false;
break;
}
}
if (dontEncode)
secretText = secretText + plainText.charAt(i);
}System.out.println("After: " + secretText);
}
}
The output will be:
After: QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD