0% found this document useful (0 votes)
23 views33 pages

Java See Laqs

The document explains the MVC (Model-View-Controller) architecture, detailing its components and providing a simple example program. It also covers event handling in Java, including mouse and key events, adapter classes, applets, and differences between applets and applications. Additionally, it discusses the delegation event model, AWT vs Swing, JComboBox, servlets, and JDBC, including its architecture and types of drivers.

Uploaded by

Nawaz Khadar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views33 pages

Java See Laqs

The document explains the MVC (Model-View-Controller) architecture, detailing its components and providing a simple example program. It also covers event handling in Java, including mouse and key events, adapter classes, applets, and differences between applets and applications. Additionally, it discusses the delegation event model, AWT vs Swing, JComboBox, servlets, and JDBC, including its architecture and types of drivers.

Uploaded by

Nawaz Khadar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

UNIT-4

Q1 Explain the concept of MVC with an example program

MVC (Model-View-Controller) Architecture:

Model: Manages data and business logic.


View: Displays data (UI). 
Controller: Handles user input and update’s model/view.

Diagram:
+ + + + + + | Model | <---->| Controller |<----> | View | + + + + + +

✅ 1. Model (student.py)

class Student:

def __init__(self, name, roll):

self.name = name

self.roll = roll

def get_details(self):
return f"Name: {self.name}, Roll: {self.roll}"

✅ 2. View (view.py)

class StudentView:

def display_student(self, student_details):

print("Student Info:")
print(student_details)

✅ 3. Controller (controller.py)

class StudentController:
def __init__(self, model, view):

self.model = model

self.view = view

def update_student_name(self, name):

self.model.name = name

def show_student(self):
details = self.model.get_details()

self.view.display_student(details)

✅ 4. Main Program (main.py)

from student import Student

from view import StudentView


from controller import StudentController

# Create objects

model = Student("Alice", 101)

view = StudentView()

controller = StudentController(model, view)

# Show student info

controller.show_student()

# Update name and show again

controller.update_student_name("Bob")

controller.show_student()

✅ Output:
Student Info:

Name: Alice, Roll: 101

Student Info:

Name: Bob, Roll: 101

💡 Benefits of MVC:

 Easy to maintain and update code.

 Separation of logic (Model), UI (View), and control flow (Controller).

 Scalable and testable.

Q2. Explain Event Handling in Java and describe methods of


mouse event and key event.

Event Handling in Java is a mechanism that allows a program to respond to user


interactions such as clicking a button, moving a mouse, or pressing a key.
Java uses the Event Delegation Model for handling events. It involves three main
components:
1. Event Source – The component that generates the event (e.g., Button,
Frame).
2. Event Object – Contains information about the event (e.g., MouseEvent,
KeyEvent).
3. Event Listener – Interface that receives and handles the event (e.g.,
MouseListener).

🔹 Methods of MouseListener Interface:

Method Description

mouseClicked(MouseEvent e) Called when mouse is clicked

mousePressed(MouseEvent e) Called when mouse button is pressed


Method Description

mouseReleased(MouseEvent e) Called when mouse button is released

mouseEntered(MouseEvent e) Called when mouse enters a component

mouseExited(MouseEvent e) Called when mouse exits a component

✅ Example:

public void mouseClicked(MouseEvent e) {


System.out.println("Mouse clicked at:" + e.getX() + "," + e.getY());
}

Q3. Explain Key Handling in Java with program

🔹 1. Explanation of Key Handling in Java

Key handling in Java means detecting and responding to keyboard actions (like
pressing a key). It is part of event handling in Java GUI applications.

To handle key events, Java provides:


 Event Class: KeyEvent – stores information about the key action.

 Listener Interface: KeyListener – provides methods to handle key events.

🔹 KeyListener Interface Methods:

Method Description

keyPressed(KeyEvent e) Called when a key is pressed down

keyReleased(KeyEvent e) Called when a key is released

keyTyped(KeyEvent e) Called when a key is typed (pressed & released)

To use key handling, a component must:

 Register with addKeyListener(...)

 Override the above methods

🔹 2. Example
public void keyPressed(KeyEvent e) {
System.out.println("Key pressed: " + e.getKeyChar());
}

Q4. Adapter class with program

🔹 1. What is an Adapter Class? (2 Marks)

An adapter class in Java is a predefined abstract class that provides empty


implementations for all methods of an event listener interface.

When you don’t want to implement all methods of a listener interface, you can
extend the adapter class and override only the needed methods.

📌 Common Adapter Classes:

 MouseAdapter (for MouseListener)

 KeyAdapter (for KeyListener)

 WindowAdapter (for WindowListener)

 FocusAdapter (for FocusListener)

🔹 2. Why Use Adapter Class?

 To avoid writing unnecessary empty method bodies


 Makes event handling simpler and cleaner

🔹 3. Example Program using MouseAdapter (4 Marks)

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

import javax.swing.*;

public class AdapterExample extends JFrame {

AdapterExample() {

JLabel label = new JLabel("Click anywhere");


label.setBounds(50, 50, 200, 30);
add(label);

addMouseListener(new MouseAdapter() {

public void mouseClicked(MouseEvent e) {

label.setText("Clicked at (" + e.getX() + ", " + e.getY() + ")");

});

setSize(300, 200);

setLayout(null);
setVisible(true);

setDefaultCloseOperation(EXIT_ON_CLOSE);

public static void main(String[] args) {

new AdapterExample();

✅ Output:

When the user clicks anywhere in the window, the label shows the click position:

Mouse Clicked at (123, 85)

Q5. Applet def, creation , methods and life cycle

🔹 1. Definition of Applet (1 Mark)

An applet is a small Java program that runs inside a web browser or applet
viewer.
It is used to create interactive web applications and GUI-based programs.

📌 Unlike standalone Java applications (with main()), applets do not have main().
Instead, they use special life cycle methods.
🔹 2. How to Create an Applet (1 Mark)

To create an applet:
1. Extend Applet or JApplet class.

2. Override life cycle methods like init(), start(), paint(), etc.

3. Compile the .java file and run using appletviewer or embed in HTML.

📌 Import Required Packages:

import java.applet.*;

import java.awt.*;

🔹 3. Life Cycle Methods of Applet (2 Marks)

Method Purpose

init() Called once when the applet is first loaded.

start() Called every time the applet becomes visible (e.g., reload).

paint(Graphics g) Called to draw graphics or text.

stop() Called when the applet is hidden or moved to background.

destroy() Called when the applet is closed or unloaded completely.

🔹 4. Simple Applet Program (2 Marks)

import java.applet.*;

import java.awt.*;

/* <applet code="MyApplet" width=300 height=200></applet> */

public class MyApplet extends Applet {

public void init() {

setBackground(Color.yellow);

public void start() {


}
public void paint(Graphics g) {

g.drawString("Hello from Applet!", 100, 100);

public void stop() {

public void destroy() {

🔹 To Run the Applet:

1. Save as MyApplet.java
2. Compile:

3. javac MyApplet.java

4. Run using applet viewer:


5. appletviewer MyApplet.java

Q6. Differences between applet and application

Feature Applet Application

Runs in a browser or
1. Execution Runs as a standalone program
applet viewer

2. main() Method No main() method used Requires a main() method

Uses AWT (Abstract


3. GUI Library Can use AWT, Swing, or JavaFX
Window Toolkit)

4. Security Runs in sandbox, with Has full access to system


Restrictions restricted access resources

5. Life Cycle Uses init(), start(), paint(), No predefined life cycle methods,
Methods stop(), destroy() controlled by user

Used for web-based GUI Used for general-purpose


6. Use Case
programs desktop programs
🔹 Example Use Cases:

 Applet: Online calculators, interactive animations in web pages

 Application: Inventory systems, desktop software, games, etc.

Q7. Delagation event model(event, event source and event


listeners)

🔹 1. What is the Delegation Event Model? (2 Marks)

The Delegation Event Model is Java’s way of handling events like mouse clicks,
key presses, or button actions.
It separates event generation from event handling using three main components:

📌 The event is generated by a source and handled by a listener.

🔹 2. Components of Delegation Event Model (4 Marks)

Component Description Example

Event A button (Button),


The component that generates the event.
Source window, etc.

An instance of a class from java.awt.event ActionEvent,


Event Object
that holds event data. MouseEvent

Event An interface that receives and handles the ActionListener,


Listener event. MouseListener

🔹 How It Works:

1. A GUI component (like a button) is the event source.

2. When the user interacts (like clicking), it generates an event object (e.g.,
ActionEvent).
3. The event object is sent to the registered listener.
4. The listener executes the code to handle the event.
Q8. Program on check box and Text field

import java.awt.*;

import java.awt.event.*;

public class CheckBoxTextField {

public static void main(String[] args) {

Frame f = new Frame();

Checkbox cb = new Checkbox("Accept");


TextField tf = new TextField(20);

cb.addItemListener(e -> tf.setText(cb.getState() ? "Checked" : "Unchecked"));

f.add(cb);
f.add(tf);

f.setLayout(new FlowLayout());

f.setSize(250, 100);
f.setVisible(true);
}

Q9. Awt def, Awt hierarchy n important components like label,


button, check box n checkbox group/radiobutton, list and choice

🔹 1. Definition of AWT (1 Mark)

AWT (Abstract Window Toolkit) is a set of GUI (Graphical User Interface)


components provided by Java for building window-based applications.

It is part of the java.awt package and allows you to create windows, buttons, labels,
checkboxes, etc.
🔹 2. AWT Class Hierarchy (2 Marks)

3. Important AWT Components (3 Marks)

Component Description

Label Displays a non-editable text on the screen.

Button Creates a clickable button for user actions.

Checkbox Allows selection of multiple options (like toggles).

Checkbox Used to create Radio Buttons (select only one option from a
Group group).

Text Field Allows the user to enter single-line text input.

List Displays a scrollable list of items (multiple selection possible).

Choice A drop-down menu with one item visible at a time.

Q10 Graphics class with program


🔹 Example:

import java.awt.*;

public class SimpleGraphics extends Frame {

public void paint(Graphics g) {

g.drawString("Hello", 100, 100);

g.drawRect(80, 120, 100, 50);

public static void main(String[] args) {

SimpleGraphics f = new SimpleGraphics();

f.setSize(300, 200);
f.setVisible(true);

UNIT-5

Q1. Diff between awt and swings

AWT (Abstract Window


No. Feature Swing
Toolkit)

1. Package java.awt javax.swing

Platform Platform-dependent (uses Platform-independent (pure


2.
Dependency native code) Java)

3. Component Type Heavyweight components Lightweight components

OS-based (cannot be Pluggable (can be


4. Look and Feel
changed) customized)
AWT (Abstract Window
No. Feature Swing
Toolkit)

Speed / Slower due to native


5. Faster UI rendering
Performance resource usage

Component Fewer components (no Rich set (JTable, JTree,


6.
Variety tables, trees, etc.) JTabbedPane, etc.)

Naming Components like Button, Components prefixed with J


7.
Convention Label, TextField (e.g., JButton)

Not very flexible or


8. Extensibility Highly flexible and extensible
extensible

Advanced Supports features like tooltips,


9. Lacks advanced features
Features tabbed panes

Event Handling Older delegation event Improved and simplified event


10.
Model model handling

Follows MVC (Model-View-


11. MVC Architecture Does not follow MVC strictly
Controller)

Uses more system


12. Resource Usage More efficient and lightweight
resources

Q2. Jcombobox with program

🔹 1. What is JComboBox? (2 Marks)

A JComboBox is a drop-down list component in Java Swing that allows users to


select one item from a list. It is part of the javax.swing package.

📌 Useful when you want a compact way to present multiple options (like gender,
country, etc.).

🔹 2. Basic Methods of JComboBox:

Method Description

addItem(Object item) Adds an item to the combo box


Method Description

getSelectedItem() Returns the currently selected item

Sets selected item


setSelectedItem(Object)
programmatically

🔹 3. Example Program using JComboBox (4 Marks)

import javax.swing.*;

public class ShortComboBox {

public static void main(String[] args) {

JFrame f = new JFrame();

JComboBox<String> cb = new JComboBox<>(new String[]{"Java", "Python",


"C++"});

JLabel l = new JLabel();

cb.addActionListener(e -> l.setText("Selected: " + cb.getSelectedItem()));

f.setLayout(new java.awt.FlowLayout());
f.add(cb); f.add(l);

f.setSize(250, 100); f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}

Q3. Servlet and it's life cycle


A Servlet is a Java class used to create dynamic web applications.
It runs on a web server (like Tomcat) and responds to HTTP requests, typically from
web browsers.

📌 Servlet is part of javax.servlet and javax.servlet.http packages.

🔹 2. Servlet Life Cycle (4 Marks)

The life cycle of a servlet is managed by the Servlet Container and includes 5 main
phases:
Phase Description

Called once when the servlet is first loaded; used for


init()
initialization.

Called every time the servlet handles a client request (GET,


service()
POST, etc.).

doGet() / Specific methods inside service() to handle HTTP GET or POST


doPost() requests.

Called once before the servlet is unloaded; used to release


destroy()
resources.

Called by the container before init(); used to create the servlet


Constructor
object.

Q4. JDBC definition, architecture


🔹 1. JDBC Definition (2 Marks)

JDBC (Java Database Connectivity) is a Java API that allows Java programs to
connect to and interact with databases (like MySQL, Oracle, etc.).

📌 JDBC helps perform operations like connecting to DB, executing SQL queries,
retrieving results, etc.

🔹 2. JDBC Architecture
JDBC follows a layered architecture with the following components:

🔸 JDBC Architecture Types:

There are two main models:

✅ A. Two-Tier Architecture

 Java application directly communicates with the database using JDBC Driver.

 Suitable for small applications.

Java Application → JDBC API → JDBC Driver → Database

✅ B. Three-Tier Architecture

 Introduces a middle-tier server (like a web server or application server).

 Used in enterprise applications.

Java Application → Web Server → JDBC API → Driver → Database

🔹 JDBC API Core Components:

Component Description

DriverManager Manages a list of database drivers

Connection Establishes a connection to the database

Statement Executes SQL queries

ResultSet Stores data retrieved from SELECT queries

SQLException Handles SQL errors

Q5. JDBC drivers with diagrams

🔹 What are JDBC Drivers?

JDBC drivers are software components that enable Java applications to interact
with databases.
They translate Java JDBC calls into DB-specific calls.

🔹 Types of JDBC Drivers


Driver
Name Description
Type

JDBC-ODBC Bridge Uses ODBC driver to connect to DB; requires


Type 1
Driver ODBC setup on client system.

Type 2 Native-API Driver Uses native DB client libraries; platform-dependent.

Network Protocol Sends requests to a middle-tier server; platform-


Type 3
Driver independent.

Thin Driver (Pure Communicates directly with DB using Java; fastest


Type 4
Java Driver) and platform-independent.

🔹 JDBC Driver Architecture Diagram (1 Mark)

Q6. Crud operations using JDBC

CRUD stands for the four basic operations performed on database tables:

 C – Create: Add new records to the database

 R – Read: Retrieve (or fetch) existing records

 U – Update: Modify existing records

 D – Delete: Remove records from the database


🔹 2. JDBC CRUD Operations Explained

Using JDBC (Java Database Connectivity), Java applications can interact with a
database and perform the following:

✅ 1. Create (Insert)

 Inserts new data into the database.


 Achieved using INSERT INTO SQL statements.

 JDBC uses the executeUpdate() method.

✅ 2. Read (Select)

 Retrieves data from the database.


 Performed using SELECT queries.

 JDBC uses the executeQuery() method, which returns a ResultSet.

✅ 3. Update

 Modifies existing data in a table.


 Performed using the UPDATE SQL command.

 JDBC again uses executeUpdate().

✅ 4. Delete

 Deletes specific records from the database.


 Done using the DELETE FROM statement.

 Uses executeUpdate() in JDBC.

Q7. Jlabel and Jtextfield with example

🔹 1. Definition (2 Marks)

 JLabel: A non-editable text component used to display a message or label


for other components (like input fields).
 JTextField: A single-line input field where the user can enter text.

🔹 2. Uses (1 Mark)

Component Use Example

JLabel "Enter Name:", "Email ID:"

JTextField To input user data

🔹 3. Common Methods (1 Mark)

Method Purpose

getText() Gets input from JTextField

setText(String) Sets or updates text

🔹 4. Simple Example Program

import javax.swing.*;

import java.awt.*;

public class LabelTextFieldExample {

public static void main(String[] args) {

JFrame f = new JFrame("Form");

JLabel lbl = new JLabel("Enter Name:");

JTextField tf = new JTextField(15);

f.setLayout(new FlowLayout());
f.add(lbl); f.add(tf);
f.setSize(250, 100);

f.setVisible(true);

f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

✅ Output:

 A window with:
o A label: "Enter Name:"

o A text field for user input.

UNIT-1

Q1.Assess why Java is considered a pure object-oriented


programming language

Java is often considered a pure object-oriented programming (OOP) language due to


the following reasons:

Point Explanation

In Java, all code (except for primitive types) must be written


1. Everything is part
inside classes. There is no concept of standalone functions
of a class
or variables outside a class.
Point Explanation

Almost everything in Java is treated as an object. Even


2. Object-based
features like threads, exceptions, and events are handled
design
using objects.

Java fully supports all four major OOP concepts:


3. Supports all OOP
Encapsulation, Inheritance, Polymorphism, and
principles
Abstraction.

4. Use of new
Objects in Java are explicitly created using the new
keyword for object
keyword, reinforcing the object-oriented nature.
creation

Java is a class-based language. Every function and variable


5. Class-based
belongs to a class, and object instances operate based on
architecture
these classes.

Java does not support global functions or variables outside


6. No global
of a class context. This ensures that all logic and data are
functions or variables
encapsulated in objects.

Q2. Differentiate different types of constructors with an example.

In Java, constructors are special methods used to initialize objects. There are mainly
three types of constructors:

🔸 1. Default Constructor

 A constructor with no parameters.

 Provided automatically by the compiler if no constructor is defined.


Example:

class Student {
Student() {
System.out.println("Default Constructor Called");

🔸 2. Parameterized Constructor

 A constructor that accepts arguments to initialize object with specific values.

Example:

class Student {

String name;

int age;

Student(String n, int a) {

name = n;

age = a;
}

🔸 3. Copy Constructor

 A constructor that creates a new object by copying values from another


object.
 Java does not provide this by default, but it can be user-defined.

Example:

class Student {

String name;

Student(Student s) {

name = s.name;

}
Q3. What is method overloading? Explain with an example.

3. What is Method Overloading? – 6 Marks

🔹 Definition:

Method Overloading is a feature in Java where multiple methods can have the
same name but different parameters (type, number, or order) within the same
class.
It increases readability and allows different ways to call a method based on input.

🔹 Key Points:

 Methods must differ in parameter list.

 Return type can be same or different (but return type alone cannot distinguish
overloaded methods).
 It is an example of compile-time (static) polymorphism.

🔹 Example:

class Calculator {

int add(int a, int b) {

return a + b;
}

// Overloaded method to add three integers

int add(int a, int b, int c) {

return a + b + c;

}
// Overloaded method to add two double values
double add(double a, double b) {
return a + b;

public class Main {

public static void main(String[] args) {

Calculator calc = new Calculator();

System.out.println(calc.add(10, 20)); // 30

System.out.println(calc.add(10, 20, 30)); // 60


System.out.println(calc.add(5.5, 4.5)); // 10.0

🔹 Benefits:

 Code becomes more flexible and understandable.

 Avoids writing multiple method names for similar tasks.

Q4. Discuss about the constructor overloading with an example


program.

🔹 Definition:

Constructor Overloading in Java means having multiple constructors in the


same class with different parameter lists (number, type, or order of parameters).
It allows the creation of objects in different ways using the same class.

🔹 Key Points:

 Constructors must have the same name as the class.

 Overloading is done by changing the parameter list.


 Helps in initializing objects with different sets of data.
🔹 Example Program:

class Student {

String name;

int age;

// Default Constructor

Student() {

name = "Unknown";

age = 0;

// Parameterized Constructor
Student(String n) {

name = n;

age = 18;
}

// Another Parameterized Constructor

Student(String n, int a) {

name = n;

age = a;

void display() {

System.out.println("Name: " + name + ", Age: " + age);

public class Main {

public static void main(String[] args) {

Student s1 = new Student();

Student s2 = new Student("Ali");


Student s3 = new Student("Hiba", 22);
s1.display(); // Name: Unknown, Age: 0

s2.display(); // Name: Ali, Age: 18

s3.display(); // Name: Hiba, Age: 22

🔹 Benefits:

 Makes code more flexible and readable.

 Allows object creation with different initialization needs.

Q5. What is Array? Explain the concept of arrays with an example


program.

🔹 Definition:

An Array in Java is a collection of similar data types stored in contiguous


memory locations. It is used to store multiple values in a single variable, instead
of declaring separate variables for each value.

🔹 Key Concepts:

 Arrays are fixed in size (cannot grow or shrink after creation).

 They can be single-dimensional or multi-dimensional.

 Index starts from 0.

 Arrays can store primitive or object types.

🔹 Syntax:

dataType[] arrayName = new dataType[size];


🔹 Example Program:

public class ArrayExample {

public static void main(String[] args) {

int[] marks = new int[5];

marks[0] = 85;

marks[1] = 90;

marks[2] = 75;

marks[3] = 88;

marks[4] = 95;

System.out.println("Student Marks:");
for(int i = 0; i < marks.length; i++) {

System.out.println("Mark " + (i+1) + ": " + marks[i]);

}
}

🔹 Output:

Student Marks:

Mark 1: 85

Mark 2: 90
Mark 3: 75

Mark 4: 88

Mark 5: 95

🔹 Advantages of Arrays:

 Stores multiple values using one variable.


 Allows random access of elements using index.
 Useful for loops and data structures.
Q6. Explain briefly about String class and discuss various methods
in String class with an example.

🔹 What is the String Class?

In Java, the String class represents a sequence of characters.


Strings are objects in Java and are immutable, meaning once created, they cannot
be changed.
Java provides many built-in methods in the String class for string manipulation.

🔹 Commonly Used String Methods:

Method Description

length() Returns the length of the string

charAt(int index) Returns the character at the specified index

substring(int begin, int end) Returns a substring from begin to end index

toLowerCase() Converts all characters to lowercase

toUpperCase() Converts all characters to uppercase

equals(String str) Compares two strings for equality (case-sensitive)

equalsIgnoreCase(String str) Compares two strings ignoring case

concat(String str) Appends the given string

replace(char old, char new) Replaces characters in the string

trim() Removes leading and trailing spaces

🔹 Example Program:

public class StringExample {

public static void main(String[] args) {


String str = " Java ";
System.out.println(str.length()); // Length

System.out.println(str.trim()); // Trim

System.out.println(str.toUpperCase()); // Uppercase

System.out.println(str.toLowerCase()); // Lowercase

System.out.println(str.charAt(2)); // Char at index

System.out.println(str.replace('a', 'x')); // Replace

Output (Sample):

CopyEdit

Java

JAVA

java

Jxvx

Q7. Discuss about various conditional statements with necessary


examples

Conditional statements are used to make decisions in a program. They control the
flow of execution based on true or false conditions.

🔹 Types of Conditional Statements:

Type Description

if Executes block if the condition is true

if-else Executes one block if condition is true, another if false


Type Description

else-if ladder Checks multiple conditions sequentially

switch Selects one of many blocks based on variable value

🔹 Examples:

✅ 1. if statement

int num = 10;

if (num > 0)

System.out.println("Positive number");

✅ 2. if-else

int age = 17;

if (age >= 18)

System.out.println("Eligible to vote");

else
System.out.println("Not eligible");

✅ 3. else-if ladder

int marks = 75;

if (marks >= 90)

System.out.println("Grade A");

else if (marks >= 60)

System.out.println("Grade B");

else

System.out.println("Grade C");

4. switch statement

int day = 3;
switch (day) {

case 1: System.out.println("Monday"); break;

case 2: System.out.println("Tuesday"); break;

case 3: System.out.println("Wednesday"); break;

default: System.out.println("Invalid Day");

Q8. Define static field, static method ? Write with an example

🔹 1. Static Field (Variable):

A static field belongs to the class, not to any specific object.


It is shared among all instances of the class.

static int count; // Shared by all objects

🔹 2. Static Method:

A static method also belongs to the class and can be called without creating an
object.
It can only access static fields/methods.

static void display() {

System.out.println("This is a static method");

🔹 Example Program:

class Student {

static String college = "ABC College"; // Static field

String name;

Student(String n) {
name = n;
}

static void changeCollege() {

college = "XYZ College"; // Static method

void display() {

System.out.println(name + " - " + college);

}
public class Main {

public static void main(String[] args) {

Student.changeCollege(); // Call static method

Student s1 = new Student("Alice");

Student s2 = new Student("Bob");

s1.display();

s2.display();

🔹 Output:

Alice - XYZ College

Bob - XYZ College

Q9. Develop a Java program to read ‘n’ numbers from the console
and compute their sum and average.

✅ Java Program:

import java.util.Scanner;
public class SumAverage {
public static void main(String[] args) {

Scanner sc = new Scanner(System.in);

System.out.print("Enter how many numbers: ");

int n = sc.nextInt();

int sum = 0;

System.out.println("Enter " + n + " numbers:");

for (int i = 0; i < n; i++) {

int num = sc.nextInt();


sum += num;

double average = (double) sum / n;

System.out.println("Sum = " + sum);

System.out.println("Average = " + average);

✅ Sample Output:

Enter how many numbers: 4

Enter 4 numbers:

10

20

30

40

Sum = 100

Average = 25.0

You might also like