Prepared by Zanamwe N at 2014
Prepared by Zanamwe N at 2014
Normally, when we work with characters, we use primitive data types char.
Example:
char ch = 'a';
// an array of chars
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:
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:
Character ch = 'a';
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:
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.
A CharSequence is a readable and classes like CharBuffer, Segment, String, StringBuffer, StringBuilder
implement the CharSequence class.
char charAt(int index) -Returns the char value at the specified index.
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:
To name or reference this object you need to assign it to an object variable of class String:
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.
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:
This constructs a new String that contains the same sequence of characters as the specified String
argument.
1.
public String()
Constructs a new String with the value "" containing no characters. The value is not null. For example:
2.
Constructs a new String containing the same sequence of characters contained in the character array
argument.
For example:
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:
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:
System.out.println();
4. public boolean contains(CharSequence s) -Returns true if and only if this string contains the
specified sequence of char values.
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:
System.out.println(s1.concat(string3));
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:
9. public String trim() this method returns a string without leading and trailing white space for
example:
Note any number of methods may be applied to an object in the same statement, for example:
10. public boolean startsWith(String prefixString, int offset) - Starting from offset, check if this string
has prefixString.
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)
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.
System.out.println(match[0]); //Zanamwe
int x = 3;
String sX = String.valueOf(x);
StringBuffer Class
The java.lang.StringBuffer class is a thread-safe, mutable sequence of characters. Following are the
important points about StringBuffer:
It contains some particular sequence of characters, but the length and content of the sequence can
be changed through certain method calls.
Class constructors
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
1 StringBuffer append(boolean b)
StringBuffer append(char c)
2
This method appends the string representation of the char argument to this sequence.
StringBuffer append(CharSequence s)
5
This method appends 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.
int capacity()
15
This method returns the current capacity.
int length()
40
This method returns the length (character count).
StringBuffer reverse()
43
This method causes this character sequence to be replaced by the reverse of the sequence.
void trimToSize()
50
This method attempts to reduce storage used for the character sequence.
clone, equals, finalize, getClass, hashCode, notify, notifyAll, wait, wait, wait
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 “”:
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)
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.
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.
----- Hell
Obviously “greeting” and the newly created string “Hell” have different references. But
greeting.subtring(0, 4).equals(“Hell”);
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:
If we have:
***Then the compiler could arrange to have only one copy of the string “Hello World” on the heap so
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:
The String class also contains the equalsIgnoreCase() method with the following prototype:
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.
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:
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
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:
To perform the reverse operation, converting strings representing numbers to values, we use the
Integer.parseInt and the Double.parseDouble methods:
Wrapper classes
Normally, when we work with Numbers, we use primitive data types such as byte, int, long, double, etc.
Example:
int i = 5000; //
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.
System.out.println(x);
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.
Here is the list of the instance methods that all the subclasses of the Number class implement:
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()
Integer x = 5;
System.out.println( x.byteValue() );
System.out.println(x.doubleValue());
System.out.println( x.longValue() );
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.
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
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.
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.
Java 1.4 SDK introduced regex support in Java. The package java.util.regex supports regex.
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.
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
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].";
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:
+---------------- 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
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:
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:
};
Day day;
this.day = day;
switch (day)
case MONDAY:
break;
case FRIDAY:
break;
case SATURDAY:
case SUNDAY:
break;
default:
firstDay.tellItLikeItIs();
thirdDay.tellItLikeItIs();
fifthDay.tellItLikeItIs();
sixthDay.tellItLikeItIs();
seventhDay.tellItLikeItIs();
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:
for(Sex v : Sex.values()){
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:
Color c1 = Color.RED;
Color c2 = Color.RED;
if(c1 == c2)
System.out.println("==");
if(c1.equals(c2))
{ System.out.println("dot equals");
==
dot equals
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,
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):
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));
If you run Planet.class from the command line with an argument of 175, you get this output: