Implement a program to accomplish the following task using string / string Buffer class.
In this program, we will do the following:
- Accept a password from user.
- Check if password is correct then display "Good" Else display "Incorrect password"
- Append the password with the string "Welcome to java!!!"
- Display the password in reverse order.
- Replace the character '!' in password with "*" character.
String str = "abc"; // Creates a string literal
OR
String str = new String("abc");
A StringBuffer class is like a String, but can be modified. StringBuffer class is mutable. StringBuffer is fast and consumes less memory when you concat strings. For example,
// Constructs string buffer with no characters in it
// and an initial capacity of 16 characters.
StringBuffer s1 = new StringBuffer( );
OR
// Constructs a string buffer that contains the three characters.
// The initial capacity of the string buffer is 16 plus
// the length of the "abc" string in short it is 19.
StringBuffer s2 = new StringBuffer("abc");
We have used the following methods of String class:
- compareTo(String anotherString) : It compares two strings lexicographically.
- replace(char oldChar, char newChar) : Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
We have used the following methods of StringBuffer class:
- append(String str) : It appends the specified string to the character sequence.
- reverse( ) : It causes the character sequence to be replaced by the reverse of the sequence.
PROGRAM
import java.lang.*;
import java.io.*;
class StringActivity {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s1 = "admin!";
String s2;
System.out.println ("Enter Password");
s2 = br.readLine();
if(s1.compareTo(s2)==0) {
System.out.println ("Good");
}
else {
System.out.println ("Password is incorrect");
System.exit(0);
}
String s3 = "Welcome to Java!!!";
StringBuffer sb = new StringBuffer(s1);
sb.append(s3);
System.out.println ("Appended Password = "+sb);
StringBuffer s4 = new StringBuffer(s1);
s4=s4.reverse();
System.out.println ("String in Reverse Order = "+s4);
System.out.println ("Replaced '!' with '*' = "+s1.replace('!','*'));
}
}
OUTPUT
C:\>javac StringActivity.java C:\>java StringActivity Enter Password admin! Good Appended Password = admin!Welcome to Java!!! String in Reverse Order = !nimda Replaced '!' with '*' = admin*