Java Programming Concepts Explained
Java Programming Concepts Explained
(Core)
Program Execution flow :-
•Platform Independence: Java code can run on any platform with a compatible JVM.
•Portability: Java's platform independence and Write Once, Run Anywhere (WORA)
principle make it highly portable across different devices and platforms.
Rules :-
➢ The first rule of object orientation is the world is a collection of objects.
➢ Every object in this world belongs to a category or Type.
➢ Type is only known as Class in Java.
➢ Type is imaginary but objects are real.
➢ A Java program is a collection of objects and classes.
➢ Every object has two parts i.e.,
1. State/Properties or what an object has.
2. Behavior or what an object does(actions).
➢ In Java state/properties are handled using Data types.
➢ Behavior is handled using methods or functions.
➢ for any program to execute, the operating system (OS) should give control of execution (COE) to the programming
language
➢ public: It is an access specifier, which makes the main
method visible to the operating system.
➢ static: It is a keyword, where the operating system can
access the main method without creating an object.
➢ void: It is a return type, where the main method returns
nothing.
➢ main: It is the name of the method.
➢ String [] args: Are command line arguments. It is an array of
strings that can be used to pass the arguments to execute before
the main method.
Note: In Java, to store a long value, at the end of the value a suffix ‘L’ or ‘l’ is added.
Note: If the suffix ‘f’ is not present, by default Java will consider it as a double
value.
➢ Boolean data type does not have a specified size & it is dependent on JVM.
2) Explicit typecasting
➢ Conversion of a larger data type into a smaller data type.
➢ This conversion is not automatically performed by the Java compiler.
➢ Explicit typecasting must be done by the programmer explicitly.
➢ Explicit typecasting results in a loss of precision, where
some data is lost.
Wrapper classes
➢ Primitive data types are not treated as objects in java
➢ The wrapper class in Java is a class provides the mechanism to convert primitive data types into object and
object into primitive data type
•Types of variables:
1) Instance Variables
•➢ Instance variables are declared within a class but
outside of a method.
➢ Instant variables are a part of an object's state and
are created when an object is instantiated.
➢ Each instance of a class has its copy of instance
variables.
➢ Memory for instance variables is allocated in the
heap segment.
•Default values of primitive data
types:
1. Integers (byte, short, int, long) :
0
2. Real numbers (float, double): 0.0
3. Boolean: false
4. Character (char): empty
character
5. Objects (Arrays, Strings): null
1. Regular Array:
➢ An array, where all rows have the same number of columns, is also known as a rectangular array.
➢ [Link] will give the number of blocks in a 3-D array.
➢ a[i].length will give the number of rows in ith block of a 3-D array. (Variable “i” is used for the count of the number of
blocks)
➢ a[i][j].length will give the number of columns in a 3-D array.(Variable “i” is used for the count of the number of blocks)
•2. Jagged Array: An array of
arrays where each row has a
different number of columns
is also known as an irregular
or non-rectangular array.
STRINGS
➢ A string is a collection of a sequence of characters enclosed within double quotes “ ”.
➢ Strings are classified into two types.
String Tokenizer:
In Java, the String class has a split( ) method that can be used to tokenize a string into an array of substrings based on a
specified delimiter.
➢ The nextToken( ) method returns the next token and the hasMoreTokens( ) method returns true if there are more tokens.
•Built-In Methods in Strings:
➢ length( ) - Returns the length of the string.
➢ charAt(int index) - Returns the character at the specified index in the string.
➢ substring(int startIndex, int endIndex) - Returns a new string that is a substring of the original
string, starting from the startIndex and ending at endIndex- 1.
➢ indexOf(String str) - Returns the index of the first occurrence of the specified str in the original
string.
➢ lastIndexOf(String str) - Returns the index of the last occurrence of the specified str in the original
string.
➢ replace(char oldChar, char newChar) - Replaces all occurrences of oldChar with newChar in the
original string.
➢ replaceAll(String regex, String replacement) - Replaces all occurrences of the regular expression
regex with replacement in the original string.
➢ toLowerCase( ) - Returns a new string that is the lowercase version of the original string.
➢ toUpperCase( ) - Returns a new string that is the uppercase version of the original string.
➢ trim( ) - Returns a new string with all leading and trailing whitespace removed from the original
string.
➢ split(String regex) - Splits the original string into an array of strings based on the specified regular
expression regex.
➢ toCharArray( ) - Converts a string into an array of characters.
➢ contains(String) – Returns whether the string present in the main String.
➢ repeat(int count) - provides a concise way to create a new string by concatenating the original
string a specified number of times
Mutable Strings: Strings whose values can be changed.
➢ To create a mutable string in Java, there are two classes
1) String Buffer : The default capacity of StringBuffer is 16.
➢ append(String str) - Adds the specified string to the end of the current string.
➢ capacity( ) - Returns the current capacity of the buffer or builder, which is the amount of memory allocated for storing the
string.
➢ length( ) - Returns the length of the string.
➢ trimToSize( ) - Trims the buffer or builder to the current length of the string, freeing up any unused memory.
➢ Initially, the capacity was 16, but now the size will
automatically increase.
➢ To calculate the capacity of a String Buffer, there is a
formula.
METHOD OVERLOADING :-
Method overloading is a It is also called as Static
process of creating Binding OR Early
multiple methods with Binding OR Compile –
the same name inside a Time Polymorphism OR
class but with different Virtual Polymorphism.
parameters.
class MainOverload {
public static void main(String[] args) {
➢ Main method can also be overrided [Link]("Main method with String[] args");
main(10);
main("Hello", 20);
}
Output:- public static void main(int num) {
Main method with String[] args [Link]("Main method with int: " + num);
Main method with int: 10 }
Main method with String and int: Hello 20 public static void main(String str, int num) {
[Link]("Main method with String and int: " + str + " " + num);
}
}
ENCAPSULATION
➢ Encapsulation is a process of providing security & controlled access to the most important component of an object. i.e.,
data members of an object.
➢ Security can be provided by two steps.
1. Preventing direct access by declaring data members as private.
2. Providing controlled access by using public setters and public getters.
➢ Variables with private keyword can be accessible only within the same class and cannot be accessed outside the class.
➢ Setter is a public method that updates or sets the value of data members.
➢ Setter is also known as a mutator in Java
➢ Getter is a public method that reads or returns the value of data members.
➢ Getter is also known as accessor in Java.
Reason :- There is a name clash between instance variable and
Public void setData(int cId, String cName){
local variables as variable names are same.
cId = cId;
➢ This is known as the shadowing problem, that is a name
cName = cName;
clash that occurs inside a setter when the names of instance
}
and local variables are the same.
➢ To avoid the shadowing problem, we should attach the
Public void setData(int cId, String cName){ “this” keyword to the names of instance variables.
[Link] = cId;
[Link] = cName;
}
Constructors in Java:
➢ Constructor is a built-in setter or special method that is automatically called during object creation.
➢ Constructors do not have a return type (not even void).
Differences between a method and a constructor:
Method Constructor
This method name can be anything Should be same as class name
Must have return type No return type
Called after object creation Called during object creation
No default method is provided by java A default constructor is provided by java
compiler compiler
Methods can be overloaded and Can only be overloaded
overridden
Can be static Cannot be static
➢ Constructors are of two types.
1. Zero parameterized (No-argument) constructor: This constructor does not take any arguments and it is used to
initialize the default values for the objects.
2. Parameterized constructor: This constructor takes one or more arguments, and it is used to initialize the object with
specific values.
Constructor chaining: Constructor chaining can be achieved in two ways.
1. Within the same class (Local chaining).
2. Child class to parent class.
Local chaining:
➢ If a constructor calls another constructor within the same class,then it is known as local chaining.
➢ Local chaining can be achieved using this( ) method.
Child
class to
parent
class :-
STATIC : The static keyword in Java is a powerful tool that can be used to improve the efficiency and readability of code. A class
in Java consists of the following members,
Static members belong to a class and non-static members (Instance) belong to objects.
•Static Method:
➢ A static method in Java is a method that belongs to the class and not to the object.
➢ A static method can access only static data. It cannot call non-static data (instance
variables).
➢ A static method can call only other static methods and cannot call a non-static method
from it.
➢ A static method can be accessed directly by class name and does not need any object.
•Static Block:
➢ The static block in Java is a code segment within a class that runs just once when the class
is loaded into memory.
➢ Its primary purpose is to initialize static variables.
➢ The static block executes even before the main method begins its execution.
INHERITANCE
➢ Inheritance is the process of acquiring the properties and behaviour of a class by another class.
➢ Inheritance can be implemented using the “extends” keyword.
Advantages of Inheritance: Rules
➢ Code reusability. ➢ Private members do not participate in inheritance
➢ Reduce development time and effort. ➢ Multilevel (Hierarchical Inheritance) Inheritance is
➢ Increases profitability. permitted in Java
Types (Supported by java) ➢ Multiple Inheritance is not permitted in Java as it leads to
➢ Single diamond shaped problem which results in ambiguity.
➢ Multilevel ➢ Constructors do not participate in inheritance.
➢ Hierarchical ➢ Cyclic Inheritance is not permitted.
➢ Hybrid (Single + Hierarchical OR Multilevel + Hierarchical)
Note :- If a class explicitly doesnot extend any other class then it is implicitly extending Object class
Types of methods :-
➢ Inherited Methods
➢ Specialized methods
➢ Overridden methods Note:- Use @Override annotation before overriding method in childclass
Rules of overriding
➢ The overridden method of child class must either maintain the same access modifier as the parent class method or
provide greater access; however, it can never be reduced.
➢ The overridden method of child class must maintain the same return types as the parent class method.
➢ In the overridden method of child class, the return types can be different, provided the relationship between the return types
is ‘is-a’ relationship. Such return types between which “is-a” relationship exists are called as covariant return types.
Polymorphism
Polymorphism is derived from two Greek words: poly and morphs. The word ‘poly’ means many and ‘morphs’ means forms.
Creating parent-type references to child objects is called loose
coupling, through which we have achieved polymorphism.
There is one limitation of parent type reference to child type.
That is using parent type reference we cannot directly access
the specialized methods of child class
In order to access the specialised methods of a child class
using a parent type reference, it is necessary to downcast the
reference to the child type.
Advantages of Polymorphism:
1. Code reusability
2. flexibility
3. Reduction in complexity
This is second method of polymorphism
Method overriding is also called as dynamic binding,
late binding
Naming , dynamic method dispatch
conventions
•Packages: lowercase (e.g., [Link]).
•Classes and Interfaces: CamelCase, starting with an uppercase letter
(e.g., MyClass, MyInterface).
•Methods: camelCase, starting with a lowercase letter
(e.g., calculateArea()).
•Variables: camelCase, starting with a lowercase letter
(e.g., userName, totalCount).
•Constants: uppercase with underscores separating words
(e.g., MAX_VALUE, DEFAULT_NAME).
Final Keyword
The final keyword in Java is used to restrict the user.
1. Variable (Cannot be changed)
2. Method (Cannot be overriden)
3. Class (Cannot be extended)
Aggregation and Composition:
➢ Aggregation is “has-a” relationship between two objects where one object contains a reference to another object, but the
two objects can exist independently.
➢ Composition is a “part-of” relationship where one object is composed of one or more other objects, and the component
objects cannot exist independently without the parent object.
➢ Aggregation is a loose bound has-a relationship.
➢ Composition is a tight bound has-a relationship.
➢ Charger can exist without a phone and therefore it is aggregation. (loosely bound)
➢ An OS cannot exist without a phone and therefore it is composition. (tightly bound)
ABSTRACTION
➢ Abstraction in Java is a mechanism for hiding implementation details and exposing only the necessary information to the
user.
➢ Abstract classes cannot be instantiated and can only be used as a base class for other classes.
➢ The abstract keyword is a non-access modifier.
➢ It is only used for classes and methods.
Abstract class: It’s a restricted class, that cannot be used to create objects (to access, it must be inherited from another class).
Abstract method: It's a method with just a signature, no body. If a class has even one abstract method, you need to mark the
whole class as abstract.
An abstract class can have both abstract and regular methods.
Abstract methods can only exist in abstract classes only
➢ An abstract class can contain both abstract methods as well as concrete methods.
➢ A normal class can inherit from an abstract class.
➢ An abstract class can inherit from another abstract class.
➢ An abstract class can inherit from a normal class.
➢ If a class contains even a single abstract method, then the class should be declared as abstract.
➢ Abstract class objects cannot be created/instantiated. If you want to create it then it must be inherited from another class.
➢ Abstract and final keywords cannot be used together.
➢ Abstract cannot go with variables
INTERFACE
An interface is a collection of pure abstract methods; inside an interface, you have only Rules of interface
Rule 1: An interface is like a contract which when implemented helps to achieve standardization.
Rule 2: Interfaces promote polymorphism. An interface type reference can point to implementing class objects. This achieves
loose coupling, code reduction and code flexibility.
Rule 3: Methods within an interface are automatically public, abstract.
Rule 4: Specialized methods cannot be accessed directly using interface type reference.
Rule 5: If a class partially implements interface, it must declare itself as abstract.
Rule 6: A class can implement multiple interfaces because diamond shape problem does not exist as interfaces will not have
parents.
Rule 7: An interface cannot implement another interface, because interface cannot provide methods with bodies inside it.
Rule 8: An interface can extend another interface. Not only this it can inherit from multiple interfaces because the diamond
shape problem does not exist.
Rule 9: A class can both extend another class as well as implement an interface. However, order should be extend first and
implemented later.
Rule 10: An interface can contain constant variables and method signatures. A variable within an interface is automatically
public static final.
Rule 11: An empty interface in Java is referred to as a Marker interface or Tagged interface. It is used to provide special
properties to the object of the class.
➢ To use concrete methods in interfaces we need to use default(Not an access specifier) keyword before concreate methods. It
is used to achieve backward competability
➢ We use static methods in interfaces , to use them before implementation
➢ We can use private methods in interface for creating concrete methods
Functional Interfaces
➢ To specify an interface as functional interface we need to use “@functionalInterface” annotation
➢ To provide security we use a nested class and to access the functional interface and it can be done in four ways
i) Normal class
ii) Nested class
iii) Anonymus class EX :- Runnable is an example of functional interface.
iv) Lambda expressions
Note :- If a class is inside main method it can be used normally if it is outside main method we need to use it after making it
static only otherwise it will throw an error.
➢ Whenever there are multiple methods, if within a method an exception object gets
generated, it is handled by the run-time system,
➢ And the run-time system checks if there is any try-catch block to handle the
exception. If it is not there, then the exception object does not directly go to the default
exception handler, instead, it gets propagated below the stack.
➢ If none of the methods handle the exception, then it reaches the default exception
handler, and abrupt termination happens.
➢ Once an exception is caught it does not gets propagate down to the caller methods
and normal termination of the program happens.
Different Ways to Handle Exception.
1) Handling the Exception(try-catch)
2) Re-throwing the Exception(try-catch-throw-throws-finally)
3) Ducking the Exception(throws)
Case-2: Re-throwing the Exception (try-catch-throw-throws-finally)
➢ If an exception occurs within a method and is also handled in the same method, but the same exception object must also
propagate to the caller of the method, then it is referred to as re-throwing the exception.
➢ Throw keyword is used to explicitly throw an exception from a method or anyblock of code.
➢ The disadvantage of the throw keyword is that statements below the throw keyword do not execute. This can be overcome
by placing the statements within the finally block.
Case-3: Ducking the Exception(throws)
➢ If an exception occurs within a method and the method does not want to handle it, instead it wants to hand over the
responsibility of handling the exception to the caller of the method, it is referred to as ducking an exception.
➢ To achieve this, the throws keyword is used.
Custom Exception
1. Create a class.
2. Make that class extend from the built-in Exception or RuntimeException class.
3. Override the getMessage() method.
Note :-
PrintStackTrace():- This method in the exception class provide detailed information about where an exception is included
It includes the name of the exception and where it is generated.
getMessage() :- This method in the exception class retrives the desriptive message associated with the exception
Ex:-
Main(){ Note :- A generic catch block can never be placed on top of specific catch
try{ blocks. It would result an error.
int arr[] = new int[Integer.MAX_VALUE];
}
catch(Error e){
[Link](“Error handled”);
}
}
•Exceptions are further subdivided into two types
1. Checked Exceptions (compile-time)
2. Unchecked Exceptions (run-time)
• Checked Exception:
•➢ Checked Exceptions, also referred to as compiler-known exceptions.
➢ These are identified by the compiler during the compilation process.
➢ The compiler enforces the handling of checked exceptions since it can predict their
occurrence.
➢ Errors related to these exceptions must be addressed immediately.
Example: FileNotFoundException, SocketException etc
MULTI ➢ A thread is part of a process or the path followed when executing a program.
➢ Thread scheduler in Java is a software that decides which thread should run.
➢ Only one thread can run in a single process at a time.
THREADI •Note:
➢ When the currentThread method is invoked, a reference is created for the currently
NG
executing thread.
➢ If we print the reference of the thread, it will display three pieces of information:
the thread's name, its priority, and the name of the method in which the thread is
currently executing.
➢ Here, you can modify the thread's name and priority using the setName() method
to change the thread's name and the setPriority() method to adjust the thread’s
priority. However, it's important to note that you cannot modify the method name
associated with the thread
➢ The default priority of the main thread is 5, and the priorities of these threads
typically lie between 1 and 10
•There are two ways to achieve multithreading:
1. Extending Thread class
2. Implementing Runnable Interface
1. Extending the Thread class:
➢ This involves creating a class that extends the Thread class
➢ Overriding the run() method to define the task that will be executed in a separate thread.
➢ Then, create an instance of the class and call its start() method to start the execution of the task in a new thread.
Note:
➢ The programmer must never directly call the run() method.
➢ It must always be indirectly called using start().
•When start() is called, a new thread is created and code inside run() method is executed in new thread while if you call run() directly no new
thread is created and code inside run() will execute on the current thread or main thread.
•[Link] Runnable Interface
➢ Create a class that implements the Runnable interface. The Runnable interface has a single method called run().
➢ Override the run() method in your class to include the code that you want to run in the new thread.
➢ Create an instance of your class.
➢ Create an instance of the Thread class and pass the instance of your class as a parameter to the constructor.
➢ Call the start() method on the Thread instance to start the new thread.
➢Implementing from runnable interface will not allow us to create a new small stack frame to do so we need to use thread class
Thread v/s Runnable:
There are several differences between the Thread class and Runnable interface based on their performance, memory usage, and
composition.
➢ By extending the thread, there is the overhead of additional methods, i.e. they consume excess or indirect memory,
computation time, or other resources.
➢ Since in Java, we can only extend one class, and therefore if we extend the Thread class, then we will not be able to extend
any other class. That is why we should implement Runnable interface to create a thread.
➢ Runnable makes the code more flexible, if we are extending a thread, then our code will only be in a thread whereas, in the
case of runnable, one can pass it in various executor services, or pass it to the single-threaded environment.
➢ Maintenance of the code is easy if we implement the Runnable interface.
User Thread:
➢ User Thread is a Thread that is created by the user
➢ It is the normal thread that runs in the foreground to perform a task.
➢ When all the user threads are completed, the program will be terminated automatically.
Daemon Thread:
➢ It is a low-priority thread that runs in the background to perform specific tasks such as garbage collection, finalization, etc.
➢ The JVM automatically terminates a daemon thread if all the user threads are completed
➢ To create a daemon thread in Java, you simply need to call the setDaemon(true) method on a Thread object before starting
the thread.
The life cycle of thread:
The moment the thread is created till the thread finishes its execution, a thread goes through different phases or states.
New State:
➢ The thread is created but not yet started. Created using the new keyword.
➢ It's waiting for the start() method to be invoked to transition to the "Runnable" state.
Runnable State:
➢ Once the thread's start() method has been invoked, it transitions to the "Runnable" state,
indicating that it is ready to run.
➢ However, it may not immediately start executing as the thread scheduler has not yet
selected it to be the running thread.
•Running State:
➢ The thread transitions to the "Running" state when the thread scheduler has selected it to run, and it is currently
executing its code.
Blocked State:
➢ Threads enter the "Blocked" state when they are temporarily inactive.
➢ This typically occurs when a thread is waiting for a specific resource, such as I/O operations or synchronization.
Waiting State:
➢ In the "Waiting" state, a thread pauses its execution, anticipating another thread to perform a certain action.
➢ The thread can remain in this state until it is notified and transitions back to the "Runnable" state.
Sleep State:
➢ Threads can enter the "Sleep" state voluntarily using the [Link]() method, introducing a pause in their
execution.
➢ After the specified time elapses, the thread automatically transitions back to the "Runnable" state, ready to resume
its tasks.
Dead State:
➢ A thread enters the "Dead" state when it completes its task or is terminated due to an error or being forcefully
killed.
➢ Once a thread is in the dead state, it cannot be restarted.
•Threads from runnable, running, sleep, blocked and wait state can be moved to dead state by calling interrupt()
method.
•Synchronization
•➢ To prevent this, statements that only a single thread should access at a time are referred to as Semaphores.
➢ Locks can be used to implement Semaphores in Java, and they can be achieved by using the synchronized keyword.
➢ This is achieved by synchronizing access to the resource using the synchronized keyword.
➢ If you aim to lock an entire method, incorporate the synchronized keyword into the method's signature.
➢ If the need is to lock only specific lines within a method, utilize a synchronized block.
DeadLock: A deadlock in Java occurs when two or more threads are stuck in the blocked state, each waiting for the other to
release resources.
➢ Deadlock is caused by the synchronized keyword, which causes a thread to block while waiting for a lock associated with a
particular object.
Join() in Java
➢ In Java, the Thread class provides the join() method, which allows one thread to wait for another thread to complete its
execution.
➢ This is useful when the output of one thread is dependent on the execution of another thread.
➢ When a Thread object, let's say t, is currently executing, then calling [Link]() will ensure that t is terminated before the next
instruction is executed by the program.
•Producer-Consumer problem in Java:
➢ The producer-consumer problem is a well-known multi-process
synchronization issue
➢ in computer science that is also referred to as the bounded-
buffer problem.
➢ It involves two distinct processes, the producer and the
consumer, which share a fixed-size buffer that functions as a queue.
➢ The producer's primary responsibility is to create data, put it into
the buffer, and repeat the process.
➢ On the other hand, the consumer is in charge of taking the data
out of the buffer one piece at a time.
➢ This situation creates a challenge because the producer must
ensure that the buffer is not full before adding more data,
➢ while the consumer must make sure that the buffer is not empty
before taking data from it.
➢ As a result, the producer and consumer must cooperate to
ensure that the buffer is not overloaded or underutilized.
COLLECTIONS
The Collection Framework is a group of classes and interfaces that provide a standard way to manage a group of objects in Java.
• boolean add(Object o) - Adds an element to the collection and returns true if the element was successfully added.
• boolean addAll(Collection c) - Adds all of the elements in the specified collection to the current collection and returns true if
the collection was modified as a result of the call.
• boolean remove(Object o) - Removes the first occurrence of the specified element from the collection and returns true if the
element was successfully removed.
• boolean removeAll(Collection c) - Removes all of the elements in the specified collection from the current collection and
returns true if the collection was modified as a result of the call.
• boolean retainAll(Collection c) - Retains only the elements in the collection that are also in the specified collection and returns
true if the collection was modified as a result of the call.
• void clear() - Removes all elements from the collection.
• boolean contains(Object o) - Returns true if the collection contains the specified element.
• boolean containsAll(Collection c) - Returns true if the collection contains all of the elements in the specified collection.
• Iterator iterator() - Returns an iterator over the elements in the collection.
• Object[] toArray() - Returns an array containing all of the elements in the collection
• boolean isEmpty() - Returns true if the collection is empty (i.e., contains no elements).
• int size() - Returns the number of elements in the collection.
LIST:
➢ The List interface is a sub interface of the Collection interface in the Java Collection framework.
➢ A List is an ordered collection of elements and is used to store a collection of elements that can be accessed in order.
Properties: Ordered collection, Index-based access, Duplicates allowed, Multiple implementations, Inherits from Collection,
Resizable, Null allowed.
Methods
• add(int index, Object element): Adds the specified element at the specified position in the list.
• addAll(int index, Collection c): Adds all of the elements in the specified collection to the list, starting at the specified position.
• get(int index): Returns the element at the specified position in the list.
• indexOf(Object o): Returns the index of the first occurrence of the specified element in the list.
• lastIndexOf(Object o): Returns the index of the last occurrence of the specified element in the list.
• remove(int index): Removes the element at the specified position in the list.
• set(int index, Object element): Replaces the element at the specified position in the list with the specified element.
ArrayList:
ArrayList is a commonly used implementation of the List interface in Java. It provides a dynamic array, which automatically
resizes as elements are added or removed from the list.
Different ways of creating ArrayList:
1. Using the default constructor: The simplest way to create an ArrayList is to use the default constructor, which creates an
empty ArrayList.
ArrayList< > list = new ArrayList< >();
2. Specifying the initial capacity: you can also create an initial capacity, which is number of elements that ArrayList can hold
without resizing.
ArrayList< > list = new ArrayList< >(100);
3. Initializing with a collection: you can create arrayList from exisiting collection by passing a collection.
1. void addFirst(Object o) - This method inserts an element at the beginning of the list.
2. void addLast(Object o) - This method inserts an element at the end of the list.
3. Object getFirst() - This method returns the first element in the list.
4. Object getLast() - This method returns the last element in the list.
5. Object removeFirst() - This method removes and returns the first element in the list.
6. Object removeLast() - This method removes and returns the last element in the list.
Stack:
Stack is a data structure that operates on the Last-In-First-Out (LIFO) principle. It is an abstract data type that provides two main
operations, namely, push and pop, which add or remove elements from the top of the stack, respectively.
Methods of stack:
1. Object push(Object o): Adds specified object o to the top of stack and returns the same object as a result.
2. Object pop(Object o): The pop() method pops(removes and returns) the top elements of stack.
3. Object peek(Object o): peek() method that returns the object at top of stack without removing it.
4. Int search(Object o): search(Object o) method provided by the stack class in Java that is used to search for the occurrence of
an object in the stack and returns its position (counted from the top of the stack) if it is found.
If the object is not found in the stack, the method returns -1.
5. Boolean empty(): empty() method in Java’s Stack class is a boolean method that returns a boolean value of true if the stack
is empty and false if it contain elements.
Different ways of traversing a Collection:
Iterator:
➢ Iterator is a Java interface used to traverse a collection and retrieve its elements one by one. The iterator allows sequential
access to the elements of the collection.
➢ It is widely used in the Java collections framework for traversing and manipulating the collections.
Methods of Iterator:
➢ hasNext(): this method returns true is the iterator has more elements to traverse, and false otherwise.
➢ next(): This method returns the next element in the collection and advance the iterator. If there are no more elements, a
NoSuchElementException is thrown.
➢ remove(): This method removes the last element returned by the iterator from the underlying collection. This method can onoy
be called once per call to next(), otherwise an IllegalStateException is thrown.
ListIterator:
ListIterator is an interface in Java that provides a way to iterate over a list (or any List implementation) and allows for both
forward and backward traversal of the list.
Methods Of ListIterator:
➢ hasNext() - returns true if the iteration has more elements in the forward direction.
➢ next() - returns the next element in the list and advances the cursor position.
➢ hasPrevious() - returns true if the iteration has more elements in the reverse direction.
➢ previous() - returns the previous element in the list and moves the cursor position backward.
➢ nextIndex() - returns the index of the next element.
➢ previousIndex() - returns the index of the previous element.
➢ remove() - removes the last element returned by the iterator from the list.
➢ set(E e) - replaces the last element returned by the iterator with the specified element
Set:
The Set interface is a part of [Link] pakage and represents a collection of the unique element, meaning that no two elements in
Set can be equal.
➢ HashtSet
➢ LinkedHashSetTreeSet
HashSet:
HashSet is a class that implements the Set interface and provides an implantation of a set that uses a hash table for storage. A
HashSet is similar to an array or a List, but with the added feature that it does not allow duplicate elements.
Properties:
➢ It follows Hashing Algorithm internally Different ways of creating Hashset:
➢ Efficient Data Structure is Hashing Algorithm new HashSet()
➢ Default capacity = 16 new HashSet(Collection c)
➢ LoadFactor = 0.75 new HashSet(int initalCapacity)
➢ newCapacity = oldCapacity *2 new HashSet(int initalCapacity, float loadfactor)
➢ Duplicates are not allowed
➢ Insertion order not maintained
➢ Majorly used for searching
Linked HashSet:
LinkedHashSet is a class that extends the HashSet class and provides a set that maintains the insertion order of its elements. It
does this by using a doubly-linked list to keep track of order in which elements were added to set, in addition to hash table used
by HashSet class.
TreeSet:
TreeSet is a class that implements the SortedSet interface and provides set that is sorted in natural ascending order.
Properties: Different ways of creating TreeSet:
➢ Insertion order is not preserved. new TreeSet()
➢ Duplicates are not allowed. new TreeSet(Collection c)
➢ Heterogenous objects not allowed. new TreeSet(SortedSet s)
➢ Null insertion not allowed. new Tree set(Comparator c)
➢ Elements are in sorted order.
Methods of TreeSet:
➢ First(): Returns the first (lowest) elements currently in the set.
➢ Last(): Returns the last (highest) elements currently in the set.
➢ headset(E toElement): Returns a view of the portion of the set whose elements are strictly less than toElement.
➢ tailSet(E fromElement): Returns a view of the portion of the set whose elements are greater than or equal to fromElement.
Queue:
➢ A queue is linear data structure in which elements are added at one end (called the rear or trail) and removed from the other
(called the front or head).
➢ It follows the First-In-First-Out (FIFO) principle, meaning that the elements that is added first is the one that will be
removed first.
Methods Of Queue:
1. offer(Object e): Insert the specified elements into the queue. If the task is successful, offer() returns true, if not it returns
false.
2. remove(): Retrieves and removes the head of the queue. Throws NoSuchElementException is the queue is empty.
3. Poll(): Retrieves and removes the head of the queue, or returns is empty.
4. element(): Retrives, but does not remove, the head of the queue. Throws NoSuchElementException if the queue is empty.
5. peek(): Retrives, but does not remove, the head of the queue, or returns null if the queue is empty.
PriorityQueue:
➢ PriorityQueue is a special kind of queue in Java's Collection framework where each element is associated with a priority
value.
➢ The elements in a PriorityQueue are ordered based on their priority, with the highest priority elements appearing at the front
of the queue.
Some common operations that can be performed on a PriorityQueue include:
• add(E e): Inserts the specified element into the queue based on its priority.
• Remove(): Retrieves and removes the head of the queue.
• peek(): Retrieves, but does not remove, the head of the queue.
• size(): Returns the number of elements in the queue.
Comparable Interface:
➢ A comparable interface is a generic interface that defines a single method, compareTo()
➢ Which is used to compare two objects of the same class.
➢ By implementing the Comparable interface, a class indicates that its instances can be ordered or sorted in some natural way.
➢ compareTo() method takes a single argument, which is the object to be compared to the current object.
➢ It returns a negative integer if the current object is less than the argument, zero if they are equal, or a positive integer if the
current object is greater than the argument.
Comparator Interface:
➢ The comparator interface is a generic interface that provides a way to define custom ordering or sorting for objects of a
particular class.
➢ The Comparator interface defines a single method, compare()
➢ which takes two arguments of the type we want to compare, and returns a negative integer if the first argument is less than the
second, zero if they are equal, or a positive integer if the first argument is greater than the second.
import [Link];
public class Alpha{
public static void main(String[] args){
String path = "c:\\Users\\Megha\Desktop\\Myfiles\\[Link]";
File file = new File(path);
[Link]([Link]());
}
}
➢ canWrite() method will check whether the file is writable or not. It returns true if it readable else false.
[Link]([Link]());
2. getName(): This method returns the Name of the file object. The function returns a string object which contains the Name of
the given file object.
[Link]([Link]());
3. getParent(): This method returns a string that denotes the pathname string of the parent directory named by this abstract
pathname, or null if this pathname does not name a parent.
[Link]([Link]());
4. getAbsolutePath(): The getAbsolutePath() method is a part of the file class. This function returns the absolute pathname of
the given file object. If the pathname of the file object is absolute then it simply returns the path of current file object.
[Link]([Link]());
5. isFile(): The isFile() function is a part of the File class in Java. This function determines whether the file or directory denoted
by the abstract filename is a File or not. The function returns true if the abstract file path is File else returns false.
[Link]([Link]());
6. isDirectory(): This function determines whether the file or directory denoted by the abstract filename is a directory or not.
The function returns true if the abstract file path is Directory else returns false.
[Link]([Link]());
7. createNewFile(): The createNewFile() method creates a new and empty file with specified name. this operation
succeeded when the name did not yet exist. Checking for the existence of the file and creation of the file are atomic operations.
[Link]()
The createNewFile() will throw IOException so you need to handle this exception using throw or try catch
8. mkdir(): The mkdir() function used to create new directory denoted by the abstract pathname. The function returns if the
directory is created else returns false.
[Link]([Link]())
9. list(): Returns an array of strings naming the files and directories in the directory denoted by this abstract pathname.
10. delete(): Deletes the file or directory denoted by this abstract pathname. If this pathname denotes a directory, then the
directory must be empty in order to be deleted.
[Link]([Link]())
File Writer:
Java FileWriter class is used to write character-oriented data to file. It is character-oriented class which is used for file
handling in java.
➢ Create an object of file writer.
➢ Call write () and pass the string to be written inside the file.
➢ Now call the flush () to push the data to the file form the stream.
import [Link];
import [Link];
import [Link];
public class Alpha {
public static void main(String[] args) {
String path = "C:\\Users\\TAP\\Desktop\\MyFiles\\[Link]";
File file = new File(path);
FileWriter writer;
try {
writer = new FileWriter(file);
[Link]("Hello World");
[Link]();
}
catch (IOException e) {
[Link]();
}
}
}
File Reader: Java FileReader class is used to read data from the file. It returns data in byte format like FileInputStream class.
It is a character-oriented class which is used for file handling in java.
➢ Store path of the file in a string.
➢ Create an object of file reader and this will throw an exception of FileNotFoundException if the file is not present in that
directory so need to handle that exception.
➢ Call read() which will read the characters present in that file and this method will throw IO Exception need to handle that.
➢ The read() will return -1 if there are non characters in the file.
public class Alpha {
public static void main(String[] args) {
String path = "C:\\Users\\TAP\\Desktop\\MyFiles\\[Link]";
FileReader reader = null;
try {
reader = new FileReader(path);
[Link]([Link]());
}
catch (FileNotFoundException e) {
[Link]();
}
catch(IOException e1) {
[Link]();
}
}
}
BufferedReader:- Now let’s see how to read the data from the file using BufferedReader. BufferedReader reads line by line.
➢ Create an object of file reader
➢ Convert file reader to BufferedReader by creating an object of the buffered reader.
➢ Call readLine() to read the each line present inside the file.
➢ This readLine() will also take the cursor to the next line.
➢ When there are no next line of characters readLine() method will return default value of String i.e null.
public class Alpha {
public static void main(String[] args) {
Parallel Collector : The parallel garbage collector, also referred to as the throughput garbage collector, was the default for early
Java releases through Java 8. Its capabilities exceed that of the serial collector in that it was designed for medium- to large-
sized heaps and multithreaded applications.
CMS : The CMS garbage collector was deprecated in Java 9 and removed from the Java platform in Java 14. Its purpose was to
minimize the amount of time an application was paused for garbage collection. The reasons for deprecation and removal
included high resource consumption, failures due to lag, difficulty in maintaining the code base, and that there were better
alternatives.
G1 Collector : The G1 Collector became the default garbage collector in Java 9. The G1 Collector can be considered the
primary and default garbage collector.
ZGC : Java 11 was released with the ZGC garbage collector as an experimental feature. ZGC’s aim was to provide a low-latency
garbage collector that was scalable. The intention was for ZGC to handle a wide range of heap sizes, from very small to very
large (for example, terabytes). ZGC delivered on these goals without sacrificing pause times. This success led to ZGC being
released as a Java 15 feature.