You are on page 1of 30

Enumerations:

Versions prior to JDK 5 lacked one feature that many programmers felt
was needed: enumerations.
 In its simplest form, an enumeration is a list of named constants.
Although Java offered other features that provide somewhat similar
functionality, such as final.
In their simplest form, Java enumerations appear similar to
enumerations in other languages.
 This keyword can be used similar to the static final constants.
Syntax:
enum enum_name
{ Data values }
Example: enum Days
{ Sunday, Monday, Tuesday, Wednesday, Thrusday, Friday,
Saturday
}
 The identifiers Sunday, Monday, and so on, are called enumeration constants.
 Each is implicitly declared as a public, static final member of Days.
 Once you have defined an enumeration, you can create a variable of that type.
 However, even though enumerations define a class type, you do not
instantiate an enum using new.
 Instead, you declare and use an enumeration variable in much the same way as
you do one of the primitive types.
 For example, this declares dy as a variable of enumeration type Days.
Days dy;
 Because dy is of type Days, the only values that it can be assigned (or can
contain) are those defined by the enumeration.
 For example, this assigns dy the value Sunday:
dy = Days.Sunday
The values( ) and valueOf( ) Methods:
All enumerations automatically contain two predefined methods:
values( ) and valueOf( ).
Their general forms are shown here:
public static enum-type[ ] values( )
public static enum-type valueOf(String str)
The values( ) method returns an array that contains a list of the
enumeration constants.
The valueOf( ) method returns the enumeration constant whose value
corresponds to the string passed in str.
• Two enumeration constants can be compared for equality by using the
= = relational operator.
• For example, this statement compares the value in dy with the
Saturday constant:
• if(dy == Days.Saturday)
• An enumeration value can also be used to control a switch statement.
• Of course, all of the case statements must use constants from the same
enum as that used by the switch expression.
• For example, this switch is perfectly valid:
// Use an enum to control a switch statement.
switch(dy) {
case Sunday:
// ...
case Monday:
// ...
String Handling:
• In Java a string is a sequence of characters.
• But, unlike many other languages that implement strings as
character arrays,
• Java implements strings as objects of type String.
• Java has methods to compare two strings, search for a substring,
concatenate two strings, and change the case of letters within a
string.
• when you create a String object, that cannot be changed.
• That is, once a String object has been created, you cannot
change the characters that comprise that string.
• At first, this may seem to be a serious restriction. So strings are
called immutable strings.
• Java provides two options: StringBuffer and StringBuilder.
• Both hold strings that can be modified after they are created.
• The String, StringBuffer, and StringBuilder classes are defined in
java.lang.
The String Constructors:
• The String class supports several constructors.
• To create an empty String, you call the default constructor.
• Eg: String s = new String();
• will create an instance of String with no characters in it.
• The String class provides a variety of constructors to handle this.
• To create a String initialized by an array of characters, use the
constructor shown here:
String(char chars[ ])
• Eg: char chars[ ] = { 'a', 'b', 'c' };
String s = new String(chars);
• This constructor initializes s with the string “abc”
• You can specify a sub range of a character array as an initializer using
the following constructor:
String(char chars[ ], int startIndex, int numChars)
• Here, startIndex specifies the index at which the sub range begins,
and numChars specifies the number of characters to use.
• Here is an example:
char chars[] = { 'a', 'b', 'c', 'd', 'e', 'f' };
String s = new String(chars, 2, 3);
• This initializes s with the characters “cde”.
• You can construct a String object that contains the same character
sequence as another String object using this constructor:
String(String strObj)
• Here, strObj is a String object.
char ch [ ] = {‘E’,’C’,’E’};
String s1 = new String(ch);
String s2 = new String(s1);
String Methods:
concat() substring()
length() toLowerCase()
charAt() toUpperCase()
compareTo() trim()
compareToIgnoreCase() split()
equals() getChars()
equalsIgnoreCase()
startsWith()
endsWith()
indexOf()
lastIndexOf()
replace()
concat():
This methods is used to concatenation of two strings.
Syntax:
String concat(String str); // str is string object

Eq: String s1 = “Hello”, s2 = “world”;


String s3 = s1.concat(s2); // Hello world
length():
This method is used to find the length of a string.
It returns integer value, count start from 1 to n.
Syntax:
int length();
String str = “Welcome to MRECW”;
int n = str.length(); // length method
charAt():
This method is used to retrive a character from a specified position.
It return a character.
Syntax:
char charAt(int i);
where ‘i’ is specified position
Eg: String str = “Final year ECED”;
char ch = str.charAt(6); // ‘y’ character displays
compareTo():
• This method compares to strings and to know which string is bigger or
smaller.
• It has this general form:
int compareTo(String str)
• Here, str is the String being compared with the invoking String.
• The result of the comparison is returned and is interpreted, as shown
here:
Value Meaning
First string is greater than It returns positive value
second string
First string is less than It returns negative value
second string
First string is equal to It returns zero value
second string

Eq: String s1 = "MRECW", s2 = “mrecw";


s1.compareTo(s2); // display’s negative value
• This is method is a case sensitive i.e BOX and box are two different
Strings. It returns integer value.
compareToIgnoreCase():
• This method compares to strings and to know which string is bigger
or smaller.
• This method is a case insensitive i.e BOX and box are same.
• It has this general form:
int compareToIgnoreCase(String str)
• Here, str is the String being compared with the invoking String.

• Eq: String s1 = "MRECW", s2 = “mrecw";


s1.compareTo(s2); // display’s Zero value
equals():

• This method compare two strings for equality, use equals( ).


• It has this general form:
boolean equals(String str)
• Here, str is the String object being compared with the invoking String
object.
• It returns true if the strings contain the same characters in the same
orde:r, and false otherwise. The comparison is case-sensitive.
• E.q: String s1 = "Hello";
String s2 = “hello";
s1.equals(s2); // It returns false.
equalsIgnoreCase():

• This method compare two strings for equality, use equals( ).


• It has this general form:
boolean equalsIgnoreCase(String str)
• Here, str is the String object being compared with the invoking String
object.
• It returns true if the strings contain the same characters in the same
order, and false otherwise. The comparison is case-insensitive.
• E.q: String s1 = "Hello";
String s2 = “hello";
s1.equalsIgnoreCase(s2); // It returns true.
startsWith():

• The startsWith( ) method determines whether a given String begins


Theywith a specified string.
• This method retuns boolean data value.
• have the following general forms:
boolean startsWith(String str)
• Here, str is the String being tested.
• If the string matches, true is returned. Otherwise, false is returned.
• This method is a case sensitive.
• Eq: String s1 = “Have a wonderful day”, s2 = “Have”;
s1.startsWith(s2); // it return true
endsWith():

• The endsWith( ) method determines whether a given String endswith


a specified string.
• This method retuns boolean data value.
• The following general forms:
boolean endsWith(String str)
• Here, str is the String being tested.
• If the string matches, true is returned. Otherwise, false is returned.
• This method is a case sensitive.
• Eq: String s1 = “Have a wonderful day”, s2 = “Have”;
s1.endsWith(s2); // it return false
indexOf():
• This method searches for the first occurrence of a character or
substring in a main string.
• This method returns integer value i.e location of occurrence
character or substring.
• If substring or character is not occur in main string it return negative
value.
• If multiple occurrence character or substring occur it will take first
occurrence location.
• The following general forms:
int indexOf(String str);
• Here str is String Object.
• Eg: String s1 = “this is a book”, s2 = “this”;
s1.indexOf(s2); // It display’s location 2
• This method is a case sensitive.
lastIndexOf():
• This method searches for the last occurrence of a character or
substring in a main string.
• This method returns integer value i.e location of occurrence
character or substring.
• If substring or character is not occur in main string it return negative
value.
• If multiple occurrence character or substring occur it will take last
occurrence location.
• The following general forms:
int lastIndexOf(String str);
• Here str is String Object.
• Eg: String s1 = “this is a book”, s2 = “is”;
s1.lastIndexOf(s2); // It display’s location 5
• This method is a case sensitive.
replace():

• This method replace the specified character in all occurrences in


string.
• This method returns string.
• The following general forms:
String replace(char original, char replacement)
• Here, original specifies the character to be replaced by the character
specified by replacement.
• The resulting string is returned.
• Eg: String s1 = “this is a book”;
s1.replace(‘i’ , ‘a’) // It display’s thas as a book
• This method is a case sensitive.
Substring():

• This method used to extract a substring from the main string.


• The following general forms:
String substring(int startIndex)
• Here, startIndex specifies the index at which the substring will begin.
• This form returns a copy of the substring that begins at startIndex and
runs to the end of the invoking string.
• The resulting string is returned.
• Eg: String s1 = “Have a nice day and wonderful day”;
s1.substring(6) // It display’s nice day and wonderful day
• Count starts from ‘0’.
Substring():
• This method used to extract a substring from the main string, but we
can specify startindex and endindex.
• It extract sub string form main string at specified location.
• The following general forms:
String substring(int startIndex, int endindex)
• Here, startIndex specifies the index at which the substring will begin
endindex specifies the index at which the substring will end.
• Endindex always -1.
• This form returns a copy of the substring that begins at startIndex and
ends at endindex.
• The resulting string is returned.
• Eg: String s1 = “Have a nice day and wonderful day”;
s1.substring(6,15) // It display’s nice day (6th to 14th )
• Count starts from ‘0’.
toLowerCase():
• The method toLowerCase( ) converts all the characters in a string
from uppercase to lowercase.
• It returns string.
• The General format.
String toLowerCase();
• Eg: String str = “MRECW”;
str.toLowerCase( ); // mrecw
toUpperCase():
• The method toUpperCase( ) converts all the characters in a string
from lowercase to uppercase.
• It returns string.
• The General format.
String toUpperCase();
• Eg: String str = “mrecw”;
str.toUpperCase( ); // MRECW
trim():
• This method used to remove white space from a string.
• It removes space before and after the string but not middle of the
string.
• The following general forms:
String trim();
• The resulting string is returned.
• Eg: String s1 = “ Have a nice day ”;
s1.trim(); // Have a nice day
getChars():
• This method used to copies characters from a string into character
array.
• The general form
void getChars(int start, int end, char arr[ ] , int index);
• Where start is the starting index, end is the ending index ( end-1) ,
arr[ ] array of characters stored in an array and index is array starting
location.
• Eg: String str = “welcome to java class”;
char ch[ ] = new char[20];
str.getChars(3,8,ch,0); // display’s come
System.out.println(ch);
“= =“ between equals() method:
• = = operator compares the reference of the string object. It does not
compare the contents of the objects.
• equals() methods compares the contents.
String Buffer:
• String represents fixed-length, immutable character sequences.
• In contrast, StringBuffer represents growable and writeable character
sequences.
• StringBuffer may have characters and substrings inserted in the
middle or appended to the end.
Creating StringBuffer:
• StringBuffer defines these four constructors:
StringBuffer sb = new StringBuffer();
StringBuffer sb = new StringBuffer(int size);
StringBuffer sb = new StringBuffer (String str);
StringBuffer sb = new StringBuffer (CharSequence chars);
Methods:
append( )
insert()
delete()
reverse()
toString()
replace()
length();
append():
• append() method is used to add data into StringBuffer class.
• Syntax:
• StringBuffer append(x);
• ‘x’ may be boolean, byte,int,long,float,double, char, character array,
string or another string buffer.
• It will be added to string buffer object.
insert():
• insert () method is used to inserted into StringBuffer at specified
position.
• Syntax:
• StringBuffer insert(int i,x);
• ‘x’ may be boolean, byte,int,long,float,double, char, character array,
string or another string buffer.
• It will be inserted into StringBuffer at the position represented by ‘i’.
Eg: StringBuffer sb = new StringBuffer(“ Have day”);
sb.insert(4,”a wonderful”);
System.out.println(sb); // Have a wonderful day
delete():
• delete() method is used to remove the character from specified
position from StringBuffer.
• Syntax:
• StringBuffer delete(int i, int j);
• ‘i’ is the starting index and ‘j’ is the end index and ‘j’ always -1(j-1).
Eg: StringBuffer sb = new StringBuffer(“ Final Year ECE D Students”);
sb.delete(0,10);
System.out.println(sb); // ECE D Students
reverse():
• reserve() method is used to revese character sequence in the
StringBuffer.
• Syntax:
• StringBuffer reverse():
• StringBuffer sb = new StringBuffer(“ MRECW”);
• sb.reverse(); // WCERM
toString():
• This method is converts the StringBuffer object into String object.
• This will enables use to use string class methods on StringBuffer,
after it conversion.
• Syntax:
• StringBuffer toString();
• StringBuffer sb = new StringBuffer(“Hello”);
sb.toString();
replace():
• This method is used to replace a sequence of characters from
specified positions by a new string “str”.
• Syntax:
• StringBuffer replace(int i, int j, String str);
• StringBuffer sb = new StringBuffer("Final Year CSE Students");
• sb.replace(11,14,"ECED");
• System.out.println(sb);

You might also like