Ad
Monday, August 28, 2023
Object Oriented Programming using Java - 1 : TYBCS : SPPU : PYQs
Chapter 1 An Introduction to Java
1 m
Q. What is JAR file?
- A JAR (Java ARchive) file is a compressed archive format used in Java to package multiple files, including Java class files, resources, and metadata, into a single file.
Q. What is an applet?
Answer: An applet is a java program that runs in a web browser. It is designed to be included in HTML document.
Q. What is java?
- Java is a high-level object oriented programming language. It combines both data and functions that operate on data into a single unit (i.e. an object).
Q. What is final variable?
Answer: Final variable is a variable with a value that cannot be modified during the execution of the program.
It is declared with following syntax:
final data_type varName=value;
Q. What is JDK?
- JDK (Java Development Kit) is a software development environment used to develop java applications.
Q. What is JRE?
- It is a set of software tools used to develop java applications. It provides runtime environment. Java Runtime Environment.
- c) What is javadoc?
- Javadoc is a tool in Java used for generating documentation. Documentation is made using special comments within the source code. It contains clear explanations of classes, methods, and their usage. The generated documentation helps in code understanding and usage by other developers.
(b) List primitive data types in Java with their width in bits.
- Following are the primitive data types in Java with their width in bits:
byte: 8 bits
short: 16 bits
int: 32 bits
long: 64 bits
float: 32 bits
double: 64 bits
char: 16 bits
boolean: Not strictly defined, but typically represented as 8 bits (1 byte)
(a) What do you mean by jdb ?
- jdb stands for Java Debugger, which is a command-line debugging tool that comes with the Java Development Kit (JDK).
It's used by Java developers to find and fix errors (bugs) in their Java programs.
Q. What is Object?
- It is an instance of class which has it's unique data .
Q. What is Class?
- It is a blueprint that defines structure and behaviour of objects.
e) What is Javadoc comments?
- Javadoc comments are special comments in Java code that are used to create documentation for classes, methods, fields, and other program elements.Javadoc comments start with /** and use specific tags (e.g., @param, @return, @throws) to structure and organize the information.
f) What is command line argument?
- A command-line argument in Java is input data that we pass to a program when running it from the command line or terminal. These arguments are accessed through the args parameter in the main method and allow us to customize the program's behavior without changing its code.
(a) What is the use of javap tool ?
- The javap tool in Java is used to disassemble compiled .class files, revealing the bytecode instructions that make up the Java code. It helps developers understand how Java code is translated into bytecode, providing insights into the low-level details of the program's structure, methods, fields, and interfaces.
(b) What is blank final variable ?
-
A blank final variable in Java is a variable that is declared asfinal
but is not assigned a value when it is declared. Instead, it is assigned a value only once, typically in the constructor of the class or in an instance initialization block. Once a value is assigned to a blank final variable, it cannot be changed again.(c) “Java is platform dependant language.” True/False ? Justify.
Answer: False. Java is often described as a platform-independent or "write once, run anywhere" language. This is due to its ability to run on any platform that has a compatible Java Virtual Machine (JVM). Here's the justification:
Q. Name any four tags of Javadoc.
Answer: Following are the tags of javadoc:
@param: Used to describe the parameters of a method , explaining their purpose and expected values.
@return: Describes the value that a method returns, explaining its meaning and possible outcomes.
@throws : Specifies the exceptions that a method might throw and provides details about when these exceptions can occur.
@see: Provides links to other related classes, methods, or fields that developers might find useful when using or understanding the current code.
4 mark
Q. Explain the process of compilation of Java program.
Answer:
1. The java code is written using text editor which contains instructions that program will execute,
2. Once ready, we use Java Compiler using javac file_name command in command line.
3. Javac compiler creates a file named filename.class which contians bytecode version of the program.
4. This bytecode file is loaded into memory using JVM which interprets the bytecode and executes the programs logic step by step.
a) Write a Java program to accept a number from user. If it is zero then throw user defined exception "Number is zero". Otherwise calculate its factorial.
Q. Explain how the input is accepted from command line with the help of program.
Answer: The Java command line argument is an argument passed at runtime. The arguments passed from console can be received in java program and it can be used as an input.
The argument is passed to main() from the command line and these areguments are stored in parameter of main() which is an array of string objects, i.e. args[].
Program:
public class commdLineArg
{
public static void main(String args[])
{
System.out.println("Total arguments passed are" + args.length);
System.out.println("Each of them are");
for(int k=0; k<args.length; k++)
System.out.println ("arg["+k+"]:" + args [k]);
}
}
Output:
java commdLineArg I am a girl
Total Arguments passed are 4
Each of them are:
arg[0] : I
arg[1]: am
arg[2]: a
arg[3]: girl
Here we use public static void main(String args[]) to receive the arguments passed in command line.
The arguments supplied are of string type in array of string objects.
Q. Write a java program to find second smallest element in array.
- Answer:
public class SecondSmallestElement {
public static void main(String[] args) {
int[] array = {5, 2, 8, 1, 3, 7}; // Replace this with your array
if (array.length < 2) {
System.out.println("Array should have at least two elements.");
return;
}
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int num : array) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num != smallest) {
secondSmallest = num;
}
}
if (secondSmallest == Integer.MAX_VALUE) {
System.out.println("No second smallest element found.");
} else {
System.out.println("The second smallest element is: " + secondSmallest);
}
}
}
Q. Explain various ways to read input string from console or keyboard.
Answer: Java provides following ways to accept input from the user:
1) Using BufferedReader Class: The java.io.BufferedReader class reads text from a character-input stream.
Class declaration:
public class BufferedReader
extends Reader
Class constructors:
1. BufferedReader(Reader in) : It uses default-sized input buffer.
2. BufferedReader(Reader in, int sz): It uses an input buffer of specified size.
Class Methods:
1. int read(): Reads single character.
2. String readLine(): Reads a line of text.
3. long skip(long n) : Skips characters.
2) Using Command Line Arguments: It is the argument passed at time of running a java program.
The arguments are stored in parameter of main() which is an array of string objects - args[].
public static void main(String args[]) is used to receive argument.
3) Using Scanner Class: It can be used to read input from user by importing java.util.Scanner package.
Class Methods:
1. int nextInt(): Scans next token of input as integer.
2. String nextLine(): Scans the currrent line.
3. byte nextByte(): Scans the next token of input as a Byte.
b) Explain the features of Java.
:- Following are the features of Java:
1. Simple: It is a simple language and easy to learn since it dosen't use concepts like pointers, preprocessors, headerfiles, etc.
2. Object Oriented: All the program code in java is present within objects and classes.
3. Platform Independent: It can run on multiple platforms like windows, Linus, Mac Os, etc.
4. Interpreted: Java is an interpreted language i.e. programs run directly from the source code.
5. Dynamic: It can dynamically link in new class libraries, methods and objects at runtime.
6. Secure: It does not allocate direct pointer to memory which makes it very secure.
7: Arcihtecture Neutral: Java compiler generates object file which is executable on many processors.
8: Portable: Java environment can be easily ported to different architectures,
9: High performance: It uses JIT (Just in Time) Compilers which increases its performace.
10. Multithreading: We can write programs that can perform many tasks simultaneously.
Q. Why is Java called purely object oriented programming language ? Explain features of Java.
Answer: Java is called purely object oriented programming language because:
Everything in Classes: In Java, all code is organized within classes.
Objects Everywhere: Java focuses on using objects as the building blocks of programs.
Inheritance and Polymorphism: Java allows classes to inherit properties from other classes and enables objects to be treated as instances of their parent classes, promoting code reuse.
Abstraction with Interfaces:In Java, we can make a plan called an "interface" that describes what a group of classes should be able to do. This helps keep different parts of a program separate and makes it easier to work on one thing at a time.
Chapter 2 Objects and Classes
1m
e) What is use of static keyword?
Answer: The static keyword in Java is used to declare members (fields and methods) that belong to the class rather than to any specific instance of the class. It means that the static member is shared among all instances of the class and can be accessed using the class name.
(c) What is the use of this keyword in Java ?
The this keyword in Java is a reference variable that refers to the current object.
g) List the types of constructor.
h) What is package?
Answer: In Java, a package is a way to organize related classes and interfaces into a single unit.
h) Which method is used for first time initialization in Applet?
The init()
method is used for first-time initialization in an Applet.
(d) Write down syntax for equals() method.
Answer: public boolean equals(Object obj)
This method is used to compare the calling object with the object passed as an argument. It returns true if the objects are equal; otherwise, it returns false. The equals() method is often overridden in user-defined classes to define the criteria for equality.
(e) What is deep copy in cloning ?
Answer: Deep copy in cloning refers to the process of creating a new object that is a complete and independent copy of another object, including all nested objects within it.
(g) What is the use of finally block ?
The finally block in Java is used to define a block of code that will be executed regardless of whether an exception is thrown or not.
(b) List any two methods of object class.
Answer: toString(): Returns a string representation of the object. It is often overridden in user-defined classes to provide a meaningful string representation.
hashCode(): Returns a hash code value for the object. It is used by hash-based data structures like hash tables.
(i) Which method is used to compare values of 2 string objects ?
Answer: The equals() method is used to compare the values of two string objects in Java.
2 mark
a) List any two methods of string buffer class.
Answer:
append(String str): Appends the specified string to the end of the StringBuffer.
insert(int offset, String str): Inserts the specified string at the specified position in the StringBuffer.
b) What is use of 'throw' keyword.
Answer: The throw keyword in Java is used to explicitly throw an exception.
3 mark
c) Write a Java program to find second smallest element in an array.
public class SecondSmallestElement {
public static void main(String[] args) {
int[] arr = {5, 8, 2, 10, 7};
int smallest = Integer.MAX_VALUE;
int secondSmallest = Integer.MAX_VALUE;
for (int num : arr) {
if (num < smallest) {
secondSmallest = smallest;
smallest = num;
} else if (num < secondSmallest && num != smallest) {
secondSmallest = num;
}
}
System.out.println("Second smallest element: " + secondSmallest);
}
}
(c) Write a java program to find second smallest element in an array.
a) Write a Java program to count number of vowels from given string.
public class CountVowels {
public static void main(String[] args) {
String input = "Hello, World!";
int vowelCount = 0;
// Convert the input string to lowercase to handle both uppercase and lowercase vowels
input = input.toLowerCase();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u') {
vowelCount++;
}
}
System.out.println("Number of vowels: " + vowelCount);
}
}
c) What is package? How to create a package. Explain with example.
c) Enlist any two method of string with syntax. [2]
(b) What is difference between string and string buffer class.
(b) How do we design, create and access a package in java ? Discuss with suitable example.
Chapter 3 Inheritance and Interface
1 m
b) Define Interface
An interface in Java is a collection of abstract methods. It declares a set of methods that must be implemented by any class that implements the interface.
c) What is use of final keyword?
Answer: The final keyword in Java has different uses:
Final Variable: If a variable is declared as final, its value cannot be changed once assigned.
Final Method: If a method is declared as final in a class, it cannot be overridden by subclasses.
Final Class: If a class is declared as final, it cannot be extended, i.e., no other class can inherit from it.
(f) What is the use of final keyword ?
j) What is difference between repaint and update method.
repaint(): This method is used to request the repainting of a component. When repaint() is called, it eventually leads to the invocation of the paint() method. It is commonly used to update the appearance of a component.
update(): This method is called automatically after repaint() and is responsible for clearing the previous state of the component before repainting.
(c) When we declare a method or class final ?
Answer: Final Method: When you want to prevent the method from being overridden by subclasses. This is often done to ensure that the method's implementation remains consistent across all subclasses.
Final Class: When you want to prevent the class from being extended. This is useful when you have a class that should not have any subclasses, perhaps because it represents a complete or core functionality.
2 mark
c) Differentiate between final and finally keyword.
Answer: final: It is a keyword used to declare a variable constant, a method not to be overridden, or a class not to be extended.
finally: It is used in exception handling. The code inside the finally block will always be executed, whether an exception is thrown or not. It is typically used for cleanup operations.
d) What is method overloading?
Method overloading in Java occurs when two or more methods in the same class have the same name but different parameters (either the number or the type of parameters).
(c) Explain the use of this keyword in java. [2]
(b) Explain 2 types of Inheritance with suitable example. [3]
Answer:
Single inheritence:
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog is barking");
}
}
In this example, Dog inherits from Animal, demonstrating single inheritance.
Multiple inheritence
interface A {
void methodA();
}
interface B {
void methodB();
}
class C implements A, B {
public void methodA() {
System.out.println("Implementation of methodA");
}
public void methodB() {
System.out.println("Implementation of methodB");
}
}
4 mark
c) Define an interface shape with abstract method area( ). Write a Java program to calculate area of rectangle
Answer: interface Shape {
double area();
}
class Rectangle implements Shape {
private double length;
private double width;
public Rectangle(double length, double width) {
this.length = length;
this.width = width;
}
public double area() {
return length * width;
}
}
public class TestRectangle {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(5.0, 3.0);
System.out.println("Area of Rectangle: " + rectangle.area());
}
}
b) Write a Java program to illustrate multilevel inheritance such that state is inherited from country. City is inherited from state. Display city, state and country.
Answer:
class Country {
String countryName;
Country(String name) {
this.countryName = name;
}
}
class State extends Country {
String stateName;
State(String countryName, String stateName) {
super(countryName);
this.stateName = stateName;
}
}
class City extends State {
String cityName;
City(String countryName, String stateName, String cityName) {
super(countryName, stateName);
this.cityName = cityName;
}
void displayInfo() {
System.out.println("City: " + cityName);
System.out.println("State: " + stateName);
System.out.println("Country: " + countryName);
}
}
public class TestInheritance {
public static void main(String[] args) {
City myCity = new City("USA", "California", "Los Angeles");
myCity.displayInfo();
}
}
b) Explain uses of super-keyword with suitable example.
b) Write difference between Abstract class and Interface. [3]
(iii) Write down any two differences between the abstract class and interface
(a) What is runtime polymorphism ? How is it implemented in java ? Give suitable example.
Chapter 4 Exception and File Handling
1 m
a) Define exception
Answer: An exception in Java is an abnormal event that disrupts the normal flow of a program during its execution.
i) How to open a file in read mode?
Answer: import java.io.*;
public class ReadFile {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("example.txt");
// Perform reading operations here
fileInputStream.close(); // Close the file when done
} catch (IOException e) {
e.printStackTrace();
}
}
}
a) What is JAR file?
Answer: A JAR (Java Archive) file is a platform-independent file format that aggregates multiple files (typically .class files, images, and other resources) into a single archive.
f) Define Unchecked exception.
Answer: Unchecked exceptions in Java, also known as runtime exceptions, are exceptions that are not checked at compile time.
(e) Define unchecked exception.
Answer:
(h) Which method is used to set the current position of the file pointer within the file.
Answer: The seek(long pos)
method of the RandomAccessFile
class is used to set the current position of the file pointer within the file.
4 mark
(a) What are user-defined exceptions ? Illustrate them with an example.
Answer: User-defined exceptions in Java are exceptions that are created by the programmer to handle specific situations in the code. To create a user-defined exception, a new class is defined that extends the built-in Exception class.
class InvalidProductException extends Exception {
public InvalidProductException(String message) {
super(message);
}
}
public class ProductDetails {
public static void main(String[] args) {
try {
acceptProductDetails("123", "Laptop", 120);
} catch (InvalidProductException e) {
System.out.println("Exception: " + e.getMessage());
}
}
static void acceptProductDetails(String productCode, String productName, int weight) throws InvalidProductException {
if (weight > 100) {
throw new InvalidProductException("Invalid Product: Weight exceeds the limit");
} else {
System.out.println("Product Code: " + productCode);
System.out.println("Product Name: " + productName);
System.out.println("Weight: " + weight + " grams");
}
}
}
(ii) Write a java program to display the contents of the file in reverse order.
Answer: import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.Stack;
public class ReverseFileContent {
public static void main(String[] args) {
try (BufferedReader reader = new BufferedReader(new FileReader("example.txt"))) {
Stack<String> lines = new Stack<>();
String line;
// Read lines and push them onto the stack
while ((line = reader.readLine()) != null) {
lines.push(line);
}
// Pop and print lines from the stack to display in reverse order
while (!lines.isEmpty()) {
System.out.println(lines.pop());
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
(iii) What is checked and unchecked exceptions ? [2]
Answer: Checked Exceptions: Checked exceptions are exceptions that are checked at compile time. They are subclasses of Exception (excluding RuntimeException and its subclasses). These exceptions must be either caught using a try-catch block or declared using the throws clause in the method signature.
Unchecked Exceptions (Runtime Exceptions): Unchecked exceptions are exceptions that are not checked at compile time. They are subclasses of RuntimeException or its subclasses. Programmers are not required to catch or declare these exceptions explicitly.
(b) Write a java program which display the contents of file in reverse order.
(c) What is stream ? Explain the types of streams supported by java.
Answer: In Java, a stream is a sequence of data elements that supports various operations to perform computations on those elements. Java supports two types of streams:
Byte Streams:
InputStream and OutputStream are the base classes for reading and writing binary data.
Examples: FileInputStream, FileOutputStream, BufferedInputStream, BufferedOutputStream.
Character Streams:
Reader and Writer are the base classes for reading and writing character data.
Examples: FileReader, FileWriter, BufferedReader, BufferedWriter.
b) Write a Java program to copy content from one file into another file, while copying digits are replaced by '*'.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class CopyReplaceDigits {
public static void main(String[] args) {
try (FileReader reader = new FileReader("input.txt");
FileWriter writer = new FileWriter("output.txt")) {
int c;
while ((c = reader.read()) != -1) {
// Replace digits with '*'
if (Character.isDigit((char) c)) {
writer.write('*');
} else {
writer.write(c);
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
a) Write a Java program to appends the content of one file to another.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class AppendFiles {
public static void main(String[] args) {
try (FileReader reader = new FileReader("file1.txt");
FileWriter writer = new FileWriter("file2.txt", true)) {
int c;
while ((c = reader.read()) != -1) {
writer.write(c);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
b) What are user defined exceptions? Illustrate them with an example.
User-defined exceptions in Java are exceptions that are created by the programmer to handle specific situations in the code. To create a user-defined exception, a new class is defined that extends the built-in Exception
class or one of its subclasses.
Example:
// User-defined exception class class InvalidProductException extends Exception { public InvalidProductException(String message) { super(message); } } // Main class public class ProductDetails { public static void main(String[] args) { try { acceptProductDetails("123", "Laptop", 120); } catch (InvalidProductException e) { System.out.println("Exception: " + e.getMessage()); } } // Method to accept product details static void acceptProductDetails(String productCode, String productName, int weight) throws InvalidProductException { if (weight > 100) { // Throw the user-defined exception throw new InvalidProductException("Invalid Product: Weight exceeds the limit"); } else { // Display product details System.out.println("Product Code: " + productCode); System.out.println("Product Name: " + productName); System.out.println("Weight: " + weight + " grams"); }
(a) Write a java program to accept the details of product as productcode, productname and weight. If weight > 100 then throw an exception as InvalidProduct Exception and give the proper message. Otherwise display the product details. Define required exception class.
Answer:
// User-defined exception class
class InvalidProductException extends Exception {
public InvalidProductException(String message) {
super(message);
}
}
// Product class
class Product {
String productCode;
String productName;
int weight;
// Constructor to initialize product details
public Product(String productCode, String productName, int weight) {
this.productCode = productCode;
this.productName = productName;
this.weight = weight;
}
// Method to validate product weight
public void validateProduct() throws InvalidProductException {
if (weight > 100) {
throw new InvalidProductException("Invalid Product: Weight exceeds the limit");
} else {
System.out.println("Product Code: " + productCode);
System.out.println("Product Name: " + productName);
System.out.println("Weight: " + weight + " grams");
}
}
}
// Main class
public class ProductDetails {
public static void main(String[] args) {
// Example usage
Product laptop = new Product("123", "Laptop", 120);
try {
laptop.validateProduct();
} catch (InvalidProductException e) {
System.out.println("Exception: " + e.getMessage());
}
}
}
Chapter 5 User Interface with AWT and Swing
1m
(d) What is AutoBoxing and unboxing ?
d) What is AWT?
Answer: AWT stands for Abstract Window Toolkit. It is a part of JFC (Java Foundation Classes). It is a standard API for providing graphical user interface (GUI) for java program.
j) List any two listener.
Answer: Listener Is an object that watch for events and handles them when they occur.
Types of listeners:
1) Mouse listener: This interface is used for receiving mouse events.
2) Key listener: This interface is used for receiving key events.
3) Action listener: This interface is used for receiving action events.
i) What is Anonymous classes?
Answer: It is a class in java which has no name. They are used for creating event listeners where short implementation is needed.
a) Explain Inner and Nested class with example.
Answer:
2 mark
e) What is anonymous inner class?
Answer: Anonymous classes in java are more accurately known as anonymous inner class. They are defined insider another class.
4 mark
(j) Why swing objects are called as light weight components ?
Answer: The swing objects are light weight components because they are rendered mostly using pure JAVA code instead of operating system calls.
(c) Explain inner class with an example.
a) Write a Java program using AWT to change background color of table to 'RED' by clicking on button.
c) Differentiate between AWT and swing.
Answer:
Feature | AWT | Swing |
---|---|---|
Platform Dependency | Platform-dependent | Platform-independent |
Component Type | Heavyweight | Lightweight |
Customization | Limited | Extensive |
Components | Basic set | Rich set |
Performance | May have issues | Generally better |
Popularity | Widely used historically | Common in modern GUI development |
(B) (i) Explain Layout Managers used in AWT. [4]
Answer: In AWT layout managers are used to control placement and sizing of components within a container. They help us organize components within a container.
AWT provides several layout managers:
1) FlowLayout Manager:
-Here the components are arranged in left to right flow.
- It wraps the component to next row if there is not enough space.
- Few of it's constructors are
FlowLayout() : It centers all components and leaves five pixel spaces between each component.
FlowLayout(int align): It allows to specify how each line of component is align
i.e. Flowlayout.LEFT
Flowlayout.RIGHT
Flowlayout.Centre
2) Grid Layout Manager:
: It arranges components in a two dimensional grid. It has a defined number of rows and columns.
- It places items in rows (left to right) and columns (top to bottom).
- The components are present in cells and each of them have same size.
- Few of it's contructors:
GridLayout(): It creates single column grid layout.
GridLayout(int numRows, int numColumns) : It creates a grid layout with specified number of rows and columns.
3) Card Layout Manager:
- It arranges each component in a container as a card.
- Only one card is visible at a time, container acts as stack of cards.
- It has following constructors:
CardLayout(): It creates default card layout.
CardLayout(int horz, int vert): It allows us to specify horizontal and vertical space left between components horizontically and vertically respectively.
- (c) What is use of layout manager ? Explain any one layout manager ?
a) Write a Java program which will create a frame if we try to close it. It should change it’s color Red and it display closing message on the screen.(Use swing)
b) What are the different types of dialogs in Java? Write any one in detail
Answer: Dialogs are GUI elements in java used to interact with user, to gather input or present information.
Types of Dialogs
1) Message Dialogs: It displays informative messages to users like warning, error or general information.
JOptionPane.showMessageDialog();
2) JFile Chooser: Allows users to select files or directories.
JFileChooser(File currentDirectory)
3) JColor Chooser: Allows user to pick a color.
JColorChooser(Color initialColor): This constructor creates a color chooser pane with specified initial color.
c) Which swing classes are used to create menu? [2]
Answer: Swing classes used to create menus are :
1) JMenuBar: It represents menu bar , which is located at top of swing application.
2) JMenu: It represents a menu inside a menu bar.
3) JMenuItem: It represents an item in a menu.
4) JPopupMenu: It represents a pop-up menu that can be shown at specific location.
(b) How is menu created in java ? Explain with suitable example.
Answer:
(i) What is the use of Checkboxes and RadioButtons ? Explain with suitable example.
Answer: Checkboxes and Radiobuttons are components used in GUI allows users to make selections or choices. They are types of input components. They are used when users need to provide input by selecting one or more options from a set of choices.
Checkboxes are used when users can make multiple selections from a group of options.
Example of checkboxes:
JCheckBox checkbox1= new JCheckBox("Option 1");
JCheckBox checkbox2= newJCheckBox("Option 2");
JCheckBox checkbox3= newJCheckBox("Option 3");
RadioButtons are used when users need to make a single selection from a group of mutually exclusive options.
JRadioButton radioButton1 = new JRadioButton("Option 1"); JRadioButton radioButton2 = new JRadioButton("Option 2"); JRadioButton radioButton3 = new JRadioButton("Option 3");
(h) Write a syntax of JFileChooser class.
Answer: The JFileChooser class in Java Swing is used to create a file dialog that allows user to select files or directories.
import javax.swing.JFileChooser;
JFileChooser fileChooser = new JFileChooser(); int result = fileChooser.showOpenDialog(null); if (result == JFileChooser.APPROVE_OPTION) { java.io.File selectedFile = fileChooser.getSelectedFile(); // Process the selected file } else { // User canceled file selection }
(c) Write a program in java to create a screen which contains three checkboxes (.net, php, java) and displays the selected items in a textbox.
(g) Explain the use of repaint ( ).
Answer: The repaint() method is used to request that a component be repainted. When you call repaint(), it schedules a call to the component's paint() method, which is responsible for rendering the appearance of the component.
b) What is meant by Garbage collection?
Answer: . In Java, memory is allocated to objects during runtime, and when an object is no longer in use or referenced by any part of the program, it becomes eligible for garbage collection.
(f) What is meant by Garbage collection ?
d) “Import statement is not essential in Java”. True/False? Justify.
False. The import statement in Java is essential for using classes and packages from external libraries or packages
g) List any two methods of file class.
Two methods of the File class in Java are:
createNewFile(): This method is used to create a new, empty file at the specified location.
delete(): This method is used to delete the file or directory specified by the File object.
(A) a) Write a program to read string from user, reverse it and display the reverse string on textbox using Applets
Answer:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ReverseStringApplet extends Applet implements ActionListener {
TextField inputText, outputText;
public void init() {
Label inputLabel = new Label("Enter a String:");
inputText = new TextField(20);
Button reverseButton = new Button("Reverse");
outputText = new TextField(20);
reverseButton.addActionListener(this);
add(inputLabel);
add(inputText);
add(reverseButton);
add(outputText);
}
public void actionPerformed(ActionEvent e) {
String input = inputText.getText();
String reversed = new StringBuilder(input).reverse().toString();
outputText.setText(reversed);
}
}
(j) Which method is used for first time initialization in applet ?
Answer:
The init() method is used for first-time initialization in an applet.
(e) What is deep copy in cloning ?
Answer: Deep copy in cloning refers to the process of creating a new object that is a complete and independent copy of another object, including all nested objects within it.
(a) Write a java program to implement operations of queue which is of the fixed size. It uses an interface queue, containing two methods addq() and delq(), which are implemented by queue class.
Answer:
interface Queue {
void addq(int item);
int delq();
}
class FixedSizeQueue implements Queue {
private int maxSize;
private int[] queueArray;
private int front;
private int rear;
private int nItems;
public FixedSizeQueue(int size) {
maxSize = size;
queueArray = new int[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void addq(int item) {
if (nItems == maxSize) {
System.out.println("Queue is full. Cannot add element.");
return;
}
if (rear == maxSize - 1) {
rear = -1;
}
queueArray[++rear] = item;
nItems++;
}
public int delq() {
if (nItems == 0) {
System.out.println("Queue is empty. Cannot delete element.");
return -1;
}
int temp = queueArray[front++];
if (front == maxSize) {
front = 0;
}
nItems--;
return temp;
}
}
public class TestQueue {
public static void main(String[] args) {
FixedSizeQueue myQueue = new FixedSizeQueue(5);
myQueue.addq(10);
myQueue.addq(20);
myQueue.addq(30);
System.out.println("Deleted element: " + myQueue.delq());
System.out.println("Deleted element: " + myQueue.delq());
}
}
(i) State any four methods of WindowListener.
Answer: Four methods of the WindowListener interface in Java are:
windowOpened(WindowEvent e): Invoked when a window has been opened.
windowClosing(WindowEvent e): Invoked when the user attempts to close the window, such as by clicking the close button.
windowClosed(WindowEvent e): Invoked when the window has been closed as a result of the user closing it.
windowActivated(WindowEvent e): Invoked when the window is set to be the active window.
(b) Write a java program to create a package named student. Define class studentInfo with method to display information about student such as rollno, name, class and percentage. Create another class studentPer with method to find percentage of the student. Accept student details like rollno, name, class and marks of three subject from user.
Answer: package student;
import java.util.Scanner;
public class StudentInfo {
public void displayInfo(int rollNo, String name, String studentClass, double percentage) {
System.out.println("Student Information:");
System.out.println("Roll Number: " + rollNo);
System.out.println("Name: " + name);
System.out.println("Class: " + studentClass);
System.out.println("Percentage: " + percentage + "%");
}
}
class StudentPer {
public double calculatePercentage(int marks1, int marks2, int marks3) {
return (marks1 + marks2 + marks3) / 3.0;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter Roll Number:");
int rollNo = scanner.nextInt();
System.out.println("Enter Name:");
String name = scanner.next();
System.out.println("Enter Class:");
String studentClass = scanner.next();
System.out.println("Enter Marks in three subjects:");
int marks1 = scanner.nextInt();
int marks2 = scanner.nextInt();
int marks3 = scanner.nextInt();
StudentInfo studentInfo = new StudentInfo();
StudentPer studentPer = new StudentPer();
double percentage = studentPer.calculatePercentage(marks1, marks2, marks3);
studentInfo.displayInfo(rollNo, name, studentClass, percentage);
scanner.close();
}
}
(ii) Explain the Applet Life Cycle. [4]
Answer: The life cycle of an applet in Java consists of several stages:
Initialization (init): This method is called when the applet is first loaded. It is used for one-time initialization tasks such as setting up variables, creating GUI components, or loading resources.
Start (start): The start method is called after init and is used to start or resume the execution of the applet. It is called whenever the user returns to the page containing the applet.
Stop (stop): The stop method is called when the applet is no longer visible or is being replaced by another applet. It is used to suspend the execution or perform cleanup tasks.
Destroy (destroy): The destroy method is called when the applet is about to be unloaded. It is used for cleanup operations such as releasing resources or closing streams.
(d) How print() is differ from print() method ?
Answer: In Java, print() and println() are methods used to display output in the console:
print(): This method is used to print the specified content to the console without moving the cursor to the next line. Subsequent output will appear on the same line.
println(): This method is used to print the specified content to the console and then move the cursor to the next line. Subsequent output will appear on a new line.
(a) Differentiate between Java & C++.
Answer:
(a) Create an applet which contains three radio buttons red, green and blue and change the background color to the selected color.
Answer:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChangeApplet extends Applet implements ItemListener {
CheckboxGroup colorGroup;
Checkbox redCheckbox, greenCheckbox, blueCheckbox;
public void init() {
colorGroup = new CheckboxGroup();
redCheckbox = new Checkbox("Red", colorGroup, false);
greenCheckbox = new Checkbox("Green", colorGroup, false);
blueCheckbox = new Checkbox("Blue", colorGroup, false);
redCheckbox.addItemListener(this);
greenCheckbox.addItemListener(this);
blueCheckbox.addItemListener(this);
add(redCheckbox);
add(greenCheckbox);
add(blueCheckbox);
}
public void itemStateChanged(ItemEvent e) {
Color selectedColor = null;
if (redCheckbox.getState()) {
selectedColor = Color.RED;
} else if (greenCheckbox.getState()) {
selectedColor = Color.GREEN;
} else if (blueCheckbox.getState()) {
selectedColor = Color.BLUE;
}
if (selectedColor != null) {
setBackground(selectedColor);
repaint();
}
}
}
(e) What is assertion ?
Answer:
An assertion in Java is a statement that is used to declare a condition that should be true at a particular point in a program's execution. It is primarily used for debugging and testing purposes. Assertions are enabled or disabled at runtime, and if an assertion is false, it typically indicates a bug in the code.
About Abhishek Dhamdhere
Qna Library Is a Free Online Library of questions and answers where we want to provide all the solutions to problems that students are facing in their studies. Right now we are serving students from maharashtra state board by providing notes or exercise solutions for various academic subjects
No comments:
Post a Comment