Answers to exercises and questions in Java Course Material

The following are answers to exercises and questions in Java Course Material.

Answers To Exercises In Getting Started With Java

Here are the answers to exercises given in Getting Started With Java Course Material.
  1. Display first 10 Fibonacci numbers
  2. Display palindrome numbers in the range 1000 to 2000
  3. Write a program to take a number from user and display whether it is perfect number
  4. Accept ten numbers from user and display the largest of the given numbers
  5. Accept two numbers and display the GCD of the numbers
  6. Accept two numbers on command line and raise base (first number) to power (second number)
  7. Accept a number and display its highest factor
  8. Accept a number and display the digits in the reverse order
  9. Create a function that takes a set of integers using varying length argument and returns the average of all the numbers
  10. Create an array of 10 elements. Read values from keyboard and fill the array. Interchange first 5 elements with last 5 elements and display the array

Answers To Exercises In Java Student's Guide

Here are the answers to exercises given in Java Students' Guide Course Material.
  1. Count number of words in a given file.
  2. Accept a filename, a string and display all lines in the file that contain the given string
  3. Display only non-blank lines of the given file along with line numbers
  4. Accept path from user and display list of files from the given path
  5. Accept file name from user and display contents of file in reverse order- first line last
1. Display first 10 Fibonacci numbers
// display Fibonacci series
public class Fibonacci {
    public static void main(String[] args) {
        int first = 1,second = 1, result;

        System.out.println(first);
        System.out.println(second);

        for ( int i = 3; i <= 10 ; i ++) {
             result = first + second;
             System.out.println( result );
             first = second;
             second = result;
        } // for
    } // end of main
}

2. Display palindrome numbers in the range 100 to 1000

public class PalindromeNumbers {

    public static void main(String[] args) {

        for ( int i = 1000; i <= 2000; i ++)  {

              int n = i, rn  = 0;
              while (n > 0 ) {
                  int d = n % 10;  // get right most digit
                  rn = rn * 10 + d;
                  n /= 10;   // remove right most digit
              }
              if ( i == rn )
                  System.out.println(i);
        }

    }

}

3.Write a program to take a number from user and display whether it is perfect number
// Perfect Number

import java.util.Scanner;
public class PerfectNumber {
    public static void main(String[] args) {

        // take numbers from user
        Scanner s = new Scanner(System.in);
        int num = s.nextInt();
        int sum = 0;
        for ( int i = 1;  i <= num/2 ; i ++) {
          if ( num % i == 0 ) {
               sum += i;
          }
        }
        if ( sum == num)
              System.out.println("Perfect Number");
        else
              System.out.println("Not Perfect Number");
    }
}

4.Accept ten numbers from user and display the largest of the given numbers
// Accept ten numbers from user and display the largest of the given numbers.

import java.util.Scanner;

public class LargestNumber {
    public static void main(String[] args) {
        // take numbers from user
        Scanner s = new Scanner(System.in);
        int num, largest = 0;

        for ( int i = 1; i <= 10 ;i ++) {
         System.out.print("Enter a number : ");
         num = s.nextInt();
         if ( num > largest)
              largest = num;
        }
        System.out.println("Largest Number : " + largest);
    }
}

5. Accept two numbers and display the GCD of the numbers
// Accept two numbers and display the GCD of the numbers

import java.util.Scanner;
public class GCD {
    public static void main(String[] args) {
        // take numbers from user
        Scanner s = new Scanner(System.in);
        int first = s.nextInt();
        int second = s.nextInt();

        int i = first < second ? first : second;

        for ( ;  i > 0 ; i --) {
          if ( first % i == 0 &&  second % i == 0) {
               System.out.println("GCD = " + i);
               break;
          }
        }
    }
}

6. Accept two numbers on command line and raise base (first number) to power (second number).
// Accept two numbers on command line and raise base (first number) to power (second number).

public class Power {
    public static void main(String[] args) {
        int base = Integer.parseInt( args[0]);
        int power  = Integer.parseInt( args[1]);
        int result =1;
        for ( int i = 1; i <= power ; i ++) {
              result *= base;
        }
        System.out.printf("%d raised to %d = %d", base, power, result);
    }

}

7. Accept a number and display its highest factor
import java.util.Scanner;

public class HighestFactor {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = s.nextInt();

        for ( int i = num/2; i > 0 ; i --) {
            if ( num % i == 0 ) {
                System.out.printf("Highest Factor : %d\n",i);
                break;
            }
        }

    }
}

8. Accept a number and display the digits in the reverse order

import java.util.Scanner;
public class ReverseDigits {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter a number : ");
        int num = s.nextInt();

        while( num != 0 )
        {
            System.out.print( num % 10);
            num /= 10;
        }
    }
}

9. Create a function that takes a set of integers using varying length argument and returns the average of all the numbers.

public class AverageOfNumbers {


    public static void main(String[] args) {
       System.out.println( average(10,20,45,33));
       System.out.println( average(12,22,88));
    }

    public static int average(int ... numbers) {
        int total = 0;
        for(int n : numbers)
            total += n;

        return total / numbers.length;
    }
}


10. Create an array of 10 elements. Read values from keyboard and fill the array. Interchange first 5 elements with last 5 elements and display the array.
import java.util.Scanner;

public class InterchangeArray {
    public static void main(String[] args) {
            int a[] = new int[10];

            Scanner s = new Scanner(System.in);
            // read values from keyboard into array
            for ( int i = 0 ; i <  a.length ; i ++) {
                System.out.printf("Enter a number for [%d] element :",i);
                a[i] = s.nextInt();
            }

            System.out.println("Orginal Array");
            printArray(a);

            // interchange array
            for ( int i = 0, j = a.length -1 ; i < a.length / 2; i ++, j --) {
                int t = a[i];
                a[i] = a[j];
                a[j] = t;
            }

            System.out.println("Interchanged Array");
            printArray(a);
    }

    public static void printArray(int [] a) {
            for(int n : a) {
                System.out.printf("%5d",n);
            }
    }
}

Accept a file and count number of words in the given file. (Section : Library-II, Page : 5)
// counts number of words assuming words are separated with only one space
import java.io.FileReader;
import java.util.Scanner;

public class CountWords {

    public static void main(String[] args) {
        System.out.print("Enter a filename : ");
        Scanner s = new Scanner(System.in);
        String filename = s.nextLine();

        try (FileReader fr = new FileReader(filename)) {
            int nowords = 0;
            int ch = fr.read();
            while (ch != -1) {
                if (ch == '\n' || ch == ' ') {
                    nowords++;
                }
                ch = fr.read();
            }
            System.out.printf("No. of words =  %d\n", nowords);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

// A better version of the exercise is given with BufferedReader and split() method of String

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class CountWordsInFile {

    public static void main(String[] args) {

        System.out.print("Enter a filename : ");
        Scanner s = new Scanner(System.in);
        String filename = s.nextLine();
        try (FileReader fr = new FileReader(filename);
                BufferedReader br = new BufferedReader(fr)) {

            String line = br.readLine();
            int nowords = 0;
            while (line != null) {
                String[] words = line.split(" ");
                // trim words to count only words with non-space characters
                for (String w : words) {
                    if (w.trim().length() > 0) {
                        nowords++;
                    }
                }
                line = br.readLine();
            }
            System.out.printf("No. of words =  %d\n", nowords);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Accept a filename, a string and display all lines in the file that contain the given string. (Section : Library-II, Page :6)

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class DisplayLinesWithString {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a filename : ");
        String filename =  scanner.nextLine();

        System.out.print("Enter a string  : ");
        String searchstring =  scanner.nextLine();
        try ( FileReader fr = new FileReader(filename);
              BufferedReader br = new BufferedReader(fr)) {
        String line = br.readLine();
        while( line != null) {
            if ( line.contains(searchstring))
                 System.out.println(line);

            line = br.readLine();
        }
        }
        catch(Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Display only non-blank lines of the given file along with line numbers.(Section : Library-II, Page :7)

import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;

public class NonblankLinesWithLineNumbers {

    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a filename : ");
        String filename = scanner.nextLine();

        try (FileReader fr = new FileReader(filename);
                BufferedReader br = new BufferedReader(fr)) {
            String line = br.readLine();
            int lineno = 1;
            while (line != null) {
                if (line.trim().length() > 0) {
                    System.out.printf("%5d:%s\n", lineno, line);
                }
                line = br.readLine();
                lineno ++;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Accept path from user and display list of files from the given path. (Section : Library-II, Page : 15)
import  java.io.*;
import  java.util.Scanner;

public class FileList
{
 public static void main(String args[])
 {
  Scanner s = new Scanner(System.in);
  System.out.println("Enter directory name :");
  String dir = s.nextLine();
  File path = new File(dir);
  if (! path.isDirectory())
  {
     System.out.println( dir + " is not a directory");
     return;
  }
  File list [] = path.listFiles();
  for ( File f : list)
  {
     if ( f.isDirectory())
      System.out.println(f.getName() + "\t" +  "[DIR]");
     else
      System.out.println( f.getName() + "\t" +  f.length());
  } // end of for loop
 } // end of main
} // end of class

Accept file name from user and display contents of file in reverse order- first line last. (Section : Library-II, Page : 49)
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
import java.util.Stack;

public class ReverseFile {
    public static void main(String[] args) {

        Scanner scanner = new Scanner(System.in);
        System.out.print("Enter a filename : ");
        String filename = scanner.nextLine();


        Stack<String>  lines= new Stack();
        try (FileReader fr = new FileReader(filename);
                BufferedReader br = new BufferedReader(fr)) {
            String line = br.readLine();
            while (line != null) {
                lines.push(line);
                line = br.readLine();
            }

            // display stack
            while(! lines.isEmpty())
                System.out.println( lines.pop());

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
    }
}

Answers To Questions In Java Examination

Here are the answers for questions given in Java Examination PDF.

Question No. Correct Answer
1 c
2 d
3 d
4 c
5 a
6 c
7 c
8 a
9 d
10 d
11 a
12 c
13 a
14 c
15 d
16 c
17 c
18 c
19 d
20 c
21 d
22 b
23 c
24 b
25 d
26 a
27 d
28 c
29 c
30 b
31 b
32 b
33 a
34 c
35 b
36 b
37 d
38 b
39 c
40 c
41 a
42 d
43 a
44 c
45 d
46 b
47 c
48 a
49 d
50 d