0% found this document useful (0 votes)
17 views35 pages

Core Java April 23

Uploaded by

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

Core Java April 23

Uploaded by

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

Core java

April 23

Q1) Attempt any Eight:


1) Define variable in Java? What are the naming rules of variable?
ii) What is recursion?
iii) Define Inheritance?
iv) What is difference between Anay and Array List?
v) What is error? List types of error?
vi) List any two restrictions for applet.
vii) What is an event?
viii) What is Object and Class?
ix) Write the definition of abstract class?
x) What is Container?

Q2) Attempt any Four:


1) Write a note on package in Java.
ii) What is exception? Expalin its keyword with example.
iii) Explain java, util package.
iv) What is a method in Java? Explain method overloading with example.
v) How to handle events in applet? Explain with example.

Q3) Attempt any Four:


i) Write a Java program using AWT to display details of Customer (cust_id,
cust_name, cust_addr) from user and display it on the next frame.
ii) Write a Java program to reverse elements in array.
iii) Write a Java program using static method which maintain bank account
information about various customers.
iv) Define an abstract class Shape with abstract method area() and volume(). Write a
Java program to calculate area and volume of cone and cylinder.
v) Write a Java program to display smiley face using applet.

Q4) Attempt any Four:


1) What is Layout Manager? Explain any one in detail.
ii) How to create and access package in Java? Explain it with example.
iii) Write a Java program to Fibonacci series.
iv) Explain anonymous class in detail.
v) Write a Java program to display contents of file in reverse order.

Q5) Write a short note any Two.


1)Which are the predefined streams?
ii) Define multiple inheritance.
iii) Why Java is a platform neutral language?

Q1) Attempt any Eigh

i) Define variable in Java? What are the naming rules of variable?


Variables are the identifier of the memory location, which used to save data temporarily for
later use in the program. During execution of a program, values can Be stored in a variable,
and the stored value can be changed.
• While naming Java variables we have following naming rules.
1. Variable names are case-sensitive.
2. Variable name can be an unlimited-length sequence of Unicode letters and digits.
3. Variable name must begin with either a letter or the dollar sign "$", or the underscore
character "_"
4. No white space is permitted in variable names.
5. Variable name must not be a keyword or reserved word.
6. Do not begin with a digit.
7. A name can be of any realistic length.

ii) What is recursion?


The process in which a function calls itself directly or indirectly is called recursion and the
corresponding function is
called as recursive function. Using recursive algorithm, certain problems can be solved
quite easily. Examples of such
problems are Towers of Hanoi (TOH), Inorder/Preorder/Postorder Tree Traversals, DFS of
Graph. etc.

iii) Define Inheritance.


Inheritance is a fundamental concept in object-oriented programming (OOP) where a new
class (called a subclass or derived class) inherits properties and behaviors (methods) from
an existing class (called a superclass or base class). This allows for code reuse and the
extension of functionalities without modifying existing code.

iv) What is the difference between Array and ArrayList?


Array:
Fixed size: Once declared, the size of the array cannot be changed.
Can store primitive data types (like int, float) and objects.
Syntax: int[] array = new int[10];
ArrayList:
Dynamic size: It can grow or shrink as needed during runtime.
Can only store objects (wrapper classes for primitive types like Integer, Float).
Syntax: ArrayList<Integer> list = new ArrayList<>();

v) What is an error? List types of errors.


An error is an unexpected condition that occurs during the execution of a program, leading
to the abnormal
termination of the program.

Types of errors:

1. Syntax Errors: Occur when the code violates the rules of the programming language
(e.g., missing semicolons or brackets).
2. Runtime Errors: Occur during program execution (e.g., division by zero, array index out
of bounds).
3. Logical Errors: The program runs but gives incorrect results due to flawed logic in the
code.
vi) List any two restrictions for applets:
1. Cannot access local file system: Applets are restricted from reading or writing to the
user's local file system for security reasons.
2. Cannot make network connections: Applets cannot establish network connections to
any server other than the one they originated from (the server where the applet is hosted).

vii) What is an event?


An event is an action or occurrence detected by the program that can be handled by
event-handling code. Events
include actions like a user clicking a button, pressing a key, or moving the mouse.

viii) What is Object and Class?


Class: A blueprint or template for creating objects. It defines properties (attributes) and
methods (behaviors) common to all objects of that type.
Object: An instance of a class. It represents a specific entity with values for the attributes
defined in the class.

ix) Write the definition of an abstract class.


An abstract class is a class that cannot be instantiated on its own and is meant to be
subclassed. It may contain abstract methods (methods without implementation) that must
be implemented by its subclasses.
Example:
abstract class Shape {
abstract void draw();
}

x) What is a Container?
A container is a component in a graphical user interface (GUI) that can hold and manage
other components (like buttons, text fields). Examples of containers in Java are JFrame,
JPanel, Applet, etc.

Q2) Attempt any Four:

1) Write a note on package in Java.


• Java is an Object Oriented programming language. Any Java programmer will
quickly build large number of different classes for use in each application that they develop.
• Initially it may be tempting to store the classes in the same directory as the end
application, but as the complexity of applications grow so will the number of classes. The
answer is to organize the classes into packages.
• A Java package is a mechanism for organizing Java classes. Package are used in
Java, in-order to avoid name conflicts and to control access of class, interface and
enumeration etc.
• A package can be defined as, a group of similar types of classes, interface,
enumeration and sub-packages”
• A package does not contain the source code of any type of Java file. Each Java
source code file is a collection of one or more classes, or one or more interface with their
members.
Packages Concept
• A package is a collection of classes and interfaces.
• A package does not contain the source code of any type of java file. Each Java
source Code file is a collection of one or more classes, or one or more interface with their
members.
• After compilation, a separate class file is created for individual class or interface.
Either these are part of one Java file or stored in individual file.
• That class file (byte code) is placed in a particular related package using a package
Declaration.
 Creating user defined Packages
• Java package created by user to categorized classes, interface and enumeration.
• Declaration Syntax:
Package <package name>;
• The package declaration statement must be the first statement of the source file. The
package name is stored in the byte code (class file).
• The dot (.) notation is used to distinctively spot (identify) the package name in the
package hierarchy. One naming convention for a package is that, package name is written
in all lowercase. It will escape the confliction with classes and interfaces Name.

Accessing and Using Packages
There are three ways to access the package from outside the package i.e., import
package.”; import package.classname; fully qualified name.
1. Using packagename:
• If you use package then all the classes and interfaces of this package will be
Accessible but not subpackages.
• The import keyword ord is used to make the classes and interface of another
package Accessible to the current package

2. Using packagename.classname:
• If you import package.classname then only declared class of this package will be
accessible.
3. Using fully qualified name:
• If you use fully qualified name then only declared class of this package will be
accessible. Now there is no need to import. But you need to use fully qualified name every
time when you are accessing the class or interface.
• It is generally used when two packages have same class name e.g. java.util and
java.sql packages contain Date class.

Java Built-in Packages
• In Java group of related classes are put together in a package. E.g. File directory
has different folders.
• In Java you can either use built-in packages or user defined packages.
o Java.lang: It has classes for primitive types, strings, threads, exceptions and math
functions.
o Java.io: It has stream classes for Input/Output.
o Java.awt: Classes for implementing Graphical User Interface menus, windows,
buttons etc.
o Java.util: It has classes such as dates, Calendars, vectors, hash tables, etc.
o Java.net: Classes for networking.
o Java. Applet: Classes for creating and implementing applets.
 Import statement, Static import
 Import statement:
• Import statement brings certain classes or the entire packages, into visibility. Class
can be referred directly by using only its name once imported
• Import statements occurs immediately followed by package statement (if exists) …

ii) What is exception? Expalin its keyword with example.


• A Java exception is an object that describes an exceptional (that is, error) condition
that has occurred in a piece of code.
• When an exceptional condition arises, an object representing that exception is
created and thrown in the method that caused the error. That method may choose to
handle the exception itself or pass it on.
• Either way, at some point, the exception is caught and processed. Exceptions can be
generated by the Java run-time system, or they can be manually generated by your code
• Exceptions thrown by java relate to fundamental errors that violate the rules of the
Java language or the constraints of the Java execution environment..
• Java exception handling is handled by five different keywords, these are try, catch,
throw, throws and finally keywords.
1. Try: It is keyword which is utilized as a program statement. The statements which
you want to monitor for exceptions are written inside try block. If any exception Occurs then
it is thrown.
2. Catch: It is a keyword used to catch an exception object thrown by try block.
3. Throw: To throw exception manually, we use throw keyword.
4. Throws: In some cases, we need to use a method to throw an exception. So when
we want to throw an exception thrown out of a method is written here.
5. Finally: Whether an exception occurs or not, handled or not the finally block is
executed. In other words, if an exception is not handled by any of the catch block, it will be
handled by finally.

Keywords used in Java for Exception handling are as follows: Try, Catch, Finally.
Throw, Throws
1. Try:
• This block of code might rise an exception in special block having try keyword. For
example, we might suspect that there might be a “division by zero” operation in the code
that will throw an exception.
Syntax of the try block is as follows:
Try {
// Code that may throw an exception
}

2. Catch:
• It is used to catch an exception when its raised. It is always used with try and used
when try block raises an exception.

Syntax of the catch block is:


Catch (ExceptionType e) {
// Handle exception
}
Syntax of the try-catch block:
Try
{
//code causing exception.
}
Catch (exception (exception_type) e (object))
}
//exception handling code.
}
• The try block can have multiple lines of code that can raise multiple exceptions. Each
Of these exceptions is handled by an independent catch block.
• Java Try Catch Example: In the try block, we define a division operation. The divisor
is zero. The statement that divides the two numbers raises an Arithmetic exception. The
catch block defines a handler for Arithmetic exception.

3. Nested Try-Catch/Multiple Catch:


• A try block inside another try block is called a nested try block.
Syntax of a nested try block is given below:
Try
{
//try block 1;
Try
{
//try block 2;
}
Catch(Exception e)
{
//exception handler code
}
}
Catch(Exception e)
{
//exception handler code
}

4.Finally:
• It follows try block or try-catch block. Some code in our program that needs to be
executed irrespective of whether or not the exception is thrown. The finally block cannot
exist without a try block.

5.Throw:
• Java provides a keyword “throw” using which we can explicitly throw the exceptions
in the code or to throw custom exceptions. It can be used to throw the checked or
Unchecked exceptions
. Syntax of the throw keyword is:
Throw exception;
Or
Throw new exception_class(“error message”);
6. Throws:
• It is used to declare exceptions but does not throw an exception. It is used to indicate
That an exception might occur in the program or method..

• The declaration of exception using the “throws” keyword tells the programmer that
there may be an exception specified after the “throws keyword and the programmer should
provide corresponding handler code for this exception to maintain the normal flow of the
program.
• Declaring exception with throws keyword in the method signature and then handling
the method call using try-catch seems to be a viable solution.
Syntax of the throws keyword:
Another advantage of declaring exceptions using throws keyword is that we are forced to
handle the exceptions. If we do not provide a handler for a declared exception then the
program will raise an erroг.
Return_type_ method _name() throws exception_class_name
{
//method code
}

iii) Explain java, util package


The java.util package is one of the most commonly used packages in Java. It provides
utility classes that are fundamental for handling data structures, time, random number
generation, and more. This package contains various utility classes such as collections,
date/time utilities, and other helper classes that facilitate everyday programming tasks.
Key Components of the java.util Package

1. Collection Framework

The Java Collection Framework is a set of classes and interfaces that implement
commonly reusable data structures. It includes classes for handling groups of objects such
as lists, sets, queues, and maps.

Interfaces:
List: An ordered collection (e.g., ArrayList, LinkedList).
Set: A collection that contains no duplicate elements (e.g., HashSet, TreeSet).
Queue: A collection that represents a queue data structure (e.g., PriorityQueue).
Map: A collection that maps keys to values (e.g., HashMap, TreeMap).

Classes:
ArrayList: A dynamic array that can grow in size.
HashSet: An implementation of the Set interface that does not allow duplicates.
LinkedList: A doubly-linked list implementation of List and Deque.
HashMap: A key-value mapping implementation that allows null values and null keys.
TreeMap: A map implementation that orders its keys.

Example of using ArrayList:


import java.util.ArrayList;
public class Test {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
list.add("C++");

for (String language : list) {


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

2. Date and Time Classes

Before Java 8, java.util.Date and java.util.Calendar were the primary classes for working
with dates and times.
Date: Represents a specific instant in time, with millisecond precision.
Example:
import java.util.Date;
public class Test {
public static void main(String[] args) {
Date date = new Date();
System.out.println("Current Date and Time: " + date);
}
}

Calendar: A class that provides methods for manipulating dates and times based on
different calendar systems. Example:

import java.util.Calendar;
public class Test {
public static void main(String[] args) {
Calendar cal = Calendar.getInstance();
System.out.println("Year: " + cal.get(Calendar.YEAR));
System.out.println("Month: " + (cal.get(Calendar.MONTH) + 1)); // Month starts from 0
System.out.println("Day: " + cal.get(Calendar.DAY_OF_MONTH));
}
}

Note: In Java 8 and later, the java.time package is recommended for date and time
manipulation as it provides a more comprehensive and user-friendly API.

3. Random Number Generation


The Random class is used to generate random numbers, booleans, and random values for
other primitive data types.
Example:
import java.util.Random;
public class Test {
public static void main(String[] args) {
Random random = new Random();
int randomInt = random.nextInt(100); // Random number between 0 and 99
System.out.println("Random number: " + randomInt);
}
}

4. Scanner Class

The Scanner class is a useful class for reading input, particularly from the console. It can
read input of various types like strings, integers, and doubles.

Example:

import java.util.Scanner;
public class Test {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name);
}

5. Legacy Classes (Vector, Stack, Hashtable)


Before the introduction of the Java Collections Framework, Java provided classes such as
Vector, Stack, and Hashtable for managing data collections.

Vector: A resizable array that is synchronized.


Stack: A subclass of Vector representing a LIFO (Last In First Out) stack of objects.
Hashtable: A legacy class similar to HashMap, but synchronized.

Example of using Stack:

import java.util.Stack;
public class Test {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(10);
stack.push(20);
stack.push(30);

System.out.println("Stack: " + stack);


System.out.println("Popped element: " + stack.pop());
System.out.println("Stack after pop: " + stack);
}
}

6. Utility Classes
Arrays: Contains static methods for manipulating arrays, like sorting and searching.
Example: Arrays.sort(array)
Collections: Contains static methods for manipulating collections, such as sorting lists or
finding minimum/maximum values..

Example:
import java.util.ArrayList;
import java.util.Collections;
public class Test {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
list.add(40);
list.add(20);
list.add(10);
list.add(30);

Collections.sort(list);
System.out.println("Sorted list: " + list);
}
}

Properties: Represents a persistent set of properties that can be loaded from or saved to a
file. Example:

import java.util.Properties;
public class Test {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("username", "admin");

properties.setProperty("password", "1234");
System.out.println("Username: " + properties.getProperty("username"));
System.out.println("Password: " + properties.getProperty("password"));
}
}

Summary
The java.util package is a collection of utility classes that simplify programming tasks such
as managing collections, working with dates and times, generating random numbers, and
handling input/output. These utilities enhance the functionality of Java and provide efficient
ways to manage complex data structures and operations.

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


Methods in Java:
A Java method is a collection of statements that are grouped together to perform a certain
task.
Method describes behaviour of an object. A method is a collection of statements that.
Are group together to perform an operation. The only required elements of a method
declaration are the method’s return type,
Name, a pair of parentheses (), and a body between braces {}

More generally, method declarations have following components, in order:


1. Modifiers: Such as public, private, default, protected.
2. The return type: The data type of the value returned by the method, or void if the
method does not return a value.
3. The method name: The rules for field names apply to method names as well, but the
convention is a little different.
4. The parameter list in parenthesis: A comma-delimited list of input parameters,
preceded by their data types, enclosed by parentheses (). If there are no parameters, you
must use empty parentheses.
5. The method body, enclosed between braces: The method’s code, including the
declaration of local variables, goes here.
Syntax:
Return_type_methodName(parameter_list)
{
//body of method
}
• Example:Program for the method.
Public class Main
{
Public String getName(String st)
{
System.out.println(“Kamil Ajmal Khan”);
}
public static void main(String[] args)
{
Main Obj-new Main();
Obj.getName();
}
}
Output:
Kamil Ajmal Khan

 Methods Overloading
• In Java, we can define number of methods in a class with the same name. Defining
two or more methods with the same name in a class is called Method Overloading.

• The overloaded constructors are called here as method overloading because we are
allowed to create methods with same name, but different parameters can be passed with
different definitions. This is referred as Polymorphism.
• When we call a method with its object, Java first checks for the method name and
then for the number of parameters and its types. Then it decides which method should be
executed.
Program for method overloading.

Class overload
{
Int m, n;
Overload(). //default constructor
}
m=5;
n=28;
}
Overload(int p, int q). //parameterized constructor
{
m=p;
n=q;
}
Overload(double x, double y)
{
m=x;
n=y;
}
Void display()
{
System.out.println(m);
System.out.println(n);
}
}
Class mainover
{
Public static void main(String args[])
{
Overload ob1=new overload();
Overload ob2=new overload(10,5);
Overload ob3=new overload (25.6, 88.5);
Ob1.display();
Ob2.display();
Ob3.display();
}
}
Output:
5 -for ob1
28- for ob1
5-for obj2
10-for obj2
25-for obj3
80-for obj3
• Here, for object ob1, the default constructor is called. For object ob2 the
parameterized constructor “overload (int p, int q)” is called, whereas for object ob3, the
parameterized constructor “overload (double x, double y)” is called. But because of the
data type of m and n are int, the value of x and y i.e. 25.6 and 80.5 get truncated to integer
part.

v) How to handle events in applet? Explain with example.


In Java applets, event handling is the mechanism that manages user interactions such as
mouse clicks, keyboard inputs, etc. Java uses a delegation event model to handle events,
where an event source (like a button) generates an event, and listeners respond to that
event.

Here's how events are handled in applets:


1. Event Source: The object that generates an event. For example, a button that generates
an event when clicked.
2. Event Listener: The object that listens to events from the event source and handles the
event.
3. Event Object: The event object that encapsulates the event, e.g., ActionEvent,
MouseEvent, etc.

Example: Handling Button Click Event in an Applet


import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
// Applet class implementing ActionListener interface
public class EventHandlingApplet extends Applet implements ActionListener {
Button button; // Declare a button
// Initialize the applet and the button
public void init() {
button = new Button("Click Me"); // Create a new button with label "Click Me"
add(button); // Add button to the applet
button.addActionListener(this); // Register the button with ActionListener
}

// This method is called when the button is clicked


public void actionPerformed(ActionEvent e) {
showStatus("Button Clicked!"); // Show a message in the applet's status bar
}
}

Explanation:
1. Extending Applet: The class EventHandlingApplet extends the Applet class, which
means it's an applet that can run in a browser or an applet viewer.
2. ActionListener Interface: The applet implements the ActionListener interface, which
requires defining the actionPerformed method to handle button click events.
3. Button Creation: Inside the init() method, a Button object is created and added to the
applet. The addActionListener() method is used to register the button for listening to click
events. The current applet (this) is passed as the listener.
4. Event Handling: When the button is clicked, the actionPerformed() method is called.
Here, we use showStatus() to display a message ("Button Clicked!") in the status bar of the
applet.

Running the Applet:

To run this applet, use an HTML file or an applet viewer. Here’s a basic HTML file to load
the applet:

<html>
<body>
<applet code="EventHandlingApplet.class" width="300" height="300">
</applet>
</body>
</html>

Event Handling Overview:

ActionListener is the listener interface for handling action events like button clicks.
MouseListener, KeyListener, etc., can be used for handling mouse and keyboard events.
Use addActionListener(), addMouseListener(), etc., to register an event listener for specific
events.
This mechanism of event handling is used to interact with various components like buttons,
text fields, and other UI elements within an applet or any GUI-based application in Java.

Q3) Attempt any Four:

i) Write a Java program using AWT to display details of Customer (cust_id,


cust_name, cust_addr) from user and display it on the next frame.

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

// First Frame to input customer details


class CustomerDetails extends Frame implements ActionListener {
Label labelId, labelName, labelAddr;
TextField textId, textName, textAddr;
Button submitButton;

// Constructor for input frame


CustomerDetails() {
// Set layout and size for the frame
setLayout(new FlowLayout());
setSize(400, 300);
setTitle("Customer Details");

// Initialize Labels
labelId = new Label("Customer ID:");
labelName = new Label("Customer Name:");
labelAddr = new Label("Customer Address:");

// Initialize Text Fields


textId = new TextField(20);
textName = new TextField(20);
textAddr = new TextField(20);

// Initialize Button
submitButton = new Button("Submit");

// Add components to the Frame


add(labelId);
add(textId);
add(labelName);
add(textName);
add(labelAddr);
add(textAddr);
add(submitButton);

// Register Button with ActionListener


submitButton.addActionListener(this);

// Close the Frame on window close


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {

System.exit(0);
}
});

setVisible(true); // Make the frame visible


}

// Action performed when Submit button is clicked


public void actionPerformed(ActionEvent ae) {
// Get user input data from TextFields
String custId = textId.getText();
String custName = textName.getText();
String custAddr = textAddr.getText();

// Create a new frame to display the customer details


new CustomerDisplay(custId, custName, custAddr);

// Close the current input frame


this.dispose();
}
public static void main(String[] args) {
new CustomerDetails();
}
}

// Second Frame to display customer details


class CustomerDisplay extends Frame {
// Constructor for the display frame
CustomerDisplay(String custId, String custName, String custAddr) {
// Set layout and size for the frame
setLayout(new FlowLayout());
setSize(400, 200);
setTitle("Customer Information");

// Display Customer Information


add(new Label("Customer ID: " + custId));
add(new Label("Customer Name: " + custName));
add(new Label("Customer Address: " + custAddr));

// Close the Frame on window close


addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
});

setVisible(true); // Make the frame visible


}
}

Output:

Step 1: Input Frame

A window appears where the user inputs the customer details like:
Customer ID: 101

Customer Name: John Doe

Customer Address: 123 Main St

Step 2: Output Frame

Once the user clicks the "Submit" button, a new window opens showing the entered details:

Customer ID: 101

Customer Name: John Doe


Customer Address: 123 Main St

ii) Write a Java program to reverse elements in array.


public class ReverseArray {
public static void main(String[] args) {
//Initialize array
int [] arr = new int [] {1, 2, 3, 4, 5};
System.out.println("Original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println();
System.out.println("Array in reverse order: ");
//Loop through the array in reverse order
for (int i = arr.length-1; i >= 0; i--) {
System.out.print(arr[i] + " ");
}
}
}

Output:

Original array:
12345
Array in reverse order:
54321

iii) Write a Java program using static method which maintain bank account
information about various customers.
Here's a Java program using a static method to manage bank account information for
various customers. The program will have a class BankAccount that stores details such as
the account number, customer name, and balance. A static method will display account
information for all customers.

Java Program Using Static Method for Bank Account Information:

import java.util.Scanner;

class BankAccount {
// Variables to store account information
private int accountNumber;
private String customerName;

private double balance;

// Static variable to count the total number of accounts


private static int accountCount = 0;
// Array to store multiple customer accounts
private static BankAccount[] accounts = new BankAccount[100]; // Assume a maximum
of 100 customers

// Constructor to initialize account details


public BankAccount(int accountNumber, String customerName, double balance) {
this.accountNumber = accountNumber;
this.customerName = customerName;
this.balance = balance;
accounts[accountCount] = this; // Add current account to the array
accountCount++; // Increment account count
}

// Static method to display details of all customers


public static void displayAllAccounts() {
System.out.println("Displaying all customer accounts:");
for (int i = 0; i < accountCount; i++) {
System.out.println("Account Number: " + accounts[i].accountNumber);
System.out.println("Customer Name: " + accounts[i].customerName);
System.out.println("Balance: $" + accounts[i].balance);
System.out.println("------------------------");
}
}
}

public class BankManagement {


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

// Example: Create 3 bank accounts


System.out.println("Enter details for 3 bank accounts.");

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


System.out.println("\nEnter details for customer " + (i + 1) + ":");

// Input: account number


System.out.print("Enter Account Number: ");
int accNo = sc.nextInt();

// Input: customer name


System.out.print("Enter Customer Name: ");
sc.nextLine(); // Consume the newline left-over
String name = sc.nextLine();

// Input: initial balance


System.out.print("Enter Initial Balance: ");
double balance = sc.nextDouble();

// Create a new BankAccount object


new BankAccount(accNo, name, balance);
}

// Call the static method to display all accounts


BankAccount.displayAllAccounts();
}
}

Explanation:

1. BankAccount Class:

This class contains three fields for each account: accountNumber, customerName, and
balance.
It has a static array accounts[] to store the list of all customer accounts.
The accountCount static variable keeps track of the total number of accounts created.

2. Constructor:
The constructor initializes the fields for each customer when a BankAccount object is
created. It also adds the new account to the accounts[] array.

3. Static Method (displayAllAccounts()):

This static method loops through the accounts[] array and prints the account details for all
customers.
The method can be called without needing an object, and it uses the static accountCount
variable to limit the loop.

4. BankManagement Class:
In the main method, the program takes input for creating 3 bank accounts using a loop.
After creating the accounts, the static method displayAllAccounts() is called to display all
the account details.

Sample Output:

Enter details for 3 bank accounts.

Enter details for customer 1:


Enter Account Number: 101
Enter Customer Name: John Doe
Enter Initial Balance: 5000

Enter details for customer 2:


Enter Account Number: 102
Enter Customer Name: Alice Smith
Enter Initial Balance: 3000

Enter details for customer 3:


Enter Account Number: 103
Enter Customer Name: Bob Johnson
Enter Initial Balance: 4500
Displaying all customer accounts:
Account Number: 101
Customer Name: John Doe
Balance: $5000.0
------------------------
Account Number: 102
Customer Name: Alice Smith
Balance: $3000.0
------------------------
Account Number: 103
Customer Name: Bob Johnson

Balance: $4500.0
------------------------

Key Points:
The static method displayAllAccounts() is used to display the details of all the bank
accounts created. Since it is static, it can be called without creating an instance of the
BankAccount class.

The account information is stored in an array, and the program can handle multiple
customers.

iv) Define an abstract class Shape with abstract method area() and volume(). Write a
Java program to calculate area and volume of cone and cylinder.
import java.util.Scanner;

// Abstract class Shape


abstract class Shape {
// Abstract methods to calculate area and volume
abstract double area();
abstract double volume();
}

// Cone class extending Shape


class Cone extends Shape {
double radius, height;

// Constructor to initialize radius and height


Cone(double radius, double height) {
this.radius = radius;
this.height = height;
}

// Method to calculate the surface area of the cone


@Override
double area() {
double slantHeight = Math.sqrt((radius * radius) + (height * height));
return Math.PI * radius * (radius + slantHeight);
}

// Method to calculate the volume of the cone


@Override
double volume() {
return (Math.PI * radius * radius * height) / 3;
}
}

// Cylinder class extending Shape


class Cylinder extends Shape {
double radius, height;

// Constructor to initialize radius and height


Cylinder(double radius, double height) {
this.radius = radius;
this.height = height;
}

// Method to calculate the surface area of the cylinder

@Override
double area() {
return 2 * Math.PI * radius * (radius + height);
}

// Method to calculate the volume of the cylinder


@Override
double volume() {
return Math.PI * radius * radius * height;
}
}

// Main class
public class ShapeTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);

// Input details for the cone


System.out.print("Enter radius of the cone: ");
double coneRadius = sc.nextDouble();
System.out.print("Enter height of the cone: ");
double coneHeight = sc.nextDouble();

// Create Cone object and calculate area and volume


Cone cone = new Cone(coneRadius, coneHeight);
System.out.println("Cone Surface Area: " + cone.area());
System.out.println("Cone Volume: " + cone.volume());
System.out.println();

// Input details for the cylinder


System.out.print("Enter radius of the cylinder: ");
double cylinderRadius = sc.nextDouble();
System.out.print("Enter height of the cylinder: ");
double cylinderHeight = sc.nextDouble();

// Create Cylinder object and calculate area and volume


Cylinder cylinder = new Cylinder(cylinderRadius, cylinderHeight);
System.out.println("Cylinder Surface Area: " + cylinder.area());
System.out.println("Cylinder Volume: " + cylinder.volume());
}
}

Sample Output:

Enter radius of the cone: 3


Enter height of the cone: 5
Cone Surface Area: 83.22976079115259
Cone Volume: 47.12388980384689

Enter radius of the cylinder: 3


Enter height of the cylinder: 5
Cylinder Surface Area: 150.79644737231007
Cylinder Volume: 141.3716694115407

v) Write a Java program to display smiley face using applet.


import java.applet.Applet;
import java.awt.*;

// Applet class to draw a smiley face


public class SmileyFaceApplet extends Applet {

// Method to draw on the applet


public void paint(Graphics g) {
// Set the color for the face
g.setColor(Color.YELLOW);
// Draw the circle for the face (x, y, width, height)
g.fillOval(50, 50, 200, 200);

// Set the color for the eyes


g.setColor(Color.BLACK);
// Draw the left eye
g.fillOval(90, 100, 30, 30);
// Draw the right eye
g.fillOval(180, 100, 30, 30);
// Draw the mouth
g.drawArc(100, 160, 100, 50, 0, -180); // Smiling arc

// Optionally, draw an outline for the face


g.setColor(Color.BLACK);
g.drawOval(50, 50, 200, 200); // Face outline
}
}

/*
<applet code="SmileyFaceApplet" width="300" height="300"></applet>
*/
[12:46 pm, 02/10/2024] sauravsapkal04: Sample Output:

The output will display a yellow circle representing the smiley face, with two black eyes and
a smiling mouth in the center of the applet window.

Q4) Attempt any Four:

i)What is Layout Manager? Explain any one in detail.


LAYOUT MANAGERS
• Layout means the arrangement of components within the container. In other way we
can say that placing the components at a particular position within the container.
• The task of layouting the controls are done automatically by the Layout Manager.
Layout manager is an object which determines the way that components are arranged in a
frame window. All of the components that we have shown so far have been Positioned by
the default layout manager.
• A layout manager automatically arranges our controls within a window by using
some type of algorithm. A layout manager is an instance of any class that implements. The
LayoutManager interface.
• The layout manager is set by the setLayout() method. If no call to set Layout() is
made, then the default layout manager is used.
• Whenever, a container is resized (or sized for the first time), the layout manager is
used to position each of the components within it.
• The setLayout() method has the following general form:

• Syntax: void setLayout(LayoutManager layoutObj)


• Here, layoutObj is a reference to the desired layout manager. If we wish to disable
the layout manager and position components manually, pass null for layoutObj.
• If we do this, we will need to determine the shape and position of each component
manually, using the setBounds() method defined by Component. Normally, we will want to
use a layout manager.
• The layout manager automatically positions all the components within the container
Default values are provided otherwise.
• Java has several predefined Layout Manager Classes. Layout manager classes are
founded in the java.awt package same as the classes used for displaying graphical
components.
• The java.awt package provides five layout manager classes as given below:

1. FlowLayout Manager:
• The FlowLayout is one the most popular and simplest layout manager. FlowLayout.
Manager places components in a container from left to right in the order in which they were
added to the container.
• When one row is filled, layout advances to the next row. It is analogous to lines of
text in a paragraph. Components managed by a FlowLayout are always set to their
Preferred size (both width and height) regardless of the size of the parent container.
• Whenever, the container is resized then the components in the container are also
adjusted from the top-left corner. The FlowLayout is the default layout manager for a Panel
and JPanel.
Following are Constructors for FlowLayout:
1. FlowLayout(): This constructor centers all components and leaves five pixel
between each component Spaces
2. FlowLayout(int align): This constructor allows to specify how each line of
components is aligned i.e.. Flowlayout.LEFT, FlowLayout.CENTER,FlowLayout.RIGHT.
3. FlowLayout(int align, int hspace, int vspace): This constructor allow to specify the
alignment as well as the horizontal and vertical space between components.

ii) How to create and access package in Java? Explain it with example.
In Java, a package is a namespace that organizes a set of related classes and interfaces.
Packages are used to avoid name conflicts, manage access control, and make it easier to
locate and use the classes, interfaces, and sub-packages.

Steps to Create and Access a Package in Java:

1. Create a Package:

A package is created using the package keyword.

The package name should be the first statement in a Java source file.

2. Access a Package:

You can use the import keyword to access classes or interfaces from other packages.

If you want to access a class from a package without importing, you can use the fully
qualified name (i.e., including the package name).

Example:

We'll create a package called mypackage and include a class in it, then access that class
from another program.

Step 1: Create the Package

1. Create a directory mypackage (folder).


2. Inside the directory, create a Java file MyClass.java as shown below.

// Save this file as MyClass.java in the mypackage directory


package mypackage; // Defining the package

public class MyClass {


// Constructor
public MyClass() {
System.out.println("Hello from MyClass in mypackage");
}

// Method to display a message


public void displayMessage() {
System.out.println("This is a message from MyClass.");
}
}

Step 2: Compile the Package

Compile MyClass.java using the -d flag to specify where to put the compiled package.

javac -d . MyClass.java

The -d . option ensures that the compiled mypackage directory will be created in the
current directory (.) and the .class file will be placed inside it.

Step 3: Create Another Java Program to Access the Package

Create another Java file in the main directory to use the package and its class.

// Save this file as TestPackage.java


import mypackage.MyClass; // Importing the class from the mypackage package

public class TestPackage {


public static void main(String[] args) {
// Create an instance of MyClass from mypackage
MyClass obj = new MyClass();
obj.displayMessage(); // Call method from MyClass
}
}

Step 4: Compile and Run the Test Program

1. Compile the program:


javac TestPackage.java

2. Run the program:

java TestPackage

Output:

Hello from MyClass in mypackage


This is a message from MyClass.

Explanation:

1. Creating the Package:

In MyClass.java, the statement package mypackage; creates a package named


mypackage.

This class contains a constructor and a method displayMessage().

2. Accessing the Package:

In TestPackage.java, we use the import statement to import mypackage.MyClass so that


we can access the class from the mypackage package.

An object of MyClass is created, and its methods are invoked in the main() method.

Notes:

The -d option while compiling ensures that the package structure is maintained.

The fully qualified class name mypackage.MyClass includes the package name, and it
avoids name conflicts if other classes have the same name but are in different packages.

If the import statement is not used, you would have to refer to the class by its fully qualified
name like this:

mypackage.MyClass obj = new mypackage.MyClass();


Benefits of Using Packages:

Modularity: Packages allow you to organize your classes and interfaces into easily
manageable modules.

Name Conflicts: Using different packages for different classes with the same name avoids
name conflicts.

Access Control: Packages can control access to classes and methods by using different
access levels (public, protected, default, private).

Package Naming Convention:

The package name should be in lowercase.

It is common practice to use a reverse domain name to create unique package names. For
example:

com.example.mypackage if you have a domain example.com.

iii) Write a Java program to Fibonacci series.


import java.util.Scanner;

public class FibonacciSeries {


public static void main(String[] args) {
// Create a Scanner object for user input
Scanner sc = new Scanner(System.in);

// Get the number of terms in the Fibonacci series from the user
System.out.print("Enter the number of terms in the Fibonacci series: ");
int n = sc.nextInt();

// First two Fibonacci numbers


int first = 0, second = 1;

// Print the Fibonacci series


System.out.println("Fibonacci Series up to " + n + " terms:");
for (int i = 1; i <= n; i++) {
System.out.print(first + " ");

// Calculate the next term


int next = first + second;
first = second;
second = next;
}
}
}

Output:
Enter the number of terms in the Fibonacci series: 10
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34

iv) Explain anonymous class in detail.


An anonymous class in Java is a special type of inner class without a name. It is defined
and instantiated in a single expression and is used primarily to instantiate a subclass or an
interface at the time of its creation. Anonymous classes are particularly useful for creating
instances of classes that may not be reused elsewhere, typically for short-lived tasks such
as event handling, callbacks, and simple implementations of interfaces.

Key Characteristics of Anonymous Classes:

1. No Name: As the name suggests, anonymous classes do not have a name. They are
declared and instantiated at the same time.
2. Syntax: The syntax for creating an anonymous class involves the use of the new
keyword followed by the class name or interface name, and then the class body is provided
within curly braces.
3. Access: Anonymous classes can access the variables and methods of their enclosing
class. They can also access local variables that are effectively final.
4. Single Use: They are often used for one-time use situations, such as when you need to
provide a specific implementation of an interface or abstract class.

When to Use Anonymous Classes:

Event Handling: When creating a listener for a button or other UI elements.


Threading: When creating a thread with a specific behavior.
Short Implementations: When a class implementation is too short to warrant a full class
definition.

Example of an Anonymous Class:

Here’s an example to illustrate the concept of an anonymous class in Java. This example
will use an anonymous class to handle a button click event in a Swing application.

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AnonymousClassExample {


public static void main(String[] args) {
// Create a JFrame
JFrame frame = new JFrame("Anonymous Class Example");
JButton button = new JButton("Click Me");

// Add an ActionListener using an anonymous class


button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// Action to perform on button click
System.out.println("Button was clicked!");
}
});

// Set up the frame


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

Explanation of the Example:

1. Creating a JFrame: A simple JFrame is created with a button labeled "Click Me".
2. Anonymous Class for ActionListener:
Instead of creating a separate class that implements ActionListener, we create an instance
of ActionListener using an anonymous class directly in the addActionListener() method.
The actionPerformed() method is overridden to provide the functionality when the button is
clicked.
2. Action Execution: When the button is clicked, the message "Button was clicked!" is
printed to the console.

Benefits of Using Anonymous Classes:

Conciseness: Reduces the amount of boilerplate code since you don’t need to create a
separate named class for simple implementations.
Readability: Keeps the code related to the action close together, which can improve
readability, especially in small applications or event-driven programming.

Encapsulation: Since the anonymous class can access the variables and methods of its
enclosing class, it helps encapsulate the functionality without exposing it to the outside.

Limitations of Anonymous Classes:

Single Use: Anonymous classes are not reusable; they are defined for one-time use only.
If you need multiple instances, you will have to define a named class.

Limited to One Class/Interface: An anonymous class can extend one class or implement
one interface at a time. If you need multiple inheritances, you need to use regular classes.
Debugging Difficulties: Since anonymous classes do not have a name, it can be more
challenging to debug them, especially if they contain complex logic.

Conclusion:
Anonymous classes are a powerful feature in Java that allows for quick implementation of
classes and interfaces without the overhead of separate named classes. They are
particularly useful in event handling, callbacks, and scenarios where a short-lived
implementation is sufficient. However, their single-use nature and limitations should be
considered when deciding whether to use them.

v) Write a Java program to display contents of file in reverse order.


import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;

public class ReverseFileContents {


public static void main(String[] args) {
// Specify the file name
String fileName = "example.txt"; // Change this to your file path

// Create a list to store the lines


ArrayList<String> lines = new ArrayList<>();

// Read the file and store each line in the ArrayList


try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}
} catch (IOException e) {
System.err.println("Error reading the file: " + e.getMessage());
return;
}

// Reverse the list of lines


Collections.reverse(lines);

// Display the lines in reverse order


System.out.println("Contents of the file in reverse order:");
for (String line : lines) {
System.out.println(line);
}
}
}

Sample Output:
If the contents of example.txt are as follows:

Hello, World!
This is a sample file.
Java programming is fun.

The output of the program will be:

Contents of the file in reverse order:


Java programming is fun.
This is a sample file.
Hello, World!

Q5) Write a short note any Two:

i)Which are the predefined streams?


In Java, predefined streams are used for input and output operations. These streams are
provided by the Java platform and are an integral part of the Java I/O (Input/Output)
system. The most commonly used predefined streams in Java are:

1. System.in

Type: Input Stream

Description: System.in is a standard input stream that is used to read input from the user
through the console (usually keyboard input). It is an instance of InputStream.

Usage: It is commonly used in conjunction with Scanner or BufferedReader to read data.

Example:

import java.util.Scanner;

public class InputExample {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
}
}

2. System.out

Type: Output Stream


Description: System.out is a standard output stream that is used to display output to the
console. It is an instance of PrintStream and provides various methods for printing different
types of data (like print(), println(), and printf).

Usage: It is the most commonly used stream for displaying output.

Example:

public class OutputExample {


public static void main(String[] args) {
System.out.println("Welcome to Java!");
}
}

3. System.err

Type: Output Stream

Description: System.err is a standard error output stream used to output error messages.
It is also an instance of PrintStream. It is primarily used for logging error messages or
warnings and usually displays output in red in the console, making it easy to distinguish
from normal output.

Usage: It is useful for error handling or debugging purposes.

Example:

public class ErrorExample {


public static void main(String[] args) {
System.err.println("This is an error message.");
}
}

Summary

System.in: Used for input from the keyboard.

System.out: Used for standard output to the console.

System.err: Used for error messages and warnings.

These predefined streams simplify the process of performing input and output operations in
Java, making it easier for developers to interact with users and handle errors effectively.

ii) Define multiple inheritance.


Multiple inheritance is a feature in object-oriented programming (OOP) where a class can
inherit attributes and methods from more than one parent class. This allows a subclass to
inherit and combine functionalities from multiple base classes, leading to a richer and more
versatile class structure.

Key Characteristics of Multiple Inheritance:

1. Multiple Parent Classes: In multiple inheritance, a single derived class can have more
than one base class. This means that the derived class can inherit members (fields and
methods) from all of its parent classes.

2. Enhanced Functionality: It allows a class to possess the characteristics of multiple


classes, which can facilitate code reuse and implementation of complex behaviors.

3. Potential for Ambiguity: Multiple inheritance can lead to ambiguity, particularly when
two or more parent classes have methods or attributes with the same name. This situation
is often referred to as the "Diamond Problem."

Example of Multiple Inheritance in Java (via Interfaces):

Java does not support multiple inheritance with classes to avoid ambiguity. However, it
allows multiple inheritance through interfaces. Here's how it works:

// Interface 1
interface CanFly {
void fly();
}

// Interface 2
interface CanSwim {
void swim();
}

// Class implementing both interfaces


class Duck implements CanFly, CanSwim {
@Override
public void fly() {
System.out.println("Duck can fly.");
}

@Override
public void swim() {
System.out.println("Duck can swim.");
}
}

public class MultipleInheritanceExample {


public static void main(String[] args) {
Duck duck = new Duck();
duck.fly();
duck.swim();
}
}

Summary
Multiple Inheritance: A class inherits from multiple base classes, combining their
functionalities.
Ambiguity: Can lead to conflicts when base classes have methods or properties with the
same name.
Java's Approach: Java avoids multiple inheritance of classes but allows it through
interfaces, enabling a form of multiple inheritance without ambiguity.

Conclusion
Multiple inheritance can enhance the capabilities of classes by allowing them to inherit
features from multiple sources. However, it also introduces complexities that developers
need to manage, particularly in languages that support it
directly. In contrast, Java's use of interfaces provides a way to achieve similar benefits
without the potential pitfalls associated with direct multiple inheritance.

iii) Why Java is a platform neutral language?


Java is considered a platform-neutral language primarily due to its ability to run on any
platform that has a Java Virtual Machine (JVM). This characteristic arises from several key
features of the Java language and its architecture:

1. Write Once, Run Anywhere (WORA)


Bytecode Compilation: When a Java program is compiled, it is transformed into an
intermediate form known as bytecode. This bytecode is not specific to any hardware or
operating system.
JVM Independence: The bytecode can be executed on any system that has a compatible
JVM, allowing Java programs to run on different platforms without needing to be
recompiled.

2. Java Virtual Machine (JVM)


Abstraction Layer: The JVM acts as an abstraction layer between the Java program and
the underlying hardware and operating system. When a Java program is run, the JVM
translates the bytecode into machine code that is specific to the host system.
Platform-Specific Implementations: Different platforms (Windows, Linux, macOS, etc.) have
their own implementations of the JVM, ensuring that Java programs behave consistently
across different environments.

3. Standard Library and APIs


Unified API: Java provides a comprehensive set of standard libraries and APIs that are
consistent across all platforms. This means that Java developers can rely on the same
functionalities and behaviors, regardless of the operating system they are using.
Cross-Platform Libraries: Many Java libraries are designed to be platform-independent,
further enhancing the portability of Java applications.

4. Garbage Collection and Memory Management


Automatic Memory Management: Java's built-in garbage collection ensures that memory
management is handled consistently across different platforms. This reduces platform-
specific memory management issues, contributing to portability.
Example of Java Platform Neutrality
Consider a simple Java program:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}

1. Compilation: When you compile this program using javac HelloWorld.java, it produces a
HelloWorld.class file containing bytecode.
3. Execution: You can run this bytecode on any platform with a JVM by executing java
HelloWorld, and it will print "Hello, World!" regardless of the operating system.

Conclusion
Java's platform neutrality stems from its architecture, which separates the source code
from the underlying platform through the use of bytecode and the JVM. This design
enables developers to create applications that can run on any operating system without
modification, fulfilling the "Write Once, Run Anywhere" promise. This portability is one of
Java's significant advantages, making it a popular choice for enterprise applications, web
development, and cross-platform software development

You might also like