Home

Learn Programming & Prepare for NPTEL Exams... Swayam Solver is your one-stop destination for NPTEL exam preparation.

NPTEL Programming In Java Programming Assignment July-2025 Swayam

NPTEL » Programming In Java



  Please scroll down for latest Programs. ðŸ‘‡  



Week 01 : Programming Assignment 1

Due on 2025-08-07, 23:59 IST

Write a Java program to check if a given integer is “Positive” or “Negative”.

(0 (Zero) should be considered positive by this program.)

 

NOTE:

The code you see is not complete.

Your task is to complete the code as per the question.
Think of it like a programming puzzle.

 

(Remember to match the output given exactly, including the spaces and new lines)

(Passed with presentation error means you will get full marks)

Your last recorded submission was on 2025-07-24, 10:13 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P1 {
4
    public static void main(String[] args) {
5
        Scanner in = new Scanner(System.in);
6
        int number = in.nextInt();
7
// Check if the number is Positive or Negative and print accordingly
8
if (number >= 0) {
9
  System.out.print("Positive");
10
} else {
11
  System.out.print("Negative");
12
}
0
in.close();
1
    }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4
Positive
Positive
Passed
Test Case 2
-3
Negative
Negative
Passed



Week 01 : Programming Assignment 2

Due on 2025-08-07, 23:59 IST

Write a Java program to calculate the volume of a cylinder given its radius and height.

Formula:

=2ℎ

You can use Math.PI for the computation.

NOTE:

The code you see is not complete.

Your task is to complete the code as per the question.
Think of it like a programming puzzle.

(This question can be solved in just one line of code)


Your last recorded submission was on 2025-07-24, 10:15 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P2 {
4
    public static void main(String[] args) {
5
        Scanner in = new Scanner(System.in);
6
        double radius = in.nextDouble();
7
        double height = in.nextDouble();
8
// Calculate the volume
9
double volume = Math.PI * radius * radius * height;
0
// Display the result
1
    System.out.printf("Volume is: %.2f", volume);
2
    in.close();
3
  }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
3.5
5.0
Volume is: 192.42
Volume is: 192.42
Passed



Week 01 : Programming Assignment 3

Due on 2025-08-07, 23:59 IST

Write a Java program to print the multiplication table of a given number up to 4.

 

NOTE:

Print EXACTLY as shown in the sample output.

DO NOT MISS a single space otherwise you will not be scored.

(Remember to match the output given exactly, including the spaces and new lines)

(passed with presentation error means you will get full marks)

Your last recorded submission was on 2025-07-24, 10:16 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W01_P3 {
4
    public static void main(String[] args) {
5
        Scanner in = new Scanner(System.in);
6
        int number = in.nextInt();
7
// Print the multiplication table of number up to 5
8
for (int i = 1; i <= 4; i++)
9
  System.out.printf("%d x %d = %d\n", number, i, number * i);
0
in.close();
1
    }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20
5 x 1 = 5\n
5 x 2 = 10\n
5 x 3 = 15\n
5 x 4 = 20\n
Passed after ignoring Presentation Error



Week 01 : Programming Assignment 4

Due on 2025-08-07, 23:59 IST

Complete the code fragment that reads two integer inputs from keyboard and compute the quotient and remainder.

Your last recorded submission was on 2025-07-24, 10:18 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W01_P4{
3
       public static void main(String[] args) {
4
       Scanner sc = new Scanner(System.in);
5
       int x=sc.nextInt();
6
       int y=sc.nextInt();
7
//code for quotient and remainder
8
if (y == 0) {
9
  System.out.println("Error: Division by zero is not allowed.");
10
}
11
else {
12
  int quotient = x / y;
13
  int remainder = x % y;
14
  System.out.println("The Quotient is = " + quotient);
15
  System.out.print("The Remainder is = " + remainder);
16
}
0
sc.close();  
1
  }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
556
9
The Quotient is = 61\n
The Remainder is = 7
The Quotient is = 61\n
The Remainder is = 7
Passed



Week 01 : Programming Assignment 5

Due on 2025-08-07, 23:59 IST

Write a Java program to print the area and perimeter of a rectangle.

Your last recorded submission was on 2025-07-24, 10:19 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
public class W01_P5 { 
3
   public static void main(String[] strings) {
4
       double width ;
5
       double height;
6
       Scanner in = new Scanner(System.in);
7
       width = in.nextDouble();
8
       height = in.nextDouble();
9
// Calculate the perimeter of the rectangle
10
double perimeter = 2 * ( height + width ) ;
11
// Calculate the area of the rectangle
12
double area = height * width;
0
// Print the calculated perimeter using placeholders for values
1
       System.out.printf("Perimeter is 2*(%.1f + %.1f) = %.2f\n", height, width, perimeter);
2
3
// Print the calculated area using placeholders for values
4
       System.out.printf("Area is %.1f * %.1f = %.2f", width, height, area);    
5
   }
6
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5.6 8.5
Perimeter is 2*(8.5 + 5.6) = 28.20\n
Area is 5.6 * 8.5 = 47.60
Perimeter is 2*(8.5 + 5.6) = 28.20\n
Area is 5.6 * 8.5 = 47.60
Passed




W02 Programming Assignments 1

Due on 2025-08-07, 23:59 IST

Write a Java program to calculate the area of a rectangle.

The formula for area is:
Area = length × width

You are required to read the length and width from the user, compute the area, and print the result.

This task helps you practice using variables, arithmetic operations, and printing output in Java.

Your last recorded submission was on 2025-08-01, 16:57 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W02_P1 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read length and width of the rectangle
8
        int length = sc.nextInt();
9
        int width = sc.nextInt();
10
// ================================================
11
        // NOTE TO STUDENTS:
12
        // This is a simple beginner-level task.
13
        // Your role is to calculate the area using the given length and width.
14
        // Complete the line below using the correct formula.
15
        // ================================================
16
17
        // TODO: Calculate area of the rectangle
18
19
        /*
20
         Hint:
21
         - Multiply length and width to get the area
22
         - Store the result in a variable called 'area'
23
         */
24
int area = length * width;
0
// Print the area
1
        System.out.print("Area is: " + area);
2
3
        sc.close();
4
    }
5
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5
10
Area is: 50
Area is: 50
Passed



W02 Programming Assignments 2

Due on 2025-08-07, 23:59 IST

Problem Statement

Write a Java program to calculate the perimeter of a rectangle.

The formula for perimeter is:
Perimeter = 2 multiplied by (length + width)

You are required to read the length and width as integers from the user, compute the perimeter, and print the result.

This problem helps in practicing arithmetic operations and output printing in Java.

Your last recorded submission was on 2025-08-01, 16:59 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W02_P2 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read length and width of the rectangle
8
        int length = sc.nextInt();
9
        int width = sc.nextInt();
10
// Complete the code to calculate the perimeter of the rectangle
11
        // TODO: Calculate the perimeter using the correct formula
12
        /*
13
         Hint:
14
         The formula is: perimeter = 2 multiplied by (length + width)
15
         */
16
int perimeter = 2 * (length + width);
0
System.out.println("Perimeter is: " + perimeter);
1
2
        sc.close();
3
    }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
4  
6
Perimeter is: 20
Perimeter is: 20\n
Passed after ignoring Presentation Error



W02 Programming Assignments 3

Due on 2025-08-07, 23:59 IST

Finding the Maximum Element in an Array


Problem Statement

What is the Maximum Element?
In an array of numbers, the maximum is the largest number among all elements.

In this assignment:

  • You will read n numbers from the user

  • Store them in an array

  • Find the largest number among them

  • Print the maximum number

This task helps you apply loops and arrays together to solve a real logic-based problem.

Your last recorded submission was on 2025-08-01, 17:00 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W02_P3 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        int n = sc.nextInt();
8
        int[] arr = new int[n];
9
10
        // Read n numbers into array
11
        for (int i = 0; i < n; i++) {
12
            arr[i] = sc.nextInt();
13
        }
14
15
        int max = arr[0];  // Assume first element is maximum
16
// TODO: Use a loop to find maximum element
17
        /*
18
         Hint:
19
         Start loop from index 1 to n - 1
20
         Compare each element with max
21
         If element is greater, update max
22
         */
23
for (int i = 1; i < n; i++) {
24
  if (arr[i] > max) {
25
    max = arr[i];
26
  }
27
}
0
System.out.println("Maximum is: " + max);
1
2
        sc.close();
3
    }
4
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5  
15 42 9 28 37
Maximum is: 42
Maximum is: 42\n
Passed after ignoring Presentation Error



W02 Programming Assignments 4

Due on 2025-08-07, 23:59 IST

Create a Class and Access Its Member Variable


Problem Statement

In this task, you will practice creating and using a class in Java.

You need to:

  1. Create a class called Rectangle

  2. Declare two integer member variables length and width

  3. In the main method, create an object of the Rectangle class, assign values to length and width, and print their sum

This problem helps you understand how to define a class, create objects, and access class members in Java.

Your last recorded submission was on 2025-08-01, 17:01 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W02_P4 {
4
5
    // Declare a class named Rectangle
6
    static class Rectangle {
7
        int length;
8
        int width;
9
    }
10
11
    public static void main(String[] args) {
12
        Scanner sc = new Scanner(System.in);
13
14
        // Read length and width
15
        int l = sc.nextInt();
16
        int w = sc.nextInt();
17
18
        // Create an object of the Rectangle class
19
        Rectangle rect = new Rectangle();
20
21
        // Assign values to the object's member variables
22
        rect.length = l;
23
        rect.width = w;
24
// Complete the code to print the sum of length and width
25
        // TODO: Print the sum using rect.length and rect.width
26
        /*
27
         Hint:
28
         Use: rect.length + rect.width to get the sum
29
         Print the result using System.out.println
30
         tip--System.out.println("Sum of length and width is: " +.....)
31
         */
32
System.out.println("Sum of length and width is: " + (rect.length + rect.width));
0
sc.close();
1
    }
2
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
5  
10
Sum of length and width is: 15
Sum of length and width is: 15\n
Passed after ignoring Presentation Error



W02 Programming Assignments 5

Due on 2025-08-07, 23:59 IST

Working with Multiple Classes, Constructors, and the this Keyword


Problem Statement

In this task, you will learn how to:

  • Declare multiple classes in the same Java program

  • Use constructors to initialize values

  • Apply the this keyword to refer to instance variables

What you need to do:

  1. Declare a class called Circle with one member variable radius

  2. Write a constructor for Circle that takes radius as a parameter and assigns it using the this keyword

  3. In the main method, create an object of Circle and print its radius

This task helps understand how classes work together and how constructors and the this keyword are used for clarity.


Your last recorded submission was on 2025-08-01, 17:02 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W02_P5 {
4
5
    // Declare a separate class named Circle
6
    static class Circle {
7
8
        int radius;
9
// TODO: Write a constructor that takes radius as parameter
10
        // Use the 'this' keyword to assign the value to the member variable
11
        /*
12
         Hint:
13
         The constructor name should be Circle
14
         Use: this.radius = radius;
15
         */
16
public Circle(int radius) {
17
  this.radius = radius;
18
}
0
}
1
2
    public static void main(String[] args) {
3
        Scanner sc = new Scanner(System.in);
4
5
        // Read radius value from user
6
        int r = sc.nextInt();
7
8
        // Create an object of Circle class using constructor
9
        Circle c = new Circle(r);
10
11
        // Print the radius using object member
12
        System.out.println("Radius of the circle is: " + c.radius);
13
14
        sc.close();
15
    }
16
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
7
Radius of the circle is: 7
Radius of the circle is: 7\n
Passed after ignoring Presentation Error





W06 Programming Assignments 1

Due on 2025-09-04, 23:59 IST

Safe Division with Run-time Error Handling


Problem Statement

In Java, some operations can cause run-time errors, for example dividing a number by zero.
We can use a try-catch block to handle such errors and avoid program crashes.

Task:

  • Read two integers from the user

  • Divide the first number by the second inside a try-catch block

  • If the second number is zero, print "Cannot divide by zero"

  • Otherwise, print the result

This task introduces basic run-time error handling in a safe and controlled way.

Your last recorded submission was on 2025-08-30, 17:15 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W06_P1 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read two integers
8
        int num1 = sc.nextInt();
9
        int num2 = sc.nextInt();
10
11
        // Use try-catch to handle possible run-time error
12
        try {
13
int result = num1 / num2;
14
System.out.println("Result is: " + result);
0
} catch (ArithmeticException e) {
1
            // Print safe message if division by zero occurs
2
            System.out.println("Cannot divide by zero");
3
        }
4
5
        sc.close();
6
    }
7
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
10  
0
Cannot divide by zero
Cannot divide by zero\n
Passed after ignoring Presentation Error
Test Case 2
10  
2
Result is: 5
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 2

Due on 2025-09-04, 23:59 IST

Programming Assignment: Nested try-catch Block


Problem Statement

In Java, nested try-catch blocks allow handling multiple levels of errors separately.
You can place one try-catch block inside another to handle different types of errors in different places.

Programming Assignment:

  • Read two integers from the user

  • Inside an outer try-catch block, perform the following:

    • Inside a nested try block, divide the first number by the second

    • If division by zero occurs, handle it with the inner catch block

  • In the outer catch block, handle any other unexpected errors

  • Print appropriate messages for each scenario

This programming assignment introduces nested try-catch structure.

Your last recorded submission was on 2025-08-30, 17:17 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W06_P2 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read two integers
8
        int num1 = sc.nextInt();
9
        int num2 = sc.nextInt();
10
11
        // Outer try-catch block
12
        try {
13
14
            // Inner try-catch block for division operation
15
            try {
16
int result = num1 / num2;
17
System.out.println("Division successful");
18
System.out.println("Result is: " + result);
0
} catch (ArithmeticException e) {
1
                System.out.println("Cannot divide by zero");
2
            }
3
4
        } catch (Exception e) {
5
            // Handles other unexpected errors
6
            System.out.println("An unexpected error occurred");
7
        }
8
9
        sc.close();
10
    }
11
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
10  
2
Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 3

Due on 2025-09-04, 23:59 IST

Programming Assignment: try Block with Multiple catch Blocks


Problem Statement

In Java, a try block can be followed by multiple catch blocks to handle different types of errors separately.

This improves error handling by allowing specific actions for different exceptions.

Key Concepts:

  • The first matching catch block handles the error

  • Catch blocks are written in order from most specific to general

Programming Assignment:

  • Read two integers from the user

  • Inside a try block, divide the first number by the second

  • Handle ArithmeticException separately to detect division by zero

  • Handle any other general errors using another catch block

  • Print suitable messages based on the type of error

This demonstrates structured error handling with multiple catch blocks.

Your last recorded submission was on 2025-08-30, 17:19 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W06_P3 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read two integers
8
        int num1 = sc.nextInt();
9
        int num2 = sc.nextInt();
10
11
        // Try block with multiple catch blocks
12
        try {
13
// TODO: Perform division and print result if successful
14
            int result = num1 / num2;
15
            System.out.println("Division successful");
16
            System.out.println("Result is: " + result);
0
} catch (ArithmeticException e) {
1
            // Handles division by zero error
2
            System.out.println("Cannot divide by zero");
3
        } catch (Exception e) {
4
            // Handles other general errors
5
            System.out.println("An unexpected error occurred");
6
        }
7
8
        sc.close();
9
    }
10
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
20  
4
Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Passed after ignoring Presentation Error



W06 Programming Assignments 4

Due on 2025-09-04, 23:59 IST

Programming Assignment: Using finally in try-catch Block


Problem Statement

In Java, the finally block is a special part of error handling.

What is finally?

  • The code inside a finally block always runs, whether there is an error or not

  • It is usually used to close resources like files, database connections, or simply to show a message

Programming Assignment:

  • Read two integers from the user

  • Inside a try block, divide the first number by the second

  • If division by zero occurs, show an error message using catch block

  • Use a finally block to print "Program Ended" no matter what happens

This helps you understand how finally block always runs in a program.

Your last recorded submission was on 2025-08-30, 17:21 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W06_P4 {
4
    public static void main(String[] args) {
5
        Scanner sc = new Scanner(System.in);
6
7
        // Read two integers
8
        int num1 = sc.nextInt();
9
        int num2 = sc.nextInt();
10
11
        // try-catch-finally structure
12
        try {
13
// TODO: Perform division and print result
14
            int result = num1 / num2;
15
            System.out.println("Result is: " + result);
0
} catch (ArithmeticException e) {
1
            System.out.println("Cannot divide by zero");
2
        } finally {
3
            // Print final message, runs always
4
            System.out.println("Program Ended");
5
        }
6
7
        sc.close();
8
    }
9
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
15  
3
Result is: 5\n
Program Ended
Result is: 5\n
Program Ended\n
Passed after ignoring Presentation Error



W06 Programming Assignments 5

Due on 2025-09-04, 23:59 IST

Programming Assignment: Using throws Statement for Error Handling


Problem Statement

In Java, the throws keyword is used when a method might cause an error, but the method itself does not handle it.
Instead, it passes the responsibility to the caller of the method.

Why use throws?

  • Some methods may cause errors called "checked exceptions"

  • Instead of handling the error inside the method, we declare throws to inform the caller

Programming Assignment:

  • Create a method called calculateSquareRoot

  • The method reads a number and returns its square root

  • If the number is negative, it throws an Exception

  • In the main method, use a try-catch block to handle the error

This demonstrates how to use throws and handle errors safely in the caller method.

Your last recorded submission was on 2025-08-30, 17:23 IST
Select the Language for this assignment. 
File name for this program : 
1
import java.util.Scanner;
2
3
public class W06_P5 {
4
5
    // Method to calculate square root, may throw Exception
6
    public static double calculateSquareRoot(double num) throws Exception {
7
// TODO: Throw Exception if number is negative
8
        if (num < 0) {
9
            throw new Exception("Number cannot be negative");
10
        }
11
        return Math.sqrt(num);
0
}
1
2
    public static void main(String[] args) {
3
        Scanner sc = new Scanner(System.in);
4
5
        double number = sc.nextDouble();
6
7
        try {
8
            double result = calculateSquareRoot(number);
9
            System.out.println("Square root is: " + result);
10
        } catch (Exception e) {
11
            System.out.println("Cannot calculate square root of negative number");
12
        }
13
14
        sc.close();
15
    }
16
}
You may submit any number of times before the due date. The final submission will be considered for grading.
This assignment has Public Test cases. Please click on "Compile & Run" button to see the status of Public test cases. Assignment will be evaluated only after submitting using Submit button below. If you only save as or compile and run the Program , your assignment will not be graded and you will not see your score after the deadline.
   


 
 
Public Test CasesInputExpected OutputActual OutputStatus
Test Case 1
16
Square root is: 4.0
Square root is: 4.0\n
Passed after ignoring Presentation Error











































































No comments:

Post a Comment

Keep your comments reader friendly. Be civil and respectful. No self-promotion or spam. Stick to the topic. Questions welcome.