Programming in Java | Week 7

Session: JAN-APR 2024

Course name: Programming In Java

Course Link: Click Here

For answers or latest updates join our telegram channel: Click here to join

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q1. Which stream does Java application uses to read data from a source, it may be a file, an array, peripheral device or socket?
a. InputStream
b. OutputStream
c. Input/OutputStream
d. None of the above

Answer: a. InputStream


Q2. What is the primary purpose of input streams in Java?
a. To write data to a file.
b. To read data from a file.
c. To append data to a file.
d. To create directories.

Answer: b. To read data from a file.


Q3. Which class in Java is used to create a new directory?
a. FileReader
b. FileWriter
c. File
d. Directory

Answer: c. File


For answers or latest updates join our telegram channel: Click here to join

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q4. Which class in Java is used to read data line by line from a file?
a. BufferedReader
b. FileInputStream
c. FileWriter
d. OutputStream

Answer: a. BufferedReader


Q5. What does the following code do?
FileInputStream fis = new FileInputStream(“test.dat”);

a. It creates a new file named test.dat if it does not exist and opens the file so you can write to it, if write permission is available.
b. It thows an error if the file named test.dat does not exist and opens the file, if it exists, so you can read from it and write into it, if write permission is available.

c. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can write to it, if write permission is available.
d. It creates a new file named test.dat regardless of whether it exists or not and opens the file so you can read from it and write to it, if write permission is available.

Answer: b. It thows an error if the file named test.dat does not exist and opens the file, if it exists, so you can read from it and write into it, if write permission is available.


Q6. What is the output of this program? (Assume ‘inputoutput.java’ file exists in the current directory)
a. true
b. false
c. prints number of bytes in file
d. prints number of characters in the file

Answer: c. prints number of bytes in file


For answers or latest updates join our telegram channel: Click here to join

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q7. What will be the output of the following Java program?
a. abc
b. abcd
c. abcde
d. none of the mentioned

Answer: d. none of the mentioned


Q8. What is the output of the following Java program?
a. 30
b. Compiler Error
c. Garbage value
d. 0

Answer: b. Compiler Error


Q9. In order to restrict a variable of a class from inheriting to subclass, how variable should be declared?
a. Protected
b. Private
c. Public
d. Static

Answer: b. Private


Q10. A _________ is a type of object that organizes components in a container.
a. Event adapter
b. Event Handler
c. Layout manager
d. Grid Manager

Answer: c. Layout manager


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Programming Assignment

Question 1
A Student class with private fields (name, age) is provided,
Your task is to make the following:
a parameterized constructor to initialize the private fields
the getter/setter methods for each field
Follow the naming convention as given in the main method of the suffix code.

Solution:

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 2
A BankAccount class with private field balance is provided,
Your task is to make the following:
a parameterized constructor to initialize the private field
public void deposit(…) // to deposit money
public void withdraw(…) // to withdraw money, should print “Insufficient funds!” if not enough money to withdraw
public double getBalance() // to return the current balance
Follow the naming convention as given in the main method of the suffix code.

Solution:

    public BankAccount(double initialBalance) {
        this.balance = initialBalance;
    }

    public void deposit(double amount) {
        balance += amount;
    }

    public void withdraw(double amount) {
        if (amount > balance) {
            System.out.println("Insufficient funds!");
        } else {
            balance -= amount;
        }
    }

    public double getBalance() {
        return balance;
    }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 3
An abstract class shape is provided,
Your task is to make the following:
a parameterized constructor to initialize the Circle class
@Override the area function to compute the area of a circle (Use Math.PI for value of pi, not 22/7)
@Override the displayInfo() function to print exactly in the format provided by the test cases.
Follow the naming convention as given in the main method of the suffix code.

See also  Programming In Java | Week 1

Solution:

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * Math.pow(radius, 2);
    }

    @Override
    public void displayInfo() {
        System.out.print("Circle - Radius: " + radius + ", Area: " + area());
    }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 4
An interface shape is provided,
Your task is to make the following:
Create a class “Circle” that implements the “Shape” interface and provides its own implementation for calculateArea().
@Override the area function to compute the area of a circle (Use Math.PI for value of pi, not 22/7)
Create another class “Rectangle” that implements the “Shape” interface and provides its own implementation for calculateArea().
@Override the area function to compute the area of a rectangle
Follow the naming convention as given in the main method of the suffix code.

Solution:

class Circle implements Shape {
    private double radius;

    public Circle(double radius) {
        this.radius = radius;
    }

    @Override
    public double calculateArea() {
        return Math.PI * Math.pow(radius, 2);
    }
}

class Rectangle implements Shape {
    private double length;
    private double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    @Override
    public double calculateArea() {
        return length * width;
    }
}

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 5
Two interfaces are provided, namely Flyable and Swimmable,
Your task is to make the following:
Create a class “FlyingFish” that implements both interfaces and provides its own implementation for fly() and swim()
It should have a private variable name, use a constructor to set the value and the functions fly() and swim() to print exactly as given in the test case.
Follow the naming convention as given in the main method of the suffix code.

Solution:

class FlyingFish implements Flyable, Swimmable {
    private String name;

    public FlyingFish(String name) {
        this.name = name;
    }

    @Override
    public void fly() {
        System.out.println(name + " can glide through the air");
    }

    @Override
    public void swim() {
        System.out.print(name + " can swim in water");
    }
}

For answers or latest updates join our telegram channel: Click here to join

These are NPTEL Programming In Java Week 7 Assignment 7 Answers

More Weeks of Programming In Java: Click here

More Nptel Courses: https://progiez.com/nptel-assignment-answers


Session: JULY-DEC 2023

Course Name: Programming In Java

Course Link: Click Here

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Programming Assignment

Question 1
Complete the following code fragment to read three integer values from the keyboard and find the sum of the values. Declare a variable “sum” of type int and store the result in it.

Solution:

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

           int i,n=0,sum=0;
           Scanner in = new Scanner(System.in);
           for(i=0;i<3;i++)
           {
              n = in.nextInt();
              sum =sum+n;
           }

Question 2
Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “Please enter valid data” .If there is no such exception, it will print the “square of the number”.

Solution:

  try{
       InputStreamReader r=new InputStreamReader(System.in);
       BufferedReader br=new BufferedReader(r);
       String number=br.readLine();
       int x = Integer.parseInt(number);
       System.out.print(x*x);
     }
  catch(Exception e){
       System.out.print("Please enter valid data");
     }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 3
A byte char array is initialized. You have to enter an index value”n”. According to index your program will print the byte and its corresponding char value. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, it will print the required output.

Solution:

        	  String s2 = new String(barr,n,1);
              System.out.println(barr[n]);
        	  System.out.print(s2);
        }

Question 4
The following program reads a string from the keyboard and is stored in the String variable “s1”. You have to complete the program so that it should should print the number of vowels in s1 . If your input data doesn’t have any vowel it will print “0”.

    			for(int i=0;i<s1.length();i++)
                {
                    char s2=s1.charAt(i);
                    if(s2=='e' || s2=='E'|| s2=='a' || s2=='A' || s2=='i'
                       || s2=='I' || s2=='o' || s2=='O' || s2=='u' || s2=='U')
                   	{
                     	c=c+1;
                    }
             	}

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 5
A string “s1” is already initialized. You have to read the index “n” from the keyboard. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, your program should replace the char “a” at the index value “n” of the “s1” ,then it will print the modified string.

See also  Programming in Java Nptel Week 5 Assignment Answers

Solution:

    		byte[] barr=s1.getBytes();

            byte b1 = (byte) c;
            barr[n]=b1;
    		System.out.print(new String(barr));
	    }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers

More Weeks of Programming In Java: Click here

More Nptel Courses: Click here


Session: JAN-APR 2023

Course Name: Programming in Java

Course Link: Click Here

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q1. Which of these is a type of IO stream in Java?
a. Integer stream
b. Short stream
c. Byte stream
d. Character stream

Answer: c, d


Q2. Which of the following is a class in java.io package?
a. FileReader
b. ObjectInput
c. ObjectOutput
d. Datalnput

Answer: a. FileReader


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q3. Consider the following program.
What will be the output if the above program is executed?

a. It will give compile-time error.
b. B
c. 66
d. r

Answer: d. r


Q4. Consider the following program.
What is the output of the above code?

a. java/programm/2023
b. java’programm/
c. java
d. 2023

Answer: d. 2023


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q5. Which method is used to read b length bytes from the input stream into an array?
a. public void read(int b)throws IOException { {
b. public int read(byte[ ] b)throws IOException {}
c. public void read(byte[ ] b)throws IOException {}
d. public int read(int b)throws IOException {}

Answer: b. public int read(byte[ ] b)throws IOException {}


Q6. How many standard streams Java can support?
a. 2
b. 3
c 4
d. 1

Answer: b. 3


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q7. Which of the following stream is different from others?
a. System.in
b. System.out
c. PrintStream
d. FileOutputStream

Answer: c. PrintStream


Q8. Which of the following is used to read a string from the input stream?
a. get()
b. readLine( )
c. getLine( )
d. read()

Answer: b. readLine( )


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Q9. Which of the following class(es) can be used for handling files in Java?
a. java files
b. java.io.File
c. java.io
d. java Filehandling

Answer: b. java.io.File


Q10. Which of the following statement(s) is/are true?
a. The default delimiters for a Scanner object are the white space characters.
b. The Scanner class has instance methods for reading each of the Java primitive types except char.
c. The Scanner methods do not throw any checked exceptions.
d. The Scanner class can be found in the java.util package.

Answer: a, b, c, d


Programming Assignment of Programming in Java

Question 1

A byte char array is initialized. You have to enter an index value”n”. According to index your program will print the byte and its corresponding char value.
Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, it will print the required output.

Solution:

String s2 = new String(barr,n,1);
System.out.println(barr[n]);
System.out.println(s2);
}

Question 2

The following program reads a string from the keyboard and is stored in the String variable “s1”. You have to complete the program so that it should should print the number of vowels in s1 . If your input data doesn’t have any vowel it will print “0”.

Solution:

for(int i=0;i<s1.length();i++){
          char s2=s1.charAt(i);
          if(s2=='e' || s2=='E'|| s2=='a' || s2=='A' || s2=='i' || s2=='I' || s2=='o' || s2=='O' || s2=='u' || s2=='U')
	     {
	       c=c+1;
             }
         }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 3

A string “s1” is already initialized. You have to read the index “n”  from the keyboard. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, your program should replace the char “a” at the index value “n” of the “s1” ,then it will print the modified string.

Solution:

byte[] barr=s1.getBytes();
byte b1 = (byte) c;
barr[n]=b1;
System.out.println(new String(barr));
}

Question 4

Complete the following code fragment to read three integer values from the keyboard and find the sum of the values. Declare a variable “sum” of type int and store the result in it.

Solution:

import java.util.*;
public class Question1
{
  public static void main (String[] args)
  {
    int i,n=0,sum=0;
    Scanner inr = new Scanner(System.in);
    for (i=0;i<3;i++)
    {
      n = inr.nextInt();
      sum =sum+n;
    }

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 5

Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “Please enter valid data” .If there is no such exception, it will print the “square of the number”.

See also  All About NPTEL

Solution:

try{
  InputStreamReader r=new InputStreamReader(System.in);
  BufferedReader br=new BufferedReader(r);
  String number=br.readLine();
  int x = Integer.parseInt(number);
  System.out.println(x*x);
}
catch (Exception e)
{
  System.out.println("Please enter valid data");
}

These are NPTEL Programming In Java Week 7 Assignment 7 Answers

More Weeks of Programming In Java: Click Here


Session: JULY-DEC 2022

Course Name: Programming in Java NPTEL

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


1) Which of these is method for testing whether the specified element is a file or a directory?
a. IsFile()
b. isFile()
c. Isfile()
d. isfile()

Answer: b. isFile()


2) Which of the following is/are NOT Standard Stream(s)?
a. System.in
b. System.out
c. System.err
d. System.console

Answer: d. System.console


3) What will be the output of the Java code?
a. NPTEL
b. NPTEL/JULY/2022
c. /NPTEL/JULY/2022
d. 2022

Answer: d. 2022


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


4) What will be the output if the above program is executed?
a. It will give compile-time error
b. It will give run-time error
c. j
d. 106

Answer: d. 106


5) Which method is used to write a byte to the current output stream?
a. public void write(int b)throws IOException
b. public void write(byte[] b)throws IOException
c. public void flush()throws IOException
d. public void close() throws IOException

Answer: b. public void write(byte[] b)throws IOException


6) Which method of Random AccessFile class reads a line from the file and returns String ?
a. WriteInt()
b. readLine()
c. readInt()
d. WriteDouble()

Answer: b. readLine()


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


7) Which of these class is not a member class of java.io package?
a. File
b. PrintStream
c. StringReader
d. Stream

Answer: d. Stream


8) Which of the following is/are interface(s) of java.io package?
a. FileReader
b. File Writer
c. DataOutput
d. DataInput

Answer: c, d


9) In which Java APIs the classes for handling all IO-streams are defined?
a. java.lang
b. java.util
c. java.io
d. java.awt

Answer: c. java.io


These are NPTEL Programming In Java Week 7 Assignment 7 Answers


10) Consider the following program.
If the program is executed, then what will be the output from the execution?

a. length : 6
b. length : 5
c. length : 0
d. length : 1

Answer: b. length : 5


Programming Assignment Solutions

Question 1
Complete the following code fragment to read three integer values from the keyboard and find the sum of the values. Declare a variable “sum” of type int and store the result in it.

Solution:

//Code

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 2
Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “Please enter valid data” .If there is no such exception, it will print the “square of the number”.

Solution:

//Code

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 3
A byte char array is initialized. You have to enter an index value”n”. According to index your program will print the byte and its corresponding char value.
Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, it will print the required output.

Solution:

//Code

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 4
The following program reads a string from the keyboard and is stored in the String variable “s1”. You have to complete the program so that it should should print the number of vowels in s1 . If your input data doesn’t have any vowel it will print “0”.

Solution:

//Code

These are NPTEL Programming In Java Week 7 Assignment 7 Answers


Question 5
A string “s1” is already initialized. You have to read the index “n”  from the keyboard. Complete the code segment to catch the exception in the following, if any. On the occurrence of such an exception, your program should print “exception occur” .If there is no such exception, your program should replace the char “a” at the index value “n” of the “s1” ,then it will print the modified string.

Solution:

//Code

These are NPTEL Programming In Java Week 7 Assignment 7 Answers

More NPTEL Solutions: https://progiez.com/nptel


These are NPTEL Programming In Java Week 7 Assignment 7 Answers