Java Stack
The stack is a linear data structure that is used to store the collection of objects. It is based on Last-In-
First-Out (LIFO). Java collection framework provides many interfaces and classes to store the collection
of objects. One of them is the Stack class that provides different operations such as push, pop, search, etc.
The stack data structure has the two most important operations that are push and pop. The push operation
inserts an element into the stack and pop operation removes an element from the top of the stack.
The following table shows the different values of the top.
Java Stack Class
In Java, Stack is a class that falls under the Collection framework that extends the Vector class. It also
implements interfaces List, Collection, Iterable, Cloneable, Serializable. It represents the LIFO stack of
objects. Before using the Stack class, we must import the [Link] package. The stack class arranged in the
Collections framework hierarchy, as shown below.
Stack Class Constructor
The Stack class contains only the default constructor that creates an empty stack.
1. public Stack()
Creating a Stack
If we want to create a stack, first, import the [Link] package and create an object of the Stack
class.
1. Stack stk = new Stack();
Or
1. Stack<type> stk = new Stack<>();
Where type denotes the type of stack like Integer, String, etc.
Methods of the Stack Class
We can perform push, pop, peek and search operation on the stack. The Java Stack class
provides mainly five methods to perform these operations. Along with this, it also provides all
the methods of the Java Vector class.
Method Modifier and Method Description
Type
empty() boolean The method checks the stack is empty or not.
push(E item) E The method pushes (insert) an element onto the top of the stack.
pop() E The method removes an element from the top of the stack and returns the same
element as the value of that function.
peek() E The method looks at the top element of the stack without removing it.
search(Object int The method searches the specified object and returns the position of the object.
o)
Stack Class empty() Method
The empty() method of the Stack class check the stack is empty or not. If the stack is empty, it
returns true, else returns false. We can also use the isEmpty() method of the Vector class.
Syntax
1. public boolean empty()
Returns: The method returns true if the stack is empty, else returns false.
In the following example, we have created an instance of the Stack class. After that, we have
invoked the empty() method two times. The first time it returns true because we have not
pushed any element into the stack. After that, we have pushed elements into the stack. Again we
have invoked the empty() method that returns false because the stack is not empty.
[Link]
1. import [Link];
2. public class StackEmptyMethodExample
3. {
4. public static void main(String[] args)
5. {
6. //creating an instance of Stack class
7. Stack<Integer> stk= new Stack<>();
8. // checking stack is empty or not
9. boolean result = [Link]();
10. [Link]("Is the stack empty? " + result);
11. // pushing elements into stack
12. [Link](78);
13. [Link](113);
14. [Link](90);
15. [Link](120);
16. //prints elements of the stack
17. [Link]("Elements in Stack: " + stk);
18. result = [Link]();
19. [Link]("Is the stack empty? " + result);
20. }
21. }
Output:
Is the stack empty? true
Elements in Stack: [78, 113, 90, 120]
Is the stack empty? false
Stack Class push() Method
The method inserts an item onto the top of the stack. It works the same as the
method addElement(item) method of the Vector class. It passes a parameter item to be pushed
into the stack.
Syntax
1. public E push(E item)
Parameter: An item to be pushed onto the top of the stack.
Returns: The method returns the argument that we have passed as a parameter.
Stack Class pop() Method
The method removes an object at the top of the stack and returns the same object. It
throws EmptyStackException if the stack is empty.
Syntax
1. public E pop()
Returns: It returns an object that is at the top of the stack.
Let's implement the stack in a Java program and perform push and pop operations.
[Link]
1. import [Link].*;
2. public class StackPushPopExample
3. {
4. public static void main(String args[])
5. {
6. //creating an object of Stack class
7. Stack <Integer> stk = new Stack<>();
8. [Link]("stack: " + stk);
9. //pushing elements into the stack
10. pushelmnt(stk, 20);
11. pushelmnt(stk, 13);
12. pushelmnt(stk, 89);
13. pushelmnt(stk, 90);
14. pushelmnt(stk, 11);
15. pushelmnt(stk, 45);
16. pushelmnt(stk, 18);
17. //popping elements from the stack
18. popelmnt(stk);
19. popelmnt(stk);
20. //throws exception if the stack is empty
21. try
22. {
23. popelmnt(stk);
24. }
25. catch (EmptyStackException e)
26. {
27. [Link]("empty stack");
28. }
29. }
30. //performing push operation
31. static void pushelmnt(Stack stk, int x)
32. {
33. //invoking push() method
34. [Link](new Integer(x));
35. [Link]("push -> " + x);
36. //prints modified stack
37. [Link]("stack: " + stk);
38. }
39. //performing pop operation
40. static void popelmnt(Stack stk)
41. {
42. [Link]("pop -> ");
43. //invoking pop() method
44. Integer x = (Integer) [Link]();
45. [Link](x);
46. //prints modified stack
47. [Link]("stack: " + stk);
48. }
49. }
Output:
stack: []
push -> 20
stack: [20]
push -> 13
stack: [20, 13]
push -> 89
stack: [20, 13, 89]
push -> 90
stack: [20, 13, 89, 90]
push -> 11
stack: [20, 13, 89, 90, 11]
push -> 45
stack: [20, 13, 89, 90, 11, 45]
push -> 18
stack: [20, 13, 89, 90, 11, 45, 18]
pop -> 18
stack: [20, 13, 89, 90, 11, 45]
pop -> 45
stack: [20, 13, 89, 90, 11]
pop -> 11
stack: [20, 13, 89, 90]
Stack Class peek() Method
It looks at the element that is at the top in the stack. It also throws EmptyStackException if the
stack is empty.
Syntax
1. public E peek()
Returns: It returns the top elements of the stack.
Let's see an example of the peek() method.
[Link]
1. import [Link];
2. public class StackPeekMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. // pushing elements into Stack
8. [Link]("Apple");
9. [Link]("Grapes");
10. [Link]("Mango");
11. [Link]("Orange");
12. [Link]("Stack: " + stk);
13. // Access element from the top of the stack
14. String fruits = [Link]();
15. //prints stack
16. [Link]("Element at top: " + fruits);
17. }
18. }
Output:
Stack: [Apple, Grapes, Mango, Orange]
Element at the top of the stack: Orange
Stack Class search() Method
The method searches the object in the stack from the top. It parses a parameter that we want to
search for. It returns the 1-based location of the object in the stack. Thes topmost object of the
stack is considered at distance 1.
Suppose, o is an object in the stack that we want to search for. The method returns the distance
from the top of the stack of the occurrence nearest the top of the stack. It uses equals() method
to search an object in the stack.
Syntax
1. public int search(Object o)
Parameter: o is the desired object to be searched.
Returns: It returns the object location from the top of the stack. If it returns -1, it means that the
object is not on the stack.
Let's see an example of the search() method.
[Link]
1. import [Link];
2. public class StackSearchMethodExample
3. {
4. public static void main(String[] args)
5. {
6. Stack<String> stk= new Stack<>();
7. //pushing elements into Stack
8. [Link]("Mac Book");
9. [Link]("HP");
10. [Link]("DELL");
11. [Link]("Asus");
12. [Link]("Stack: " + stk);
13. // Search an element
14. int location = [Link]("HP");
15. [Link]("Location of Dell: " + location);
16. }
17. }
Java Stack Operations
Size of the Stack
We can also find the size of the stack using the size() method of the Vector class. It returns the
total number of elements (size of the stack) in the stack.
Syntax
1. public int size()
Let's see an example of the size() method of the Vector class.
[Link]
1. import [Link];
2. public class StackSizeExample
3. {
4. public static void main (String[] args)
5. {
6. Stack stk = new Stack();
7. [Link](22);
8. [Link](33);
9. [Link](44);
10. [Link](55);
11. [Link](66);
12. // Checks the Stack is empty or not
13. boolean rslt=[Link]();
14. [Link]("Is the stack empty or not? " +rslt);
15. // Find the size of the Stack
16. int x=[Link]();
17. [Link]("The stack size is: "+x);
18. }
19. }
Output:
Is the stack empty or not? false
The stack size is: 5
Iterate Elements
Iterate means to fetch the elements of the stack. We can fetch elements of the stack using three
different methods are as follows:
o Using iterator() Method
o Using forEach() Method
o Using listIterator() Method
Using the iterator() Method
It is the method of the Iterator interface. It returns an iterator over the elements in the stack.
Before using the iterator() method import the [Link] package.
Syntax
1. Iterator<T> iterator()
Let's perform an iteration over the stack.
[Link]
1. import [Link];
2. import [Link];
3. public class StackIterationExample1
4. {
5. public static void main (String[] args)
6. {
7. //creating an object of Stack class
8. Stack stk = new Stack();
9. //pushing elements into stack
10. [Link]("BMW");
11. [Link]("Audi");
12. [Link]("Ferrari");
13. [Link]("Bugatti");
14. [Link]("Jaguar");
15. //iteration over the stack
16. Iterator iterator = [Link]();
17. while([Link]())
18. {
19. Object values = [Link]();
20. [Link](values);
21. }
22. }
23. }
Output:
BMW
Audi
Ferrari
Bugatti
Jaguar
Using the forEach() Method
Java provides a forEach() method to iterate over the elements. The method is defined in
the Iterable and Stream interface.
Syntax
1. default void forEach(Consumer<super T>action)
Let's iterate over the stack using the forEach() method.
[Link]
1. import [Link].*;
2. public class StackIterationExample2
3. {
4. public static void main (String[] args)
5. {
6. //creating an instance of Stack class
7. Stack <Integer> stk = new Stack<>();
8. //pushing elements into stack
9. [Link](119);
10. [Link](203);
11. [Link](988);
12. [Link]("Iteration over the stack using forEach() Method:");
13. //invoking forEach() method for iteration over the stack
14. [Link](n ->
15. {
16. [Link](n);
17. });
18. }
19. }
Output:
Iteration over the stack using forEach() Method:
119
203
988
Using listIterator() Method
This method returns a list iterator over the elements in the mentioned list (in sequence), starting
at the specified position in the list. It iterates the stack from top to bottom.
Syntax
1. ListIterator listIterator(int index)
Parameter: The method parses a parameter named index.
Returns: This method returns a list iterator over the elements, in sequence.
Exception: It throws IndexOutOfBoundsException if the index is out of range.
Let's iterate over the stack using the listIterator() method.
[Link]
1. import [Link];
2. import [Link];
3. import [Link];
4.
5. public class StackIterationExample3
6. {
7. public static void main (String[] args)
8. {
9. Stack <Integer> stk = new Stack<>();
10. [Link](119);
11. [Link](203);
12. [Link](988);
13. ListIterator<Integer> ListIterator = [Link]([Link]());
14. [Link]("Iteration over the Stack from top to bottom:");
15. while ([Link]())
16. {
17. Integer avg = [Link]();
18. [Link](avg);
19. }
20. }
21. }
Output:
Iteration over the Stack from top to bottom:
988
203
119
Properties class in Java
The properties object contains key and value pair both as a string. The [Link] class
is the subclass of Hashtable.
It can be used to get property value based on the property key. The Properties class provides
methods to get data from the properties file and store data into the properties file. Moreover, it
can be used to get the properties of a system.
An Advantage of the properties file
Recompilation is not required if the information is changed from a properties file: If any
information is changed from the properties file, you don't need to recompile the java class. It is
used to store information which is to be changed frequently.
Constructors of Properties class
Method Description
Properties() It creates an empty property list with no default values.
Properties(Properties defaults) It creates an empty property list with the specified defaults.
Methods of Properties class
The commonly used methods of Properties class are given below.
Backward Skip 10sPlay VideoForward Skip 10s
Method Description
public void load(Reader r) It loads data from the Reader object.
public void load(InputStream is) It loads data from the InputStream object
public void loadFromXML(InputStream in) It is used to load all of the properties represented by the XML
document on the specified input stream into this properties table.
public String getProperty(String key) It returns value based on the key.
public String getProperty(String key, String It searches for the property with the specified key.
defaultValue)
public void setProperty(String key, String It calls the put method of Hashtable.
value)
public void list(PrintStream out) It is used to print the property list out to the specified output stream.
public void list(PrintWriter out)) It is used to print the property list out to the specified output stream.
public Enumeration<?> propertyNames()) It returns an enumeration of all the keys from the property list.
public Set<String> stringPropertyNames() It returns a set of keys in from property list where the key and its
corresponding value are strings.
public void store(Writer w, String comment) It writes the properties in the writer object.
public void store(OutputStream os, String It writes the properties in the OutputStream object.
comment)
public void storeToXML(OutputStream os, It writes the properties in the writer object for generating XML
String comment) document.
public void storeToXML(Writer w, String It writes the properties in the writer object for generating XML
comment, String encoding) document with the specified encoding.
Example of Properties class to get information from the properties file
To get information from the properties file, create the properties file first.
[Link]
1. user=system
2. password=oracle
Now, let's create the java class to read the data from the properties file.
[Link]
1. import [Link].*;
2. import [Link].*;
3. public class Test {
4. public static void main(String[] args) throws Exception{
5. FileReader reader=new FileReader("[Link]");
6.
7. Properties p=new Properties();
8. [Link](reader);
9.
10. [Link]([Link]("user"));
11. [Link]([Link]("password"));
12. }
13. }
Output:system
oracle
Now if you change the value of the properties file, you don't need to recompile the java class. That means no
maintenance problem.
Example of Properties class to get all the system properties
By [Link]() method we can get all the properties of the system. Let's create the
class that gets information from the system properties.
[Link]
1. import [Link].*;
2. import [Link].*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=[Link]();
7. Set set=[Link]();
8.
9. Iterator itr=[Link]();
10. while([Link]()){
11. [Link] entry=([Link])[Link]();
12. [Link]([Link]()+" = "+[Link]());
13. }
14.
15. }
16. }
Output:
[Link] = Java(TM) SE Runtime Environment
[Link] = C:\Program Files\Java\jdk1.7.0_01\jre\bin
[Link] = 21.1-b02
[Link] = Oracle Corporation
[Link] = [Link]
[Link] = ;
[Link] = Java HotSpot(TM) Client VM
[Link] = [Link]
[Link] = US
[Link] =
[Link] = SUN_STANDARD
...........
Example of Properties class to create the properties file
Now let's write the code to create the properties file.
[Link]
1. import [Link].*;
2. import [Link].*;
3. public class Test {
4. public static void main(String[] args)throws Exception{
5.
6. Properties p=new Properties();
7. [Link]("name","Sonoo Jaiswal");
8. [Link]("email","sonoojaiswal@[Link]");
9.
10. [Link](new FileWriter("[Link]"),"Javatpoint Properties Example");
11.
12. }
13. }
Let's see the generated properties file.
[Link]
1. #Javatpoint Properties Example
2. #Thu Oct 03 22:35:53 IST 2013
3. email=sonoojaiswal@[Link]
4. name=Sonoo Jaiswal
Local Variable Type Inference or LVTI in Java 10
What is type inference?
Type inference refers to the automatic detection of the datatype of a variable, done generally at
the compiler time.
What is Local Variable type inference?
Local variable type inference is a feature in Java 10 that allows the developer to skip the type
declaration associated with local variables (those defined inside method definitions, initialization
blocks, for-loops, and other blocks like if-else), and the type is inferred by the JDK. It will, then,
be the job of the compiler to figure out the datatype of the variable.
Why has this feature been introduced?
Till Java 9, to define a local variables of class type, the following was the only correct syntax:
Class_name variable_name=new Class_name(arguments);
For example:
// Sample Java local variable declaration
import [Link];
import [Link];
class A {
public static void main(String a[])
List<Map> data = new ArrayList<>();
Or
class A {
public static void main(String a[])
String s = " Hi there";
How to declare local variables using LVTI:
Instead of mentioning the variable datatype on the left-side, before the variable, LVTI
allows you to simply put the keyword ‘var’. For example,
// Java code for Normal local
// variable declaration
import [Link];
import [Link];
class A {
public static void main(String ap[])
List<Map> data = new ArrayList<>();
Can be re-written as:
// Java code for local variable
// declaration using LVTI
import [Link];
import [Link];
class A {
public static void main(String ap[])
var data = new ArrayList<>();
Use Cases
Here are the cases where you can declare variables using LVTI:
1. In a static/instance initialization block
// Declaration of variables in static/init
// block using LVTI in Java 10
class A {
static
var x = "Hi there";
[Link](x)'
public static void main(String[] ax)
Output:
Oh hi there
2. As a local variable
// Declaration of a local variable in java 10 using LVTI
class A {
public static void main(String a[])
var x = "Hi there";
[Link](x)
Output:
Hi there
3. As iteration variable in enhanced for-loop
// Declaring iteration variables in enhanced for loops using LVTI in Java
class A {
public static void main(String a[])
int[] arr = new int[3];
arr = { 1, 2, 3 };
for (var x : arr)
[Link](x + "\n");
Output:
1
2
3
4. As looping index in for-loop
// Declaring index variables in for loops using LVTI in Java
class A {
public static void main(String a[])
int[] arr = new int[3];
arr = { 1, 2, 3 };
for (var x = 0; x < 3; x++)
[Link](arr[x] + "\n");
Output:
1
2
3
5. As a return value from another method
// Storing the return value of a function in a variable declared with LVTI
class A {
int ret()
return 1;
}
public static void main(String a[])
var x = new A().ret();
[Link](x);
Output:
1
6. As a return value in a method
// Using a variable declared
//using the keyword 'var' as a return value of a function
class A {
int ret()
var x = 1;
return x;
public static void main(String a[])
[Link](new A().ret());
Output:
1
Error cases:
There are cases where declaration of local variables using the keyword ‘var’ produces an
error. They’re mentioned below:
1. Not permitted in class fields
// Sample java code to demonstrate
//that declaring class variables
//using 'var' is not permitted
class A {
var x; /* Error: class variables can't be declared
using 'var'. Datatype needs
to be explicitly mentioned*/
2. Not permitted for uninitialized local variables
// Sample java code to demonstrate
//that declaring uninitialized
//local variables using 'var' produces an error
class A {
public static void main(String a[])
var x; /* error: cannot use 'var'
on variable without initializer*/
3. Not allowed as parameter for any methods
// Java code to demonstrate that
// var can't be used in case of
//any method parameters
class A {
void show(var a) /*Error: can't use 'var'
on method parameters*/
4. Not permitted in method return type
// Java code to demonstrate
// that a method return type
// can't be 'var'
class A {
public var show() /* Error: Method return type
can't be var*/
return 1;
5. Not permitted with variable initialized with ‘NULL’
// Java code to demonstrate that local
variables initialized with 'Null'
can't be declared using 'var'*/
class A {
public static void main(String a[])
var x = NULL; // Error: variable initializer is 'null'
Note: All these pieces of code run only on Java 10.
Switch Expression
In Java, the switch statement has traditionally been used for control flow based on the value of an
expression. With the introduction of switch expressions, Java added more flexibility and
expressiveness to the switch construct.
Features:
Return Values: Unlike the traditional switch statement, a switch expression can return a
value.
Arrow Syntax: Introduces a more concise arrow syntax (->) to replace the traditional
case and break statements.
Exhaustiveness: Ensures that all possible cases are covered, often requiring a default
case.
Example:
int day = 2;
String dayType = switch (day) {
case 1, 2, 3, 4, 5 -> "Weekday";
case 6, 7 -> "Weekend";
default -> throw new IllegalArgumentException("Invalid day: " + day);
};
[Link](dayType); // Outputs: Weekday
Yield Keyword
The yield keyword is used within switch expressions to return a value from a case. It provides a
way to yield a result from a multi-statement block.
Example:
int month = 4;
int daysInMonth = switch (month) {
case 1, 3, 5, 7, 8, 10, 12 -> 31;
case 4, 6, 9, 11 -> 30;
case 2 -> {
int year = 2020;
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
yield 29; // Leap year
} else {
yield 28;
}
}
default -> throw new IllegalArgumentException("Invalid month: " +
month);
};
[Link](daysInMonth); // Outputs: 30
Text Blocks
Text blocks are a new feature in Java for working with multi-line strings. They simplify the
process of writing large blocks of text and eliminate the need for most escape sequences.
Features:
Ease of Use: No need for concatenation or escape characters.
Format Preservation: Preserves the format and indentation of the text.
Example:
String html = """
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
""";
[Link](html);
Record
Records are a special kind of class in Java introduced to represent immutable data carriers. They
automatically generate boilerplate code like constructors, equals(), hashCode(), and
toString() methods.
Features:
Conciseness: Reduces boilerplate code.
Immutability: Fields in records are final by default.
Example:
public record Point(int x, int y) {}
Point point = new Point(10, 20);
[Link](point.x()); // Outputs: 10
[Link](point.y()); // Outputs: 20
[Link](point); // Outputs: Point[x=10, y=20]
Sealed Class
Sealed classes and interfaces restrict which other classes or interfaces may extend or implement
them. This provides more control over the class hierarchy and allows the author to define a
closed set of subclasses.
Features:
Controlled Inheritance: Limits which classes can extend the sealed class.
Enhanced Pattern Matching: Works well with pattern matching to provide
exhaustiveness checking.
Example:
public abstract sealed class Shape permits Circle, Square, Rectangle {}
public final class Circle extends Shape {
// Implementation details
}
public final class Square extends Shape {
// Implementation details
}
public final class Rectangle extends Shape {
// Implementation details
}
In this example, only Circle, Square, and Rectangle can extend the Shape class, ensuring a
controlled and predictable class hierarchy.