0% found this document useful (0 votes)
3 views53 pages

Java Entire File

The document outlines various Java programming experiments, each with specific aims such as printing messages, taking user input, generating Fibonacci series, checking prime numbers, and implementing data structures like stacks and queues. Each experiment includes theoretical explanations, source code, expected outputs, and a set of viva voice questions and answers related to the concepts demonstrated. The document serves as a comprehensive guide for learning Java programming fundamentals and concepts.

Uploaded by

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

Java Entire File

The document outlines various Java programming experiments, each with specific aims such as printing messages, taking user input, generating Fibonacci series, checking prime numbers, and implementing data structures like stacks and queues. Each experiment includes theoretical explanations, source code, expected outputs, and a set of viva voice questions and answers related to the concepts demonstrated. The document serves as a comprehensive guide for learning Java programming fundamentals and concepts.

Uploaded by

rsharmaa483
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

EXPERIMENT 1

AIM: To write a Java program that prints “Hello <Your Name> – <Enrolment Number>” on
the screen.

THEORY:
Java is an object-oriented, platform-independent programming language.
A Java program starts execution from the main() method.
In this program:
• class defines the blueprint of the program.
• public static void main(String[] args) is the entry point of execution.
• [Link]() is used to display output on the screen.
This program demonstrates the basic structure of a Java program and how output is printed.

SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is Java?
A1: Java is a high-level, object-oriented, and platform-independent programming language.

Q2: What is the main() method?


A2: The main() method is the starting point of execution for any Java program.

Q3: Why is [Link]() used?


A3: It is used to print output on the console.

Q4. What does class keyword mean in Java?


A4: It is used to define a class, which is a blueprint for objects.

Q5: Is Java case-sensitive?


A5: Yes, Java is a case-sensitive language.
EXPERIMENT 1

AIM: To write a Java program that takes user input for name, enrollment number, and age,
and displays the entered details on the screen.

THEORY:
Java provides the Scanner class (from [Link] package) to take input from the user during
program execution.
In this program:
• Scanner class is used to read input from the keyboard.
• nextLine() method is used to read string values such as name and enrollment number.
• nextInt() method is used to read integer values such as age.
• [Link]() is used to display the entered details on the screen.
• The main() method acts as the entry point of the program.
This program demonstrates how user input is taken and displayed using Java.

SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is Scanner class in Java?
A1: Scanner class is used to take input from the user.

Q2: Which package contains the Scanner class?


A2: [Link] package.

Q3: What is the use of nextLine() method?


A3: It is used to read string input including spaces.

Q4. What does nextInt() method do?


A4: It reads an integer value from the user.

Q5: Why is [Link]() used?


A5: It closes the Scanner object and frees system resources.
EXPERIMENT 3

AIM: To write a Java program to print the designated Fibonacci series by taking the number
of terms from the user.

THEORY:
The Fibonacci series is a sequence of numbers in which each number is the sum of the two
preceding numbers, starting from 0 and 1.
In this program:
• The user enters the number of terms of the Fibonacci series.
• Variables are used to store the first two terms.
• A for loop is used to generate the Fibonacci series.
• Scanner class is used to take input from the user.
• [Link]() is used to display the series on the screen.
This program demonstrates the use of loops and user input in Java.
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is Fibonacci series?
A1: It is a series where each term is the sum of the previous two terms.

Q2: Which loop is used in this program?


A2: for loop is used.

Q3: What are the first two terms of Fibonacci series?


A3: 0 and 1.

Q4. Why is Scanner class used?


A4: To take input from the user.

Q5: What happens if the number of terms is 0?


A5: No output will be printed.
EXPERIMENT 4

AIM: To write a Java program to check whether a given number is a prime number or not.

THEORY:
A prime number is a natural number greater than 1 that has exactly two distinct positive
divisors: 1 and itself.
In this program:
• The user enters a number using the Scanner class.
• Numbers less than or equal to 1 are automatically considered not prime.
• A loop checks divisibility of the number from 2 to √n, which is an optimized approach.
• If the number is divisible by any value in this range, it is not a prime number.
• A boolean flag variable is used to store the result.
• [Link]() is used to display whether the number is prime or not.
This program demonstrates the use of conditional statements, loops, and optimized logic in
Java.
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. Why did you use [Link](num) in the loop condition?
A1: Because a number cannot have a factor greater than its square root without having a
corresponding smaller factor. This reduces the number of iterations and improves efficiency.

Q2: Why do we check divisibility only till √n?


A2: Because if a number has a factor greater than √n, it must also have a corresponding
factor smaller than √n.

Q3: What will happen if we check divisibility till num - 1 instead?


A3: The result will be correct, but the program will take more time and be inefficient.

Q4. What is the time complexity of this prime number program?


A4: The time complexity is O(√n).

Q5: What is the role of break statement in the loop?


A5: It stops the loop immediately when a divisor is found, saving unnecessary comparisons.
EXPERIMENT 5

AIM: To write a Java program to convert temperature from Celsius to Fahrenheit and
Fahrenheit to Celsius.

THEORY:
Temperature conversion is commonly required in scientific and daily-life applications.
Celsius and Fahrenheit are two widely used temperature scales.
The conversion formulas are:
• Celsius to Fahrenheit:
𝐹 = (𝐶 × 9/5) + 32
• Fahrenheit to Celsius:
𝐶 = (𝐹 − 32) × 5/9
In this program:
• A menu is displayed to the user for selecting the type of conversion.
• The Scanner class is used to take user input.
• Conditional statements (if–else) are used to perform the selected conversion.
• [Link]() is used to display the converted temperature.
This program demonstrates the use of conditional statements, arithmetic operations, and
user input in Java.
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. Which formulas are used for temperature conversion?
A1: C to F → (C × 9 / 5) + 32
F to C → (F − 32) × 5 / 9

Q2: Why is double used instead of int?


A2: Because temperature values can be fractional.

Q3: Why is a menu used in this program?


A3: To allow the user to choose between two types of temperature conversions.

Q4. Which conditional statement is used here?


A4: if–else if–else statement.

Q5: What happens if the user enters an invalid choice?


A5: The program prints “Invalid choice!”.
EXPERIMENT 6

AIM: To write a Java program to create a simple calculator for two numbers using basic
arithmetic operators.

THEORY:
A calculator performs arithmetic operations such as addition, subtraction, multiplication, and
division.
In this program:
• Two numbers are taken as input from the user.
• A menu is displayed showing the available arithmetic operations.
• The user selects an operator (+, -, *, /).
• A switch statement is used to perform the selected operation.
• Division by zero is handled using a conditional check.
• The Scanner class is used to take user input.
• The result of the operation is displayed using [Link]().
This program demonstrates the use of switch-case statements, arithmetic operators, and
user input in Java.
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. Why is switch statement used instead of if-else?
A1: switch makes the code more readable and efficient when multiple choices are present.

Q2: Why is charAt(0) used?


A2: To extract the first character entered by the user as an operator.

Q3: How is division by zero handled?


A3: By checking if the second number is not zero before division.

Q4. Why is double used for numbers?


A4: To support decimal values in calculations.

Q5: What happens if the user enters an invalid operator?


A5: The default case executes and displays “Invalid operator!”.
EXPERIMENT 7

AIM: To write a Java program to check whether a given year is a leap year or not.

THEORY:
A leap year contains 366 days instead of 365 days.
According to the Gregorian calendar, a year is a leap year if:
• It is divisible by 4
• But not divisible by 100
• Except if it is divisible by 400
That means:
• If a year is divisible by 400 → Leap Year
• If divisible by 4 but not by 100 → Leap Year
• Otherwise → Not a Leap Year
In this program:
• The user enters a year.
• Conditional statements are used to check leap year conditions.
• The result is displayed using [Link]().
This program demonstrates the use of conditional statements and logical operators in Java.
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is a leap year?
A1: A leap year has 366 days and occurs every 4 years with specific conditions.

Q2: Why is year % 400 == 0 checked first?


A2: Because years divisible by 400 are always leap years, even if they are divisible by 100.
Checking it first avoids incorrect rejection of century leap years like 2000.

Q3: Why can’t we simply write if(year % 4 == 0)?


A3: Because some years divisible by 4 (like 1900) are not leap years. Century years must also
satisfy divisibility by 400.

Q4. What happens if the user enters a negative year?


A4: The program will still evaluate divisibility mathematically, but negative years are not
practically valid calendar years.

Q5: Can the entire logic be written in one single condition?


A5: Yes
if ((year % 400 == 0) || (year % 4 == 0 && year % 100 != 0))
EXPERIMENT 8

AIM: To write a Java program to implement stack and queue concept.

THEORY:
Stack and Queue are linear data structures used to store and manage data.
• Stack follows LIFO (Last In First Out) principle.
o Operations: push, pop, peek
• Queue follows FIFO (First In First Out) principle.
o Operations: enqueue, dequeue, peek
In this program:
• Java’s built-in Stack class is used for stack implementation.
• Queue interface with LinkedList is used for queue implementation.
• Elements are inserted and removed to demonstrate working.
This program demonstrates:
• Data structure concepts
• Use of Java Collection Framework
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is a Stack?
A1: A stack is a linear data structure that follows LIFO (Last In First Out).

Q2: What is a Queue?


A2: A queue is a linear data structure that follows FIFO (First In First Out).

Q3: What is the difference between push and pop?


A3: push adds an element to stack, while pop removes the top element.

Q4. Which class is used to implement Queue in Java?


A4: LinkedList class is commonly used to implement Queue.

Q5: What does peek() do?


A5: It returns the top/front element without removing it.
EXPERIMENT 9

AIM: To write a Java program to produce the tokens from a given long string.

THEORY:
Tokenization is the process of breaking a string into smaller parts called tokens.
In Java, tokens can be generated using:
• StringTokenizer class
• split() method
In this program:
• A long string is taken as input.
• The string is divided into tokens based on spaces or delimiters.
• Each token is printed separately.
This demonstrates:
• String handling in Java
• Use of built-in classes for parsing

SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is tokenization?
A1: It is the process of breaking a string into smaller parts called tokens.

Q2: Which class is used for tokenization in Java?


A2: StringTokenizer class.

Q3: Can we use split() instead of StringTokenizer?


A3: Yes, the split() method of String class can also be used.

Q4. What does hasMoreTokens() do?


A4: It checks if more tokens are available.

Q5: What does nextToken() return?


A5: It returns the next token from the string.
EXPERIMENT 10

AIM: To write a Java package to demonstrate dynamic polymorphism and interfaces.

THEORY:
A Java package is a group of related classes and interfaces used to organize programs and
avoid naming conflicts. It makes large programs easier to manage and reuse.
Dynamic polymorphism (runtime polymorphism) is a feature where the method call is
resolved at runtime using method overriding. A superclass or interface reference can refer to
different subclass objects, and the method executed depends on the object created at
runtime.
An interface is a blueprint that contains abstract methods. Classes implement the interface
and provide definitions for its methods. This helps achieve abstraction and multiple
inheritance.
In this program, an interface defines a common method, and multiple classes implement it
differently. An interface reference is used to call methods of different classes, demonstrating
dynamic polymorphism.
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is dynamic polymorphism?
A1: It is the ability to decide which method to call at runtime.

Q2: What is an interface in Java?


A2: An interface is a collection of abstract methods implemented by classes.

Q3: How is polymorphism achieved here?


A3: Using an interface reference pointing to different class objects.

Q4. Can we create an object of an interface?


A4: No, but we can create a reference variable of an interface.

Q5: What is method overriding?


A5: It is redefining a method in a class that implements an interface or extends a class.
EXPERIMENT 11

AIM: Write a Java program to show multithreaded producer and consumer application.

THEORY:
Producer and Consumer is a classic example of multithreading in Java used to handle
synchronization between threads.
• Producer thread produces data and places it in a shared resource.
• Consumer thread consumes the data from the shared resource.
• Both threads must be synchronized to avoid conflicts.
In this program:
• A shared object is used between producer and consumer.
• Producer produces values and consumer consumes them.
• Synchronization is achieved using synchronized methods.
• wait() is used when a thread is waiting.
• notify() is used to wake up waiting threads.
This program demonstrates:
• Multithreading concept
• Inter-thread communication
• Synchronization using wait() and notify()
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is multithreading?
A1: It is the execution of multiple threads simultaneously.

Q2: What is Producer-Consumer problem?


A2: It is a problem where one thread produces data and another consumes it.

Q3: What is synchronization?


A3: It is a mechanism to control access of shared resources by multiple threads.

Q4. What does wait() do?


A4: It makes a thread wait until another thread notifies it.

Q5: What does notify() do?


A5: It wakes up a waiting thread.
EXPERIMENT 12

AIM: Create a customized exception and also make use of all the 5 exception keywords.

THEORY:
Exception handling in Java is used to handle runtime errors and maintain normal program
flow.
• A custom exception is created by extending the Exception class.
• Java provides five keywords for exception handling: try, catch, finally, throw, and throws.
• try block contains code that may cause exception.
• catch block handles the exception.
• finally block always executes.
• throw is used to explicitly throw an exception.
• throws is used to declare exceptions.
In this program:
• A custom exception is created.
• Exception is thrown using throw.
• Method declares exception using throws.
• try, catch, and finally blocks are used.
This program demonstrates:
• Custom exception creation
• Use of all exception handling keywords
• Exception handling mechanism in Java
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is an exception?
A1: It is an event that disrupts normal program execution.

Q2: What is a custom exception?


A2: It is a user-defined exception created by extending Exception class.

Q3: Name the five exception keywords.


A3: try, catch, finally, throw, throws.

Q4. W What does throw do?


A4: It is used to explicitly throw an exception.

Q5: What does throws do?


A5: It declares exceptions that a method can throw.
EXPERIMENT 13

AIM: Convert the content of a given file into the uppercase content of the same file.

THEORY:
File handling in Java allows us to read from and write to files. This experiment demonstrates
how to manipulate file data.
• Java provides classes like FileReader, BufferedReader, FileWriter, and BufferedWriter
for file operations.
• The file is read line by line using BufferedReader.
• Each line is converted into uppercase using the toUpperCase() method.
• The modified content is written back to the same file using BufferedWriter.
This program demonstrates:
• File reading and writing
• String manipulation
• Handling I/O exceptions

SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is file handling in Java?
A1: It is the process of reading from and writing to files.

Q2: What does toUpperCase() do?


A2: It converts all characters of a string to uppercase.

Q3: Which classes are used for file reading?


A3: FileReader and BufferedReader.

Q4. Which classes are used for file writing?


A4: FileWriter and BufferedWriter.

Q5: What exception is commonly used in file handling?


A5: IOException.
EXPERIMENT 14

AIM: Write a program in java to sort the content of a given text file.

THEORY:
Sorting file content is a common file-handling operation in Java. This program reads data from
a text file, sorts it, and writes the sorted content back.
• File content is read using BufferedReader.
• Each line is stored in a collection like ArrayList.
• The list is sorted using [Link]().
• Sorted data is written back using BufferedWriter.
This program demonstrates:
• File reading and writing
• Use of ArrayList
• Sorting using [Link]()
• Handling exceptions
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. Which method is used for sorting in Java?
A1: [Link]().

Q2: Which data structure is used to store file content?


A2: ArrayList.

Q3: How is file reading done in this program?


A3: Using BufferedReader.

Q4. What type of sorting is performed here?


A4: Lexicographical (alphabetical) sorting

Q5: What exception is handled in this program?


A5: IOException.
EXPERIMENT 15

AIM: Develop an analog clock using applet.

THEORY:
An applet is a Java program that runs inside a web browser or applet viewer. It is used to create
dynamic and interactive graphical applications.
• The analog clock is created using Java Applet and AWT (Abstract Window Toolkit).
• The paint() method is used to draw shapes like circles and lines.
• The clock consists of hour, minute, and second hands.
• The current system time is fetched using Date or Calendar class.
• Trigonometric functions (sin, cos) are used to calculate positions of clock hands.
This program demonstrates:
• Use of Applet
• Graphics in Java
• Real-time clock simulation
• Use of trigonometry in GUI
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is an applet?
A1: A Java program that runs inside a browser or applet viewer.

Q2: Which method is used for drawing in applet?


A2: paint() method.

Q3: Which package is used for graphics?


A3: [Link].

Q4. How is time obtained in this program?


A4: Using Calendar class.

Q5: Why are trigonometric functions used?


A5: To calculate positions of clock hands.
EXPERIMENT 16

AIM: Develop a scientific calculator using swings.

THEORY:
Java Swing is a GUI toolkit used to create window-based applications. It provides components
like buttons, text fields, and panels.
• A scientific calculator performs both basic and advanced mathematical operations.
• Swing components like JFrame, JTextField, and JButton are used.
• Event handling is done using ActionListener.
• Mathematical functions are implemented using the Math class (e.g., sin, cos, sqrt).
This program demonstrates:
• GUI development using Swing
• Event handling
• Mathematical operations
• Layout management
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is Swing in Java?
A1: It is a GUI toolkit used to create window-based applications.

Q2: Which class is used to create a window?


A2: JFrame.

Q3: Which interface handles button events?


A3: ActionListener.

Q4. Which class provides mathematical functions?


A4: Math class.

Q5: What layout is used in this program?


A5: GridLayout and BorderLayout.
EXPERIMENT 17

AIM: Create an editor like MS-word using swings.

THEORY:
Java Swing provides powerful GUI components to build applications like text editors.
• A text editor allows users to create, edit, save, and open text files.
• JTextArea is used for writing text.
• JMenuBar, JMenu, and JMenuItem are used to create menu options like File and Edit.
• File handling is done using FileReader and FileWriter.
• Event handling is managed using ActionListener.
This program demonstrates:
• GUI development using Swing
• Menu-driven applications
• File handling (Open, Save)
• Event handling
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. Which component is used for text editing?
A1: JTextArea.

Q2: Which class is used to create menu bar?


A2: JMenuBar.

Q3: How are files opened in this program?


A3: Using FileReader and BufferedReader.

Q4. Which component is used for file selection?


A4: JFileChooser.

Q5: What is the purpose of ActionListener?


A5: To handle user actions like button clicks.
EXPERIMENT 18

AIM:Create a servlet that uses Cookies to store the number of times a user has visited your
servlet.

THEORY:
Servlets are Java programs that run on a web server and handle client requests.
• Cookies are small pieces of data stored on the client side.
• They are used to track user information like visit count.
• Cookie class is used to create and manage cookies.
• HttpServletRequest is used to read cookies.
• HttpServletResponse is used to send cookies to the client.
This program:
• Checks if a cookie exists
• If yes → increments visit count
• If no → creates a new cookie
• Displays number of visits
SOURCE CODE:
OUTPUT:

VIVA VOICE:
Q1. What is a cookie?
A1: A small piece of data stored on the client side.

Q2: Which class is used to create cookies?


A2: Cookie class.

Q3: How do you read cookies in servlet?


A3: Using [Link]().

Q4. How do you send cookies to client?


A4: Using [Link]().

Q5: What is setMaxAge()?


A5: It sets the lifetime of a cookie.
EXPERIMENT 19

AIM: Create a simple java bean having bound and constrained properties.

THEORY:
A Java Bean is a reusable software component that follows certain conventions such as
having a no-argument constructor, getter and setter methods, and implementing serializable
interfaces.
There are two special types of properties in Java Beans:
• Bound Property:
A property that notifies other objects when its value changes using
PropertyChangeListener.
• Constrained Property:
A property that allows other objects to validate or reject changes using
VetoableChangeListener.
In this program:
• A Java Bean class is created.
• It contains a property (e.g., "value").
• Property change support is added using PropertyChangeSupport.
• Vetoable change support is added using VetoableChangeSupport.
• Listeners are implemented to handle changes and validations.
This program demonstrates:
• Java Bean conventions
• Event handling
• Bound and constrained properties
• Listener interfaces
SOURCE CODE:

OUTPUT:
VIVA VOICE:
Q1. What is a Java Bean?
A1: It is a reusable software component that follows specific conventions.

Q2: What is a bound property?


A2: A property that notifies listeners when its value changes.

Q3: What is a constrained property?


A3: A property that allows listeners to veto changes.

Q4. What is PropertyChangeSupport?


A4: It is used to manage property change listeners.

Q5: What is VetoableChangeSupport?


A5: It is used to manage vetoable change listeners.

You might also like