0% found this document useful (0 votes)
4 views16 pages

Java Unit 3

This document covers Java packages, classes, and collections, detailing how to define packages, use access specifiers, and implement various classes like StringTokenizer, BitSet, Date, Calendar, Random, and Scanner. It also discusses the Collections Framework, including interfaces and implementations, sorting methods, and the differences between Comparable and Comparator interfaces. Examples are provided to illustrate the usage of these concepts in Java programming.
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)
4 views16 pages

Java Unit 3

This document covers Java packages, classes, and collections, detailing how to define packages, use access specifiers, and implement various classes like StringTokenizer, BitSet, Date, Calendar, Random, and Scanner. It also discusses the Collections Framework, including interfaces and implementations, sorting methods, and the differences between Comparable and Comparator interfaces. Examples are provided to illustrate the usage of these concepts in Java programming.
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 UNIT – III

Packages- Defining a Package, CLASSPATH, Access Specifiers, importing packages


Classes - String Tokenizer, BitSet, Date, Calendar, Random, Formatter, Scanner.
Collections: Collections overview, Collection Interfaces, Collections Implementation Classes,
Sorting in Collections, Comparable and Comparator Interfaces.
Java Packages
A package in Java is used to group related classes, we use packages to avoid name
conflicts, and to write a better maintainable code. Packages are divided into two
categories:
 Built-in Packages (packages from the Java API)
 User-defined Packages (create your own packages)
 Built-in Packages
 The Java API is a library of prewritten classes, that are free to use, included
in the Java Development Environment.

 you can either import a single class (along with its methods and attributes),
or a whole package that contain all the classes that belong to the specified
package.

 To use a class or a package from the library, you need to use


the import keyword:

Syntax
import [Link]; // Import a single class
import [Link].*; // Import the whole package

Example
import [Link];

CLASSPATH:
tells the Java compiler and JVM where to find user-defined classes and
packages.
It can include:
 Current directory
 JAR files
 Other directories containing classes
Example
set CLASSPATH=.;C:\Java\lib
. represents the current directory.
Access Specifier:
In Java, access modifiers are essential tools that define how the members
of a class, like variables, methods, and even the class itself, can be accessed
from other parts of our program.
There are 4 types of access modifiers available in Java:

Private Access Modifier


The private access modifier is specified using the keyword private. The
methods or data members declared as private are accessible only within the
class in which they are declared.
Default Access Modifier
When no access modifier is specified for a class, method, or data member,
it is said to have the default access modifier by default. This means only
classes within the same package can access it.
Protected Access Modifier
The protected access modifier is specified using the keyword protected.
The methods or data members declared as protected are accessible within
the same package or subclasses in different packages.
Public Access Modifier
The public access modifier is specified using the keyword public. Public
members are accessible from everywhere in the program. There is no
restriction on the scope of public data members.

Comparison Table of Access Modifiers in Java


StringTokenizer Class
StringTokenizer class in Java is used to break a string into tokens based on
delimiters. A StringTokenizer object internally maintains a current position within
the string to be tokenized. Some operations advance this current position past the
characters processed.
 A token is returned by taking a substring of the string that was used to
create the StringTokenizer object.
 It provides the first step in the parsing process often called lexer or
scanner.
 It implements the Enumeration interface.
 To perform Java String Tokenization, we need to specify an input string
and a set of delimiters.
A delimiter is a character or set of characters that separate tokens in the
string.
Example:
import [Link];
public class Test1
{
public static void main(String[] args)
{
// Input string
String s = "welcome to java programming ";
// Create a StringTokenizer object
// with space as the delimiter
StringTokenizer t1 = new StringTokenizer(s, " ");

// Tokenize the string and print each token


while ([Link]())
{
[Link]([Link]());
}
}
}

Methods Of StringTokenizer Class


Below are some commonly used methods of StringTokenizer class along with a
combined code example demonstrating some of these methods.
Method Action Performed

Returns the total number of tokens


countTokens()
present.

Tests if tokens are present for the


hasMoreTokens()
StringTokenizer's string.

nextElement() Returns an Object rather than String.

Returns the same value as


hasMoreElements()
hasMoreToken.

Returns the next token from the given


nextToken()
StringTokenizer.

Example:
import [Link].*;
public class Test3
{

public static void main(String[] args)


{
// Creating a StringTokenizer
StringTokenizer t1 = new StringTokenizer("Welcome to java
programming");
// countTokens Method
int c = [Link]();
[Link](c);
}
}
BitSet class:

BitSet is a class defined in the [Link] package. It creates an array of bits


represented by boolean values.

Constructors:
 BitSet(): A no-argument constructor to create an empty BitSet object.
 BitSet(int no of_Bits): A one-constructor with an integer argument to
create an instance of the BitSet class with an initial size of the integer
argument representing the number of bits.

// Java program illustrating Bitset Class constructors.


import [Link].*;
public class GFG
{
public static void main(String[] args)
{
// Constructors of BitSet class
BitSet bs1 = new BitSet();
BitSet bs2 = new BitSet(6);

/* set is BitSet class method


explained in next articles */
[Link](0);
[Link](1);
[Link](2);
[Link](4);

// assign values to bs2


[Link](4);
[Link](6);
[Link](5);
[Link](1);
[Link](2);
[Link](3);

// Printing the 2 Bitsets


[Link]("bs1 : " + bs1);
[Link]("bs2 : " + bs2);
}
}
Date class:

The class Date represents a specific instant in time, with millisecond precision.
The Date class of [Link] package implements Serializable, Cloneable and
Comparable interface. It provides constructors and methods to deal with date and
time with java.

Constructors:
 Date() : Creates date object representing current date and time.
 Date(long milliseconds) : Creates a date object for the given milliseconds
since January 1, 1970, 00:00:00 GMT.
 Date(int year, int month, int date)
Methods:
 boolean after(Date date) : Tests if current date is after the given date.
 boolean before(Date date) : Tests if current date is before the given date.
 int compareTo(Date date) : Compares current date with given date.
 long getTime() : Returns the number of milliseconds since January 1,
1970, 00:00:00 GMT represented by this Date object.
 void setTime(long time) : Changes the current date and time to given time.

// Program to demonstrate methods of Date class


import [Link].*;

public class Main


{
public static void main(String[] args)
{
// Creating date
Date d1 = new Date(2000, 11, 21);
Date d2 = new Date(); // Current date
Date d3 = new Date(2010, 1, 3);

boolean a = [Link](d1);
[Link]("Date d3 comes after " +
"date d2: " + a);

boolean b = [Link](d2);
[Link]("Date d3 comes before "+
"date d2: " + b);

int c = [Link](d2);
[Link](c);
[Link]("Miliseconds from Jan 1 "+
"1970 to date d1 is " + [Link]());

[Link]("Before setting "+d2);


[Link](204587433443L);
[Link]("After setting "+d2);
}
}

Calendar Class

The Calendar class in Java represents and manipulates date and time using fields
such as YEAR, MONTH, DAY, and HOUR. It is an abstract class that extends
Object and implements Comparable, Serializable, and Cloneable, so it cannot be
instantiated using a constructor.
 Calendar objects are created using the static [Link]()
method.

Calendar Methods
METHOD DESCRIPTION

add(int field, int Adds or subtracts a specified amount of time from


amount) a calendar field.

int get(int field) Returns the value of a specific calendar field.

getMaximum(int Returns the maximum valid value for a calendar


field) field.

Returns the minimum valid value for a calendar


getMinimum(int field)
field.

Date getTime() Returns a Date object representing calendar time

Example:

import [Link].*;
public class GFG {
public static void main(String[] args) {
Calendar c = [Link]();

[Link]([Link], -15);
[Link](“15 days ago: “ + [Link]());

[Link]([Link], 4);
[Link](“4 months later: “ + [Link]());

[Link]([Link], 2);
[Link](“2 years later: “ + [Link]());
}
}

Random class

Random class is used to generate pseudo-random numbers in java. An instance


of this class is thread-safe. The instance of this class is however cryptographically
insecure. This class provides various method calls to generate different random
data types such as float, double, int.
Constructors:
 Random(): Creates a new random number generator
 Random(long seed): Creates a new random number generator using a
single long seed.

Methods:
 nextInt(), nextLong(), nextFloat(), nextBoolean(): Generate random
values of their respective types.
 nextInt(int bound): Returns a value from 0 (inclusive) to bound
(exclusive).
 nextDouble(): Generates a double between 0.0 and 1.0.
 nextBytes(byte[] bytes): Fills an array with random bytes.
 nextGaussian(): Returns a normally distributed

Example:

import [Link];
public class Test2
{
public static void main(String[] args)
{
Random r1 = new Random();
[Link]([Link](10));
[Link]([Link]());
[Link]([Link]());
}
}

Scanner class:

The Scanner class in Java is part of the [Link] package and is commonly used
to read input from various sources like the keyboard, files, or strings.

To Create a Scanner object to read input from the console (keyboard) like this:

Scanner t1 = new Scanner([Link]);

Methods

Method Description Example


nextInt() Reads an integer int age = [Link]();
nextDouble() Reads a double double price = [Link]();
nextLine() Reads a full line of text String name = [Link]();
Reads a single word (until
next() String word = [Link]();
space)
boolean flag =
nextBoolean() Reads a boolean
[Link]();

Example:

import [Link];
public class Test14
{

public static void main(String[] args)


{
Scanner p1 = new Scanner([Link]);
[Link]("enter product name:");
String name=[Link]();
[Link]("enter product price:");
double price=[Link]();
[Link]("enter no of products:");
int quantity=[Link]();
double cost=price*quantity;
[Link]("product name="+name);
}
}

Collections in Java

The Collections Framework in Java is a unified architecture for representing and


manipulating groups of objects. It provides:
Interfaces: Abstract data types (e.g., List, Set, Map)
Implementations: Concrete classes (e.g., ArrayList, HashSet)
Algorithms: Methods for sorting, searching, and manipulating data (in
Collections class)
Key features:
 Reduces programming effort (ready-to-use data structures)
 Increases performance (efficient algorithms)
 Provides interoperability between different types of collections
Package: All collection classes are in [Link].

Collection Interfaces

The core interfaces are:


Interface Description Common Implementations
Collection Root interface for all collections List, Set, Queue
Ordered collection, allows duplicates,
List ArrayList, LinkedList, Vector
indexed access
No duplicates, unordered (some have HashSet, LinkedHashSet,
Set
ordering) TreeSet
Queue FIFO data structure LinkedList, PriorityQueue
Deque Double-ended queue ArrayDeque, LinkedList
Key-value pairs (not part of Collection HashMap, LinkedHashMap,
Map
interface) TreeMap

ArrayList in Java

ArrayList in Java is a resizable array provided in the [Link] package. Unlike


normal arrays, its size can grow or shrink dynamically as elements are added or
removed.
 Elements can be accessed using their index, just like arrays.
 Duplicate elements are allowed.
 Elements are stored in the order they are inserted.
import [Link];
public class Main
{
public static void main (String[] args)
{

// Creating an ArrayList
ArrayList<Integer> a = new ArrayList<Integer>();

// Adding Element in ArrayList


[Link](1);
[Link](2);
[Link](3);

// Printing ArrayList
[Link](a);
}
}

Output
[1, 2, 3]

HashSet in Java

HashSet in Java implements the Set interface of the Collections Framework. It is


used to store the unique elements, and it doesn't maintain any specific order of
elements.
 HashSet does not allow duplicate elements.

import [Link].*;
class Test10
{
public static void main(String[] args)
{
// Instantiate an object of HashSet
HashSet<Integer> hs = new HashSet<>();

// Adding elements
[Link](1);
[Link](2);
[Link](1);

[Link]("HashSet Size: " + [Link]());


[Link]("Elements in HashSet: " + hs);
}
}

Output
HashSet Size: 2
Elements in HashSet: [1, 2]

Sorting in Collections:
In Java, sorting in collections is primarily done using the static sort() methods
provided by the [Link] utility class, which operate
on List implementations such as ArrayList and LinkedList.

There are two main approaches to sorting:


 Natural Ordering: Use the [Link](List list) method. This works
for elements that implement the Comparable interface, which defines their
default "natural" order (e.g., alphabetical for strings, numerical for
integers).
 Custom Ordering: Use the [Link](List list, Comparator
c) method. This allows you to specify a custom sorting logic using
a Comparator interface.

import [Link];
import [Link];
import [Link];
public class SortExample
{
public static void main(String[] args)
{
List<Integer> numbers = new ArrayList<>();
[Link](5);
[Link](2);
[Link](8);
[Link](1);

// Sort using natural ascending order


[Link](numbers); //
[Link]("Ascending order: " + numbers);
// Sort using reverse order with a Comparator
[Link](numbers, [Link]()); //
[Link]("Descending order: " + numbers);
}
}

Output

Ascending order: [1, 2, 5, 8]


Descending order: [8, 5, 2, 1]

Comparable and Comparator Interfaces


In Java, both Comparable and Comparator interfaces are used for sorting objects.
The main difference between Comparable and Comparator is:
 Comparable: It is used to define the natural ordering of the objects within
the class. Belongs to [Link] package.
 Comparator: It is used to define custom sorting logic [Link]
to [Link] package.

Difference Between Comparable and Comparator


The table below demonstrates the difference between comparable and comparator
in Java.
Features Comparable Comparator

It defines natural ordering It defines external or


Definition within the class. custom sorting logic.

Method compareTo() compare()

It is implemented in the It is implemented in a


Implementation class. separate class.

Sorting Criteria Natural order sorting Custom order sorting

It is used for a single It is used for multiple


Usage sorting order. sorting orders.
Example of Comparable

import [Link];
import [Link];

// Movie class implements Comparable interface to define default sorting


class Movie implements Comparable<Movie> {
private String name;
private double rating;
private int year;

public Movie(String name, double rating, int year) {


[Link] = name;
[Link] = rating;
[Link] = year;
}

// Implementation of the compareTo method for default sorting by year


public int compareTo(Movie m) {

// Sort movies in ascending order of year


return [Link] - [Link];
}

public String getName() {


return name;
}

public double getRating() {


return rating;
}

public int getYear() {


return year;
}
}

public class Geeks {


public static void main(String[] args) {

// Create a list of movies


ArrayList<Movie> l = new ArrayList<>();
[Link](new Movie("Star Wars", 8.7, 1977));
[Link](new Movie("Empire Strikes Back", 8.8, 1980));
[Link](new Movie("Return of the Jedi", 8.4, 1983));

// Sort movies using Comparable's compareTo method by year


[Link](l);

// Display the sorted list of movies


[Link]("Movies after sorting by year:");
for (Movie m : l) {
[Link]([Link]() + " " + [Link]() + " " +
[Link]());
}
}
}

Output:
Movies after sorting by year:
Star Wars 8.7 1977
Empire Strikes Back 8.8 1980
Return of the Jedi 8.4 1983

Example of Comparator
import [Link].*;

class Employee {
int age;
String name;

Employee(int age, String name) {


[Link] = age;
[Link] = name;
}

public String toString() {


return name + " (" + age + ")";
}
}

public class Main {


public static void main(String[] args) {
List<Employee> list = new ArrayList<>();
[Link](new Employee(25, "Charlie"));
[Link](new Employee(20, "David"));

[Link]((e1, e2) -> [Link] - [Link]);


[Link]("By Age: " + list);

// Custom sort by Name using [Link]()


[Link]([Link](e -> [Link]));
[Link]("By Name: " + list);
}
}

Output:

By Age: [David (20), Charlie (25)]


By Name: [Charlie (25), David (20)]

You might also like