Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Practical-1: Basics of Java

i. If-Else Statements
import java.util.Scanner;
public class Main {
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("The number is even.");
} else {
System.out.println("The number is odd.");
}
}
}
Output:

ii. Nested If-Else Statements


public class Code {
public static void main(String[] args) {
int n = 24;
// if else condition to check whether the number is even or odd
if (n % 2 == 0) {
// the number is even
System.out.print("Even ");
// nested if else condition to check if n is divisible by 6 or not
if (n % 6 == 0) {

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
// the number is divisible by 6
System.out.println("and divisible by 6");
} else {
// the number is not divisible by 6
System.out.println("and not divisible by 6");
}
} else {
// the number is odd
System.out.print("Odd ");
// nested if else condition to check if n is divisible by 3 or not
if (n % 3 == 0) {
// the number is divisible by 3
System.out.println("and divisible by 3");
} else {
// the number is not divisible by 3
System.out.println("and not divisible by 3");
}
}
}
}
Output:

iii. Addition Of 2 Numbers


public class Main {
public static void main(String[] args) {
// Define the first number
int first = 10;
// Define the second number
int second = 20;
// Add the two numbers

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
int sum = first + second;
// Print the equation and the result
System.out.println(first + " + " + second + " = " + sum);
}
}
Output:

iv. For Loop


public class ForExample {
public static void main(String[] args) {
// Code of for loop
for (int i = 1; i <= 10; i++) {
System.out.println("1 * " + i + " = " + (1 * i));
}
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
v. Method Overloading
public class Sum {
// Overloaded sum(). This sum takes two int parameters
public int sum(int x, int y) {
return (x + y);
}
// Overloaded sum(). This sum takes three int parameters
public int sum(int x, int y, int z) {
return (x + y + z);
}
// Overloaded sum(). This sum takes two double parameters
public double sum(double x, double y) {
return (x + y);
}
// Driver code
public static void main(String args[]) {
Sum s = new Sum();
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10, 20, 30));
System.out.println(s.sum(10.5, 20.5));
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-2: Inheritances

// Base class
class Bicycle {
// Fields
public int gear;
public int speed;

// Constructor
public Bicycle(int gear, int speed) {
this.gear = gear;
this.speed = speed;
}

// Methods
public void applyBrake(int decrement) {
speed -= decrement;
}

public void speedUp(int increment) {


speed += increment;
}

// toString() method to print info of Bicycle


public String toString() {
return ("No of gears are " + gear + "\n" + "Speed of bicycle is " + speed);
}
}

// Derived class
class MountainBike extends Bicycle {
// Additional field
public int seatHeight;

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
// Constructor
public MountainBike(int gear, int speed, int startHeight) {
// Invoking base-class(Bicycle) constructor
super(gear, speed);
seatHeight = startHeight;
}

// Method
public void setHeight(int newValue) {
seatHeight = newValue;
}

// Overriding toString() method of Bicycle to print more info


@Override public String toString() {
return (super.toString() + "\nSeat height is " + seatHeight);
}
}

// Driver class
public class Test {
public static void main(String args[]) {
MountainBike mb = new MountainBike(3, 100, 25);
System.out.println(mb.toString());
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-3: Multiple Inheritance (Using Interface)

interface Character {
void attack();
}

interface Weapon {
void use();
}

class Warrior implements Character, Weapon {


public void attack() {
System.out.println("Warrior attacks with a sword.");
}

public void use() {


System.out.println("Warrior uses a sword.");
}
}

class Mage implements Character, Weapon {


public void attack() {
System.out.println("Mage attacks with a wand.");
}

public void use() {


System.out.println("Mage uses a wand.");
}
}

public class MultipleInheritance {


public static void main(String[] args) {
Warrior warrior = new Warrior();

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Mage mage = new Mage();

warrior.attack(); // Output: Warrior attacks with a sword.


warrior.use(); // Output: Warrior uses a sword.

mage.attack(); // Output: Mage attacks with a wand.


mage.use(); // Output: Mage uses a wand.
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-4: Exceptional Handling

i. Exception Handling In Java


public class JavaExceptionExample {
public static void main(String args[]) {
try {
// Code that may raise an exception
int data = 100 / 0;
} catch (ArithmeticException e) {
System.out.println(e);
}
// Rest of the code
System.out.println("Rest of the code...");
}
}
Output:

ii. Throw
class tst {
public static void main(String[] args) throws InterruptedException {
Thread.sleep(10000);
System.out.println("Hello Professor :D");
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-5: MultiThreading In Java

// Java code for thread creation by extending the Thread class


class MultithreadingDemo extends Thread {
public void run() {
try { // Displaying the thread that is running
System.out.println("Thread " + Thread.currentThread().getId() + " is running");
} catch (Exception e) { // Throwing an exception
System.out.println("Exception is caught"); }
}
}
// Main Class
public class Multithread {
public static void main(String[] args) {
int n = 8; // Number of threads
for (int i = 0; i < n; i++) {
MultithreadingDemo object = new MultithreadingDemo();
object.start();
}
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-6: Taking Input From User

i. Using Scanner Class


import java.util.Scanner; // import the Scanner class
class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username:");
userName = myObj.nextLine();

// Greeting message
System.out.println("Hello, " + userName + "! Welcome to the program.");
}
}
Output:

ii. Using Buffer Class


// Java Program for taking user input using BufferedReader Class
import java.io.*;
class Main {
// Main Method
public static void main(String[] args) throws IOException {
// Creating BufferedReader Object
// InputStreamReader converts bytes to
// stream of character
BufferedReader bfn = new BufferedReader(new InputStreamReader(System.in));
Name: Anubhav Goel
Branch & Section: CSE-3D
UT Roll No.: 2101611530015
// String reading internally
String str = bfn.readLine();

// Integer reading internally


int it = Integer.parseInt(bfn.readLine());

// Printing String
System.out.println("Entered String : " + str);

// Printing Integer
System.out.println("Entered Integer : " + it);
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-7: Calculator Using Applet

Java Code:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;

public class Calculator extends Applet implements ActionListener {


TextField inp;
String num1 = "";
String op = "";
String num2 = "";

// Function to add features to the frame


public void init() {
setBackground(Color.white);
setLayout(null);

inp = new TextField();


inp.setBounds(150, 100, 270, 50);
this.add(inp);

Button button[] = new Button[10];


for (int i = 0; i < 10; i++) {
button[i] = new Button(String.valueOf(9 - i));
button[i].setBounds(150 + ((i % 3) * 50), 150 + ((i / 3) * 50), 50, 50);
this.add(button[i]);
button[i].addActionListener(this);
}

Button dec = new Button(".");


dec.setBounds(200, 300, 50, 50);
this.add(dec);

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
dec.addActionListener(this);
Button clr = new Button("C");
clr.setBounds(250, 300, 50, 50);
this.add(clr);
clr.addActionListener(this);

Button operator[] = new Button[5];


operator[0] = new Button("/");
operator[1] = new Button("*");
operator[2] = new Button("-");
operator[3] = new Button("+");
operator[4] = new Button("=");
for (int i = 0; i < 4; i++) {
operator[i].setBounds(300, 150 + (i * 50), 50, 50);
this.add(operator[i]);
operator[i].addActionListener(this);
}
operator[4].setBounds(350, 300, 70, 50);
this.add(operator[4]);
operator[4].addActionListener(this);
}

// Function to calculate the expression


public void actionPerformed(ActionEvent e) {
String button = e.getActionCommand();
char ch = button.charAt(0);
if (ch >= '0' && ch <= '9' || ch == '.') {
if (!op.equals(""))
num2 = num2 + button;
else
num1 = num1 + button;
inp.setText(num1 + op + num2);
} else if (ch == 'C') {

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
num1 = op = num2 = "";
inp.setText("");
} else if (ch == '=') {
if (!num1.equals("") && !num2.equals("")) {
double temp;
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (n2 == 0 && op.equals("/")) {
inp.setText(num1 + op + num2 + " = Zero Division Error");
num1 = op = num2 = "";
} else {
if (op.equals("+"))
temp = n1 + n2;
else if (op.equals("-"))
temp = n1 - n2;
else if (op.equals("/"))
temp = n1 / n2;
else
temp = n1 * n2;
inp.setText(num1 + op + num2 + " = " + temp);
num1 = Double.toString(temp);
}
}
op = num2 = "";
} else {
if (op.equals("") || num2.equals(""))
op = button;
else {
double temp;
double n1 = Double.parseDouble(num1);
double n2 = Double.parseDouble(num2);
if (n2 == 0 && op.equals("/")) {
inp.setText(num1 + op + num2 + " = Zero Division Error");

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
num1 = op = num2 = "";
} else {
if (op.equals("+"))
temp = n1 + n2;
else if (op.equals("-"))
temp = n1 - n2;
else if (op.equals("/"))
temp = n1 / n2;
else
temp = n1 * n2;
num1 = Double.toString(temp);
op = button;
num2 = "";
}
}
inp.setText(num1 + op + num2);
}
}
}

HTML Code for Applet:


<!DOCTYPE html>
<html>
<head>
<title>Calculator Applet</title>
</head>
<body>
<applet code="Calculator.class" width="600" height="600">
</applet>
</body>
</html>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-8: HTML

i. Display CV using HTML & JavaScript


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CV with Navbar</title>
<style>
/* Style for the navigation bar */
.navbar {
background-color: #333;
overflow: hidden;
}
.navbar a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 20px;
text-decoration: none;
}
.navbar a:hover {
background-color: #ddd;
color: black;
}
/* Style for the CV content */
.content {
padding: 20px;
}
</style>
</head>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
<body>
<div class="navbar">
<a href="#personal-info">Personal Info</a>
<a href="#education">Education</a>
<a href="#experience">Experience</a>
<a href="#skills">Skills</a>
</div>
<div class="content">
<h2 id="personal-info">Personal Information</h2>
<p>Name: ABC</p>
<p>Email: abc@example.com</p>
<h2 id="education">Education</h2>
<p>Degree: Bachelor of Science in Computer Science</p>
<p>University: Example University</p>
<h2 id="experience">Experience</h2>
<p>Position: Software Engineer</p>
<p>Company: Example Inc.</p>
<h2 id="skills">Skills</h2>
<p>Programming Languages: JavaScript, HTML, CSS</p>
<p>Frameworks: React, Angular</p>
</div>
<script>
// JavaScript code can be added here if needed, for example, to make the navbar interactive.
</script>
</body>
</html>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Output:

ii. Display Table


<!DOCTYPE html>
<html>
<head>
<style>
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid black;
padding: 8px;
text-align: left;
}
th {
Name: Anubhav Goel
Branch & Section: CSE-3D
UT Roll No.: 2101611530015
background-color: #f2f2f2;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
<th>Salary</th>
</tr>
<tr>
<td>John</td>
<td>24</td>
<td>20,000</td>
</tr>
<tr>
<td>Adam</td>
<td>31</td>
<td>35,000</td>
</tr>
<tr>
<td>Chris</td>
<td>27</td>
<td>32,000</td>
</tr>
</table>
</body>
</html>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Output:

iii. Html Form for Student Details


<!DOCTYPE html>
<html>
<head>
<title>Registration Page</title>
</head>
<body bgcolor="LightGrey">
<br>
<br>
<form>
<label>Firstname:</label>
<input type="text" name="firstname" size="15"/> <br> <br>

<label>Middlename:</label>
<input type="text" name="middlename" size="15"/> <br> <br>

<label>Lastname:</label>
<input type="text" name="lastname" size="15"/> <br> <br>

<label>Course:</label>
<select>
<option value="Course">Course</option>
<option value="BCA">BCA</option>
<option value="BBA">BBA</option>
<option value="B. Tech">B. Tech</option>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
<option value="MBA">MBA</option>
<option value="MCA">MCA</option>
<option value="M.Tech">M.Tech</option>
</select>
<br>
<br>

<label>Gender:</label><br>
<input type="radio" name="gender" value="male"/> Male <br>
<input type="radio" name="gender" value="female"/> Female <br>
<input type="radio" name="gender" value="other"/> Other
<br>
<br>

<label>Phone:</label>
<input type="text" name="country code" value="+91" size="2"/>
<input type="text" name="phone" size="10"/> <br> <br>

Address:<br>
<textarea cols="80" rows="5" name="address"></textarea>
<br>
<br>

Email:<br>
<input type="email" id="email" name="email"/> <br>
<br>

Password:<br>
<input type="password" id="pass" name="pass"> <br>
<br>

Re-type password:<br>
<input type="password" id="repass" name="repass"> <br>

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
<br>

<input type="submit" value="Submit"/>


</form>
</body>
</html>
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-9: JavaScript

i. Addition of Two Numbers


// Declare two variables and assign numbers to them
var number1 = 5;
var number2 = 3;
// Add the two numbers using the + operator
var sum = number1 + number2;
// Print the result
console.log("The sum of the two numbers is: " + sum);
Output:

ii. Calculate Simple Interest


// Define the variables to store the principal, rate of interest, and time
var p = parseFloat(prompt("Enter Principle: ")); // Principal amount = ₹10000/-
var r = parseFloat(prompt("Enter Rate: ")); // Rate of interest = 8%
var t = parseFloat(prompt("Enter Time: ")); // Time in years = 2 years
// Calculate the interest using the formula
// Simple Interest = (principle * rate * time) / 100
var interest = (p * r * t) / 100;
// Display the result
console.log("Simple Interest: " + interest);
Output:

iii. Simple Calculator


// Program for a simple calculator
// Take the operator input
const operator = prompt('Enter operator (either +, -, * or /): '); //Input: +
// Take the operand input
Name: Anubhav Goel
Branch & Section: CSE-3D
UT Roll No.: 2101611530015
const number1 = parseFloat(prompt('Enter first number: ')); // Input: 52
const number2 = parseFloat(prompt('Enter second number: ')); // Input: 609
let result;

// Perform the arithmetic operation based on the operator


if (operator === '+') {
result = number1 + number2;
} else if (operator === '-') {
result = number1 - number2;
} else if (operator === '*') {
result = number1 * number2;
} else if (operator === '/') {
if (number2 !== 0) {
result = number1 / number2;
} else {
console.log("Error: Division by zero");
result = NaN;
}
} else {
console.log("Error: Invalid operator");
result = NaN;
}

// Display the result


console.log(`${number1} ${operator} ${number2} = ${result}`);
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
Practical-10: JDBC & ODBC

i. Java Database Connectivity (JDBC)


import java.sql.*;
import java.util.*;

public class Main {


public static void main(String a[]) {
// Creating the connection using Oracle DB
String url = "jdbc:oracle:thin:@localhost:1521:xe";
String user = "system";
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);
System.out.println("Enter name:");
String name = k.next();
System.out.println("Enter roll no:");
int roll = k.nextInt();
System.out.println("Enter class:");
String cls = k.next();

// Inserting data using SQL query


String sql = "INSERT INTO student1 VALUES('" + name + "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

try {
// Registering drivers
DriverManager.registerDriver(new oracle.jdbc.OracleDriver());

// Creating a connection

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
con = DriverManager.getConnection(url, user, pass);

// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("Inserted successfully: " + sql);
else
System.out.println("Insertion failed");
} catch (Exception ex) {
// Display message when exceptions occur
System.err.println(ex);
} finally {
try {
// Closing the connections
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
ii. Microsoft Open Database Connectivity (JDBC)
import java.sql.*;
import java.util.*;

public class Main {


public static void main(String a[]) {
// Creating the connection using JDBC-ODBC Bridge
String url = "jdbc:odbc:OracleDB"; // Replace "OracleDB" with your ODBC Data
Source Name (DSN)
String user = "system";
String pass = "12345";

// Entering the data


Scanner k = new Scanner(System.in);
System.out.println("Enter name:");
String name = k.next();
System.out.println("Enter roll no:");
int roll = k.nextInt();
System.out.println("Enter class:");
String cls = k.next();

// Inserting data using SQL query


String sql = "INSERT INTO student1 VALUES('" + name + "'," + roll + ",'" + cls + "')";

// Connection class object


Connection con = null;

try {
// Registering drivers
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

// Creating a connection
con = DriverManager.getConnection(url, user, pass);

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015
// Creating a statement
Statement st = con.createStatement();

// Executing query
int m = st.executeUpdate(sql);
if (m == 1)
System.out.println("Inserted successfully: " + sql);
else
System.out.println("Insertion failed");
} catch (Exception ex) {
// Display message when exceptions occur
System.err.println(ex);
} finally {
try {
// Closing the connections
if (con != null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Output:

Name: Anubhav Goel


Branch & Section: CSE-3D
UT Roll No.: 2101611530015

You might also like