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-2026 Swayam


Programming In Java - July 2026

NPTEL

 Please scroll down for latest Programs   ðŸ‘‡ 


Code compiled and tested successfully!


W03 Programming Assignments 1

Due date on 2026-08-14, 23:59 IST

Your last recorded submission was on 2026-08-13, 11:43 IST.

Q.

Write a program to print the factorial of a number by defining a recursive method named 'Factorial'.
Factorial of any number n is represented by n! and is equal to 1*2*3*....*(n-1)*n. E.g.-
4! = 1*2*3*4 = 24
3! = 3*2*1 = 6
2! = 2*1 = 2
Also,
1! = 1
0! = 1
(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will get full marks)

Complete Program

Java
import java.util.Scanner;

class W03_P1 {

    // --- START OF SOLUTION CODE ---
    public static int factorial(int x) {
        if (x == 0 || x == 1) {
            return 1;
        } else {
            return factorial(x - 1) * x;
        }
    }
    // --- END OF SOLUTION CODE ---

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int x;
        x = in.nextInt();
        System.out.println(factorial(x));
    }
}

Code Snippet to Paste in the Editor

Java
    // --- START OF SOLUTION CODE ---
    public static int factorial(int x) {
        if (x == 0 || x == 1) {
            return 1;
        } else {
            return factorial(x - 1) * x;
        }
    }
    // --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

5

120
120\n
Presentation Error


W03 Programming Assignments 2

Due date on 2026-08-14, 23:59 IST

Q.

There are two class cls1 and cls2 which is subclass of cls1.  cls1 having a method "add" which add two numbers.
Create two method inside cls2 which will take 2 parameters as input i.e. a and b and print the sum , multiplication and sum of their squares i.e (a^2) + (b^2).
(Remember to match the output given exactly, including the spaces and new lines)
(passed with presentation error means you will get full marks)

Complete Program

Java
import java.util.Scanner;

class cls1
{
    void add(int p,int q)
    {
        System.out.println(p+q);
    }
}

// --- START OF SOLUTION CODE ---
class cls2 extends cls1
{
    void mul(int p, int q)
    {
        System.out.println(p * q);
    }
    void task(int p, int q)
    {
        System.out.println((p * p) + (q * q));
    }
}
// --- END OF SOLUTION CODE ---

public class W03_P2{
    public static void main(String args[])
    {
        Scanner sc=new Scanner(System.in);
        cls2 obj=new cls2();
        int a=sc.nextInt();
        int b=sc.nextInt();
        //String tilde=sc.next();
        obj.add(a,b);
        obj.mul(a,b);
        obj.task(a,b);
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
class cls2 extends cls1
{
    void mul(int p, int q)
    {
        System.out.println(p * q);
    }
    void task(int p, int q)
    {
        System.out.println((p * p) + (q * q));
    }
}
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

2 4

6\n
8\n
20
6\n
8\n
20\n
Presentation Error


W03 Programming Assignments 3

Due date on 2026-08-14, 23:59 IST

Q.

Complete the code segment to count number of digits in an integer using while loop.

Complete Program

Java
import java.util.Scanner;

public class W03_P3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        // --- START OF SOLUTION CODE ---
        int count = 0;
        while (num != 0) {
            num /= 10;
            ++count;
        }
        System.out.print(count);
        // --- END OF SOLUTION CODE ---
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        int count = 0;
        while (num != 0) {
            num /= 10;
            ++count;
        }
        System.out.print(count);
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 2/2 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

153

3
3
-
Test Case 2

0003452

4
4
-


W03 Programming Assignments 4

Due date on 2026-08-14, 23:59 IST

Q.

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.
(Use Student.java as file name here)

Complete Program

Java
import java.util.Scanner;

class Student {
    private String name;
    private int age;

    // --- START OF SOLUTION CODE ---
    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;
    }
    // --- END OF SOLUTION CODE ---

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // System.out.print("Enter student name: ");
        String name = scanner.next();
        // System.out.print("Enter student age: ");
        int age = scanner.nextInt();
        Student student = new Student(name, age);
        System.out.print("Name: " + student.getName() + ", Age: " + student.getAge());
        scanner.close();
    }
}

Code Snippet to Paste in the Editor

Java
    // --- START OF SOLUTION CODE ---
    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;
    }
    // --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 2/2 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

John 20

Name: John, Age: 20
Name: John, Age: 20
-
Test Case 2

Alice 25

Name: Alice, Age: 25
Name: Alice, Age: 25
-



W03 Programming Assignments 5

Due date on 2026-08-14, 23:59 IST

Q.

Complete the code segment to display the factors of a number n.

Complete Program

Java
import java.util.Scanner;

public class W03_P5 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num = sc.nextInt();

        // --- START OF SOLUTION CODE ---
        for (int i = 1; i <= num; i++) {
            if (num % i == 0) {
                System.out.print(i + " ");
            }
        }
        // --- END OF SOLUTION CODE ---
    }
}

Code Snippet to Paste in the Editor

Java
        // --- START OF SOLUTION CODE ---
        for (int i = 1; i <= num; i++) {
            if (num % i == 0) {
                System.out.print(i + " ");
            }
        }
        // --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

18

1 2 3 6 9 18
1 2 3 6 9 18 
Presentation Error






W04 Programming Assignments 1

Due date on 2026-08-20, 23:59 IST

Q.

Understanding Default Access Modifier in Java
Problem Statement
In Java, if no access modifier is written before a class member (variable or method), it is called Default Access
Modifier.
Members with default access are accessible within the same package, which in beginner programs means within
the same file.
Task:
 Create a class called Student
 Declare an integer variable rollNo with default access (do not write any modifier)
 In the main method, create an object of Student and print the rollNo
This task shows that default access members can be accessed within the same file.

Complete Program

Java
import java.util.Scanner;
public class W04_P1 {
// Declare a class Student with one member variable of default access
static class Student {
int rollNo; // Default access modifier (no keyword written)
// Constructor to assign rollNo
Student(int r) {
rollNo = r;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Read roll number
int r = sc.nextInt();
// Create Student object with roll number
Student s = new Student(r);

// --- START OF SOLUTION CODE ---
System.out.println("Roll Number is: " + s.rollNo);
// --- END OF SOLUTION CODE ---

sc.close();
}
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
System.out.println("Roll Number is: " + s.rollNo);
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

101

Roll Number is: 101
Roll Number is: 101\n
Presentation Error


W04 Programming Assignments 2

Due date on 2026-08-20, 23:59 IST

Q.

Understanding Public Access Modifier in Java


Problem Statement

In Java, members (variables or methods) declared with the public access modifier can be accessed from anywhere, including outside their class.

Task:

  • Create a class called Car

  • Declare a public integer variable called speed

  • In the main method, create an object of Car, assign a value to speed, and print it

This demonstrates how public members can be accessed from outside the class.

Complete Program

Java
import java.util.Scanner;
public class W04_P2 {
    // Declare class Car with a public member variable
    static class Car {
        public int speed; // Public access, can be accessed from outside the class
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read speed value
        int s = sc.nextInt();
        // Create Car object
        Car c = new Car();
        // Assign speed to the object
        c.speed = s;

        // --- START OF SOLUTION CODE ---
        System.out.println("Speed is: " + c.speed);
        // --- END OF SOLUTION CODE ---

        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        System.out.println("Speed is: " + c.speed);
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

80

Speed is: 80
Speed is: 80\n
Presentation Error



W04 Programming Assignments 3

Due date on 2026-08-20, 23:59 IST

Q.

Understanding Private Access Modifier in Java


Problem Statement

In Java, members declared with the private access modifier cannot be accessed directly from outside the class.
To access private members, you must use methods within the same class, often called "getter" methods.

Task:

  • Create a class called Account

  • Declare a private integer variable balance

  • Create a public method getBalance() to return the balance

  • In the main method, create an object of Account, set a balance value, and print it using the method

This demonstrates how private members can be accessed safely using methods.

Complete Program

Java
import java.util.Scanner;
public class W04_P3 {
    // Declare class Account with a private member variable
    static class Account {
        private int balance; // Private member, cannot be accessed directly from outside
        // Method to set balance value
        public void setBalance(int b) {
            balance = b;
        }

        // --- START OF SOLUTION CODE ---
        public int getBalance() {
            return balance;
        }
        // --- END OF SOLUTION CODE ---

    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read balance value
        int b = sc.nextInt();
        // Create Account object
        Account acc = new Account();
        // Set balance using method
        acc.setBalance(b);
        // Print balance using the method
        System.out.println("Account Balance is: " + acc.getBalance());
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        public int getBalance() {
            return balance;
        }
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

5000

Account Balance is: 5000
Account Balance is: 5000\n
Presentation Error


W04 Programming Assignments 4

Due date on 2026-08-20, 23:59 IST

Q.

Understanding Protected Access Modifier in Java


Problem Statement

In Java, members declared with the protected access modifier are accessible:

  • Within the same class

  • Within subclasses (even if in different files or packages)

  • Within the same package

In beginner programs (single file), protected members behave similarly to default members, but understanding this modifier is important for object-oriented concepts.

Task:

  • Create a class called Employee with a protected variable salary

  • Create a subclass Manager that inherits from Employee

  • In the main method, create an object of Manager, assign a salary value, and print it

This

Complete Program

Java
import java.util.Scanner;
public class W04_P4 {
    // Declare parent class Employee with a protected member variable
    static class Employee {
        protected int salary; // Protected member
    }
    // Subclass Manager inherits from Employee
    static class Manager extends Employee {
        // No additional members required for this task
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read salary value
        int s = sc.nextInt();
        // Create Manager object
        Manager m = new Manager();

        // --- START OF SOLUTION CODE ---
        m.salary = s;
        System.out.println("Salary is: " + m.salary);
        // --- END OF SOLUTION CODE ---

        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        m.salary = s;
        System.out.println("Salary is: " + m.salary);
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

70000

Salary is: 70000
Salary is: 70000\n
Presentation Error


W04 Programming Assignments 5

Due date on 2026-08-20, 23:59 IST

Q.

Access Modifiers with Method Overloading


Problem Statement

In Java, Method Overloading means defining multiple methods with the same name but different parameters.
These methods can have different access modifiers like public, private, etc.

Task:

  • Create a class called Calculator

  • Overload the method add as follows:

    • A public method add that adds two integers

    • A private method add that adds three integers

  • In the main method, use the public method to add two numbers

  • Inside the class, use the private method to add three numbers and print both results

This shows how access modifiers work with method overloading.

Complete Program

Java
import java.util.Scanner;
public class W04_P5 {
    // Declare Calculator class with overloaded add methods
    static class Calculator {
        // Public method to add two integers
        public int add(int a, int b) {
            return a + b;
        }

        // --- START OF SOLUTION CODE ---
        private int add(int a, int b, int c) {
            return a + b + c;
        }
        // --- END OF SOLUTION CODE ---

        // Method to demonstrate private method access within class
        public void printThreeSum(int x, int y, int z) {
            int sum = add(x, y, z); // Call private method within class
            System.out.println("Sum of three numbers: " + sum);
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read two numbers
        int a = sc.nextInt();
        int b = sc.nextInt();
        // Read three numbers
        int x = sc.nextInt();
        int y = sc.nextInt();
        int z = sc.nextInt();
        Calculator calc = new Calculator();
        // Call public method to add two numbers
        int sumTwo = calc.add(a, b);
        System.out.println("Sum of two numbers: " + sumTwo);
        // Call method that prints sum of three numbers
        calc.printThreeSum(x, y, z);
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        private int add(int a, int b, int c) {
            return a + b + c;
        }
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

5 10 2 3 4

Sum of two numbers: 15\n
Sum of three numbers: 9
Sum of two numbers: 15\n
Sum of three numbers: 9\n
Presentation Error




W05 Programming Assignments 1

Due date on 2026-08-27, 23:59 IST

Your last recorded submission was on 2026-08-18, 19:02 IST.

Q.

An interface Number is defined in the following program.
You have to declare a class A, which will implement the interface Number.

Note that the method findSqr(n) will return the square of the number n.

Complete Program

Java
import java.util.Scanner;
interface Number {
    int findSqr(int i);  // Returns the square of n
}

// --- START OF SOLUTION CODE ---
class A implements Number {
    public int findSqr(int i) {
        return i * i;
    }
}
// --- END OF SOLUTION CODE ---

public class W05_P1{
        public static void main (String[] args){
                A a = new A();   //Create an object of class A
            // Read a number from the keyboard
            Scanner sc = new Scanner(System.in);
            int i = sc.nextInt();
            System.out.print(a.findSqr(i));
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
class A implements Number {
    public int findSqr(int i) {
        return i * i;
    }
}
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Private Test Cases

Private Test cases used for Evaluation
Status
Test Case 1
Passed


W05 Programming Assignments 2

Due date on 2026-08-27, 23:59 IST

Your last recorded submission was on 2026-08-18, 19:05 IST.

Q.

This program is to find the GCD (greatest common divisor) of two integers writing a recursive function findGCD(n1,n2).
Your function should return -1, if the argument(s) is(are) negative (zero is allowed).

Complete Program

Java
import java.util.Scanner;
interface GCD {
    public int findGCD(int n1,int n2);
}

// --- START OF SOLUTION CODE ---
class B implements GCD {
    public int findGCD(int n1, int n2) {
        if (n1 < 0 || n2 < 0) {
            return -1;
        }
        if (n1 == 0 && n2 == 0) {
            return 0;
        }
        else if (n2 == 0) {
            return n1;
        }
        else {
            return findGCD(n2, n1 % n2);
        }
    }
}
// --- END OF SOLUTION CODE ---

public class W05_P2{
        public static void main (String[] args){
           B a = new B();   //Create an object of class B
            // Read two numbers from the keyboard
            Scanner sc = new Scanner(System.in);
            int p1 = sc.nextInt();
           int p2 = sc.nextInt();
            System.out.print(a.findGCD(p1,p2));
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
class B implements GCD {
    public int findGCD(int n1, int n2) {
        if (n1 < 0 || n2 < 0) {
            return -1;
        }
        if (n1 == 0 && n2 == 0) {
            return 0;
        }
        else if (n2 == 0) {
            return n1;
        }
        else {
            return findGCD(n2, n1 % n2);
        }
    }
}
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 2/2 Passed

Note: These tests may not be considered while scoring.

Private Test Cases

Private Test cases used for Evaluation
Status
Test Case 1
Passed
Test Case 2
Passed


W05 Programming Assignments 3

Due date on 2026-08-27, 23:59 IST

Your last recorded submission was on 2026-08-18, 19:07 IST.

Q.

Complete the code segment to catch the ArithmeticException in the following, if any.
On the occurrence of such an exception, your program should print "Exception caught: Division by zero."
If there is no such exception, it will print the result of division operation on two integer values.

Complete Program

Java
import java.util.Scanner;
  public class W05_P3 {
  public static void main(String[] args) {
      int a, b;
      Scanner input = new Scanner(System.in);
       // Read any two values for a and b
       int result;
      a = input.nextInt();
      b = input.nextInt();

// --- START OF SOLUTION CODE ---
      try {
          result = a / b;
          System.out.print(result);
      } catch (ArithmeticException e) {
          System.out.print("Exception caught: Division by zero.");
      }
// --- END OF SOLUTION CODE ---

}
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
      try {
          result = a / b;
          System.out.print(result);
      } catch (ArithmeticException e) {
          System.out.print("Exception caught: Division by zero.");
      }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 2/2 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

4 5

0
0
-
Test Case 2

20 0

Exception caught: Division by zero.
Exception caught: Division by zero.
-


W05 Programming Assignments 4

Due date on 2026-08-27, 23:59 IST

Your last recorded submission was on 2026-08-18, 19:09 IST.

Q.

In the following program, an array of integer data to be initialized.
During the initialization, if a user enters a value other than integer value, then it will throw InputMismatchException exception.
On the occurrence of such an exception, your program should print "You entered bad data."
If there is no such exception it will print the total sum of the array.

Complete Program

Java
//Prefixed Fixed Code:
import java.util.Scanner;
import java.util.InputMismatchException;
public class W05_P4 {
  public static void main(String[] args) {
     Scanner sc = new Scanner(System.in);
    int length = sc.nextInt();
    // create an array to save user input
    int[] name = new int[length];
     int sum=0;//save the total sum of the array.

// --- START OF SOLUTION CODE ---
    try {
        for (int i = 0; i < length; i++) {
            name[i] = sc.nextInt();
            sum += name[i];
        }
        System.out.print(sum);
    } catch (InputMismatchException e) {
        System.out.print("You entered bad data.");
    }
// --- END OF SOLUTION CODE ---

}
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
    try {
        for (int i = 0; i < length; i++) {
            name[i] = sc.nextInt();
            sum += name[i];
        }
        System.out.print(sum);
    } catch (InputMismatchException e) {
        System.out.print("You entered bad data.");
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 2/2 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

3 5 2 1

8
8
-
Test Case 2

2 1 h

You entered bad data.
You entered bad data.
-


W05 Programming Assignments 5

Due date on 2026-08-27, 23:59 IST

Your last recorded submission was on 2026-08-18, 19:12 IST.

Q.

In the following program, there may be multiple exceptions.
You have to complete the code using only one try-catch block to handle all the possible exceptions.
For example, if user's input is 1, then it will throw and catch "java.lang.NullPointerException".

Complete Program

Java
import java.util.Scanner;
public class W05_P5{
     public static void main (String   args[ ] ) {
          Scanner scan = new Scanner(System.in);
         int i=scan.nextInt();
         int j;

// --- START OF SOLUTION CODE ---
        try {
            switch (i) {
                case 0 :
                    int zero = 0;
                    j = 92/ zero;
                    break;
                case 1:
                    int b[ ] = null;
                    j = b[0] ;
                    break;
                default:
                    System.out.print("No exception");
            }
        } catch (Exception e) {
            System.out.print(e);
        }
// --- END OF SOLUTION CODE ---

}
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        try {
            switch (i) {
                case 0 :
                    int zero = 0;
                    j = 92/ zero;
                    break;
                case 1:
                    int b[ ] = null;
                    j = b[0] ;
                    break;
                default:
                    System.out.print("No exception");
            }
        } catch (Exception e) {
            System.out.print(e);
        }
// --- END OF SOLUTION CODE ---


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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 3/3 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

5

No exception
No exception
-
Test Case 2

1

java.lang.NullPointerException
java.lang.NullPointerException
-
Test Case 3

0

java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
-


W06 Programming Assignments 1

Due date on 2026-09-03, 23:59 IST

Your last recorded submission was on 2026-08-24, 15:19 IST.

Q.

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.

Complete Program

Java
import java.util.Scanner;
public class W06_P1 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        // Use try-catch to handle possible run-time error
        try {
            // --- START OF SOLUTION CODE ---
            int result = num1 / num2;
            System.out.println("Result is: " + result);
            // --- END OF SOLUTION CODE ---
        } catch (ArithmeticException e) {
            // Print safe message if division by zero occurs
            System.out.println("Cannot divide by zero");
        }
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
            int result = num1 / num2;
            System.out.println("Result is: " + result);
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

10 0

Cannot divide by zero
Cannot divide by zero\n
Presentation Error


W06 Programming Assignments 2

Due date on 2026-09-03, 23:59 IST

Your last recorded submission was on 2026-08-24, 15:18 IST.

Q.

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.

Complete Program

Java
import java.util.Scanner;
public class W06_P2 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        // Outer try-catch block
        try {
// Inner try-catch block for division operation
            try {
                // --- START OF SOLUTION CODE ---
                int result = num1 / num2;
                System.out.println("Division successful");
                System.out.println("Result is: " + result);
                // --- END OF SOLUTION CODE ---
            } catch (ArithmeticException e) {
                System.out.println("Cannot divide by zero");
            }
        } catch (Exception e) {
            // Handles other unexpected errors
            System.out.println("An unexpected error occurred");
        }
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
                int result = num1 / num2;
                System.out.println("Division successful");
                System.out.println("Result is: " + result);
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

10 2

Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Presentation Error


W06 Programming Assignments 3

Due date on 2026-09-03, 23:59 IST

Your last recorded submission was on 2026-08-24, 15:14 IST.

Q.

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.

Complete Program

Java
import java.util.Scanner;
public class W06_P3 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        // Try block with multiple catch blocks
        try {
            // --- START OF SOLUTION CODE ---
            int result = num1 / num2;
            System.out.println("Division successful");
            System.out.println("Result is: " + result);
            // --- END OF SOLUTION CODE ---
        } catch (ArithmeticException e) {
            // Handles division by zero error
            System.out.println("Cannot divide by zero");
        } catch (Exception e) {
            // Handles other general errors
            System.out.println("An unexpected error occurred");
        }
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
            int result = num1 / num2;
            System.out.println("Division successful");
            System.out.println("Result is: " + result);
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

20 4

Division successful\n
Result is: 5
Division successful\n
Result is: 5\n
Presentation Error


W06 Programming Assignments 4

Due date on 2026-09-03, 23:59 IST

Your last recorded submission was on 2026-08-24, 15:15 IST.

Q.

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.

Complete Program

Java
import java.util.Scanner;
public class W06_P4 {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        // Read two integers
        int num1 = sc.nextInt();
        int num2 = sc.nextInt();
        // try-catch-finally structure
        try {
            // --- START OF SOLUTION CODE ---
            int result = num1 / num2;
            System.out.println("Result is: " + result);
            // --- END OF SOLUTION CODE ---
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        } finally {
            // Print final message, runs always
            System.out.println("Program Ended");
        }
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        int result = num1 / num2;
        System.out.println("Result is: " + result);
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

15 3

Result is: 5\n
Program Ended
Result is: 5\n
Program Ended\n
Presentation Error


W06 Programming Assignments 5

Due date on 2026-09-03, 23:59 IST

Your last recorded submission was on 2026-08-24, 15:16 IST.

Q.


Programming Assignment: Using throws in Exception Handling

Problem Statement

In Java, the throws keyword is used in a method signature to declare that the method might throw one or more exceptions. This mechanism allows the method to delegate error handling to the caller, requiring it to catch or handle the potential exception.

Programming Assignment:
  • Read a double value from the user.
  • Define a method calculateSquareRoot that accepts a double and declares that it throws Exception.
  • Inside this method, check if the input number is negative.
  • If negative, throw a new Exception with an appropriate error message.
  • If the number is valid, return its square root using Math.sqrt(num).
  • In the main method, call calculateSquareRoot inside a try-catch block to handle any thrown exceptions and display a suitable message.
This task demonstrates how to use the throws keyword to propagate exceptions and handle them in the calling method.

Complete Program

Java
import java.util.Scanner;
public class W06_P5 {
    // Method to calculate square root, may throw Exception
    public static double calculateSquareRoot(double num) throws Exception {
        // --- START OF SOLUTION CODE ---
        if (num < 0) {
            throw new Exception("Number cannot be negative");
        }
        return Math.sqrt(num);
        // --- END OF SOLUTION CODE ---
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        double number = sc.nextDouble();
        try {
            double result = calculateSquareRoot(number);
            System.out.println("Square root is: " + result);
        } catch (Exception e) {
            System.out.println("Cannot calculate square root of negative number");
        }
        sc.close();
    }
}

Code Snippet to Paste in the Editor

Java
// --- START OF SOLUTION CODE ---
        if (num < 0) {
            throw new Exception("Number cannot be negative");
        }
        return Math.sqrt(num);
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

16

Square root is: 4.0
Square root is: 4.0\n
Presentation Error


W07 Programming Assignments 1

Due date on 2026-09-10, 23:59 IST

Your last recorded submission was on 2026-09-01, 08:38 IST.

Q.

Write a Java program to find longest word in given input.

Complete Program

java
import java.util.Scanner;

public class W07_P1 {

    // --- START OF SOLUTION CODE ---
    public static String findLongestWord(String text) {
        String longestWord = "";
        String[] words = text.split("\\s+");
        for (String word : words) {
            if (word.length() > longestWord.length()) {
                longestWord = word;
            }
        }
        return longestWord;
    }
    // --- END OF SOLUTION CODE ---

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String text = scanner.nextLine();
        scanner.close();
        String longestWord = findLongestWord(text);
        System.out.println("The longest word in the text is: " + longestWord);
    }
}

Code Snippet to Paste in the Editor

java
// --- START OF SOLUTION CODE ---
    public static String findLongestWord(String text) {
        String longestWord = "";
        String[] words = text.split("\\s+");
        for (String word : words) {
            if (word.length() > longestWord.length()) {
                longestWord = word;
            }
        }
        return longestWord;
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

Believe in yourself

The longest word in the text is: yourself
The longest word in the text is: yourself\n
Presentation Error
W07 Programming Assignments 2

Due date on 2026-09-10, 23:59 IST

Your last recorded submission was on 2026-09-01, 08:42 IST.

Q.

Write a program to remove all occurrences of an element from array in Java.

Complete Program

java
import java.util.*;

public class W07_P2 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int n = scanner.nextInt();
        int[] array = new int[n];
        for (int i = 0; i < n; i++) {
            array[i] = scanner.nextInt();
        }
        int elementToRemove = scanner.nextInt();
        scanner.close();
        System.out.println("Original Array: " + Arrays.toString(array));
        array = removeAll(array, elementToRemove);
        System.out.print("Array after removing " + elementToRemove + ": " + Arrays.toString(array));
    }

    // --- START OF SOLUTION CODE ---
    public static int[] removeAll(int[] array, int elementToRemove) {
        int[] result = new int[array.length];
        int index = 0;
        for (int value : array) {
            if (value != elementToRemove) {
                result[index++] = value;
            }
        }
        return Arrays.copyOf(result, index);
    }
    // --- END OF SOLUTION CODE ---
}

Code Snippet to Paste in the Editor

java
// --- START OF SOLUTION CODE ---
    public static int[] removeAll(int[] array, int elementToRemove) {
        int[] result = new int[array.length];
        int index = 0;
        for (int value : array) {
            if (value != elementToRemove) {
                result[index++] = value;
            }
        }
        return Arrays.copyOf(result, index);
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

5 12 23 34 23 45 23

Original Array: [12, 23, 34, 23, 45]\n
Array after removing 23: [12, 34, 45]
Original Array: [12, 23, 34, 23, 45]\n
Array after removing 23: [12, 34, 45]
-
W07 Programming Assignments 3

Due date on 2026-09-10, 23:59 IST

Your last recorded submission was on 2026-09-01, 08:46 IST.

Q.

Write a program to compute the sum of all prime numbers in a given range.
The range value will be positive.
Follow the naming convention as given in the main method of the suffix code.

Complete Program

java
import java.util.Scanner;

public class W07_P3 {

    // --- START OF SOLUTION CODE ---
    public static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public static int primeSum(int x, int y) {
        int sum = 0;
        int start = Math.min(x, y);
        int end = Math.max(x, y);
        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                sum += i;
            }
        }
        return sum;
    }
    // --- END OF SOLUTION CODE ---

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        System.out.println(primeSum(x, y));
    }
}

Code Snippet to Paste in the Editor

java
// --- START OF SOLUTION CODE ---
    public static boolean isPrime(int n) {
        if (n < 2) return false;
        for (int i = 2; i * i <= n; i++) {
            if (n % i == 0) return false;
        }
        return true;
    }

    public static int primeSum(int x, int y) {
        int sum = 0;
        int start = Math.min(x, y);
        int end = Math.max(x, y);
        for (int i = start; i <= end; i++) {
            if (isPrime(i)) {
                sum += i;
            }
        }
        return sum;
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

4 13

36
36\n
Presentation Error
W07 Programming Assignments 4

Due date on 2026-09-10, 23:59 IST

Your last recorded submission was on 2026-09-01, 08:49 IST.

Q.

Code to create two threads, one printing even numbers and the other printing odd numbers.
  • The PrintNumbers class is declared, and it implements the Runnable interface. This interface is part of Java's concurrency support and is used to represent a task that can be executed concurrently by a thread.
  • Create a constructor of this class that takes two private instance variables (start and end) to represent the range of numbers that will be printed by the thread.
  • Create a run method that is required by the Runnable interface and contains the code that will be executed when the thread is started. In this case, it should print the numbers within the specified range (start to end) in steps of 2, using a for loop.
  • Hint: Thread.currentThread().getName() returns the name of the currently executing thread, which is useful for identifying which thread is printing the numbers.
  • Note: In the main method EvenThread is started and joined before OddThread is started, so the output order is always deterministic.
Follow the naming convention as given in the main method of the suffix code.

Complete Program

java
import java.util.Scanner;

class PrintNumbers implements Runnable {
    // --- START OF SOLUTION CODE ---
    private int start;
    private int end;

    public PrintNumbers(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        for (int i = start; i <= end; i += 2) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
    // --- END OF SOLUTION CODE ---
}

class W07_P4 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int evenStart = scanner.nextInt();
        int evenEnd = scanner.nextInt();
        int oddStart = scanner.nextInt();
        int oddEnd = scanner.nextInt();
        Thread evenThread = new Thread(new PrintNumbers(evenStart, evenEnd), "EvenThread");
        Thread oddThread = new Thread(new PrintNumbers(oddStart, oddEnd), "OddThread");
        try {
            evenThread.start();
            evenThread.join();
            oddThread.start();
            oddThread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        scanner.close();
    }
}

Code Snippet to Paste in the Editor

java
// --- START OF SOLUTION CODE ---
    private int start;
    private int end;

    public PrintNumbers(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    public void run() {
        for (int i = start; i <= end; i += 2) {
            System.out.println(Thread.currentThread().getName() + ": " + i);
        }
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

2 10 3 7

EvenThread: 2\n
EvenThread: 4\n
EvenThread: 6\n
EvenThread: 8\n
EvenThread: 10\n
OddThread: 3\n
OddThread: 5\n
OddThread: 7
EvenThread: 2\n
EvenThread: 4\n
EvenThread: 6\n
EvenThread: 8\n
EvenThread: 10\n
OddThread: 3\n
OddThread: 5\n
OddThread: 7\n
Presentation Error
W07 Programming Assignments 5

Due date on 2026-09-10, 23:59 IST

Your last recorded submission was on 2026-09-01, 08:56 IST.

Q.

Implement a Simple Password Validator
In this task, you need to implement a password validation system using Java. The goal is to check if a given password meets the following conditions:
  1. Minimum Length Requirement: The password must be at least 8 characters long.
  2. Uppercase Letter Requirement: The password must contain at least one uppercase letter (A-Z).
  3. Number Requirement: The password must contain at least one numeric digit (0-9).
If the password meets all three conditions, print "Valid Password". Otherwise, print "Invalid Password".
Input Format:
  • single string representing the password (can contain alphabets, numbers, and special characters).
Output Format:
  • Print "Valid Password" if the password satisfies all the conditions.
  • Otherwise, print "Invalid Password".
Example Input:
Password123

Example Output:
Valid Password

Complete Program

java
import java.util.Scanner;

public class W07_P5 {
    private String password;

    public W07_P5(String password) {
        this.password = password;
    }

    // --- START OF SOLUTION CODE ---
    public boolean isValidPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }
        boolean hasUpper = false;
        boolean hasDigit = false;

        for (int i = 0; i < password.length(); i++) {
            char ch = password.charAt(i);
            if (Character.isUpperCase(ch)) {
                hasUpper = true;
            }
            if (Character.isDigit(ch)) {
                hasDigit = true;
            }
        }
        return hasUpper && hasDigit;
    }

    public boolean isValidPassword() {
        return isValidPassword(this.password);
    }
    // --- END OF SOLUTION CODE ---

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String inputPassword = scanner.nextLine();
        scanner.close();
        W07_P5 validator = new W07_P5(inputPassword);
        if (validator.isValidPassword(inputPassword)) {
            System.out.print("Valid Password");
        } else {
            System.out.print("Invalid Password");
        }
    }
}

Code Snippet to Paste in the Editor

java
// --- START OF SOLUTION CODE ---
    public boolean isValidPassword(String password) {
        if (password == null || password.length() < 8) {
            return false;
        }
        boolean hasUpper = false;
        boolean hasDigit = false;

        for (int i = 0; i < password.length(); i++) {
            char ch = password.charAt(i);
            if (Character.isUpperCase(ch)) {
                hasUpper = true;
            }
            if (Character.isDigit(ch)) {
                hasDigit = true;
            }
        }
        return hasUpper && hasDigit;
    }

    public boolean isValidPassword() {
        return isValidPassword(this.password);
    }
// --- END OF SOLUTION CODE ---
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.

Evaluation Results

CompilationSuccessful|Public Test Cases: 1/1 Passed

Note: These tests may not be considered while scoring.

Public Test Cases

Test Case
Input
Expected Output
Output
Status
Test Case 1

Password123

Valid Password
Valid Password
-




































































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.