Core Java April 23
Core Java April 23
April 23
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).
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.
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) …
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.
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
}
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.
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.
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);
}
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);
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.
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.
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.
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>
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.
import java.awt.*;
import java.awt.event.*;
// Initialize Labels
labelId = new Label("Customer ID:");
labelName = new Label("Customer Name:");
labelAddr = new Label("Customer Address:");
// Initialize Button
submitButton = new Button("Submit");
System.exit(0);
}
});
Output:
A window appears where the user inputs the customer details like:
Customer ID: 101
Once the user clicks the "Submit" button, a new window opens showing the entered details:
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.
import java.util.Scanner;
class BankAccount {
// Variables to store account information
private int accountNumber;
private String customerName;
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.
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:
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;
@Override
double area() {
return 2 * Math.PI * radius * (radius + height);
}
// Main class
public class ShapeTest {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Sample Output:
/*
<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.
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.
1. Create a Package:
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.
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.
Create another Java file in the main directory to use the package and its class.
java TestPackage
Output:
Explanation:
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:
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).
It is common practice to use a reverse domain name to create unique package names. For
example:
// 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();
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
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.
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;
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.
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.
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.
Sample Output:
If the contents of example.txt are as follows:
Hello, World!
This is a sample file.
Java programming is fun.
1. System.in
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.
Example:
import java.util.Scanner;
2. System.out
Example:
3. System.err
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.
Example:
Summary
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.
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.
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."
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();
}
@Override
public void swim() {
System.out.println("Duck can 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.
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