Programming in Java | Week 12

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 12 Assignment 12 Answers


Q1. Which of the following statements are correct and would NOT cause a compilation error?
a. iii, iv, v, vi
b. i, ii, iii, iv
c. ii, iii, v, vi
d. i, ii, iv, vi

Answer: a. iii, iv, v, vi

Q2. What is the result, if the following program is executed?
a. “finally”
b. “exception finished”
c. “finally exception finished”
d. Compilation fails

Answer: c. “finally exception finished”

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

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q3. What is the output of the following program?
a. java
b. ava
c. java – nptel
d. with

Answer: a. java

Q4. If you run this program the how many threads will be executed altogether?
a. One thread only.
b. Two threads only.
c. Three threads only.
d. No thread will run in this case.

Answer: b. Two threads only.

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

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q5. Which of the following method is used to set a frame, say f with size 300 × 200 pixels?
a. f.setSize(300, 200);
b. f.setSize(200, 300);
c. f.paint(300, 200);
d. f.setVisible(300, 200);

Answer: a. f.setSize(300, 200);

Q6. Which of the following control expressions are valid for an if statement?
i. Any integer expression.
ii. Any Boolean expression.
iii. A String object.
iv. Any expression with mixed arithmetic.

a. only ii
b. ii, iii
c. ii,iv
d. i, ii

Answer: a. only ii

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

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q7. Which of the following options correctly initializes the elements of the numbers array with values 1, 2, 3, 4, and 5?
a. numbers = {1, 2, 3, 4, 5};
b. for (int i=1; i < numbers.length; i++) {
numbers [i] = 1;
}
c. numbers [] = {1, 2, 3, 4, 5};
d. numbers = new int[]{1, 2, 3, 4, 5};

Answer: d. numbers = new int[]{1, 2, 3, 4, 5};

Q8. Which of the following options correctly extracts and prints the word “World” from the str string?
a. System.out.println(str.substring(7, 12));
b. System.out.println(str.substring(7, 12));
c. System.out.println(str.extract(7, 12));
d. System.out.println(str.substr(7, 13));

Answer: a. System.out.println(str.substring(7, 12));

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

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q9. What will be the output of this program?
a. true false
b. false true
c. true true
d. false false

Answer: a. true false

Q10. What will be the output of this program?
a. Compilation ERROR
b. “Finally block executed”
c. “Arithmetic exception occurred
Finally block executed”
d. Runtime ERROR

Answer: c. “Arithmetic exception occurred
Finally block executed”

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

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Programming Assignment

Question 1
Write a program that calculates the letter grade based on a numerical score entered by the user.
§ >=80 – A
§ 70-79 – B
§ 60-69 – C
§ 50-59 – D
§ 40-49 – P
§ <40 – F
Follow the naming convention as given in the main method of the suffix code.

Solution:

public static char calculateGrade(int score){
  if (score >= 80)
    return 'A';
  if (score >= 70 && score < 80)
    return 'B';
  if (score >= 60 && score < 70)
    return 'C';
  if (score >= 50 && score < 60)
    return 'D';
  if (score >= 40 && score < 50)
    return 'P';
  if (score < 40)
    return 'F';
  else
    return 'e';
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 2
Write a program that validates a user’s password based on the following criteria (in the following order):
§ 1. The password must be at least 8 characters long.
§ 2. The password must contain at least one uppercase letter (A-Z).
§ 3. The password must contain at least one lowercase letter (a-z).
§ 4. The password must contain at least one digit (0-9).
Take the following assumptions regarding the input:
§ The input will not contain any spaces
Your output should print the rule that it violates exactly as defined above.
If the password violates multiple rules then the first rule it violates should take priority.

See also  Programming in Java | Week 9

Solution:

public static void validatePassword(String pass){
  String rules = ""; boolean Uc = false; boolean Lc = false; boolean dig = false;
  if ( pass.length() < 8 )
    rules += "The password must be at least 8 characters long.\n";
  for ( int i = 0 ; i < pass.length(); i++ ){
    if ( pass.charAt(i) >= 65 && pass.charAt(i) <= 90 )
      Uc = true;
    if ( pass.charAt(i) >= 97 && pass.charAt(i) <= 122 )
      Lc = true;
    if ( pass.charAt(i) >= 48 && pass.charAt(i) <= 57 )
      dig = true;
    
  }
  if ( !Uc )
    rules += "The password must contain at least one uppercase letter (A-Z).\n";
  if ( !Lc )
    rules += "The password must contain at least one lowercase letter (a-z).\n";
  if ( !dig )
    rules += "The password must contain at least one digit (0-9).\n";
  
  if ( rules == "" )
    rules = "Your password is valid." + rules;
  else
    rules = "Your password is invalid.\n" + rules;
  
  System.out.print(rules);
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 3
Write a program that analyzes a given text and provides the following information:
§ Number of words: The total number of words in the text.
§ Longest word: The longest word found in the text.
§ Vowel count: The total number of vowels (a, e, i, o, u) in the text.
Take the following assumptions regarding the input:
§ The input will only contain lowerspace characters[a-z] and spaces.
§ The last word will not end with a space nor with any special character.
You need to print exactly as shown in the test case.
Do not print anyting else while taking input.
Follow the naming convention as given in the main method of the suffix code.

Solution:

import java.util.Scanner;
 
public class W12_P3 {
  public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);
    String text = scanner.nextLine();
    scanner.close();
    int wc = 0, vc = 0; String longest = "";
    
    String[] arrOfStr = text.split(" ");
    wc = arrOfStr.length;
    
    for (String a : arrOfStr){
      if ( a.length() >= longest.length() )
        longest = a;
      for ( int i = 0 ; i < a.length() ; i++){
        char c = a.charAt(i);
        if ( c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u' || c == 'I' )
          vc++;
      }
    }
    System.out.println("Number of words: " + wc );
    System.out.println("Longest word: " + longest);
    System.out.print("Vowel count: " + vc );
    }
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 4
Write a Java program to calculate the area of different shapes using inheritance.
Each shape should extend the abstact class Shape
Your task is to make the following classes by extending the Shape class:
§ Circle (use Math.PI for area calculation)
§ Rectangle
§ Square
Each Shape subclass should have these private variables apart from the private variables for storing sides or radius.
private String shapeType;
private double area;
Follow the naming convention as given in the main method of the suffix code.

Solution:

class Circle extends Shape {
  private String shapeType;
  private double area;
  private double radius;
  
  Circle(String shapeType, double arg1){
    this.shapeType = shapeType;
    radius = arg1;
  }
  
  protected void calcArea(){
    area = Math.PI * radius * radius;
  }
  
  public void printArea(){
    System.out.print("Area of Circle: " + area );
  }
}
 
class Rectangle extends Shape {
  private String shapeType;
  private double area;
  private double length;
  private double breadth;
  
  Rectangle(String shapeType, double arg1, double arg2){
    this.shapeType = shapeType;
    length = arg1;
    breadth = arg2;
  }
  
  protected void calcArea(){
    area = length * breadth;
  }
  
  public void printArea(){
    System.out.print("Area of Rectangle: " + area );
  }
}
 
class Square extends Shape {
  private String shapeType;
  private double area;
  private double side;
  
  Square(String shapeType, double arg1){
    this.shapeType = shapeType;
    side = arg1;
  }
  
  protected void calcArea(){
    area = side * side;
  }
  
  public void printArea(){
    System.out.print("Area of Square: " + area );
  }
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 5
Implement two classes, Car and Bike, that implement the Vehicle interface.
Each class should have appropriate attributes and constructors.
Ensure that the start, accelerate, and brake methods are implemented correctly for each vehicle.
Follow the naming convention as given in the main method of the suffix code.

See also  Programming In Java | Week 4

Solution:

class Car implements Vehicle{
    private int numDoors;
    Car(int numDoors){
      this.numDoors = numDoors;
    }
    public void start() {
      System.out.println("Car with " + numDoors + " doors started");
    }
  public void accelerate() {
      System.out.println("Accelerating to 60 mph");
    }
  public void brake() {
      System.out.print("Applying brakes");
    }
  
}
 
class Bike implements Vehicle{
    private int numWheels;
    Bike(int numWheels){
      this.numWheels = numWheels;
    }
    public void start() {
      System.out.println("Bike with " + numWheels + " wheels started");
    }
  public void accelerate() {
      System.out.println("Accelerating to 40 mph");
    }
  public void brake() {
      System.out.print("Applying brakes");
    }
  
}

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

These are NPTEL Programming In Java Week 12 Assignment 12 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 12 Assignment 12 Answers


Programming Assignment

Question 1
Complete the code to develop an extended version of the ADVANCED CALCULATOR with added special functions that emulates all the functions of the GUI Calculator as shown in the image.

Solution:

Code

Question 2
A partial code fragment is given. The URL class object is created in try block.You should write appropriate method( )  to print the protocol name and host name from the given url string.
For example:
https://www.xyz.com:1080/index.htm
protocol://host:port/filename

Solution:

try
{
  URL url=new URL("http://www.Nptel.com/java-tutorial");
  System.out.println("Protocol: "+url.getProtocol());
  System.out.print("Host Name: "+url.getHost());
}
catch(Exception e){System.out.println(e);}
}
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 3
Write a program to create a record by taking inputs using Scanner class as first name as string ,last name as string ,roll number as integer ,subject1 mark as float,subject2 mark as float. Your program should print in the format 
  “name  rollnumber avgmark”.

Solution:

String f = s1.next();
String l = s1.next();
int n = s1.nextInt();
double db = s1.nextDouble();
double db1 = s1.nextDouble();
double avg=(db+db1)/2;
System.out.print(f + l +" "+ n +" "+avg );

Question 4
A program code is given to call the parent class static method and instance method in derive class without creating object of parent class. You should write the appropriate code so that the program print the contents of static method() and instance method () of parent class.

Solution:

public static void main(String[] args)
{
  Child c= new Child();
  c.testInstanceMethod();
  Parent.testClassMethod();
}
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 5
Write a recursive function to print the sum of  first n odd integer numbers. The recursive function should have the prototype
 ” int sum_odd_n(int n) “.

Solution:

return 2*n-1 + sum_odd_n(n-1);

These are NPTEL Programming In Java Week 12 Assignment 12 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 12 Assignment 12 Answers


Q1. Which statement is incorrect in case of using “this” keyword in a static method?
a. “this” keyword can be used in static method to access static variables only
b. “this” keyword first needs to be defined by user
c. “this” keyword cannot be used as a variable name
d. “this” keyword can not be used in static method to access static variables only

Answer: b, d


Q2. State whether the following statements are True or False.
i) A catch can not have comma-separated multiple arguments.
ii) Throwing an Exception always causes program termination.

a. True. False
b. False. True
c. True. True
d. False. False

Answer: a. True. False


These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q3. Which of the following contains only date and not time?
a. java.io.date
b. java.sql.date
c. java.util.date
d. java.util. dateTime

Answer: b. java.sql.date


These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q4. Why the applets are depreciated?
a. Applet are complicated to program
b. Applet had severe security issues
c. Applet was replaced by AWT
d. Applet was resource intensive

Answer: b. Applet had severe security issues


These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q5. Which of the following control expressions are valid for an if statement?
a. Any integer expression.
b. 0 and 1 as integer.
c. A String object.
d. Any Boolean expression.

Answer: d. Any Boolean expression.


Q6. Consider the following program:
String animal = “GOAT”:
switch(animal){
break: System.out.println(“DOMESTIC”):
}
What is the output of the Java program given above?

a. No output
b. GOAT
c. DOMESTIC
d. Compiler error

See also  Programming in Java | Week 6

Answer: d. Compiler error


These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q7. Consider the following program:
What is the output of the following program?

a. java
b. ava
c. y java
d. ava n

Answer: d. ava n


Q8. Which of the following are correct statement for array declaration?
a. float[] = new float (3);
b. float f2[] = new floatl[];
c. float[] f1 = new float[3];
d. float F3[] = new float[3];

Answer: c, d


These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Q9. Consider the following piece of code in Java.
What is the result, if the above-mentioned program is executed?

a. finally
b. finally exception finally finished
c. finally exception finished
d. Compilation fails

Answer: b. finally exception finally finished


Q10. Which is a component in AWT that can contain another components like buttons, textfields, labels ete.?
a. Window
b. Panel
c. Container
d. Frame

Answer: c. Container


Programming Assignment of Programming in Java

Question 1

Complete the code to develop an extended version of the ADVANCED CALCULATOR with added special functions that emulates all the functions of the GUI Calculator as shown in the image.
Note the following points carefully:

1. Use only double datatype to store all numeric values.
2. Each button on the calculator should be operated by typing the characters from ‘a’ to ‘t’.
3. You may use the already defined function gui_map(char).
4. Use predefined methods from java.lang.Math class wherever applicable.
5. Without ‘=’ binary operations won’t give output as shown in Input_3 and Output_3 example below.
5. The calculator should be able to perform required operations on one or two operands as shown in the below example:
Input_1:
                   okhid
Output_1:
               100.0
Input_2:
                   ia
Output_2:                        2.0

Solution:

outerloop:
for(int i=0; i<seq.length; i++)
{
  int r=0;
  if(seq[i]=='+'||seq[i]=='-'||seq[i]=='/'||seq[i]=='X'||seq[i]=='=')
  {
    for(int j=0; j<i; j++)
    {
      o1+=Character.toString(seq[j]);
    }
    operand1=Double.parseDouble(o1);
    for(int k=i+1; k<seq.length; k++)
    {
      if(seq[k]=='=')
      {
        outflag=1;
        operand2=Double.parseDouble(o2);
        if(seq[i]=='+')
        {
          output=operand1+operand2;
        }
        else if(seq[i]=='-')
        {
          output=operand1-operand2;
        }
        else if(seq[i]=='/')
        {
          output=operand1/operand2;
        }
        else if(seq[i]=='X')
        {
          output=operand1*operand2;
        }
        break outerloop;
      }
      else
      {
        o2+=Character.toString(seq[k]);
      }
    }
  }
  else if(seq[i]=='R' || seq[i]=='S' || seq[i]=='F')
  {
    for (int j=0;j<i;j++)
      o1+=Character.toString(seq[j]);
    operand1=Double.parseDouble(o1);
    if (seq[i]=='R')
      System.out.print(Math.sqrt(operand1));
    else if(seq[i]=='S')
      System.out.print(operand1*operand1);
      else if (seq[i]=='F')
      System.out.print(1/operand1);
     }
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 2

A partial code fragment is given. The URL class object is created in try block.You should write appropriate method( )  to print the protocol name and host name from the given url string.
For example:
https://www.xyz.com:1080/index.htm
protocol://host:port/filename

Solution:

try{
     URL url=new URL("http://www.Nptel.com/java-tutorial");

     System.out.println("Protocol: "+url.getProtocol());
     System.out.println("Host Name: "+url.getHost());

      }
       catch(Exception e){System.out.println(e);}
   }
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 3

Write a program to create a record by taking inputs using Scanner class as first name as string ,last name as string ,roll number as integer ,subject1 mark as float,subject2 mark as float. Your program should print in the format 
  “name  rollnumber avgmark”.
For example:
input:
ram
das
123
25.5
24.5
output:
ramdas 123 25.0

Solution:

String f = s1.next();
String l = s1.next();
int n = s1.nextInt();
double db = s1.nextDouble();
double db1 = s1.nextDouble();
double avg=(db+db1)/2;
System.out.println(f + l +" "+ n +" "+avg );

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 4

A program code is given to call the parent class static method and instance method in derive class without creating object of parent class. You should write the appropriate code so that the program print the contents of static method() and instance method () of parent class.

Solution:

public static void main(String[] args)
{
  Child c= new Child();
  c.testInstanceMethod();
  Parent.testClassMethod();
}
}

These are NPTEL Programming In Java Week 12 Assignment 12 Answers


Question 5

Write a recursive function to print the sum of  first n odd integer numbers. The recursive function should have the prototype
 ” int sum_odd_n(int n) “.
For example :
input : 5
output: 25 
input : 6
output : 36

Solution:

int c=n,sum=0;
if(c==n){
	sum=n*2-1;
}
return sum+sum_odd_n(n-1);

These are NPTEL Programming In Java Week 12 Assignment 12 Answers

More Weeks of Programming In Java: Click Here

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


These are NPTEL Programming In Java Week 12 Assignment 12 Answers