Array: Array is the most important thing in any programming language.
By definition, array is the static memory allocation. It allocates the memory
for the same data type in sequence. It contains multiple values of same types.
It also store the values in memory at the fixed size. Multiple types of arrays
are used in any programming language such as: one - dimensional, two -
dimensional or can say multi - dimensional.
Declaration of an array:
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as:
int num[] = {50,20,45,82,25,63};
int num[]; or int num = new int[2];
Some times user declares an array and it's size simultaneously. You may or may not be define the size in the declaration time. such as:
int num[] = {50,20,45,82,25,63};
In this program we will see how to
declare and implementation. This program illustrates that the array working
way. This program takes the numbers present in the num[]
array in unordered list and prints numbers in ascending order. In this program
the sort() function of the java.util.*; package is using to sort all the numbers
present in the num[] array. The Arrays.sort() automatically sorts the list of number
in ascending order by default. This function held the argument which is the
array name num.
Here is the code of the program:-
import java.util.*;
public class array{ public static void main(String[] args){ int num[] = {50,20,45,82,25,63}; int l = num.length; int i,j,t; System.out.print("Given number : "); for (i = 0;i < l;i++ ){ System.out.print(" " + num[i]); } System.out.println("\n"); System.out.print("Accending order number : "); Arrays.sort(num); for(i = 0;i < l;i++){ System.out.print(" " + num[i]); } } } |
Output of the program:
C:\chandan>javac
array.java
C:\chandan>java array Given number : 50 20 45 82 25 63 Ascending order number : 20 25 45 50 63 82 |
Now lets study the structure of Arrays in java. Array is
the most widely used data structure in java. It can contain multiple values of
the same type.
Structure of Java Arrays
Now lets study the structure of Arrays in java. Array is the most widely used data structure in java. It can contain multiple values of the same type. Moreover, arrays are always of fixed length i.e. the length of an array cannot be increased or decreased.Lets have a close look over the structure of Array. Array contains the values which are implicitly referenced through the index values. So to access the stored values in an array we use indexes. Suppose an array contains "n" integers. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "n-1" indexed value.
Presume an array that contains 12 elements as shown in the figure. Each element is holding a distinct value. Here the first element is refrenced by a[0] i.e. the first index value. We have filled the 12 distinct values in the array each referenced as:
a[0]=1
a[1]=2
...
a[n-1]=n
...
a[11]=12
The figure below shows the structure of an Array more precisely.
Two-Dimensional Arrays
Two-dimensional arrays are defined as "an array of arrays". Since an array type is a first-class Java type, we can have an array of ints, an array of Strings, or an array of Objects. For example, an array of ints will have the type int[]. Similarly we can have int[][], which represents an "array of arrays of ints". Such an array is said to be a two-dimensional array.The command
int[][] A = new int[3][4];
declares a variable, A, of type int[][], and it initializes that variable to refer to a newly created object. That object is an array of arrays of ints. Here, the notation int[3][4] indicates that there are 3 arrays of ints in the array A, and that there are 4 ints in each of those arrays.
To process a two-dimensional array, we use nested for loops. We already know about for loop. A loop in a loop is called a Nested loop. That means we can run another loop in a loop.
Notice in the following example how the rows are handled as separate objects.
Code: Java
int[][] a2 = new int[10][5];
// print array in rectangular form
for (int i=0; i<a2.length; i++) {
for (int j=0; j<a2[i].length; j++) {
System.out.print(" " + a2[i][j]);
}
System.out.println("");
}
|
Here is the complete code of the example:
public class twoDimension{ public static void main(String[] args) { int [][] a2 = new int [ 10 ][ 5 ]; for ( int i= 0 ; i<a2.length; i++) { for ( int j= 0 ; j<a2[i].length; j++) { a2[i][j] = i; System.out.print( " " + a2[i][j]); } System.out.println( "" ); } } } |
C:\tamana>javac twoDimension.java
C:\tamana>java twoDimension
0 0 0 0 0
1 1 1 1 1
2 2 2 2 2
3 3 3 3 3
4 4 4 4 4
5 5 5 5 5
6 6 6 6 6
7 7 7 7 7
8 8 8 8 8
9 9 9 9 9
C:\tamana>_
|
Multi-dimensional arrays
So far we have studied about the one-dimensional and two-dimensional arrays. To store data in more dimensions a multi-dimensional array is used. A multi-dimensional array of dimension n is a collection of items. These items are accessed via n subscript expressions. For example, in a language that supports it, the element of the two-dimensional array x is denoted by x[i,j].The Java programming language does not really support multi-dimensional arrays. It does, however, supports an array of arrays. In Java, a two-dimensional array 'x' is an array of one-dimensional array. For instance :-
int[][] x = new int[3][5];
The expression x[i] is used to select the one-dimensional array; the expression x[i][j] is ued to select the element from that array. The first element of this array will be indexed with the "0" value and the last integer will be referenced by "length-1" indexed value. There is no array assignment operator.
Strings in java
Java String Class is immutable, i.e. Strings in java, once created and initialized, cannot be changed on the same reference. A java.lang.String class is final which implies no class and extend it. The java.lang.String class differs from other classes, one difference being that the String objects can be used with the += and + operators for concatenation.Two useful methods for String objects are equals( ) and substring( ). The equals( ) method is used for testing whether two Strings contain the same value. The substring( ) method is used to obtain a selected portion of a String.
Java.lang.String class creation
A simple String can be created using a string literal enclosed inside double quotes as shown;String str1 = “My name is bob”;
Since a string literal is a reference, it can be manipulated like any other String reference. The reference value of a string literal can be assigned to another String reference.
If 2 or more Strings have the same set of characters in the same sequence then they share the same reference in memory. Below illustrates this phenomenon.
String str1 = “My name is bob”;
String str2 = “My name is bob”;
String str3 = “My name ”+ “is bob”; //Compile time expression
String name = “bob”;
String str4 = “My name is” + name;
String str5 = new String(“My name is bob”);
In the above code all the String references str1, str2 and str3 denote the same String object, initialized with the character string: “My name is bob”. But the Strings str4 and str5 denote new String objects.
Constructing String objects can also be done from arrays of bytes, arrays of characters, or string buffers. A simple way to convert any primitive value to its string representation is by concatenating it with the empty string (”"), using the string concatenation operator (+).
public class StringsDemo {
public static void main(String[] args) {
byte[] bytes = {2, 4, 6, 8};
char[] characters = {'a', 'b', 'C', 'D'};
StringBuffer strBuffer = new StringBuffer("abcde");
// Examples of Creation of Strings
String byteStr = new String(bytes);
String charStr = new String(characters);
String buffStr = new String(strBuffer);
System.out.println("byteStr : "+byteStr);
System.out.println("charStr : "+charStr);
System.out.println("buffStr : "+buffStr);
}
}
|
byteStr :
charStr : abCD
buffStr : abcde
String Equality
public class StringsDemo2 { public static void main(String[] args) { String str1 = "My name is bob"; String str2 = "My name is bob"; String str3 = "My name " + "is bob"; //Compile time expression String name = "bob"; String str4 = "My name is " + name; String str5 = new String("My name is bob"); System.out.println("str1 == str2 : " + (str1 == str2)); System.out.println("str2 == str3 : " + (str2 == str3)); System.out.println("str3 == str1 : " + (str3 == str1)); System.out.println("str4 == str5 : " + (str4 == str5)); System.out.println("str1 == str4 : " + (str1 == str4)); System.out.println("str1 == str5 : " + (str1 == str5)); System.out.println("str1.equals(str2) : " + str1.equals(str2)); System.out.println("str2.equals(str3) : " + str2.equals(str3)); System.out.println("str3.equals(str1) : " + str3.equals(str1)); System.out.println("str4.equals(str5) : " + str4.equals(str5)); System.out.println("str1.equals(str4) : " + str1.equals(str4)); System.out.println("str1.equals(str5) : " + str1.equals(str5)); } } |
str1 == str2 : true
str2 == str3 : true
str3 == str1 : true
str4 == str5 : false
str1 == str4 : false
str1 == str5 : false
str1.equals(str2) : true
str2.equals(str3) : true
str3.equals(str1) : true
str4.equals(str5) : true
str1.equals(str4) : true
str1.equals(str5) : true
Java String Functions
The following program explains the usage of the some of the basic String methods like ;1. compareTo(String anotherString)
Compares two strings lexicographically.
2. charAt(int index)
Returns the character at the specified index.
3. getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
Copies characters from this string into the destination character array.
4. length()
Returns the length of this string.
5. equals(Object anObject)
Compares this string to the specified object.
6. equalsIgnoreCase(String anotherString)
Compares this String to another String, ignoring case considerations.
7. toUpperCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
7. toLowerCase()
Converts all of the characters in this String to upper case using the rules of the default locale.
9. concat(String str)
Concatenates the specified string to the end of this string.
10. indexOf(int ch)
Returns the index within this string of the first occurrence of the specified character.
11. 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.
12. indexOf(String str)
Returns the index within this string of the first occurrence of the specified substring.
13. indexOf(String str, int fromIndex)
Returns the index within this string of the first occurrence of the specified substring, starting at the specified index.
14. lastIndexOf(int ch)
Returns the index within this string of the last occurrence of the specified character.
15. lastIndexOf(int ch, int fromIndex)
Returns the index within this string of the last occurrence of the specified character, searching backward starting at the specified index.
16. lastIndexOf(String str)
Returns the index within this string of the rightmost occurrence of the specified substring.
17. lastIndexOf(String str, int fromIndex)
Returns the index within this string of the last occurrence of the specified substring, searching backward starting at the specified index.
18. substring(int beginIndex)
Returns a new string that is a substring of this string.
19. substring(int beginIndex, int endIndex)
Returns a new string that is a substring of this string.
20. replace(char oldChar, char newChar)
Returns a new string resulting from replacing all occurrences of oldChar in this string with newChar.
21. trim()
Returns a copy of the string, with leading and trailing whitespace omitted.
22. toString()
This object (which is already a string!) is itself returned.
public class StringsDemo3 { public static void main(String[] args) { String str1 = "My name is bob"; char str2[] = new char[str1.length()]; String str3 = "bob"; String str4 = "cob"; String str5 = "BoB"; String str6 = "bob"; System.out.println("Length of the String str1 : " + str1.length()); System.out.println("Character at position 3 is : " + str1.charAt(3)); str1.getChars(0, str1.length(), str2, 0); System.out.print("The String str2 is : "); for (int i = 0; i < str2.length; i++) { System.out.print(str2[i]); } System.out.println(); System.out.print("Comparision Test : "); if (str3.compareTo(str4) < 0) { System.out.print(str3 + " < " + str4); } else if (str3.compareTo(str4) > 0) { System.out.print(str3 + " > " + str4); } else { System.out.print(str3 + " equals " + str4); } System.out.println(); System.out.print("Equals Test"); System.out.println("str3.equalsIgnoreCase(5) : " + str3.equalsIgnoreCase(str5)); System.out.println("str3.equals(6) : " + str3.equals(str6)); System.out.println("str1.equals(3) : " + str1.equals(str3)); str5.toUpperCase(); //Strings are immutable System.out.println("str5 : " + str5); String temp = str5.toUpperCase(); System.out.println("str5 Uppercase: " + temp); temp = str1.toLowerCase(); System.out.println("str1 Lowercase: " + str1); System.out.println("str1.concat(str4): " + str1.concat(str4)); String str7temp = " \t\n Now for some Search and Replace Examples ";
String str7 = str7temp.trim(); System.out.println("str7 : " + str7); String newStr = str7.replace('s', 'T'); System.out.println("newStr : " + newStr); System.out.println("indexof Operations on Strings"); System.out.println("Index of p in " + str7 + " : " + str7.indexOf('p')); System.out.println("Index of for in " + str7 + " : " + str7.indexOf("for")); System.out.println("str7.indexOf(for, 30) : " + str7.indexOf("for", 30)); System.out.println("str7.indexOf('p', 30) : " + str7.indexOf('p', 30)); System.out.println("str7.lastIndexOf('p') : " + str7.lastIndexOf('p')); System.out.println("str7.lastIndexOf('p', 4) : " + str7.lastIndexOf('p', 4)); System.out.print("SubString Operations on Strings"); String str8 = "SubString Example"; String sub5 = str8.substring(5); // "ring Example" String sub3_6 = str8.substring(3, 6); // "Str" System.out.println("str8 : " + str8); System.out.println("str8.substring(5) : " + sub5); System.out.println("str8.substring(3,6) : " + sub3_6); } } |
Length of the String str1 : 14
Character at position 3 is : n
The String str2 is : My name is bob
Comparision Test : bob < cob
Equals Teststr3.equalsIgnoreCase(5) : true
str3.equals(6) : true
str1.equals(3) : false
str5 : BoB
str5 Uppercase: BOB
str1 Lowercase: My name is bob
str1.concat(str4): My name is bobcob
str7 : Now for some Search and Replace Examples
newStr : Now for Tome Search and Replace ExampleT
Indexof Operations on Strings
Index of p in Now for some Search and Replace Examples : 26
Index of for in Now for some Search and Replace Examples : 4
str7.indexOf(for, 30) : -1
str7.indexOf(’p', 30) : 36
str7.lastIndexOf(’p') : 36
str7.lastIndexOf(’p', 4) : -1
SubString Operations on Stringsstr8 : SubString Example
str8.substring(5) : ring Example
str8.substring(3,6) : Str
Below is a program to check for Alpha Numeric character’s in the string.
public class TestAlphaNumericCharacters {
private void isAlphaNumeric(final String input) {
boolean isCharFlag = false;
boolean isNumberFlag = false;
final char[] chars = input.toCharArray();
for (int x = 0; x < chars.length; x++) {
char c = chars[x];
// lowercase && uppercase alphabet
if ((c >= 'a') && (c <= 'z') || (c >= 'A') && (c <= 'Z')) {
isCharFlag = true;
continue;
}
if ((c >= '0') && (c <= '9')) { // numeric
isNumberFlag = true;
continue;
}
}
System.out.println("characters are present:" + isCharFlag);
System.out.println("Numbers are present :" + isNumberFlag);
}
public static void main(String[] args) {
TestAlphaNumericCharacters tANC = new TestAlphaNumericCharacters();
tANC.isAlphaNumeric("beginn3ers");
}
}
|
characters are present:true
Numbers are present :true
Below is a java program to Reverse a string (Reverse by words / characters)
import java.util.*; public class StringReverse { public static void main(String[] args) { String input = "beginner java tutorial"; Stack stack = new Stack(); //A Stack is a Last In First Out Data Structure StringTokenizer stringTokenizer = new StringTokenizer(input); while (stringTokenizer.hasMoreTokens()) { stack.push(stringTokenizer.nextElement()); } System.out.println("Original String: " + input); System.out.print("Reversed String by Words: "); while (!stack.empty()) { System.out.print(stack.pop()); System.out.print(" "); } System.out.println(); System.out.print("Reversed String by characters: "); StringBuffer rev = new StringBuffer(input).reverse(); System.out.print(rev); } } |
Original String: beginner java tutorial
Reversed String by Words: tutorial java beginner
Reversed String by characters: lairotut avaj rennigeb
Java String Comparison:
Java
String compare to determine Equality
java string compare can be done in
many ways as shown below. Depending on the type of java string compare
you need, each of them is used.
* == Operator
* equals method
* compareTo method
* equals method
* compareTo method
Comparing using the == Operator
The == operator is used when we have
to compare the String object references. If two String variables point to the
same object in memory, the comparison returns true. Otherwise, the comparison
returns false. Note that the ‘==’ operator does not compare the content of the
text present in the String objects. It only compares the references the 2
Strings are pointing to. The following Program would print “The strings are
unequal” In the first case and “The strings are equal” in the second case.
<br
/><font size=-1>
public class StringComparision1 {
public static
void main(String[] args) {
String
name1 = "Bob";
String
name2 = new String("Bob");
String
name3 = "Bob";
// 1st
case
if
(name1 == name2) {
System.out.println("The
strings are equal.");
} else
{
System.out.println("The
strings are unequal.");
}
// 2nd
case
if
(name1 == name3) {
System.out.println("The
strings are equal.");
} else
{
System.out.println("The
strings are unequal.");
}
}
}
|
Comparing using the equals Method
The equals method is used when we
need to compare the content of the text present in the String objects. This
method returns true when two String objects hold the same content (i.e. the
same values). The following Program would print “The strings are unequal” In
the first case and “The strings are equal” in the second case.
public class StringComparision2 {
public static
void main(String[] args) {
String
name1 = "Bob";
String
name2 = new String("Bob1");
String
name3 = "Bob";
// 1st
case
if
(name1.equals(name2)) {
System.out.println("The
strings are equal.");
} else
{
System.out.println("The
strings are unequal.");
}
// 2nd
case
if
(name1.equals(name3)) {
System.out.println("The
strings are equal.");
} else
{
System.out.println("The
strings are unequal.");
}
}
}
|
Comparing using the compareTo Method
The compareTo method is used when we
need to determine the order of Strings lexicographically. It compares char
values similar to the equals method. The compareTo method returns a negative
integer if the first String object precedes the second string. It returns zero
if the 2 strings being compared are equal. It returns a positive integer if the
first String object follows the second string. The following Program would
print “name2 follows name1” In the first case and “name1 follows name3” in the
second case.
public class StringComparision3 {
public static
void main(String[] args) {
String
name1 = "bob";
String
name2 = new String("cob");
String
name3 = "Bob";
// 1st
case
if
(name1.compareTo(name2) == 0) {
System.out.println("The
strings are equal.");
} else
if (name1.compareTo(name2) < 0) {
System.out.println("name2
follows name1");
} else
{
System.out.println("name1
follows name2");
}
// 2nd
case. Comparing Ascii Uppercase will be smaller then Lower Case
if
(name1.compareTo(name3) == 0) {
System.out.println("The
strings are equal.");
} else
if (name1.compareTo(name3) < 0) {
System.out.println("name3
follows name1");
} else
{
System.out.println("name1
follows name3");
}
}
}
|
Java String Buffer:
StringBuffer Class
StringBuffer class is a mutable class unlike the String class which is immutable. Both the capacity and character string of a StringBuffer Class. StringBuffer can be changed dynamically. String buffers are preferred when heavy modification of character strings is involved (appending, inserting, deleting, modifying etc).Strings can be obtained from string buffers. Since the StringBuffer class does not override the equals() method from the Object class, contents of string buffers should be converted to String objects for string comparison.
A StringIndexOutOfBoundsException is thrown if an index is not valid when using wrong index in String Buffer manipulations
Creation of StringBuffers
StringBuffer Constructorspublic class StringBufferDemo { public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bob"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf2 capacity : " + strBuf2.capacity()); System.out.println("strBuf3 capacity : " + strBuf3.capacity()); } } |
strBuf1 : Bob
strBuf2 capacity : 100
strBuf3 capacity : 16
StringBuffer Functions
The following program explains the usage of the some of the basic StringBuffer methods like ;1. capacity()
Returns the current capacity of the String buffer.
2. length()
Returns the length (character count) of this string buffer.
3. charAt(int index)
The specified character of the sequence currently represented by the string buffer, as indicated by the index argument, is returned.
4. setCharAt(int index, char ch)
The character at the specified index of this string buffer is set to ch
5. toString()
Converts to a string representing the data in this string buffer
6. insert(int offset, char c)
Inserts the string representation of the char argument into this string buffer.
Note that the StringBuffer class has got many overloaded ‘insert’ methods which can be used based on the application need.
7. delete(int start, int end)
Removes the characters in a substring of this StringBuffer
8. replace(int start, int end, String str)
Replaces the characters in a substring of this StringBuffer with characters in the specified String.
9. reverse()
The character sequence contained in this string buffer is replaced by the reverse of the sequence.
10. append(String str)
Appends the string to this string buffer.
Note that the StringBuffer class has got many overloaded ‘append’ methods which can be used based on the application need.
11. setLength(int newLength)
Sets the length of this String buffer.
public class StringBufferFunctionsDemo { public static void main(String[] args) { // Examples of Creation of Strings StringBuffer strBuf1 = new StringBuffer("Bobby"); StringBuffer strBuf2 = new StringBuffer(100); //With capacity 100 StringBuffer strBuf3 = new StringBuffer(); //Default Capacity 16 System.out.println("strBuf1 : " + strBuf1); System.out.println("strBuf1 capacity : " + strBuf1.capacity()); System.out.println("strBuf2 capacity : " + strBuf2.capacity()); System.out.println("strBuf3 capacity : " + strBuf3.capacity()); System.out.println("strBuf1 length : " + strBuf1.length()); System.out.println("strBuf1 charAt 2 : " + strBuf1.charAt(2)); // A StringIndexOutOfBoundsException is thrown if the index is not valid. strBuf1.setCharAt(1, 't'); System.out.println("strBuf1 after setCharAt 1 to t is : " + strBuf1); System.out .println("strBuf1 toString() is : " + strBuf1.toString()); strBuf3.append("beginner-java-tutorial"); System.out.println("strBuf3 when appended with a String : " + strBuf3.toString()); strBuf3.insert(1, 'c'); System.out.println("strBuf3 when c is inserted at 1 : " + strBuf3.toString()); strBuf3.delete(1, 'c'); System.out.println("strBuf3 when c is deleted at 1 : " + strBuf3.toString()); strBuf3.reverse(); System.out.println("Reversed strBuf3 : " + strBuf3); strBuf2.setLength(5); strBuf2.append("jdbc-tutorial"); System.out.println("strBuf2 : " + strBuf2); // We can clear a StringBuffer using the following line
strBuf2.setLength(0); System.out.println("strBuf2 when cleared using setLength(0): " + strBuf2); } } |
strBuf1 : Bobby
strBuf1 capacity : 21
strBuf2 capacity : 100
strBuf3 capacity : 16
strBuf1 length : 5
strBuf1 charAt 2 : b
strBuf1 after setCharAt 1 to t is : Btbby
strBuf1 toString() is : Btbby
strBuf3 when appended with a String : beginner-java-tutorial
strBuf3 when c is inserted at 1 : bceginner-java-tutorial
strBuf3 when c is deleted at 1 : b
Reversed strBuf3 : b
strBuf2 :
Vector implements a dynamic array. It is similar to ArrayList,
but with two differences: Vector is synchronized, and it contains
many legacy methods that are not part of the collections framework. With the
release of Java 2, Vector was reengineered to extend AbstractList and
implement the List interface, so it now is fully compatible with
collections.
Here are the Vector constructors:
Vector( )
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
Vector(int size)
Vector(int size, int incr)
Vector(Collection c)
The first form creates a default
vector, which has an initial size of 10. The second form creates a vector whose
initial capacity is specified by size. The third form creates a vector
whose initial capacity is specified by size and whose increment is
specified by incr. The increment specifies the number of elements to
allocate each time that a vector is resized upward. The fourth form creates a
vector that contains the elements of collection c. This constructor was
added by Java 2.
All vectors start with an initial
capacity. After this initial capacity is reached, the next time that you
attempt to store an object in the vector, the vector automatically allocates
space for that object plus extra room for additional objects. By allocating
more than just the required memory, the vector reduces the number of
allocations that must take place. This reduction is important, because
allocations are costly in terms of time. The amount of extra space allocated
during each reallocation is determined by the increment that you specify when
you create the vector. If you don't specify an increment, the vector's size is
doubled by each allocation cycle.
Vector
:defines these protected data
members:
int capacityIncrement;
int elementCount;
Object elementData[ ];
int elementCount;
Object elementData[ ];
The increment value is stored in capacityIncrement.
The number of elements currently in the vector is stored in elementCount.
The array that holds the vector is stored in elementData.
Because Vector implements List,
you can use a vector just like you use an ArrayList instance. You can
also manipulate one using its legacy methods. For example, after you
instantiate a Vector, you can add an element to it by calling addElement(
). To obtain the element at a specific location, call elementAt( ).
To obtain the first element in the vector, call firstElement( ). To
retrieve the last element, call lastElement( ). You can obtain the index
of an element by using indexOf( ) and lastIndexOf( ). To remove
an element, call removeElement( ) or removeElementAt( ).
The following program uses a vector
to store various types of numeric objects. It demonstrates several of the
legacy methods defined by Vector. It also demonstrates the Enumeration
interface.
// Demonstrate various Vector
operations.
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
import java.util.*;
class VectorDemo {
public static void main(String args[]) {
// initial size is 3, increment is 2
Vector v = new Vector(3, 2);
System.out.println("Initial size: " + v.size());
System.out.println("Initial capacity: " +
v.capacity());
v.addElement(new Integer(1));
v.addElement(new Integer(2));
v.addElement(new Integer(3));
v.addElement(new Integer(4));
System.out.println("Capacity after four additions: " +
v.capacity());
v.addElement(new Double(5.45));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Double(6.08));
v.addElement(new Integer(7));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Float(9.4));
v.addElement(new Integer(10));
System.out.println("Current capacity: " +
v.capacity());
v.addElement(new Integer(11));
v.addElement(new Integer(12));
System.out.println("First element: " +
(Integer)v.firstElement());
System.out.println("Last element: " +
(Integer)v.lastElement());
if(v.contains(new Integer(3)))
System.out.println("Vector contains 3.");
// enumerate the elements in the vector.
Enumeration vEnum = v.elements();
System.out.println("\\nElements in vector:");
while(vEnum.hasMoreElements())
System.out.print(vEnum.nextElement() + " ");
System.out.println();
}
}
The output from this program is
shown here:
Initial size: 0
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
Initial capacity: 3
Capacity after four additions: 5
Current capacity: 5
Current capacity: 7
Current capacity: 9
First element: 1
Last element: 12
Vector contains 3.
Elements in vector:
1 2 3 4 5.45 6.08 7 9.4 10 11 12
With the release of Java 2, Vector
adds support for iterators. Instead of relying on an enumeration to cycle
through the objects (as the preceding program does), you now can use an
iterator. For example, the following iterator-based code can be substituted
into the program:
// use an iterator to display
contents
Iterator vItr = v.iterator();
System.out.println("\\nElements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next() + " ");
System.out.println();
Iterator vItr = v.iterator();
System.out.println("\\nElements in vector:");
while(vItr.hasNext())
System.out.print(vItr.next() + " ");
System.out.println();
Because enumerations are not
recommended for new code, you will usually use an iterator to enumerate the
contents of a vector. Of course, much legacy code exists that employs
enumerations. Fortunately, enumerations and iterators work in nearly the same
manner.
Wrapper Classes
In this section you will learn about Wrapper classes and all the methods that manipulate data and allows to operate a certain work.Wrapper class is a wrapper around a primitive data type. It represents primitive data types in their corresponding class instances e.g. a boolean data type can be represented as a Boolean class instance. All of the primitive wrapper classes in Java are immutable i.e. once assigned a value to a wrapper class instance cannot be changed further.
Wrapper Classes are used broadly with Collection classes in the java.util package and with the classes in the java.lang.reflect reflection package.
Following table lists the primitive types and the corresponding wrapper classes:
Primitive
|
Wrapper
|
boolean
|
java.lang.Boolean
|
byte
|
java.lang.Byte
|
char
|
java.lang.Character
|
double
|
java.lang.Double
|
float
|
java.lang.Float
|
int
|
java.lang.Integer
|
long
|
java.lang.Long
|
short
|
java.lang.Short
|
void
|
java.lang.Void
|
In Java 5.0 version, additional wrapper classes were
introduced in the java.util.concurrent.atomic package. They provide
atomic operations for assignment, addition and increment. These classes act
like variables and cannot be used as a substitute for the regular wrapper
classes. Few of these new wrapper classes like AtomicInteger and AtomicLong are
the subclasses of the Number Classes.
Primitive
|
Wrapper
|
boolean
|
AtomicBoolean
|
int
|
AtomicInteger
|
long
|
AtomicLong
|
V
|
AtomicReference<V>
|
Features Of the Wrapper Classes
Some of the sound features maintained by the Wrapper Classes are as under :- All the methods of the wrapper classes are static.
- The Wrapper class does not contain constructors.
- Once a value is assigned to a wrapper class instance it can not be changed, anymore.
Wrapper Classes : Methods with examples
There are some of the methods of the Wrapper class which are used to manipulate the data. Few of them are given below:1. add(int, Object): Learn to insert an element at the specified position.
2. add(Object): Learn to insert an object at the end of a list.
3. addAll(ArrayList): Learn to insert an array list of objects to another list.
4. get(): Learn to retrieve the elements contained with in an ArrayList object.
5. Integer.toBinaryString(): Learn to convert the Integer type object to a String object.
6. size(): Learn to get the dynamic capacity of a list.
7. remove(): Learn to remove an element from a particular position specified by a index value.
8. set(int, Object): Learn to replace an element at the position specified by a index value.
Java Interface
In Java, this multiple inheritance problem is solved with a powerful construct called interfaces. Interface can be used to define a generic template and then one or more abstract classes to define partial implementations of the interface. Interfaces just specify the method declaration (implicitly public and abstract) and can only contain fields (which are implicitly public static final). Interface definition begins with a keyword interface. An interface like that of an abstract class cannot be instantiated.Multiple Inheritance is allowed when extending interfaces i.e. one interface can extend none, one or more interfaces. Java does not support multiple inheritance, but it allows you to extend one class and implement many interfaces.
If a class that implements an interface does not define all the methods of the interface, then it must be declared abstract and the method definitions must be provided by the subclass that extends the abstract class.
Example 1: Below is an example of a Shape interface
interface Shape {
public double area();
public double volume();
}
|
public class Point implements Shape {
static int x, y;
public Point() {
x = 0;
y = 0;
}
public double area() {
return 0;
}
public double volume() {
return 0;
}
public static void print() {
System.out.println("point: " + x + "," + y);
}
public static void main(String args[]) {
Point p = new Point();
p.print();
}
}
|
Example 2: Below is a java interfaces program showing the power of interface programming in java
Listing below shows 2 interfaces and 4 classes one being an abstract class.
Note: The method toString in class A1 is an overridden version of the method defined in the class named Object. The classes B1 and C1 satisfy the interface contract. But since the class D1 does not define all the methods of the implemented interface I2, the class D1 is declared abstract.
Also,
i1.methodI2() produces a compilation error as the method is not declared in I1 or any of its super interfaces if present. Hence a downcast of interface reference I1 solves the problem as shown in the program. The same problem applies to i1.methodA1(), which is again resolved by a downcast.
When we invoke the toString() method which is a method of an Object, there does not seem to be any problem as every interface or class extends Object and any class can override the default toString() to suit your application needs. ((C1)o1).methodI1() compiles successfully, but produces a ClassCastException at runtime. This is because B1 does not have any relationship with C1 except they are “siblings”. You can’t cast siblings into one another.
When a given interface method is invoked on a given reference, the behavior that results will be appropriate to the class from which that particular object was instantiated. This is runtime polymorphism based on interfaces and overridden methods.
interface I1 { void methodI1(); // public static by default } interface I2 extends I1 { void methodI2(); // public static by default } class A1 { public String methodA1() { String strA1 = "I am in methodC1 of class A1"; return strA1; } public String toString() { return "toString() method of class A1"; } } class B1 extends A1 implements I2 { public void methodI1() { System.out.println("I am in methodI1 of class B1"); } public void methodI2() { System.out.println("I am in methodI2 of class B1"); } } class C1 implements I2 { public void methodI1() { System.out.println("I am in methodI1 of class C1"); } public void methodI2() { System.out.println("I am in methodI2 of class C1"); } } // Note that the class is declared as abstract as it does not // satisfy the interface contract abstract class D1 implements I2 { public void methodI1() { } // This class does not implement methodI2() hence declared abstract. } public class InterFaceEx { public static void main(String[] args) { I1 i1 = new B1(); i1.methodI1(); // OK as methodI1 is present in B1 // i1.methodI2(); Compilation error as methodI2 not present in I1 // Casting to convert the type of the reference from type I1 to type I2 ((I2) i1).methodI2(); I2 i2 = new B1(); i2.methodI1(); // OK i2.methodI2(); // OK // Does not Compile as methodA1() not present in interface reference I1 // String var = i1.methodA1(); // Hence I1 requires a cast to invoke methodA1 String var2 = ((A1) i1).methodA1(); System.out.println("var2 : " + var2); String var3 = ((B1) i1).methodA1(); System.out.println("var3 : " + var3); String var4 = i1.toString(); System.out.println("var4 : " + var4); String var5 = i2.toString(); System.out.println("var5 : " + var5); I1 i3 = new C1(); String var6 = i3.toString(); System.out.println("var6 : " + var6); // It prints the Object toString() method Object o1 = new B1(); // o1.methodI1(); does not compile as Object class does not define // methodI1() // To solve the probelm we need to downcast o1 reference. We can do it // in the following 4 ways ((I1) o1).methodI1(); // 1 ((I2) o1).methodI1(); // 2 ((B1) o1).methodI1(); // 3 /* * * B1 does not have any relationship with C1 except they are "siblings". * * Well, you can't cast siblings into one another. * */ // ((C1)o1).methodI1(); Produces a ClassCastException } } |
I am in methodI1 of class B1
I am in methodI2 of class B1
I am in methodI1 of class B1
I am in methodI2 of class B1
var2 : I am in methodC1 of class A1
var3 : I am in methodC1 of class A1
var4 : toString() method of class A1
var5 : toString() method of class A1
var6 : C1@190d11
I am in methodI1 of class B1
I am in methodI1 of class B1
I am in methodI1 of class B1
Enum Data Types
Enum type is a type which consist of fixed set of constant fields. like direction and days includes values NORTH, SOUTH, EAST, and WEST and SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY and SATURDAY respectively. Since they are constants so we are taking these values into the uppercase letters.Lets take an example of enum data types:
EnumTestResult.java
public class EnumTestResult { DaysOfWeek day; public EnumTestResult(DaysOfWeek day) { this.day = day; } public void howsday() { switch (day) { case MONDAY: System.out.println("Mondays are working days."); break; case THURSDAY: System.out.println
("Thursday are also working days."); break; case SATURDAY: case SUNDAY: System.out.println("Weekends are best."); break; default: System.out.println("Midweek days are so-so."); break; } } public static void main(String[] args) { EnumTestResult FirstDay = new EnumTestResult(DaysOfWeek.MONDAY); FirstDay.howsday(); EnumTestResult ThirdDay = new EnumTestResult(DaysOfWeek.WEDNESDAY); ThirdDay.howsday(); EnumTestResult FourthDay = new EnumTestResult(DaysOfWeek.FRIDAY); FourthDay.howsday(); EnumTestResult SixthDay = new EnumTestResult(DaysOfWeek.SATURDAY); SixthDay.howsday(); EnumTestResult SeventhDay = new EnumTestResult(DaysOfWeek.SUNDAY); SeventhDay.howsday(); } } |
DaysOfWeek.java
public enum DaysOfWeek { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } |
C:\Documents and Settings\compaq
20\Desktop\Tutorials>java EnumTestResult
Mondays are working days. Midweek days are so-so. Midweek days are so-so. Weekends are best. Weekends are best. |
What Are Packages?
A package allows a developer to group classes (and interfaces) together. These classes will all be related in some way – they might all be to do with a specific application or perform a specific set of tasks. For example, the Java API is full of packages. One of them is the javax.xml package. It and its subpackages contain all the classes in the Java API to do with handling XML.Defining a Package
To group classes into a package each class must have a package statement defined at the top of its .java file. It lets the compiler know which package the class belongs to and must be the first line of code. For example, imagine you're making a simple Battleships game. It makes sense to put all the classes needed in a package called battleships: package battleships
class GameBoard{
}
Every class with the above package statement at the top will now be part of
the Battleships package. Typically packages are stored in a corresponding directory on the filesystem but it is possible to store them in a database. The directory on the filesystem must have the same name as the package. It's where all the classes belonging to that package are stored. For example, if the battleships package contains the classes GameBoard, Ship, ClientGUI then there will be files called GameBoard.java, Ship.java and ClientGUI.java stored in a directory call battleships.
Creating a Hierarchy
Organizing classes doesn't have to be at just one level. Every package can have as many subpackages as needed. To distinguish the package and subpackage a "." is placed in-between the package names. For example, the name of the javax.xml package shows that xml is a subpackage of the javax package. It doesn't stop there, under xml there are 11 subpackages: bind, crypto, datatype, namespace, parsers, soap, stream, transform, validation, ws and xpath.The directories on the file system must match the package hierarchy. For example, the classes in the javax.xml.crypto package will live in a directory structure of ..\javax\xml\crypto.
It should be noted that the hierarchy created is not recognized by the compiler. The names of the packages and subpackages show the relationship that the classes they contain have with each other. But, as far as the compiler is concerned each package is a distinct set of classes. It does not view a class in a subpackage as being part of its parent package. This distinction becomes more apparent when it comes to using packages.
Naming Packages
There is a standard naming convention for packages. Names should be in lowercase. With small projects that only have a few packages the names are typically simple (but meaningful!) names: package pokeranalyzer
package mycalculator
In software companies and large projects, where the packages might be
imported into other classes, the names need to be distinctive. If two different
packages contain a class with the same name it's important that there can be no
naming conflict. This is done by ensuring the package names are different by
starting the package name with the company domain, before being split into
layers or features: package com.mycompany.utilities
package org.bobscompany.application.userinterface
Using the Fully Qualified Name
Using a fully qualified name is the same principle as giving the full location of a file by adding its directory path. For example, to use a JOptionPane all I need to know is its package name is javax.swing:javax.swing.JOptionPane.showMessageDialog( null, "I'm fully qualified!");
This is fine in a one off situation but if a class needs to use several
JOptionPanes then writing the full name for each one is not very exciting for
the programmer.Import the Class
To avoid using the fully qualified name the packaged class can be specifically referenced. This is done using an import statement. Import statements are placed after the package statement but before the class declaration. To import just one class put its fully qualified name after the import keyword: package thisPackage;
import javax.swing.JOptionPane;
public class myClass{
JOptionPane.showMessageDialog(null, "Just my class is imported!");
}
As you can see from the above code the JOptionPane in myClass can now be
used by just using its class name. Import the Package
An advantage of importing each class used in a program separately is that a programmer can easily see which ones are being used. However, if a lot of classes are needed from the same package it might make more sense to just reference the entire package. For example, if a class is designed to create a complex user interface then a lot of the classes in the javax.swing package might be needed. In this case its easier to import the entire package by adding an ".*" at the end of the import statement: package thisPackage;
import javax.swing.*;
public class myClass{
JOptionPane.showMessageDialog(null, "My entire package is imported!");
}
The ".*" tells the compiler that the class might want to use any
of the classes contained in the javax.swing package. It does not include the
classes in any subpackages. For example, if the class needed to use the
EtchedBorder class in the javax.swing.border package it would need to be
imported separately: import javax.swing.*;
import javax.swing.border.EtchedBorder;
There is no run-time overhead incurred by importing the entire package – the
compiled code will be the same size whether each individual class or the entire
package is referenced. The choice is mainly about the readability of the code.Using Classes With the Same Name
If there are two classes that share the same name but are imported from different packages, the compiler will get confused and the code will not compile: import apackage.Person;
import anotherpackage.Person;
If both classes need to be used then use their fully qualified names to
avoid compiler (and programmer) confusion: apackage.Person bob = new apackage.Person();
anotherpackage.Person bill = new anotherpackage.Person();
Importing Static Fields and Methods
There is a shortcut for using static fields and static methods in a class. By adding the static modifier to the import statement the class name for the static field or static method is not needed. For example, all the color static fields can be imported by using: import static java.awt.Color.*;
In the code the color constants can then be used without the need for the
color class prefix: JButton pressMeButton = new JButton("Press Me");
pressMeButton.setForeground(RED);
Be careful with the use of static imports because they can cause readability
issues for programmers new to the code. It can be hard to spot a static field
without its class name attached. What Is a Naming Convention?
A naming convention is a rule to follow as you decide what to name your identifiers (e.g. class, package, variable, method, etc..).Why Use Naming Conventions?
Different Java programmers can have different styles and approaches to the way they program. By using standard Java naming conventions they make their code easier to read for themselves and for other programmers. Readability of Java code is important because it means less time is spent trying to figure out what the code does, leaving more time to fix or modify it.To illustrate the point it's worth mentioning that most software companies will have a document that outlines the naming conventions they want their programmers to follow. A new programmer who becomes familiar with those rules will be able to understand code written by a programmer who might have left the company many years before hand.
Picking a Name for Your Identifier
When choosing a name for an identifier make sure it's meaningful. For instance, if your program deals with customer accounts then choose names that make sense to dealing with customers and their accounts (e.g., customerName, accountDetails). Don't worry about the length of the name. A longer name that sums up the identifier perfectly is preferable to a shorter name that might be quick to type but ambiguous.A Few Words About Cases
Using the right letter case is the key to following a naming convention:
·
Lowercase is where all the letters in a
word are written without any capitalization (e.g., while, if, mypackage).
·
Uppercase is where all the letters in a
word are written in capitals. When there are more than two words in the name
use underscores to separate them (e.g., MAX_HOURS, FIRST_DAY_OF_WEEK).
·
CamelCase (also known as Upper CamelCase)
is where each new word begins with a capital letter (e.g., CamelCase,
CustomerAccount, PlayingCard).
·
Mixed case (also known as Lower
CamelCase) is the same as CamelCase except the first letter of the name is in
lowercase (e.g., hasChildren, customerFirstName, customerLastName).
Standard Java Naming Conventions
The below list outlines the standard Java naming conventions for each identifier type:- Packages: Names should be in lowercase. With small projects that only have a few packages it's okay to just give them simple (but meaningful!) names:
·
package pokeranalyzer
package mycalculator
In software companies and large projects where the packages
might be imported into other classes, the names will normally be subdivided.
Typically this will start with the company domain before being split into
layers or features:
package com.mycompany.utilities
package org.bobscompany.application.userinterface
- Classes: Names should be in CamelCase. Try to use nouns because a class is normally representing something in the real world:
·
class Customer
class Account
- Interfaces: Names should be in CamelCase. They tend to have a name that describes an operation that a class can do:
·
interface Comparable
interface Enumerable
Note that some programmers like to distinguish interfaces by
beginning the name with an "I":
interface IComparable
interface IEnumerable
- Methods: Names should be in mixed case. Use verbs to describe what the method does:
·
void calculateTax()
string getSurname()
- Variables: Names should be in mixed case. The names should represent what the value of the variable represents:
·
string firstName
int orderNumber
Only use very short names when the variables are short lived,
such as in for loops:
for (int i=0; i<20;i++)
{
//i only lives in here
}
- Constants: Names should be in uppercase.
·
static final int DEFAULT_WIDTH
static final int MAX_HEIGHT
No comments:
Post a Comment