Ash Ritha
Ash Ritha
Page No. :
import java.util.Scanner;
public class CheckEvenOdd {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();
if (number % 2 == 0) {
System.out.println(number + " is even.");
} else {
System.out.println(number + " is odd.");
}}}
output:-
c.java program to add two binary numbers
import java.util.Scanner;
public class AddBinaryNumbers {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter first binary number: ");
String bin1 = scanner.nextLine();
System.out.print("Enter second binary number: ");
String bin2 = scanner.nextLine();
int num1 = Integer.parseInt(bin1, 2);
int num2 = Integer.parseInt(bin2, 2);
int sum = num1 + num2;
String result = Integer.toBinaryString(sum);
System.out.println("Sum of the binary numbers: " + result);
}}
output:-
d. Java
Program to Calculate Area and Circumference of Circle import
java.util.Scanner;
public class CircleAreaCircumference {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the radius of the circle: ");
double radius = scanner.nextDouble();
double area = Math.PI * radius * radius;
double circumference = 2 * Math.PI * radius;
System.out.println("Area: " + area);
System.out.println("Circumference: " + circumference);}
}
output:-
e. Java Program to Multiply two Numbers
public class MultiplyTwoNumbers {
public static void main(String[] args) {
int num1 = 7, num2 = 8;
int product = num1 * num2;
System.out.println("Product of " + num1 + " and " + num2 + " is: " + product);
}}
output:-
f. Java
Program to
check Leap Year import
java.util.Scanner;
public class CheckLeapYear {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a year: ");
int year = scanner.nextInt();
boolean isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (isLeapYear) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year.");
}}}
output:-
else {
System.out.println(ch + " is a consonant.");
} }}
output:-
h.java program to
calculate compound interest import
java.util.Scanner;
public class CompoundInterest {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter principal amount: ");
double principal = scanner.nextDouble();
System.out.print("Enter annual interest rate (in %): ");
double rate = scanner.nextDouble();
System.out.print("Enter number of times interest applied per time period: ");
int n = scanner.nextInt();
System.out.print("Enter time the money is invested for (in years): ");
int t = scanner.nextInt();
double amount = principal * Math.pow(1 + (rate / 100) / n, n * t);
double compoundInterest = amount - principal;
System.out.println("Compound Interest: " + compoundInterest);
System.out.println("Amount: " + amount);
}}
output:-
i.Java program to calculate power of a number.
import java.util.Scanner;
public class PowerOfNumber {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter base number: ");
int base = scanner.nextInt();
System.out.print("Enter exponent: ");
int exponent = scanner.nextInt();
double result = Math.pow(base, exponent);
System.out.println(base + " raised to the power of " + exponent + " is: " + result);
}}
output:-
b.duplicate
java.util.HashMap;
public class DuplicateCharacters {
public static void main(String[] args) {
String str = "programming";
HashMap<Character, Integer> charCount = new HashMap<>();
for (char c : str.toCharArray()) {
charCount.put(c, charCount.getOrDefault(c, 0) + 1); }
System.out.println("Duplicate characters:");
for (char c : charCount.keySet()) {
if (charCount.get(c) > 1) {
System.out.println(c + ": " + charCount.get(c));
}}}
output:-
c. Java program to a string in alphabetical order.
import java.util.Arrays;
import java.util.Scanner;
public class SortStringsAlphabetically {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the number of strings: ");
int n = scanner.nextInt();
scanner.nextLine();
String[] strings = new String[n];
System.out.println("Enter the strings:");
for (int i = 0; i < n; i++) {
strings[i] = scanner.nextLine();
}
Arrays.sort(strings);
System.out.println("Strings in alphabetical order:");
for (String str : strings) {
System.out.println(str);
}}}
output:-
h.Java
java.util.Scanner;
public class VowelsAndConsonants {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();
int vowelsCount = 0;
int consonantsCount = 0;
String vowels = "aeiouAEIOU";
for (int i = 0; i < str.length(); i++) {
char ch = str.charAt(i);
if (Character.isLetter(ch)) {
if (vowels.indexOf(ch) != -1) {
vowelsCount++;
} else {
consonantsCount++; }}}
System.out.println("Number of vowels: " + vowelsCount);
System.out.println("Number of consonants: " + consonantsCount);}}
output:-
output:-
Title : Date :
Page No. :
pw.println("Login Success");
}
else {
pw.println("Sorry... Login Failed");
}
pw.close();
}
}
Output:
Title : Date :
Page No. :
Program8: Maintaining the transactional history of any user is very important. Explore the
various session tracking mechanism (Cookies, HTTP Session) 24.05.2024
Create a file in index.html using java eclipse dynamic web project.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="FirstServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
Output:
Title : Date :
Page No. :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
Cookie ck=new Cookie("uname",n);//creating cookie object
response.addCookie(ck);//adding cookie in the response
//creating submit button
out.print("<form action='SecondServlet' method='post'>");
out.print("<input type='submit' value='Submit'>");
out.print("</form>");
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Title : Date :
Page No. :
Output:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
}
Output:
Title : Date :
Page No. :
Program 9: Create a custom server using http module and explore the other modules of Node JS
like OS, path, event.
Code:
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(osInfo, null, 2));
}
else if (req.url === '/pathinfo') {
const pathInfo = {
currentDirectory: dirname,
currentFile: filename,
fileExtension: path.extname( filename),
directoryName: path.dirname( filename),
baseName: path.basename( filename),
Title : Date :
Page No. :
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(pathInfo, null, 2));
}
else if (req.url === '/eventinfo') {
const eventInfo = {
message: 'Server has started and the event has been emitted!'
};
myEmitter.emit('eventTriggered');
res.statusCode = 200;
res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify(eventInfo, null, 2));
}
else {
res.statusCode = 200;
res.setHeader('Content-Type', 'text/plain');
res.end('Hello, World!\n');
}
});
server.listen(port, hostname, () => {
myEmitter.emit('serverStart');
console.log(`Server running at http://${hostname}:${port}/`);
console.log('Operating System Info:');
console.log(`OS Type: ${os.type()}`);
console.log(`OS Platform: ${os.platform()}`);
Title : Date :
Page No. :
myEmitter.on('eventTriggered', () => {
console.log('Event has been triggered!');
});
Title : Date :
Page No. :
Output:
Page No. :
Page No. :
Output in postman:
OS module output:
Title : Date :
Page No. :
Page No. :
Program 10: Develop an express web application that can interact with REST API to perform
CRUD operations on student data. (Use Postman)
Aim: Need to develop a web application using ExpressJs which interacts with Postman API, then
perform CRUD Operations.
1. Install Node.js:
Download and install Node.js from the official website. This will also install
npm, the Node package manager.
2. Create a folder in your system and open the created folder in Visual Studio Code.
3. Create a Project Directory:
Open a terminal or command prompt and create a new directory for your
project. Navigate into this directory.
mkdir my-express-app
cd my-express-app
4. Initialize a New Node.js Project:
Initialize a new Node.js project with npm init. Follow the prompts to set up your
package.json file.
npm init -y
1. Install Express:
Install Express.js and any other necessary dependencies.
npm install express
Page No. :
// Create – POST
// Read – GET
// Update – PUT
Object.assign(item, req.body);
res.send(item);
});
// Delete – DELETE
Page No. :
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
1. Open Postman:
Open Postman to test your API endpoints.
2. Create (POST) Operation:
Set the method to POST and enter the URL http://localhost:3000/items.
Go to the Body tab, select raw, and choose JSON format.
Enter JSON data, e.g.:
{
"id": 1,
"name": "Anil",
"description": "This is item Name"
}
Click Send to create a new item.
3. Read (GET) Operations:
o To get all items, set the method to GET and enter the URL
http://localhost:3000/items, then click Send.
o To get a single item by ID, set the method to GET and enter the URL
http://localhost:3000/items/1, then click Send.
Title : Date :
Page No. :
Output:
Title : Date :
Page No. :
Title : Date :
Page No. :
Program 11: For the above application create authorized end points using JWT (JSON Web
Token).
To add authorization to the Express web application using JWT (JSON Web Token), need to
follow these steps:
1. Install additional dependencies.
2. Set up user authentication endpoints.
3. Create a middleware to protect certain routes.
4. Update your existing routes to use the authorization middleware.
// server.js
const express = require('express');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const app = express();
const port = 3000;
const SECRET_KEY = 'your_secret_key'; // You should use an environment variable for this
let users = []; // This should be a database in a real application
let students = [];
// Middleware
app.use(bodyParser.json());
// Routes
app.get('/', (req, res) => {
res.send('Welcome to the Student CRUD API!');
});
Title : Date :
Page No. :
// User registration
app.post('/register', async (req, res) => {
const { username, password } = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
users.push({ username, password: hashedPassword });
res.status(201).send({ message: 'User registered successfully' });
});
// User login
app.post('/login', async (req, res) => {
const { username, password } = req.body;
const user = users.find(u => u.username === username);
if (!user) {
return res.status(404).send({ message: 'User not found' });
}
const isPasswordValid = await bcrypt.compare(password, user.password);
if (!isPasswordValid) {
return res.status(401).send({ message: 'Invalid password' });
}
const token = jwt.sign({ username }, SECRET_KEY, { expiresIn: '1h' });
res.status(200).send({ token });
});
Page No. :
Page No. :
Page No. :
Response:
{
"token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VybmFtZSI6InRlc3R1c2VyIi
wiaWF0IjoxNzE5NzcwMTI3LCJleHAiOjE3MTk3NzM3Mjd9.v3SDW1blrSdIf60psu-uEF-
Khhp4npS7kBJaNek87Xc"
}
Output:
Title : Date :
Page No. :
Title : Date :
Page No. :
Program12: Create a react application for the student management system having registration,
login, contact, about pages and implement routing to navigate through these pages.
function Registration() {
const [formData, setFormData] = useState({
username: '',
email: '',
password: '',
confirmPassword: ''
});
Page No. :
...prevFormData,
[name]: value
}));
};
return (
<div>
<h2>Registration</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Username:</label>
<input
type="text"
name="username"
value={formData.username}
onChange={handleChange}
required
/>
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
Title : Date :
Page No. :
</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
</div>
<div>
<label>Confirm Password:</label>
<input
type="password"
name="confirmPassword"
value={formData.confirmPassword}
onChange={handleChange}
required
/>
</div>
<button type="submit">Register</button>
</form>
</div>
);
}
Login.js:
import React, { useState } from 'react';
function Login() {
const [formData, setFormData] = useState({
email: '',
password: ''
});
Title : Date :
Page No. :
return (
<div>
<h2>Login</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div>
<label>Password:</label>
<input
type="password"
name="password"
value={formData.password}
onChange={handleChange}
required
/>
Title : Date :
Page No. :
</div>
<button type="submit">Login</button>
</form>
</div>
);
}
Contact.js:
import React, { useState } from 'react';
function Contact() {
const [formData, setFormData] = useState({
name: '',
email: '',
message: ''
});
return (
<div>
Title : Date :
Page No. :
<h2>Contact Us</h2>
<form onSubmit={handleSubmit}>
<div>
<label>Name:</label>
<input
type="text"
name="name"
value={formData.name}
onChange={handleChange}
required
/>
</div>
<div>
<label>Email:</label>
<input
type="email"
name="email"
value={formData.email}
onChange={handleChange}
required
/>
</div>
<div>
<label>Message:</label>
<textarea
name="message"
value={formData.message}
onChange={handleChange}
required
/>
</div>
<button type="submit">Send</button>
</form>
</div>
);
}
Title : Date :
Page No. :
About.js:
import React from 'react';
function About() {
return (
<div>
<h2>About Us</h2>
<p>Welcome to our Student Management System. This application is designed to help
manage student information efficiently and effectively.</p>
<p>Our system allows you to register, log in, and view information about students. You can
also contact us through the contact page.</p>
<p>We aim to provide the best service possible and appreciate your feedback. Thank you
for using our system!</p>
</div>
);
}
App.js
function App() {
return (
<Router>
<div>
<nav>
<ul>
Title : Date :
Page No. :
<li>
<Link to="/">Registration</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
<li>
<Link to="/contact">Contact</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
</ul>
</nav>
<Routes>
<Route path="/" element={<Registration />} />
<Route path="/login" element={<Login />} />
<Route path="/contact" element={<Contact />} />
<Route path="/about" element={<About />} />
</Routes>
</div>
</Router>
);
}
Page No. :
Output:
Registration.js
Login.js
Title : Date :
Page No. :
Contact.js
About.js
Title : Date :
Page No. :
Program13: Create a service in react that fetches the weather information from
openweathermap.org and the display the current and historical weather information using graphical
representation using chart.js
Page No. :
return response.data;
} catch (error) {
console.error('Error fetching current weather data:', error);
throw error;
}
};
Page No. :
function App() {
return (
<div className="App">
<WeatherDashboard />
</div>
Title : Date :
Page No. :
);
}
input {
margin-right: 10px;
}
button {
padding: 5px 10px;
}
h2 {
margin-top: 20px;
}
p{
margin: 5px 0;
}
Page No. :
Output:
Title : Date :
Page No. :
Program 14: Create a TODO application in react with necessary components and deploy it into
github
App.js
This will be the main component where we'll manage our state and render other components.
// src/App.js
function App() {
const [todos, setTodos] = useState([]);
return (
<div className="App">
<h1>TODO App</h1>
Title : Date :
Page No. :
TodoForm.js
Component for adding new TODO items.
// src/components/TodoForm.js
return (
<form onSubmit={handleSubmit}>
<input
type="text"
className="input"
value={value}
onChange={(e) => setValue(e.target.value)}
placeholder="Add TODO..."
/>
<button type="submit">Add</button>
</form>
);
}
export default TodoForm;
Title : Date :
Page No. :
TodoList.js
Component to display the list of TODO items.
// src/components/TodoList.js
Page No. :
Visit the URL of your deployed TODO app to verify that it's working correctly.
Title : Date :
Page No. :
Title : Date :
Page No. :
Git Output: