Fifth Semester_JAVA_Question Answer

What is JVM?Explain features of java Programming language.(2077)

JVM (Java Virtual Machine) is an abstract machine that enables a computer to run Java programs.
When a Java program is compiled, it is converted into bytecode. This bytecode is not machine-dependent. The JVM interprets or compiles this bytecode into machine-specific instructions at runtime, making Java platform independent.

Main functions of JVM:

  • Loads bytecode

  • Verifies bytecode for security

  • Executes bytecode

  • Manages memory (Heap, Stack, Garbage Collection)

Features of Java Programming Language

  1. Platform Independent
    Java follows the principle “Write Once, Run Anywhere (WORA)”. Java bytecode can run on any system that has a JVM.

  2. Object-Oriented
    Java is based on OOP concepts such as class, object, inheritance, polymorphism, encapsulation, and abstraction, which make programs modular and reusable.

  3. Simple and Easy to Learn
    Java syntax is similar to C/C++ but removes complex features like pointers, operator overloading, and multiple inheritance (via classes), making it simpler.

  4. Secure
    Java provides strong security through bytecode verification, absence of pointers, sandbox execution, and Security Manager.

  5. Robust
    Java has automatic memory management (Garbage Collection), strong exception handling, and type checking, which reduce runtime errors.

What is constructor? write a java program to demonstrate different types of constructor.(2077)

A constructor is a special method in Java that is used to initialize objects. It has the same name as the class and does not have any return type. A constructor is automatically called when an object of the class is created.

Java program to demonstrate different types of constructor:

class ConstructorDemo { int x; int y; // Default constructor ConstructorDemo() { x = 0; y = 0; System.out.println("Default Constructor"); } // Parameterized constructor ConstructorDemo(int a, int b) { x = a; y = b; System.out.println("Parameterized Constructor"); } // Copy constructor ConstructorDemo(ConstructorDemo obj) { x = obj.x; y = obj.y; System.out.println("Copy Constructor"); } void display() { System.out.println("x = " + x + ", y = " + y); } public static void main(String[] args) { ConstructorDemo obj1 = new ConstructorDemo(); obj1.display(); ConstructorDemo obj2 = new ConstructorDemo(10, 20); obj2.display(); ConstructorDemo obj3 = new ConstructorDemo(obj2); obj3.display(); } }

This program demonstrates default constructor, parameterized constructor, and copy constructor in Java.

What is method overloading? Explain method loading with Suitable example.(2077)

Method overloading is a feature in Java that allows a class to have more than one method with the same name but with different parameters. The methods must differ in number of parameters, type of parameters, or both. Method overloading increases code readability and reusability.

Explanation of method overloading with suitable example:
In method overloading, multiple methods perform similar tasks but accept different arguments. The correct method is selected at compile time based on the method signature.

Java program example:

class MethodOverloading { int add(int a, int b) { return a + b; } int add(int a, int b, int c) { return a + b + c; } double add(double a, double b) { return a + b; } public static void main(String[] args) { MethodOverloading obj = new MethodOverloading(); System.out.println(obj.add(10, 20)); System.out.println(obj.add(10, 20, 30)); System.out.println(obj.add(5.5, 4.5)); } }

This example shows method overloading by changing the number and type of parameters while keeping the same method name.

What are different types of inheritances? Write a java program to demonstrate multilevel inheritance?(2077)

Inheritance is a mechanism in Java where one class acquires the properties and methods of another class.

Different types of inheritance are:

  1. Single inheritance
    One child class inherits from one parent class.

  2. Multilevel inheritance
    A class is derived from another derived class, forming a chain of inheritance.

  3. Hierarchical inheritance
    Multiple child classes inherit from a single parent class.

  4. Multiple inheritance (through interface)
    Java does not support multiple inheritance using classes, but it is supported using interfaces.

Java program to demonstrate multilevel inheritance:

class Animal { void eat() { System.out.println("Animal eats food"); } } class Dog extends Animal { void bark() { System.out.println("Dog barks"); } } class Puppy extends Dog { void weep() { System.out.println("Puppy weeps"); } } public class MultilevelInheritance { public static void main(String[] args) { Puppy p = new Puppy(); p.eat(); p.bark(); p.weep(); } }

This program demonstrates multilevel inheritance where Puppy inherits from Dog and Dog inherits from Animal.

How interface differes from class? Explain the concept of method overriding with example.(2077)

Interface and class are both used to achieve abstraction in Java, but they differ in several ways.

  1. An interface supports multiple inheritance, whereas a class does not support multiple inheritance.

  2. Methods in an interface are abstract by default, whereas a class can have abstract as well as concrete methods.

  3. An interface cannot have instance variables, only public static final variables (constants), whereas a class can have instance variables.

  4. A class uses the keyword extends to inherit another class, whereas a class implements an interface using the keyword implements.

  5. An interface cannot have constructors, whereas a class can have constructors.

Concept of method overriding with example:
Method overriding occurs when a subclass provides a specific implementation of a method that is already defined in its superclass. The method name, return type, and parameters must be the same. Method overriding is used to achieve runtime polymorphism.

Java program example:

class Parent { void show() { System.out.println("This is Parent class method"); } } class Child extends Parent { @Override void show() { System.out.println("This is Child class method"); } } public class MethodOverridingDemo { public static void main(String[] args) { Parent obj = new Child(); obj.show(); } }

In this example, the show() method of Child class overrides the show() method of Parent class, and the method call is decided at runtime.

What are different categories of exceptions ? Explain use of throws and thrrow clause with example.(2077)

Exceptions in Java are unwanted or abnormal events that occur during program execution.

Different categories of exceptions are:

  1. Checked exceptions
    These exceptions are checked at compile time. The programmer must handle them using try-catch or declare them using throws. Example: IOException, SQLException.

  2. Unchecked exceptions
    These exceptions are checked at runtime. They occur due to programming errors. Example: ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException.

  3. Errors
    Errors are serious problems that cannot be handled by the program. Example: OutOfMemoryError, StackOverflowError.

Use of throws and throw with example:

throws clause:
The throws keyword is used in a method declaration to indicate that the method may pass an exception to the calling method.

throw keyword:
The throw keyword is used to explicitly throw an exception inside a method or block.

Java program example:

class ExceptionDemo { // Method using throws static void checkAge(int age) throws ArithmeticException { if (age < 18) { // Using throw throw new ArithmeticException("Not eligible to vote"); } else { System.out.println("Eligible to vote"); } } public static void main(String[] args) { try { checkAge(16); } catch (ArithmeticException e) { System.out.println("Exception caught: " + e.getMessage()); } } }

In this program, the throws keyword declares the exception, and the throw keyword is used to generate the exception manually.

What is stream? Discuss the character stream classes of java with suitable example.(2077)

A stream in Java is a sequence of data that flows from a source to a destination. Streams are used to perform input and output operations such as reading from files, keyboard, or writing to files.

Character stream classes of Java:
Character streams are used to read and write data in the form of characters. They are mainly used for handling text data. Character streams use 16-bit Unicode characters.

Main character stream classes are:

  1. Reader
    Reader is an abstract class used for reading character streams.

Important subclasses of Reader are:
FileReader – used to read characters from a file
BufferedReader – used to read text efficiently and supports readLine() method
InputStreamReader – converts byte stream to character stream

  1. Writer
    Writer is an abstract class used for writing character streams.

Important subclasses of Writer are:
FileWriter – used to write characters to a file
BufferedWriter – used to write text efficiently
OutputStreamWriter – converts character stream to byte stream

Suitable Java example:

import java.io.*; class CharacterStreamDemo { public static void main(String[] args) throws IOException { // Writing to a file using character stream FileWriter fw = new FileWriter("sample.txt"); fw.write("Hello Java Character Stream"); fw.close(); // Reading from a file using character stream FileReader fr = new FileReader("sample.txt"); int ch; while ((ch = fr.read()) != -1) { System.out.print((char) ch); } fr.close(); } }

This program demonstrates the use of FileWriter and FileReader, which are character stream classes in Java.

Differentiate between component and container? Explain handling of action event with suitable example.(2077)

Differentiate between component and container:

Component:
A component is a basic GUI element that can be displayed on the screen. It does not contain other components. Examples are Button, Label, TextField, Checkbox.

Container:
A container is a special type of component that can hold and organize other components inside it. Examples are Frame, Panel, Dialog, Applet.

Difference points:

  1. Component cannot contain other components, container can contain components.

  2. Component is a single UI element, container is used to group UI elements.

  3. Example of component: Button, Label. Example of container: Frame, Panel.

Handling of ActionEvent with suitable example:
ActionEvent occurs when an action is performed, such as clicking a button. In Java, ActionEvent is handled using ActionListener interface. The actionPerformed() method is overridden to define the action.

Java program example:

import java.awt.*; import java.awt.event.*; class ActionEventDemo extends Frame implements ActionListener { Button b; ActionEventDemo() { b = new Button("Click Me"); b.addActionListener(this); add(b); setSize(300, 200); setLayout(new FlowLayout()); setVisible(true); } public void actionPerformed(ActionEvent e) { System.out.println("Button Clicked"); } public static void main(String[] args) { new ActionEventDemo(); } }

In this program, when the button is clicked, an ActionEvent is generated and handled by the actionPerformed() method.

What is byte code? Discuss Java architecture with suitable figure.(2079)

Bytecode is an intermediate code generated by the Java compiler. When a Java source program (.java) is compiled, it is converted into bytecode (.class). This bytecode is not specific to any machine and can run on any system that has a Java Virtual Machine (JVM). Bytecode makes Java platform independent.

Java architecture with suitable figure:
Java architecture explains how a Java program is executed using different components like JDK, JRE, JVM, compiler, and libraries.

Java architecture consists of the following components:

  1. Java Source Code
    The program written by the programmer using Java language.

  2. Java Compiler (javac)
    The compiler converts source code into bytecode.

  3. Bytecode
    The compiled code that is stored in .class file.

  4. Java Virtual Machine (JVM)
    JVM loads, verifies, and executes the bytecode. It converts bytecode into machine code according to the operating system.

  5. Java Runtime Environment (JRE)
    JRE includes JVM and Java class libraries required to run Java programs.

  6. Java Development Kit (JDK)
    JDK includes JRE, compiler, debugger, and other development tools.

Suitable figure (text diagram):

Java Source Code (.java) | v Java Compiler (javac) | v Bytecode (.class) | v Java Virtual Machine (JVM) | v Operating System | v Hardware

What are different type of loops isn java? Write a java program to find factorial of entered number.(2079)

Loops are used to execute a block of code repeatedly until a given condition is satisfied.

Different types of loops in Java are:

  1. for loop
    Used when the number of iterations is known.

  2. while loop
    Used when the condition is checked before executing the loop body.

  3. do-while loop
    Used when the loop body must execute at least once.

  4. enhanced for loop (for-each loop)
    Used to iterate through arrays and collections.

Java program to find factorial of entered number:

import java.util.Scanner; class Factorial { public static void main(String[] args) { int n, fact = 1; Scanner sc = new Scanner(System.in); System.out.print("Enter a number: "); n = sc.nextInt(); for (int i = 1; i <= n; i++) { fact = fact * i; } System.out.println("Factorial of " + n + " is " + fact); } }

This program uses a for loop to calculate the factorial of the entered number.

Discuss the concept of static data members and static methods with example.(2079)

Concept of static data members:
Static data members are variables declared using the static keyword. They belong to the class, not to any specific object. Only one copy of a static data member is shared among all objects of the class. Static data members are used to store common data.

Concept of static methods:
Static methods are methods declared using the static keyword. They also belong to the class rather than to objects. A static method can access only static data members directly and cannot use non-static members without creating an object.

Java example:

class StaticDemo { static int count = 0; // static data member StaticDemo() { count++; } static void displayCount() { // static method System.out.println("Number of objects created: " + count); } public static void main(String[] args) { StaticDemo obj1 = new StaticDemo(); StaticDemo obj2 = new StaticDemo(); StaticDemo obj3 = new StaticDemo(); StaticDemo.displayCount(); } }

In this program, the static variable count is shared by all objects, and the static method displayCount() accesses the static data member without creating an object.

what is interface? How it can be used for achieving multiple inheritance? Explain with example.(2079)

An interface in Java is a collection of abstract methods and constants. It is used to achieve complete abstraction. Methods in an interface do not have a body and are implemented by a class using the implements keyword.

How interface is used to achieve multiple inheritance:
Java does not support multiple inheritance using classes to avoid ambiguity. However, Java supports multiple inheritance through interfaces. A class can implement more than one interface, thus inheriting methods from multiple sources.

Explanation with example:

interface A { void showA(); } interface B { void showB(); } class C implements A, B { public void showA() { System.out.println("Method of interface A"); } public void showB() { System.out.println("Method of interface B"); } public static void main(String[] args) { C obj = new C(); obj.showA(); obj.showB(); } }

In this example, class C implements two interfaces A and B. This demonstrates multiple inheritance in Java using interfaces.

Why inheritance is important ? Write a java program to demonstrate single inheritance.(2079)

Inheritance is important in Java because it allows code reusability. A new class can use the properties and methods of an existing class, which reduces code duplication. It also helps in achieving extensibility, maintainability, and supports runtime polymorphism. Inheritance makes programs more organized and easier to manage.

Java program to demonstrate single inheritance:

class Parent { void display() { System.out.println("This is parent class"); } } class Child extends Parent { void show() { System.out.println("This is child class"); } } public class SingleInheritanceDemo { public static void main(String[] args) { Child obj = new Child(); obj.display(); obj.show(); } }

This program demonstrates single inheritance where the Child class inherits properties of the Parent class.

What is exception? Discuss the use of try... catch... finally with suitable example.(2079)

An exception is an unwanted or abnormal event that occurs during the execution of a program and disrupts the normal flow of the program.

Use of try, catch, and finally:
try block is used to write the code that may cause an exception.
catch block is used to handle the exception that occurs in the try block.
finally block is used to execute important code such as closing files or releasing resources. The finally block executes whether an exception occurs or not.

Java program example:

class TryCatchFinallyDemo { public static void main(String[] args) { try { int a = 10; int b = 0; int c = a / b; // exception occurs System.out.println(c); } catch (ArithmeticException e) { System.out.println("Exception caught: Division by zero"); } finally { System.out.println("Finally block executed"); } } }

In this program, the exception occurs in the try block, it is handled in the catch block, and the finally block is executed in all cases.

What are byte stream classes? Explain the classes with example.(2079)

Byte stream classes in Java are used to read and write data in the form of bytes (8-bit). They are mainly used to handle binary data such as images, audio, and video files. Byte streams are based on InputStream and OutputStream abstract classes.

Byte stream classes in Java:

  1. InputStream
    InputStream is an abstract class used to read byte data.

Important subclasses of InputStream are:
FileInputStream – reads bytes from a file
BufferedInputStream – improves performance by buffering input
DataInputStream – reads primitive data types

  1. OutputStream
    OutputStream is an abstract class used to write byte data.

Important subclasses of OutputStream are:
FileOutputStream – writes bytes to a file
BufferedOutputStream – improves performance by buffering output
DataOutputStream – writes primitive data types

Java example:

import java.io.*; class ByteStreamDemo { public static void main(String[] args) throws IOException { // Writing to a file using byte stream FileOutputStream fos = new FileOutputStream("data.txt"); fos.write("Hello Byte Stream".getBytes()); fos.close(); // Reading from a file using byte stream FileInputStream fis = new FileInputStream("data.txt"); int b; while ((b = fis.read()) != -1) { System.out.print((char) b); } fis.close(); } }

This program demonstrates the use of FileInputStream and FileOutputStream, which are byte stream classes in Java.

What is event handling? Explain handling of action events with example.(2079)

Event handling in Java is a mechanism that controls the events (like mouse clicks, key presses, button clicks) generated by the user or system. It allows a program to respond to user actions, making programs interactive.

Handling of Action Events:
ActionEvent occurs when a user performs an action, such as clicking a button. In Java, ActionEvents are handled using the ActionListener interface. The class that wants to handle the event must implement ActionListener and override the actionPerformed() method. The event source (like a button) is linked to the listener using the addActionListener() method.

Java example:

import java.awt.*; import java.awt.event.*; class ActionEventDemo extends Frame implements ActionListener { Button b; ActionEventDemo() { b = new Button("Click Me"); b.addActionListener(this); // registering the listener add(b); setSize(300, 200); setLayout(new FlowLayout()); setVisible(true); } public void actionPerformed(ActionEvent e) { System.out.println("Button was clicked!"); } public static void main(String[] args) { new ActionEventDemo(); } }

Explanation:

  • A Button b is created.

  • addActionListener(this) links the button to the ActionListener.

  • When the button is clicked, the actionPerformed() method is called, handling the event.

This is how action events are captured and processed in Java.

What is polymorphism? Write example program to illustrate method overriding.(2079i)

Polymorphism in Java is the ability of an object to take many forms. It allows the same method or object to behave differently based on the context. Polymorphism is mainly of two types:

  1. Compile-time polymorphism (Method Overloading) – same method name with different parameters.

  2. Runtime polymorphism (Method Overriding) – a subclass provides its own implementation of a method defined in the parent class.

Example program to illustrate method overriding:

class Parent { void show() { System.out.println("This is parent class method"); } } class Child extends Parent { @Override void show() { System.out.println("This is child class method"); } } public class PolymorphismDemo { public static void main(String[] args) { Parent obj1 = new Parent(); Parent obj2 = new Child(); // runtime polymorphism obj1.show(); // calls parent method obj2.show(); // calls child method } }

Explanation:

  • The show() method is defined in both Parent and Child classes.

  • At runtime, the JVM decides which version of show() to call based on the object type.

  • This is an example of runtime polymorphism through method overriding.

Differentiate between switch and if statement with example program

Difference between switch and if statement:

  1. Decision type:

  • if is used for conditional decisions based on expressions (true/false) and relational operators.

  • switch is used for multiple-choice decisions based on a single variable or expression.

  1. Data type:

  • if can evaluate boolean expressions and ranges.

  • switch works only with int, char, String, byte, short, or their wrappers.

  1. Number of conditions:

  • if can handle complex conditions and ranges.

  • switch is better for discrete constant values.

  1. Execution:

  • if checks conditions sequentially.

  • switch jumps directly to the matching case.


Example program using if and switch:

import java.util.Scanner; public class DecisionDemo { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Using if statement System.out.print("Enter a number: "); int num = sc.nextInt(); if (num > 0) { System.out.println("Positive number"); } else if (num < 0) { System.out.println("Negative number"); } else { System.out.println("Zero"); } // Using switch statement System.out.print("Enter a day number (1-7): "); int day = sc.nextInt(); switch (day) { case 1: System.out.println("Sunday"); break; case 2: System.out.println("Monday"); break; case 3: System.out.println("Tuesday"); break; case 4: System.out.println("Wednesday"); break; case 5: System.out.println("Thursday"); break; case 6: System.out.println("Friday"); break; case 7: System.out.println("Saturday"); break; default: System.out.println("Invalid day"); } sc.close(); } }

This program shows the difference: if handles ranges and conditions, while switch handles discrete constant values.

Why throws keyword is used in exception handling? Write a program to handle exception of array index out of bound error.

The throws keyword in Java is used in a method declaration to declare the exceptions that a method may throw during its execution. It tells the caller of the method that they must handle or propagate these exceptions. This is mainly used for checked exceptions.


Java program to handle ArrayIndexOutOfBoundsException:

import java.util.Scanner; class ArrayExceptionDemo { // Method declares that it may throw ArrayIndexOutOfBoundsException static void accessArray(int arr[], int index) throws ArrayIndexOutOfBoundsException { System.out.println("Element at index " + index + " is: " + arr[index]); } public static void main(String[] args) { int[] arr = {10, 20, 30, 40, 50}; Scanner sc = new Scanner(System.in); System.out.print("Enter index to access: "); int index = sc.nextInt(); try { accessArray(arr, index); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Exception caught: Index out of bounds"); } sc.close(); } }

Explanation:

  • The method accessArray() declares throws ArrayIndexOutOfBoundsException.

  • If the user enters an invalid index, an exception occurs.

  • The exception is caught in the try-catch block and handled gracefully.

This demonstrates the use of throws for exception propagation and handling Array Index Out of Bound error.

How abstract class is created in java? Explain why abstract class is used in program with supportive example.

An abstract class in Java is declared using the abstract keyword. It may contain abstract methods (methods without a body) as well as concrete methods (methods with a body). Abstract classes cannot be instantiated directly; they must be subclassed, and the abstract methods must be implemented in the subclass.

Why abstract class is used:

  1. To provide partial abstraction – a class can have both implemented and unimplemented methods.

  2. To define a common template for subclasses.

  3. To enforce that certain methods must be implemented in subclasses.

  4. To achieve code reusability and polymorphism.


Java Example:

abstract class Shape { abstract void area(); // abstract method void display() { // concrete method System.out.println("This is a shape"); } } class Circle extends Shape { double radius; Circle(double r) { radius = r; } void area() { // implementing abstract method System.out.println("Area of Circle: " + (3.14 * radius * radius)); } } public class AbstractClassDemo { public static void main(String[] args) { Circle c = new Circle(5); c.display(); // calls concrete method of abstract class c.area(); // calls implemented abstract method } }

Explanation:

  • Shape is an abstract class with one abstract method area() and one concrete method display().

  • Circle extends Shape and provides implementation for area().

  • Abstract classes allow us to define common behavior while forcing subclasses to implement specific methods.

This is how abstract classes provide flexibility and partial abstraction in Java.

Write java program that create database to store 2 book(isbn, title, author, price page) records.

import java.sql.*;

public class BookDemo { public static void main(String[] args) { try { Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/", "root", "password"); Statement stmt = con.createStatement(); stmt.executeUpdate("CREATE DATABASE IF NOT EXISTS BookDB"); stmt.executeUpdate("USE BookDB"); stmt.executeUpdate("CREATE TABLE IF NOT EXISTS Book(isbn VARCHAR(20), title VARCHAR(50), author VARCHAR(50), price DOUBLE, pages INT)"); stmt.executeUpdate("INSERT INTO Book VALUES('ISBN001','Java Basics','John Doe',450,300)"); stmt.executeUpdate("INSERT INTO Book VALUES('ISBN002','Advanced Java','Jane Smith',600,400)"); stmt.close(); con.close(); } catch (Exception e) { System.out.println(e); } } }

Notes:

  • This creates the database and table.

  • Inserts 2 book records.

  • No unnecessary prints or extra code – exactly what the question asks.

write java program to create gui window that contain two text field and two buttons using grid layout.


Here’s a simple Java program that creates a GUI window with two text fields and two buttons using GridLayout:

import java.awt.*; import javax.swing.*; public class GridLayoutDemo { public static void main(String[] args) { // Create a frame JFrame frame = new JFrame("GridLayout Example"); // Set GridLayout with 2 rows and 2 columns frame.setLayout(new GridLayout(2, 2, 10, 10)); // 10px gap // Create text fields JTextField tf1 = new JTextField(); JTextField tf2 = new JTextField(); // Create buttons JButton b1 = new JButton("Button 1"); JButton b2 = new JButton("Button 2"); // Add components to frame frame.add(tf1); frame.add(tf2); frame.add(b1); frame.add(b2); // Set frame size and behavior frame.setSize(300, 150); frame.setVisible(true); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } }

Explanation:

  • JFrame creates the window.

  • GridLayout(2, 2) arranges components in 2 rows and 2 columns.

  • JTextField is used for text fields, JButton for buttons.

  • Components are added in order: tf1, tf2, b1, b2.

What is adapter class? Why adapter class is used in programs? Explain with examples.

An adapter class in Java is a class that provides empty (default) implementations of all methods in an interface. It acts as a bridge between an interface and the class that wants to use the interface. Adapter classes are mainly used with event handling interfaces that have multiple methods, like MouseListener or KeyListener.

Why adapter class is used:

  1. To avoid implementing all methods of an interface if you need only a few of them.

  2. To reduce boilerplate code.

  3. Makes it easier to handle events without writing unnecessary empty methods.

Example with MouseAdapter:

import java.awt.*; import java.awt.event.*; public class AdapterDemo extends Frame { AdapterDemo() { setTitle("Adapter Class Example"); setSize(300, 200); setLayout(new FlowLayout()); addMouseListener(new MouseAdapter() { @Override public void mouseClicked(MouseEvent e) { System.out.println("Mouse Clicked at (" + e.getX() + ", " + e.getY() + ")"); } }); setVisible(true); } public static void main(String[] args) { new AdapterDemo(); } }

Explanation:

  • MouseListener interface has 5 methods.

  • Using MouseAdapter, we override only the method we need (mouseClicked) instead of all 5 methods.

  • This makes code cleaner and easier to manage.

Write java program to take 2 double data from user and store them in fine named tendouble.txt

Here’s the version that appends double values to the file so it won’t overwrite previous entries:

import java.io.*; import java.util.Scanner; public class StoreDoubleInFile { public static void main(String[] args) { try { Scanner sc = new Scanner(System.in); System.out.print("Enter first double value: "); double num1 = sc.nextDouble(); System.out.print("Enter second double value: "); double num2 = sc.nextDouble(); // FileWriter in append mode FileWriter fw = new FileWriter("tendouble.txt", true); fw.write(num1 + "\n"); fw.write(num2 + "\n"); fw.close(); System.out.println("Values stored in tendouble.txt successfully."); sc.close(); } catch (Exception e) { System.out.println(e); } } }

✅ Features:

  • Takes 2 doubles from user.

  • Stores them in tendouble.txt.

  • Appends new values without deleting old ones.

  • Minimal, exam-ready, works perfectly.



Comments

Popular posts from this blog

Third Semester_Web Technology_Quesiton Answer