Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
29 views

Core Java Imp

Java

Uploaded by

wenav37876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
29 views

Core Java Imp

Java

Uploaded by

wenav37876
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 53

Core Java Imp

Q1. Answer in Short.

1. What is Java?

Ans: Java is a high-level, object-oriented programming language developed by Sun


Microsystems (now owned by Oracle). It is platform-independent, secure, and supports
multithreading and distributed computing.

2. What is an Exception?

Ans: An exception in Java is an event that disrupts the normal flow of a program's
execution. It typically occurs during runtime and can be handled using try-catch blocks
to prevent program crashes.

3. Enlist types of Inheritance.

 Ans: Single Inheritance

 Multilevel Inheritance

 Hierarchical Inheritance

 Multiple Inheritance (via interfaces)

 Hybrid Inheritance (combination of multiple types)

4. What is AWT?

Ans: AWT (Abstract Window Toolkit) is a Java library used for creating graphical user
interfaces (GUI). It contains various classes like Button, Label, and TextField for
developing windows-based applications.

5. State the purpose of throw keyword

Ans: The throw keyword is used in Java to explicitly throw an exception. For example:
throw new ArithmeticException("Error message");

6. What is Abstract class

Ans: An abstract class in Java is a class that cannot be instantiated and may contain
abstract methods (methods without implementation) that subclasses must override. It
can also contain concrete methods.

7. What is an event?

Ans: An event in Java refers to any action or occurrence recognized by software, like
button clicks or mouse movements, which can trigger a specific response within a
program.

8. What is Method Overloading?

Ans: Method overloading occurs when multiple methods in the same class have the
same name but differ in the number or type of their parameters.

9. Why Java is a architectural neutral language?

Ans: Java is considered architectural-neutral because compiled Java code (bytecode)


can run on any system that has a Java Virtual Machine (JVM), regardless of the
underlying hardware or operating system.

10. Define Encapsulation.

Ans: Encapsulation is the concept of bundling data (variables) and methods that
operate on the data within a single unit, typically a class, and restricting access to some
of the object’s components using access specifiers.

11. Why Java is a platform neutral language?

Ans: Java is platform-neutral because its compiled bytecode can be executed on any
platform that has a compatible JVM, allowing programs to be written once and run
anywhere.

12. What is access specifiers? List them.

 Ans: Access specifiers define the visibility and accessibility of classes, methods,
and variables. They are:

o public

o private

o protected

o default (no keyword)

13. Define Keyword-Static.

Ans: The static keyword in Java is used to define class-level methods or variables that
are shared among all instances of the class. Static members belong to the class itself
rather than any specific object.

14. Why we set environment variable in Java?

Ans: Environment variables such as JAVA_HOME and CLASSPATH are set to configure
the Java Development Kit (JDK) and to specify the path where Java programs and
libraries can be found by the operating system.

15. Write advantages of Inheritance.

Ans: Advantages of Inheritance:

 Code Reusability: Subclasses reuse code from the parent class.

 Method Overriding: Allows for dynamic polymorphism.

 Extensibility: New functionalities can be added to an existing class.

16. Define class and object with one example.

Ans: A class is a blueprint for creating objects (instances). An object is an instance of a


class.
Example:

class Car {

String model;

void start() {

System.out.println("Car started");

Car myCar = new Car(); // myCar is an object of the class Car.

17. What is Swing?

Ans: Swing is a part of Java’s Foundation Classes (JFC) used to create lightweight GUI
applications. It provides more powerful and flexible components than AWT, such as
buttons, panels, and text fields.

18. When buffered reader is used?

Ans: BufferedReader is used to read text from a character-based input stream efficiently.
It buffers input, minimizing the number of I/O operations by reading chunks of data.

19. What is main difference between exception and error?

Ans: Main difference between Exception and Error:

 Exception: Recoverable issue that can be handled by the program (e.g.,


IOException, NullPointerException).
 Error: Serious problem that is generally beyond the control of the program (e.g.,
OutOfMemoryError).

20. What is Panel?

Ans: Panel is a container in AWT that can hold multiple components (like buttons and
text fields) and group them together. It is often used for layout purposes in GUI
applications.

21. Define variable in Java? What are the naming rules of variable?

Ans: A variable is a container that holds data that can be changed during the execution
of a program.
Naming rules:

 Must start with a letter, $, or _

 Subsequent characters can be letters, digits, $, or _

 Case-sensitive

 Cannot be a keyword.

22. What is recursion?

Ans: Recursion is a programming technique where a method calls itself to solve a


problem.

23. Define Inheritance?

Ans: Inheritance is a mechanism where a new class (subclass) inherits the properties
and behavior of an existing class (superclass), promoting code reuse and hierarchical
relationships.

24. What is difference between Anay and Array List?

Ans: Difference between Array and ArrayList:

 Array: Fixed size, can store both primitive data types and objects.

 ArrayList: Dynamic size, can only store objects (wrapper classes for primitives).

25. What is error? List types of error?

Ans: An error is a serious problem that occurs during the execution of a program,
usually related to system resources or environment. Types include:

 Compile-time errors

 Runtime errors
 Logical errors

26. List any two restrictions for applet.

 Ans: Applets cannot access local file systems.

 Applets cannot communicate with other servers except the one from which they
were loaded.

27. What is an event?

Ans: Already answered in question 7.

28. What is Container?

Ans: A container is a component that can hold other components, such as panels or
frames, in GUI applications.

29. What is JDK? How to build and run java program?

Ans: JDK (Java Development Kit) is a software development kit required to develop
Java applications. To build and run a Java program:

 Write the source code.

 Compile using javac command.

 Run the compiled bytecode using the java command.

30. What is use of classpath?

Ans: The classpath is an environment variable that tells the Java Virtual Machine (JVM)
where to look for user-defined classes and packages when running Java applications.

31. What is collection? Explain collection frame work in details.

Ans: A collection is an object that groups multiple elements into a single unit. Java’s
Collection Framework provides classes like List, Set, and Map for storing and
manipulating data.

32. What is the use of Reader and Writer class?

Ans: Reader and Writer classes are used for handling character-based input/output
streams in Java. Reader reads characters, while Writer writes characters.

33. What is the use of layout manager?

Ans: A layout manager is used to arrange components in a container in a specific layout,


such as flow, grid, or border layouts.
34. What is difference between paint ( ) and repaint ( ).

 Ans: paint(): Directly used to draw the component.

 repaint(): Calls the update() method, which in turn calls paint(), used to refresh
the UI.

35. Explain Access modifiers used in Java.

Ans: Access modifiers control the visibility of class members. They include:

 Public: Accessible from everywhere.

 Private: Accessible only within the class.

 Protected: Accessible within the same package and subclasses.

 Default: Accessible only within the same package.

36. Define polymorphism.

Ans: Polymorphism is the ability of an object to take many forms, mainly through
method overriding (runtime polymorphism) and method overloading (compile-time
polymorphism)

37. What is a java program structure?

Ans: A typical Java program structure includes:

 Package declaration (optional)

 Import statements

 Class definition

 Methods

 Main method (entry point)

38. Define this Keyword.

Ans: this is a reference variable that points to the current object within a method or
constructor.

39. Explain in detail the data types in java?

Ans: Data types in Java are categorized into:

 Primitive types: byte, short, int, long, float, double, boolean, char

 Reference types: Arrays, Classes, Interfaces


40. Which method is used to specify containers layout with syntax.

Ans: The setLayout(LayoutManager layout) method is used to specify a container's


layout. Example: container.setLayout(new FlowLayout());

41. What is the default layout for Frame and Panel?

Ans: The default layout for a Frame is BorderLayout, and for a Panel, it is FlowLayout.

42. List and explain any 2 in-built exceptions.

 Ans: NullPointerException: Thrown when attempting to use null where an object


is required.

 ArrayIndexOutOfBoundsException: Thrown when accessing an array with an


invalid index.

43. Explain the purpose of getContentPane().

Ans: In Swing, getContentPane() is used to retrieve the content pane of a JFrame, where
you can add components like buttons or text fields.

44. What is an Interface?

Ans: An interface in Java is a reference type that can contain only abstract methods
(before Java 8) or default methods (Java 8 and later). Classes implement interfaces to
provide specific behaviors.

Q2. Long answer type questions.

1. What is Super Keyword? Explain the use of super keyword with suitable
example.
Ans: The super keyword in Java refers to the superclass (parent class) of the current
object. It is used to access superclass methods, constructors, or variables from a
subclass.
Uses of the super keyword:
 Access superclass variables when they are hidden by subclass variables.
 Invoke superclass methods when overridden by subclass methods.
 Invoke superclass constructors from a subclass constructor.
Example:
class Animal {
String name = "Animal";
void display() {
System.out.println("This is an Animal");
}
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println("This is a Dog");
}
void printInfo() {
System.out.println(super.name); // Accessing superclass variable
super.display(); // Calling superclass method
}
}
public class TestSuper {
public static void main(String[] args) {
Dog dog = new Dog();
dog.printInfo();
}
}

2. Describe file handling in brief.


Ans: File handling in Java is used to perform operations on files such as reading from or
writing to files. Java provides the java.io package, which includes classes like
FileReader, FileWriter, BufferedReader, BufferedWriter, and FileInputStream,
FileOutputStream for working with files.
Basic operations:
 Creating a file: Using File class.
 Reading from a file: Using FileReader and BufferedReader for reading character
data.
 Writing to a file: Using FileWriter and BufferedWriter for writing data to a file.
 Deleting a file: Using delete() method in the File class.

3. What is datatype? Explain types of datatypes used in Java.


Ans: A datatype specifies the type of data a variable can hold. Java has two types of
data types:
1. Primitive Data Types: These are the basic data types in Java, and they include:
o byte: 8-bit integer (Range: -128 to 127)
o short: 16-bit integer
o int: 32-bit integer
o long: 64-bit integer
o float: 32-bit floating point
o double: 64-bit floating point
o boolean: Stores true/false
o char: 16-bit Unicode character
2. Reference Data Types: These refer to objects and include:
o Classes
o Arrays
o Interfaces

4. What is interface? Why they are used in Java?


Ans: An interface in Java is a reference type that can contain only abstract methods
(before Java 8) or default and static methods (from Java 8 onwards). Interfaces cannot
contain any concrete (implemented) methods.
Why are interfaces used?
 To achieve full abstraction in Java.
 To implement multiple inheritance since a class can implement multiple
interfaces.
 They define a contract that classes must follow, ensuring that certain methods
are present in the implementing class.
Example:
interface Animal {
void sound();
}
class Dog implements Animal {
public void sound() {
System.out.println("Dog barks");
}
}
class TestInterface {
public static void main(String[] args) {
Dog dog = new Dog();
dog.sound();
}
}

5. Why the main() method in public static? Can we overload it? Can we run java class
without main() method?
Ans: The main() method is public and static in Java because:
 public: It must be accessible to the JVM, which calls it to start the execution.
 static: It can be called without creating an instance of the class.
1. Can we overload main()? Yes, you can overload the main() method by defining
other versions of main() with different parameter lists, but the JVM will always
look for public static void main(String[] args) to start execution.
2. Can we run a Java class without the main() method? In recent versions of Java,
if you have a class that doesn't have a main() method, the JVM will throw a
NoSuchMethodError. However, earlier versions could run via static initialization
blocks.

6. What is recursion is Java? Write a Java Program to final factorial of a given number
using recursion.
Ans: Recursion is a process in which a method calls itself continuously until it reaches a
base condition.
Example: Factorial using Recursion:
class RecursionExample {
static int factorial(int n) {
if (n == 0) { // Base condition
return 1;
} else {
return n * factorial(n - 1); // Recursive call
}
}
public static void main(String[] args) {
int number = 5;
System.out.println("Factorial of " + number + " is: " + factorial(number));
}
}

7. Explain method overloading and method overriding in detail.


Ans: Method Overloading: When two or more methods in the same class have the same
name but different parameter lists (i.e., different number or types of parameters), it is
called method overloading.
 Compile-time polymorphism
Example:
class Example {
void display(int a) {
System.out.println(a);
}
void display(String b) {
System.out.println(b);
}
}
Method Overriding: When a subclass provides a specific implementation of a method
already defined in its superclass, it is called method overriding.
 Run-time polymorphism
Example:
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}

8. Explain in brief delegation event model for handling events.


Ans: The delegation event model in Java is used to handle events such as button clicks
or mouse movements in a GUI application. It works on a listener pattern:
Components of the model:
1. Event Source: The component on which the event occurs (e.g., a button).
2. Event Object: Encapsulates the details of the event (e.g., ActionEvent for a button
click).
3. Event Listener: The object that listens and handles the event. It implements event
-listener interfaces and defines the logic of what happens when an event occurs.
Example:
 A button that listens for a click:
Button button = new Button("Click Me");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
});

9. Write a note on package in Java.


Ans: A package in Java is a namespace that groups related classes and interfaces. It is
used to organize classes and interfaces into manageable units and avoid name
conflicts. Packages provide access protection and can also control the visibility of
classes, interfaces, and their members.
Types of Packages:
1. Built-in Packages: Java comes with several built-in packages like java.lang,
java.util, java.io, etc.
2. User-defined Packages: Users can create their own packages to group related
classes.
Creating a Package: To create a package, use the package keyword at the beginning of
your Java source file:
package com.example;
public class MyClass {
}
Importing Packages: To use classes from a package, you can import them using the
import statement:
import com.example.MyClass;
import com.example.*;

10. What is exception? Explain its keyword with example.


Ans: An exception in Java is an event that disrupts the normal flow of a program's
execution. Exceptions are used to handle errors and other exceptional events. When an
exception occurs, an object called an exception object is created, which contains
information about the error.
Keywords associated with exceptions:
1. try: A block where you place code that might throw an exception.
2. catch: A block that handles the exception.
3. finally: A block that is executed regardless of whether an exception occurs or not
(often used for cleanup).
4. throw: Used to explicitly throw an exception.
5. throws: Declares that a method may throw exceptions.
Example:
public class ExceptionExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("This block always executes.");
}
}
}

11. Explain java. util package.


Ans: The java.util package is a part of the Java Standard Library and provides a
collection of utility classes that are widely used in Java programming. It includes:
1. Collections Framework: Classes like ArrayList, LinkedList, HashMap, and
HashSet for storing and manipulating collections of objects.
2. Date and Time Utilities: Classes like Date, Calendar, and GregorianCalendar for
handling date and time.
3. Random Number Generation: The Random class for generating random numbers.
4. Utilities for Working with Strings: The StringTokenizer class for parsing strings
and Properties for managing configuration properties.
Example: Using ArrayList from java.util package
import java.util.ArrayList;

public class UtilExample {


public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Orange");

for (String fruit : list) {


System.out.println(fruit);
}
}
}

12. What is a method in Java? Explain method overloading with example.


Ans: A method in Java is a block of code that performs a specific task. It can take
parameters, execute code, and return a value. Methods help to organize code into
reusable components.
Method Overloading occurs when multiple methods in the same class have the same
name but different parameter lists (different types or number of parameters). It allows
methods to perform similar functions while accepting different types of data.
Example of Method Overloading:
public class OverloadingExample {
// Method to add two integers
int add(int a, int b) {
return a + b;
}

// Method to add three integers


int add(int a, int b, int c) {
return a + b + c;
}

// Method to add two double values


double add(double a, double b) {
return a + b;
}

public static void main(String[] args) {


OverloadingExample obj = new OverloadingExample();
System.out.println("Sum of two integers: " + obj.add(5, 10)); // Calls first add
method
System.out.println("Sum of three integers: " + obj.add(5, 10, 15)); // Calls second
add method
System.out.println("Sum of two doubles: " + obj.add(5.5, 10.5)); // Calls third
add method
}
}

13. How to handle events in applet? Explain with example.


Ans: In Java applets, events can be handled using the event delegation model, which
involves using event listeners to respond to user actions, such as mouse clicks or key
presses.
Steps to handle events in an applet:
1. Implement the required event listener interface (e.g., MouseListener, KeyListener).
2. Override the appropriate methods to handle events.
3. Register the applet as a listener for the events.
Example of handling a mouse click event in an applet:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class EventHandlingApplet extends Applet implements MouseListener {


String message = "";

public void init() {


addMouseListener(this); // Register the applet as a mouse listener
}

public void mouseClicked(MouseEvent e) {


message = "Mouse clicked at: (" + e.getX() + ", " + e.getY() + ")";
repaint(); // Calls the paint method to update the display
}

public void paint(Graphics g) {


g.drawString(message, 20, 20); // Display the message on the applet
}

// Other MouseListener methods can be left empty if not used


public void mouseEntered(MouseEvent e) {}
public void mouseExited(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
}

14. What is Layout Manager? Explain any one in detail.


Ans: A Layout Manager in Java is used to define how components are arranged inside a
container (like a JPanel or JFrame). It automates the process of positioning and sizing
components based on a specific layout policy.
Java provides several layout managers, such as:
 FlowLayout
 BorderLayout
 GridLayout
 GridBagLayout
 CardLayout
FlowLayout (Detailed Explanation):
FlowLayout is the simplest layout manager in Java. It arranges components in a
container from left to right, and when there’s no space left, it moves to the next line. It's
similar to how words wrap in a text editor.
 Alignment options: FlowLayout.LEFT, FlowLayout.RIGHT, FlowLayout.CENTER
(default).
 Constructor:
o FlowLayout(): Creates a layout aligned to the center with a default 5-pixel
horizontal and vertical gap.
o FlowLayout(int align): Creates a layout with a specified alignment.
o FlowLayout(int align, int hgap, int vgap): Specifies alignment and gaps.
Example:
import java.awt.*;
import javax.swing.*;

public class FlowLayoutExample {


public static void main(String[] args) {
JFrame frame = new JFrame("FlowLayout Example");
frame.setLayout(new FlowLayout(FlowLayout.LEFT, 20, 15)); // Left alignment,
gaps of 20, 15

// Adding buttons to the frame


frame.add(new JButton("Button 1"));
frame.add(new JButton("Button 2"));
frame.add(new JButton("Button 3"));
frame.add(new JButton("Button 4"));

frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

15. How to create and access package in Java? Explain it with example.
Ans: A package in Java is used to group related classes and interfaces, providing
modularity and avoiding naming conflicts. It helps in organizing the project and
controlling access to different classes.
Steps to create and access a package:
1. Create a Package: Use the package keyword followed by the package name at
the top of your Java file.
2. Compile the Package: After creating the class inside a package, you need to
compile it using javac with the -d option to specify the destination folder.
3. Import the Package: In other Java classes, you can use the import keyword to
access the classes inside the package.
Example:
Step 1: Create a package java
Copy code
// File: MyPackage/MyClass.java
package MyPackage;

public class MyClass {


public void display() {
System.out.println("Hello from MyClass in MyPackage");
}
}
Step 2: Compile the package bash
Copy code
javac -d . MyPackage/MyClass.java
Step 3: Use the package in another class java
Copy code
// File: TestPackage.java
import MyPackage.MyClass;

public class TestPackage {


public static void main(String[] args) {
MyClass obj = new MyClass();
obj.display();
}
}
Step 4: Compile and run the TestPackage
bash
Copy code
javac TestPackage.java
java TestPackage

16. Explain anonymous class in detail.


Ans: An anonymous class in Java is a local class without a name. It is used to
instantiate and define a class simultaneously, typically to provide a concise
implementation of an interface or abstract class. Anonymous classes are often used in
event handling or when quick custom behavior is needed without defining a separate
class.
Key Features:
1. No class name: The class is declared and instantiated at the same time.
2. Used for short-lived objects: Often used when a one-time use implementation of
an interface or abstract class is needed.
3. Can't have a constructor: Since they don’t have a name, you can’t define
constructors for anonymous classes.
Syntax:
new InterfaceOrAbstractClass() {
// Override methods or add custom behavior here
};
Advantages of Anonymous Classes:
1. Concise code: Helps to avoid clutter by reducing the need for separate class
declarations.
2. Convenience: Ideal for one-time use classes, particularly in event handling.
Limitations of Anonymous Classes:
1. No reuse: Since they don’t have a name, anonymous classes can't be reused.
2. Hard to debug: Since anonymous classes lack a name, debugging can be more
challenging when errors occur.
3.
17. Explain features of Java.
Ans: Java is a high-level, object-oriented programming language known for its simplicity
and platform independence. Key features of Java include:
1. Object-Oriented: Everything in Java is treated as an object, promoting modular,
reusable code.
2. Platform-Independent: Java programs are compiled into bytecode, which can be
run on any system with the Java Virtual Machine (JVM), making Java Write Once,
Run Anywhere (WORA).
3. Simple and Easy to Learn: Java has a simple syntax that is easy to understand
and learn, especially for developers familiar with C or C++.
4. Secure: Java provides a secure execution environment through features like
bytecode verification and sandboxing.
5. Robust: Java handles memory management automatically using garbage
collection, reducing memory leaks and crashes.
6. Multithreaded: Java provides built-in support for multithreading, allowing efficient
execution of multiple tasks simultaneously.
7. Dynamic: Java supports dynamic loading of classes and dynamic memory
management.
8. Distributed: Java supports distributed computing with the use of remote method
invocation (RMI) and Java's networking capabilities.
9. High Performance: While Java is interpreted, the Just-In-Time (JIT) compiler
improves the performance by compiling bytecode into native machine code
during runtime.
18. What is difference between constructor and method? Explain types of
constructors.
Ans:

Types of Constructors in Java:


1. Default Constructor: A no-argument constructor provided by the compiler if no
constructors are defined.
public class Example {
public Example() {
System.out.println("Default constructor called.");
}
}
2. Parameterized Constructor: A constructor that takes arguments to initialize an
object with specific values.
public class Example {
public Example(int a) {
System.out.println("Parameterized constructor called with value: " + a);
}
}
19. Differentiate between interface and abstract class.
Ans:
20. Explain the concept of exception and exception handling.
Ans: An exception in Java is an event that disrupts the normal flow of a program's
execution. Exceptions typically occur when something unexpected happens, such as
invalid input, file not found, or division by zero. Exception handling in Java ensures that
runtime errors do not crash the program and allows developers to manage these errors
gracefully.
Java's exception handling mechanism consists of:
1. try: The block of code where exceptions might occur.
2. catch: The block that handles the exception.
3. finally: The block that is executed regardless of whether an exception occurred or
not (used for cleanup).
4. throw: Used to explicitly throw an exception.
5. throws: Declares exceptions that a method might throw.

21. Explain try and Catch with example.


Ans: In Java, the try block is used to wrap code that might throw an exception, while the
catch block is used to handle the exception.
Syntax:
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example:
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Exception caught: " + e.getMessage());
}
}
}
22. How a Java program is structured? Explain data types.
Ans: A Java program is structured into the following components:
1. Package Declaration: Specifies the package in which the class belongs.
2. Import Statements: Used to import other classes and packages.
3. Class Declaration: Defines the class.
4. Main Method: The entry point of the Java application.
Example Structure:
package mypackage; // Package Declaration

import java.util.Scanner; // Import Statement

public class MyClass { // Class Declaration


public static void main(String[] args) { // Main Method
System.out.println("Hello, World!"); // Statement inside method
}
}

23. What is applet? Explain its types.


Ans: An applet is a small Java program that runs inside a web browser or an applet
viewer. Applets are primarily used for creating dynamic web content. Unlike standalone
Java applications, applets do not have a main method. Instead, they use the init(), start(),
stop(), and destroy() methods provided by the Applet class.
Types of Applets:
1. Trusted Applet: These applets are given more privileges (e.g., access to the local
filesystem) because they are signed by a trusted authority.
2. Untrusted Applet: These applets run inside a restricted environment (sandbox)
and cannot access certain resources on the local machine for security reasons.
Example:
import java.applet.Applet;
import java.awt.Graphics;
public class MyApplet extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, Applet!", 20, 20);
}
}

24 What are the different types of streams? Explain in details.


Ans: In Java, streams are used to read and write data to files, memory, and other data
sources. They represent a sequence of data and are categorized into two types based
on the type of data they handle:
1. Byte Streams: Handle raw binary data. They are useful for reading and writing
binary files (e.g., images, audio files). Byte streams are based on two abstract
classes:
o InputStream: An abstract class that serves as the superclass for all
classes representing an input stream of bytes.
o OutputStream: An abstract class that serves as the superclass for all
classes representing an output stream of bytes.
2. Character Streams: Handle characters (text data). They are useful for reading
and writing text files and are based on the following abstract classes:
 Reader: An abstract class for reading character streams.
 Writer: An abstract class for writing character streams.

25 What is collection? Explain Collection framework in details.


Ans: A collection in Java is an object that can hold multiple values in a single unit. The
Java Collection Framework provides a set of classes and interfaces to store, retrieve,
manipulate, and communicate aggregate data in a variety of ways.
Main Classes in the Collection Framework:
 ArrayList: A resizable array implementation of the List interface. It allows random
access and is not synchronized.
 LinkedList: A doubly linked list implementation of the List interface. It allows fast
insertions and deletions.
 HashSet: A collection that does not allow duplicates and does not maintain any
order. It is backed by a hash table.
 TreeSet: A collection that stores elements in a sorted order and does not allow
duplicates.
 HashMap: A collection that maps keys to values and does not allow duplicate
keys. It allows null values and keys.
 TreeMap: A collection that stores key-value pairs in a sorted order.

26 Difference between Swing and AWT.


Ans:

27 What is polymorphism? Explain its types.


Ans: Polymorphism in Java is the ability of an object to take on many forms. It allows
methods to do different things based on the object that it is acting upon. Polymorphism
enhances flexibility and maintainability of the code.
Types of Polymorphism:
1. Compile-Time Polymorphism (Static Binding):
o Achieved through method overloading and operator overloading.
o The method to be executed is determined at compile time.
o Example: Method Overloading.

2. Runtime Polymorphism (Dynamic Binding):

 Achieved through method overriding.


 The method to be executed is determined at runtime based on the object
being referred to.
 Example: Method Overriding.

28 What is difference between constructor and method Explain types of constructors.


Ans:

29. what is array. explain its types.


Ans: An array in Java is a data structure that allows you to store multiple values of the
same type in a single variable. Arrays can hold primitive data types (like int, char, float)
or objects (like instances of classes).
Types of Arrays in Core Java:
1. Single-Dimensional Array: A linear array that holds elements in a single row.
int[] numbers = {1, 2, 3, 4, 5};
2. Multi-Dimensional Array: An array of arrays, allowing storage of data in two or
more dimensions (e.g., matrices).
Two-Dimensional Array:
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};
3. Jagged Array: An array where each element can have different lengths, creating a
non-rectangular structure.
int[][] jaggedArray = {
{1, 2},
{3, 4, 5},
{6}
};
Example of Using Arrays:
public class ArrayExample {
public static void main(String[] args) {

// Single-Dimensional Array

int[] singleArray = {10, 20, 30, 40};

// Accessing elements

System.out.println("Single Array Element: " + singleArray[2]); // Output: 30

// Two-Dimensional Array

int[][] twoDArray = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

// Accessing elements

System.out.println("Two-Dimensional Array Element: " + twoDArray[1][1]); //


Output: 5

// Jagged Array

int[][] jaggedArray = {

{1, 2},

{3, 4, 5},

{6}

};

// Accessing elements

System.out.println("Jagged Array Element: " + jaggedArray[2][0]); // Output: 6


}

Q3. Programs.
1. Write a java program which accepts student details (Sid, Sname, Saddr)
from user and display it on next frame. (Use AWT).
Ans: import java.awt.*;
import java.awt.event.*;

public class StudentDetails extends Frame implements ActionListener {


Label labelSid, labelSname, labelSaddr;
TextField textSid, textSname, textSaddr;
Button submitButton;

public StudentDetails() {
labelSid = new Label("Student ID:");
labelSname = new Label("Student Name:");
labelSaddr = new Label("Student Address:");

textSid = new TextField();


textSname = new TextField();
textSaddr = new TextField();

submitButton = new Button("Submit");


submitButton.addActionListener(this);

setLayout(new GridLayout(4, 2));


add(labelSid);
add(textSid);
add(labelSname);
add(textSname);
add(labelSaddr);
add(textSaddr);
add(submitButton);

setSize(300, 200);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
new DisplayFrame(textSid.getText(), textSname.getText(), textSaddr.getText());
}

public static void main(String[] args) {


new StudentDetails();
}
}

class DisplayFrame extends Frame {


public DisplayFrame(String sid, String sname, String saddr) {
setTitle("Student Details");
setLayout(new FlowLayout());

Label label = new Label("ID: " + sid + ", Name: " + sname + ", Address: " + saddr);
add(label);

setSize(400, 100);
setVisible(true);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
}
2. Write a package MCA which has one class student. Accept student
details through parameterized constructor. Write display() method to
display details. Create a main class which will use package and calculate
total marks and percentage.
Ans:
// Package MCA
package MCA;

public class Student {


String sid;
String sname;
String saddr;
int totalMarks;
float percentage;

public Student(String sid, String sname, String saddr, int totalMarks) {


this.sid = sid;
this.sname = sname;
this.saddr = saddr;
this.totalMarks = totalMarks;
this.percentage = (totalMarks / 500.0f) * 100; // Assuming total marks is out of 500
}

public void display() {


System.out.println("ID: " + sid + ", Name: " + sname + ", Address: " + saddr);
System.out.println("Total Marks: " + totalMarks + ", Percentage: " + percentage +
"%");
}
}

// Main Class
import MCA.Student;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter Student ID: ");


String sid = scanner.nextLine();
System.out.print("Enter Student Name: ");
String sname = scanner.nextLine();
System.out.print("Enter Student Address: ");
String saddr = scanner.nextLine();
System.out.print("Enter Total Marks: ");
int totalMarks = scanner.nextInt();

Student student = new Student(sid, sname, saddr, totalMarks);


student.display();
}
}
3. Write Java program which accepts string from user, if its length is less
than five, then throw user defined exception “Invalid String” otherwise
display string in uppercase.
Ans:
import java.util.Scanner;

class InvalidStringException extends Exception {


public InvalidStringException(String message) {
super(message);
}
}

public class StringValidation {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

try {
if (input.length() < 5) {
throw new InvalidStringException("Invalid String: Length must be 5 or more.");
}
System.out.println("Uppercase: " + input.toUpperCase());
} catch (InvalidStringException e) {
System.out.println(e.getMessage());
}
}
}
4. Write a Java Program using Applet to create login form.
Ans:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class LoginForm extends Applet implements ActionListener {


Label labelUser, labelPass;
TextField textUser, textPass;
Button loginButton;
public void init() {
labelUser = new Label("Username:");
labelPass = new Label("Password:");

textUser = new TextField(20);


textPass = new TextField(20);
textPass.setEchoChar('*');

loginButton = new Button("Login");


loginButton.addActionListener(this);

add(labelUser);
add(textUser);
add(labelPass);
add(textPass);
add(loginButton);
}

public void actionPerformed(ActionEvent e) {


String user = textUser.getText();
String pass = textPass.getText();
// Logic to check credentials can be added here
System.out.println("Username: " + user + ", Password: " + pass);
}
}
5. Write a applet application in java for designing smiley.
Ans:
import java.applet.Applet;
import java.awt.*;

public class SmileyApplet extends Applet {


public void paint(Graphics g) {
// Draw face
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 100, 100); // Face

// Draw eyes
g.setColor(Color.BLACK);
g.fillOval(75, 80, 10, 10); // Left eye
g.fillOval(115, 80, 10, 10); // Right eye

// Draw mouth
g.drawArc(75, 90, 50, 30, 0, -180); // Smile
}
}
6. Write a java program to copy the dates from one file into another file.
Ans:
import java.io.*;

public class FileCopy {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("source.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("destination.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line);
bw.newLine();
}
System.out.println("File copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
7. Write a java program to accept’ ‘n’ integers from the user & store them
in an ArrayList Collection. Display the elements of ArrayList collection
in reverse order.
Ans:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class ReverseArrayList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> numbers = new ArrayList<>();
System.out.print("Enter the number of integers: ");
int n = scanner.nextInt();
System.out.println("Enter " + n + " integers:");

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


numbers.add(scanner.nextInt());
}

Collections.reverse(numbers);
System.out.println("Reversed ArrayList: " + numbers);
}
}
8. Write a Java program using AWT to display details of Customer (cust_id,
cust_name, cust_addr) from user and display it on the next frame.
Ans:
import java.awt.*;
import java.awt.event.*;

public class CustomerDetails extends Frame implements ActionListener {


Label labelCustId, labelCustName, labelCustAddr;
TextField textCustId, textCustName, textCustAddr;
Button submitButton;

public CustomerDetails() {
labelCustId = new Label("Customer ID:");
labelCustName = new Label("Customer Name:");
labelCustAddr = new Label("Customer Address:");

textCustId = new TextField();


textCustName = new TextField();
textCustAddr = new TextField();

submitButton = new Button("Submit");


submitButton.addActionListener(this);

setLayout(new GridLayout(4, 2));


add(labelCustId);
add(textCustId);
add(labelCustName);
add(textCustName);
add(labelCustAddr);
add(textCustAddr);
add(submitButton);

setSize(300, 200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


new DisplayCustomerFrame(textCustId.getText(), textCustName.getText(),
textCustAddr.getText());
}

public static void main(String[] args) {


new CustomerDetails();
}
}

class DisplayCustomerFrame extends Frame {


public DisplayCustomerFrame(String custId, String custName, String custAddr) {
setTitle("Customer Details");
setLayout(new FlowLayout());

Label label = new Label("ID: " + custId + ", Name: " + custName + ", Address: " +
custAddr);
add(label);

setSize(400, 100);
setVisible(true);

addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
dispose();
}
});
}
}
9. Write a Java program to reverse elements in array.
Ans:
import java.util.Scanner;

public class ReverseArray {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of elements in array: ");
int n = scanner.nextInt();

int[] arr = new int[n];


System.out.println("Enter " + n + " integers:");
for (int i = 0; i < n; i++) {
arr[i] = scanner.nextInt();
}

System.out.print("Reversed Array: ");


for (int i = n - 1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}
10. Write a Java program using static method which maintain bank account
information about various customers.
Ans:
import java.util.Scanner;

class BankAccount {
static int accountCount = 0;
String accountHolderName;
double balance;

public BankAccount(String name, double initialBalance) {


this.accountHolderName = name;
this.balance = initialBalance;
accountCount++;
}

static void displayAccountCount() {


System.out.println("Total accounts created: " + accountCount);
}

void displayInfo() {
System.out.println("Account Holder: " + accountHolderName + ", Balance: $" +
balance);
}
}

public class BankManagement {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter account holder name: ");


String name = scanner.nextLine();
System.out.print("Enter initial balance: ");
double initialBalance = scanner.nextDouble();

BankAccount account = new BankAccount(name, initialBalance);


account.displayInfo();
BankAccount.displayAccountCount();
}
}
11. Define an abstract class Shape with abstract method area() and volume().
Write a Java program to calculate area and volume of cone and cylinder.
Ans:
abstract class Shape {
abstract void area();
abstract void volume();
}

class Cone extends Shape {


double radius;
double height;

Cone(double r, double h) {
radius = r;
height = h;
}
void area() {
double area = Math.PI * radius * (radius + Math.sqrt(height * height + radius *
radius));
System.out.println("Cone Surface Area: " + area);
}

void volume() {
double volume = (1.0 / 3) * Math.PI * radius * radius * height;
System.out.println("Cone Volume: " + volume);
}
}

class Cylinder extends Shape {


double radius;
double height;

Cylinder(double r, double h) {
radius = r;
height = h;
}

void area() {
double area = 2 * Math.PI * radius * (radius + height);
System.out.println("Cylinder Surface Area: " + area);
}

void volume() {
double volume = Math.PI * radius * radius * height;
System.out.println("Cylinder Volume: " + volume);
}
}

public class ShapeTest {


public static void main(String[] args) {
Shape cone = new Cone(5, 10);
cone.area();
cone.volume();

Shape cylinder = new Cylinder(5, 10);


cylinder.area();
cylinder.volume();
}
}
12. Write a Java program to display smiley face using applet.
Ans:
import java.applet.Applet;
import java.awt.*;

public class SmileyFaceApplet extends Applet {


public void paint(Graphics g) {
// Draw face
g.setColor(Color.YELLOW);
g.fillOval(50, 50, 100, 100); // Face

// Draw eyes
g.setColor(Color.BLACK);
g.fillOval(75, 80, 10, 10); // Left eye
g.fillOval(115, 80, 10, 10); // Right eye

// Draw mouth
g.drawArc(75, 90, 50, 30, 0, -180); // Smile
}
}
13. Write a Java program to Fibonacci series.
Ans:
import java.util.Scanner;

public class Fibonacci {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of terms: ");
int n = scanner.nextInt();

int a = 0, b = 1, c;
System.out.print("Fibonacci Series: " + a + " " + b);

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


c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
}
}
14. Write a Java program to display contents of file in reverse order.
Ans:
import java.io.*;
import java.util.*;

public class ReverseFile {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
List<String> lines = new ArrayList<>();
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
Collections.reverse(lines);
for (String l : lines) {
System.out.println(l);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
15. Write a Java program to display all the perfect numbers between 1 to n.
Ans:
import java.util.Scanner;

public class PerfectNumbers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the limit (n): ");
int n = scanner.nextInt();

System.out.println("Perfect numbers between 1 and " + n + ":");


for (int i = 1; i <= n; i++) {
if (isPerfect(i)) {
System.out.println(i);
}
}
}

static boolean isPerfect(int number) {


int sum = 0;
for (int i = 1; i < number; i++) {
if (number % i == 0) {
sum += i;
}
}
return sum == number;
}
}
16. Write a Java program to calculate area of circle, Triangle and Rectangle
(Use Method over loading)
Ans:
class AreaCalculator {
// Method to calculate area of circle
public double area(double radius) {
return Math.PI * radius * radius;
}

// Method to calculate area of triangle


public double area(double base, double height) {
return 0.5 * base * height;
}

// Method to calculate area of rectangle


public double area(double length, double width) {
return length * width;
}
}

public class AreaTest {


public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
System.out.println("Area of Circle (r=5): " + calculator.area(5));
System.out.println("Area of Triangle (b=4, h=3): " + calculator.area(4, 3));
System.out.println("Area of Rectangle (l=5, w=6): " + calculator.area(5, 6));
}
}
17. Write a java program to accept n integers from the user and store them
in on Arraylist collection. Display elements in reverse order.
Ans:
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;

public class IntegerArrayList {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
ArrayList<Integer> integers = new ArrayList<>();

System.out.print("Enter the number of integers: ");


int n = scanner.nextInt();
System.out.println("Enter " + n + " integers:");

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


integers.add(scanner.nextInt());
}

Collections.reverse(integers);
System.out.println("Reversed ArrayList: " + integers);
}
}
18. Write a Java program to count number of digits, spaces and characters
from a file.
Ans:
import java.io.*;

public class FileCharacterCounter {


public static void main(String[] args) {
int digitCount = 0;
int spaceCount = 0;
int charCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {


int c;
while ((c = br.read()) != -1) {
charCount++;
if (Character.isDigit(c)) {
digitCount++;
}
if (Character.isWhitespace(c)) {
spaceCount++;
}
}
System.out.println("Digits: " + digitCount);
System.out.println("Spaces: " + spaceCount);
System.out.println("Characters: " + charCount);
} catch (IOException e) {
e.printStackTrace();
}
}
}
19. Create an applet that display x and y position of the cursor movement
using mouse and keyboard. (Use appropriate listener)
Ans:
import java.applet.Applet;
import java.awt.event.*;

public class MousePositionApplet extends Applet implements MouseMotionListener {


String msg = "";

public void init() {


addMouseMotionListener(this);
}

public void mouseMoved(MouseEvent me) {


msg = "Mouse Position: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}
public void mouseDragged(MouseEvent me) {}

public void paint(Graphics g) {


g.drawString(msg, 20, 20);
}
}
20. Write a java program to count number of Lines, words and characters
from a given file.
Ans:
import java.io.*;

public class FileWordCounter {


public static void main(String[] args) {
int lineCount = 0;
int wordCount = 0;
int charCount = 0;

try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {


String line;
while ((line = br.readLine()) != null) {
lineCount++;
charCount += line.length();
String[] words = line.split("\\s+");
wordCount += words.length;
}
System.out.println("Lines: " + lineCount);
System.out.println("Words: " + wordCount);
System.out.println("Characters: " + charCount);
} catch (IOException e) {
e.printStackTrace();
}
}
}
21. Write a Java program to design email registration form. (Use swing
components)
Ans:
import javax.swing.*;
import java.awt.event.*;
public class EmailRegistrationForm {
public static void main(String[] args) {
JFrame frame = new JFrame("Email Registration Form");
JLabel labelEmail = new JLabel("Email:");
JTextField textEmail = new JTextField(20);
JButton submitButton = new JButton("Submit");

submitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Email submitted: " + textEmail.getText());
JOptionPane.showMessageDialog(frame, "Email submitted!");
}
});

JPanel panel = new JPanel();


panel.add(labelEmail);
panel.add(textEmail);
panel.add(submitButton);

frame.add(panel);
frame.setSize(300, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
22. Create a class Teacher (Tid, Tname, Designation, Salary, Subject). Write
Ans:
class Teacher {
int Tid;
String Tname;
String Designation;
double Salary;
String Subject;

Teacher(int id, String name, String designation, double salary, String subject) {
this.Tid = id;
this.Tname = name;
this.Designation = designation;
this.Salary = salary;
this.Subject = subject;
}
}

public class TeacherTest {


public static void main(String[] args) {
Teacher[] teachers = {
new Teacher(1, "Alice", "Professor", 50000, "Java"),
new Teacher(2, "Bob", "Lecturer", 30000, "Python"),
new Teacher(3, "Charlie", "Instructor", 40000, "Java")
};

System.out.println("Teachers who teach Java:");


for (Teacher teacher : teachers) {
if (teacher.Subject.equals("Java")) {
System.out.println("ID: " + teacher.Tid + ", Name: " + teacher.Tname);
}
}
}
}
23. java program to accept 'n' teachers and display who teach Java subject
(Use Array of object)
Ans:
import java.util.Scanner;

public class AlternateCharacters {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String input = scanner.nextLine();

System.out.print("Alternate characters: ");


for (int i = 0; i < input.length(); i += 2) {
System.out.print(input.charAt(i));
}
}
}
24. Write a java program to display alternate character from a given string.
Ans:
class AreaCalculator {
public double area(double radius) {
return Math.PI * radius * radius;
}

public double area(double base, double height) {


return 0.5 * base * height;
}

public double area(double length, double width) {


return length * width;
}
}

public class AreaTest {


public static void main(String[] args) {
AreaCalculator calculator = new AreaCalculator();
System.out.println("Area of Circle (r=5): " + calculator.area(5));
System.out.println("Area of Triangle (b=4, h=3): " + calculator.area(4, 3));
System.out.println("Area of Rectangle (l=5, w=6): " + calculator.area(5, 6));
}
}
25. Write a Java program to calculate area of Circle, Triangle & Rectangle.
(Use Method Overloading).
Ans:
import java.util.Scanner;

public class NameSearch {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String[] names = {"Alice", "Bob", "Charlie", "Diana", "Eve"};

System.out.print("Enter name to search: ");


String searchName = scanner.nextLine();
int index = search(names, searchName);

if (index != -1) {
System.out.println("Name found at index: " + index);
} else {
System.out.println("Name not found.");
}
}

static int search(String[] names, String searchName) {


for (int i = 0; i < names.length; i++) {
if (names[i].equalsIgnoreCase(searchName)) {
return i;
}
}
return -1;
}
}
26. Write a java program to search given name into the array, if it is found
then display its index otherwise display appropriate message.
Ans:
import java.io.*;

public class AsciiValuesFromFile {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("input.txt"))) {
int c;
while ((c = br.read()) != -1) {
System.out.println((char) c + ": " + c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
27. Write a java program to display ASCII values of the characters from a
file.
Ans:
import javax.swing.*;
import java.awt.event.*;

public class MultiplicationTable {


public static void main(String[] args) {
JFrame frame = new JFrame("Multiplication Table");
JLabel label = new JLabel("Enter a number:");
JTextField textField = new JTextField(5);
JButton button = new JButton("Generate Table");
DefaultListModel<String> listModel = new DefaultListModel<>();
JList<String> list = new JList<>(listModel);

button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listModel.clear();
int number = Integer.parseInt(textField.getText());
for (int i = 1; i <= 10; i++) {
listModel.addElement(number + " x " + i + " = " + (number * i));
}
}
});

JPanel panel = new JPanel();


panel.add(label);
panel.add(textField);
panel.add(button);
panel.add(new JScrollPane(list));

frame.add(panel);
frame.setSize(300, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
28. Write a java program to display multiplication table of a given number
into the List box by clicking on button.
Ans:
// Package named Series
package Series;

class Fibonacci {
public void printFibonacci(int n) {
int a = 0, b = 1;
System.out.print("Fibonacci Series: " + a + " " + b);
for (int i = 2; i < n; i++) {
int c = a + b;
System.out.print(" " + c);
a = b;
b = c;
}
System.out.println();
}
}

class Cube {
public void printCubes(int n) {
System.out.print("Cubes: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i * i + " ");
}
System.out.println();
}
}

class Square {
public void printSquares(int n) {
System.out.print("Squares: ");
for (int i = 1; i <= n; i++) {
System.out.print(i * i + " ");
}
System.out.println();
}
}

// Main Class
import Series.*;

public class SeriesTest {


public static void main(String[] args) {
int n = 10; // Example term count
Fibonacci fib = new Fibonacci();
fib.printFibonacci(n);

Cube cube = new Cube();


cube.printCubes(n);

Square square = new Square();


square.printSquares(n);
}
}
29. Create a package named Series having three different classes to print
series:
i) Fibonacci series
ii) Cube of numbers
iii) Square of numbers
Write a java program to generate ‘n’ terms of the above series
Ans:
import java.util.Scanner;

public class ArmstrongNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a number: ");
int number = scanner.nextInt();

if (isArmstrong(number)) {
System.out.println(number + " is an Armstrong number.");
} else {
System.out.println(number + " is not an Armstrong number.");
}
}

static boolean isArmstrong(int number) {


int sum = 0, original = number, digits = String.valueOf(number).length();
while (number > 0) {
int digit = number % 10;
sum += Math.pow(digit, digits);
number /= 10;
}
return sum == original;
}
}
30. Write a ‘java’ program to check whether given number is Armstrong or
not. (Use static keyword)
Ans:
import java.io.*;

public class NonNumericFileCopy {


public static void main(String[] args) {
try (BufferedReader br = new BufferedReader(new FileReader("source.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("destination.txt"))) {
String line;
while ((line = br.readLine()) != null) {
StringBuilder nonNumericLine = new StringBuilder();
for (char c : line.toCharArray()) {
if (!Character.isDigit(c)) {
nonNumericLine.append(c);
}
}
bw.write(nonNumericLine.toString());
bw.newLine();
}
System.out.println("Non-numeric data copied successfully.");
} catch (IOException e) {
e.printStackTrace();
}
}
}
31. Write a ‘java’ program to copy only non-numeric data from one file to
another file
Ans:
import java.io.*;

public class NonNumericFileCopy {


public static void main(String[] args) {
// Specify the source and destination file paths
String sourceFilePath = "source.txt"; // Source file to read from
String destinationFilePath = "destination.txt"; // Destination file to write to

try (BufferedReader br = new BufferedReader(new FileReader(sourceFilePath));


BufferedWriter bw = new BufferedWriter(new FileWriter(destinationFilePath))) {
String line;
// Read each line from the source file
while ((line = br.readLine()) != null) {
StringBuilder nonNumericLine = new StringBuilder();
// Check each character in the line
for (char c : line.toCharArray()) {
if (!Character.isDigit(c)) { // If character is not a digit, append it to the new
line
nonNumericLine.append(c);
}
}
// Write the non-numeric line to the destination file
bw.write(nonNumericLine.toString());
bw.newLine(); // Write a new line in the destination file
}
System.out.println("Non-numeric data copied successfully.");
} catch (IOException e) {
e.printStackTrace(); // Handle any I/O exceptions
}
}
}

Q4. Short Notes.


1. What is repaint method does?
Ans: The repaint() method in Java is used to request the system to repaint a component,
such as a window, panel, or any graphical user interface (GUI) element. When repaint()
is called, it schedules a call to the paint() method of the component, where the
rendering occurs. This is often used in situations where the visual representation of a
component needs to be updated, such as after a change in data or user interaction.
2. Write constructors of Jtabbed panel.
Ans: JTabbedPane is a Swing component that allows tabbed navigation. Here are some
common constructors:
 JTabbedPane(): Creates a new tabbed pane with default settings.
 JTabbedPane(int tabPlacement): Creates a new tabbed pane with the specified
tab placement (e.g., JTabbedPane.TOP, JTabbedPane.BOTTOM,
JTabbedPane.LEFT, JTabbedPane.RIGHT).
 JTabbedPane(int tabPlacement, int tabLayoutPolicy): Creates a new tabbed pane
with specified tab placement and layout policy (e.g.,
JTabbedPane.WRAP_TAB_LAYOUT, JTabbedPane.SCROLL_TAB_LAYOUT).
3. Abstract class.
Ans: An abstract class in Java is a class that cannot be instantiated on its own and is
meant to be subclassed. It can contain abstract methods (methods without a body) that
must be implemented by subclasses. Abstract classes can also have concrete methods
(methods with a body) and fields. They are used to define a base class with common
functionality that can be shared by derived classes.
4. Which are the predefined streams?
Ans: Java has three predefined streams for input and output:
 InputStream: An abstract class that represents an input stream of bytes.
Common subclasses include FileInputStream, ByteArrayInputStream, etc.
 OutputStream: An abstract class representing an output stream of bytes.
Common subclasses include FileOutputStream, ByteArrayOutputStream, etc.
 Reader: An abstract class for reading character streams. Common subclasses
include FileReader, BufferedReader, etc.
 Writer: An abstract class for writing character streams. Common subclasses
include FileWriter, BufferedWriter, etc.

5. Define multiple inheritance.


Ans: Multiple inheritance is a feature of some programming languages in which a class
can inherit properties and methods from more than one parent class. In Java, multiple
inheritance is not supported through classes to avoid ambiguity (the "diamond
problem"). However, a class can implement multiple interfaces, allowing for some level
of multiple inheritance.
6. Define object.
Ans: In Java, an object is an instance of a class. It represents a real-world entity that has
attributes (fields) and behaviors (methods). Objects are created from classes and can
interact with one another. Each object has its own state and can be manipulated
through its methods.
7. Define term finally block.
Ans: The finally block in Java is used to execute code after a try block, regardless of
whether an exception was thrown or caught. It is typically used for cleanup operations,
such as closing files or releasing resources. The finally block ensures that important
code runs, even if an exception occurs.
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle exception
} finally {
// Code that will always execute
}
8. What is package? Write down all the steps for package creation.
Ans: A package in Java is a namespace that organizes a set of related classes and
interfaces. It helps to avoid naming conflicts and can control access with visibility
modifiers.
Steps for Package Creation:
1. Create a Directory: Create a directory structure that matches the package name
(e.g., com/example).
2. Write the Class: Create a Java file within the package directory and include the
package declaration at the top of the file (e.g., package com.example;).
3. Compile the Class: Use the javac command to compile the Java file. The
compiled .class file will be placed in the package directory.
4. Use the Package: To use the package in another class, use the import statement
(e.g., import com.example.MyClass;).

9. Define new operator.


Ans: The new operator in Java is used to create new instances of classes or arrays.
When the new operator is used, it allocates memory for the object and calls the
constructor to initialize the object. The syntax for creating an object is as follows:
ClassName objectName = new ClassName();
10 . Define term finalize () method.
Ans: The finalize() method in Java is a method of the Object class that is called by the
garbage collector before an object is removed from memory. It can be overridden in a
class to perform cleanup operations, such as releasing resources. However, its use is
generally discouraged in favor of try-with-resources or explicit resource management
since there is no guarantee when or if finalize() will be executed.

protected void finalize() throws Throwable {


try {
// Cleanup code here
} finally {
super.finalize();
}
}

You might also like