0% found this document useful (0 votes)
66 views

Prepared by Zanamwe N at 2014

1) The Character class in Java provides a wrapper for the primitive char data type, allowing chars to be used as objects. It contains useful static methods for manipulating characters, such as isLetter() and toUpperCase(). 2) Strings in Java are objects of the String class. They can be created using double quotes or the String constructor. Common String methods include length(), charAt(), substring(), and toUpperCase(). 3) The CharSequence interface defines methods common to all classes that allow accessing their characters, such as String, StringBuffer, and CharBuffer. It contains methods like charAt(), length(), and subSequence().

Uploaded by

Marlon Tugwete
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Prepared by Zanamwe N at 2014

1) The Character class in Java provides a wrapper for the primitive char data type, allowing chars to be used as objects. It contains useful static methods for manipulating characters, such as isLetter() and toUpperCase(). 2) Strings in Java are objects of the String class. They can be created using double quotes or the String constructor. Common String methods include length(), charAt(), substring(), and toUpperCase(). 3) The CharSequence interface defines methods common to all classes that allow accessing their characters, such as String, StringBuffer, and CharBuffer. It contains methods like charAt(), length(), and subSequence().

Uploaded by

Marlon Tugwete
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

Char Data Type

Normally, when we work with characters, we use primitive data types char.

Example:

char ch = 'a';

// Unicode for uppercase Greek omega character

char uniChar = '\u039A';

// an array of chars

char [] charArray ={ 'a', 'b', 'c', 'd', 'e' };

However in development, we come across situations where we need to use objects instead of primitive
data types. In order to achieve this, Java provides wrapper class Character for primitive data type char.

The Character class offers a number of useful class (i.e., static) methods for manipulating characters. You
can create a Character object with the Character constructor:

Character ch = new Character('a');

The Java compiler will also create a Character object for you under some circumstances. For example, if
you pass a primitive char into a method that expects an object, the compiler automatically converts the
char to a Character for you. This feature is called autoboxing or unboxing, if the conversion goes the
other way.

Example:

// Here following primitive char 'a'

// is boxed into the Character object ch

Character ch = 'a';

Prepared by Zanamwe N @ 2014


// Here primitive 'x' is boxed for method test,

// return is unboxed to char 'c'

char c = test('x');

Character Methods:

Here is the list of the important STATIC instance methods that all the subclasses of the Character class
implement:

SN Methods with Description

isLetter()
1
Determines whether the specified char value is a letter.

isDigit()
2
Determines whether the specified char value is a digit.

isWhitespace()
3
Determines whether the specified char value is white space.

isUpperCase()
4
Determines whether the specified char value is uppercase.

isLowerCase()
5
Determines whether the specified char value is lowercase.

toUpperCase()
6
Returns the uppercase form of the specified char value.

toLowerCase()
7
Returns the lowercase form of the specified char value.

toString()
8 Returns a String object representing the specified character value that is, a one-character
string.

For a complete list of methods, please refer to the java.lang.Character API specification.

Prepared by Zanamwe N @ 2014


ChaSequence Class

A CharSequence is a readable and classes like CharBuffer, Segment, String, StringBuffer, StringBuilder
implement the CharSequence class.

Below are some of the methods in this class:

 char charAt(int index) -Returns the char value at the specified index.

 int length() -Returns the length of this character sequence.

 Char SequencesubSequence(int start, int end) -Returns a new CharSequence that is a


subsequence of this sequence.

 String toString()-Returns a string containing the characters in this sequence in the same order as
this sequence.

String Class

The String class has seven different constructors. Only the most common constructors will be presented.
In Java strings are objects which belong to the standard class String. String objects like all object
variables in Java have to be created before use. Objects are created by the system operator “new”. This
operator finds storage space on the system heap, initializes this space to the parameter supplied and
returns a reference to this storage location. (A reference is a pointer to the storage location, or more
simply an address) for example:

new String(“Good Morning Zimbabwe”);

------- “Good Morning Zimbabwe”

To name or reference this object you need to assign it to an object variable of class String:

String greeting = new String(“Good Morning Zimbabwe”);

greeting ---- “Good Morning Zimbabwe”

the variable “greeting “ references the object; object variables are often referred to as “handles.” In
OOP parlance the object variable “greeting” is an instance of the class String and “greeting”
instantiates the class String.

Prepared by Zanamwe N @ 2014


An object variable may be assigned freely to another variable of the same class:

String string1 = new String(“Hello world”);

String string2 = string1;

Now both string1 and string2 reference the same String object containing “Hello world”

The above constructor shows one of seven types of constructors supported by Java and the prototype is
as follows:

public String( String value )

This constructs a new String that contains the same sequence of characters as the specified String
argument.

The other two constructors are:

1.

public String()

Constructs a new String with the value "" containing no characters. The value is not null. For example:

String s1 = new String();

2.

public String( char[] value )

Constructs a new String containing the same sequence of characters contained in the character array
argument.

For example:

char[] data = { 'a', 'b', 'c' };

String s4 = new String( data );

Prepared by Zanamwe N @ 2014


Alternatively; The simplest method to create a String object is to enclose the string literal in quotes and
assign the value to a String object. Creation of a String through assignment does not require the use of
the new operator, for example

String str = "abc"; // String str = new String(“abc”);

String language = "Java";

Java provides many useful functions in the String class. Here follows some examples:

1. public int length() this returns the number of characters in a string including spaces. The function
“length()” is a member function of the class String, that is length() is part of the interface of the
class String. Functions are generally termed “methods” in Java. The method length() is termed an
“instance method” of class String. The method is prefixed by a String variable as follows:

String s1 = new String("Good");

int size = s1. length();

System.out.println(size); //returns 4

2. public int indexOf(char character)- This returns the index of a char in a string. You can also use
lastIndexOf(char character). Value of −1, indicates “not found.”

3. public char charAt(int index) this returns an individual character from a String. The index may
range from 0 to length() - 1. Note that the first character is at position zero. For example:

String string1 = new String(“Hello world”);

char c = string1.charAt(4); // c is ‘o’

character variable c contains ‘o’.

To print individual characters of a string use a for loop:

for (int i = 0; i < string1.length(); i++)

Prepared by Zanamwe N @ 2014


System.out.print(string1.charAt(i));

System.out.println();

4. public boolean contains(CharSequence s) -Returns true if and only if this string contains the
specified sequence of char values.

5. public String concat( String str )

Concatenates the specified string to the end of the current (this) string. If the length of the argument
string is 0, then this String is returned.

Example:

String s1 = new String("Boko");

String string3 = " Harama";

System.out.println(s1.concat(string3));

This returns Boko Harama

6. public String substring(int x, int y) provided that the condition x <= y holds, this returns a
substring starting at x inclusive and ending at y exclusive. Note again that characters are indexed
from zero and that the second index is the position of the first character which is not included.
This convention means that the length of the substring is always right – left characters. For
example:

String string1 = “Hello world”;

string1.substring(6, 11); //returns “world”

7. public String toUpperCase() this returns a string in uppercase for example:

String string1 = “Hello world”;

string1.toUpperCase(); // returns “HELLO WORLD”

Prepared by Zanamwe N @ 2014


8. public String toLowerCase() this method returns a string in lowercase for example:

String string1 = “Hello world”;

string1.toLowerCase(); // returns “hello world”

9. public String trim() this method returns a string without leading and trailing white space for
example:

String string1 = “ Hello world ”;

string1.trim() // returns “Hello world” without trailing and leading spaces.

Note any number of methods may be applied to an object in the same statement, for example:

String string1 = “Hello world”;

string1.substring(6, 11).toUpperCase();// returns “WORLD”

10. public boolean startsWith(String prefixString, int offset) - Starting from offset, check if this string
has prefixString.

String n = "Zanamwe is kind";

System.out.println(n.startsWith("is",8)); //true

11. public boolean startsWith(String prefixString)- Check if this string has prefixString; equivalent to
startsWith(prefixString, 0);

12. public boolean endsWith(String suffixString) -Check if this string has the suffixString.

13. public boolean regionMatches(int start, String matchingStr, int matchStartOffset, int matchLen)

 start - the starting offset of the subregion in this string.

 matchingStr - the string argument.

 matchStartOffset - the starting offset of the subregion in the string argument.

 matchLen - the number of characters to compare.

Prepared by Zanamwe N @ 2014


Example:

String n = "Zanamwe is kind";

String match = "Zanamwe";

System.out.println(n.regionMatches(0, match, 0, 7)); //true

14. boolean regionMatches(boolean ignoreCase, int start, String matchingStr, int matchStartOffset,
int matchLen) - Same as the previous method, but with the additional first argument, which
ignores the case differences.

15. Split(delimiter)-Splits a string using the delimeter into words which can be stored in an array.

String n = "Zanamwe is kind";

String[] match = n.split(" ");

System.out.println(match[0]); //Zanamwe

The following methods create the String representation of the argument.

16. public static String valueOf( boolean b )

17. public static String valueOf( char ch )

18. public static String valueOf( int inum )

19. public static String valueOf( long lnum )

20. public static String valueOf( float fnum )

21. public static String valueOf( double dnum )

int x = 3;

String sX = String.valueOf(x);

Prepared by Zanamwe N @ 2014


*** Go and look at rest of the methods in String class and StringBuffer class

StringBuffer Class

The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are the
important points about StringBuffer:

 A string buffer is like a String, but can be modified.

 It contains some particular sequence of characters, but the length and content of the sequence can
be changed through certain method calls.

 They are safe for use by multiple threads.

 Every string buffer has a capacity.

Class constructors

S.N. Constructor & Description

StringBuffer()
1
This constructs a string buffer with no characters in it and an initial capacity of 16 characters.

StringBuffer(CharSequence seq)
2
This constructs a string buffer that contains the same characters as the specified CharSequence.

StringBuffer(int capacity)
3
This constructs a string buffer with no characters in it and the specified initial capacity.

StringBuffer(String str)
4
This constructs a string buffer initialized to the contents of the specified string.

Class methods

S.N. Method & Description

1 StringBuffer append(boolean b)

Prepared by Zanamwe N @ 2014


This method appends the string representation of the boolean argument to the sequence

StringBuffer append(char c)
2
This method appends the string representation of the char argument to this sequence.

StringBuffer append(char[] str)


3
This method appends the string representation of the char array argument to this sequence.

StringBuffer append(char[] str, int offset, int len)


4 This method appends the string representation of a subarray of the char array argument to this
sequence.

StringBuffer append(CharSequence s)
5
This method appends the specified CharSequence to this sequence.

StringBuffer append(CharSequence s, int start, int end)


6
This method appends a subsequence of the specified CharSequence to this sequence.

StringBuffer append(double d)
7
This method appends the string representation of the double argument to this sequence.

StringBuffer append(float f)
8
This method appends the string representation of the float argument to this sequence.

StringBuffer append(int i)
9
This method appends the string representation of the int argument to this sequence.

StringBuffer append(long lng)


10
This method appends the string representation of the long argument to this sequence.

StringBuffer append(Object obj)


11
This method appends the string representation of the Object argument.

StringBuffer append(String str)


12
This method appends the specified string to this character sequence.

StringBuffer append(StringBuffer sb)


13
This method appends the specified StringBuffer to this sequence.

Prepared by Zanamwe N @ 2014


StringBuffer appendCodePoint(int codePoint)
14
This method appends the string representation of the codePoint argument to this sequence.

int capacity()
15
This method returns the current capacity.

char charAt(int index)


16
This method returns the char value in this sequence at the specified index.

int codePointAt(int index)


17
This method returns the character (Unicode code point) at the specified index

int codePointBefore(int index)


18
This method returns the character (Unicode code point) before the specified index

int codePointCount(int beginIndex, int endIndex)


19 This method returns the number of Unicode code points in the specified text range of this
sequence

StringBuffer delete(int start, int end)


20
This method removes the characters in a substring of this sequence.

StringBuffer deleteCharAt(int index)


21
This method removes the char at the specified position in this sequence

void ensureCapacity(int minimumCapacity)


22
This method ensures that the capacity is at least equal to the specified minimum.

void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)


23
This method characters are copied from this sequence into the destination character array dst.

int indexOf(String str)


24
This method returns the index within this string of the first occurrence of the specified substring.

int indexOf(String str, int fromIndex)


25 This method returns the index within this string of the first occurrence of the specified substring,
starting at the specified index.

Prepared by Zanamwe N @ 2014


StringBuffer insert(int offset, boolean b)
26
This method inserts the string representation of the boolean argument into this sequence.

StringBuffer insert(int offset, char c)


27
This method inserts the string representation of the char argument into this sequence.

StringBuffer insert(int offset, char[] str)


28
This method inserts the string representation of the char array argument into this sequence.

StringBuffer insert(int index, char[] str, int offset, int len)


29 This method inserts the string representation of a subarray of the str array argument into this
sequence.

StringBuffer insert(int dstOffset, CharSequence s)


30
This method inserts the specified CharSequence into this sequence.

StringBuffer insert(int dstOffset, CharSequence s, int start, int end)


31
This method inserts a subsequence of the specified CharSequence into this sequence.

StringBuffer insert(int offset, double d)


32
This method inserts the string representation of the double argument into this sequence.

StringBuffer insert(int offset, float f)


33
This method inserts the string representation of the float argument into this sequence.

StringBuffer insert(int offset, int i)


34
This method inserts the string representation of the second int argument into this sequence.

StringBuffer insert(int offset, long l)


35
This method inserts the string representation of the long argument into this sequence.

StringBuffer insert(int offset, Object obj)


36 This method inserts the string representation of the Object argument into this character
sequence.

StringBuffer insert(int offset, String str)


37
This method inserts the string into this character sequence.

Prepared by Zanamwe N @ 2014


int lastIndexOf(String str)
38 This method returns the index within this string of the rightmost occurrence of the specified
substring.

int lastIndexOf(String str, int fromIndex)


39
This method returns the index within this string of the last occurrence of the specified substring.

int length()
40
This method returns the length (character count).

int offsetByCodePoints(int index, int codePointOffset)


41 This method returns the index within this sequence that is offset from the given index by
codePointOffset code points.

StringBuffer replace(int start, int end, String str)


42 This method replaces the characters in a substring of this sequence with characters in the
specified String.

StringBuffer reverse()
43
This method causes this character sequence to be replaced by the reverse of the sequence.

void setCharAt(int index, char ch)


44
The character at the specified index is set to ch.

void setLength(int newLength)


45
This method sets the length of the character sequence.

CharSequence subSequence(int start, int end)


46
This method returns a new character sequence that is a subsequence of this sequence.

String substring(int start)


47 This method returns a new String that contains a subsequence of characters currently contained
in this character sequence

String substring(int start, int end)


48 This method returns a new String that contains a subsequence of characters currently contained
in this sequence.

Prepared by Zanamwe N @ 2014


String toString()
49
This method returns a string representing the data in this sequence.

void trimToSize()
50
This method attempts to reduce storage used for the character sequence.

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait

Null or empty string

This is a string with no characters and length zero and is represented as “”

For example string2 = “”; // now string2 references the null string.

Null references

If an object variable is assigned the predefined constant “null” then the variable references no object.
Note the difference between the null reference “null” and the null string “”:

string1 = “” ;// string1 references no characters

string2 = null; // string2 does not reference anything

System.out.println(string1); // prints no characters

System.out.println(string2); // Error! Program terminated

String string1 references the null string with no characters and string2 does not reference anything.

The system throws an exception if a null reference is accessed and immediately terminates the program
unless code is supplied to catch this exception. You can test whether a reference is null before using it:

if(s==null)

Prepared by Zanamwe N @ 2014


{

// handle the problem

else

System.out.println(string1); // display it

String Comparison

String variables like all object variables contain references (pointers to addresses) not the object
contents themselves. The objects themselves are allocated on the heap by the Java system.

This means that the expression (string1 == string2) does NOT test whether string1 and string2 contain
the same string, it tests whether string1 and string2 contain the same reference or address. To test for
string equality use the boolean equals() method of the String class:

string1.equals(string2); // returns true if string1 and string2 have the same characters and false
otherwise.

Note that if greeting contains “Hello world” then

greeting.substring(0,4) ==”Hell”; is false. It might appear that the substring “Hell” is being compared to
the string literal “Hell” and that the substrings are the same, but in fact the reference of the substring
“Hell” is being compared to the reference of an anonymous String object created to contain “Hell” and
the references are different.

greeting.substring(0,4) == new String(“Hell”);

greeting ----- Hello World.

----- Hell

Obviously “greeting” and the newly created string “Hell” have different references. But

greeting.subtring(0, 4).equals(“Hell”);

Prepared by Zanamwe N @ 2014


is obviously true.

Whenever you create a class you should consider including an equals() method.

Of course if string1 == string2 is true then string1.equals(string2); is also true, for all objects, not just for
String objects. If for example:

String string3 = “ Hello World”;

String string4 = string3;

Then obviously (string3 == string4) is true and string3.eqauls(string4) is true.

If we have:

String string3 = “ Hello World”;

String string4 = “ Hello World”;

***Then the compiler could arrange to have only one copy of the string “Hello World” on the heap so

(String3 == string4) should be true.

If new is not used to assign a value to a String object, then all other Strings constructed similarly with
the same literal value will refer to the same object in memory.

NB: Never use == to test equality of String contents or immutable objects in general.

The String class contains the compareTo() method which returns -1, 0, +1 according to whether the first
string is less than, equal to or greater than the second string in the Unicode sequence. The prototype is
as follows:

public int compareTo( String str )

Prepared by Zanamwe N @ 2014


This method compares the current String object to str, and returns 0 only if the two strings contain the
same sequence of characters (case sensitive). A negative value is returned if the current String is lower
in the Unicode set than the String str. A positive value is returned if the current String is higher in the
Unicode set than the String str.

The String class also contains the equalsIgnoreCase() method with the following prototype:

public boolean equalsIgnoreCase( String str )

Performs a case-insensitive comparison of the current String object with str and returns true if str is
another String containing the same sequence (ignoring case) of characters; false is returned otherwise.

Strings are immutable

Methods which access object contents are called accessor methods and methods which change object
contents are called mutator methods. All of the methods supplied for class String are accessors. So it is
not possible to change or mutate the contents of a String object, and accordingly Strings are termed
immutable. The only way to change the contents of a String object is to replace the existing contents by
assigning a new object to the object variable:

String stringOne = new String (“Hie”); // original object.

stringOne = new String(“How are you”); // new object

Later will consider other classes which do provide mutator methods for changing the fields of the object

Note that the immutability of class String is design decision: an object class may be designed to have
only accessors, like String, or accessors and mutators, or even mutators only, but this later class would
not be very useful in practice.

String concatenation

Strings are concatenated using the “+” operator:

String string1 = “Hello world” ;

String string5 = string1.substring(0, 5);

Prepared by Zanamwe N @ 2014


String string6 = string1.substring(6, 11).toUpperCase();

String string7 = string5 + string6; // returns “HelloWORLD”

String string8 = string5 + ”” + string6; // returns “Hello WORLD”

If a string and a non-string are concatenated the non-string is converted to a string:

String name = “Moses”;

int age = 56;

String details = name + age; // returns “Moses56”

String details = name + “ ” + age + “years”; // returns “Moses56” // “Moses 56years”

Since + automatically converts a non-string to a string you can concatenate a null string “” to any value
to obtain a string value fro example:

double height = 123,4567;

String string45 = height + “ ”;

To perform the reverse operation, converting strings representing numbers to values, we use the
Integer.parseInt and the Double.parseDouble methods:

String code = “5678”;

int num1 = Integer.parseInt(code);

double num2 = Double.parseDouble(code);

Wrapper classes

Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.

Example:

int i = 5000; //

float gpa = 13.65;

byte mask = 0xaf;

Prepared by Zanamwe N @ 2014


However, in development, we come across situations where we need to use objects instead of primitive
data types. In-order to achieve this Java provides wrapper classes for each primitive data type.

All the wrapper classes (Integer, Long, Byte, Double, Float, Short) are subclasses of the abstract class
Number.

This wrapping is taken care of by the compiler, the process is called boxing. So when a primitive is used
when an object is required, the compiler boxes the primitive type in its wrapper class. Similarly, the
compiler unboxes the object to a primitive as well. The Number is part of the java.lang package.

Here is an example of boxing and unboxing:

public class Test{

public static void main(String args[]){

Integer x = 5; // boxes int to an Integer object

x = x + 10; // unboxes the Integer to a int

System.out.println(x);

This would produce the following result:

15

When x is assigned integer values, the compiler boxes the integer because x is integer objects. Later, x is
unboxed so that they can be added as integers.

Prepared by Zanamwe N @ 2014


Number Methods:

Here is the list of the instance methods that all the subclasses of the Number class implement:

SN Methods with Description

xxxValue()
Converts the value of this Number object to the xxx primitive data type and returned it.

byte byteValue()

short shortValue()

int intValue()

long longValue()

float floatValue()

double doubleValue()

public class Test{

1 public static void main(String args[]){

Integer x = 5;

// Returns byte primitive data type

System.out.println( x.byteValue() );

// Returns double primitive data type

System.out.println(x.doubleValue());

// Returns long primitive data type

System.out.println( x.longValue() );

Prepared by Zanamwe N @ 2014


}

compareTo()
2
Compares this Number object to the argument.

equals()
3
Determines whether this number object is equal to the argument.

valueOf()
4
Returns an Integer object holding the value of the specified primitive.

toString()
5
Returns a String object representing the value of specified int or Integer.

parseInt()
6
This method is used to get the primitive data type of a certain String.

abs()
7
Returns the absolute value of the argument.

ceil()
8 Returns the smallest integer that is greater than or equal to the argument. Returned as a
double.

floor()
9
Returns the largest integer that is less than or equal to the argument. Returned as a double.

rint()
10
Returns the integer that is closest in value to the argument. Returned as a double.

round()
11
Returns the closest long or int, as indicated by the method's return type, to the argument.

min()
12
Returns the smaller of the two arguments.

Prepared by Zanamwe N @ 2014


max()
13
Returns the larger of the two arguments.

exp()
14
Returns the base of the natural logarithms, e, to the power of the argument.

log()
15
Returns the natural logarithm of the argument.

pow()
16
Returns the value of the first argument raised to the power of the second argument.

sqrt()
17
Returns the square root of the argument.

sin()
18
Returns the sine of the specified double value.

cos()
19
Returns the cosine of the specified double value.

tan()
20
Returns the tangent of the specified double value.

asin()
21
Returns the arcsine of the specified double value.

acos()
22
Returns the arccosine of the specified double value.

atan()
23
Returns the arctangent of the specified double value.

atan2()
24
Converts rectangular coordinates (x, y) to polar coordinate (r, theta) and returns theta.

toDegrees()
25
Converts the argument to degrees

Prepared by Zanamwe N @ 2014


toRadians()
26
Converts the argument to radians.

random()
27
Returns a random number.

Regular Expressions

A regular expression defines a search pattern that can be used to execute operations such as string
search and string manipulation. A regular expression is nothing but a sequence of predefined symbols
specified in a predefined syntax that helps you search or manipulate strings. A regular expression is
specified as a string and applied on another string from left to right.

Understanding regex Symbols

We will now focus on understanding the syntax and semantics of symbols used to specify regular
expressions.

You can use the following in place of some of the symbols above.

Prepared by Zanamwe N @ 2014


Quantifier Symbols

Regex Support in Java

Java 1.4 SDK introduced regex support in Java. The package java.util.regex supports regex.

The java.util.regex package primarily consists of three classes: Pattern, Matcher,


and PatternSyntaxException.

Prepared by Zanamwe N @ 2014


 A Pattern object is a compiled representation of a regular expression. The Pattern class provides
no public constructors. To create a pattern, you must first invoke one of its public static
compile methods, which will then return a Pattern object.

 A Matcher object is the engine that interprets the pattern and performs match operations
against an input string. Like the Pattern class, Matcher defines no public constructors. You
obtain aMatcher object by invoking the matcher method on a Pattern object.

 A PatternSyntaxException object is an unchecked exception that indicates a syntax error in a


regular expression pattern.

You first need to call a static method compile() in the Pattern class to get an instance of a pattern. The
first argument of this method is a regex. Then, you need to call another static method called matcher()
from the Pattern class to get an instance of the Matcher class. The matcher() method returns a Matcher
object. This object is then used to execute the required operation on the input string.

Matches Email:

Have to import:

import java.util.regex.Pattern;

import java.util.regex.Matcher;

String n = "[email protected]";

Pattern p = Pattern.compile("\\w+@\\w+\\.\\w+");

Matcher m = p.matcher(n);

System.out.println(m.find());

System.out.println(m.group());

you can see that the regular expression matched a valid e-mail. What happened here was that we
invoked the compile() method along with a regex of the Pattern class to get an instance of Pattern. After

Prepared by Zanamwe N @ 2014


that, we got an instance of the Matcher class by calling the matcher() method on pattern instance. And
finally we got the result using the group() and find() methods of the Matcher class. The method find()
returns true if there exists any search result. The group() method returns a search result occurrence as a
string.

Searches For E-mail in a string of text:

String str = "Danny Doo, Flat no 502, Big Apartment, Wide Road, Near Huge Milestone,Hugo-city 56010,
Ph: 9876543210, Email: [email protected]. Maggi Myer, Post bag no 52, Big bank post office, Big
bank city 56000, ph: 9876501234, Email: [email protected].";

Pattern pattern = Pattern.compile("\\w+@\\w+\\.com");

Matcher matcher = pattern.matcher(str);

while(matcher.find()) {

System.out.println(matcher.group());

Garbage collection

When the contents of an object are changed the previous contents are no longer referenced:

String string3 = new String(“Goodbye”); // string3 --- Goodbye

String3 = new String(“Welcome”); // string3----+ Goodbye

+---------------- Welcome

The object containing “Goodbye” is no longer referenced so it cannot be accessed. The accumulation
of unreferenced memory locations is termed memory leakage. The Java system includes an automatic

Prepared by Zanamwe N @ 2014


garbage collection routine which periodically returns such unreferenced locations to the system free
memory.

Enum Types

An enum type is a type whose fields consist of a fixed set of constants. Common examples include
compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week. Because they
are constants, the names of an enum type's fields are in uppercase letters.

In the Java programming language, you define an enum type by using the enum keyword. For example,
you would specify a days-of-the-week enum type as:

public enum Day

{SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY

You should use enum types any time you need to represent a fixed set of constants. That includes
natural enum types such as the months in a year and data sets where you know all possible values at
compile time—for example, the choices on a menu, command line flags, and so on.

Here is some code that shows you how to use the Day enum defined above:

public class EnumTest

public enum Day

SUNDAY, MONDAY, TUESDAY, WEDNESDAY,

THURSDAY, FRIDAY, SATURDAY

};

Day day;

Prepared by Zanamwe N @ 2014


public EnumTest(Day day)

this.day = day;

public void tellItLikeItIs()

switch (day)

case MONDAY:

System.out.println("Mondays are bad.");

break;

case FRIDAY:

System.out.println("Fridays are better.");

break;

case SATURDAY:

case SUNDAY:

System.out.println("Weekends are best.");

break;

default:

System.out.println("Midweek days are so-so.");

Prepared by Zanamwe N @ 2014


break;

public static void main(String[] args)

EnumTest firstDay = new EnumTest(Day.MONDAY);

firstDay.tellItLikeItIs();

EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);

thirdDay.tellItLikeItIs();

EnumTest fifthDay = new EnumTest(Day.FRIDAY);

fifthDay.tellItLikeItIs();

EnumTest sixthDay = new EnumTest(Day.SATURDAY);

sixthDay.tellItLikeItIs();

EnumTest seventhDay = new EnumTest(Day.SUNDAY);

seventhDay.tellItLikeItIs();

The output is:

Mondays are bad.

Midweek days are so-so.

Fridays are better.

Prepared by Zanamwe N @ 2014


Weekends are best.

Weekends are best.

Java programming language enum types are much more powerful than their counterparts in other
languages. The enum declaration defines a class (called an enum type). The enum class body can include
methods and other fields. The compiler automatically adds some special methods when it creates an
enum. For example, they have a STATIC values() method that returns an array containing all of the
values of the enum in the order they are declared. This method is commonly used in combination with
the for-each construct to iterate over the values of an enum type.

Example:

enum Sex {MALE,FEMALE};

And then iterate enum as shown below :

for(Sex v : Sex.values()){

System.out.println(" values :"+ v);

Equality for Enums

Once you've declared an enum, it's not expandable. At runtime, there's no way to make additional enum
constants. Of course, you can have as many variables as you'd like refer to a given enum constant, so it's
important to be able to compare two enum reference variables to see if they're "equal", i.e. do they
refer to the same enum constant. You can use EITHER the == operator or the equals() method to
determine if two variables are referring to the same enum constant:

public class EnumEqual

public enum Color {RED, BLUE}

Prepared by Zanamwe N @ 2014


public static void main(String[] args)

Color c1 = Color.RED;

Color c2 = Color.RED;

if(c1 == c2)

System.out.println("==");

if(c1.equals(c2))

{ System.out.println("dot equals");

This produces the output:

==

dot equals

Note: All enums implicitly extend java.lang.Enum.

In the following example, Planet is an enum type that represents the planets in the solar system. They
are defined with constant mass and radius properties.

Each enum constant is declared with values for the mass and radius parameters. These values are
passed to the constructor when the constant is created. Java requires that the constants be defined first,

Prepared by Zanamwe N @ 2014


prior to any fields or methods. Also, when there are fields and methods, the list of enum constants must
end with a semicolon.

Note: The constructor for an enum type must be package-private or private access. It automatically
creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum
constructor yourself.

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface
gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth
(in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public enum Planet {


MERCURY (3.303e+23, 2.4397e6),
VENUS (4.869e+24, 6.0518e6),
EARTH (5.976e+24, 6.37814e6),
MARS (6.421e+23, 3.3972e6),
JUPITER (1.9e+27, 7.1492e7),
SATURN (5.688e+26, 6.0268e7),
URANUS (8.686e+25, 2.5559e7),
NEPTUNE (1.024e+26, 2.4746e7);

private final double mass; // in kilograms


private final double radius; // in meters
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
private double mass() { return mass; }
private double radius() { return radius; }

// universal gravitational constant (m3 kg-1 s-2)


public static final double G = 6.67300E-11;

double surfaceGravity() {
return G * mass / (radius * radius);
}
double surfaceWeight(double otherMass) {
return otherMass * surfaceGravity();
}
public static void main(String[] args) {
if (args.length != 1) {
System.err.println("Usage: java Planet <earth_weight>");
System.exit(-1);
}
double earthWeight = Double.parseDouble(args[0]);
double mass = earthWeight/EARTH.surfaceGravity();
for (Planet p : Planet.values())
System.out.printf("Your weight on %s is %f%n",
p, p.surfaceWeight(mass));

Prepared by Zanamwe N @ 2014


}
}

If you run Planet.class from the command line with an argument of 175, you get this output:

$ java Planet 175


Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Prepared by Zanamwe N @ 2014

You might also like