java unit-4
java unit-4
The Collection in Java is a framework that provides architecture to store and manipulate the
group of objects.
Java Collections can achieve all the operations that you perform on a data such as searching,
sorting, insertion, manipulation, and deletion.
Java Collection framework provides many interfaces (Set, List, Queue, Deque) and classes
(ArrayList, Vector, LinkedList, PriorityQueue, HashSet, LinkedHashSet, TreeSet).
The Java Collections Framework is structured around key interfaces-Collection, List, Set,
Queue, and Map. Each tailored for specific data management tasks. Implementations like
ArrayList, HashSet, and HashMap offer practical solutions for working with these
collections, giving Java developers a versatile set of tools for efficient data handling.
o Class: A class is a blueprint from which individual objects are created. It encapsulates
data for objects through fields (attributes) and defines behavior via methods. Classes
support inheritance, allowing one class to inherit the properties and methods of
another, facilitating code reuse and polymorphism.
o Interface: An interface is a reference type in Java that can contain constants and
abstract methods (methods without a body). Interfaces specify what a class must do
but not how it does it, enforcing a set of methods that the class must implement.
Interfaces are used to achieve abstraction and multiple inheritance in Java.
Generics in Java
Generics means parameterized types. The idea is to allow a type (like Integer, String, etc.,
or user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics,
it is possible to create classes that work with different data types. An entity such as a class,
interface, or method that operates on a parameterized type is a generic entity.
Why Generics?
Generics provide a way to create reusable code components in Java, improving type safety
and readability.
Generic Method: Generic Java method takes a parameter and returns some value after
performing a task. It is exactly like a normal function, however, a generic method has type
parameters that are cited by actual type. This allows the generic method to be used in a
more general way. The compiler takes care of the type of safety which enables
programmers to code easily since they do not have to perform long, individual type
castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of
parameter, separated by a comma. The classes, which accept one or more parameters, ?are
known as parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects
of a generic class, we use the following syntax.
Note: In Parameter type we can not use primitives like ‘int’,’char’ or ‘double’.
this.obj1 = obj1;
this.obj2 = obj2;
System.out.println(obj1);
System.out.println(obj2);
}
}
class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj = new Test<String, Integer>("GfG", 15);
obj.print();
}
}
Output
GfG
15
JAVA ARRAYLIST
ArrayList in Java is a dynamic array implementation that belongs to the Java Collections
Framework. This is a big array that grows on its own as more elements are added to it.
ArrayLists come from the java.util package and are quite commonly used for their ease of use
and flexibility. They offer flexibility in that you do not need to determine the size of the
ArrayList at the time of its creation, which is similar to standard arrays in Java. So, it is much
more flexible than the traditional array. It is like the Vector in C++.
Syntax:
1. import java.util.*;
2. public class ArrayListExample1{
3. public static void main(String args[]){
4. ArrayList<string> list=new ArrayList<string>();//Creating arraylist
5. list.add("Mango");//Adding object in arraylist
6. list.add("Apple");
7. list.add("Banana");
8. list.add("Grapes");
9. //Printing the arraylist object
10. System.out.println(list);
11. }
12. }
Output:
EXAMPLE 2:
1. import java.util.*;
2. class TestJavaCollection1{
3. public static void main(String args[]){
4. ArrayList<String> list=new ArrayList<String>();//Creating arraylist
5. list.add("Ravi");//Adding object in arraylist
6. list.add("Vijay");
7. list.add("Ravi");
8. list.add("Ajay");
9. //Traversing list through Iterator
10. Iterator itr=list.iterator();
11. while(itr.hasNext()){
12. System.out.println(itr.next());
13. }
14. }
15. }
Output:
Ravi
Vijay
Ravi
Ajay
Java Vector
Vector is like the dynamic array which can grow or shrink its size. Unlike array, we can
store n-number of elements in it as there is no size limit. It is a part of Java Collection
framework since Java 1.2. It is found in the java.util package and implements
the List interface, so we can use all the methods of List interface here.
It is recommended to use the Vector class in the thread-safe implementation only. If you don't
need to use the thread-safe implementation, you should use the ArrayList, the ArrayList will
perform better in such case.
o Vector is synchronized.
o Java Vector contains many legacy methods that are not the part of a collections
framework.
o import java.util.*;
o public class TestJavaCollection3
o {
o public static void main(String args[])
o {
o Vector<String> v=new Vector<String>();
o v.add("Ayush");
o v.add("Amit");
o v.add("Ashish");
o v.add("Garima");
o Iterator<String> itr=v.iterator();
o while(itr.hasNext()){
o System.out.println(itr.next());
o }
o }
o }
Output:
Ayush
Amit
Ashish
Garima
EXAMPLE 2:
1. import java.util.*;
2. public class VectorExample1 {
3. public static void main(String args[]) {
4. //Create an empty vector with initial capacity 4
5. Vector<String> vec = new Vector<String>(4);
6. //Adding elements to a vector
7. vec.add("Tiger");
8. vec.add("Lion");
9. vec.add("Dog");
10. vec.add("Elephant");
11. //Check size and capacity
12. System.out.println("Size is: "+vec.size());
13. System.out.println("Default capacity is: "+vec.capacity());
14. //Display Vector elements
15. System.out.println("Vector element is: "+vec);
16. vec.addElement("Rat");
17. vec.addElement("Cat");
18. vec.addElement("Deer");
19. //Again check size and capacity after two insertions
20. System.out.println("Size after addition: "+vec.size());
21. System.out.println("Capacity after addition is: "+vec.capacity());
22. //Display Vector elements again
23. System.out.println("Elements are: "+vec);
24. //Checking if Tiger is present or not in this vector
25. if(vec.contains("Tiger"))
26. {
27. System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
28. }
29. else
30. {
31. System.out.println("Tiger is not present in the list.");
32. }
33. //Get the first element
34. System.out.println("The first animal of the vector is = "+vec.firstElement());
35. //Get the last element
36. System.out.println("The last animal of the vector is = "+vec.lastElement());
37. }
38. }
Test it Now
Output:
Size is: 4
Default capacity is: 4
Vector element is: [Tiger, Lion, Dog, Elephant]
Size after addition: 7
Capacity after addition is: 8
Elements are: [Tiger, Lion, Dog, Elephant, Rat, Cat, Deer]
Tiger is present at the index 0
The first animal of the vector is = Tiger
The last animal of the vector is = Deer
Stack
The stack is the subclass of Vector. It implements the last-in-first-out data structure, i.e.,
Stack. The stack contains all of the methods of Vector class and also provides its methods
like boolean push(), boolean peek(), boolean push(object o), which defines its properties.
Filename: TestJavaCollection4.java
1. import java.util.*;
2. public class TestJavaCollection4{
3. public static void main(String args[]){
4. Stack<String> stack = new Stack<String>();
5. stack.push("Ayush");
6. stack.push("Garvit");
7. stack.push("Amit");
8. stack.push("Ashish");
9. stack.push("Garima");
10. stack.pop();
11. Iterator<String> itr=stack.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Ayush
Garvit
Amit
Ashish
Hashtable in Java is a data structure in which each key is unique and is used to store key-
value pairs. It belongs to Java.util package, which implements Map interface in order to work
with the elements it includes. An important characteristic of a Hashtable is its capability of
providing rapid lookup and insertion operations.
Hash Table uses a hash function to determine an index into an array of buckets or slots,
where each bucket identifies a potential location where a key-value pair can be stored. When
we add an entry to the Hashtable, the hash code of the key is calculated, and the particular
bucket in which the entry will be stored is retrieved based on the hash code.
Hashtable is just like HashMap, but it is synchronized which, so it is thread-safe. This entails
that several threads can operate a Hashtable concurrently without causing data corruption
Points to Remember
o A Hashtable is an array of a list. Each list is known as a bucket. The position of the
bucket is identified by calling the hashcode() method. A Hashtable contains values
based on the key.
o Java Hashtable class contains unique elements.
o Java Hashtable class doesn't allow null key or value.
o Java Hashtable class is synchronized.
o The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75.
Hashtable Class Declaration
1. public class Hashtable<k ,v> extends Dictionary<k ,v> implements Map<k ,v>, Cloneable,
Serializable
Hashtable Class Parameters
Let's see the Parameters for java.util.Hashtable class.
import java.util.Hashtable;
hashtable.put("One", 1);
hashtable.put("Two", 2);
hashtable.put("Three", 3);
}
}Test it Now
Output
Hashtable Elements: {One=1, Three=3, Two=2}
Java Hashtable Example: remove()
Hashtable2.java
1. import java.util.*;
2. public class Hashtable2 {
3. public static void main(String args[]) {
4. Hashtable<integer ,string> map=new Hashtable<integer ,string>();
5. map.put(100,"Amit");
6. map.put(102,"Ravi");
7. map.put(101,"Vijay");
8. map.put(103,"Rahul");
9. System.out.println("Before remove: "+ map);
10. // Remove value for key 102
11. map.remove(102);
12. System.out.println("After remove: "+ map);
13. }
14. }
Output:
Important Features
Enumeration is Synchronized.
It does not support adding, removing, or replacing elements.
Elements of legacy Collections can be accessed in a forward direction using
Enumeration.
Legacy classes have methods to work with enumeration and returns Enumeration
objects.
Declaration
public interface Enumeration<E>
monthNames.add("January");
monthNames.add("February");
monthNames.add("March");
monthNames.add("April");
monthNames.add("May");
monthNames.add("June");
monthNames.add("July");
monthNames.add("August");
monthNames.add("September");
monthNames.add("October");
monthNames.add("November");
monthNames.add("December");
months = monthNames.elements();
while (months.hasMoreElements()) {
System.out.println(months.nextElement());
}
}
}
Output
January
February
March
April
May
June
July
August
September
October
November
December
Iterator in Java
In Java, an Iterator is one of the Java cursors. Java Iterator is an interface that is practiced
in order to iterate over a collection of Java object components entirety one by one.
o hasNext()
o next()
o remove()
o forEachRemaining()
1. import java.io.*;
2. import java.util.*;
3.
4. public class JavaIteratorExample {
5. public static void main(String[] args)
6. {
7. ArrayList<String> cityNames = new ArrayList<String>();
8.
9. cityNames.add("Delhi");
10. cityNames.add("Mumbai");
11. cityNames.add("Kolkata");
12. cityNames.add("Chandigarh");
13. cityNames.add("Noida");
14.
15. // Iterator to iterate the cityNames
16. Iterator iterator = cityNames.iterator();
17.
18. System.out.println("CityNames elements : ");
19.
20. while (iterator.hasNext())
21. System.out.print(iterator.next() + " ");
22.
23. System.out.println();
24. }
25. }
Output:
CityNames elements:
Delhi Mumbai Kolkata Chandigarh Noida
EXAMPLE:
1. import java.util.StringTokenizer;
2. public class Simple{
3. public static void main(String args[]){
4. StringTokenizer st = new StringTokenizer("my name is khan"," ");
5. while (st.hasMoreTokens()) {
6. System.out.println(st.nextToken());
7. }
8. }
9. }
Output:
my
name
is
khan
System.out.println(random.nextInt(10));
System.out.println(random.nextBoolean());
System.out.println(random.nextDouble());
System.out.println(random.nextFloat());
System.out.println(random.nextGaussian());
random.nextBytes(bytes);
System.out.printf("[");
System.out.printf("]\n");
System.out.println(random.nextLong());
System.out.println(random.nextInt());
random.setSeed(seed);
random.ints().count());
random.doubles().count());
random.longs().count());
*/
}
Output:
4
true
0.19674934340402916
0.7372021
1.4877581394085997
[-44 75 68 89 81 -72 -1 -66 -64 117 ]
158739962004803677
-1344764816
Input types:
Method Description
import java.util.Scanner;
// Driver Class
// main function
// String input
// Character input
// correctly obtained.
Input
Geek
F
40
9876543210
9.9
Output
Name: Geek
Gender: F
Age: 40
Mobile Number: 9876543210
CGPA: 9.9
import java.util.*;
Calendar c = Calendar.getInstance();
Output:
The Current Date is:Tue Aug 28 11:10:40 UTC 2018
import java.util.*;
Output:
Current Calendar's Year: 2018
Current Calendar's Day: 28
Current MINUTE: 10
Current SECOND: 45
FILES:
Character Stream
In Java, characters are stored using Unicode conventions . Character stream automatically
allows us to read/write data character by character. For example, FileReader and FileWriter
are character streams used to read from the source and write to the destination.
import java.io.*;
public class GFG
{
public static void main(String[] args)
throws IOException
{
// finally block that executes for sure where we are closing file connections
// to avoid memory leakage
finally {
Byte Stream
Byte streams process data byte by byte (8 bits). For example, FileInputStream is used to
read from the source and FileOutputStream to write to the destination.
import java.io.*;
Output:
Program successfully executed
Java IO : Input-output in Java with Examples
Java brings various Streams with its I/O package that helps the user to
perform all the input-output operations. These streams support all the types of
objects, data-types, characters, files etc to fully execute the I/O operations.
Before exploring various input and output streams lets look at 3 standard or
default streams that Java has to provide which are also most common in use:
System.in:
This is the standard input stream(System.in) that is used to read characters from the
keyboard or any other standard input device.
System.out
This is the standard output stream(System.out) that is used to produce the result of a
program on an output device like the computer screen. Here is a list of the various print
functions that we use to output statements:
– print(): This method in Java is used to display a text on the console. This text is passed as
the parameter to this method in the form of String. This method prints the text on the console
and the cursor remains at the end of the text at the console. The next printing takes place from
just here. Syntax:
System.out.print(parameter);
Java I/O Classes
1. Java provides a rich set of classes for performing I/O operations. Some of the key classes include:
2. InputStream and OutputStream: These abstract classes form the foundation for byte-oriented
I/O operations. They provide methods for reading and writing bytes from/to various sources and
destinations.
3. Reader and Writer: These abstract classes are used for character-based I/O operations. They
provide methods for reading and writing characters from/to character-based streams.
4. FileInputStream and FileOutputStream: These classes allow reading from and writing to files
in a byte-oriented manner.
5. FileReader and FileWriter: These classes enable reading from and writing to files using
character-oriented operations.
6. BufferedInputStream and BufferedOutputStream: These classes provide buffering
capabilities, which can significantly improve I/O performance by reducing the number of system
calls.
7. BufferedReader and BufferedWriter: These classes offer buffered reading and writing of
character data, enhancing I/O efficiency when working with character-based streams.
Java - RandomAccessFile
This class is used for reading and writing to random access file. A random access file behaves
like a large array of bytes. There is a cursor implied to the array called file pointer, by moving the
cursor we do the read write operations. If end-of-file is reached before the desired number of byte
has been read than EOFException is thrown. It is a type of IOException.
Method
Modi Method Method
fier
and
Type
Void close() It closes this random access file stream and releases any system resources associated with the stream.
FileChan
getChannel() It returns the unique FileChannel object associated with this file.
nel
Void seek(long pos) It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
It converts the double argument to a long using the doubleToLongBits method in class Double, and then writes that
Void writeDouble(double v)
long value to the file as an eight-byte quantity, high byte first.
It converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int
Void writeFloat(float v)
value to the file as a four-byte quantity, high byte first.
Void seek(long pos) It sets the file-pointer offset, measured from the beginning of this file, at which the next read or write occurs.
Example
1. import java.io.IOException;
2. import java.io.RandomAccessFile;
3.
4. public class RandomAccessFileExample {
5. static final String FILEPATH ="myFile.TXT";
6. public static void main(String[] args) {
7. try {
8. System.out.println(new String(readFromFile(FILEPATH, 0, 18)));
9. writeToFile(FILEPATH, "I love my country and my people", 31);
10. } catch (IOException e) {
11. e.printStackTrace();
12. }
13. }
14. private static byte[] readFromFile(String filePath, int position, int size)
15. throws IOException {
16. RandomAccessFile file = new RandomAccessFile(filePath, "r");
17. file.seek(position);
18. byte[] bytes = new byte[size];
19. file.read(bytes);
20. file.close();
21. return bytes;
22. }
23. private static void writeToFile(String filePath, String data, int position)
24. throws IOException {
25. RandomAccessFile file = new RandomAccessFile(filePath, "rw");
26. file.seek(position);
27. file.write(data.getBytes());
28. file.close();
29. }
30. }
The myFile.TXT contains text "This class is used for reading and writing to random access file."
File(File parent, String child): Creates a new File instance from a parent
abstract pathname and a child pathname string.
File(String pathname): Creates a new File instance by converting the given
pathname string into an abstract pathname.
File(String parent, String child): Creates a new File instance from a parent
pathname string and a child pathname string.
File(URI uri): Creates a new File instance by converting the given file: URI
into an abstract pathname.
Methods of File Class in Java
S. Return
No. Method Description Type
pathname.
abstract pathname.
setReadable(boolean
Sets the owner’s or everybody’s
27. readable, boolean boolean
read permission.
ownerOnly)
import java.io.File;
// Displaying file property
class fileProperty {
public static void main(String[] args)
{
// accept file name or directory name through command line args
String fname = args[0];
Output
File name :file.txt
Path: file.txt
Absolute path:C:\Users\akki\IdeaProjects\codewriting\src\file.txt
Parent:null
Exists :true
Is writable:true
Is readabletrue
Is a directory:false
File Size in bytes 20