JAVA.
UTIL PACKAGE
The java.util package is a standard package of Java SDK. It contains the
collections framework, legacy collection classes, event model, date and time
facilities, internationalization, and miscellaneous utility classes. This package is
very useful as it provides commonly used Collections like ArrayList, HashMap,
Set etc. Java.util provides StrinTokenizer classes for String operations and
similarly other utility classes for event model handlings, date and time
operations and lot more.
java.util package and its all classes can be imported using following syntax:
import java.util.*;
Here we've used * operator to import all classes from java.util package and now
any class can be used in the program. In case of specific class, for example
ArrayList, we can import a class using following syntax:
import java.util.ArrayList;
Why java.util Package is used in Java Programs
Java.util package classes contains utility classes like collections frameworks,
String operations utilities, Date and Time operations utilities. Following list
shows some of the categories of classes of java.util package.
Collections − ArrayList, HashMap, Dictionary are few of the classes of
large set of Collection classes availble in java.util package. These classes
provides commonly used operations on large data sets.
Date Time Operations − GregorianCalendar, Timezone are some of the
classes of utility classes availble in java.util package. These classes
provides commonly used operations on date and time.
String Manipulations − StringTokenizer is an important utility class
availble in java.util package. This class provides a lot of operations to
manipulate strings.
Enumerations − Enumeration class of java.util package provides
operations on set of values like iterations, comparison etc.
Exceptions − java.util package contains various commonly occuring
exceptions like ConcurrentModificationException,
InputMismatchException etc.
Scanner: The Java Scanner class is a simple text scanner which can
parse primitive types and strings using regular expressions.
Following are the important points about Scanner −
A Scanner breaks its input into tokens using a delimiter pattern,
which by default matches whitespace.A scanning operation may block
waiting for input.A Scanner is not safe for multithreaded use without
external synchronization.
java.util.Scanner class is a powerful tool for parsing and reading input in Java.
It's commonly used for reading user input from various sources such as
keyboard input, files, and strings.
Creating a Scanner
You can create a Scanner object to read input from different sources. The most
common use case is reading input from the console (keyboard):
Scanner scanner = new Scanner(System.in);
Here's a simple example that reads user input from the console:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Reading a string input
System.out.print("Enter your name: ");
String name = scanner.nextLine();
System.out.println("Hello, " + name + "!");
// Reading an integer input
System.out.print("Enter your age: ");
int age = scanner.nextInt();
System.out.println("You are " + age + " years old.");
// Close the scanner
scanner.close();
Reading Different Data Types
The Scanner class provides methods to read different types of data:
nextLine(): Reads a line of text.
next(): Reads a single word.
nextInt(): Reads an integer.
nextDouble(): Reads a double.
nextBoolean(): Reads a boolean.
Collection classes:
In Java, collection classes are part of the Java Collections Framework, which
provides a unified architecture for storing and manipulating groups of objects.
Collections are used to represent and work with groups of data as a single unit,
such as lists, sets, and maps.
Core Interfaces
The core interfaces of the Java Collections Framework are as follows:
1. Collection: The root interface that represents a group of objects.
2. List: An ordered collection (also known as a sequence) that allows
duplicate elements.
3. Set: A collection that does not allow duplicate elements.
4. Map: An object that maps keys to values; it does not allow duplicate
keys.
5. Queue: A collection used to hold multiple elements prior to processing.
List Implementations
1. ArrayList
o Implements the List interface.
o Provides a resizable array.
o Offers constant-time positional access.
o Example:
ArrayList<String> arrayList = new ArrayList<>();
arrayList.add("Apple");
arrayList.add("Banana");
arrayList.add("Cherry");
Set Implementations
1. HashSet
o Implements the Set interface.
o Uses a hash table for storage.
o Offers constant-time performance for basic operations.
o Does not maintain any order.
o Example:
HashSet<Integer> hashSet = new HashSet<>();
hashSet.add(10);
hashSet.add(20);
hashSet.add(30);
Map Implementations
1. HashMap
o Implements the Map interface.
o Uses a hash table for storage.
o Offers constant-time performance for basic operations.
o Does not maintain any order.
o Example:
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("One", 1);
hashMap.put("Two", 2);
hashMap.put("Three", 3);
AUTOBOXING
Autoboxing is a feature in Java that automatically converts primitive types into
their corresponding wrapper class objects and vice versa. This process
simplifies the code and enhances readability by reducing the need for explicit
conversions.
Primitive Types and Wrapper Classes
Java has eight primitive data types: byte, short, int, long, float, double, char, and
boolean. Each primitive type has a corresponding wrapper class in the java.lang
package:
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean
It happens when:
1. You assign a primitive value to a variable of the corresponding wrapper
class.
2. You pass a primitive value as a parameter to a method that expects an
object of the corresponding wrapper class.
For example:
java
int primitiveInt = 5;
Integer wrapperInt = primitiveInt; // Autoboxing from int to Integer
Unboxing
Unboxing is the reverse process of autoboxing, where an object of a wrapper
class is automatically converted to its corresponding primitive type. It happens
when:
1. You assign a variable of a wrapper class to a variable of the
corresponding primitive type.
2. You pass an object of a wrapper class as a parameter to a method that
expects a primitive type.
For example:
java
Integer wrapperInt = 10;
int primitiveInt = wrapperInt; // Unboxing from Integer to int
Example
Here's a complete example that demonstrates autoboxing and unboxing in Java:
java
import java.util.ArrayList;
public class AutoboxingExample {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>();
// Autoboxing: adding primitive int values to an ArrayList of Integer
list.add(10); // Autoboxes int to Integer
list.add(20); // Autoboxes int to Integer
// Unboxing: retrieving the Integer values from the ArrayList and assigning
them to int variables
int num1 = list.get(0); // Unboxes Integer to int
int num2 = list.get(1); // Unboxes Integer to int
System.out.println("Number 1: " + num1);
System.out.println("Number 2: " + num2);
}
Key Points
Autoboxing simplifies code by removing the need for explicit conversion
between primitive types and wrapper classes.
Unboxing allows wrapper class objects to be treated as their
corresponding primitive types.
Autoboxing and unboxing are automatically handled by the Java
compiler, making the code more concise and readable.
wrapper class in java
In Java, a wrapper class is a class that encapsulates a primitive data type in an
object. This allows primitive types to be used where objects are required, such
as in collections, and provides utility methods to perform operations on these
types.
Primitive Types and Their Wrapper Classes
Here are the eight primitive data types in Java and their corresponding wrapper
classes:
Primitive Type Wrapper Class
byte Byte
short Short
int Integer
long Long
float Float
double Double
char Character
boolean Boolean
Purpose of Wrapper Classes
1. Collections: Java's collection classes, like ArrayList and HashMap, can
only store objects. Wrapper classes allow primitive types to be stored in
collections.
2. Utility Methods: Wrapper classes provide utility methods to perform
operations on primitive types, such as converting strings to primitives and
vice versa.
3. Default Values: In some cases, it's necessary to represent a value as null.
Primitive types can't be null, but their wrapper classes can.
Example of Using Wrapper Classes
Here's a simple example to demonstrate the use of a wrapper class:
java
import java.util.ArrayList;
public class WrapperClassExample {
public static void main(String[] args) {
// Autoboxing: Converting primitive int to Integer
int primitiveInt = 42;
Integer wrapperInt = primitiveInt; // Autoboxing
// Unboxing: Converting Integer to primitive int
int unboxedInt = wrapperInt; // Unboxing
// Using wrapper classes in collections
ArrayList<Integer> list = new ArrayList<>();
list.add(wrapperInt); // Adding Integer to ArrayList
// Converting String to Integer
String numberStr = "123";
Integer number = Integer.valueOf(numberStr); // Static method of Integer
// Converting Integer to String
String numberStr2 = number.toString(); // Instance method of Integer
System.out.println("Wrapper Integer: " + wrapperInt);
System.out.println("Unboxed Integer: " + unboxedInt);
System.out.println("List contains: " + list.get(0));
System.out.println("String to Integer: " + number);
System.out.println("Integer to String: " + numberStr2);
Key Points
Autoboxing and Unboxing: Java automatically converts between
primitive types and their wrapper classes, which simplifies the code.
Utility Methods: Wrapper classes provide methods to perform common
operations, such as parsing strings and converting values.
Collections: Wrapper classes are necessary to store primitive values in
collections, as collections can only store objects.
Wrapper classes add flexibility and functionality to Java programming by
bridging the gap between primitive types and objects.
Java generics:
Java generics allow you to create classes, interfaces, and methods that operate
on types specified as parameters, providing stronger type checks at compile
time and reducing the risk of ClassCastException. Generics enhance code
reusability and flexibility by enabling you to use one implementation with
multiple types.
Here's a basic rundown:
Why Use Generics?
1. Type Safety: Ensures that you work with the correct type without explicit
casting.
2. Code Reusability: Allows you to write more general and reusable code.
3. Readability: Makes the code more readable and easier to understand.
Examples of Java Generics
Generic Class
A generic class uses a type parameter (usually indicated by T) that can be used
like a class or interface type.
public class Box<T> {
private T content;
public void setContent(T content) {
this.content = content;
public T getContent() {
return content;
}
}
public class Main {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setContent("Hello");
System.out.println(stringBox.getContent()); // Output: Hello
Box<Integer> intBox = new Box<>();
intBox.setContent(123);
System.out.println(intBox.getContent()); // Output: 123
public class Box<T>: Here, we define a generic class called Box. The <T>
syntax indicates that Box is a generic class and T is a placeholder for the type
that will be specified when an object of Box is created.
private T content;: This declares a private variable content of type T. Since T
is a placeholder, content can hold any type of object.
public void setContent(T content): This method allows us to set the value of
content. The parameter content is of type T.
public T getContent(): This method returns the value of content. The return
type is T.
public class Main: This is the main class containing the main method where
the execution starts.
public static void main(String[] args): This is the entry point of the Java
application.
Box<String> stringBox = new Box<>();: Here, we create an instance of Box
with the type String. The type T is now replaced with String, making stringBox
capable of holding String values.
stringBox.setContent("Hello");: We set the content of stringBox to "Hello".
System.out.println(stringBox.getContent());: We print the content of
stringBox, which outputs Hello.
Box<Integer> intBox = new Box<>();: Similarly, we create another instance
of Box, but this time with the type Integer. The type T is replaced with Integer,
making intBox capable of holding Integer values.
intBox.setContent(123);: We set the content of intBox to 123.
System.out.println(intBox.getContent());: We print the content of intBox,
which outputs 123.