Advanced Java Fundamentals
Learn important Java concepts such as packages, access modifiers, wrapper classes, generics, lambda expressions, functional interfaces and the Stream API.
Introduction to This Module
So far, you have learned how to write Java programs, create classes and objects, handle exceptions and work with collections.
Now, it is time to understand some additional Java features that make programs more organised, reusable and easier to work with.
These concepts are useful in real-world Java development and are also frequently discussed in technical interviews.
What You Will Learn
- Organise Java code using packages.
- Control access to classes, methods and variables using access modifiers.
- Understand wrapper classes and their uses.
- Convert between primitive values and wrapper objects.
- Write reusable and type-safe code using generics.
- Understand lambda expressions and shorter ways to write functions.
- Process collections using the Stream API.
- Understand functional interfaces and their role in modern Java.
1. Packages in Java
What Is a Package?
A package in Java is a way to group related classes, interfaces and other Java files together.
Think of a package like a folder on your computer. You create different folders to organise different types of files. In the same way, Java packages help organise related program code.
Real-Life Example
Imagine a college application. You may have separate sections for students, teachers and accounts. Keeping their related files in separate folders makes the application easier to manage.
Java packages provide a similar way to organise code.
Why Do We Use Packages?
- To organise related classes.
- To avoid naming conflicts between classes.
- To make code easier to maintain.
- To support code reuse.
- To control access to classes and members.
Types of Packages
Java packages are commonly discussed in two categories:
- Built-in packages: Packages provided by Java.
- User-defined packages: Packages created by programmers.
Common Built-in Packages
| Package | Purpose |
|---|---|
| java.lang | Contains basic classes such as String, Math and System. |
| java.util | Contains utility classes and collections. |
| java.io | Provides input and output functionality. |
| java.time | Provides classes for working with dates and time. |
| java.net | Provides networking-related classes. |
Importing a Package
The import keyword allows us to use classes
from another package without writing their complete
package name every time.
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Aman");
names.add("Riya");
System.out.println(names);
}
}
[Aman, Riya]
Creating a User-Defined Package
We can create our own package using the
package keyword. The package declaration
must appear at the beginning of the Java source file,
before import statements and class declarations.
File 1: Student.java
package mypackage;
public class Student {
public void display() {
System.out.println("Welcome to Java Packages");
}
}
File 2: Main.java
import mypackage.Student;
class Main {
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}
Welcome to Java Packages
2. Access Modifiers
What Are Access Modifiers?
Access modifiers are keywords that control where a class, method, constructor or variable can be accessed.
In simple words, they decide who is allowed to use a particular part of your program.
Real-Life Example
Think about a house. Some areas may be open to everyone, some may be available only to family members, and some may be private.
Access modifiers work in a similar way by controlling access to Java program members.
Types of Access Modifiers
Java provides four access levels:
| Modifier | Same Class | Same Package | Subclass in Other Package | Other Package |
|---|---|---|---|---|
| private | Yes | No | No | No |
| default | Yes | Yes | No | No |
| protected | Yes | Yes | Yes, through inheritance rules | No |
| public | Yes | Yes | Yes | Yes |
1. private
The private modifier allows access only
within the same class.
class Student {
private int marks = 90;
public void displayMarks() {
System.out.println(marks);
}
}
class Main {
public static void main(String[] args) {
Student s = new Student();
s.displayMarks();
}
}
90
The variable marks is private, so it
cannot be accessed directly from the Main class.
The public method provides a way to display it.
2. default Access
When no access modifier is written, Java uses package-private, also called default access. The member can be accessed by classes in the same package.
class Student {
int marks = 85;
void display() {
System.out.println(marks);
}
}
class Main {
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}
85
3. protected
The protected modifier allows access
within the same package and also in subclasses
in other packages, subject to Java's inheritance
access rules.
class Parent {
protected void display() {
System.out.println("Protected method");
}
}
class Child extends Parent {
void show() {
display();
}
}
class Main {
public static void main(String[] args) {
Child c = new Child();
c.show();
}
}
Protected method
4. public
The public modifier allows access from
anywhere, provided the class itself is accessible.
class Student {
public void display() {
System.out.println("Public method");
}
}
class Main {
public static void main(String[] args) {
Student s = new Student();
s.display();
}
}
Public method
Important Points
- private provides the most restricted access.
- public provides the widest access.
- Default access means no modifier is specified.
- Top-level classes can be public or package-private, not private or protected.
- Access modifiers are important for encapsulation and data protection.
3. Wrapper Classes
What Are Wrapper Classes?
Java has primitive data types such as int, char, double and boolean. Wrapper classes allow us to represent these primitive values as objects.
In simple words, a wrapper class wraps a primitive value inside an object.
Primitive Types and Their Wrapper Classes
| Primitive Type | Wrapper Class |
|---|---|
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
| char | Character |
| boolean | Boolean |
Why Do We Need Wrapper Classes?
- Collections such as ArrayList store objects, not primitive values directly.
- They provide useful conversion and utility methods.
- They allow primitive values to be used where objects are required.
- They can represent the absence of a value using null.
Example: Using Integer Wrapper Class
class Main {
public static void main(String[] args) {
int a = 10;
Integer b = Integer.valueOf(a);
System.out.println("Primitive: " + a);
System.out.println("Wrapper object: " + b);
}
}
Primitive: 10 Wrapper object: 10
Useful Wrapper Class Methods
class Main {
public static void main(String[] args) {
int number = Integer.parseInt("100");
double price = Double.parseDouble("45.50");
System.out.println(number + 20);
System.out.println(price + 10);
System.out.println(Integer.MAX_VALUE);
}
}
120 55.5 2147483647
Important Methods
| Method | Purpose |
|---|---|
| Integer.parseInt() | Converts a numeric String into an int. |
| Double.parseDouble() | Converts a numeric String into a double. |
| Integer.valueOf() | Returns an Integer object from a value. |
| Integer.MAX_VALUE | Provides the maximum int value. |
| Integer.MIN_VALUE | Provides the minimum int value. |
4. Autoboxing and Unboxing
What Is Autoboxing?
Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper object.
Example: Autoboxing
class Main {
public static void main(String[] args) {
int number = 100;
Integer obj = number;
System.out.println(obj);
}
}
100
Java automatically converts the int value into an
Integer object. We do not need to call
Integer.valueOf() ourselves.
What Is Unboxing?
Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value.
Example: Unboxing
class Main {
public static void main(String[] args) {
Integer obj = 200;
int number = obj;
System.out.println(number);
}
}
200
Autoboxing and Unboxing Together
class Main {
public static void main(String[] args) {
int a = 10;
// Autoboxing
Integer obj = a;
// Unboxing
int b = obj;
System.out.println("Object: " + obj);
System.out.println("Primitive: " + b);
}
}
Object: 10 Primitive: 10
Difference Between Autoboxing and Unboxing
| Autoboxing | Unboxing |
|---|---|
| Primitive to wrapper object. | Wrapper object to primitive. |
| Example: int to Integer. | Example: Integer to int. |
| Done automatically by Java. | Done automatically by Java. |
5. Generics
What Are Generics?
Generics allow us to write classes, interfaces and methods that work with different data types while maintaining type safety.
In simple words, generics let us decide what type of data a class or method should work with.
Real-Life Example
Imagine a box designed only for books. You can put books inside it, but you should not put shoes or vegetables inside it.
Generics work in a similar way. They help specify the type of data that a class or collection can accept.
Why Do We Use Generics?
- To improve type safety.
- To reduce unnecessary type casting.
- To create reusable code.
- To detect many type-related errors at compile time.
Example Without Generics
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList list = new ArrayList();
list.add("Aman");
list.add(100);
String name = (String) list.get(0);
System.out.println(name);
}
}
Aman
Without generics, an ArrayList can accept different object types. We may need to perform type casting when retrieving values.
Example With Generics
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
ArrayList<String> names = new ArrayList<>();
names.add("Aman");
names.add("Riya");
String name = names.get(0);
System.out.println(name);
}
}
Aman
Here, ArrayList<String> means that
the list is designed to store String objects.
Adding an Integer directly would cause a compile-time error.
Creating a Generic Class
We can also create our own generic classes using
a type parameter such as T.
class Box<T> {
T value;
void setValue(T value) {
this.value = value;
}
T getValue() {
return value;
}
}
class Main {
public static void main(String[] args) {
Box<String> box = new Box<>();
box.setValue("Hello Java");
System.out.println(box.getValue());
Box<Integer> numberBox = new Box<>();
numberBox.setValue(100);
System.out.println(numberBox.getValue());
}
}
Hello Java 100
Common Generic Type Parameter Names
| Letter | Common Meaning |
|---|---|
| T | Type |
| E | Element |
| K | Key |
| V | Value |
| N | Number |
6. Lambda Expressions
What Is a Lambda Expression?
A lambda expression is a shorter way to write an implementation of a functional interface.
It helps us write cleaner code without creating a separate class or writing lengthy anonymous class code for simple operations.
Basic Syntax
(parameters) -> expression
The arrow symbol -> separates the
parameters from the body of the lambda expression.
Example Without Lambda Expression
interface Message {
void display();
}
class Main {
public static void main(String[] args) {
Message m = new Message() {
public void display() {
System.out.println("Hello Java");
}
};
m.display();
}
}
Same Example Using Lambda Expression
interface Message {
void display();
}
class Main {
public static void main(String[] args) {
Message m = () ->
System.out.println("Hello Java");
m.display();
}
}
Hello Java
Lambda Expression With Parameters
interface Addition {
int add(int a, int b);
}
class Main {
public static void main(String[] args) {
Addition obj = (a, b) -> a + b;
int result = obj.add(10, 20);
System.out.println(result);
}
}
30
Lambda Expression With Multiple Statements
When a lambda contains multiple statements, we use curly braces. If the functional method returns a value, we use the return keyword.
interface Calculator {
int calculate(int a, int b);
}
class Main {
public static void main(String[] args) {
Calculator multiply = (a, b) -> {
int result = a * b;
return result;
};
System.out.println(multiply.calculate(5, 4));
}
}
20
Benefits of Lambda Expressions
- Reduce unnecessary code.
- Make simple operations easier to read.
- Work with functional interfaces.
- Are useful with collections and the Stream API.
7. Stream API
What Is the Stream API?
The Stream API allows us to process data from collections and other data sources in a clean and readable way.
It provides operations such as filtering, mapping and sorting without requiring us to write lengthy loops for every task.
Real-Life Example
Imagine you have a list of 100 students and want to find only those students who scored more than 70.
Instead of manually checking every student and creating another list, you can use the Stream API to filter the required values.
Important Stream Operations
| Operation | Purpose |
|---|---|
| filter() | Selects elements that match a condition. |
| map() | Transforms each element into another value. |
| sorted() | Sorts the stream elements. |
| forEach() | Performs an action for each element. |
| collect() | Collects results into a collection or another result container. |
| count() | Counts the number of elements. |
| distinct() | Removes duplicate elements from the stream. |
Example 1: Filtering Even Numbers
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30, 35);
numbers.stream()
.filter(n -> n % 2 == 0)
.forEach(System.out::println);
}
}
10 20 30
The filter() method keeps only even numbers.
The forEach() method displays the selected values.
Example 2: Transforming Values Using map()
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(1, 2, 3, 4, 5);
numbers.stream()
.map(n -> n * n)
.forEach(System.out::println);
}
}
1 4 9 16 25
The map() method transforms every number
into its square.
Example 3: Sorting Numbers
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(50, 10, 40, 20, 30);
numbers.stream()
.sorted()
.forEach(System.out::println);
}
}
10 20 30 40 50
Example 4: Counting Elements
import java.util.Arrays;
import java.util.List;
class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 20, 30, 40, 50);
long total = numbers.stream().count();
System.out.println("Total elements: " + total);
}
}
Total elements: 5
Example 5: Collecting Filtered Results
We can use collect() to store the
processed stream results in a collection.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
class Main {
public static void main(String[] args) {
List<Integer> numbers =
Arrays.asList(10, 15, 20, 25, 30);
List<Integer> evenNumbers =
numbers.stream()
.filter(n -> n % 2 == 0)
.collect(Collectors.toList());
System.out.println(evenNumbers);
}
}
[10, 20, 30]
Intermediate and Terminal Operations
Stream operations are commonly divided into two groups.
| Intermediate Operations | Terminal Operations |
|---|---|
| Return another stream. | Produce a final result or action. |
| Examples: filter(), map(), sorted(), distinct(). | Examples: forEach(), collect(), count(), reduce(). |
| Are generally lazy. | Trigger stream processing. |
8. Functional Interfaces
What Is a Functional Interface?
A functional interface is an interface that contains exactly one abstract method.
It can also contain default methods, static methods and methods inherited from Object. However, it must have only one abstract method.
Functional interfaces are commonly used with lambda expressions.
Creating a Functional Interface
Java provides the @FunctionalInterface
annotation. It is optional, but it helps the compiler
check that the interface follows the functional
interface rules.
@FunctionalInterface
interface Greeting {
void sayHello();
}
class Main {
public static void main(String[] args) {
Greeting g = () ->
System.out.println("Hello Student");
g.sayHello();
}
}
Hello Student
Common Built-in Functional Interfaces
Java provides several ready-made functional interfaces
in the java.util.function package.
| Interface | Purpose |
|---|---|
| Predicate<T> | Accepts a value and returns true or false. |
| Function<T, R> | Accepts a value and returns another value. |
| Consumer<T> | Accepts a value and performs an action without returning a result. |
| Supplier<T> | Provides a value without accepting an input. |
1. Predicate
Predicate takes an input and returns a boolean value. It is useful for checking conditions.
import java.util.function.Predicate;
class Main {
public static void main(String[] args) {
Predicate<Integer> isEven =
n -> n % 2 == 0;
System.out.println(isEven.test(10));
System.out.println(isEven.test(15));
}
}
true false
2. Function
Function accepts one input and produces a result.
import java.util.function.Function;
class Main {
public static void main(String[] args) {
Function<Integer, Integer> square =
n -> n * n;
System.out.println(square.apply(5));
}
}
25
3. Consumer
Consumer accepts an input and performs an operation without returning a result.
import java.util.function.Consumer;
class Main {
public static void main(String[] args) {
Consumer<String> display =
name -> System.out.println("Hello " + name);
display.accept("Aman");
}
}
Hello Aman
4. Supplier
Supplier does not accept an input. It simply provides
a value when its get() method is called.
import java.util.function.Supplier;
class Main {
public static void main(String[] args) {
Supplier<String> message =
() -> "Welcome to Java";
System.out.println(message.get());
}
}
Welcome to Java
Quick Comparison
| Interface | Input | Output | Main Method |
|---|---|---|---|
| Predicate | Yes | boolean | test() |
| Function | Yes | Result | apply() |
| Consumer | Yes | No result | accept() |
| Supplier | No | Value | get() |
Important Interview Questions
Q1. What is a package in Java?
A package groups related classes and interfaces to organise code and avoid naming conflicts.
Q2. What are the four access modifiers in Java?
private, default, protected and public.
Q3. What is the difference between private and public?
private members are accessible only within their own class, while public members can be accessed wherever the declaring type is accessible.
Q4. What is a wrapper class?
A wrapper class represents a primitive value as an object, such as Integer for int.
Q5. What is the difference between int and Integer?
int is a primitive data type, while Integer is its wrapper class and represents an object.
Q6. What is autoboxing?
Autoboxing is the automatic conversion of a primitive value into its corresponding wrapper object.
Q7. What is unboxing?
Unboxing is the automatic conversion of a wrapper object into its corresponding primitive value.
Q8. What are generics in Java?
Generics allow classes, interfaces and methods to work with specified data types while providing compile-time type safety.
Q9. What is the advantage of generics?
Generics improve type safety, reduce type casting and help create reusable code.
Q10. What is a lambda expression?
A lambda expression is a concise way to provide an implementation of a functional interface.
Q11. What is the Stream API?
The Stream API provides operations to process data from collections and other sources in a readable and functional style.
Q12. What is the difference between filter() and map()?
filter() selects elements based on a condition, while map() transforms elements into new values.
Q13. What is a functional interface?
It is an interface with exactly one abstract method. It can be used as the target of a lambda expression.
Q14. What is the use of @FunctionalInterface?
It tells the compiler to check that the interface follows the functional interface rules.
Q15. Name four built-in functional interfaces.
Predicate, Function, Consumer and Supplier.
Q16. What is the difference between Predicate and Function?
Predicate returns a boolean result, while Function returns a result of a specified type.
Q17. What is the difference between Consumer and Supplier?
Consumer accepts an input and performs an action. Supplier does not accept an input and provides a value.
Q18. What is the difference between intermediate and terminal stream operations?
Intermediate operations return another stream and are generally lazy. Terminal operations produce a final result or action and trigger processing.
Module Summary
- Packages organise related Java classes and interfaces.
- Access modifiers control where program members can be accessed.
- Java provides private, default, protected and public access levels.
- Wrapper classes represent primitive values as objects.
- Autoboxing converts primitive values into wrapper objects automatically.
- Unboxing converts wrapper objects into primitive values automatically.
- Generics provide reusable and type-safe code.
- Lambda expressions provide a shorter way to implement functional interfaces.
- The Stream API helps process data using operations such as filter(), map() and sorted().
- Functional interfaces contain exactly one abstract method.
- Predicate, Function, Consumer and Supplier are common built-in functional interfaces.
Practice Questions
Try writing these programs yourself to strengthen your understanding of advanced Java fundamentals.
- Create a user-defined package and use its class in another Java file.
- Write a program demonstrating private and public access modifiers.
- Create a class with a protected method and access it through inheritance.
- Convert a String containing a number into an int using Integer.parseInt().
- Demonstrate autoboxing and unboxing with Integer.
- Create a generic class named Box that stores different types of values.
- Write a lambda expression to add two numbers.
- Use a lambda expression to check whether a number is even.
- Use the Stream API to filter even numbers from a list.
- Use map() to calculate the square of every number in a list.
- Use sorted() to display numbers in ascending order.
- Create a functional interface and implement it using a lambda expression.
- Use Predicate to check whether a number is positive.
- Use Function to convert a name into uppercase.
- Use Consumer to display a student's name.
- Use Supplier to provide a welcome message.
Congratulations! Module 08 Completed
You have learned important advanced Java fundamentals, including packages, access modifiers, wrapper classes, generics, lambda expressions, the Stream API and functional interfaces.
These concepts help you write more organised and reusable Java programs. Practise the examples and interview questions before moving to the next module.