Write a program to display “This is my first java Program”
public class FirstProgram {
public static void main(String[] args) {
System.out.println("This is my first Java Program");
}
}
Write a program to add two numbers (2 and 6) and display its
sum,multiply.
public class AddMultiply {
public static void main(String[] args) {
// Define two numbers
int num1 = 2;
int num2 = 6;
// Perform addition
int sum = num1 + num2;
// Perform multiplication
int product = num1 * num2;
// Display the results
System.out.println("Sum of " + num1 + " and " + num2 + " is: " +
sum);
System.out.println("Product of " + num1 + " and " + num2 + " is: " +
product);
}
}
Program to implement conditional statements in Java language.
import java.util.Scanner;
public class ConditionalStatements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking an integer input from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Using if-else-if-else conditional statements
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
// Using switch-case to check if number is even or odd
System.out.println("Checking if the number is even or odd using
switch case.");
switch (number % 2) {
case 0:
System.out.println("The number is even.");
break;
case 1:
System.out.println("The number is odd.");
break;
default:
System.out.println("Error: Invalid number.");
break;
}
// Closing the scanner to avoid memory leaks
scanner.close();
}
}
Program to implement if-else ladder statement in Java language
import java.util.Scanner;
public class ConditionalStatements {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking an integer input from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Using if-else-if-else conditional statements
if (number > 0) {
System.out.println("The number is positive.");
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
// Using switch-case to check if number is even or odd
System.out.println("Checking if the number is even or odd using
switch case.");
switch (number % 2) {
case 0:
System.out.println("The number is even.");
break;
case 1:
case -1:
System.out.println("The number is odd.");
break;
default:
System.out.println("Error: Invalid number.");
break;
}
// Closing the scanner to avoid memory leaks
scanner.close();
}
}
Program to implement Nested if statement in java language
import java.util.Scanner;
public class NestedIfExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking an integer input from the user
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Outer if statement to check if the number is positive
if (number > 0) {
System.out.println("The number is positive.");
// Nested if statement to check if the number is even or odd
if (number % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
} else if (number < 0) {
System.out.println("The number is negative.");
} else {
System.out.println("The number is zero.");
}
// Closing the scanner to avoid memory leaks
scanner.close();
}
}
Program to implement switch-case statement in java language
import java.util.Scanner;
public class SwitchCaseExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking an integer input from the user
System.out.print("Enter a number between 1 and 7: ");
int day = scanner.nextInt();
// switch-case statement to determine the day of the week
switch (day) {
case 1:
System.out.println("Sunday");
break;
case 2:
System.out.println("Monday");
break;
case 3:
System.out.println("Tuesday");
break;
case 4:
System.out.println("Wednesday");
break;
case 5:
System.out.println("Thursday");
break;
case 6:
System.out.println("Friday");
break;
case 7:
System.out.println("Saturday");
break;
default:
System.out.println("Invalid input! Please enter a number between 1
and 7.");
break;
}
// Closing the scanner to avoid memory leaks
scanner.close();
}
}
Program to implement looping constructs in java language
public class LoopingConstructs {
public static void main(String[] args) {
// Using a for loop to print numbers from 1 to 5
System.out.println("Using for loop:");
for (int i = 1; i <= 5; i++) {
System.out.println(i);
}
// Using a while loop to print numbers from 1 to 5
System.out.println("Using while loop:");
int j = 1;
while (j <= 5) {
System.out.println(j);
j++;
}
// Using a do-while loop to print numbers from 1 to 5
System.out.println("Using do-while loop:");
int k = 1;
do {
System.out.println(k);
k++;
} while (k <= 5);
}
}
Write a C program to check given number is maximum of 2
numbers and 3 numbers
#include <stdio.h>
int main() {
int num1, num2, num3;
// Taking input for two numbers
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Checking maximum of two numbers
if (num1 > num2) {
printf("Maximum of %d and %d is: %d\n", num1, num2, num1);
} else {
printf("Maximum of %d and %d is: %d\n", num1, num2, num2);
}
// Taking input for three numbers
printf("Enter three numbers: ");
scanf("%d %d %d", &num1, &num2, &num3);
// Checking maximum of three numbers
if (num1 > num2 && num1 > num3) {
printf("Maximum of %d, %d and %d is: %d\n", num1, num2,
num3, num1);
} else if (num2 > num1 && num2 > num3) {
printf("Maximum of %d, %d and %d is: %d\n", num1, num2,
num3, num2);
} else {
printf("Maximum of %d, %d and %d is: %d\n", num1, num2,
num3, num3);
}
return 0;
}
Write a program to sum of first n number ,given n number
import java.util.Scanner;
public class SumOfFirstN {
public static void main(String[] args) {
// Creating a Scanner object to take input
Scanner scanner = new Scanner(System.in);
// Taking input from the user
System.out.print("Enter a positive integer: ");
int n = scanner.nextInt();
// Variable to store the sum
int sum = 0;
// Checking if n is positive
if (n <= 0) {
System.out.println("Please enter a positive integer
greater than 0.");
} else {
// Calculating the sum of the first n numbers
for (int i = 1; i <= n; i++) {
sum += i;
}
// Displaying the result
System.out.println("The sum of the first " + n + "
natural numbers is: " + sum);
}
// Closing the scanner
scanner.close();
}
Write a program to Digit reversing ,Table generat
import java.util.Scanner;
public class DigitReversingTableGeneration {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Part 1: Digit Reversing
System.out.print("Enter a number to reverse its digits: ");
int number = scanner.nextInt();
int reversed = 0;
int temp = number;
while (temp != 0) {
int digit = temp % 10; // Extract the last digit
reversed = reversed * 10 + digit; // Append the digit to
reversed number
temp /= 10; // Remove the last digit from the number
}
System.out.println("Reversed number: " + reversed);
// Part 2: Table Generation
System.out.print("Enter a number to generate its
multiplication table: ");
int tableNumber = scanner.nextInt();
System.out.println("Multiplication table for " +
tableNumber + ":");
for (int i = 1; i <= 10; i++) {
System.out.println(tableNumber + " x " + i + " = " +
(tableNumber * i));
}
// Closing the scanner
scanner.close();
}
}
Write a program to find Factorial ,Swapping
import java.util.Scanner;
public class FactorialAndSwapping {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Part 1: Factorial Calculation
System.out.print("Enter a non-negative integer to find its factorial:
");
int number = scanner.nextInt();
// Check for non-negative input
if (number < 0) {
System.out.println("Factorial is not defined for negative
numbers.");
} else {
long factorial = 1;
for (int i = 1; i <= number; i++) {
factorial *= i; // Calculating factorial
}
System.out.println("Factorial of " + number + " is: " + factorial);
}
// Part 2: Swapping Two Numbers
System.out.print("Enter the first number: ");
int firstNumber = scanner.nextInt();
System.out.print("Enter the second number: ");
int secondNumber = scanner.nextInt();
// Swapping using a temporary variable
System.out.println("Before swapping: firstNumber = " +
firstNumber + ", secondNumber = " + secondNumber);
int temp = firstNumber; // Store firstNumber in temp
firstNumber = secondNumber; // Assign secondNumber to
firstNumber
secondNumber = temp; // Assign temp (original firstNumber) to
secondNumber
System.out.println("After swapping: firstNumber = " + firstNumber
+ ", secondNumber = " + secondNumber);
// Closing the scanner
scanner.close();
}
}
Write a program to print nCr series
import java.util.Scanner;
public class NCRSeries {
// Function to calculate factorial
public static long factorial(int num) {
long fact = 1;
for (int i = 2; i <= num; i++) {
fact *= i;
}
return fact;
}
// Function to calculate nCr
public static long nCr(int n, int r) {
if (r > n) {
return 0; // nCr is 0 if r > n
}
return factorial(n) / (factorial(r) * factorial(n - r));
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Taking input for n
System.out.print("Enter the value of n: ");
int n = scanner.nextInt();
// Printing nCr for all r from 0 to n
System.out.println("nCr series for n = " + n + ":");
for (int r = 0; r <= n; r++) {
System.out.println("C(" + n + ", " + r + ") = " + nCr(n, r));
}
// Closing the scanner
scanner.close();
}
}
Write a Java program to input 5 numbers into an array, and then find
and display the largest number.
import java.util.Scanner;
public class LargestNumberInArray {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Create an array to hold 5 numbers
int[] numbers = new int[5];
// Input: Taking 5 numbers from the user
System.out.println("Enter 5 numbers:");
for (int i = 0; i < 5; i++) {
System.out.print("Number " + (i + 1) + ": ");
numbers[i] = scanner.nextInt();
}
// Finding the largest number
int largest = numbers[0]; // Assume the first number is the largest
initially
for (int i = 1; i < numbers.length; i++) {
if (numbers[i] > largest) {
largest = numbers[i]; // Update largest if current number is
greater
}
}
// Output: Display the largest number
System.out.println("The largest number is: " + largest);
// Closing the scanner
scanner.close();
}
}
Write a Java program that takes a string as input, reverses it, and
checks if it is a palindrome (a word that reads the same forwards and
backwards).
import java.util.Scanner;
public class PalindromeChecker {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input: Take a string from the user
System.out.print("Enter a string: ");
String original = scanner.nextLine();
// Remove spaces and convert to lowercase for uniform comparison
String formattedString = original.replaceAll("\\s+",
"").toLowerCase();
// Reverse the string
String reversed = new
StringBuilder(formattedString).reverse().toString();
// Check if the original (formatted) string is equal to the reversed
string
if (formattedString.equals(reversed)) {
System.out.println("\"" + original + "\" is a palindrome.");
} else {
System.out.println("\"" + original + "\" is not a palindrome.");
}
// Closing the scanner
scanner.close();
}
}
Create a class Person with an attribute name. Then, create another
class Employee that inherits from Person and adds an id attribute.
Write a program to display the name and ID of the employee.
// Person class
class Person {
// Attribute
protected String name;
// Constructor
public Person(String name) {
this.name = name;
}
// Method to get name
public String getName() {
return name;
}
}
// Employee class that inherits from Person
class Employee extends Person {
// Attribute
private int id;
// Constructor
public Employee(String name, int id) {
super(name); // Call the constructor of Person
this.id = id;
}
// Method to get ID
public int getId() {
return id;
}
}
// Main class to execute the program
public class Main {
public static void main(String[] args) {
// Creating an Employee object
Employee employee = new Employee("Alice", 101);
// Displaying name and ID of the employee
System.out.println("Employee Name: " +
employee.getName());
System.out.println("Employee ID: " + employee.getId());
}
}
Write a Java program to perform division of two numbers, and handle
the ArithmeticException in case of division by zero.
import java.util.Scanner;
public class DivisionWithExceptionHandling {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
// Input: Take two numbers from the user
System.out.print("Enter the numerator: ");
int numerator = scanner.nextInt();
System.out.print("Enter the denominator: ");
int denominator = scanner.nextInt();
// Performing division
int result = numerator / denominator;
// Output: Display the result
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
// Handling division by zero
System.out.println("Error: Division by zero is not
allowed.");
} catch (Exception e) {
// Handling any other potential exceptions
System.out.println("An error occurred: " +
e.getMessage());
} finally {
// Closing the scanner
scanner.close();
}
}
}
Write a Java program to create two threads: one that prints even
numbers from 1 to 10 and another that prints odd numbers from 1 to
10.
// Class for printing even numbers
class EvenNumbers extends Thread {
@Override
public void run() {
System.out.println("Even Numbers:");
for (int i = 1; i <= 10; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
}
// Class for printing odd numbers
class OddNumbers extends Thread {
@Override
public void run() {
System.out.println("Odd Numbers:");
for (int i = 1; i <= 10; i++) {
if (i % 2 != 0) {
System.out.println(i);
}
}
}
}
// Main class to execute the program
public class EvenOddThreads {
public static void main(String[] args) {
// Creating instances of the thread classes
Thread evenThread = new EvenNumbers();
Thread oddThread = new OddNumbers();
// Starting the threads
evenThread.start();
oddThread.start();
// Optional: Wait for both threads to finish
try {
evenThread.join();
oddThread.join();
} catch (InterruptedException e) {
System.out.println("Thread interrupted: " +
e.getMessage());
}
System.out.println("Both threads have finished
execution.");
}
}
Create an HTML page with a heading, a paragraph, and an image.
Include a comment in the code to explain each section.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>My Sample HTML Page</title>
<!-- The title of the HTML document that appears in the browser tab --
>
</head>
<body>
<!-- This is the main heading of the page -->
<h1>Welcome to My Sample Page</h1>
<!-- This paragraph provides a brief description or information -->
<p>This page is an example of a simple HTML structure. It includes a
heading, a paragraph for content, and an image to enhance the visual
appeal.</p>
<!-- This section displays an image -->
<img src="https://via.placeholder.com/300" alt="Placeholder Image"
width="300" height="200">
<!-- The 'src' attribute specifies the image source URL, 'alt' provides
alternative text for the image,
and 'width' and 'height' specify the dimensions of the image -->
</body>
</html>
Design an HTML form that takes the user's name and email as input.
Include a "Submit" button that sends the data to the server.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-
scale=1.0">
<title>User Information Form</title>
<!-- The title of the HTML document that appears in the browser tab --
>
</head>
<body>
<h1>User Information Form</h1>
<!-- Heading for the form -->
<form action="/submit" method="POST">
<!-- Form element to collect user input -->
<!-- 'action' specifies where to send the form data when submitted -
->
<!-- 'method' specifies how to send the data (GET or POST) -->
<label for="name">Name:</label>
<!-- Label for the name input -->
<input type="text" id="name" name="name" required>
<!-- Text input for the user's name; 'required' ensures this field must
be filled -->
<br><br>
<label for="email">Email:</label>
<!-- Label for the email input -->
<input type="email" id="email" name="email" required>
<!-- Email input for the user's email; 'required' ensures this field
must be filled -->
<br><br>
<button type="submit">Submit</button>
<!-- Submit button to send the form data to the server -->
</form>
</body>
</html>
Write a Java servlet that responds to an HTTP GET request and displays
the message "Welcome to Java Servlet" in the browser.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
// Define the servlet and map it to a URL pattern
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
// Handle GET requests
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Set the response content type
response.setContentType("text/html");
// Get the output stream to write the response
PrintWriter out = response.getWriter();
// Write the response message
out.println("<html><body>");
out.println("<h1>Welcome to Java Servlet</h1>");
out.println("</body></html>");
// Close the PrintWriter
out.close();
}
}
//xml page
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>your.package.name.WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Create a JSP page that takes a user’s name as input and displays a
personalized greeting like "Hello, [name]!" when the form is
submitted.
<%@ page contentType="text/html;charset=UTF-8"
language="java" %>
<%@ page import="java.io.*" %>
<%@ page import="javax.servlet.*" %>
<%@ page import="javax.servlet.http.*" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,
initial-scale=1.0">
<title>Personalized Greeting</title>
</head>
<body>
<%
// Check if the form has been submitted
String name = request.getParameter("name");
if (name != null && !name.trim().isEmpty()) {
%>
<!-- Display personalized greeting -->
<h1>Hello, <%= name %>!</h1>
<%
} else {
%>
<!-- Display the form for user input -->
<h1>Enter Your Name</h1>
<form action="" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<button type="submit">Submit</button>
</form>
<%
}
%>
</body>
</html>