Oops With Java Notes Unit 2
Oops With Java Notes Unit 2
What is Java?
Java is a high-level, general-purpose, object-oriented, and secure
programming language developed by James Gosling at Sun Microsystems,
Inc. in 1991. It is formally known as OAK. In 1995, Sun Microsystem changed
the name to Java. In 2009, Sun Microsystem takeover by Oracle Corporation.
Editions of Java
Each edition of Java has different capabilities. There are three editions of
Java:
Java Platform
Java Platform is a collection of programs. It helps to develop and run a
program written in the Java programming language. Java Platform includes
an execution engine, a compiler and set of libraries. Java is a platform-
independent language.
Features of Java
o Simple: Java is a simple language because its syntax is simple, clean,
and easy to understand. Complex and ambiguous concepts of C++ are
either eliminated or re-implemented in Java. For example, pointer and
operator overloading are not used in Java.
o Object-Oriented: In Java, everything is in the form of the object. It
means it has some data and behavior. A program must have at least
one class and object.
o Robust: Java makes an effort to check error at run time and compile
time. It uses a strong memory management system called garbage
collector. Exception handling and garbage collection features make it
strong.
o Secure: Java is a secure programming language because it has no
explicit pointer and programs runs in the virtual machine. Java contains
a security manager that defines the access of Java classes.
o Platform-Independent: Java provides a guarantee that code writes
once and run anywhere. This byte code is platform-independent and
can be run on any machine.
1. Primitive data types: The primitive data types include boolean, char,
byte, short, int, long, float and double.
2. Non-primitive data types: The non-primitive data types
include Classes, Interfaces, and Arrays.
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Example:
Literals in Java
In Java
, literal is a notation that represents a fixed value in the source code. In lexical analysis, literals
of a given type are generally known as tokens
. In this section, we will discuss the term literals in Java.
Literals
In Java, literals are the constant values that appear directly in the program.
It can be assigned directly to a variable. Java has various types of literals.
The following figure represents a literal.
1. Integer Literal
2. Character Literal
3. Boolean Literal
4. String Literal
Integer Literals
Integer literals are sequences of digits. There are three types of integer literals:
Decimal Integer: These are the set of numbers that consist of digits from 0 to 9. It may have a positive
(+) or negative (-) Note that between numbers commas and non-digit characters are not permitted. For
example, 5678, +657, -89, etc.
Binary Integer: Base 2, whose digits consists of the numbers 0 and 1 (you can create binary literals in
Java SE 7 and later). Prefix 0b represents the Binary system. For example, 0b11010.
Real Literals
The numbers that contain fractional parts are known as real literals. We can also represent real
literals in exponent form. For example, 879.90, 99E-3, etc.
Backslash Literals
Java supports some special backslash character literals known as backslash literals. They are
used in formatted output. For example:
Character Literals
String Literals
String literal is a sequence of characters that is enclosed between double quotes ("") marks. It
may be alphabet, numbers, special characters, blank space, etc. For example, "Jack", "12345",
"\n", etc.
The vales that contain decimal are floating literals. In Java, float and double primitive types fall
into floating-point literals. Keep in mind while dealing with floating-point literals.
Java Variables
A variable is a container which holds the value while the Java program is
executed. A variable is assigned with a data type.
There are two types of data types in Java: primitive and non-primitive.
Variable
A variable is the name of a reserved area allocated in memory. In other
words, it is a name of the memory location. It is a combination of "vary +
able" which means its value can be changed.
1. int data=50;//Here data is variable
Types of Variables
There are three types of variables in Java:
o local variable
o instance variable
o static variable
Local Variable
A variable declared inside the body of the method is called local variable.
You can use this variable only within that method and the other methods in
the class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is
called an instance variable. It is not declared as static.
Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects
into primitives automatically. The automatic conversion of primitive into an object is known as
autoboxing and vice-versa unboxing.
● Change the value in Method: Java supports only call by value. So, if we pass a
primitive value, it will not change the original value. But, if we convert the primitive
value in an object, it will change the original value.
● Serialization: We need to convert the objects into streams to perform the serialization. If
we have a primitive value, we can convert it in objects through the wrapper classes.
● Synchronization: Java synchronization works with objects in Multithreading.
● java.util package: The java.util package provides the utility classes to deal with objects.
● Collection Framework: Java collection framework works with objects only. All classes
of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet,
TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
The eight classes of the java.lang package are known as wrapper classes in Java. The list of eight
wrapper classes are given below:
Primitive Wrapper
Type class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Java Arrays
Normally, an array is a collection of similar type of elements which has contiguous memory
location.
Java array is an object which contains elements of a similar data type. Additionally, The
elements of an array are stored in a contiguous memory location. It is a data structure where we
store similar elements. We can store only a fixed set of elements in a Java array.
Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element
is stored on 1st index and so on.
Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to
use the sizeof operator.
In Java, array is an object of a dynamically generated class. Java array inherits the Object class,
and implements the Serializable as well as Cloneable interfaces. We can store primitive values or
objects in an array in Java. Like C/C++, we can also create single dimentional or
multidimentional arrays in Java.
Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.
Advantages
● Code Optimization: It makes the code optimized, we can retrieve or sort the data
efficiently.
● Random access: We can get any data located at an index position.
Disadvantages
● Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its
size at runtime. To solve this problem, collection framework is used in Java which grows
automatically.
1. arrayRefVar=new datatype[size];
Let's see the simple example of java array, where we are going to declare, instantiate, initialize
and traverse an array.
1. //Java Program to illustrate how to declare, instantiate, initialize
2. //and traverse the Java array.
3. class Testarray{
4. public static void main(String args[]){
5. int a[]=new int[5];//declaration and instantiation
6. a[0]=10;//initialization
7. a[1]=20;
8. a[2]=70;
9. a[3]=40; llo
10. a[4]=50;
11. //traversing array
12. for(int i=0;i<a.length;i++)//length is the property of array
13. System.out.println(a[i]);
14. }}
Output
10
20
70
40
50
OPERATORS
Programming in Computer Science requires some arithmetical or logical operations. In such
circumstances, we need operators to perform these tasks. Thus, an Operator is basically a symbol
or token, which performs arithmetical or logical operations and gives us meaningful result. The
values involved in the operation are called Operands.
● Arithmetical Operators
● Relational Operators
● Logical Operators
● ARITHMETICAL OPERATORS
● The operators which are applied to perform arithmetical calculations in a program, are
known as Arithmetical operators. Some basic calculations like addition, subtraction,
multiplication, division, modulus are often used during programming. One can apply
arithmetic operators like +, -, *, / and % respectively to carry out these calculations. For
example, A + B, A – B, A % B are all examples of arithmetical operator usage.
● Do you know what Arithmetical Expressions are? A + B is considered an Arithmetical
Expression. Basically, an Arithmetical expression may contain variables, constants and
arithmetical operators together to produce a meaningful result. A + B, A – B, A % B are
all examples of arithmetical expressions.
● Now what happens if we assign an arithmetical expression to a variable? For example,
what do we call X = A + B? Is it an arithmetical expression or is it something else? Well
this is called an Arithmetical Statement. If an arithmetical expression is assigned to a
variable then it is known as Arithmetical Statement. Syntax of Arithmetical Statement is
− X = A + B, Y = A % B etc.
● Now we need to know who to write expression in Java Program.
EXPRESSIONS IN JAVA
When you write a program in Java, it is necessary to represent the arithmetical expressions into
Java expressions. Given below are few examples of how to illustrate a mathematical expression
in JAVA.
● Mathematical Expression: abc
Java Expression: a * b * c
● Mathematical Expression: ab + bc + ca
Java Expression: a * b + b * c + c * a
● Mathematical Expression: a2 + b2
Java Expression: a * a + b * b
● Mathematical Expression: (1/3)ab + (2/5)ba
Java Expression: 1.0/3.0 * a * b + 2.0/5.0 * b * a
Now there exist three different types of Arithmetical Operators. They are −
● Unary Operator
● Binary Operator
● Ternary Operator
UNARY OPERATOR
An Arithmetical operator, which is applied with a single operand is known as Unary Operator.
Example: +, -, ++, --, etc. Details of each types of operators are given below.
This operator is applied before the operand. It is just applied as a pointer to a variable which
results in the same value of a variable. Example: If a = 10, then +a will result in 10. If a = -10,
then +a will result in -10.
a = 10;
a = ++a * 2;
Before the operation, value of a was 10. Then in the next arithmetical statement, ++a increases
a’s value by 1. So the new value of a is 11. Then the arithmetical operation a * 2 takes place,
after which value of a becomes 22.
a = 10;
a = --a * 2;
Before the operation, value of a was 10. Then in the next arithmetical statement, --a decreases a’s
value by 1. So the new value of a is 9. Then the arithmetical operation a * 2 takes place, after
which value of a becomes 18.
When increment or decrement operators are applied after the operant, it is known as postfix
operators. This operator works on the principle “CHANGE AFTER THE ACTION”. It means
the value of the variable changes after the operation takes place.
a = 10;
a = a++ * 2;
Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.
a = 10;
a = a-- * 2;
Before the operation, value of a was 10. Then the arithmetical operator a * 2 takes place, after
which value of a become 20. This value is then stored in a. Hence the new value of a becomes
20.
BINARY OPERATOR
An arithmetic operator which deals with two operands, is known as Binary Arithmetic Operator.
Example
Ternary Operators deal with three operands. It is also called conditional assignment statement
because the value assigned to a variable depends upon a logical expression.
Example: a = 10, b = 7;
Logical OPERATORS
Java uses logical operators AND (&&), OR (||) or NOT (!). These operators yield 1 or 0
depending upon the outcome of different expressions. The different types of logical operators
along with their format are as shown below −
Logical Symb
Syntax
Operators ol
(a > b) && (a >
AND &&
c)
(a == b) || (a ==
OR ||
c)
NOT ! !(a == b)
Precedence of logical operators is NOT (!), AND (&&) and OR (||) i.e., if a statement contains
all the three logical operators then NOT operator will perform first. Here are the details of each
logical operator.
Logical NOT operator is applied when you want to revert the outcome of an expression. It is a
unary operator because it uses a single operand.
Example
!(8 > 3) − False, because 8>3 is True, !(3 > 8) − True, because 3>8 is False.
Output
a is not equal to b
Logical OR (||)
This operator is used to combine two conditional expressions. It will result in true if either of two
conditions (expressions) is true otherwise false.
Example
(5 > 4) || (8 > 12) : True, because 5>4 is True, (5 < 4) || (8 > 12) : False, because both the
expressions are false.
Output
Max Element is 10
The AND operator results in true if both the expressions (comprising its operands) are true.
Example
(5 > 3) && (4 > 3) : True, because both the expressions are True, ( 5 > 3) && ( 3 > 5) : False,
because 3 > 5 is False.
Output
Max Element is 13
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
Decision-making statements evaluate the Boolean expression and control the program flow
depending upon the result of the condition provided. There are two types of decision-making
statements in Java, i.e., If statement and switch statement.
1) If Statement:
In Java, the "if" statement is used to evaluate a condition. The control of the program is diverted
depending upon the specific condition. The condition of the If statement gives a Boolean value,
either true or false. In Java, there are four types of if-statements given below
1. Simple if statement
2. if-else statement
3. if-else-if ladder
4. Nested if-statement
1) Simple if statement:
It is the most basic statement among all control flow statements in Java. It evaluates a Boolean
expression and enables the program to enter a block of code if the expression evaluates to true.
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
Consider the following example in which we have used the if statement in the java code.
Student.java
Student.java
2) if-else statement
The if-else statement is an extension to the if-statement, which uses another block of code, i.e.,
else block. The else block is executed if the condition of the if-block is evaluated as false.
Syntax:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
4. else{
5. statement 2; //executes when condition is false
6. }
Student.java
x + y is greater than 20
3) if-else-if ladder:
The if-else-if statement contains the if-statement followed by multiple else-if statements. In other
words, we can say that it is the chain of if-else statements that create a decision tree where the
program may enter in the block of code where the condition is true. We can also define an else
statement at the end of the chain.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. }
4. else if(condition 2) {
5. statement 2; //executes when condition 2 is true
6. }
7. else {
8. statement 2; //executes when all the conditions are false
9. }
Nested if-statement
In nested if-statements, the if statement can contain a if or if-else statement inside another if or
else-if statement.
Syntax of Nested if-statement is given below.
Switch Statement:
In Java, Switch statements are similar to if-else-if statements. The switch statement contains
multiple blocks of code called cases and a single case is executed based on the variable which is
being switched. The switch statement is easier to use instead of if-else-if statements. It also
enhances the readability of the program.
● The case variables can be int, short, byte, char, or enumeration. String type is also
supported since version 7 of Java
● Cases cannot be duplicate
● Default statement is executed when any of the case doesn't match the value of expression.
It is optional.
● Break statement terminates the switch block when the condition is satisfied.
It is optional, if not used, next case is executed.
● While using switch statements, we must notice that the case expression will be of the
same type as the variable. However, it will also be a constant value.
Student.java
Loop Statements
In programming, sometimes we need to execute the block of code repeatedly while some
condition evaluates to true. However, loop statements are used to execute the set of instructions
in a repeated order. The execution of the set of instructions depends upon a particular condition.
In Java, we have three types of loops that execute similarly. However, there are differences in
their syntax and condition checking time.
1. for loop
2. while loop
3. do-while loop
In Java, for loop is similar to C and C++. It enables us to initialize the loop variable, check the
condition, and increment/decrement in a single line of code. We use the for loop only when we
exactly know the number of times, we want to execute the block of code.
Output:
Java provides an enhanced for loop to traverse the data structures like array or collection. In the
for-each loop, we don't need to update the loop variable. The syntax to use the for-each loop in
java is given below.
The do-while loop checks the condition at the end of the loop after executing the loop
statements. When the number of iteration is not known and we have to execute the loop at least
once, we can use do-while loop.
It is also known as the exit-controlled loop since the condition is not checked in advance. The
syntax of the do-while loop is given below.
Jump Statements
Jump statements are used to transfer the control of the program to the specific statements. In
other words, jump statements transfer the execution control to the other part of the program.
There are two types of jump statements in Java, i.e., break and continue.
As the name suggests, the break statement is used to break the current flow of the program and
transfer the control to the next statement outside a loop or switch statement. However, it breaks
only the inner loop in the case of the nested loop.
The break statement cannot be used independently in the Java program, i.e., it can only be
written inside the loop or switch statement.
Consider the following example in which we have used the break statement with the for loop.
BreakExample.java
BreakExample.java
0
1
2
3
4
5
6
Unlike break statement, the continue statement doesn't break the loop, whereas, it skips the
specific part of the loop and jumps to the next iteration of the loop immediately.
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table,
car, etc. It can be physical or logical (tangible and intangible). The example of an intangible
object is the banking system.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
A class is a group of objects which have common properties. It is a template or blueprint from
which objects are created. It is a logical entity. It can't be physical.
A class in Java can contain:
● Fields
● Methods
● Constructors
● Blocks
● Nested class and interface
1. class <class_name>{
2. field;
3. method;
4. }
A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime when
an object or instance is created. That is why it is known as an instance variable.
Method in Java
In Java, a method is like a function which is used to expose the behavior of an object.
Advantage of Method
● Code Reusability
● Code Optimization
The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.
In this example, we have created a Student class which has two data members id and name. We
are creating the object of the Student class by new keyword and printing the object's value.
File: Student.java
Output:
0
null
1. By reference variable
2. By method
3. By constructor
4. 1) Object and Class Example: Initialization through reference
Initializing an object means storing data into the object. Let's see a simple example where
we are going to initialize the object through a reference variable.
5. class Student{
6. int id;
7. String name;
8. }
9. class TestStudent2{
10. public static void main(String args[]){
11. Student s1=new Student();
12. s1.id=101;
13. s1.name="Sonoo";
14. System.out.println(s1.id+" "+s1.name);//printing members with a white space
15. }
16. }
Output:
101 Sonoo
Class Modifiers in java
There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifiers in Java specifies the accessibility or scope of a field, method, constructor,
or class. We can change the access level of fields, constructors, methods, and class by applying
the access modifier on it.
1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot be
accessed from outside the package. If you do not specify any access level, it will be the
default.
3. Protected: The access level of a protected modifier is within the package and outside the
package through child class. If you do not make the child class, it cannot be accessed
from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile,
transient, etc. Here, we are going to learn the access modifiers only.
1) Private
re is a compile-time error.
If you make any class constructor private, you cannot create the instance of that class from
outside the class. For example:
1. class A{
2. private A(){}//private constructor
3. void msg(){System.out.println("Hello java");}
4. }
5. public class Simple{
6. public static void main(String args[]){
7. A obj=new A();//Compile Time Error
8. }
9. }
2) Default
If you don't use any modifier, it is treated as default by default. The default modifier is
accessible only within package. It cannot be accessed from outside the package. It provides more
accessibility than private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
In this example, we have created two packages pack and mypack. We are accessing the A class
from outside its package, since A class is not public, so it cannot be accessed from outside the
package.
1. //save by A.java
2. package pack;
3. class A{
4. void msg(){System.out.println("Hello");}
5. }
1. //save by B.java
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. obj.msg();//Compile Time Error
8. }
9. }
Output:
nice fruits
1. A class is created, but its name is decided by the compiler, which extends the Person
class and provides the implementation of the eat() method.
2. An object of the Anonymous class is created that is referred to by 'p,' a reference variable
of Person type.
1. import java.io.PrintStream;
2. static class TestAnonymousInner$1 extends Person
3. {
4. TestAnonymousInner$1(){}
5. void eat()
6. {
7. System.out.println("nice fruits");
8. }
9. }
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only functionality to
the user.
Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.
Abstraction lets you focus on what the object does instead of how it does it.
A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
Points to Remember
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. The
relationship between the two classes is Programmer IS-A Employee. It means that Programmer is a type
of Employee.
1. class Employee{
2. float salary=40000;
3. }
4. class Programmer extends Employee{
5. int bonus=10000;
6. public static void main(String args[]){
7. Programmer p=new Programmer();
8. System.out.println("Programmer salary is:"+p.salary);
9. System.out.println("Bonus of Programmer is:"+p.bonus);
10. }
11. }
output
In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.
Single Inheritance Example
When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class TestInheritance{
8. public static void main(String args[]){
9. Dog d=new Dog();
10. d.bark();
11. d.eat();
12. }}
Output:
barking...
eating.
File: TestInheritance2.java
1. class Animal{
2. void eat(){System.out.println("eating...");}
3. }
4. class Dog extends Animal{
5. void bark(){System.out.println("barking...");}
6. }
7. class BabyDog extends Dog{
8. void weep(){System.out.println("weeping...");}
9. }
10. class TestInheritance2{
11. public static void main(String args[]){
12. BabyDog d=new BabyDog();
13. d.weep();
14. d.bark();
15. d.eat();
16. }}
Output:
weeping...
barking...
eating..
Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes. If
A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.
Since compile-time errors are better than runtime errors, Java renders compile-time error if you
inherit 2 classes. So whether you have same method or different, there will be compile time
error.
1. statement 1;
2. statement 2;
3. statement 3;
4. statement 4;
5. statement 5;//exception occurs
6. statement 6;
7. statement 7;
8. statement 8;
9. statement 9;
10. statement 10;
There are many differences between throw and throws keywords. A list of differences between
throw and throws are given below:
S
r.
Basis of Differences throw throws
n
o.
Java throws keyword is used
Java throw keyword is
in the method signature to
used throw an exception
declare an exception which
1. Definition explicitly in the code,
might be thrown by the
inside the function or the
function while the execution
block of code.
of the code.
Using throws keyword,
Type of exception Using
we can declare both
throw keyword, we can only
checked and unchecked
propagate unchecked
2. exceptions. However, the
exception i.e., the checked
throws keyword can be
exception cannot be
used to propagate checked
propagated using throw only.
exceptions only.
The throw keyword is The throws keyword is
3. Syntax followed by an instance of followed by class names of
Exception to be thrown. Exceptions to be thrown.
throw is used within the throws is used with the
4. Declaration
method. method signature.
We can declare multiple
We are allowed to throw exceptions using throws
only one exception at a keyword that can be thrown
5. Internal implementation
time i.e. we cannot throw by the method. For example,
multiple exceptions. main() throws IOException,
SQLException.
Output
Consider the example 1 in which InvalidAgeException class extends the Exception class.
Using the custom exception, we can have your own exception and message. Here, we have
passed a string to the constructor of superclass i.e. Exception class that can be obtained using
getMessage() method on the object we have created.
In this section, we will learn how custom exceptions are implemented and used in Java
programs.
Why use custom exceptions?
Java exceptions cover almost all the general type of exceptions that may occur in the
programming. However, we sometimes need to create custom exceptions.
In order to create custom exception, we need to extend Exception class that belongs to java.lang
package.
Collections in Java
1. Java Collection Framework
2. Hierarchy of Collection Framework
3. Collection interface
4. Iterator interface
Java Collections can achieve all the operations that you perform on a data
such as searching, sorting, insertion, manipulation, and deletion.
No Method Description
.
Iterator interface
Iterator interface provides the facility of iterating the elements in a forward direction only
There are only three methods in the Iterator interface. They are:
No Method Description
.
1 public boolean It returns true if the iterator has more elements otherwise
hasNext() returns false.
2 public Object next() It returns the element and moves the cursor pointer to th
next element.
3 public void remove() It removes the last elements returned by the iterator. It i
less used.
Iterable Interface
The Iterable interface is the root interface for all the collection classes. The
Collection interface extends the Iterable interface and therefore all the
subclasses of Collection interface also implement the Iterable interface.
It contains only one abstract method. i.e.,
1. Iterator<T> iterator()
List Interface
List interface is the child interface of Collection interface. It inhibits a list type
data structure in which we can store the ordered collection of objects. It can
have duplicate values.
ArrayList
The ArrayList class implements the List interface. It uses a dynamic array to
store the duplicate element of different data types. The ArrayList class
maintains the insertion order and is non-synchronized. The elements stored
in the ArrayList class can be randomly accessed. Consider the following
example.
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. }
LinkedList
LinkedList implements the Collection interface. It uses a doubly linked list
internally to store the elements. It can store the duplicate elements. It
maintains the insertion order and is not synchronized. In LinkedList, the
manipulation is fast because no shifting is required.
Consider the following example.
1. import java.util.*;
2. public class TestJavaCollection2{
3. public static void main(String args[]){
4. LinkedList<String> al=new LinkedList<String>();
5. al.add("Ravi");
6. al.add("Vijay");
7. al.add("Ravi");
8. al.add("Ajay");
9. Iterator<String> itr=al.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ravi
Vijay
Ravi
Ajay
Vector
Vector uses a dynamic array to store the data elements. It is similar to
ArrayList. However, It is synchronized and contains many methods that are
not the part of Collection framework.
1. import java.util.*;
2. public class TestJavaCollection3{
3. public static void main(String args[]){
4. Vector<String> v=new Vector<String>();
5. v.add("Ayush");
6. v.add("Amit");
7. v.add("Ashish");
8. v.add("Garima");
9. Iterator<String> itr=v.iterator();
10. while(itr.hasNext()){
11. System.out.println(itr.next());
12. }
13. }
14. }
Output:
Ayush
Amit
Ashish
Garima
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.
HashSet
HashSet class implements Set Interface. It represents the collection that uses
a hash table for storage. Hashing is used to store the elements in the
HashSet. It contains unique items.
Consider the following example.
1. import java.util.*;
2. public class TestJavaCollection7{
3. public static void main(String args[]){
4. //Creating HashSet and adding elements
5. HashSet<String> set=new HashSet<String>();
6. set.add("Ravi");
7. set.add("Vijay");
8. set.add("Ravi");
9. set.add("Ajay");
10. //Traversing elements
11. Iterator<String> itr=set.iterator();
12. while(itr.hasNext()){
13. System.out.println(itr.next());
14. }
15. }
16. }
Output:
Vijay
Ravi
Ajay
Java Enums
The Enum in Java is a data type which contains a fixed set of constants.
It can be used for days of the week (SUNDAY, MONDAY, TUESDAY,
WEDNESDAY, THURSDAY, FRIDAY, and SATURDAY) , directions (NORTH,
SOUTH, EAST, and WEST), season (SPRING, SUMMER, WINTER, and AUTUMN
or FALL), colors (RED, YELLOW, BLUE, GREEN, WHITE, and BLACK) etc.
According to the Java naming conventions, we should have all constants in
capital letters. So, we have enum constants in capital letters.
Java Enums can be thought of as classes which have a fixed set of constants
(a variable that does not change). The Java enum constants are static and
final implicitly. It is available since JDK 1.5.
Enums are used to create our own data type like classes. The enum data
type (also known as Enumerated Data Type) is used to define an enum in
Java. Unlike C/C++, enum in Java is more powerful. Here, we can define an
enum either inside the class or outside the class.
Java Enum internally inherits the Enum class, so it cannot inherit any other
class, but it can implement many interfaces. We can have fields,
constructors, methods, and main methods in Java enum.
Set in Java
The set interface is present in java.util package and extends the Collection
interface. It is an unordered collection of objects in which duplicate values cannot
be stored. It is an interface that implements the mathematical set. This interface
contains the methods inherited from the Collection interface and adds a feature
that restricts the insertion of the duplicate elements. There are two interfaces that
extend the set implementation namely SortedSet and NavigableSet.
In the above image, the navigable set extends the sorted set interface. Since a
set doesn’t retain the insertion order, the navigable set interface provides the
implementation to navigate through the Set. The class which implements the
navigable set is a TreeSet which is an implementation of a self-balancing tree.
Therefore, this interface provides us with a way to navigate through this tree.
public interface Set extends Collection
Creating Set Objects
Since Set is an interface, objects cannot be created of the typeset. We always
need a class that extends this list in order to create an object. And also, after the
introduction of Generics in Java 1.5, it is possible to restrict the type of object that
can be stored in the Set. This type-safe set can be defined as:
// Obj is the type of the object to be stored in Set
Set<Obj> set = new HashSet<Obj> ();
Java List
List in Java provides the facility to maintain the ordered collection. It
contains the index-based methods to insert, update, delete and search the
elements. It can have the duplicate elements also. We can also store the null
elements in the list.
The List interface is found in the java.util package and inherits the Collection
interface. It is a factory of ListIterator interface. Through the ListIterator, we
can iterate the list in forward and backward directions. The implementation
classes of List interface are ArrayList, LinkedList, Stack and Vector. The
ArrayList and LinkedList are widely used in Java programming. The Vector
class is deprecated since Java 5.
Geeks, the brainstormer should have been why and when to use Maps.
Maps are perfect to use for key-value association mapping such as dictionaries.
The maps are used to perform lookups by keys or when someone wants to
retrieve and update elements by keys. Some common scenarios are as follows:
● A map of error codes and their descriptions.
● A map of zip codes and cities.
● A map of managers and employees. Each manager (key) is associated with a
list of employees (value) he manages.
● A map of classes and students. Each class (key) is associated with a list of
students (value).
Iterators in Java
A Java Cursor is an Iterator, which is used to iterate or traverse or retrieve a
Collection or Stream object’s elements one by one. In this article, we will learn
about Java Iterators and it’s working.
Types of Cursors in Java
There are three cursors in Java as mentioned below:
1. Iterator
2. Enumeration
3. ListIterator
1. Iterator
Iterators in Java are used in the Collection framework to retrieve elements one by
one. It is a universal iterator as we can apply it to any Collection object. By using
Iterator, we can perform both read and remove operations. It is an improved
version of Enumeration with the additional functionality of removing an element.