At the end of the chapter, you will be able to understand and write programs using
In Chapters 15 and 16 you have been introduced to some simple IO statements. We continue in this chapter to introduce you to further IO programs as these are required for carrying out meaningful programming in Java. You will learn techniques to input primitive data types using BufferedReader and InputStreamReader and read() and readline() commands. StringTokenizer which will be used for inputting multiple data in a single line will also be introduced in this chapter.
In this section, we will see how to take string and numeric input for Java applications using standard input or output and in Java keyboard is represented by
We will use BufferedReader to read one String per line. Figure 17.1 shows two streams – InputStreamReader and BufferedReader – that are connected together. Two streams are required because the computer is a high-speed device and keyboard is a slow device. InputStreamreader accepts the input from keyboard and converts the ascii to data types required by computer and BufferedReader stores them so that Java can accept them when they are ready to be picked up.
Figure 17.1 Input from keyboard
We will read name of the student. We will also read identification number and marks of the student. We will also read s a single character from keyboard
Example 17.1: Student.java: To Obtain Input String, Int and Float Data from Console
// Example 17.1 Student.java : To obtain input String , int and double data from keyboard using InputStreamreader
1. package com.oops.chap17; 2. import java.io.*; 3. import javax.swing.*; 4. public class Student { 5. public static void main(String[] args) throws IOException{ 6. BufferedReader in; 7. in=new BufferedReader(new InputStreamReader(System.in)); 8. System.out.print(„Enter name : „); 9. String name =in.readLine(); 10. System.out.print(ʺEnter your Roll Number :ʺ); 11. String input=in.readLine(); 12. int id=Integer.parseInt(input); 13. System.out.print(ʺEnter your Total Marks : ʺ); 14. String input2=in.readLine(); 15. double totalmarks=Double.parseDouble(input2); 16. System.out.print(“Enter Grade of the Student : “); 17. char ch = (char) in.readLine().charAt(0); JOptionPane.showMessage Dialog(null,ʺName ʺ+ name + 18. ʺ Roll Number :ʺ + id +ʺ Total Marks :ʺ + 19. totalmarks+ʺ Grade ʺ + ch,ʺ output displayʺ ,JOptionPane.PLAIN_MESSAGE); } 20. } Output: Enter name : Ramesh Enter your Roll Number :50595 Enter your Total Marks : 999 Enter Grade of the Student : A
Those of you familiar with C will know that in scanf statement for receiving input from the keyboard we can read several variables together in a single line. How do we achieve the same result in Java? By using a class called StringTokenizer of java.util package. Firstly we create an object of String class and read the in:
String stg = input.readLine(); // to read a string from keyboard
Assume that our input data is separated by commas. For example, ʺRameshʺ , 50595,89.0,ʺAʺ representing name. RollNo, total marks and grade.
Make an object of StringTokenizer and pass the String object as a parameter to StringTokenizer object : StringTokenizer stkn = new StringTokenizer( stg, ʺ,ʺ);
String Tokenizer breaks the single line string into tokens based on the separating symbol comma. We can retrieve the token using nextToken(). String tkn = stkn.nextToken();
We will attempt a problem in which we will read name, number, credits and debits of an employee. Compute net pay and display the result.
Example 17.2: EmployeeCredits.java: To Obtain Multiple Inputs in a Single Line Using StringTokenizer.
1. package com.oops.chap17;
2. import java.util.*; // For using StringTokenizer()
3. import java.io.*;
4. import javax.swing.JOptionPane; // Swing components
5. public class EmployeeCredits {
6. public static void main(String[] args) throws IOException{
7. String name,idNo,crdts,debts;// variables or reading input date
8. double credits,debits,netPay; // variables for internal computations
9. BufferedReader input = new BufferedReader (new InputStreamReader (System.in));
10. System.out.println(ʺEnter Emp name, idNo,credits,debits separated by commaʺ);
11. String stg = input.readLine(); // multiple data separated by comma
12. StringTokenizer stkn = new StringTokenizer(stg,","); // object of StringTokenizer
13. name = stkn.nextToken(); // break into tokens
14. idNo = stkn.nextToken(); idNo.trim(); // trim is to remove leading trailing spaces
15. crdts = stkn.nextToken(); crdts.trim();
16. debts = stkn.nextToken();debts.trim();
17. // convert to double
18. credits = Double.parseDouble(crdts);
19. debits = Double.parseDouble(debts);
20. netPay = credits-debits;
21. JOptionPane.showMessageDialog(null,"Name "+ name +
22. " Id Number :" + idNo +"
Credits :" +
23. credits+" Debits " + debits +" Net Pay :"+ netPay,"Employee Pay Bill",JOptionPane.PLAIN_MESSAGE);
24. }
25. }
Line No. 2: | imports java.util.* a package housing StringTokenizer() |
Line No. 11: | String stg = input.readLine(); reads String input from keyboard. |
Line No. 14: | idNo = stkn.nextToken(); idNo.trim(); shows how to break a continuous string into token by using nextToken(). Further idNo.trim() removes leading and trailing spaces if any. |
Line No 17: | converts String to double data. This is required to do internal computations. |
While StringTokenizer class discussed in the previous section does its job, it is cumbersome in that we have to perform several tasks such as creating an object, passing an argument, using the trim() and finally to convert into primitive data type. Java has provided a simpler alternative called Scanner class in java.util package.
The first action is to create object. Scanner scn = new Scanner(System.in); int idNo = scn.nextInt(); is the only statement we need to use to begin the computing process. Similarly, nextDouble(), nextLong(), next.Float() would be used for other data types. Here in Scanner class, when data is inputted from keyboard, variables are required to be separated by spaces. Blank space will be treated as the end of a token.
Example 17.3: ScannerInput.java: To Obtain Multiple Inputs in a Single Line Using Scanner Class of Java
1. package com.oops.chap17;
2. import java.util.*; // for Scanner class
3. import java.io.*;
4. import javax.swing.JOptionPane;
5. public class ScannerInput {
6. public static void main(String[] args) throws IOException{
7. String name;// variables or reading input date
8. int idNo;
9. double credits,debits,netPay;
10. System.out.println(ʺEnter Emp name, idNo,credits,debits separated by spacesʺ);
11. Scanner scn = new Scanner(System.in);
12. name = scn.next();
13. idNo = scn.nextInt();
14. credits = scn.nextDouble();
15. debits = scn.nextDouble();
16. netPay = credits-debits;
17. JOptionPane.showMessageDialog(null,ʺName ʺ+ name +
18. ʺ Id Number :ʺ + idNo +ʺ
Credits :ʺ +
19. credits+ʺ Debits ʺ + debits +ʺ Net Pay :ʺ +
20. netPay,ʺ Employee Pay Billʺ ,JOptionPane.PLAIN_MESSAGE);
21. }
22. }
Line No. 2: | java.util.* for Scanner class. |
Line No. 11: | Scanner scn = new Scanner(System.in); creates an object of Scanner class. System.in represents key board. |
Line No. 12: | shows how to take in String data by using name=scn.next(); |
Line No. 13: | shows how to take in int data by using idNo=scn.nextInt(); |
Line Nos. 14 & 15: | shows how to take in Double data credits & debits by using : credits =scn.nextDouble(); debits=scn.nextDouble(); |
You might have used C language printf() command wherein we have used controlling formats to display primitive data types. Java also provides such a facility to format and display primitive data types using System.out.printf() command. The controlling formats offered by Java are shown in Table 17.1:
Table 17.1 Formatting for use with System.out.printf()
%s : String | %c : char | %d : Decimal Integer |
%f : float | %o : octal | % x or % X : hexa |
%n : new line | %e or %E : scientific notation |
1. package com.oops.chap17;
2. import java.util.*;
3. import java.io.*;
4. import javax.swing.JOptionPane;
5. public class PrintfJava {
6. public static void main(String[] args){
7. String name;// variables or reading input date
8. int idNo;
9. double credits,debits,netPay;
10. System.out.println(ʺEnter Emp name, idNo,credits,debits separated by spacesʺ);
11. Scanner scn = new Scanner(System.in);
12. name=scn.next();
13. idNo=scn.nextInt();
14. credits =scn.nextDouble();
15. debits=scn.nextDouble();
16. netPay=credits-debits;
17. System.out.println(ʺEmployee pay Bill…..ʺ);
18. System.out.printf(ʺString = name : %s idNo : %dʺ ,name,idNo );
19. System.out.printf(ʺString = Credits:%8.2f debits: %8.2f NetPay %8.2fʺ ,credits,debits,netPay );
20. }
21. }
22. Output: Enter Emp name, idNo,credits,debits separated by spaces
23. ʺRameshʺ 50595 20000.00 2000.00
24. Empleoyee pay Bill…..
25. String = name : ʺRameshʺ idNo : 50595String = Credits :20000.00 debits : 2000.00 NetPay 17000.00
Line No. 17: | shows the usage of System.out.printf() command. (ʺString = name : %s idNo : %dʺ ,name,idNo) is passed as an argument. |
Line No. 19: | shws usage of %8.2 f for credits , debits , and netPay fields. It means total formatting space of 8 spaces out of which 2 spaces after decimal. |
Java has provided an alternative to format when only strings are involved in outputting we can use String.format() method. This is a static method and hence can be called directly using String.format() method.
Example 17.5: StringFormat.java: To Send the Formatted Output Using String.format()
1. package com.oops.chap17;
2. import java.util.*;
3. import java.io.*;
4. public class StringFormat{
5. public static void main(String[] args){
6. String name;// variables or reading input date
7. int idNo;
8. double credits,debits,netPay;
9. System.out.println(ʺEnter Emp name, idNo,credits,debits separated by spacesʺ);
10. Scanner scn = new Scanner(System.in);
11. name=scn.next();
12. idNo=scn.nextInt();
13. credits =scn.nextDouble();
14. debits=scn.nextDouble();
15. netPay=credits-debits;
16. System.out.println(ʺEmpleoyee pay Bill…..ʺ);
17. String stg = String.format(ʺname : %s idNo : %dʺ ,name,idNo );
18. System.out.println(stg);
19. stg=String.format(ʺCredits :%8.2f debits : %8.2f NetPay %8.2fʺ ,credits,debits,netPay );
20. System.out.println(stg);
21. }
22. }
Output: Enter Emp name, idNo,credits,debits separated by spaces
ʺRameshʺ 50595 20000.0 2000.0
Empleoyee pay Bill…..
name : ʺRameshʺ idNo : 50595
Credits :20000.00 debits : 2000.00 NetPay 17000.00
Line No. 17: | stg=String.format(ʺname : %s idNo : %dʺ ,name,idNo ); shows the formatting the argument for name and idNo.Line No. 17 similarly show the formatting for credits and debits and netPay using %8.2f |
In day-to-day life, there are several occasions wherein we have to store data of the same type in contiguous locations For example, consider a situation where you would like to store the marks obtained by a student in six different subjects. Java provides us with a feature called Arrays which can be used to accomplish the above task.
An array is defined as a collection of elements where each element is of the same type. The elements of the array can either be elementary data types like int, float, char or they can be complex data types like structures and objects. An array is a data structure that defines a contiguous memory location for a single data type. It can be a group of students’ marks or it can be a group of employees’ salaries. For example, float marks[5]; represents an array with 5 marks. The particular value of an array can be accessed by referring to cell number called index of an array. For example, marks[5] refers to marks at index 5. Generally, the indexes are numbered for 0 to n-1, where n is the number of elements in the array. Marks obtained by a student in six different subjects are shown in an array named marks in Figure 17.2. Elements of the array are referenced by array name followed by subscript. We have shown an array named marks; six subject marks scored by the student can be represented by marks[0]=80.0 and marks[5]=70.0 etc.
Figure 17.2 Representation of an array
Java provides us with two methods to declare arrays. The first method involves a two-step procedure, as follows:
Step 1: Declaration of the array using the syntax datatype [] arrayname for example to declare an array of integers with the name integer_array we would declare as follows:
int [ ] integer_array
Step 2: Creation of the array using the syntax arrayname = new datatype[size]; this step basically assigns storage space in the memory for the array. For example, if we want integer_array declared in step1 to accommodate 6 integers we would create as follows:
integer_array = new int[6]
Note that while programming both declaration and creation, i.e. both step 1 and step 2 can be combined as follows. Also note that when we declare arrays in such a fashion all the elements in the array are initialized to 0.
int [ ] integer_array = new int[6]
The second method is used when you want to declare arrays using some initial values. To declare arrays with some initial values we use the syntax datatype [size(optional)] arrayname = {initializer_list}. For example:
int [6] marks = {40, 50, 60, 70, 80,90} or int [ ] marks = {40, 50, 60, 70, 80,90}
Both the above declarations are valid and we do not have to specify the size of the array. The compiler will calculate the size of the array based on the initializer list.
int [] myArray = new int[size]; String input; BufferedReader in; in=new BufferedReader(new InputStreamReader(System.in)); for ( int i =0; i<size; i++) { System.out.println(ʺ Enter Array [ʺ + i +ʺ] elementʺ); input=in.readLine(); myArray[i] = Integer.parseInt(input); } // end of for loop
Consider an array named x, declared as int [] x = new int []{80,90,100,50,65,70};
The addresses shown above are dummy addresses. Using of size of operator would tell us the memory requirement of data type int on your hardware. Assuming that it is 24 bytes, the memories of the array element are shown in Figure 17.3.
Figure 17.3 Representation arrays with memory locations shown
To access an element in the array we must provide the array name and the index of the element in the array. Array indices start from 0 and go up to array length –1, where index 0 is for the first element and index length –1 is for the last element. For example, in Figure 17.3, the array marks have a length of 6, so indices will range from 0 to 5. The general syntax for accessing elements of the array is arrayname[expression]. It is absolutely essential that the value of the expression must be an integer and the value must be in the range of the array indices, i.e. [0, length–1] else we will encounter an array out of bounds exception. Let us see a few examples on accessing array elements; all the statements below use the marks array shown in Figure 17.2.
marks[3] = 50 // statement will change value stored at index 3 in marks array to 50
val = marks[2] //statement will store value present at index 2 (100) into variable val
int index = 6
marks[index -1] = 70 //expression inside bracket evaluates to 4 so same as marks[5] = 75
marks[index +1] = 10 //expression evaluates to 7, so we get array out of bound exception
Java provides us with a length attribute through which we can get the length of the array at run-time. The syntax for getting the length of the array is arrayname.length. Usage of length attribute is particularly useful when processing array elements using for loops as demonstrated in the following example.
Example 17.6: TestArrayLength.java To Obtain the Length of the Array
1. package com.oops.chap17;
2. public class ArrayLengthTest {
3. public static void main(String[] args) {
4. int[] arr = new int[]{10,20,30,40,50,60,70};
5. System.out.println(ʺ Given Array…………ʺ);
6. for(int i = 0; i < arr.length ; i++ )
7. { System.out.print(arr[i] + ʺ, ʺ );}
8. System.out.println(ʺ
Given Array Length :ʺ +arr.length);
9. }
10. }
Output: Given Array…………
10, 20, 30, 40, 50, 60, 70,
Given Array Length :7
Line No. 6: | shows the usage of arr.length. Here arr.length returns the length of array arr. |
Arrays can be passed as parameters to functions. To define a method with an array as a parameter use the following syntax:
ReturnType MethodName(datatype[] arrayname).
To pass an array as an argument in the calling function use the following syntax:
MethodName(arrayname),
i.e. use the array name without the brackets. In the program shown below in Example 17.7, when we pass the array to the function using the call, the array is passed by reference.
Example 17.7: SortIntArray.java: To Sort the Integer Array by Sending Array to a Method
1. package com.oops.chap17;
2. class IntSort1{
3. public void Sort(int myArray[], int len){
4. int temp;
5. for(int i=0; i <len-1; i++){
6. for ( int j=i+1; j<len; j++){
7. if(myArray[i]<myArray[j]){ //swap
8. temp=myArray[i]; myArray[i]=myArray[j]; myArray[j]=temp; }//end of if
9. }// end of inner for loop
10. }// end of outer for loop
11. }//end of method Sort
12. }//end of class IntSort
13. class IntSortDemo {
14. public static void main(String[] args) {
15. IntSort1 obj = new IntSort1();//make an object
16. int[] myArray = new int[]{10,13,17,20};
17. int len = myArray.length;
18. System.out.println(ʺ Given Array ……ʺ);
19. for(int i=0;i<len;i++)
20. System.out.print( ʺ ʺ + myArray[i]);
21. obj.Sort(myArray, len);
22. System.out.println(ʺ
Sorted Array ……ʺ);
23. for(int i=0;i<len;i++)
24. System.out.print( ʺ ʺ + myArray[i]);
25. }
26. }
Output : Given Array …… 10 13 17 20
Sorted Array …… 20 17 13 10
Line No. 3: | public void Sort(int myArray[], int len){ method defines procedure for sorting an array. Observe that int myArray[] is passed as an argument. No need to mention the dimension. Line No. 8 swaps the variable myArray[i] if myArray[i]<myArray[j] as shown at Line No. 7. |
Line No. 15: | defines an object of IntSort1. Line No. 21 calls the Sort() method of class IntSort1 by passing myArray and length as arguments. Observe that myArray is passed as reference. |
We have seen through the above example how arrays can be passed as parameters to a function. Similarly, arrays can also be a return type. To define a method with an array as a return type, we use the following syntax:
dataType[] methodName() { function body}
Program to demonstrate array as return type of a function. Method copies the input array into a new array and returns the new array.
Example 17.8: ArrayCopyDemo1.java : To Copy an Array and Return the Array to Calling Method
package com.oops.chap17;
class ArrayCopy1{
public int[]Copy( int[] myArray) {
int [] arr = new int[myArray.length];
for(int i=0; i <myArray.length; i++)
arr[i]=myArray[i];
return arr;
}//end of method Copy
}//end of class ArrayCopy
class ArrayCopyDemo1 {
public static void main(String[] args) {
ArrayCopy obj = new ArrayCopy();//make an object
int[] myArray = new int[]{10,15,20,30,35};
int[] copyArray = new int[myArray.length];
System.out.println(ʺ Given Array ……ʺ);
for(int i=0;i<myArray.length;i++)
System.out.print( ʺ ʺ + myArray[i]);
copyArray=obj.Copy(myArray);
System.out.println(ʺ
Copied Array ……ʺ);
for(int i=0;i<copyArray.length;i++)
System.out.print( ʺ ʺ + copyArray[i]);
}
}
Output : Given Array …… 10,15,20,30,35
Copied Array ……ʺ) 10,15,20,30,35
Arrays can have more than one dimension. For example, a matrix is a two-dimensional array with a number of rows and a number of columns as show in Figure 17.4.
Figure 17.4 A two-dimensional matrix
As an example, to demonstrate the two-dimensional arrays we would consider the problem of finding a transpose of a matrix.
Example 17.9: MatTranspose.java A Program to Find Transpose of a Matrix
// Matrix transpose 1. package com.oops.chap19; 2. import java.io.*; 3. class Matrix{ 4. void ReadMat(int A[][],int rows, int cols){ 5. //input matrix related data using scanner 6. Scanner scn=new Scanner(System.in); 7. for ( int i=0;i<rows;i++) 8. for ( int j=0;j<cols;j++) 9. { System.out.print(ʺEnter[ʺ+i+ʺ ]ʺ +ʺ [ʺ+j+ʺ ] element :ʺ); 10. A[i][j]=scn.nextInt();} 11. }//end of ReadMat 12. void DisplayMatrix(int A[][],int rows, int cols){ 13. for ( int i=0;i<rows;i++) 14. {for ( int j=0;j<cols;j++) 15. { System.out.print( A[i][j] +ʺ ʺ);} 16. System.out.print( ʺ ʺ); 17. } 18. } 19. void TranspMat(int A[][],int rows, int cols){ 20. for (int i=0;i<cols;i++) 21. {for (int j=0;j<rows;j++) 22. { System.out.print( A[j][i] +ʺ ʺ);} 23. System.out.print( ʺ ʺ); 24. } 25. }//end of TranspMat 26. }//end of Matrix 27. class MatTranspose{ 28. public static void main(String[] args) 29. { Scanner scn = new Scanner(System.in); 30. System.out.print(ʺEnter no of rows & columns:ʺ); 31. int rows= scn.nextInt(); 32. int cols= scn.nextInt(); 33. int A[][]= new int[rows][cols]; //two-dimensional matrix 34. Matrix mat = new Matrix(); //create an object 35. mat.ReadMat(A,rows,cols); 36. System.out.println(ʺGiven Matrixʺ); 37. mat.DisplayMatrix(A,rows,cols); 38. System.out.println(ʺTransposed Matrixʺ); 39. mat.TranspMat(A, rows, cols); 40. } 41. }//end of MatTranspose Output : Enter no of rows & columns:3 3 Enter[0][0] element :1 Enter[0][1] element :2 Enter[0][2] element :3 Enter[1][0] element :4 Enter[1][1] element :5 Enter[1][2] element :6 Enter[2][0] element :7 Enter[2][1] element :8 Enter[2][2] element :9 Given Matrix 1 2 3 4 5 6 7 8 9 Transposed Matrix 1 4 7 2 5 8 3 6 9
Java.util package provides a useful collection class called Arrays class. Arrays class defines several static methods that can be used directly without creating an object. A few of the important and useful static methods by Arrays class are discussed here. Note that we will show an example for only one primitive data type but the syntax and concepts are equally applicable to other data types. Datatype in Table 17.2 refers to primitive data type, for example, say int.
Table 17.2 Arrays class static methods
Arrays class static methods | Functionality |
---|---|
static datatype binarySearch datatype array[],datatype val); | Can be applied to sorted arrays. Uses binary search method |
static boolean equals(datatype myArray1[],datatype myarray2[]); static boolean deepEquals (Object [] obj1,Object[]obj2) |
Returns true if two arrays are equal Returns true if both arrays and their nested arrays if any are equal |
static void sort(datatype myArray[]); ststic void sort(datatype myArray[],int start,int end) |
Sorts the array Specifies the range in an array for sorting. |
static void fill( datatype myArray[], datatype val); | Fills all elements of array with val. If index is beyond, ArrayIndexOutOfBounds Exception occurs |
Example 17.10: ArraysClassDemo.java: To Show Usage of Arrays Class Static Methods
1. package com.oops.chap17;
2. import java.io.*;
3. import java.util.Arrays;
4. public class ArraysClassDemo {
5. public static void main(String [] args)
6. throws IOException,ArrayIndexOutOfBoundsException{
7. int[]myArray = new int[12];
8. // fill the array with zeros as initial values
9. Arrays.fill(myArray, 0);
10. System.out.print(ʺ
Array with initial values
ʺ);
11. DisplayArray(myArray);
12. System.out.print(ʺ
now allocate values to arrayʺ);
13. //populata the array in aloop
14. for ( int i=0;i<=(myArray.length)/2;i++)
15. myArray[i]=(4*i);
16. for ( int i=myArray.length-1;i>myArray.length/2;i--)
17. myArray[i]=i;
18. System.out.print(ʺ
Array after allocating values
ʺ);
19. DisplayArray(myArray);
20. System.out.print(ʺ
Sorting the array….ʺ);
21. Arrays.sort(myArray);
22. System.out.print(ʺ
Array after sorting values
ʺ);
23. DisplayArray(myArray);
24. System.out.print(ʺ
Binary Search the array….ʺ);
25. int pos = Arrays.binarySearch(myArray,4);
26. System.out.print(ʺ
index = ʺ + (pos+1));
27. }//end of main
28. static void DisplayArray(int myArray[]){
29. for ( int i=0;i<myArray.length;i++)
30. System.out.print(myArray[i]+ʺ ʺ);
31. // System.out.println(ʺ
ʺ);
32. }// end of DisplayArray
33. }// end of ArraysClassDemo}// end of ArraysClassDemo
Output:
Array with initial values
0 0 0 0 0 0 0 0 0 0 0 0
now allocate values to array
Array after allocating values
0 4 8 12 16 20 24 7 8 9 10 11
Sorting the array….
Array after sorting values
0 4 7 8 8 9 10 11 12 16 20 24
Binary Search the array….
Pos = 2
A String is an array of characters or a sequence of characters. In Java, the String occupies an important position and role because Java is a language created for network and to transmit data on the network we have to use the Strings. In C or C++, a string is an array of character, with the last one being ‘ ’. In Java, this is not so. A String is an object in Java. They are implemented by String class and StringBuffer class. We can use any one of the following three methods to create a String Object:
Method 1 : String name ; name = new String(ʺHello Classʺ);
Or we can combine both statements into one
String name = new String(ʺHello Classʺ);
Method 2 : convert character arrays into Strings.
char x[] = {‘G’,’o’,’o’,’d’};
String stg = new String (stg);
Method 3 : String name =ʺ Hello Classʺ ;
There are two important methods with Strings that are widely used.
int len = name.length() ; // gives the length of String name
Strings can be concatenated as shown below:
System.out.println ( name +ʺ ʺ + x); // gives out Hello Class Good
We can create an array of Strings. For example, we want to create an array of Strings containing 6 city names.
//create array of Strings
String [] cityNames= new String[6];
Scanner scn = new Scanner(System.in);
int i=0;
int len = cityNames.length;
System.out.println(ʺEnter 6 city names separated by spacesʺ);
for ( i=0;i<len;i++)
cityNames[i]=scn.next();
Example solved at Ex 17.6 will show the working of Array of strings. We will obtain the strings into an array called cityNames using Scanner methods and sort the array of strings alphabetically.
Method supported by string class is shown in Table 17.3.
Table 17.3 String class methods
Example 17.11: StringMethodsDemo.java: To Show Usage of String Class Methods
1. package com.oops.chap17;
2. public class StringSort {
3. public static void main(String[] args) {
4. //create array of Strings
5. String [] cityNames= new String[]{ʺMADRASʺ ,ʺ BANGALOREʺ ,ʺ GHAZIABADʺ ,ʺ BINTULUʺ ,ʺ VIZAGʺ ,ʺ RAIPURʺ };
6. // Get the size
7. int len = cityNames.length;
8. System.out.println(ʺ
City Names ………ʺ);
9. for ( int i=0;i<len-1;i++)
10. System.out.print(cityNames[i]+ʺ ʺ);
11. String temp;
12. for ( int i=0;i<len-1;i++){
13. for ( int j=i+1;j<len;j++){
14. if( cityNames[j].compareTo(cityNames[i])<0)
15. { // swap city names
16. temp=cityNames[i]; cityNames[i]=cityNames[j];
17. cityNames[j]=temp;
18. }
19. }//inerfor loop
20. }//outer for loop
21. System.out.println(ʺ
City Names Sorted alphabeticallyʺ);
22. for ( int i=0;i<len-1;i++)
23. System.out.print(cityNames[i]+ʺ ʺ);
24. }//end of main
25. }// end of class StringSort
Output: City Names ………
MADRAS BANGALORE GHAZIABAD BINTULU VIZAG
City Names Sorted alphabetically
BANGALORE BINTULU GHAZIABAD MADRAS RAIPUR
Line No. 6: | creates a String Object called cityNames[] and allocates resources using new operator. |
Line No. 7: | gets length of String cityNames. Observe that length has no brackets. |
Line Nos. 12 & 13: | are outer & inner for loops for sorting the String Array cityNames[]. |
Line No. 14: | if(cityNames[j].compareTo(cityNames[i])<0)uses compareTo() method. This method compares cityNames[j]& cityNames[i]) and returns <0 or 0 or >0 i.e negative, zero, and positive depending on of cityNames[i]) is alphabetically appears before cityNames[j] |
String is a fixed length and modifying the length and content is not allowed, i.e., they cannot be muted (they are immutable). StringBuffer class is meant to fulfill the gap in requirements of programmers. We can insert in the middle or at the end of a string. Hence StringBuffer class elements are mutable. Methods supported by StringBuffer class are shown in Table 17.4.
Table 17.4 StringBuffer class methods
StringBuffer Class Methods | Functionality |
---|---|
stg.setCharAt(pos,’c’); stg1.append(stg2); stg1.insert(pos,stg2); stg.setLength(n); |
Changes character at pos to c. Appends stg2 to stg1. Inserts stg2 at pos. Sets length of stg to n. Truncation or addition with zeros takes place if original length is > n or <n. |
Example 17.12: StringBufferDemo.java: To Show Usage of StringBuffer Class Methods
1. package com.oops.chap17;
2. import java.util.*;
3. public class StringBufferDemo {
4. public static void main(String[] args) {
5. //create object of StringBuffer
6. StringBuffer stg = new StringBuffer(ʺC++ & Javaʺ);
7. System.out.println(ʺ
Given String : ʺ + stg);
8. int len = stg.length();
9. System.out.println(ʺPrinting Given String character by characterʺ);
10. for (int i=0;i<len;i++)
11. System.out.print(stg.charAt(i)+ʺ ʺ);
12. System.out.println(ʺ
Inserting a string :OOPS in: at the beginning ʺ);
13. String stg2=ʺ OOPS in ʺ;
14. stg.insert(0,stg2);
15. System.out.println(ʺString after insertingʺ);
16. System.out.println(stg);
17. System.out.println(ʺModifying few elements of Stringʺ);
18. stg.setCharAt(0,’o’);
19. stg.setCharAt(1,’o’);
20. stg.setCharAt(2,’p’);
21. stg.setCharAt(3,'s’);
22. System.out.println(ʺString after modificationsʺ);
23. System.out.println(stg);
24. System.out.println(ʺAppending Stringʺ);
25. stg.append(ʺ Languagesʺ);
26. System.out.println(ʺString after appendingʺ);
27. System.out.println(stg);
28. }//end of main
29. }//end of class StringBufferDemo
Output: Given String : C++ & Java
Printing Given String character by character
C + + & J a v a
Inserting a string :OOPS in: at the begining
String after inserting
OOPS inC++ & Java
Modifying few elements of String
String after modifications
oops inC++ & Java
Appending String
String after appending
oops inC++ & Java Languages
Line No. 3: | StringBuffer stg = new StringBuffer(ʺC++ & Javaʺ); creates an object of stringBuffer class and assigns initial value as (ʺC++ & Javaʺ); |
Line No. 11: | prints the string chara by character using : charAt() method. |
Line No. 14: | inserts the string ʺOOPS in ʺ using : insert() method. |
Line No. 17 to 21: | modifies the character using setCharAt() method. |
Line No. 25: | append a string ʺLanguagesʺ to the existing String using append() method |
Jdk1.5 has provided StringBuilder class in addition to StringBuffer class. StringBuilder class is the same as that of StringBuffer, but it is not synchronized. What this means is that when several threads are waiting as StringBuffer class is synchronized, all the waiting threads will be executed as per priority one after the other and thereby prevent a condition called racing. More details about synchronized methods and racing are provided in the chapter on multithread programming. When programming with single thread, StringBuilder will provide quicker solution but multithreaded programming use of StringBuffer is recommended.
Arrays, while they are extremely useful, have their own limitations. They are static in nature. This means that resources are to be allocated at compile time. Arrays are fixed length data structures. Further arrays contain only homogenous data types. How do we store a group of objects in an array? J2SE 5.0 has provided a collection framework. This is somewhat similar to container of C++ but has quite a number of differences. Collection framework is implemented in java.util package. The concept is: make a collection object, Store group of objects in collection object. The collection framework of Java is shown in Figure 17.5.
Figure 17.5 Collection class of java.util
Collection class provides several interfaces. They are shown in Table 17.5.
Table 17.5 Collection class interfaces
Collection Class Interface | Classes |
---|---|
Set<T> | HashSet<T> LinkedHashSet<T> |
List<T> | Stack<T> LinkedList<T> ArrayList<T> Vector<T> |
Queue<T> | LinkedList<T> |
Map<k,s> | HashMap<k,s> Hashtabel<k,s> |
In our next section, we deal with vector class and leave the balance to be dealt by other succeeding chapters on Java Collection.
Vector is a data structure provided by java J2SE 5.0 to store any number of objects of any type, and these can be decided and resources can be allocated at run-time. The advantages of vectors over arrays can be summarized as follows:
The disadvantage is that only objects can be stored and not direct data. Hence we need to use wrapper class to convert primitive data to objects. We will implement vector class as it is logically linked to arrays and leave the balance topics for handling in ensuing chapters.
Methods supported by Vector Class are placed in Table 17.6.
Method | Remark |
---|---|
boolean addElement() boolean assElementAt(n) |
Adds at end Adds at position n |
boolean removeElement() boolean removeElementAt(n) boolean removeAllElements() |
Removes the specified element Removes element at position n Removes all elements |
int size() element get(pos) void set(pos,obj) |
Returns no of object Returns element at pos Sets obj at position |
Object[] toarray() | Copies contents into array |
InsertElementAt() | Returns object class type array with all elements of vector |
Example 17.13: VectorDemo.java: A Program to Demonstrate Usage of Vector Class
1. package com.oops.chap17; 2. import java.util.*; 3. public class VectorDemo { 4. public static void main(String[] args) { 5. // create an object of vector class to store integers 6. Vector<Integer> vec = new Vector<Integer>(); 7. // define an integer array 8. int [] x = new int []{ 10,20,30,40,50,60,70}; 9. /* store the integers into vec. But integers are converted to objects automatically by a feature autoboxing*/ 10. for ( int i=0;i<x.length; i++) 11. vec.add(x[i]); 12. System.out.println(ʺ Displaying Vector using vec.get()ʺ); 13. for ( int i=0;i<vec.size(); i++) 14. System.out.print(vec.get(i)+ʺ ʺ); 15. System.out.println(ʺDisplaying using ListIteratorʺ); 16. ListIterator itr = vec.listIterator(); 17. System.out.println(ʺUsing ListIterator move forwardʺ); 18. while ( itr.hasNext())System.out.print(itr.next()+ʺ ʺ); 19. System.out.println(ʺUsing ListIterator move reverseʺ); 20. while ( itr.hasPrevious()) 21. System.out.print(itr.previous()+ʺ ʺ); 22. }// end of main 23. }// end of vectorDemo Output: Displaying Vector elements using vec.get() 10 20 30 40 50 60 70 Displaying Vector elements using ListIterator Using ListIterator move forward 10 20 30 40 50 60 70 Using ListIterator move reverse 70 60 50 40 30 20 10
Line No. 6: | Vector<Integer> vec = new Vector<Integer>();creates an object called vec of Vector<Integer> |
Line No. 8: | defines an array called x and assigns values to the array |
Line Nos. 9 to 11: | adds elements into Vector object.Integers are converted to objects automatically by a feature autoboxing. Line No. 11 : vec.add(x[i]); shows addition to Vector object vec. |
Line No. 14: | gets the elements from Vector object vec and prints them System.out.print(vec.get(i)+ʺ ʺ); |
Lne No. 16: | creates an object called listIterator for class ListIteraotr. This iterator is used to raverse the Vector both forward and reverse directions by using itr.next and itr.previous. |
Line Nos. 18 & 20: | checks if itr.hasNext or itr.hasPrevious is true |
3.128.173.53