import java.util.Scanner;
class Rectangle {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter length: ");
double length = sc.nextDouble();
System.out.print("Enter breadth: ");
double breadth = sc.nextDouble();
System.out.println("Area: " + (length * breadth));
System.out.println("Perimeter: " + (2 * (length + breadth)));
}
}
import java.util.Scanner;
class SimpleInterest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = sc.nextDouble();
System.out.print("Enter rate of interest: ");
double rate = sc.nextDouble();
System.out.print("Enter time (in years): ");
double time = sc.nextDouble();
double interest = (principal * rate * time) / 100;
double totalAmount = principal + interest;
System.out.println("Simple Interest: " + interest);
System.out.println("Total Amount: " + totalAmount);
}
}
import java.util.Scanner;
class TemperatureConversion {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter temperature in Fahrenheit: ");
double fahrenheit = sc.nextDouble();
double celsius = (fahrenheit - 32) * 5 / 9;
System.out.println("Temperature in Celsius: " + celsius);
}
}
import java.util.Scanner;
class SwapNumbers {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.println("Before Swap: num1 = " + num1 + ", num2 = " + num2);
num1 = num1 + num2;
num2 = num1 - num2;
num1 = num1 - num2;
System.out.println("After Swap: num1 = " + num1 + ", num2 = " + num2);
}
}
import java.util.Scanner;
class GreatestNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter first number: ");
int num1 = sc.nextInt();
System.out.print("Enter second number: ");
int num2 = sc.nextInt();
System.out.print("Enter third number: ");
int num3 = sc.nextInt();
if (num1 >= num2 && num1 >= num3) {
System.out.println("The greatest number is: " + num1);
} else if (num2 >= num1 && num2 >= num3) {
System.out.println("The greatest number is: " + num2);
} else {
System.out.println("The greatest number is: " + num3);
}
}
}
import java.util.Scanner;
class EvenOddCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
if (num % 2 == 0) {
System.out.println("The number is even.");
} else {
System.out.println("The number is odd.");
}
}
}
import java.util.Scanner;
class LeapYearCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = sc.nextInt();
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println("The year is a leap year.");
} else {
System.out.println("The year is not a leap year.");
}
}
}
import java.util.Scanner;
class SumOfDigits {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int sum = 0;
while (num != 0) {
sum += num % 10;
num /= 10;
}
System.out.println("The sum of digits is: " + sum);
}
}
import java.util.Scanner;
class Factorial {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int factorial = 1;
for (int i = 1; i <= num; i++) {
factorial *= i;
}
System.out.println("The factorial is: " + factorial);
}
}
import java.util.Scanner;
class ReverseNumber {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int reverse = 0;
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
System.out.println("The reversed number is: " + reverse);
}
}
import java.util.Scanner;
class PalindromeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int original = num;
int reverse = 0;
while (num != 0) {
reverse = reverse * 10 + num % 10;
num /= 10;
}
if (original == reverse) {
System.out.println("The number is a palindrome.");
} else {
System.out.println("The number is not a palindrome.");
}
}
}
import java.util.Scanner;
class ArmstrongCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
int original = num;
int sum = 0;
while (num != 0) {
int digit = num % 10;
sum += digit * digit * digit;
num /= 10;
}
if (original == sum) {
System.out.println("The number is an Armstrong number.");
} else {
System.out.println("The number is not an Armstrong number.");
}
}
}
import java.util.Scanner;
class PrimeCheck {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number: ");
int num = sc.nextInt();
boolean isPrime = true;
if (num <= 1) {
isPrime = false;
} else {
for (int i = 2; i <= Math.sqrt(num); i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}
}
if (isPrime) {
System.out.println("The number is prime.");
} else {
System.out.println("The number is not prime.");
}
}
}
import java.util.Scanner;
class FibonacciSeries {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the number of terms: ");
int n = sc.nextInt();
int a = 0, b = 1;
System.out.print("Fibonacci series: " + a + ", " + b);
for (int i = 2; i < n; i++) {
int next = a + b;
System.out.print(", " + next);
a = b;
b = next;
}
System.out.println();
}
}
import java.util.Scanner;
class SumAndAverage {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers:");
int sum = 0;
for (int i = 0; i < 10; i++) {
numbers[i] = sc.nextInt();
sum += numbers[i];
}
double average = sum / 10.0;
System.out.println("Sum: " + sum);
System.out.println("Average: " + average);
}
}
import java.util.Scanner;
class BubbleSort {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[] numbers = new int[10];
System.out.println("Enter 10 numbers:");
for (int i = 0; i < 10; i++) {
numbers[i] = sc.nextInt();
}
for (int i = 0; i < numbers.length - 1; i++) {
for (int j = 0; j < numbers.length - 1 - i; j++) {
if (numbers[j] > numbers[j + 1]) {
int temp = numbers[j];
numbers[j] = numbers[j + 1];
numbers[j + 1] = temp;
}
}
}
System.out.println("Sorted numbers in ascending order:");
for (int num : numbers) {
System.out.print(num + " ");
}
System.out.println();
}
}
import java.util.Scanner;
class LinearSearch {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter the size of the array: ");
int n = sc.nextInt();
int[] array = new int[n];
System.out.println("Enter " + n + " sorted elements:");
for (int i = 0; i < n; i++) {
array[i] = sc.nextInt();
}
System.out.print("Enter the element to search: ");
int target = sc.nextInt();
boolean found = false;
for (int i = 0; i < n; i++) {
if (array[i] == target) {
System.out.println("Element found at index " + i);
found = true;
break;
}
}
if (!found) {
System.out.println("Element not found in the array.");
}
}
}
import java.util.Scanner;
class MatrixAddition {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] matrix1 = new int[2][2];
int[][] matrix2 = new int[2][2];
int[][] sum = new int[2][2];
System.out.println("Enter elements of first 2x2 matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix1[i][j] = sc.nextInt();
}
}
System.out.println("Enter elements of second 2x2 matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix2[i][j] = sc.nextInt();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
sum[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
System.out.println("Sum of the matrices:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(sum[i][j] + " ");
}
System.out.println();
}
}
}
import java.util.Scanner;
class MatrixMultiplication {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int[][] matrix1 = new int[2][2];
int[][] matrix2 = new int[2][2];
int[][] product = new int[2][2];
System.out.println("Enter elements of first 2x2 matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix1[i][j] = sc.nextInt();
}
}
System.out.println("Enter elements of second 2x2 matrix:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
matrix2[i][j] = sc.nextInt();
}
}
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
product[i][j] = 0;
for (int k = 0; k < 2; k++) {
product[i][j] += matrix1[i][k] * matrix2[k][j];
}
}
}
System.out.println("Product of the matrices:");
for (int i = 0; i < 2; i++) {
for (int j = 0; j < 2; j++) {
System.out.print(product[i][j] + " ");
}
System.out.println();
}
}
}
class Student {
String name;
int age;
void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
}
public static void main(String[] args) {
Student student = new Student();
student.name = "John";
student.age = 20;
student.displayInfo();
}
}
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
public static void main(String[] args) {
Calculator calc = new Calculator();
System.out.println("Sum (int): " + calc.add(10, 20));
System.out.println("Sum (double): " + calc.add(5.5, 4.5));
}
}
class Rectangle {
int length, breadth;
Rectangle() {
length = 0;
breadth = 0;
}
Rectangle(int l, int b) {
length = l;
breadth = b;
}
int area() {
return length * breadth;
}
public static void main(String[] args) {
Rectangle rect1 = new Rectangle();
Rectangle rect2 = new Rectangle(5, 10);
System.out.println("Default area: " + rect1.area());
System.out.println("Parameterized area: " + rect2.area());
}
}
class Animal {
void sound() {
System.out.println("Animals make sound");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Dogs bark");
}
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e);
}
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
int[] arr = new int[2];
arr[3] = 10; // This will throw an ArrayIndexOutOfBoundsException
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: " + e);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error: " + e);
}
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Error: " + e);
}
try {
String str = null;
System.out.println(str.length()); // This will throw a NullPointerException
} catch (Exception e) {
System.out.println("Error: " + e);
}
}
}
public class ExceptionDemo {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Arithmetic Error: " + e);
}
try {
int[] arr = new int[2];
arr[3] = 10; // This will throw an ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index Error: " + e);
}
}
}
// Interface
interface Animal {
void sound(); // Abstract method
void sleep(); // Abstract method
}
// Concrete class implementing the interface
class Dog implements Animal {
@Override
public void sound() {
System.out.println("Woof Woof");
}
@Override
public void sleep() {
System.out.println("Dog is sleeping.");
}
}
class Cat implements Animal {
@Override
public void sound() {
System.out.println("Meow");
}
@Override
public void sleep() {
System.out.println("Cat is sleeping.");
}
}
public class InterfaceDemo {
public static void main(String[] args) {
Animal dog = new Dog();
dog.sound();
dog.sleep();
Animal cat = new Cat();
cat.sound();
cat.sleep();
}
}
// In package animals
package animals;
public class Dog {
public void sound() {
System.out.println("Woof Woof");
}
}
// In package test
package test;
import animals.Dog;
public class PackageDemo {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}
// Extending Thread class
class MyThread extends Thread {
@Override
public void run() {
for (int i = 1; i <= 5; i++) {
try {
Thread.sleep(1000);
System.out.println(Thread.currentThread().getId() + " Value " + i);
} catch (InterruptedException e) {
System.out.println(e);
}
}
}
}
public class MultiThreadingDemo {
public static void main(String[] args) {
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
thread1.start(); // Start thread1
thread2.start(); // Start thread2
}
}
import java.sql.*;
public class OracleJDBCExample {
public static void main(String[] args) {
try {
// Load the Oracle Type 2 driver (OCI driver)
// The Oracle OCI driver uses the Oracle Client libraries to connect to the Oracle DB
Class.forName("oracle.jdbc.OracleDriver");
System.out.println("Driver Loaded Successfully!");
// Establish a connection using Type 2 driver (OCI)
// You must have the Oracle client (OCI) installed and configured
Connection conn = DriverManager.getConnection(
"jdbc:oracle:oci8:@localhost:1521:orcl", // JDBC URL for OCI driver
"username", // Replace with your Oracle username
"password" // Replace with your Oracle password
);
System.out.println("Connection Established Successfully!");
// Create a statement
Statement stmt = conn.createStatement();
// Execute a query
String query = "SELECT id, Name FROM students"; // SQL query to retrieve student data
ResultSet rs = stmt.executeQuery(query);
// Process the result set
while (rs.next()) {
System.out.println("ID = " + rs.getInt("id") + ", Name = " + rs.getString("Name"));
}
// Close resources
rs.close();
stmt.close();
conn.close();
System.out.println("Connection Closed Successfully!");
} catch (Exception e) {
System.out.println("Something went wrong: " + e.getMessage());
}
}
}
Part 1: JSP (Login Page) login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*, javax.servlet.*, javax.servlet.http.*" %>
<html>
<head>
<title>Login Page</title>
</head>
<body>
<h2>Login Form</h2>
<form action="LoginServlet" method="post">
<label for="username">Username:</label><br>
<input type="text" id="username" name="username" required><br><br>
<label for="password">Password:</label><br>
<input type="password" id="password" name="password" required><br><br>
<button type="submit">Login</button>
</form>
</body>
</html>
Part 2: Servlet (Backend Logic) LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Set response content type
response.setContentType("text/html");
// Get the user input from the login form
String username = request.getParameter("username");
String password = request.getParameter("password");
// Logic to validate the credentials (For simplicity, using hardcoded values)
PrintWriter out = response.getWriter();
if ("admin".equals(username) && "password123".equals(password)) {
// If valid, redirect to a welcome page
out.println("Welcome, " + username + "!
");
out.println("You have logged in successfully.
");
} else {
// If invalid, send an error message
out.println("Invalid login credentials.
");
out.println("");
}
}
}
Using Servlet
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class UserServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
// Connect to the database
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"root", "password");
// Fetch the first 5 users
String query = "SELECT id, username, password FROM users LIMIT 5";
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
// Start HTML output
out.println("<html><body>");
out.println("<h2>User Details</h2>");
out.println("<table border='1'><tr><th>ID</th><th>Username</th><th>Password</th></tr>");
// Loop through the result set and display data in a table
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("username") + "</td>");
out.println("<td>" + rs.getString("password") + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("</body></html>");
// Close resources
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
out.println("Error: " + e.getMessage());
}
}
}
Using JSP
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@ page import="java.sql.*, java.util.*" %>
<html>
<head>
<title>User Details</title>
<style>
table {
width: 50%;
margin: 50px auto;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border: 1px solid #ddd;
}
th {
background-color: #f2f2f2;
}
</style>
</head>
<body>
<h2 style="text-align: center;">User Details</h2>
<table>
<thead>
<tr>
<th>ID</th>
<th>Username</th>
<th>Password</th>
</tr>
</thead>
<tbody>
<%
// Establish the database connection using the utility class
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = DBConnection.getConnection(); // Use the DBConnection class
stmt = conn.createStatement();
// Query to fetch first 5 users from the database
String query = "SELECT id, username, password FROM users LIMIT 5";
rs = stmt.executeQuery(query);
// Loop through the result set and display user data in the table
while (rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getInt("id") + "</td>");
out.println("<td>" + rs.getString("username") + "</td>");
out.println("<td>" + rs.getString("password") + "</td>");
out.println("</tr>");
}
} catch (SQLException e) {
out.println("<tr><td colspan='3'>Error: " + e.getMessage() + "</td></tr>");
} finally {
// Close the database resources
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
out.println("<tr><td colspan='3'>Error closing resources: " +
e.getMessage() + "</td></tr>");
}
}
%>
</tbody>
</table>
</body>
</html>
Servlet: CookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.text.*;
public class CookieServlet extends HttpServlet {
private static final String LOG_FILE_PATH = "C:/logs/application.log";
// Change this path based on your system
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// Create a new cookie
String userId = UUID.randomUUID().toString(); // Generate a unique user ID
Cookie userCookie = new Cookie("userID", userId);
userCookie.setMaxAge(60 * 60); // Set cookie expiration to 1 hour
response.addCookie(userCookie);
// Log the request information
logRequestToFile(request);
out.println("<html>");
out.println("<body>");
out.println("<h2>Cookie Created Successfully!</h2>");
out.println("<p>Your unique user ID (Cookie): " + userId + "</p>");
out.println("<p><a href='log.jsp'>Click here to view the log file</a></p>");
out.println("</body>");
out.println("</html>");
}
// Method to log request information into a log file
private void logRequestToFile(HttpServletRequest request) {
try {
PrintWriter logWriter = new PrintWriter(new FileWriter(LOG_FILE_PATH, true)); // Append mode
String timestamp = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
String logMessage = timestamp + " - Access from IP: " + request.getRemoteAddr()
+ " with User-Agent: " + request.getHeader("User-Agent");
logWriter.println(logMessage);
logWriter.close();
} catch (IOException e) {
System.out.println("Error logging request: " + e.getMessage());
}
}
}
JSP: log.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*, java.util.*" %>
<html>
<head>
<title>Log File and Cookie Information</title>
</head>
<body>
<h2>Cookie Information</h2>
<p>
<%
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if ("userID".equals(cookie.getName())) {
out.println("Your User ID (Cookie): " + cookie.getValue());
}
}
} else {
out.println("No cookies found.");
}
%>
</p>
<h2>Log File Contents</h2>
<pre>
<%
String logFilePath = "C:/logs/application.log";
// Make sure the path is correct for your environment
File logFile = new File(logFilePath);
if (logFile.exists()) {
BufferedReader reader = new BufferedReader(new FileReader(logFile));
String line;
while ((line = reader.readLine()) != null) {
out.println(line);
}
reader.close();
} else {
out.println("Log file does not exist.");
}
%>
</pre>
</body>
</html>