Unittwo
Unittwo
Java, Packages
[Website]
Access specifiers
Access specifiers, also known as access modifiers, are keywords in
Java that control the visibility and accessibility of classes, interfaces,
methods, variables, constructors, and data members. There are four
types of access specifiers in Java, each with a different level of
accessibility
Public:
The public access specifier allows access from any class, regardless
of its package.
Protected:
The protected access specifier allows access within the same
package and by subclasses in other packages.
Default (package-private):
When no access specifier is specified, it is considered default or
package-private. This allows access within the same package only.
Private:
The private access specifier restricts access to within the same class
only.
Example=>
package mypackage;
class Demo {
System.out.println("Public Method");
System.out.println("Protected Method");
void showDefault() {
System.out.println("Default Method");
}
private void showPrivate() {
System.out.println("Private Method");
void displayAll() {
obj.showPublic(); // Accessible
obj.showProtected(); // Accessible
obj.showDefault(); // Accessible
obj.displayAll();
All methods are implicitly public and abstract (unless they are default
or static).
All fields are public, static, and final (constants).
A class implements an interface using the implements keyword.
A class can implement multiple interfaces, overcoming Java’s single
inheritance limitation.
Interfaces cannot have constructors.
Syntax:
// Defining an interface
interface MyInterface {
// Abstract method (no body)
void showMessage();
Java Packages
A package in Java is a way to organize related classes, interfaces, and
sub-packages. It helps avoid name conflicts and provides better
access control.
Prevent naming conflicts by allowing classes with the same name to
exist in different packages,
like college.staff.cse.Employee and college.staff.ee.Employee.
Built-in Packages (Predefined by Java)
Example: java.util, java.io, java.net, java.sql, javax.swing
User-defined Packages (Created by developers)
Example: com.myapp.models, com.myapp.utils
They make it easy to organize, locate, and use classes, interfaces, and
other components
Packages also provide controlled access for Protected members that
are accessible within the same package and by subclasses.
Directory Structure: Package names and directory structures are
closely related. For example, if a package name is college.staff.cse,
then three directories are, college, staff, and cse, where cse is inside
staff, and staff is inside the college
Import a specific class:
import java.util.Vector;
Features of java packages
✔ Code Organization – Helps group related classes.
✔ Avoids Name Conflicts – Prevents class name clashes.
✔ Access Control – Protects data with different access levels.
✔ Reusability – Promotes modular programming.
Example:
Create package
Javac –d.Myclass.java
Import packages
Nested Classes in Java
In Java, it is possible to define a class within another class, such
classes are known as nested classes. They enable you to logically
group classes that are only used in one place, thus this increases the
use of encapsulation and creates more readable and maintainable
code.
A nested class has access to the members, including private
members, of the class in which it is nested. But the enclosing class
does not have access to the member of the nested class.
A nested class is also a member of its enclosing class.
As a member of its enclosing class, a nested class can be
declared private, public, protected, or package-private(default).
Nested classes are divided into two categories:
static nested class: Nested classes that are declared static are called
static nested classes.
inner class: An inner class is a non-static nested class.
Example:
class Outer {
static class StaticNested {
void display() {
System.out.println("Inside Static Nested Class");
}
}
}
Abstract Class
Abstract Class: A class that is declared using the “abstract” keyword is
known as an abstract class.
The main idea behind an abstract class is to implement the concept of
Abstraction.
An abstract class can have both abstract methods(methods without
body) as well as the concrete methods(regular methods with the
body).
However, a normal class(non-abstract class) cannot have abstract
methods. The following is an example of how an abstract class is
declared.
Normal Import
A normal import is used to import classes from a package so that they
can be used without specifying their full package names.
Key Points About Normal Import:
It is used to import entire classes (not static members).
You can import a single class or multiple classes.
Using import package.*; imports all classes of a package, but it does
not include sub-packages.
It improves code readability and reduces redundancy.
Static import
Static import allows you to access static methods and variables of a
class directly, without using the class name.
Improves readability by removing class qualifiers.
Makes code cleaner and shorter.
Downsides of Static Import:
Can lead to confusion if multiple static members with the same name
exist.
Can reduce code clarity by hiding where methods/fields come from.
JAVA.LANG (package)
The java.lang package is one of the core Java packages and is
automatically imported in every Java program. It contains fundamental
classes essential for Java programming, such as String, Math, System,
Object, Thread, Integer, and many more.
Example:
System.out.println(str.toUpperCase()); // Output: JAVA
System.out.println(Math.sqrt(16)); // Output: 4.0
No need to explicitly import it (import is automatic).
Contains fundamental classes used in almost all Java programs.
Provides utilities for strings, math, system operations, threading, and
exceptions.
Object Class
The root class of all Java classes.
Provides methods like equals(), hashCode(), toString(), clone(), and
more.
String Class
Represents immutable character sequences.
Provides methods like length(), concat(), toUpperCase(), substring(),
etc.
Math Class
Contains mathematical functions like sqrt(), pow(), abs(), random(),
etc.
JAVA.UTIL
java.util is a package in Java that contains a collection of utility classes
that provide various functionalities, such as data structures, date/time
handling, random number generation, and more. Some of the most
commonly used classes in java.util include
Random Number Generation
Random - Generates random numbers.
Splitable Random - A more efficient random number generator
introduced in Java 8.
Date and Time
Date (deprecated, replaced by java.time package in Java 8+)
Calendar - Provides methods for date and time manipulation.
Time Zone - Represents a time zone
Both Gregorian Calendar and Calendar are part of the java.util
package and are used for date and time manipulation in Java.
However, there are key differences between them.
Calendar (Abstract Class)
Calendar is an abstract class that provides a generic way to work with
date and time.
It defines methods for date/time manipulation but does not
implement them.
It serves as a base class for specific calendar systems like Gregorian
Calendar.
Example:
import java.util.GregorianCalendar;
import java.util.Calendar;
Key Differences
When to Use What?
Wrapper class
In Java, primitive data types (like int, char, double, etc.) do not have
methods, so Java provides wrapper classes in the java.lang package to
convert them into objects with useful methods.
Example:
public class WrapperDemo {
public static void main(String[] args) {
// Primitive types
int primitiveInt = 10;
double primitiveDouble = 5.5;
// Wrapper classes
Integer wrappedInt = Integer.valueOf(primitiveInt); // Boxing
Double wrappedDouble = Double.valueOf(primitiveDouble);
// Auto-unboxing
int autoUnboxedInt = wrappedInt;
double autoUnboxedDouble = wrappedDouble;
// Printing values
System.out.println("Primitive int: " + primitiveInt);
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Auto-boxed Integer: " + autoBoxedInt);
System.out.println("Unboxed Integer: " + unboxedInt);
System.out.println("Auto-unboxed Integer: " + autoUnboxedInt);
}
}
Vector in java
Vector<String> → This declares a Vector that will store only String
type data.
(Diamond Operator) automatically infers the type.
This prevents adding elements of other types (like numbers or
objects).
new Vector<>() → This creates a new Vector object in memory.
It initializes an empty dynamic array with a default capacity of 10
elements.
The Vector will grow automatically when more elements are added.
Example:
import java.util.Vector;
// Adding elements
vector.add("Apple");
vector.add("Banana");
vector.add("Cherry");
// Accessing elements
System.out.println("First element: " + vector.get(0));
// Removing an element
vector.remove("Banana");
LinkedList in Java
In Java, LinkedList is a part of the Java Collection Framework and is found in the
java.util package. It implements the List and Deque interfaces, allowing elements
to be stored in a doubly-linked list structure.
LinkedList is a linear data structure in Java where elements (nodes) are stored
non-contiguously in memory.
Each element in a LinkedList is called a Node, and every node contains two parts
Data (Value) → Stores the actual data.
Links (Next & Previous) → Pointers that store the address of the next and previous
nodes.
Example:
import java.util.LinkedList;
// Adding elements
list.add("Apple");
list.add("Banana");
list.add("Cherry");
// Accessing elements
System.out.println("First Element: " + list.getFirst());
System.out.println("Last Element: " + list.getLast());
// Removing elements
list.remove("Banana");
list.removeFirst();
list.removeLast();
Create mypackage.MyClass
package mypackage;
Create mypackage.subpackage.SubClass
Save this file as SubClass.java inside the mypackage/subpackage
folder.
package mypackage.subpackage;