Skip to content
Ananda Technologies Pvt. Ltd.

Java Programming practicals — MSBTE

Every practical of MSBTE K-scheme Java Programming (314317) with 3 different tested programs, real output, explanation and viva questions.

✅ Solved by Ananda TechnologiesDiplomaSemester 4MSBTE K-schemeCode 314317CO, IF, CM, CW, SE, IH, AN, AI, DSQuestion papers →
Build your own practical file in 3 steps
  1. 1Tick one answer (A, B or C) for the questions you need — one practical or all.
  2. 2Press Generate PDF at the bottom. First time: free account (asked only once).
  3. 3Choose Save as PDF in the print window. Print again any time.

💡 Explain buttons are for your understanding — explanations are never printed.

Practical 1Compulsory

Set up the Java development environment (command prompt and IDE)

Aim: Install the JDK, set PATH and CLASSPATH, compile and run a program from the command prompt and from an IDE.

QSet up the Java development environment and run your first Java program.

Showing answer A of 3 · tap A, B or C to see the others

  1. Download the JDK (Oracle JDK or OpenJDK, version 17 or later) and install it, e.g. in C:\Program Files\Java\jdk-21.
  2. Open Start → "Edit the system environment variables" → Environment Variables.
  3. PATH: edit Path → New → C:\Program Files\Java\jdk-21\bin (this lets you type javac and java anywhere).
  4. CLASSPATH (optional): New variable CLASSPATH = .; (the dot means "current folder").
  5. Open a new Command Prompt and check: javac -version and java -version.
  6. Save the program as Main.java, then run: javac Main.java and java Main

Output

Hello! Java is installed correctly.
Java version : 21
Running from the command prompt.
public class Main
{
    public static void main(String[] args)
    {
        System.out.println("Hello! Java is installed correctly.");
        System.out.println("Java version : " + System.getProperty("java.specification.version"));
        System.out.println("Running from the command prompt.");
    }
}
🎤 Viva questions (5)
Q. What is the difference between JDK, JRE and JVM?
A. JVM runs bytecode; JRE = JVM + libraries to run programs; JDK = JRE + tools like javac to develop programs.
Q. What does javac do?
A. It compiles .java source code into .class bytecode.
Q. Why is Java platform independent?
A. Bytecode runs on any machine that has a JVM — "write once, run anywhere".
Q. What is the PATH variable used for?
A. It tells Windows where javac and java are, so they run from any folder.
Q. Why is main() static?
A. The JVM calls main() before any object exists, so it must belong to the class.

Practical 2

Evaluate different types of expressions

Aim: Use arithmetic, relational, logical, bitwise, increment/decrement and conditional operators in expressions.

QWrite a program to evaluate different types of expressions.

Showing answer A of 3 · tap A, B or C to see the others

Output

a + b = 22
a - b = 12
a * b = 85
a / b = 3   (integer division)
a % b = 2   (remainder)
(double) a / b = 3.4
x += 5  -> 15
x *= 2  -> 30
x -= 4  -> 26
public class Main
{
    public static void main(String[] args)
    {
        int a = 17, b = 5;
        System.out.println("a + b = " + (a + b));
        System.out.println("a - b = " + (a - b));
        System.out.println("a * b = " + (a * b));
🎤 Viva questions (5)
Q. What is an expression?
A. A combination of variables, constants and operators that gives a value.
Q. What is the difference between / and %?
A. / gives the quotient, % gives the remainder.
Q. What is the difference between ++i and i++?
A. ++i increments before use, i++ uses the old value and then increments.
Q. What is the difference between & and &&?
A. & is bitwise (and evaluates both sides); && is logical AND with short-circuit.
Q. What is type casting?
A. Converting one data type into another, e.g. (double) a.

Practical 3

if statements, switch-case and loops (for, while, do..while)

Aim: Write programs using all forms of if, the switch statement and the three loops.

Q1Program 1: use all forms of the if statement.

Showing answer A of 3 · tap A, B or C to see the others

Output

Enter percentage: 68.4
Grade: First class
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter percentage: ");

Q2Program 2: use the switch-case statement.

Showing answer A of 3 · tap A, B or C to see the others

Output

Enter two numbers: 24 6
Choose operator (+ - * /): /
Result = 4.0
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter two numbers: ");

Q3Program 3: use the for, while and do..while loops.

Showing answer A of 3 · tap A, B or C to see the others

Output

Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a number: ");
🎤 Viva questions (5)
Q. What is the difference between while and do..while?
A. while checks the condition first; do..while runs the body once before checking.
Q. What happens if break is missing in a switch case?
A. Execution falls through into the next case.
Q. Can switch work with String in Java?
A. Yes, from Java 7 onwards.
Q. What is a nested if?
A. An if statement written inside another if or else block.
Q. What is an infinite loop?
A. A loop whose condition never becomes false, e.g. for(;;).

Practical 4Compulsory

Methods of the String class and the StringBuffer class

Aim: Use common methods of String (immutable) and StringBuffer (mutable).

Q1Program 1: demonstrate methods of the String class.

Showing answer A of 3 · tap A, B or C to see the others

Output

String       : Java Programming
length()     : 16
charAt(5)    : P
toUpperCase(): JAVA PROGRAMMING
toLowerCase(): java programming
substring(5) : Programming
indexOf('a') : 1
replace      : Core Java Programming
contains Pro : true
trim()       : [hello]
public class Main
{
    public static void main(String[] args)
    {
        String s = "Java Programming";
        System.out.println("String       : " + s);
        System.out.println("length()     : " + s.length());
        System.out.println("charAt(5)    : " + s.charAt(5));

Q2Program 2: demonstrate methods of the StringBuffer class.

Showing answer A of 3 · tap A, B or C to see the others

Output

Start       : Java
append()    : Java Programming
insert()    : Core Java Programming
replace()   : Advanced Java Programming
delete()    : Java Programming
reverse()   : gnimmargorP avaJ
length()    : 16
capacity()  : 42
public class Main
{
    public static void main(String[] args)
    {
        StringBuffer sb = new StringBuffer("Java");
        System.out.println("Start       : " + sb);
        sb.append(" Programming");
        System.out.println("append()    : " + sb);
🎤 Viva questions (5)
Q. Why is String immutable?
A. Once created, its value cannot change; methods return new String objects. This makes it safe to share.
Q. What is the difference between String and StringBuffer?
A. String is immutable; StringBuffer is mutable and changes the same object.
Q. What is the difference between StringBuffer and StringBuilder?
A. StringBuffer is synchronized (thread-safe); StringBuilder is not, so it is faster.
Q. What is the default capacity of StringBuffer?
A. 16 characters (plus the length of the initial string).
Q. What is the difference between == and equals()?
A. == compares references; equals() compares contents.

Practical 5Compulsory

Use of arrays and Vectors

Aim: Store data in one- and two-dimensional arrays, and in a growable Vector.

Q1Program 1: demonstrate the use of arrays.

Showing answer A of 3 · tap A, B or C to see the others

Output

How many numbers? 5
Enter 5 numbers: 12 45 7 30 18
Sum     = 112
Average = 22.4
Largest = 45
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("How many numbers? ");

Q2Program 2: demonstrate the use of Vectors.

Showing answer A of 3 · tap A, B or C to see the others

Output

Vector          : [C, C++, Java, Python]
insertElementAt : [C, HTML, C++, Java, Python]
remove("C++")   : [C, HTML, Java, Python]
elementAt(2)    : Java
contains Java   : true
indexOf Python  : 3
size / capacity : 4 / 10
import java.util.Vector;

public class Main
{
    public static void main(String[] args)
    {
        Vector<String> v = new Vector<>();
        v.add("C");
🎤 Viva questions (5)
Q. What is the difference between an array and a Vector?
A. An array has a fixed size and can hold primitives; a Vector grows automatically and holds objects only.
Q. What is the default capacity of a Vector?
A. 10; it doubles when full (unless an increment is given).
Q. Is Vector synchronized?
A. Yes, its methods are synchronized (thread-safe).
Q. What is the index of the first element of an array?
A. 0
Q. What happens if you access an index outside the array?
A. ArrayIndexOutOfBoundsException is thrown.

Practical 6

Wrapper classes: primitive to object and object to primitive

Aim: Convert primitive values to wrapper objects and back, manually and with auto-boxing.

QWrite a program to convert primitive data types into objects and objects into primitive data types.

Showing answer A of 3 · tap A, B or C to see the others

Output

Objects    : 25, 9.75, J
Primitives : 25, 9.75, J
io + 5     = 30
public class Main
{
    public static void main(String[] args)
    {
        int i = 25;
        double d = 9.75;
        char c = 'J';
🎤 Viva questions (5)
Q. What is a wrapper class?
A. A class that wraps a primitive value in an object, e.g. Integer for int.
Q. What is auto-boxing?
A. Automatic conversion of a primitive into its wrapper object.
Q. What is unboxing?
A. Getting the primitive value back from the wrapper object.
Q. Why are wrapper classes needed?
A. Collections like Vector store only objects, and wrappers give useful methods like parseInt.
Q. Name the wrapper class of char and int.
A. Character and Integer.

Practical 7

Different types of constructors

Aim: Use default, parameterized and copy constructors and constructor overloading.

QWrite a program to demonstrate different types of constructors.

Showing answer A of 3 · tap A, B or C to see the others

Output

Roll: 0  Name: Not set
Roll: 12  Name: Aditi
Roll: 12  Name: Aditi
class Student
{
    int roll;
    String name;

    Student()                          // default constructor
    {
        roll = 0;
🎤 Viva questions (5)
Q. What is a constructor?
A. A special method with the class name and no return type that initializes a new object.
Q. What is a default constructor?
A. A constructor without parameters; Java gives one automatically if you write none.
Q. What is constructor overloading?
A. Having several constructors in a class with different parameter lists.
Q. Does Java have a built-in copy constructor?
A. No, you write it yourself by taking an object of the same class as a parameter.
Q. What is the use of this()?
A. To call another constructor of the same class; it must be the first statement.

Practical 8

Single inheritance and multilevel inheritance

Aim: Reuse a class with extends, use super, and build a multilevel chain.

Q1Program 1: implement single inheritance.

Showing answer A of 3 · tap A, B or C to see the others

Output

Name: Kavita  Salary: 45000.0
Bonus: 8000.0  Total: 53000.0
class Employee
{
    String name;
    double salary;
    Employee(String name, double salary)
    {
        this.name = name;
        this.salary = salary;

Q2Program 2: implement multilevel inheritance.

Showing answer A of 3 · tap A, B or C to see the others

Output

Person created
Employee created
Manager created
501 | Rohit | Sales
class Person
{
    String name;
    Person(String name) { this.name = name; System.out.println("Person created"); }
}

class Employee extends Person
{
🎤 Viva questions (5)
Q. What is inheritance?
A. Acquiring the properties and methods of one class into another using extends.
Q. Does Java support multiple inheritance with classes?
A. No; a class can extend only one class. Interfaces are used instead.
Q. What is the use of super?
A. To call the parent constructor (super()) or a parent method/field (super.x).
Q. What is method overriding?
A. A child class giving its own version of a parent method with the same signature.
Q. In which order are constructors called in multilevel inheritance?
A. From the top parent class down to the child class.

Practical 9Compulsory

Implementation of interface

Aim: Declare interfaces, implement them in classes and achieve multiple inheritance through interfaces.

QWrite a program to implement an interface.

Showing answer A of 3 · tap A, B or C to see the others

Output

Circle     area =   12.57  perimeter =  12.57
Rectangle  area =   24.00  perimeter =  20.00
interface Shape
{
    double PI = 3.14159;              // public static final by default
    double area();                    // public abstract by default
    double perimeter();
}

class Circle implements Shape
🎤 Viva questions (5)
Q. What is an interface?
A. A reference type with abstract methods and constants that a class implements.
Q. Why are interface methods public?
A. They are public abstract by default, so implementing methods must also be public.
Q. How does Java achieve multiple inheritance?
A. A class can implement more than one interface.
Q. What is the difference between an abstract class and an interface?
A. An abstract class can have state and constructors; a class implements many interfaces but extends one class.
Q. Can we create an object of an interface?
A. No, but an interface reference can point to an object of an implementing class.

Practical 10Compulsory

Built-in packages and user-defined packages

Aim: Import classes from Java packages and create your own package.

Q1Program 1: use built-in packages.

Showing answer A of 3 · tap A, B or C to see the others

Output

sqrt(144)   = 12.0
pow(2, 10)  = 1024.0
max(7, 19)  = 19
Sorted list = [10, 20, 30, 40]
Date        = 28-10-2026
Day         = WEDNESDAY
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;

public class Main
{
    public static void main(String[] args)

Q2Program 2: create and use a user-defined package.

Showing answer A of 3 · tap A, B or C to see the others

Output

add(12, 30)        = 42
multiply(6, 7)     = 42
average(4, 8, 15)  = 9.0
// FILE: mypack/Calculator.java
package mypack;

public class Calculator
{
    public int add(int a, int b) { return a + b; }
    public int multiply(int a, int b) { return a * b; }
    public double average(int... nums)
🎤 Viva questions (5)
Q. What is a package?
A. A group of related classes and interfaces, stored in a folder with the same name.
Q. Which package is imported by default?
A. java.lang
Q. How do you compile a class that is in a package?
A. javac -d . FileName.java — -d creates the package folders.
Q. What is the difference between import java.util.* and import java.util.Scanner?
A. The first imports all classes of java.util, the second only Scanner.
Q. What is default (package) access?
A. A member with no modifier is visible only inside its own package.

Practical 11

Exception handling with try, catch and finally

Aim: Handle run-time errors with try, catch (single and multiple) and finally.

QWrite a program to implement try, catch and finally blocks.

Showing answer A of 3 · tap A, B or C to see the others

Output

Enter two numbers: 20 0
Error: / by zero
finally block: always runs
Program continues normally.
import java.util.Scanner;

public class Main
{
    public static void main(String[] args)
    {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter two numbers: ");
🎤 Viva questions (5)
Q. What is an exception?
A. An error event at run time that stops the normal flow of the program.
Q. What is the use of finally?
A. It always runs, so it is used to close files, connections etc.
Q. Can we have try without catch?
A. Yes, try with finally only (or try-with-resources).
Q. Why must catch(Exception e) come last?
A. Otherwise the specific catch blocks below it can never be reached (compile error).
Q. Name two unchecked exceptions.
A. ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.

Practical 12Compulsory

throw and throws clauses

Aim: Throw exceptions with throw, declare them with throws and create your own exception class.

QWrite a program to implement the throw and throws clauses.

Showing answer A of 3 · tap A, B or C to see the others

Output

Enter two ages: 21 16
Age 21: eligible to vote
Exception: Age 16 is below 18, cannot vote
import java.util.Scanner;

class InvalidAgeException extends Exception
{
    InvalidAgeException(String msg) { super(msg); }
}

public class Main
🎤 Viva questions (5)
Q. What is the difference between throw and throws?
A. throw throws an exception object inside a method; throws declares possible exceptions in the method signature.
Q. How do you create a user-defined exception?
A. Create a class that extends Exception (checked) or RuntimeException (unchecked).
Q. What is a checked exception?
A. An exception checked at compile time that must be caught or declared, e.g. IOException.
Q. Can we throw more than one exception with throws?
A. Yes, separated by commas: throws IOException, SQLException.
Q. What does super(msg) do in an exception class?
A. It stores the message so getMessage() can return it.

Practical 13Compulsory

Multithreading

Aim: Create threads by extending Thread and implementing Runnable, use sleep, join, priority and synchronization.

QWrite a program to implement multithreading.

Showing answer A of 3 · tap A, B or C to see the others

Output

Even: 2
Odd : 1
Even: 4
Odd : 3
Even: 6
Odd : 5
Even: 8
Odd : 7
Even: 10
Odd : 9
Both threads finished.
class EvenThread extends Thread
{
    public void run()
    {
        for (int i = 2; i <= 10; i += 2)
        {
            System.out.println("Even: " + i);
            try { Thread.sleep(300); } catch (InterruptedException e) { }
🎤 Viva questions (5)
Q. What are the two ways to create a thread?
A. Extend the Thread class, or implement the Runnable interface.
Q. What is the difference between start() and run()?
A. start() creates a new thread that calls run(); calling run() directly runs it in the current thread.
Q. What does join() do?
A. Makes the current thread wait until the other thread finishes.
Q. What is synchronization?
A. Allowing only one thread at a time to access shared code/data, to avoid wrong results.
Q. Name the states of a thread.
A. New, Runnable, Running, Blocked/Waiting, Terminated (Dead).

Practical 14Compulsory

Design a form using AWT components

Aim: Use Frame, Label, TextField, TextArea, Checkbox, CheckboxGroup, Choice, List and Button to design a form.

QWrite a program to design any type of form using AWT components.

Showing answer A of 3 · tap A, B or C to see the others

Output

A window titled "Student
Registration" (420 × 420) opens
with:
Name      [ Sneha Patil            ]
Gender    (•) Male   ( ) Female
Branch    [ Computer ▼ ]
Hobbies   [✓] Coding  [ ] Sports
Address   [ Shivaji Nagar, Pune    ]
[ Submit ]  [ Reset ]
Clicking × closes the window.
import java.awt.*;
import java.awt.event.*;

public class Main extends Frame
{
    Main()
    {
        setTitle("Student Registration");
🎤 Viva questions (5)
Q. What is AWT?
A. Abstract Window Toolkit — Java's original package (java.awt) for GUI components.
Q. What is the difference between Frame and Panel?
A. Frame is a top-level window with title bar; Panel is a container placed inside another container.
Q. How do you make radio buttons in AWT?
A. Put Checkbox objects in a CheckboxGroup.
Q. What is the default layout of Frame and Panel?
A. Frame: BorderLayout; Panel: FlowLayout.
Q. Why does an AWT Frame not close on ×?
A. We must add a WindowListener and call dispose() or System.exit() in windowClosing().

Practical 15

Menu bar with menu items and sub-menu items

Aim: Create a menu bar with menus, menu items, a sub-menu, separators and shortcut keys.

QWrite a program to create a menu bar with various menu items and sub-menu items.

Showing answer A of 3 · tap A, B or C to see the others

Output

A window titled "AWT Menu Demo"
opens with a menu bar: File  Edit
Help.
File contains: New, Open, Open
Recent ▸ (notes.txt, marks.csv),
———, Exit.
Edit contains: Cut, Copy, Paste, ✓
Word wrap.
Help contains: About.
The text area says "Click File >
Open Recent to see the sub-menu."
import java.awt.*;
import java.awt.event.*;

public class Main extends Frame
{
    Main()
    {
        super("AWT Menu Demo");
🎤 Viva questions (5)
Q. Which classes are used to create a menu in AWT?
A. MenuBar, Menu, MenuItem, CheckboxMenuItem.
Q. How is a sub-menu created?
A. By adding a Menu (or JMenu) object to another Menu.
Q. Which method attaches a menu bar to a JFrame?
A. setJMenuBar() (setMenuBar() for an AWT Frame).
Q. What is a mnemonic?
A. An Alt-key shortcut that opens a menu, e.g. Alt+F.
Q. What is an accelerator?
A. A key combination like Ctrl+S that runs a menu item directly.

Practical 16

BorderLayout with four buttons using Swing

Aim: Place buttons "left", "right", "top", "bottom" (and centre) with BorderLayout.

QWrite a program to demonstrate the use of border layout using four buttons labelled "left", "right", "top" and "bottom".

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Border Layout":
┌────────── top ──────────┐
│ left │   (empty)   │ right │
└───────── bottom ────────┘
top and bottom stretch across the
width; left and right fill the
height between them.
import java.awt.BorderLayout;
import javax.swing.*;

public class Main
{
    public static void main(String[] args)
    {
        JFrame f = new JFrame("Border Layout");
🎤 Viva questions (5)
Q. What are the five regions of BorderLayout?
A. NORTH, SOUTH, EAST, WEST, CENTER.
Q. What happens if two components are added to the same region?
A. Only the last one is shown.
Q. Which region gets the extra space?
A. CENTER.
Q. What is the default layout of JFrame?
A. BorderLayout.
Q. What do the two numbers in new BorderLayout(10, 10) mean?
A. Horizontal and vertical gaps between regions.

Practical 17Compulsory

Calculator using GridLayout (Swing)

Aim: Arrange calculator buttons with GridLayout and handle their clicks.

QWrite a program to create a calculator using grid layout.

Showing answer A of 3 · tap A, B or C to see the others

Output

A window titled "Calculator": a
large display at the top showing 48
(the demo 12 * 4 =),
and below it a 4 × 4 grid of
buttons:
7 8 9 /
4 5 6 *
1 2 3 -
C 0 = +
Clicking digits and operators works
like a normal calculator; C clears;
dividing by 0 shows "Error".
import java.awt.*;
import javax.swing.*;

public class Main extends JFrame
{
    JTextField display = new JTextField("0");
    double first = 0;
    String op = "";
🎤 Viva questions (5)
Q. What is GridLayout?
A. A layout that arranges components in a grid of equal-size rows and columns.
Q. What do the parameters of GridLayout(4, 4, 6, 6) mean?
A. rows, columns, horizontal gap, vertical gap.
Q. Which listener handles a button click?
A. ActionListener, method actionPerformed(ActionEvent e).
Q. Why is the display text field set not editable?
A. So the user can enter numbers only through the buttons.
Q. How do you convert a text field value into a number?
A. Double.parseDouble(field.getText()) or Integer.parseInt().

Practical 18

JComboBox in a JFrame

Aim: Show a list of choices with JComboBox and respond to the selected item.

QWrite a program to demonstrate the use of JComboBox in a JFrame.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "States": "State:"
[Maharashtra ▼] and the label
"Capital of Maharashtra is Mumbai".
Choosing Karnataka changes the label
to "Capital of Karnataka is
Bengaluru".
import java.awt.*;
import javax.swing.*;

public class Main
{
    public static void main(String[] args)
    {
        String[] states = {"Maharashtra", "Gujarat", "Karnataka", "Tamil Nadu", "Madhya Pradesh"};
🎤 Viva questions (5)
Q. What is JComboBox?
A. A Swing component that combines a drop-down list with an optional text field.
Q. How do you get the selected item?
A. getSelectedItem() (or getSelectedIndex() for its position).
Q. How do you add and remove items?
A. addItem(), removeItem(), removeItemAt(), removeAllItems().
Q. What does setEditable(true) do?
A. Lets the user type a value that is not in the list.
Q. Which listener is used for JComboBox selection?
A. ActionListener (or ItemListener).

Practical 19

JTree and JTable

Aim: Show hierarchical data with JTree and tabular data with JTable.

Q1Program 1: demonstrate the use of JTree.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "College Tree" shows:
Polytechnic
  ▾ Computer    First Year    Second
  Year    Third Year
  ▸ Information Technology
  Mechanical
Clicking ▸ Information Technology
opens Second Year and Third Year.
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;

public class Main
{
    public static void main(String[] args)
    {
        DefaultMutableTreeNode college = new DefaultMutableTreeNode("Polytechnic");

Q2Program 2: demonstrate the use of JTable.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Marks Table" with a grid:
Roll | Name   | Java | DBMS | OS
1    | Aarav  | 78   | 82   | 69
2    | Bhavna | 88   | 75   | 91
3    | Chetan | 64   | 70   | 58
4    | Diya   | 92   | 89   | 85
5    | Eshan  | 55   | 61   | 73
Cells can be clicked and edited;
columns can be resized by dragging
the header.
import javax.swing.*;

public class Main
{
    public static void main(String[] args)
    {
        String[] cols = {"Roll", "Name", "Java", "DBMS", "OS"};
        Object[][] rows = {
🎤 Viva questions (5)
Q. What is JTree used for?
A. To show data in a hierarchy (parent and child nodes), like folders.
Q. Which class creates a tree node?
A. DefaultMutableTreeNode.
Q. Why is a JTable placed inside a JScrollPane?
A. To show the column headers and allow scrolling.
Q. What is DefaultTableModel?
A. A table model that lets you add, remove and change rows at run time.
Q. How do you read a cell value from a JTable?
A. table.getValueAt(row, column).

Practical 20Compulsory

Key events and mouse events

Aim: Handle keyboard and mouse events with KeyListener, MouseListener and MouseMotionListener.

Q1Program 1: demonstrate key events.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Key Events" with a text
field and three labels.
Typing "J" with Shift shows: Typed:
J   Pressed: J  (code 74)
Released: J
Pressing Shift alone shows: Pressed:
Shift  (code 16) — no "Typed" event
for Shift.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JFrame implements KeyListener
{
    JTextField input = new JTextField(20);
    JLabel typed = new JLabel("Typed: ");

Q2Program 2: demonstrate mouse events.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Mouse Events": a light blue
area with the status bar "Move or
click the mouse inside the window".
When the mouse enters, the area
turns light green; moving shows
"Moving at (x, y)";
clicking shows "Clicked at (x, y),
clicks: 1"; leaving turns it light
blue again.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JFrame implements MouseListener, MouseMotionListener
{
    JLabel status = new JLabel(" Move or click the mouse inside the window");
    JPanel area = new JPanel();
🎤 Viva questions (5)
Q. Which methods does KeyListener have?
A. keyPressed(), keyReleased(), keyTyped().
Q. Which methods does MouseListener have?
A. mouseClicked(), mousePressed(), mouseReleased(), mouseEntered(), mouseExited().
Q. What is an adapter class?
A. A class with empty listener methods, so you override only the ones you need (KeyAdapter, MouseAdapter).
Q. Which listener gives mouseMoved and mouseDragged?
A. MouseMotionListener.
Q. What is the difference between getKeyChar() and getKeyCode()?
A. getKeyChar() gives the typed character; getKeyCode() gives the virtual key code (VK_...).

Practical 21Compulsory

Action events using Swing components

Aim: Handle ActionEvent from JButton, JTextField, JCheckBox and JRadioButton.

QWrite a program to demonstrate action events in a frame using Swing components.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Login":
Username [student]
Password [•••••••]
[ Login ] [ Clear ]        Login
  successful   (green)
A wrong password shows "Wrong
username or password" in red; Clear
empties the fields.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Main extends JFrame implements ActionListener
{
    JTextField user = new JTextField(12);
    JPasswordField pass = new JPasswordField(12);
🎤 Viva questions (5)
Q. Which interface handles action events?
A. ActionListener, with the method actionPerformed(ActionEvent e).
Q. Which components generate ActionEvent?
A. JButton, JTextField (on Enter), JCheckBox, JRadioButton, JMenuItem, JComboBox.
Q. What does e.getSource() return?
A. The component object that generated the event.
Q. What is getActionCommand()?
A. The command string of the event, by default the button text.
Q. Why use ButtonGroup?
A. To make radio buttons mutually exclusive.

Practical 22

Text events on text components

Aim: React to every change in a text component using TextListener (AWT) and DocumentListener (Swing).

QWrite a program to demonstrate text events on text components.

Showing answer A of 3 · tap A, B or C to see the others

Output

Window "Text Event":
[Hello MSBTE]
You typed: Hello MSBTE
Length: 11
Both labels update with every letter
typed or deleted.
import java.awt.*;
import java.awt.event.*;

public class Main extends Frame implements TextListener
{
    TextField tf = new TextField(20);
    Label echo = new Label("You typed: ");
    Label len = new Label("Length: 0");
🎤 Viva questions (5)
Q. Which listener handles TextEvent?
A. TextListener, with the method textValueChanged(TextEvent e).
Q. Which components generate TextEvent?
A. AWT TextField and TextArea.
Q. How do you detect text changes in a Swing JTextField?
A. Add a DocumentListener to its Document.
Q. What are the methods of DocumentListener?
A. insertUpdate(), removeUpdate(), changedUpdate().
Q. What is the difference between ActionEvent and TextEvent on a text field?
A. ActionEvent comes only on Enter; TextEvent comes on every change.

Practical 23

Retrieve host name and IP address using InetAddress

Aim: Use the InetAddress class to find the name and IP address of the local machine and of other hosts.

QWrite a program to retrieve the host name and IP address using the InetAddress class.

Showing answer A of 3 · tap A, B or C to see the others

Output

Local host     : LAB-PC-12/192.168.1.12
Host name      : LAB-PC-12
IP address     : 192.168.1.12
Loopback name  : localhost
Loopback IP    : 127.0.0.1
Is loopback?   : true
import java.net.InetAddress;
import java.net.UnknownHostException;

public class Main
{
    public static void main(String[] args)
    {
        try
🎤 Viva questions (5)
Q. What is InetAddress?
A. A class in java.net that represents an IP address (and its host name).
Q. How do you get the IP address of your own computer?
A. InetAddress.getLocalHost().getHostAddress().
Q. Which exception do InetAddress methods throw?
A. UnknownHostException.
Q. What is the loopback address?
A. 127.0.0.1 (localhost) — it always means the same machine.
Q. What is DNS?
A. Domain Name System — it converts host names into IP addresses.

Practical 24Compulsory

Methods of the URL class and the URLConnection class

Aim: Split a URL into its parts and use URLConnection to read header information and content.

QWrite a program to demonstrate the use of the URL and URLConnection classes and their methods.

Showing answer A of 3 · tap A, B or C to see the others

Output

URL          : https://www.msbte.org.in:443/results/index.php?seat=245781&exam=W26#top
Protocol     : https
Host         : www.msbte.org.in
Port         : 443
Default port : 443
Path         : /results/index.php
File         : /results/index.php?seat=245781&exam=W26
Query        : seat=245781&exam=W26
Ref (anchor) : top
Authority    : www.msbte.org.in:443
import java.net.URI;
import java.net.URL;

public class Main
{
    public static void main(String[] args) throws Exception
    {
        URL u = new URI("https://www.msbte.org.in:443/results/index.php?seat=245781&exam=W26#top").toURL();
🎤 Viva questions (5)
Q. What is a URL?
A. Uniform Resource Locator — the address of a resource on the internet.
Q. Name four methods of the URL class.
A. getProtocol(), getHost(), getPort(), getFile() (also getPath(), getQuery(), getRef()).
Q. What does getPort() return when no port is given?
A. -1 (getDefaultPort() gives 80/443).
Q. How do you get a URLConnection object?
A. By calling openConnection() on a URL object.
Q. What is the difference between URL and URLConnection?
A. URL only describes the address; URLConnection actually connects and reads/writes data.

Practical 25Compulsory

Connection-oriented communication using sockets (TCP)

Aim: Write a server with ServerSocket and a client with Socket that exchange messages over TCP.

QWrite a program to demonstrate connection-oriented communication using sockets.

Showing answer A of 3 · tap A, B or C to see the others

Output

--- Server window ---
Server waiting on port 5000...
Client connected from 127.0.0.1
Client says: Priya Deshmukh
Server closed

--- Client window ---
Connected to server
Enter your name: Priya Deshmukh
Server replied: Hello Priya Deshmukh, welcome to the JPR server!
// FILE: Server.java
import java.io.*;
import java.net.*;

public class Server
{
    public static void main(String[] args) throws IOException
    {
🎤 Viva questions (5)
Q. What is a socket?
A. One end-point of a two-way connection between two programs on a network (IP + port).
Q. Which classes are used for TCP in Java?
A. ServerSocket (server) and Socket (client).
Q. What does accept() do?
A. Waits for a client and returns a Socket connected to it.
Q. What is a port number?
A. A number (0–65535) that identifies a program/service on a computer.
Q. Why is TCP called connection-oriented?
A. A connection is set up before data is sent, and delivery and order are guaranteed.

Practical 26

Sending and receiving data using datagrams (UDP)

Aim: Use DatagramSocket and DatagramPacket to send and receive messages without a connection.

QWrite a program to send and receive data through datagrams.

Showing answer A of 3 · tap A, B or C to see the others

Output

--- Receiver window ---
Receiver waiting on port 6000...
Received: Practical 26 works
From 127.0.0.1 port 59684

--- Sender window ---
Message to send: Practical 26 works
Sent 18 bytes
// FILE: Receiver.java
import java.net.*;

public class Receiver
{
    public static void main(String[] args) throws Exception
    {
        DatagramSocket ds = new DatagramSocket(6000);
🎤 Viva questions (5)
Q. What is a datagram?
A. An independent, self-contained packet sent over UDP without a connection.
Q. Which classes are used for UDP?
A. DatagramSocket and DatagramPacket.
Q. What is the difference between TCP and UDP?
A. TCP is connection-oriented and reliable; UDP is connectionless, faster, but delivery is not guaranteed.
Q. Which method waits for a packet?
A. DatagramSocket.receive(packet).
Q. Give one use of UDP.
A. Video/voice streaming, online games, DNS.

Practical 27Compulsory

Create a sample database and connect to it (JDBC)

Aim: Create a MySQL database and table from Java and connect using the JDBC driver.

QWrite a program to create a sample database in any DBMS and connect to it.

Showing answer A of 3 · tap A, B or C to see the others

  1. Install MySQL Server (or XAMPP, which includes MySQL/MariaDB) and note the root password.
  2. Download "Connector/J" (mysql-connector-j-*.jar) from dev.mysql.com/downloads/connector/j (Platform Independent).
  3. Put the jar next to your program (or add it to the IDE build path).
  4. Compile: javac Main.java
  5. Run on Windows: java -cp .;mysql-connector-j-9.1.0.jar Main (on Linux/Mac use : instead of ;)

Output

Connected successfully!
Database product : MySQL
Driver           : MySQL Connector/J
Driver version   : mysql-connector-j-8.4.0 (Revision: 1c3f5c149e0bfe31c7fbeb24e2d260cd890972c4)
User             : root@localhost
import java.sql.*;

public class Main
{
    public static void main(String[] args)
    {
        String url = "jdbc:mysql://localhost:3306/";
        try (Connection con = DriverManager.getConnection(url, "root", "root"))
🎤 Viva questions (5)
Q. What is JDBC?
A. Java Database Connectivity — an API (java.sql) to connect Java programs to databases.
Q. What are the steps to connect to a database?
A. Load the driver, get a Connection, create a Statement, execute SQL, process the ResultSet, close.
Q. What is a JDBC driver?
A. Software (a JAR) that converts JDBC calls into the database's own protocol, e.g. MySQL Connector/J.
Q. Which driver type is MySQL Connector/J?
A. Type 4 (pure Java, thin driver).
Q. What is the difference between executeQuery and executeUpdate?
A. executeQuery runs SELECT and returns a ResultSet; executeUpdate runs INSERT/UPDATE/DELETE/DDL and returns a row count.

Practical 28Compulsory

Database operations: insert, update and delete records

Aim: Insert, update and delete records in the student table using JDBC.

QWrite a program to insert, update and delete a record in a database.

Showing answer A of 3 · tap A, B or C to see the others

Output

Inserted rows: 1
Updated rows : 1
Deleted rows : 1
Table now:
  1 | Aarav Kulkarni | CO | 78.5
  2 | Bhavna Jadhav | IF | 84.2
  3 | Chetan More | CO | 70.5
  4 | Diya Shinde | AI | 91.4
  6 | Farhan Shaikh | CO | 72.6
import java.sql.*;

public class Main
{
    static void show(Statement st) throws SQLException
    {
        ResultSet rs = st.executeQuery("SELECT * FROM student ORDER BY roll");
        while (rs.next())
🎤 Viva questions (5)
Q. Which method is used for INSERT, UPDATE and DELETE?
A. executeUpdate().
Q. What does executeUpdate() return?
A. The number of rows affected.
Q. What is auto-commit?
A. By default every SQL statement is saved (committed) immediately.
Q. What is rollback?
A. Undoing the uncommitted changes of a transaction.
Q. What is SQL injection?
A. An attack where user input changes the SQL command; avoid it with PreparedStatement.

Practical 29

PreparedStatement

Aim: Use PreparedStatement with ? parameters for insert, update, select and batch operations.

QWrite a program to demonstrate the use of PreparedStatement.

Showing answer A of 3 · tap A, B or C to see the others

Output

How many students to add? 2
Roll: 6
Full name: Gauri D'Souza
Branch: CO
Percentage: 81.3
1 row inserted
Roll: 7
Full name: Harsh Wagh
Branch: AI
Percentage: 74.9
1 row inserted
import java.sql.*;
import java.util.Scanner;

public class Main
{
    public static void main(String[] args) throws SQLException
    {
        Scanner sc = new Scanner(System.in);
🎤 Viva questions (5)
Q. What is PreparedStatement?
A. A precompiled SQL statement with ? parameters (sub-interface of Statement).
Q. Why is PreparedStatement better than Statement?
A. Faster for repeated SQL and safe from SQL injection.
Q. How are parameters set?
A. With setInt(), setString(), setDouble()… using the parameter index starting at 1.
Q. What is CallableStatement?
A. Used to call stored procedures in the database.
Q. What do addBatch() and executeBatch() do?
A. Collect several executions and send them together.

Practical 30Compulsory

Retrieve data using the ResultSet interface and its navigation methods

Aim: Read records with ResultSet and move through them with next, previous, first, last, absolute and relative.

QWrite a program to retrieve data using the ResultSet interface (navigation methods).

Showing answer A of 3 · tap A, B or C to see the others

Output

first()        -> row 1: 1 Aarav Kulkarni (78.5%)
last()         -> row 5: 5 Eshan Pawar (59.8%)
previous()     -> row 4: 4 Diya Shinde (91.4%)
absolute(2)    -> row 2: 2 Bhavna Jadhav (84.2%)
relative(2)    -> row 4: 4 Diya Shinde (91.4%)
absolute(-2)   -> row 4: 4 Diya Shinde (91.4%)
Forward with next():
  1 Aarav Kulkarni
  2 Bhavna Jadhav
  3 Chetan More
  4 Diya Shinde
  5 Eshan Pawar
isAfterLast(): true
import java.sql.*;

public class Main
{
    static void print(String how, ResultSet rs) throws SQLException
    {
        System.out.printf("%-14s -> row %d: %d %s (%.1f%%)%n", how, rs.getRow(),
                rs.getInt("roll"), rs.getString("name"), rs.getDouble("percentage"));
🎤 Viva questions (5)
Q. What is a ResultSet?
A. An object that holds the rows returned by a SELECT query, with a cursor pointing to one row.
Q. Where is the cursor at the start?
A. Before the first row; call next() to move to the first row.
Q. Name the navigation methods of ResultSet.
A. next(), previous(), first(), last(), absolute(n), relative(n), beforeFirst(), afterLast().
Q. How do you make a ResultSet scrollable?
A. createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY).
Q. What is ResultSetMetaData?
A. Information about the columns of a ResultSet: count, names, types.

Tick the answers you want in your file

YOUR DIPLOMA, STEP BY STEP

Save this page — everything till your final year is here

Free practicals, micro projects and question papers for your semesters — and when your final year comes, ready projects with report, setup and viva help.

📲 Your class needs this too

Send it to your class WhatsApp group — practical file done in minutes for everyone, free.