OBJECT-ORIENTED PROGRAMMING
THROUGH JAVA
UNIT - IV
Session 21 - Packages and Core Java
Library
1. Introduction to Packages
Introduction to Packages
Definition:
In Java, packages are used to group related classes and interfaces. They help to organize the
code into manageable sections and avoid naming conflicts.
What is a Package in Java?
In Java, a package is essentially a directory structure used to group related classes, interfaces,
and sub-packages based on their functionality. It provides an organized way to manage your
code and makes it easier to locate and use different components. Java includes several built-in
packages, such as java.lang, java.util, java.io, and java.net, each designed to
categorize and manage related functionality systematically.
Real-Life Analogy of Packages in Java
Consider how you organize files on your computer: you might create separate folders for
movies, music, or games. Similarly, in Java, a package acts like a library where classes and
interfaces are grouped. Each package is like a category in the library, and its classes and
interfaces are akin to books that can be referenced and reused as needed. This organization
simplifies programming by making code reuse more straightforward and maintaining clarity
within a project.
When developing software in Java, you may work with hundreds or thousands of classes and
interfaces. To keep things manageable, these elements are grouped into packages with
meaningful names, facilitating easier reuse and better organization across different programs.
Advantages of Using Packages in Java
1. Maintenance: Packages help maintain code by grouping related files together. This
structure allows new developers to quickly locate and work with the necessary files.
2. Reusability: Common code can be placed in a shared package, making it accessible to
all developers and projects that need it.
3. Name Conflict Resolution: Packages resolve naming conflicts by keeping classes with
the same name in different packages. For example, Student.java in stdPack1 and
Student.java in stdPack2 are distinct due to their package names.
4. Organization: Packages help keep files organized within a project, making the
codebase more manageable.
5. Access Protection: Packages provide access control by limiting the visibility of class
members to other elements within the same package, enhancing security and
encapsulation.
Types of Packages in Java
Java offers two main types of packages:
1. User-Defined Packages: Created by developers to organize their own classes and
interfaces.
2. Built-In Packages: Predefined by Java, such as java.lang, java.util, java.io,
and java.net.
Built-in Packages and User-defined Packages in Java
Built-in Packages
Built-in packages are pre-existing Java packages provided with the Java Development Kit
(JDK). These packages include classes and interfaces that help in various programming tasks.
Some commonly used built-in packages are java.lang, java.util, and java.io.
Example: Using java.util Package
import java.util.HashMap;
class HashMapExample {
public static void main(String[] args) {
HashMap<String, Integer> map = new HashMap<>();
map.put("Apples", 10);
map.put("Bananas", 5);
map.put("Oranges", 8);
System.out.println(map);
}
}
Output:
{Apples=10, Bananas=5, Oranges=8}
In this example, the HashMap class from the java.util package is used to store and manage
a collection of key-value pairs. To use HashMap, we import the java.util package with the
import statement:
import java.util.HashMap;
User-defined Packages
Java allows you to create your own packages, known as user-defined packages. These
packages help you organize your classes and interfaces into a logical structure, making it easier
to manage and avoid name conflicts.
How to Define a Java Package
1. Create a Directory Structure:
- Packages correspond to directories in the file system. For example, if you want to
create a package named com.example.myapp, your directory structure should
look like this:
└── com
└── example
└── myapp
└── MyClass.java
2. Package Statement:
- At the beginning of your Java source file, include a package statement to
declare the package to which the class belongs.
package com.example.myapp;
public class MyClass {
public static void main(String[] args) {
System.out.println("Welcome to the custom package!");
}
}
Output:
Welcome to the custom package!
In this example, the MyClass class belongs to the com.example.myapp package. To ensure
the class is correctly placed in this package, the package statement must match the directory
structure.
Package Naming Conventions
- Package names should be unique and follow a specific naming convention to avoid
conflicts. A common practice is to use a reversed domain name structure. For example,
if your domain is example.com, your package might be com.example.
- Example Directory Structure for Package Naming:
└── com
└── example
└── utilities
└── UtilityClass.java
UtilityClass.java:
package com.example.utilities;
public class UtilityClass {
public static void displayMessage() {
System.out.println("This is a utility class.");
}
}
2. Defining Package
Defining Packages
User-Defined Java Packages
User-defined packages in Java are a powerful way to group related classes, interfaces, and
other types into a single namespace. This organization helps in avoiding naming conflicts,
managing access control, and improving code maintainability. Here’s how you can define and
use packages in Java:
Creating a Java Package
1. Package Statement:
To define a package, include a package statement at the top of your source file. This
statement should be the first line in the file and applies to all types within the file.
Example:
package library;
This declares that all classes, interfaces, and types in the file belong to the library
package.
2. Source File Structure:
If no package statement is included, the classes and interfaces are placed in the default
package.
Example Source File:
package library;
public class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
Compiling with Java Packages
To compile Java files with package statements, use the -d option with the javac command to
specify the destination directory for compiled class files. This command ensures the directory
structure reflects the package hierarchy.
Command:
javac -d Destination_folder FileName.java
Explanation: This compiles the source files and places the resulting class files into the directory
structure corresponding to the package names.
Example of Creating and Using a Java Package
1. Define a Package:
Class Definition in Package library:
/* File name: Book.java */
package library;
public class Book {
private String title;
public Book(String title) {
this.title = title;
}
public String getTitle() {
return title;
}
}
Class Implementation in the Same Package:
/* File name: LibraryManagement.java */
package library;
public class LibraryManagement {
public static void main(String[] args) {
Book book = new Book("Java Programming");
System.out.println("Book Title: " + book.getTitle());
}
}
2. Compile the Package:
Commands:
javac -d . Book.java
javac -d . LibraryManagement.java
These commands will create a library directory in the current directory and place the
compiled Book.class and LibraryManagement.class files inside it.
3. Execute the Class File:
Command:
java library.LibraryManagement
Output:
Book Title: Java Programming
Do It Yourself
1. What is the purpose of using the package statement in a Java source file?
2. How do packages prevent naming conflicts in Java?
3. Describe the process of compiling and running a Java program that uses user-defined
packages.
4. What happens if the package statement is omitted in a Java file?
5. Explain the difference between the default package and user-defined packages.
Quiz
1. How should you declare a package in Java?
A. package myLibrary;
B. package MyLibrary;
C. package My_Library;
D. myLibrary package;
Answer: A. package myLibrary;
2. Which command correctly compiles Java files into the specified directory
structure for a package?
A. javac -d . FileName.java
B. javac FileName.java -d .
C. java -d . FileName.java
D. javac -d FileName.java
Answer: A. javac -d . FileName.java
3. What will happen if you have the same package name in multiple Java files?
A. Compilation fails due to duplicate packages
B. The files are combined into the same package
C. Only one file is compiled
D. The files are ignored
Answer: B. The files are combined into the same package
4. After compiling Java files with packages, where are the compiled class files
located?
A. In the root directory
B. In the directory specified by the -d option
C. In the default package directory
D. In the user’s home directory
Answer: B. In the directory specified by the -d option
5. What is the effect of omitting the package statement in a Java source file?
A. The file is compiled into the default package
B. The file is not compiled
C. The file will result in a compilation error
D. The file is ignored by the compiler
Answer: A. The file is compiled into the default package
3. Importing Packages and Classes into
Programs
Importing Packages in Java
In Java, the import statement allows you to access classes and interfaces from other
packages. This can be done in two primary ways: importing specific classes or importing all
classes from a package.
Syntax for Importing Packages:
1. Importing a Specific Class:
import package.name.ClassName; // Imports only the specified class
2. Importing All Classes in a Package:
import package.name.*; // Imports all classes from the specified package
Examples:
1. Importing a Single Class:
import java.util.Calendar; // Imports only the Calendar class from java.util package
public class CalendarExample {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date: " + calendar.getTime());
}
}
2. Importing All Classes from a Package:
import java.text.*; // Imports all classes from java.text package
public class DateFormatExample {
public static void main(String[] args) {
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
String formattedDate = dateFormat.format(new java.util.Date());
System.out.println("Formatted Date: " + formattedDate);
}
}
Using Fully Qualified Names:
If you prefer not to use the import statement, you can use the fully qualified name of a class,
which includes its package hierarchy.
Example:
public class FullyQualifiedNameExample {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println("Today's Date: " + today);
}
}
Example: Defining and Importing a Custom Package
Suppose you have created a package named com.example.util with a class Formatter:
File Structure:
└── com
└── example
└── util
└── Formatter.java
Formatter.java:
package com.example.util;
public class Formatter {
public static String formatCurrency(double value) {
return String.format("$%.2f", value);
}
}
To use the Formatter class in another file, you would import it as follows:
Main.java:
import com.example.util.Formatter;
public class Main {
public static void main(String[] args) {
double amount = 123.45;
String formattedAmount = Formatter.formatCurrency(amount);
System.out.println("Formatted Amount: " + formattedAmount);
}
}
Output:
Formatted Amount: $123.45
Import Statement Placement:
The import statements should be placed after the package statement (if it exists) and before
the class definition.
Example:
package com.example;
import com.example.util.Formatter; // Importing a specific class
public class ExampleClass {
// Class body
}
Do It Yourself
1. Create a package named com.tools with a class Tool that has a method
performTask(). Write a program in another package to use this class and call the
method.
2. Define a package com.math containing a class Calculator with a method add(int
a, int b). Import this class in a new file and use it to add two numbers.
Quiz
1. Which import statement brings in all classes from the java.util package?
A. import java.util.*;
B. import java.util;
C. import *;
D. import java.util.All;
Answer: A. import java.util.*;
2. What is the effect of using the fully qualified name of a class?
A. It imports the class into your file
B. It allows you to reference the class without an import statement
C. It compiles the class automatically
D. It generates the class file
Answer: B. It allows you to reference the class without an import statement
3. What should you do if you encounter a class name conflict between two
packages?
A. Use only one package
B. Rename the classes
C. Use fully qualified class names to distinguish between them
D. Avoid using packages
Answer: C. Use fully qualified class names to distinguish between them
4. Where should the import statements be placed in a Java file?
A. Before the package statement
B. After the package statement and before the class definition
C. After the class definition
D. At the end of the file
Answer: B. After the package statement and before the class definition
5. Which statement is correct regarding the import statement?
A. It is mandatory for all Java classes
B. It allows access to classes from other packages
C. It automatically imports all classes from the JDK
D. It is used to define new packages
Answer: B. It allows access to classes from other packages
4. Path and Class Path
Path and Class Path
Definition:
The path and classpath are environment variables that tell the Java Virtual Machine (JVM)
and Java compiler where to find classes and packages.
- Path: This environment variable specifies the directories or JAR files where executable
files (like java and javac) are located. It helps the operating system locate Java
commands.
- Classpath: This environment variable tells the JVM and Java compiler where to find
class files, libraries, and JAR files needed to run or compile Java programs. It includes
paths to directories or JAR files where Java classes are stored.
Syntax:
- Setting Path (Windows):
set PATH=C:\Program Files\Java\jdk-14\bin;%PATH%
- Setting Classpath (Windows):
set CLASSPATH=C:\myclasses;C:\mylibs\mylib.jar
- Setting Path (Linux/Mac):
export PATH=/usr/local/java/jdk-14/bin:$PATH
- Setting Classpath (Linux/Mac):
export CLASSPATH=/home/user/myclasses:/home/user/mylibs/mylib.jar
Example:
Assuming you have a Java program HelloWorld.java and a library utils.jar:
- To compile HelloWorld.java with the utils.jar library:
javac -cp utils.jar HelloWorld.java
- To run HelloWorld.class with the utils.jar library:
java -cp .;utils.jar HelloWorld
Comparison:
S. PATH CLASSPATH
No.
1. An environment variable used by the An environment variable used by the Java
operating system to locate executable compiler and JVM to locate compiled class
files like java and javac. files.
2. Sets up the environment for the OS to find Sets up the environment for Java to find
and execute binary files. and load classes and libraries.
3. Refers to the operating system's Refers to the Java runtime and
executable search path. development environment's class search
path.
4. The PATH variable should include the The CLASSPATH variable should include
directory path where the Java paths to directories or .jar files
executables are located (e.g., .bin containing the compiled .class files.
folder).
5. Used by the command prompt or terminal Used by the JVM and compiler to locate
to locate binary files for execution. class files and libraries for execution and
compilation.
Explanation:
The -cp or -classpath option is used to specify the classpath for the compiler or JVM. The
classpath tells Java where to look for classes and libraries required during compilation and
execution.
Do It Yourself
1. Create a simple Java program that uses an external JAR file. Compile and run it using
the classpath.
2. Set up the classpath for a project with multiple packages and demonstrate how to
compile and run the program.
Quiz
1. Which environment variable is used to specify the directories where Java
commands are located?
a) CLASSPATH
b) PATH
c) JAVA_HOME
d) JAVA_PATH
Answer: b) PATH
2. How do you specify additional directories or JAR files for Java classpath?
a) Use -d option.
b) Use -classpath or -cp option.
c) Set the CLASSPATH environment variable.
d) Use -path option.
Answer: b) Use -classpath or -cp option.
3. What happens if the required classes are not found in the classpath during
execution?
a) The program runs but without some features.
b) The JVM throws a ClassNotFoundException.
c) The compilation fails.
d) The program executes with default classes.
- Answer: b) The JVM throws a ClassNotFoundException.
4. What is the effect of setting the CLASSPATH environment variable?
a) It specifies the locations of Java compiler executable.
b) It tells the JVM where to find classes and libraries.
c) It sets the location of Java source files.
d) It defines the location of Java documentation.
Answer: b) It tells the JVM where to find classes and libraries.
5. How do you include multiple JAR files in the classpath?
a) Use a comma to separate the JAR files.
b) Use a semicolon (Windows) or colon (Linux/Mac) to separate the JAR files.
c) List them on separate lines.
d) Use a pipe character to separate the JAR files.
Answer: b) Use a semicolon (Windows) or colon (Linux/Mac) to separate the JAR files.
5.
Access Control
In Java, packages are used not only to group related classes and interfaces but also to control
access to these elements. Access control determines the visibility and accessibility of classes,
methods, and other members within a package and from outside packages.
Access Modifiers in Java
Java provides four access modifiers to control the visibility of classes, methods, and fields:
1. public: The member is accessible from any other class in any package.
2. protected: The member is accessible within its own package and by subclasses (even
if they are in different packages).
3. default (no modifier): The member is accessible only within its own package.
4. private: The member is accessible only within the class it is defined in.
Access Control within a Package
- Public Classes: Can be accessed from any other class in any package.
- Protected Members: Accessible within the same package and by subclasses in other
packages.
- Default (Package-Private) Members: Accessible only within the same package.
- Private Members: Accessible only within the same class.
Examples of Access Control in Packages
1. Public Access
// File: com/example/PublicClass.java
package com.example;
public class PublicClass {
public void display() {
System.out.println("Public method in PublicClass.");
}
}
// File: com/example/AnotherClass.java
package com.example;
public class AnotherClass {
public static void main(String[] args) {
PublicClass obj = new PublicClass();
obj.display(); // Accessible because PublicClass is public
}
}
2. Protected Access
// File: com/example/BaseClass.java
package com.example;
public class BaseClass {
protected void show() {
System.out.println("Protected method in BaseClass.");
}
}
// File: com/example/DerivedClass.java
package com.example;
public class DerivedClass extends BaseClass {
public void display() {
show(); // Accessible because show() is protected and DerivedClass is a
subclass
}
}
3. Default Access
// File: com/example/DefaultClass.java
package com.example;
class DefaultClass {
void print() {
System.out.println("Default method in DefaultClass.");
}
}
// File: com/example/AnotherClass.java
package com.example;
public class AnotherClass {
public static void main(String[] args) {
DefaultClass obj = new DefaultClass();
obj.print(); // Accessible because DefaultClass and AnotherClass are in the
same package
}
}
4. Private Access
// File: com/example/PrivateClass.java
package com.example;
public class PrivateClass {
private void secret() {
System.out.println("Private method in PrivateClass.");
}
public void accessSecret() {
secret(); // Accessible because it's within the same class
}
}
// File: com/example/AnotherClass.java
package com.example;
public class AnotherClass {
public static void main(String[] args) {
PrivateClass obj = new PrivateClass();
obj.accessSecret(); // Accessible because accessSecret() is public
// obj.secret(); // Not accessible because secret() is private
}
}
Summary
● Public members are accessible from any other class.
● Protected members are accessible within the same package and by subclasses.
● Default (Package-Private) members are accessible only within the same package.
● Private members are accessible only within the same class.
Do It Yourself
1. Create a class with all access modifiers and demonstrate their usage in a separate class
within the same package.
2. Write a program with a class that has private and protected members, and access
them from a subclass in a different package.
Quiz
1. Which access modifier allows access to a class member from any other class?
a) protected
b) default
c) public
d) private
Answer: c) public
2. What is the default access level for class members without an explicit modifier?
a) public
b) protected
c) default
d) private
Answer: c) default
3. Which access modifier is the most restrictive?
a) default
b) protected
c) public
d) private
Answer: d) private
4. Can a protected member of a class be accessed outside its package?
a) Yes, by any class.
b) No, it can only be accessed by subclasses.
c) Yes, but only by classes within the same package.
d) No, it can only be accessed within the same package.
Answer: b) No, it can only be accessed by subclasses.
5. What is the result of accessing a private member from a different class in the
same package?
a) The member can be accessed.
b) The member cannot be accessed and a compile-time error occurs.
c) The member is accessible if it is inherited.
d) The member can be accessed using reflection.
Answer: b) The member cannot be accessed and a compile-time error occurs.
6. Packages in Java SE
Packages in Java SE
Overview
In Java SE (Standard Edition), packages are used to group related classes, interfaces, and sub-
packages into a single unit. This helps in organizing the code, avoiding naming conflicts, and
providing access protection. Java SE includes a number of built-in packages such as
java.lang, java.util, and java.io, which contain commonly used classes and interfaces.
Common Packages:
- java.lang: Contains fundamental classes like String, Math, and Object.
- java.util: Contains utility classes like ArrayList, HashMap, and Date.
- java.io: Provides classes for input and output operations.
- java.net: Contains classes for networking operations.
Syntax
To use a package in Java, you need to:
1. Declare a package: Use the package keyword at the top of your Java file.
package com.example.myapp;
2. Import a package: Use the import keyword to bring classes or entire packages into
visibility.
import java.util.List; // Imports a specific class
import java.util.*; // Imports all classes in the package
Built-in Packages in Java SE
1. java.lang: This package is automatically imported and contains fundamental classes
such as String, Math, Object, Thread, and more.
String str = "Hello";
int length = str.length();
2. java.util: Contains utility classes such as collections framework classes (ArrayList,
HashMap), date and time utilities, and more.
import java.util.ArrayList;
ArrayList<String> list = new ArrayList<>();
list.add("One");
list.add("Two");
3. java.io: Provides classes for input and output operations, including file handling,
serialization, and stream handling.
import java.io.File;
File file = new File("example.txt");
4. java.net: Contains classes for networking, including sockets, URLs, and network
interfaces.
import java.net.URL;
URL url = new URL("http://www.example.com");
5. java.sql: Provides classes for database access and SQL operations.
import java.sql.Connection;
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"user", "password");
Examples
Example 1: Using java.util Package
import java.util.ArrayList;
public class ListExample {
public static void main(String[] args) {
ArrayList<String> fruits = new ArrayList<>();
fruits.add("Apple");
fruits.add("Banana");
fruits.add("Cherry");
System.out.println(fruits);
}
}
Example 2: Using java.io Package
import java.io.File;
import java.io.IOException;
public class FileExample {
public static void main(String[] args) {
File file = new File("example.txt");
try {
if (file.createNewFile()) {
System.out.println("File created: " + file.getName());
} else {
System.out.println("File already exists.");
}
} catch (IOException e) {
System.out.println("An error occurred.");
e.printStackTrace();
}
}
}
Example 3: Creating and Using a Custom Package
File: com/example/util/MathUtil.java
package com.example.util;
public class MathUtil {
public static int square(int number) {
return number * number;
}
}
File: Main.java
import com.example.util.MathUtil;
public class Main {
public static void main(String[] args) {
int result = MathUtil.square(5);
System.out.println("Square of 5 is: " + result);
}
}
Example 4: Using Fully Qualified Names
public class FullyQualifiedExample {
public static void main(String[] args) {
java.util.Date today = new java.util.Date();
System.out.println("Today's date: " + today);
}
}
Do It Yourself
1. List some commonly used packages in Java SE.
2. Explain the purpose of the java.util package.
3. Write a program using classes from java.net to create a simple socket connection.
4. Describe the java.lang package and its importance in Java.
Quiz
1. Which package is automatically imported in every Java program?
A) java.util
B) java.lang
C) java.io
D) java.net
Answer: B) java.lang
2. Which of the following statements correctly imports all classes from the
java.util package?
A) import java.util.*;
B) import java.util;
C) import java.util.All;
D) import * from java.util;
Answer: A) import java.util.*;
3. Which package provides classes for working with collections like ArrayList and
HashMap?
a) java.io
b) java.util
c) java.lang
d) java.net
Answer: b) java.util
4. Which package contains the String class?
- a) java.io
- b) java.util
- c) java.lang
- d) java.net
- Answer: c) java.lang
Answer: C) .java source files
5. Which command is used to compile Java files with packages?
A) javac -cp
B) javac -classpath
C) javac -d
D) javac -dir
Answer: C) javac -d
7. Java.lang Package and its Classes
Java.lang Package and its Classes
Definition:
The java.lang package is automatically imported by all Java programs. It contains
fundamental classes that are essential for Java programming.
Key Classes:
- Object: The root class of the Java class hierarchy.
- String: Represents a sequence of characters.
- Math: Provides mathematical functions and constants.
- System: Provides access to system-related features.
Syntax and Examples:
Key Classes in java.lang
1. Object: The root class of the Java class hierarchy. Every class in Java implicitly
extends Object. It provides basic methods such as equals(), hashCode(),
toString(), and getClass().
public class Example {
public static void main(String[] args) {
Object obj = new Object();
System.out.println(obj.toString()); // Prints the object's string
representation
}
}
2. String: Represents a sequence of characters. It is immutable and provides methods
for string manipulation such as length(), substring(), toLowerCase(),
toUpperCase(), and concat().
public class StringExample {
public static void main(String[] args) {
String str = "Hello, World!";
System.out.println(str.length()); // Prints the length of the string
System.out.println(str.toUpperCase()); // Converts the string to uppercase
}
}
3. Math: Contains mathematical functions and constants. It includes methods for basic
arithmetic, trigonometric functions, logarithms, and constants such as PI and E.
public class MathExample {
public static void main(String[] args) {
double squareRoot = Math.sqrt(16); // Calculates the square root
double power = Math.pow(2, 3); // Calculates 2 raised to the power of 3
System.out.println("Square root: " + squareRoot);
System.out.println("Power: " + power);
}
}
4. System: Provides access to system-level operations and properties. It includes methods
for standard input/output, environment variables, and system properties. Key methods
include System.out.println(), System.currentTimeMillis(), and
System.getenv().
public class SystemExample {
public static void main(String[] args) {
long startTime = System.currentTimeMillis(); // Gets the current time in
milliseconds
System.out.println("Current time: " + startTime);
}
}
Do It Yourself
1. Write a program using String methods to manipulate and display a string.
2. Use the Math class to perform various mathematical operations and display results.
Quiz
1. Which class is the root of the Java class hierarchy?
a) String
b) Object
c) Math
d) System
Answer: b) Object
2. Which method of the String class converts all characters to uppercase?
a) toLowerCase()
b) toUpperCase()
c) trim()
d) substring()
Answer: b) toUpperCase()
3. What does the Math.sqrt() method do?
a) Calculates the square of a number.
b) Calculates the square root of a number.
c) Calculates the cube root of a number.
d) Calculates the exponential of a number.
Answer: b) Calculates the square root of a number.
4. Which class provides access to system-related features like standard input and
output?
a) Math
b) String
c) System
d) Object
Answer: c) System
5. Which method of the Object class is used to get the class type of an object?
a) getClass()
b) getType()
c) className()
d) getObject()
Answer: a) getClass()
8. Class Object
Class Object
Definition:
In Java, the Object class is the superclass of all classes. Every class implicitly inherits from
Object. It provides fundamental methods that are common to all objects.
Key Methods:
- toString(): Returns a string representation of the object.
- equals(Object obj): Compares the current object with the specified object for
equality.
- hashCode(): Returns a hash code value for the object.
- getClass(): Returns the runtime class of the object.
Syntax and Examples:
- toString() Method:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public String toString() {
return "Person{name='" + name + "'}";
}
public static void main(String[] args) {
Person p = new Person("John");
System.out.println(p.toString());
}
}
- equals() Method:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null || getClass() != obj.getClass()) return false;
Person person = (Person) obj;
return name.equals(person.name);
}
public static void main(String[] args) {
Person p1 = new Person("John");
Person p2 = new Person("John");
System.out.println(p1.equals(p2)); // true
}
}
Explanation:
- toString() provides a string representation of the object.
- equals() is used to compare objects for equality.
- hashCode() provides a unique identifier for the object.
- getClass() gives the runtime class of the object.
Do It Yourself
1. Override the toString() method in a custom class and print its object.
2. Implement the equals() method in a class and test equality of objects.
Quiz
1. Which method of the Object class returns a string representation of the object?
a) getClass()
b) toString()
c) equals()
d) hashCode()
Answer: b) toString()
2. What is the result of comparing two objects using the equals() method?
a) It compares object references.
b) It compares the memory addresses of objects.
c) It checks if the two objects are logically equivalent.
d) It always returns true.
Answer: c) It checks if the two objects are logically equivalent.
3. Which method should be overridden when overriding the equals() method?
a) hashCode()
b) toString()
c) getClass()
d) clone()
Answer: a) hashCode()
4. What does the getClass() method return?
a) The name of the class as a string.
b) The runtime class of the object.
c) The superclass of the object.
d) The memory address of the object.
Answer: b) The runtime class of the object.
5. Which of the following methods is used to get a unique identifier for an object?
a) toString()
b) getClass()
c) equals()
d) hashCode()
Answer: d) hashCode()
9. Enumeration
Enumeration in Java
Enumeration (enum) is a special data type in Java that enables a variable to be a set of
predefined constants. It is useful when you have a fixed set of related values, such as days of
the week, directions (NORTH, SOUTH, EAST, WEST), or status flags (READY, BUSY,
WAITING).
The enum keyword was introduced in Java 5 and is part of the java.lang package. Enums in
Java are more powerful than in other programming languages because they can have
constructors, methods, and instance variables.
1. Syntax of enum in Java
The basic syntax for defining an enum in Java is as follows:
enum EnumName {
CONSTANT1, CONSTANT2, CONSTANT3;
}
- EnumName: The name of the enum.
- CONSTANT1, CONSTANT2, CONSTANT3: The constants that represent the values of
the enum.
2. Example of Enum
Let's define an enum to represent the days of the week.
enum Day {
SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY;
}
public class EnumExample {
public static void main(String[] args) {
Day today = Day.SUNDAY;
System.out.println("Today is: " + today);
}
}
Output:
Today is: SUNDAY
In this example, we defined an enum Day and assigned a value SUNDAY to the variable today.
3. Enum with Constructors and Methods
In Java, enums can have constructors and methods just like a class. This makes Java enums
powerful because each enum constant can be associated with data and have behavior.
Let's create an enum to represent the different levels of a severity rating (LOW, MEDIUM,
HIGH), each with a priority level.
enum Severity {
LOW(1), MEDIUM(2), HIGH(3);
private int priorityLevel;
// Constructor
Severity(int priorityLevel) {
this.priorityLevel = priorityLevel;
}
// Method to get the priority level
public int getPriorityLevel() {
return priorityLevel;
}
}
public class EnumWithConstructorExample {
public static void main(String[] args) {
Severity severity = Severity.HIGH;
System.out.println("Severity level: " + severity + " with priority " +
severity.getPriorityLevel());
}
}
Output:
Severity level: HIGH with priority 3
In this example:
- We created an enum Severity with three levels: LOW, MEDIUM, and HIGH.
- Each level has an associated priority value.
- The enum has a constructor that assigns a priority value to each constant, and a method
getPriorityLevel() to access that value.
4. Enum Methods
Java provides several built-in methods to work with enums:
- values(): Returns an array of all enum constants.
- valueOf(String name): Returns the enum constant with the specified name.
- ordinal(): Returns the ordinal position of the enum constant (0-based index).
enum Season {
WINTER, SPRING, SUMMER, FALL;
}
public class EnumMethodsExample {
public static void main(String[] args) {
// Using values() method
for (Season s : Season.values()) {
System.out.println(s);
}
// Using valueOf() method
Season currentSeason = Season.valueOf("SUMMER");
System.out.println("Current season is: " + currentSeason);
// Using ordinal() method
System.out.println("Ordinal of SUMMER is: " + currentSeason.ordinal());
}
}
Output:
WINTER
SPRING
SUMMER
FALL
Current season is: SUMMER
Ordinal of SUMMER is: 2
5. Enum in Switch Case Statements
Enums are commonly used in switch statements, making it easier to handle multiple constant
values.
enum TrafficSignal {
RED, YELLOW, GREEN;
}
public class EnumSwitchExample {
public static void main(String[] args) {
TrafficSignal signal = TrafficSignal.GREEN;
switch (signal) {
case RED:
System.out.println("Stop!");
break;
case YELLOW:
System.out.println("Get Ready!");
break;
case GREEN:
System.out.println("Go!");
break;
}
}
}
Output:
Go!
In this example, the TrafficSignal enum is used inside a switch statement to control the
flow based on the current signal.
6. Enum Constants with Fields and Methods
Enums in Java can contain fields and methods just like a regular class. This allows each enum
constant to have its own values or behavior.
enum Planet {
MERCURY(3.303e+23, 2.4397e6),
VENUS(4.869e+24, 6.0518e6),
EARTH(5.976e+24, 6.37814e6),
MARS(6.421e+23, 3.3972e6);
private final double mass; // in kilograms
private final double radius; // in meters
// Constructor
Planet(double mass, double radius) {
this.mass = mass;
this.radius = radius;
}
public double getMass() {
return mass;
}
public double getRadius() {
return radius;
}
}
public class EnumWithFieldsExample {
public static void main(String[] args) {
for (Planet p : Planet.values()) {
System.out.println(p + ": mass = " + p.getMass() + ", radius = " +
p.getRadius());
}
}
}
Output:
MERCURY: mass = 3.303E23, radius = 2439700.0
VENUS: mass = 4.869E24, radius = 6051800.0
EARTH: mass = 5.976E24, radius = 6378140.0
MARS: mass = 6.421E23, radius = 3397200.0
In this example, each planet has its own mass and radius. These values are assigned when the
enum constants are declared.
Do It Yourself
1. Create an enum for the days of the week and demonstrate its usage in a switch
statement.
2. Write a program to list all values of an enum using the values() method.
3. Write a program that defines an enum for the days of the week and prints whether the
day is a weekday or a weekend.
4. Create an enum for the four cardinal directions (NORTH, SOUTH, EAST, WEST) and
write a program that prints the opposite direction of a given direction.
5. Write a program that defines an enum for the planets in the solar system, each with its
own gravity value, and computes the weight of an object on each planet.
Quiz
1. What is the purpose of an enum in Java?
a) To define constants.
b) To handle errors.
c) To perform arithmetic operations.
d) To handle user input.
Answer: a) To define constants.
2. Which method is used to get all constants of an enum type?
a) values()
b) getConstants()
c) list()
d) enumValues()
Answer: a) values()
3. Can enums in Java have methods?
a) Yes, enums can have methods.
b) No, enums cannot have methods.
c) Enums can only have static methods.
d) Enums can have methods only in Java 8 and above.
Answer: a) Yes, enums can have methods.
4. What will be the output of the following code snippet?
public enum Color {
RED, GREEN, BLUE;
}
public class TestColor {
public static void main(String[] args) {
System.out.println(Color.RED.ordinal());
}
}
a) 0
b) 1
c) RED
d) Color.RED
Answer: a) 0
5. Which statement is true about enums?
a) Enums are mutable.
b) Enums can extend other classes.
c) Enums are implicitly final.
d) Enums cannot have constructors.
Answer: c) Enums are implicitly final.
10. class Math
The java.lang.Math Class
The java.lang.Math class is a part of the java.lang package in Java and provides a
collection of static methods for performing basic mathematical operations like exponentiation,
logarithms, square roots, and trigonometric calculations. Since these methods are static, they
can be called without creating an instance of the Math class.
Key Features of Math Class
- All methods in the Math class are static, so you can directly invoke them without
creating an object.
- The class cannot be instantiated because it has a private constructor.
- The Math class includes constants for commonly used mathematical values like PI and
E.
Commonly Used Constants
- Math.PI: The value of pi (π), which is approximately 3.14159.
- Math.E: The base of natural logarithms (e), which is approximately 2.71828.
Commonly Used Methods in Math Class
Method Description
Math.abs(a) Returns the absolute value of a.
Math.max(a, b) Returns the greater of two values a and b.
Math.min(a, b) Returns the smaller of two values a and b.
Math.pow(a, b) Returns a raised to the power of b (a^b).
Math.sqrt(a) Returns the square root of a.
Math.log(a) Returns the natural logarithm (base e) of a.
Math.log10(a) Returns the base 10 logarithm of a.
Math.sin(a) Returns the sine of a, where a is in radians.
Math.cos(a) Returns the cosine of a, where a is in radians.
Math.tan(a) Returns the tangent of a, where a is in radians.
Math.random() Returns a random number between 0.0 and 1.0.
Math.ceil(a) Returns the smallest integer greater than or
equal to a.
Math.floor(a) Returns the largest integer less than or equal to
a.
Math.round(a) Rounds the floating-point value a to the nearest
integer.
Math.toRadians(a) Converts the value a from degrees to radians.
Method Description
Math.toDegrees(a) Converts the value a from radians to degrees.
Examples of Math Methods
Example 1: Using Math.abs(), Math.max(), and Math.min()
public class MathExample1 {
public static void main(String[] args) {
int x = -10;
int y = 5;
int z = 20;
System.out.println("Absolute value of x: " + Math.abs(x)); // 10
System.out.println("Maximum of y and z: " + Math.max(y, z)); // 20
System.out.println("Minimum of y and z: " + Math.min(y, z)); // 5
}
}
Output:
Absolute value of x: 10
Maximum of y and z: 20
Minimum of y and z: 5
Example 2: Using Math.pow() and Math.sqrt()
public class MathExample2 {
public static void main(String[] args) {
double base = 5;
double exponent = 2;
System.out.println(base + " raised to the power of " + exponent + " is: " +
Math.pow(base, exponent)); // 25.0
System.out.println("Square root of 25 is: " + Math.sqrt(25)); // 5.0
}
}
Output:
5.0 raised to the power of 2.0 is: 25.0
Square root of 25 is: 5.0
Example 3: Using Math.random()
public class MathExample3 {
public static void main(String[] args) {
double randomValue = Math.random(); // Generates a random number between 0.0
and 1.0
System.out.println("Random value: " + randomValue);
}
}
Output:
Random value: 0.635434634
Example 4: Using Trigonometric Functions
public class MathExample4 {
public static void main(String[] args) {
double angle = 45.0; // angle in degrees
double radians = Math.toRadians(angle); // Convert angle to radians
System.out.println("Sine of 45 degrees: " + Math.sin(radians));
System.out.println("Cosine of 45 degrees: " + Math.cos(radians));
System.out.println("Tangent of 45 degrees: " + Math.tan(radians));
}
}
Output:
Sine of 45 degrees: 0.7071067811865475
Cosine of 45 degrees: 0.7071067811865476
Tangent of 45 degrees: 0.9999999999999999
Explanation of Some Important Methods
- Math.abs(): The absolute value of a number is its distance from zero, without
considering the sign. For example, Math.abs(-10) returns 10.
- Math.pow(a, b): This method returns a raised to the power of b. For example,
Math.pow(2, 3) returns 8.0 (i.e., 2^3).
- Math.sqrt(a): This method returns the square root of the number a. For example,
Math.sqrt(25) returns 5.0.
- Math.random(): This method generates a random double value between 0.0 and
1.0. You can scale it to generate a random number in a specific range.
- Math.ceil() and Math.floor(): These methods are used to round a number up or
down to the nearest integer. For example, Math.ceil(5.3) returns 6.0, and
Math.floor(5.3) returns 5.0.
Do It Yourself
1. Write a program that calculates the hypotenuse of a right triangle using the
Math.sqrt() method.
2. Use Math.pow() to compute the result of different exponential calculations.
3. Write a program to calculate the maximum of three numbers using Math.max().
4. Create a program that generates 5 random integers between 1 and 100 using
Math.random().
5. Write a program that takes an angle in degrees from the user and calculates its sine,
cosine, and tangent using the Math.sin(), Math.cos(), and Math.tan() methods.
Quiz
1. Which method is used to calculate the square root of a number in Java?
a) Math.pow()
b) Math.sqrt()
c) Math.log()
d) Math.abs()
Answer: b) Math.sqrt()
2. What does the Math.pow() method do?
a) Computes the square root.
b) Computes the power of a number.
c) Computes the logarithm.
d) Computes the absolute value.
Answer: b) Computes the power of a number.
3. Which method would you use to find the smaller of two numbers?
a) Math.max()
b) Math.min()
c) Math.sqrt()
d) Math.abs()
Answer: b) Math.min()
4. How can you find the absolute value of a number using the Math class?
a) Math.abs()
b) Math.max()
c) Math.min()
d) Math.sqrt()
Answer: a) Math.abs()
5. What does the Math.max() method return?
a) The minimum of two values.
b) The maximum of two values.
c) The absolute difference between two values.
d) The average of two values.
Answer: b) The maximum of two values.
References
End of Session - 21