17

Simple IO and Arrays and Strings Vectors

LEARNING OBJECTIVES

At the end of the chapter, you will be able to understand and write programs using

  • Simple IO statements using BufferedReader and InputStreamreader.
  • Read(), readLine() and StringTokenizer class and its methods.
  • Java's input using scanner class and output using String format().
  • Arrays and Strings handling.
  • Vectors and wrapper classes.

17.1 Introduction

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.

17.2 Input from Keyboard

17.2.1 System.in, System.out and System.err Commands

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

  • System.in: Standard input is from keyboard. This represents inputStream Object
  • System.out: Console is represented by System.out. This represents PrintStream object.
  • System.err: Java handles stream objects for input and output and hence is likely to encounter errors or exceptions. System.err is used to log errors that occur while handling streams. We need to catch these errors and exception objects using try and catch blocks. We will tell you how to use these commands now and reserve more detailed discussion to later chapters on errors and exceptions.

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.

 

Input from keyboard

 

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

 

image

 

Line No. 2: import java.io.*;is required as we are using InputStreamReader, BufferedReader, and IOException
Line No. 5: void main() throw IOException object. This is an example of method(void main() throwing an exception.
Observe in Line No. 6: System.in is for console input. InputStreamreader is attached to System.in. InputStremreader in turn belongs to BufferedReader.
Line Nos. 8 & 9: show how to accept a string from keyboard : String input=in.readLine();
Line Nos. 10 to 12: show the commands for accepting integer from keyboards:
10   System.out.print(ʺEnter your Roll Number :ʺ);
11String input=in.readLine(); //Accept the integer as String
12 int id=Integer.parseInt(input);// conver String into integer.
Line Nos. 13 to 15: show the commands for accepting double from keyboards
13 System.out.print(ʺEnter your Total Marks : ʺ);
14 String input2=in.readLine();//Accept the integer as String
15 double totalmarks=Double.parseDouble(input2);
Line Nos. 16 to 17: show the commands for accepting a character from keyboard using a readLine() command. Note that readLine read the String(). charAt() returns first character of the string. Hence our command would be: char ch = (char) in.readLine().charAt(0); We could also write this as: String ch = in.readLine();

17.2.2 StringTokenizer to Receive Multiple Inputs in a Single Line

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. }

 

image

 

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.

17.2.3 Obtaining Inputs Using Java's Scanner Class

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. }

 

image

 

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();

17.2.4 Using Control Formats – System.out.printf()

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  

 

Example 17.4:   PrintfJava.java: To Send the Formatted Output Using System.out.Printf(

   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.

17.2.5 Formatted Output with String Format

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

17.3 Arrays

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.

 

Representation of an array

 

Figure 17.2 Representation of an array

 

17.3.1 Declaring and Creation 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.

17.3.2 Initialization of Arrays

  • If the array size is small, we can use dynamic declaration and allocation all in a single line as : int [] myArray = new int[5] { 10,20,30,40,50};
  • If the array size is large, we will use for loop to enter the data
   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

17.3.3 How Are Arrays Stored in the Memory?

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.

 

Representation arrays with memory locations shown

 

Figure 17.3 Representation arrays with memory locations shown

17.3.4 Accessing and Modifying Array Elements

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.

17.3.5 Passing Arrays as Arguments to Methods

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.

17.3.6 Returning Arrays as Arguments to Methods

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

17.3.7 Multi-dimensional Arrays

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.

 

A two-dimensional matrix

 

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
      Line No. 29: creates an object for Scanner class called scn. Line Nos. 31 and 32 reads no of rows and columns from keyboard using nextInt()
Line No. 33: int A[][]= new int[rows][cols]; defines two-dimensional matrix called A[][]. Line No. 35 calls ReadMat() method and Line No. 37 calls DisplayMatix() and Line No. 39 calls TranspMat() methods of class matrix. All these methods pass two-dimensional matrix and rows and columns as arguments.
Line Nos. 7 & 8: are two for loops for reading matrix elements row major wise. Also observe that at line No. 10 : A[i][j]=scn.nextInt(); we have read element A[i][j] using Scanner object as scn.nextInt();
Line Nos. 20 & 21: viz for (int i=0;i<cols;i++) {for ( int j=0;j<rows;j++) observe that outer loop we have used cols and inner loop we have used rows, thus producing the transpose of a matrix.

17.3.8 Java.util. Arrays Class

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
Line No. 3: imports java.uti.Arrays.
Line No. 6: throws IOException,ArrayIndexOutOfBoundsException.
Line No. 9: Arrays.fill(myArray, 0); uses static method of Arrays called fill(array[],arg) to fill the array wit all zeros. Note that a static method can be called directly with class name. No need to invoke them with object as we normally do with class objects.
Line Nos. 11 and 19 and 23: DisplayArray(myArray); I a static method displayed in the same class. Hence we have used the specifier static.
Line Nos. 14 to 17: populate the arrays with values (4*i) and I in a loop.
Line No. 21: calls Arrays.sort(myArray) to sort the array

17.4 String

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

17.4.1 Array of Strings

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.

17.4.2 String Class Methods

Method supported by string class is shown in Table 17.3.

 

Table 17.3 String class methods

String Method Functionality Performed

stg.length();

stg.CharAt(pos);

stg1.compare(stg2);

stg1.concat(stg2);

Returns length.

Returns char at pos.

Returns -1/0/1 on stg1< or = or > stg2

Concatenates stg1 & stg2

stg2=stg1.toLowerCase();

stg2=stg1.toUpperCase();

stg2=stg1.replace( ‘a’, ‘b’);

stg2=stg1.trim();

Converts stg1 to lower case

Converts stg1 to upper case

Replaces char a with char b

Removes leading & Trailing white space of stg1.

stg1.equals(stg2);

stg1.equalsIgnoreCase();

Returns true if stg1 equals stg2

Returns true if stg1 equals stg2 ignoring the case

stg1.substring(pos);

stg2.substring( start,end);

string.valueOf( s);

stg.toString();

stg.indexOf(‘x’);

stg.indexof(‘x’,pos);

Returns substring from pos

Returns substring specified by start and end-1.

Converts s into an object of String.

Converts object stg to string

Returns position of first occurrence of x.

Returns position of first occurrence of x after pos.

 

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]

17.4.3 StringBuffer Class

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

17.4.4 StringBuilder Class

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.

17.5 Collection Framework

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.

 

Collection class of java.util

 

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.

17.5.1 Vector Class

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:

  • Vectors are dynamic and can be used to store any number, any type and any size of objects.
  • Addition and deletion of objects from the vector is easy whereas deletion and addition in array requires readjustment of data.

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.

17.5.2 Vector Methods

Methods supported by Vector Class are placed in Table 17.6.

 

Table 17.6 Vector methods

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

17.6 Summary

  1. StringTokenizer class is used to receive multiple inputs in a single line.
  2. Scanner class of Java is elegant and easy to use to read the input data from keyboard.
  3. String.format() is a static method and hence can be used directly to control the output.
  4. 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 can be complex data types like structures and objects.
  5. 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.
  6. A String is an array of characters or sequence of characters. A String is an object in Java. They are implemented by String class and StringBuffer class.
  7. 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.
  8. StringBuilder class is the same as that of StringBuffer but it is not synchronized.
  9. Collection framework is implemented in java.util package.
  10. Vector is a data structure provided by java J2SE 5.0 to store any number of objects of any type.
  11. Wrapper class converts the primitive data into objects.

Exercise Questions

Objective Questions

  1. Arrays are passé to methods as pass by reference only.     TRUE/FALSE
  2. Which of the following statements are true in respect of Java Strings?
    1. Java String is an array of characters terminated by ‘’
    2. Java String is an object of String class.
    3. String is implemented using character array.
    4. Java String is implemented using String class or StringBuffer class.
    1. i and iii
    2. ii and iii
    3. ii and iv
    4. iii and iv
  3. A string in Java can be implemented by
    1. String class
    2. StringBuffer
    3. StringBuilder
    4. a, b and c
  4. Which of the following are true in respect of Arrays and Strings?
    1. arr.length() gives length of the array
    2. stg.length; gives the length of the string
    3. stg.length() gives the length of stg
    4. arr.length ; gives the length of the array
    1. ii and iv
    2. i and iii
    3. iii and iv
    4. i and ii
  5. String is a fixed length and content can be modified.     TRUE/FALSE
  6. StringBuffer class elements are immutable.     TRUE/FALSE
  7. StringBuilder class elements are mutable.     TRUE/FALSE
  8. Java String elements are mutable.     TRUE/FALSE
  9. Both StringBuffer and StringBuilder methods are synchronized.     TRUE/FALSE
  10. Vectors cannot store direct primitive data.     TRUE/FALSE

    Short-answer Questions

  11. What is an array? How can it be created and set initial values?
  12. Distinguish vector and array.
  13. What is a Scanner class?
  14. Distinguish the ways in which we can get length of an array and String.
  15. How is an element of character array accessed?
  16. How is an element of String accessed?
  17. Explain formatted output using System.out.printf() method.
  18. Explain String.format() method to output formatted data.
  19. What is collection framework provided by Java?
  20. What is wrapper class?

    Long-answer Questions

  21. Explain with examples how primitive data can be inputted from KeyBoard.
  22. Explain the utility of StringTokenizer class. How is Scanner class different from class?
  23. Write in detail about one-dimensional and multi-dimensional arrays. Also write about how initial values can be specified for each type of array.
    1. In what way is array different from ordinary variable?
    2. What conditions must be satisfied by the entire elements of any given array?
    3. What are subscripts? How are they written? What restrictions apply to the values that can be assigned to subscripts?
    4. What advantage is there in defining an array size in terms of a symbolic constant rather than a fixed integer quantity?
  24. Explain the various methods available for creation and setting initial values to an array with suitable examples.
  25. How are multi-dimensional arrays defined? Compare with the manner in which one-dimensional arrays are defined.
  26. Explain salient features of Vector class.
  27. Explain with examples the various methods to create and set initial values to a String.
  28. Explain methods of String class with examples.
  29. Explain what you understand by the statement StringBuffer elements are mutable.
  30. Distinguish the String class and StringBuffer Class and StringBuilder Class.

    Assignment Questions

  31. Write a Java program to find the sum of elements of an array with recursion.
  32. Write a Java program to find the product of two matrices.
  33. Write a Java program to find the determinant of a matrix.
  34. Write a function to merge two sorted arrays.
  35. Write a program to read a line from the keyboard and print the line using a suitable encryption. Simple encryption can be a substitution with the next character A with B, a with b, z with a and so on. De-crypt and display the original message.
  36. Develop String class to implement all the functionality provided by Java String class.
  37. Develop Array class to implement the functionality provided by Arrays class.

Solutions to Objective Questions

  1. True
  2. c
  3. d
  4. c
  5. False
  6. False
  7. True
  8. False
  9. False
  10. True
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.58.220.83