PART 9 Number Methods
9.1 toString() Method
The method is used to get a String object representing the value of the Number
Object. If the method takes a primitive data type as an argument then the String object
representing the primitive data type value is return.
String toString(int i)
Example
public class Test{
public static void main(String args[]){
int x = 5;
int y = 3;
System.out.println(Integer.toString(x) + Integer.toString(y));
}
}
This produces following result:
53
9.2 parseInt(), parseDouble() Methods
This method is used to get the primitive data type of a certain String. parseXxx() is a
static method and can have one argument or two.
int parseInt(String s)
int parseInt(String s, int radix)
s -- This is a string representation of decimal.
radix -- (radix equals 10, 2, 8, or 16 respectively). Parses given string into
decimal, binary, octal, or hexadecimal format.
Example
public class Test{
public static void main(String args[]){
int x =Integer.parseInt("9");
double c = Double.parseDouble("5");
int b = Integer.parseInt("A",16);
System.out.println(x);
System.out.println(c);
System.out.println(b);
}
}
This produces following result:
9
5.0
10
9.3 Math Methods Math.abs() The method gives the absolute value of the argument.
public class Test{
public static void main(String args[]){
Integer a = -8;
double d = -100;
float f = -90;
System.out.println(Math.abs(a));
System.out.println(Math.abs(d));
System.out.println(Math.abs(f));
}
}
Math.ceil()
The method ceil gives the smallest integer that is greater than or equal to the argument.
public class Test{
public static void main(String args[]){
double d = -100.675;
float f = -90;
System.out.println(Math.ceil(d));
System.out.println(Math.ceil(f));
}
}
Math.floor() The method floor gives the largest integer that is less than or equal to the argument.
public class Test{
public static void main(String args[]){
double d = -100.675;
float f = -90;
System.out.println(Math.floor(d));
System.out.println(Math.floor(f));
}
}
Math.round() The method round returns the closest long or int, as given by the methods return type.
public class Test{
public static void main(String args[]){
double d = 100.675;
double e = 100.500;
float f = 100;
float g = 90f;
System.out.println(Math.round(d));
System.out.println(Math.round(e));
System.out.println(Math.round(f));
System.out.println(Math.round(g));
}
}
Math.min()
The method gives the smaller of the two arguments.
public class Test{
public static void main(String args[]){
System.out.println(Math.min(12.123, 12.456));
System.out.println(Math.min(23.12, 23.0));
}
}
Math.max()
The method gives the maximum of the two arguments.
public class Test{
public static void main(String args[]){
System.out.println(Math.max(12.123, 12.456));
System.out.println(Math.max(23.12, 23.0));
}
}
Math.exp() The method returns the base of the natural logarithms, e, to the power of the argument.
public class Test{
public static void main(String args[]){
double x = 2;
System.out.println("e :" + Math.E);
System.out.println("e^2 :" +Math.exp(x));
}
}
Math.pow() The method returns the value of the first argument raised to the power of the second argument.
public class Test{
public static void main(String args[]){
double x = 2;
double y = 3;
System.out.println(Math.pow(x, y));
}
}
Math.sqrt() The method returns the square root of the argument.
public class Test{
public static void main(String args[]){
double x = 2;
System.out.println(Math.sqrt(x));
}
}
Math.sin() The method returns the sine of the specified double value.
public class Test{
public static void main(String args[]){
double degrees = 45.0;
double radians = Math.toRadians(degrees);
System.out.println(Math.sin(radians));
}
}
Math.cos() The method returns the cosine of the specified double value.
public class Test{
public static void main(String args[]){
double degrees = 45.0;
double radians = Math.toRadians(degrees);
System.out.println(Math.cos(radians));
}
}
Math.tan() The method returns the tangent of the specified double value.
public class Test{
public static void main(String args[]){
double degrees = 45.0;
double radians = Math.toRadians(degrees);
System.out.println(Math.tan(radians));
}
}
Math.random() The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math.random < 1.0.
Different ranges can be achieved by using arithmetic.
public class Test{
public static void main(String args[]){
System.out.println( Math.random() );
System.out.println( Math.random() );
}
}
PART 10 10. Character Class
Normally, when we work with characters, we use primitive data types char.
Example
char ch = 'a';
// Unicode for uppercase Greek omega character
char uniChar = '\u03A9';
However in development we come across situations were we need to use objects
instead of primitive data types. In-order to achieve this Java provides wrapper
classe Character for primitive data type char.
The Character class offers a number of useful class methods for manipulating
characters. You can create a Character object with the Character constructor:
Character ch = new Character('a');
10.1 Character Methods
Here is the list of the important instance methods that all the subclasses of the
Character class implement:
Methods with Description Example
isLetter()
Determines whether the
specified char value is a
letter.
public class Test {
public static void main(String args[]) {
System.out.println(Character.isLetter('c'));
System.out.println(Character.isLetter('5'));
}
}
This produces following result:
true
false
isDigit()
Determines whether the
specified char value is a digit.
public class Test {
public static void main(String args[]) {
System.out.println(Character.isDigit('c'));
System.out.println(Character.isDigit('5'));
}
}
This produces following result:
false
true
isWhitespace()
The method determines
whether the specified char
value is a white space which
includes
space,
tab
new line.
public class Test{
public static void main(String args[]){
System.out.println(Character.isWhitespace('c'));
System.out.println(Character.isWhitespace(' '));
System.out.println(Character.isWhitespace('\n'));
System.out.println(Character.isWhitespace('\t'));
}
}
This produces following result:
false
true
true
true
isUpperCase()
Determines whether the
specified char value is
uppercase.
public class Test{
public static void main(String args[]){
System.out.println( Character.isUpperCase('c'));
System.out.println( Character.isUpperCase('C'));
System.out.println( Character.isUpperCase('\n'));
System.out.println( Character.isUpperCase('\t'));
}
}
This produces following result:
false
true
false
false
isLowerCase()
Determines whether the
specified char value is
lowercase.
public class Test{
public static void main(String args[]){
System.out.println(Character.isLowerCase('c'));
System.out.println(Character.isLowerCase('C'));
System.out.println(Character.isLowerCase('\n'));
System.out.println(Character.isLowerCase('\t'));
}
}
This produces following result:
true
false
false
false
toUpperCase()
Returns the uppercase form
of the specified char value.
public class Test{
public static void main(String args[]){
System.out.println(Character.toUpperCase('c'));
System.out.println(Character.toUpperCase('C'));
}
}
This produces following result:
C
C
toLowerCase()
Returns the lowercase form
of the specified char value.
public class Test{
public static void main(String args[]){
System.out.println(Character.toLowerCase('c'));
System.out.println(Character.toLowerCase('C'));
}
}
This produces following result:
c
c
toString()
Returns a String object
representing the specified
character valuethat is, a one-
character string.
public class Test{
public static void main(String args[]){
System.out.println(Character.toString('c'));
System.out.println(Character.toString('C'));
}
}
This produces following result:
c
C
PART 11 11. Strings
Strings, which are widely used in Java programming, are a sequence of characters. In
the Java programming language, strings are objects.
The Java platform provides the String class to create and manipulate strings.
11.1 Creating Strings
The most direct way to create a string is to write:
String greeting = "Hello world!";
Whenever it encounters a string literal in your code, the compiler creates a String
object with its value in this case, "Hello world!'.
As with any other object, you can create String objects by using the new keyword and
a constructor. The String class has eleven constructors that allow you to provide the
initial value of the string using different sources, such as an array of characters:
public class StringDemo{
public static void main(String args[]){
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'};
String helloString = new String(helloArray);
System.out.println( helloString );
}
}
This would produce following result:
hello
11.2 String Length
Methods used to obtain information about an object are known as accessor methods.
One accessor method that you can use with strings is the length() method, which
returns the number of characters contained in the string object.
After the following two lines of code have been executed, len equals 17:
public class StringDemo {
public static void main(String args[]) {
String palindrome = "Dot saw I was Tod";
int len = palindrome.length();
System.out.println( "String Length is : " + len );
}
}
This would produce following result:
String Length is : 17
11.3 Concatenating Strings
The String class includes a method for concatenating two strings:
string1.concat(string2);
This returns a new string that is string1 with string2 added to it at the end. You can
also use the concat() method with string literals, as in:
"My name is ".concat("Zara");
Strings are more commonly concatenated with the + operator, as in:
"Hello," + " world" + "!"
which results in:
"Hello, world!"
Let us look at the followinge example:
public class StringDemo {
public static void main(String args[]) {
String string1 = "saw I was ";
System.out.println("Dot " + string1 + "Tod");
}
}
This would produce following result:
Dot saw I was Tod
11.4 String Methods
Methods with Description Example
char charAt(int index)
Returns the character at the specified
index. The string indexes start from zero.
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
char result = s.charAt(8);
System.out.println(result);
}
}
This produces following result:
a
int compareTo(Object o)
Compares this String to another Object.
The value 0 if the argument is a string
lexicographically equal to this string; a
value less than 0 if the argument is a string
lexicographically greater than this string;
and a value greater than 0 if the argument
is a string lexicographically less than this
string.
public class Test {
public static void main(String args[]) {
String str1 = "Strings are immutable";
String str2 = "Strings are immutable";
String str3 = "Integers are not immutable";
int result = str1.compareTo( str2 );
System.out.println(result);
result = str2.compareTo( str3 );
System.out.println(result);
result = str3.compareTo( str1 );
System.out.println(result);
}
}
This produces following result:
0
10
-10
int compareToIgnoreCase(String str)
Compares two strings lexicographically,
ignoring case differences.
public class Test {
public static void main(String args[]) {
String str1 = "Maltepe";
String str2 = "maltepe";
int result = str1.compareTo(str2);
System.out.println(result);
result = str1.compareToIgnoreCase(str2);
System.out.println(result);
}
}
This produces following result:
-32
0
String concat(String str)
This method appends one String to the end
of another.
public class Test {
public static void main(String args[]) {
String s = "Strings are immutable";
s = s.concat(" all the time");
System.out.println(s);
}
}
This produces following result:
Strings are immutable all the time
boolean endsWith(String suffix)
Tests if this string ends with the specified
suffix.
public class Test{
public static void main(String args[]){
String Str = new String("This is immutable");
boolean retVal;
retVal = Str.endsWith( "immutable" );
System.out.println(retVal );
retVal = Str.endsWith( "immu" );
System.out.println(retVal );
}
}
This produces following result:
true
false
boolean equals(Object anObject)
Compares this string to the specified
object.
public class Test {
public static void main(String args[]) {
String Str1 = new String("maltepe");
String Str2 = Str1;
String Str3 = new String("maltepe");
boolean retVal;
retVal = Str1.equals( Str2 );
System.out.println("Returned = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("Returned = " + retVal );
}
}
This produces following result:
Returned = true
Returned = true
boolean equalsIgnoreCase(String
anotherString)
Compares this String to another String,
ignoring case considerations.
Modify the example given in the equals method description as shown
below.
String Str4 = new String("Maltepe");
retVal = Str1.equalsIgnoreCase( Str4 );
System.out.println("Returned = " + retVal );
int length()
Returns the length of this string. public class Test{
public static void main(String args[]){
String Str2 = new String("Tutorials" );
System.out.print("String Length :" );
System.out.println(Str2.length());
}
}
This produces following result:
String Length :9
String replace(char oldChar, char
newChar)
Returns a new string resulting from
replacing all occurrences of oldChar in this
string with newChar.
public class Test{
public static void main(String args[]){
String Str =new String("Maltepe University");
System.out.print("Return Value :" );
System.out.println(Str.replace('e', 'i'));
}
}
This produces following result:
Return Value :Maltipi Univirsity
String toLowerCase()
Converts all of the characters in this String
to lower case using the rules of the default
locale.
public class Test{
public static void main(String args[]){
String Str =new String("Maltepe University");
System.out.print("Return Value :");
System.out.println(Str.toLowerCase());
}
}
This produces following result:
Return Value :maltepe university
String toLowerCase(Locale locale)
Converts all of the characters in this String
to lower case using the rules of the given
Locale.
public class Test{
public static void main(String args[]){
String Str = “ILLAKI”;
System.out.println(Str.toLowerCase(new Locale("en")));
System.out.println(Str.toLowerCase());
}
}
This produces following result:
illaki
ıllakı
String toUpperCase()
Converts all of the characters in this String
to upper case using the rules of the default
locale.
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Java");
System.out.print("Return Value :" );
System.out.println(Str.toUpperCase() );
}
}
This produces following result:
Return Value :WELCOME TO JAVA
String toUpperCase(Locale locale)
Converts all of the characters in this String
to upper case using the rules of the given
Locale.
public class Test{
public static void main(String args[]){
String Str = “illaki”;
System.out.println(Str.toUpperCase(new Locale("en")));
System.out.println(Str.toUpperCase());
}
}
This produces following result:
ILLAKI
İLLAKİ
String trim()
Returns a copy of the string, with leading
and trailing whitespace omitted.
public class Test{
public static void main(String args[]){
String Str = new String(" Welcome to
Tutorials ");
System.out.print("Return Value :" );
System.out.println(Str.trim() );
}
}
This produces following result:
Return Value :Welcome to Tutorials
11.4.1 indexOf()
This method has following different variants:
public int indexOf(int ch): Returns the index within this string of the first
occurrence of the specified character or -1 if the character does not occur.
public int indexOf(int ch, int fromIndex): Returns the index within this string
of the first occurrence of the specified character, starting the search at the
specified index or -1 if the character does not occur.
int indexOf(String str): Returns the index within this string of the first
occurrence of the specified substring. If it does not occur as a substring, -1 is
returned.
int indexOf(String str, int fromIndex): Returns the index within this string of
the first occurrence of the specified substring, starting at the specified index. If
it does not occur, -1 is returned.
Here is the syntax of this method:
public int indexOf(int ch )
public int indexOf(int ch, int fromIndex)
int indexOf(String str)
int indexOf(String str, int fromIndex)
Here is the detail of parameters:
ch -- a character.
fromIndex -- the index to start the search from.
str -- a string.
Example
public class Test {
public static void main(String args[]) {
String Str = new String("Welcome to Tutorials about Java");
String SubStr1 = new String("Tutorials");
String SubStr2 = new String("Sutorials");
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o' ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( 'o', 5 ));
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1 ));
System.out.print("Found Index :" );
System.out.println( Str.indexOf( SubStr1, 15 ));
System.out.print("Found Index :" );
System.out.println(Str.indexOf( SubStr2 ));
}
}
This produces following result:
Found Index :4
Found Index :9
Found Index :11
Found Index :-1
Found Index :-1
11.4.2 split()
This method has two variants and splits this string around matches of the given
regular expression.
Here is the syntax of this method:
public String[] split(String regex, int limit)
public String[] split(String regex)
Here is the detail of parameters:
regex -- the delimiting regular expression.
limit -- the result threshold which means how many strings to be returned.
Example
public class Test{
public static void main(String args[]){
String Str = new String("Jim-Jack-Marry-David");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 2)){
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 3)){
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-", 0)){
System.out.println(retval);
}
System.out.println("");
System.out.println("Return Value :" );
for (String retval: Str.split("-")){
System.out.println(retval);
}
}
}
This produces following result:
Return Value :
Jim
Jack-Marry-David
Return Value :
Jim
Jack
Marry-David
Return Value :
Jim
Jack
Marry
David
Return Value :
Jim
Jack
Marry
David
11.4.3 startsWith()
This method has two variants and tests if a string starts with the specified prefix
beginning a specified index or by default at the beginning.
Here is the syntax of this method:
public boolean startsWith(String prefix, int toffset)
public boolean startsWith(String prefix)
Here is the detail of parameters:
prefix -- the prefix to be matched.
toffset -- where to begin looking in the string.
Example
import java.io.*;
public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorials");
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Welcome") );
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Tutorials") );
System.out.print("Return Value :" );
System.out.println(Str.startsWith("Tutorials", 11) );
}
}
This produces following result:
Return Value :true
Return Value :false
Return Value :true
11.4.3 subSequence()
This method returns a new character sequence that is a subsequence of this
sequence.
Here is the syntax of this method:
public CharSequence subSequence(int beginIndex, int endIndex)
Here is the detail of parameters:
beginIndex -- the begin index, inclusive.
endIndex -- the end index, exclusive.
Example public class Test{
public static void main(String args[]){
String Str = new String("Welcome to Tutorials");
System.out.print("Return Value :" );
System.out.println(Str.subSequence(0, 10) );
System.out.print("Return Value :" );
System.out.println(Str.subSequence(10, 15) );
}
}
PART 12 12. Arrays
Java provides a data structure, the array, which stores a fixed-size sequential
collection of elements of the same type. An array is used to store a collection of data,
but it is often more useful to think of an array as a collection of variables of the same
type.
Instead of declaring individual variables, such as number0, number1, ..., and
number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables.
12.1 Declaring Array Variables
To use an array in a program, you must declare a variable to reference the array, and
you must specify the type of array the variable can reference. Here is the syntax for
declaring an array variable:
double[] myList; // preferred way.
or
double myList[]; // works but not preferred way,
// comes from the C/C++ language and was adopted in Java to accommodate C/C++ programmers.
12.2 Creating Arrays
You can create an array by using the new operator with the following syntax:
Following statement declares an array variable, myList, creates an array of 10
elements of double type, and assigns its reference to myList.:
double[] myList = new double[10];
Following picture represents array myList. Here myList holds ten double values and
the indices are from 0 to 9.
12.3 Processing Arrays
When processing array elements, we often use either for loop or foreach loop
because all of the elements in an array are of the same type and the size of the array
is known.
Example
Here is a complete example of showing how to create, initialize and process arrays:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (int i = 0; i < myList.length; i++) {
System.out.println(myList[i] + " ");
}
// Summing all elements
double total = 0;
for (int i = 0; i < myList.length; i++) {
total += myList[i];
}
System.out.println("Total is " + total);
// Finding the largest element
double max = myList[0];
for (int i = 1; i < myList.length; i++) {
if (myList[i] > max) max = myList[i];
}
System.out.println("Max is " + max);
}
}
This would produce following result:
1.9
2.9
3.4
3.5
Total is 11.7
Max is 3.5
12.4 The foreach Loops
JDK 1.5 introduced a new for loop, known as foreach loop or enhanced for loop,
which enables you to traverse the complete array sequentially without using an index
variable.
Example
The following code displays all the elements in the array myList:
public class TestArray {
public static void main(String[] args) {
double[] myList = {1.9, 2.9, 3.4, 3.5};
// Print all the array elements
for (double element: myList) {
System.out.println(element);
}
}
}
This would produce following result:
1.9
2.9
3.4
3.5
12.5 Passing Arrays to Methods
Just as you can pass primitive type values to methods, you can also pass arrays to
methods. For example, the following method displays the elements in an int array:
public static void printArray(int[] array) {
for (int i = 0; i < array.length; i++) {
System.out.print(array[i] + " ");
}
}
You can invoke it by passing an array. For example, the following statement invokes
the printArray method to display 3, 1, 2, 6, 4, and 2:
printArray(new int[]{3, 1, 2, 6, 4, 2});
12.6 sort() and binarySearch()
import java.util.Arrays;
public class ArrayDemo {
public static void main(String[] args) {
// initializing unsorted int array
int[] intArr = {30,20,5,12,55};
// sorting array
Arrays.sort(intArr);
// let us print all the elements available in list
System.out.println("The sorted int array is:");
for (int number : intArr) {
System.out.println("Number = " + number);
}
// entering the value to be searched
int searchVal = 12;
int retVal = Arrays.binarySearch(intArr,searchVal);
System.out.println("The index of element 12 is : " + retVal);
}
}
Let us compile and run the above program, this will produce the following result:
The sorted int array is:
Number = 5
Number = 12
Number = 20
Number = 30
Number = 55
The index of element 12 is : 1
Top Related