0% found this document useful (0 votes)
2 views

Java2 Assignment (1)

The document contains a Java assignment with ten tasks that involve writing programs for various functionalities such as validating strings, email addresses, and URLs using regular expressions, handling exceptions, and performing file operations. Each task includes sample code demonstrating the required functionality and error handling. The assignment emphasizes the use of Java programming concepts including regex, exception handling, and input validation.

Uploaded by

Death Slime
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Java2 Assignment (1)

The document contains a Java assignment with ten tasks that involve writing programs for various functionalities such as validating strings, email addresses, and URLs using regular expressions, handling exceptions, and performing file operations. Each task includes sample code demonstrating the required functionality and error handling. The assignment emphasizes the use of Java programming concepts including regex, exception handling, and input validation.

Uploaded by

Death Slime
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 18

Java Assignment

1. Write a program that takes a string input and checks if it contains only digits using a
regular expression.

package Assignment02;

import java.util.Scanner;

public class DigitValidator {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter a string: ");


String input = sc.nextLine();

if (input.matches("\\d+")) {

System.out.println("String contains only digits.");

} else {
System.out.println("String does not contain only digits.");

sc.close();
}

}
Output:

2. Ask the user to input an email address and use regex to validate if it follows a standard
format (e.g., [email protected]).

package Assignment02;

import java.util.Scanner;
public class EmailChecker {

public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter email address: ");

String email = sc.nextLine();

if (email.matches("^[\\w.-]+@[\\w.-]+\\.[a-zA-Z]{2,6}$")) {

System.out.println("Valid email format.");

} else {

System.out.println("Invalid email format.");


}

sc.close();
}

Output:
3. Define a custom exception called ‘InvalidInputException’ and throw it when a user
enters a negative number.
package Assignment02;

import java.util.Scanner;
class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter a positive number: ");
int number = sc.nextInt();

if (number < 0) {
throw new InvalidInputException("Negative numbers are not allowed.");
} else {
System.out.println("You entered: " + number);
}

} catch (InvalidInputException e) {
System.out.println("Custom Exception caught: " + e.getMessage());
} catch (Exception e) {
System.out.println("General Exception caught: Please enter a valid number.");
} finally {
sc.close();
}
}
}
Output:
4. Write a program that performs a file operation inside a try-catch-finally block,
ensuring a message is printed from the finally block
package Assignment02;

import java.io.*;
public class FileOperationExample {
public static void main(String[] args) {
FileReader fr = null;
try {
fr = new FileReader("a.txt");
int ch;
while ((ch = fr.read()) != -1) {
System.out.print((char) ch);
}
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
} finally {
System.out.println("\nThis message is from the finally block.");
try {
if (fr != null) fr.close();
} catch (IOException e) {
System.out.println("Failed to close file.");
}
}
}
}
Output:

5. Create a Java program that checks if a given input string is a valid URL (http or https)
using regex.
package Assignment02;

import java.util.Scanner;
public class URLValidator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a URL: ");
String url = sc.nextLine();
if (url.matches("^(https?://)?[\\w.-]+\\.[a-zA-Z]{2,6}(/\\S*)?$")) {
System.out.println("Valid URL.");
} else {
System.out.println("Invalid URL.");
}
sc.close();

}
Output:
6. Use Pattern and Matcher classes to find all occurrences of the word "Java" in a
paragraph and count how many times it appears.
package Assignment02;

import java.util.regex.*;
import java.util.Scanner;
public class WordMatcher {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter a paragraph:");
String text = sc.nextLine();
Pattern pattern = Pattern.compile("\\bJava\\b");
Matcher matcher = pattern.matcher(text);
int count = 0;
while (matcher.find()) {
count++;
}
System.out.println("The word 'Java' appears " + count + " times.");
sc.close();
}
}

Output:
7. Write a program that opens a file and reads content line by line.
Handle FileNotFoundException and IOException.
package Assignment02;

import java.io.*;
public class ReadFileWithException {
public static void main(String[] args) {
BufferedReader br = null;
try {
FileReader fr = new FileReader("a.txt");
br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println("Error reading file.");
} finally {
try {
if (br != null) br.close();
} catch (IOException e) {
System.out.println("Error closing file.");
}
}
}
}

Output:

8. Write a method that reads an integer from the user and


handles InputMismatchException when the input is not a valid integer
package Assignment02;
import java.util.InputMismatchException;
import java.util.Scanner;

public class InputValidator {


public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
try {
System.out.print("Enter an integer: ");
int num = sc.nextInt();
System.out.println("You entered: " + num);
} catch (InputMismatchException e) {
System.out.println("Invalid input! Please enter a valid integer.");
}
sc.close();
}
}

Output:
9. Write a Java program that validates a password using regex. The password must:

• Be at least 8 characters long.


• Contain at least one uppercase letter.
• Contain at least one lowercase letter.
• Contain at least one digit.
• Contain at least one special character.
package Assignment02;

import java.util.Scanner;

public class PasswordValidator {

public static void main(String[] args) {


Scanner sc = new Scanner(System.in);

System.out.print("Enter password: ");


String password = sc.nextLine();
String regex = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@#$%^&+=!]).{8,15}$";

if (password.matches(regex)) {
System.out.println("Strong password.");
} else {
System.out.println("Weak password. It must:");
System.out.println("- Be 8 to 15 characters long");
System.out.println("- Contain at least one uppercase letter");
System.out.println("- Contain at least one lowercase letter");
System.out.println("- Contain at least one digit");
System.out.println("- Contain at least one special character (@#$%^&+=!)");
}

sc.close();
}
}
Output:
10. Create a program with three methods: A calls B, B calls C. Method C throws an
exception. Demonstrate how to propagate the exception from method C to A using
the throws keyword and handle it in method A.
package Assignment02;

public class ExceptionPropagation {

public static void methodC() throws Exception {


throw new Exception("Exception thrown in methodC");
}

public static void methodB() throws Exception {


methodC();
}

public static void methodA() {


try {
methodB();
} catch (Exception e) {
System.out.println("Caught in methodA: " + e.getMessage());
}
}

public static void main(String[] args) {


methodA();
}
}

Output:

You might also like