0% found this document useful (0 votes)
29 views27 pages

Java Packages

java basic knowldge

Uploaded by

bsravani1992
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)
29 views27 pages

Java Packages

java basic knowldge

Uploaded by

bsravani1992
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

 Java Packages

Packages are an essential feature in Java for organizing large-scale applications.


Understanding how to create, import, and manage packages is crucial for efficient Java
programming.

Back to Index Packages Access Demo Basic Examples JARs

Packages in Java are used to group related classes, interfaces, and sub-packages into a
namespace. They provide a way to organize files in larger projects, avoid name conflicts, and
manage access control. Packages also help in making code modular and manageable,
especially when dealing with large-scale applications.

Java Package Diagram

Access Modifiers in Java

Private No Modifier (Default) Protected Public

Same Class Yes Yes Yes Yes

Same Package No Yes Yes Yes

Different Package Subclass No No Yes Yes

Different Package Non-Subclass No No No Yes

Questions and Answers


1. What is a Package in Java?

A package is a namespace that organizes a set of related classes and interfaces. Packages are
used to prevent name clashes and to control the access of classes, interfaces, and methods.

package [Link];

In the above example, [Link] is a package that could contain utility classes related
to an application. Classes inside the package can be imported and used by other classes.

2. Why Use Packages?

Organizing Code: Packages help group similar functionality into modules.

Avoiding Naming Conflicts: Packages provide namespaces, so two classes with the same
name can exist in different packages.
Access Control: Java packages provide access control mechanisms. Classes, methods, and
fields can have package-level visibility.

Reusability: Code can be organized into packages that can be reused across projects.

3. Types of Packages in Java

Built-in Packages: These are provided by the Java API (e.g., [Link], [Link], [Link]).

User-defined Packages: These are created by users to organize their classes and interfaces.

4. How to Create a Package?

To create a package in Java, you use the package keyword. The package statement must be
the first line in the source file (excluding comments).

// File: com/example/[Link]

package [Link];

public class HelloWorld {

public void greet() {

[Link]("Hello from the [Link] package!");

5. Accessing Classes from Packages

To access a class from a package, the fully qualified name of the class should be used, or the
class should be imported.

Accessing With Import:

import [Link];

public class Main {

public static void main(String[] args) {


HelloWorld hello = new HelloWorld();

[Link]();

6. Importing Packages

Java provides the import statement to import classes or entire packages.

Importing a Single Class: import [Link];

Importing All Classes: import [Link].*;

7. Sub-packages in Java

Java supports sub-packages, which are packages within other packages. They are treated like
regular packages, but the hierarchy is created by adding dots in the package name.

package [Link];

8. Package Naming Conventions

Reverse Domain Name: Use your domain name in reverse as the base of your package names
(e.g., [Link]).

Lowercase Names: Use lowercase letters to avoid conflicts.

Meaningful Names: Use descriptive names to reflect the content.

9. Java Built-in Packages

Java comes with several built-in packages that provide a wide range of functionalities.

[Link]: Fundamental classes (automatically imported).

[Link]: Utility classes, collections framework.

[Link]: Input/output operations.

[Link]: Networking operations.

10. Example Program Using Packages

Here’s a full example of creating and using user-defined packages.


// Step 1: Define a Package

// File: com/example/greetings/[Link]

package [Link];

public class Greeter {

public void sayHello() {

[Link]("Hello from the Greeter class!");

// Step 2: Create Another Class to Use This Package

// File: com/example/app/[Link]

package [Link];

import [Link];

public class MainApp {

public static void main(String[] args) {

Greeter greeter = new Greeter();

[Link]();

To compile and run this example, navigate to the root directory and compile both files before
running java [Link].

Benefits of Using Packages in Java

Namespace Management: Avoid name conflicts by grouping related classes and interfaces.
Access Protection: Provide controlled access to classes and members.

Modularity: Promote modular programming by organizing code into distinct units.

Reusability: Classes in packages can be easily reused across different projects.

Java Interfaces: A Foundation and Practical Guide

An interface in Java is a blueprint for a class. It defines a contract that specifies what a class
must do, but not how it does it. Before Java 8, interfaces could only contain method
signatures (abstract methods) and constant fields. Since Java 8, they can also include default
and static methods.

What is an Interface? 🤔
Think of an interface as a formal agreement. If a class decides to implement an interface, it's
making a promise to provide concrete implementations for all the abstract methods defined in
that interface. This promotes a concept called abstraction, where you hide the complex
implementation details and only show the necessary functionalities to the user.

Key characteristics of a Java interface:

By default, all methods in an interface are public and abstract.

All variables are public, static, and final by default.

Interfaces cannot be instantiated.

A class can implement multiple interfaces.

An interface can extend another interface.

How Java Achieves Multiple Inheritance with Interfaces

Unlike C++, Java does not support multiple inheritance of classes. This is primarily to avoid
the "Diamond Problem." The diamond problem occurs when a class inherits from two
superclasses that both have a method with the same name. It creates ambiguity for the
compiler, which can't determine which version of the method to inherit. However, this
problem is neatly avoided by using interfaces.

Since interfaces only define a contract (a set of abstract methods) and not the implementation,
there's no ambiguity when a class implements multiple interfaces. The implementing class
itself provides the concrete implementation for each method. This allows a single class to
adopt behaviors from multiple "parent" interfaces, effectively achieving multiple inheritance
of behavior.

Let's look at an example:

// Interface for a land vehicle

interface Walkable {

void walk();

// Interface for a water vehicle

interface Swimmable {

void swim();

// A class that can both walk and swim

class Duck implements Walkable, Swimmable {

@Override

public void walk() {

[Link]("Duck is walking.");

@Override

public void swim() {

[Link]("Duck is swimming.");

}
}

In the code above, the Duck class inherits the behaviors of both Walkable and Swimmable,
providing its own implementation for each. There is no ambiguity because the
implementation is explicitly provided by the Duck class itself.

Important Notes for Interview Preparation 📝

1. Interface vs. Abstract Class


This is a very common interview question. While both are used to achieve abstraction, they
have key differences:

Interface: Provides 100% abstraction (before Java 8). Cannot have constructors. A class can
implement multiple interfaces.

Abstract Class: Can have both abstract and concrete (implemented) methods. Can have
constructors. A class can only extend one abstract class. Use abstract classes when you need
to share a common base implementation among subclasses.

2. Default and Static Methods (Java 8+)

Java 8 introduced default methods to interfaces. This was a significant change that allows
developers to add new methods to an existing interface without breaking all the classes that
implement it.

Default methods are useful for backward compatibility. They have a default implementation
that can be used by implementing classes, but can also be overridden.

interface Vehicle {

void move();

// Default method introduced in Java 8

default void honk() {


[Link]("Honk!");

Static methods in interfaces are utility methods that are tied to the interface itself, not to an
implementing class or object. They are called using the interface name (e.g.,
[Link]()).

3. Marker Interfaces

A marker interface is an interface that has no methods or fields. Its sole purpose is to "mark"
a class with a certain capability. The Java Virtual Machine (JVM) then uses this information
to perform some special operation on the class. Common examples include Serializable and
Cloneable.

// This is a marker interface

public interface Serializable {

When a class implements Serializable, the JVM knows that objects of this class can be
converted into a byte stream (serialized).

4. Loose Coupling and Polymorphism

Interfaces promote loose coupling, which means different parts of your code are less
dependent on each other. You can program to an interface rather than to a concrete
implementation.

This also enables polymorphism. A variable of an interface type can hold a reference to any
object that implements that interface. This makes your code flexible and easy to maintain.
// Using an interface type for polymorphism

List<String> myList = new ArrayList<>();

// The variable 'myList' is of type List, but its object is an ArrayList.

// You can later switch to a different implementation (e.g., LinkedList)

// without changing the code that uses 'myList'.

Java Exception Handling Basics

In Java, **exception handling** is a robust mechanism to manage runtime errors, which are
known as exceptions. It helps maintain the normal flow of the application even when
unexpected events occur.

The core keywords used for exception handling are **try**, **catch**, **finally**,
**throw**, and **throws**.

The try-catch Block

The **try** block encloses the code that might throw an exception. The **catch** block
handles the exception if it occurs. You can have multiple catch blocks to handle different
types of exceptions.

ArithmeticException

This example demonstrates how to handle a common runtime exception,


**ArithmeticException**, which occurs when you try to divide a number by zero.

public class DivisionDemo {

public static void main(String[] args) {


int numerator = 10;

int denominator = 0; // This will cause an ArithmeticException

try {

// The code that might throw an exception

int result = numerator / denominator;

[Link]("Result: " + result);

} catch (ArithmeticException e) {

// The code to handle the exception

[Link]("Error: Cannot divide by zero.");

[Link]("Exception details: " + [Link]());

[Link]("Program continues after exception handling.");

Output

Error: Cannot divide by zero.

Exception details: / by zero

Program continues after exception handling.

The finally Block


The **finally** block contains code that will be executed regardless of whether an exception
occurred or not. It's often used for cleanup tasks, such as closing resources like files or
database connections.
Practical Demo: Using finally

public class FinallyDemo {

public static void main(String[] args) {

try {

int data = 100 / 0; // Throws an exception

[Link]("This line will not be executed.");

} catch (ArithmeticException e) {

[Link]("Exception caught: " + [Link]());

} finally {

[Link]("The finally block is always executed.");

Output

Exception caught: / by zero

The finally block is always executed.

Basic Java Exception Handling Interview Questions for Freshers


Assignment Question:
[Link] is an **Exception** in Java?

2. What's the difference between a **Checked Exception** and an **Unchecked


Exception**?

3 .What are the 5 keywords used for exception handling in Java?

4. Explain the purpose of the **try**, **catch**, and **finally** blocks.

5. What is the difference between the **throw** and **throws** keywords?

6. Can a **try** block exist without a **catch** or **finally** block?

7. When is the **finally** block not executed?

8. What are some common types of **unchecked exceptions** you have encountered?
(e.g., `NullPointerException`, `ArrayIndexOutOfBoundsException`).

9. What is the purpose of the **`printStackTrace()`** method?

10. Explain the **Java Exception Hierarchy**.

11. How do you create a **custom exception** in Java?

12. What is the difference between **Exception** and **Error** in Java?

13. What is the difference between **final**, **finally**, and **finalize()**?

14. Explain the concept of **exception propagation** in Java.

15. Explain about Throable class in Java

16. What are the two main subclasses of the Throwable class in Java?

17. How does the Throwable class facilitate exception handling in Java?

18. What methods are commonly used from the Throwable class to retrieve exception
information?

19. Explain Checked and Unchecked Exceptions in Java with examples


Java SE: Core Packages and Classes

Packages in Java SE

A package in Java is a mechanism to group related classes, interfaces, enumerations, and


annotations. Packages provide a way to organize code, prevent naming conflicts, and control
access to classes.

Example:

// Declares a class in the '[Link]' package

package [Link];

import [Link];

public class MyClass {

// Class content

[Link] Package and its Classes


The [Link] package contains fundamental classes and interfaces that are essential to the
Java language. It is automatically imported into every Java program. Key classes include
Object, String, Math, and the wrapper classes.

Class Object
The Object class is the root of the class hierarchy. Every class in Java, implicitly or explicitly,
is a direct or indirect subclass of Object. It defines basic methods like equals(), hashCode(),
and toString().

Example:

class Person {

private String name;

public Person(String name) {

[Link] = name;

@Override

public String toString() {

return "Person [name=" + name + "]";

public class ObjectDemo {

public static void main(String[] args) {

Person p = new Person("Alice");

[Link]([Link]());

Output:

Person [name=Alice]

Enumeration
An enumeration (enum) is a special data type that represents a fixed set of constants. They
are used to create a type-safe collection of constants, making the code more readable and less
error-prone.

Example:

public enum Day {

SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY,


SATURDAY

public class EnumDemo {

public static void main(String[] args) {

Day today = [Link];

[Link]("Today is " + today);

Output:

Today is WEDNESDAY

Class Math

The Math class contains methods for performing basic numeric operations such as elementary
exponential, logarithm, square root, and trigonometric functions. All methods in this class are
static.

Example:

public class MathDemo {

public static void main(String[] args) {

double x = 25.0;

double sqrtX = [Link](x);


[Link]("Square root of " + x + " is " + sqrtX);

int max = [Link](10, 20);

[Link]("Maximum value is " + max);

Output:

Square root of 25.0 is 5.0

Maximum value is 20

Wrapper Classes
Wrapper classes in Java are used to convert primitive data types (like int, char) into objects.
Each primitive type has a corresponding wrapper class, such as Integer, Character, Double,
etc.

Example:

public class WrapperDemo {

public static void main(String[] args) {

int primitiveInt = 100;

Integer wrapperInt = [Link](primitiveInt); // Boxing

[Link]("Wrapper object value: " + wrapperInt);

double primitiveDouble = 99.99;

Double wrapperDouble = [Link](primitiveDouble);

[Link]("Wrapper object value: " + wrapperDouble);


}

Output:

Wrapper object value: 100

Wrapper object value: 99.99

Auto-boxing and Auto-unboxing

Autoboxing is the automatic conversion of a primitive type to its corresponding wrapper class
object. Auto-unboxing is the reverse process, where a wrapper class object is automatically
converted back to its primitive type.

Example:

import [Link];

public class AutoboxingDemo {

public static void main(String[] args) {

// Autoboxing: int to Integer

Integer x = 10;

[Link]("Autoboxing: " + x);

// Auto-unboxing: Integer to int

int y = x;

[Link]("Auto-unboxing: " + y);

// Autoboxing in a collection

ArrayList<Integer> list = new ArrayList<>();


[Link](15);

int z = [Link](0);

[Link]("From list: " + z);

Output:

Autoboxing: 10

Auto-unboxing: 10

From list: 15

[Link] Classes and Interfaces

The [Link] package contains the collections framework, date and time facilities, event
model, and more. It includes classes like ArrayList, HashMap, Random, and interfaces like
List and Map.

Formatter Class

The Formatter class provides support for layout justification and alignment, common formats
for numeric, string, and date/time data, and locale-specific output.

Example:

import [Link];

public class FormatterDemo {

public static void main(String[] args) {

Formatter f = new Formatter();

[Link]("The value of pi is %.2f", [Link]);

[Link]([Link]());

[Link]();
}

Output:

The value of pi is 3.14

Random Class

The Random class is used to generate a stream of pseudo-random numbers. It can produce
random integers, doubles, and booleans.

Example:

import [Link];

public class RandomDemo {

public static void main(String[] args) {

Random rand = new Random();

int randomNumber = [Link](100);

[Link]("Random number: " + randomNumber);

Example Output:

Random number: 42

Time Package ([Link])

Introduced in Java 8, the [Link] package provides a new, modern API for date and time
manipulation. It is immutable and thread-safe, addressing many shortcomings of the older
[Link] and Calendar classes.

Class Instant ([Link])

An Instant represents a specific point in time on the timeline. It is independent of any time
zone and is ideal for marking time-stamps. It represents the number of seconds from the
epoch of 1970-01-01T[Link]Z.
Example:

import [Link];

public class InstantDemo {

public static void main(String[] args) {

Instant now = [Link]();

[Link]("Current Instant: " + now);

Example Output:

Current Instant: 2025-09-23T[Link].123456789Z

Formatting for Date/Time in Java

The [Link] class is used to format and parse date and time
objects. It offers a powerful way to convert date/time objects to strings and vice versa, using
predefined patterns or custom ones.

Example:

import [Link];

import [Link];

public class DateTimeFormatterDemo {

public static void main(String[] args) {

LocalDateTime now = [Link]();

DateTimeFormatter formatter = [Link]("dd-MM-yyyy


HH:mm:ss");

String formattedDateTime = [Link](formatter);

[Link]("Formatted Date/Time: " + formattedDateTime);


}

Example Output:

Formatted Date/Time: 23-09-2025 [Link]

View Oracle Documentation for DateTimeFormatter

TemporalAdjusters Class

The TemporalAdjusters class, part of the [Link] package, provides a rich set of
static methods for common date adjustments, such as finding the next day of the week, the
last day of the month, or the first day of the year.

Example:

import [Link];

import [Link];

import static [Link];

public class TemporalAdjustersDemo {

public static void main(String[] args) {

LocalDate date = [Link](2025, 1, 20);

LocalDate nextFriday = [Link]([Link](FRIDAY));

[Link]("Next Friday from " + date + " is " + nextFriday);

Output:

Next Friday from 2025-01-20 is 2025-01-24


Java I/O API and Streams

Overview of Java I/O

The Java I/O (Input/Output) API is used for handling the input and output of data in an
application. It is primarily based on the concept of streams, which represent a sequence of
data flowing from a source to a destination.

Standard I/O Streams

Java provides three standard streams that are automatically created for every program:

[Link]: The standard input stream (keyboard).

[Link]: The standard output stream (console).

[Link]: The standard error stream (console, for error messages).

Example:

public class StandardIO {

public static void main(String[] args) {

[Link]("This is a message sent to standard output.");

[Link]("This is an error message sent to standard error.");

Output:

This is a message sent to standard output.

This is an error message sent to standard error.

Byte Streams
Byte streams are used to perform I/O of 8-bit bytes. They are ideal for handling raw binary
data, such as images, audio files, or any non-text data. The two main classes are InputStream
and OutputStream.

Example: File Copy with Byte Streams

import [Link];

import [Link];

import [Link];

public class ByteStreamExample {

public static void main(String[] args) {

// Assume '[Link]' contains binary data.

// This code copies content from '[Link]' to '[Link]'.

try (FileInputStream in = new FileInputStream("[Link]");

FileOutputStream out = new FileOutputStream("[Link]")) {

int byteRead;

while ((byteRead = [Link]()) != -1) {

[Link](byteRead);

[Link]("File copied successfully using byte streams.");

} catch (IOException e) {

[Link]("An I/O error occurred: " + [Link]());

}
Example Output:

File copied successfully using byte streams.

View Oracle Documentation for InputStream

Character Streams

Character streams are used to handle I/O of 16-bit Unicode characters. They are best suited
for working with text-based data, as they automatically handle character encoding. The main
classes are Reader and Writer.

Example: File Copy with Character Streams

import [Link];

import [Link];

import [Link];

public class CharacterStreamExample {

public static void main(String[] args) {

// Assume '[Link]' contains text data.

// This code copies content from '[Link]' to '[Link]'.

try (FileReader in = new FileReader("[Link]");

FileWriter out = new FileWriter("[Link]")) {

int charRead;

while ((charRead = [Link]()) != -1) {

[Link](charRead);

[Link]("File copied successfully using character streams.");

} catch (IOException e) {
[Link]("An I/O error occurred: " + [Link]());

Example Output:

File copied successfully using character streams.

View Oracle Documentation for Reader

Scanner Class

The Scanner class, found in the [Link] package, is a simple text scanner that can parse
primitive types and strings using regular expressions. It is commonly used for reading input
from the console or from a file.

Example: Reading User Input

import [Link];

public class ScannerExample {

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Please enter your name: ");

String name = [Link]();

[Link]("Hello, " + name + "!");

[Link]();

}
Example Output:

Please enter your name: Bob

Hello, Bob!

View Oracle Documentation for Scanner

Files in Java ([Link])

Introduced in Java 7 as part of the New I/O (NIO.2) API, the [Link] class provides
static methods for operating on files, directories, and other types of files. It offers a more
modern, robust, and efficient way to handle file I/O operations.

Example: Writing to a File

import [Link];

import [Link];

import [Link];

public class FilesExample {

public static void main(String[] args) {

String content = "Hello, this is content from the Files class!";

Path filePath = [Link]("modern_output.txt");

try {

[Link](filePath, content);

[Link]("Content written to file successfully.");

} catch (IOException e) {
[Link]("Failed to write to file: " + [Link]());

Example Output:

Content written to file successfully.

You might also like