CS 406 Lab Manual

Download as odt, pdf, or txt
Download as odt, pdf, or txt
You are on page 1of 22

1.

Installation of J2SDK (Java 2 Software Development


Kit)
2. Write a program to show Scope of Variables//Program - 02
public class program2{

private static int x = 1; // Class variable accessible in whole class

public static void main(String[] args) {


int y = 5; // Local variable to main method
System.out.println("Class variable x " + x);
System.out.println("Local variable y. " + y);
someMethod();
}

public static void someMethod() {


System.out.println("Class variable x from someMethod " + x);
// System.out.println("Local variable y from someMethod " +
y); // Error. y cannot be accessed here
}
}

3. Write a program to show Concept of CLASS in


JAVA
// Program - 03
public class Car {

// Fields (attributes)
private String color;
private String model;

//Constructor
public Car(String color, String model) {

this.color=color;
this.model= model;
}

//Method
public void displayInfo() {

System.out.println("Car model: "+model+"\nColor: "+color);

// Main method to create and use objects of Car class


public static void main(String[] args) {

Car myCar = new Car("Red", "Toyota Corolla");

myCar.displayInfo();

}
4. Write a program to show Type Casting in
JAVA

// Program - 04
public class TypeCasting {

public static void main(String[] args) {

//Implicit casting (automatic type conversion)


int mylnt =9;
double myDouble=mylnt;

System.out.println("Int value: "+mylnt);


System.out.println("Converted to double: "+myDouble);

//Explicit casting (manual type conversion)


double anotherDouble = 9.78;
int anotherint = (int) anotherDouble;

System.out.println("Double value: " + anotherDouble);


System.out.println("Converted to int: " + anotherint);

}
}

5. Write a program to show How Exception Handling is in


JAVA

// Program -05
public class Exception_andling_Example {

public static void main(String[] args) {

try {

int[] numbers={1, 2, 3};


System.out.println(numbers [5]); // This will throw an ArrayIn-
dexOutOfBoundsException
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("An exception occurred "+e.getMessage());
}
finally {
System.out.println("The try catch is finished");
}
}
}

6. Write a Program to show


Inheritance

//program - 06

// Base class (parent)


class Vehicle {

//Vehicle attribute
protected String brand="Ford";

//Vehicle method
public void honk() {
System.out.println("Tuut, tuut!");
}
}

// Derived class (child)


class Car extends Vehicle {
// Car attribute
private String modelName="Mustang";

public void displayModel() {


System.out.println("Brand : "+brand+"\nModel: "+modelName);
}
}

public class Main {


public static void main(String[] args)
{
Car myCar = new Car();
myCar.honk();
myCar.displayModel();
}
}

7. Write a program to show


Polymorphism
//Program - 07
class Animal {
public void sound() {
System.out.println("Some sound");

}
}

class Dog extends Animal {


@Override public void sound() {
System.out.println("Woof");
}
}

class Cat extends Animal {


@Override public void sound() {
System.out.println("Meow");
}
}

public class Main {

public static void main(String[] args) {


Animal myAnimal =new Animal();
Animal myDog=new Dog();
Animal myCat=new Cat();

myAnimal.sound(); //Outputs Some sound


myDog.sound(); //Outputs Woof
myCat.sound(); //Outputs Meow

}
}
8. Write a program to show Access Specifiers (Public, Private, Protected) in
JAVA
//Program - 08

class AccessSpecifierDemo {

public int publicVar=100; //Accessible for many other class

private int privateVar=200; // Accessible only within the class

protected int protectedVar=300; // Accessible within the class and by


derived classes

public void display() {


System.out.println("Public" + publicVar);
System.out.println("Private: "+privateVar);
System.out.println("Protected "+protectedVar);
}
}

public class Main {


public static void main(String[] args) {
AccessSpecifierDemo demo = new AccessSpecifierDemo();
demo.display();

System.out.println(demo.publicVar);
//Systemout.println(demma,privateVar); //Error: Cannot access
// Systemout.println(demaprotectedVar); //Error: Cannot access outside
the class without inheritance
}
}

9. Write a program to show use and Advantages of


CONSTRUCTOR
//Program - 09

class Car {
private String model;
private int year;

//Constructor
public Car (String model, int year) {

this.model =model;
this.year=year;
}

public void displayInfo() {


System.out.println("Model: "+model+"\nYear: "+year);
}
}

public class Main {


public static void main(String[] args) {

Car car1 = new Car ("Toyota Corolla", 2020);


car1.displayInfo();
}
}

10. Write a program to show Interfacing between two classes

// Program - 10

interface Animal {
void sound(); // Interface method (does not have a body) }
}

class Dog implements Animal {

public void sound() { //The body of sound() is provided here


System.out.println("Wbof");
}
}

class Cat implements Animal {

public void sound() {


System.out.println("Meow");
}
}

public class Main {

public static void main(String[] args) {

Dog myDog = new Dog();


Cat myCat = new Cat();

myDog.sound();
myCat.sound();
}
}
11. Write a program to Add a Class to a
Package

// program - 11

package com.example.project;
public class program11 {

public static void main(String[] args) {


System.out.println("Hello from a package!");
}
}
12. Write a program to show Life Cycle of a Thread
//program - 12

class ThreadDemo extends Thread {


public void run() {
try {
// Moving thread to Timed Waiting state
Thread.sleep(150);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("State after completion " + Thread.current-
Thread().getState());
}

public static void main(String[] args) throws InterruptedException {


ThreadDemo t1 = new ThreadDemo();
System.out.println("State when created " + t1.getState());
t1.start();
System.out.println("State when started " + t1.getState());
// waiting for thread to die
t1.join();
System.out.println("State after thread ended its task " + t1.get-
State());
}
}
13. Write a program to demonstrate AWT
// program - 13

import java.awt.*;
import java.awt.event.*;

public class program13 extends Frame {


program13() {
// create a button
Button b = new Button("Click Me");
b.setBounds(30, 100, 80, 30); // setting button position
// add button to the frame
add(b);
setSize(300, 300); // frame size 300 width and 300 height
setLayout(null); // no layout manager
setVisible(true); // now frame will be visible
// close the frame when close button is clicked
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dispose();
}
});
}

public static void main(String args[]) {


new program13();
}
}
14. Write a program to Hide a Class

// program - 14

package com.example.project;

class InnerClass {// package-private class, not accessible outside


'comexample.project' package
void display() {
System.out.println("Hello from Inner Class!");
}
}

public class program14 {

public static void main(String[] args) {


InnerClass obj = new InnerClass();
obj.display();
}
}
15. Write a Program to show Database Connectivity Using JAVA

// program - 15

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class program15 {


public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/yourDatabase";
String user = "username";
String password = "password";

// Establish Connection
Connection conn = DriverManager.getConnection(url, user,
password);

// Create a statement
Statement stmt = conn.createStatement();

// Execute a query
ResultSet rs = stmt.executeQuery("SELECT * FROM yourTable");

// Iterate through the result set


while (rs.next()) {
System.out.println(rs.getString("columnName"));
}

// Clean up environment
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

16. Write a Program to show "HELLO JAVA" in Explorer using


Applet

Note: Applets are deprecated as of Java 9 and removed in later versions, and modern browsers no
longer support Java applets due to security concerns. However, here's how it
would have been written for historical understanding.

17. Write a Program to show Connectivity using


JDBC

// program 17

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class SimpleJDBCConnection {

public static void main(String[] args) {


try {
// Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnec-
tion("jdbc:mysql://localhost:3306/company", "root", "");

Statement statement = connection.createStatement();


ResultSet resultSet = statement.executeQuery("SELECT * FROM
employee");
while (resultSet.next()) {
System.out.println(resultSet.getString("name"));
}
resultSet.close();
statement.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

18. Write a program to demonstrate multithreading using Java.

// program -18

class Printer extends Thread {

private String message;

public Printer(String msg) {


this.message = msg;
}

public void run() {


for (int i = 0; i < 5; i++) {
System.out.println(message);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println("Thread interrupted.");
}
}
}
}

public class MultiThreadingDemo {

public static void main(String[] args) {


Printer thread1 = new Printer("Thread 1 is running");
Printer thread2 = new Printer("Thread 2 is running");
thread1.start();
thread2.start();
}

19. Write a program to demonstrate applet life cycle.

Again, applets are deprecated, but for educational purposes, the code might
look like:

import
java.applet.Applet;

import
java.awt.Graphics;

public class LifecycleApplet extends Applet


{

public void init()


{

System.out.println("Applet
initialized");
}
}

public void start() {

System.out.println("Applet starting");

public void stop()


{

System.out.println("Applet
stopping");

public void destroy()


{

}
System.out.println("Applet
destroyed");

public void paint(Graphics


g) {

}
g.drawString("See console for life cycle messages.",
10, 20);
20. Write a program to demonstrate the concept of a servlet.

Servlets are Java programs that run on a server, typically to process web requests. Below is a
simple servlet example that displays "Hello Servlet" in response to HTTP requests.

import javax.servlet.*;

import
javax.servlet.http.*;
import java.io.*;

public class HelloServlet extends


HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse


response)

throws ServletException,
IOException {

response.setContentType("text/
html");

PrintWriter out =
response.getWriter();

out.println("<html><body>");

out.println("<h1>Hello
Servlet</h1>");

out.println("</body></
html>");

}
}

This servlet would need to be deployed on a servlet container such as Apache Tomcat. You would also
need to configure it in the web.xml file or use annotations in newer Java versions to specify URL
patterns.

You might also like