Core Java
Core Java
Java is a programming language and a platform. Java is a high level, robust, object-oriented and secure
programming language.
Java was developed by Sun Microsystems (which is now the subsidiary of Oracle) in the year
1995. James Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team changed the name from Oak to Java.
Platform: Any hardware or software environment in which a program runs, is known as a platform.
Since Java has a runtime environment (JRE) and API, it is called a platform.
Features of Java:
The primary objective of Java programming language creation was to make it portable, simple and
secure programming language. Apart from this, there are also some excellent features which play an
important role in the popularity of this language. The features of Java are also known as Java buzzwords.
1. Object-Oriented
• Java is based on object-oriented principles, allowing for modular, reusable, and organized code.
This means it supports key concepts like inheritance, polymorphism, encapsulation, and
abstraction.
2. Platform-Independent
• Java's "Write Once, Run Anywhere" (WORA) philosophy means that compiled Java code can
run on any device with a Java Virtual Machine (JVM), making it highly portable and cross-
platform.
3. Simple and Readable
• Java has a syntax similar to C++, but with reduced complexity. It omits complex features like
operator overloading and multiple inheritance, making it easier to learn and write.
4. Secure
• Java provides strong security features through its runtime environment, which helps prevent
unauthorized access and memory leaks. Its secure architecture and the use of the Java sandbox
also add a layer of security for untrusted code.
5. Multithreaded
• Java supports multithreading, enabling concurrent processing to improve performance,
especially in applications requiring parallel execution like games or complex computations.
6. High Performance
• Java is faster than interpreted languages due to its bytecode compilation, and modern JVMs
include Just-In-Time (JIT) compilation for optimized performance.
Components of Java:
In Java, JDK, JRE, and JVM are crucial components, each serving a specific role in the development
and execution of Java applications. Here’s a breakdown of each:
1. JVM (Java Virtual Machine)
• Purpose: The JVM is a runtime environment that runs Java bytecode, which is produced after
compiling Java source code.
• Functionality: It converts bytecode into machine code specific to the operating system. JVM
provides platform independence, allowing Java applications to run on any OS with a compatible
JVM.
2. JRE (Java Runtime Environment)
• Purpose: JRE provides the libraries and JVM required to run Java applications.
• Functionality: It includes the JVM and essential libraries but does not contain development
tools like the compiler. So, it is intended for users who want to run Java applications without
developing them.
3. JDK (Java Development Kit)
• Purpose: The JDK is a full development kit for creating, compiling, and running Java
applications.
• Functionality: It includes both the JRE and development tools like the Java compiler (javac),
debugger, and other tools required for developing Java programs. Developers use the JDK to
write, compile, and debug Java code.
Your First Java Program: The following program displays Hello, World! on the screen.
Ex: public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!"); } }
Java Comments:Comments are hints that we add to our code, making it easier to read and understand.
Comments are completely ignored by Java compilers.
1.Single-line Comment
In Java, a single-line comment starts and ends in the same line. To write a single-line comment, we can
use the // symbol.
2.Multi-line Comment
When we want to write comments in multiple lines, we can use the multi-line comment. To write multi-
line comments, we can use the /*....*/ symbol.
Variables:
In Java, variables are containers for storing data values. Each variable has a data type that defines what
type of data it can hold, and the data type also dictates how much memory the variable will consume.
Here’s an overview of variables in Java:
Types of Variables:
There are three types of variables in Java:
o local variable
o instance variable
o static variable
1) 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.
A local variable cannot be defined with "static" keyword.
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.
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable:
A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
Variable Declaration:
In Java, a variable must be declared with a type before it can be used. The syntax for declaring a variable
is:
Syntax: type variableName = value;
Data Type Default Value Default size
byte 0 1 byte
short 0 2 byte
int 0 4 byte
long 0L 8 byte
Data Types:
In Java, data types specify the different sizes and values that variables can hold. Java has two main
categories of data types:
1. Primitive Data Types
Primitive data types are the most basic data types in Java, directly storing the value in memory
and having a fixed size. Java has 8 primitive data types:
The Boolean data type is used to store only two possible values: true and false. This data type is used
for simple flags that track true/false conditions.
Java Scanner Class:
The Scanner class of the java.util package is used to read input data from different sources like input
streams, files, etc. Let's take an example.
The Scanner class provides various methods that allow us to read inputs of different types.
Method Description
import java.util.Scanner;
class Main {
input.close();
Operators:
Operators are symbols that perform operations on variables and values. For example, + is an operator
used for addition, while * is also an operator used for multiplication.
1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
7. Ternary Operator
class Main {
// declare variables
// addition operator
// subtraction operator
// multiplication operator
// division operator
// modulo operator
class Main {
int a = 4;
int var;
var = a;
var += a;
var *= a;
class Main {
int a = 7, b = 11;
// == operator
// != operator
System.out.println(a != b); // true
// > operator
// < operator
// >= operator
// <= operator
Ex:
class Main {
// && operator
// || operator
// ! operator
class Main {
result1 = ++a;
result2 = --b;
// Bitwise AND
int andResult = num1 & num2;
8.Ternary Operator: ?
System.out.println(result);
Java Strings:
In Java, a string is a sequence of characters. For example, "hello" is a string containing a sequence of
characters 'h', 'e', 'l', 'l', and 'o'.
// create a string
class Main {
// create strings
// print strings
Java provides various string methods to perform different operations on strings. We will look into some
of the commonly used string operations.
To find the length of a string, we use the length() method. For example,
class Main {
// create a string
}
}
We can join two strings in Java using the concat() method. For example,
class Main {
// create second
In Java, we can make comparisons between two strings using the equals() method. For example,
class Main {
// create 3 strings
Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear.
Decision-Making statements:
As the name suggests, decision-making statements decide which statement to execute and when.
1) If Statement:
if statement is used to evaluate a condition. 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. }
Ex:
1. if(condition) {
2. statement 1; //executes when condition is true
3. }
1. int x = 10;
2. int y = 12;
3. if(x+y > 20) {
4. System.out.println("x + y is greater than 20");
5. }
6. }
7. }
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. }
Ex:
The if-else-if statement contains the if-statement followed by multiple else-if statements.
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. }
Ex:
4. 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.
1. if(condition 1) {
2. statement 1; //executes when condition 1 is true
3. if(condition 2) {
4. statement 2; //executes when condition 2 is true
5. }
6. else{
7. statement 2; //executes when condition 2 is false
8. }
9. }
Ex:
Switch Statement:
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.
1. switch (expression){
2. case value1:
3. statement1;
4. break;
5. .
6. .
7. .
8. case valueN:
9. statementN;
10. break;
11. default:
12. default statement;
13. }
Ex:
Loop Statements:
In programming, sometimes we need to execute the block of code repeatedly while some condition
evaluates to true.
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
1.For loop:
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.
Ex:
2. for-each loop:
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.
3. while loop:
The while loop is also used to iterate over the number of statements multiple times. However, if we
don't know the number of iterations in advance, it is recommended to use a while loop.
1. while(condition){
2. //looping statements
3. }
Ex:
4. do-while loop:
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.
Syntax:
1. do
2. {
3. //statements
4. } while (condition);
Ex:
1. public class Calculation {
2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int i = 0;
5. System.out.println("Printing the list of first 10 even numbers \n");
6. do {
7. System.out.println(i);
8. i = i + 2;
9. }while(i<=10);
10. }
11. }
Jump Statements:
Jump statements are used to transfer the control of the program to the specific statements.
1.break statement:
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.
Ex:
continue 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.
Ex:
Java Arrays:
In Java, we can declare and allocate the memory of an array in one single statement. For example,
Note:
• Array indices always start from 0. That is, the first element of an array is at index 0.
• If the size of an array is n, then the last element of the array will be at index n-1.
class Main {
// create an array
}
Example: Using For Loop
class Main {
// create an array
System.out.println(age[i]);
class Main {
// create an array
for(int a : age) {
System.out.println(a);
}
Example: Compute Sum and Average of Array Elements
class Main {
int sum = 0;
Double average;
sum += number;
Multidimensional Arrays:
Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Java.
A multidimensional array is an array of arrays. That is, each element of a multidimensional array is an
array itself. For example,
{4.1, -1.1}
};
class MultidimensionalArray {
// create a 2d array
class MultidimensionalArray {
int[][] a = {
{7},
};
System.out.println(a[i][j]);
}
}
OOPs Concepts:
Object-Oriented Programming is a paradigm that provides many concepts, such as inheritance, data
binding, polymorphism, etc.
The main aim of object-oriented programming is to implement real-world entities, for example, object,
classes, abstraction, inheritance, polymorphism, etc.
Object means a real-world entity such as a pen, chair, table, computer, watch, etc. Object-Oriented
Programming is a methodology or paradigm to design a program using classes and objects. It simplifies
software development and maintenance by providing some concepts:
o Object
o Class
o Inheritance
o Polymorphism
o Abstraction
o Encapsulation
1.Object:
o Any entity that has state and behavior is known as an object. For example, a chair, pen, table,
keyboard, bike, etc. It can be physical or logical.
2.Class:
A class is a blueprint for the object. Before we create an object, we first need to define the class.
We can create a class in Java using the class keyword. For example,
class ClassName {
// fields
// methods
}
Example: Java Class and Objects
class Lamp {
// true if light is on
boolean isOn;
void turnOn() {
isOn = true;
void turnOff() {
isOn = false;
led.turnOn();
// turn off the light by
halogen.turnOff();
Java Methods:
• User-defined Methods: We can create our own method based on our requirements.
• Standard Library Methods: These are built-in methods in Java that are available to use.
Here,
• returnType - It specifies what type of value a method returns For example if a method has
an int return type then it returns an integer value.
If the method does not return a value, its return type is void.
• methodName - It is an identifier that is used to refer to the particular method in a program.
• method body - It includes the programming statements that are used to perform some tasks. The
method body is enclosed inside the curly braces { }.
• This is the simple syntax of declaring a method. However, the complete syntax of declaring a
method is
Static Method
A method that has static keyword is known as static method. In other words, a method that belongs to
a class rather than an instance of a class is known as a static method. We can also create a static method
by using the keyword static before the method name.
The main advantage of a static method is that we can call it without creating an object. It can access
static data members and also change the value of it. It is used to create an instance method. It is invoked
by using the class name. The best example of a static method is the main() method.
Example of static method
Instance Method
The method of the class is known as an instance method. It is a non-static method defined in the class.
Before calling or invoking the instance method, it is necessary to create an object of its class. Let's see
an example of an instance method.
InstanceMethodExample.java
Java Constructors:
A constructor in Java is similar to a method that is invoked when an object of the class is created.
Unlike Java methods, a constructor has the same name as that of the class and does not have any return
type.
For example,
class Test {
Test() {
// constructor body
Ex:
class Main {
// constructor
Main() {
System.out.println("Constructor Called:");
name = "Programiz";
Types of Constructor
1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor
Similar to methods, a Java constructor may or may not have any parameters (arguments).
If a constructor does not accept any parameters, it is known as a no-argument constructor. For example,
private Constructor() {
class Main {
int i;
private Main() {
i = 5;
System.out.println("Constructor is called");
A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).
class Main {
String languages;
Main(String lang) {
languages = lang;
If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during
the execution of the program.
class Main {
int a;
boolean b;
System.out.println("Default Value:");
}
Important Notes on Java Constructors
class Animal {
}
Types of Access Modifier:
There are four access modifiers keywords in Java and they are:
Modifier Description
Default declarations are visible only within the package (package private)
If we do not explicitly specify any access modifier for classes, methods, variables, etc, then by default
the default access modifier is considered. For example,
package defaultPackage;
class Logger {
void message(){
System.out.println("This is a message");
When variables and methods are declared private, they cannot be accessed outside of the class. For
example,
class Data {
// private variable
d.name = "Programiz";
When methods and data members are declared protected, we can access them within the same package
as well as from subclasses. For example,
class Animal {
// protected method
System.out.println("I am an animal");
dog.display();
When methods, variables, classes, and so on are declared public, then we can access them from
anywhere. The public access modifier has no scope restriction. For example,
// Animal.java file
// public class
public class Animal {
// public variable
// public method
System.out.println("I am an animal.");
// Main.java
animal.legCount = 4;
animal.display();
Inheritance:
Inheritance is one of the key features of OOP that allows us to create a new class from an existing class.
The new class that is created is known as subclass (child or derived class) and the existing class from
where the child class is derived is known as superclass (parent or base class).
class Animal {
// to perform inheritance
On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn
about interfaces later.
1.Single Inheritance:
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.
Ex:
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. }}
2.Multi Level:
When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
multilevel inheritance.
Ex:
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. }}
3.Heirarchical:
When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example
given below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
Ex:
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 Cat extends Animal{
8. void meow(){System.out.println("meowing...");}
9. }
10. class TestInheritance3{
11. public static void main(String args[]){
12. Cat c=new Cat();
13. c.meow();
14. c.eat();
15. //c.bark();//C.T.Error
16. }}
To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
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. class A{
2. void msg(){System.out.println("Hello");}
3. }
4. class B{
5. void msg(){System.out.println("Welcome");}
6. }
7. class C extends A,B{//suppose if it were
8.
9. public static void main(String args[]){
10. C obj=new C();
11. obj.msg();//Now which msg() method would be invoked?
12. }
13. }
Java Interface:
An interface is a fully abstract class. It includes a group of abstract methods (methods without a body).
We use the interface keyword to create an interface in Java. For example,
interface Language {
Implementing an Interface
To use an interface, other classes must implement it. We use the implements keyword to implement an
interface.
Ex:
interface Polygon {
class Main {
public static void main(String[] args) {
r1.getArea(5, 6);
Java Polymorphism
Polymorphism is an important concept of object-oriented programming. It simply means more than one
form.
That is, the same entity (method or operator or object) can perform different operations in different
scenarios.
class Polygon {
System.out.println("Rendering Polygon...");
// renders Square
System.out.println("Rendering Square...");
// renders circle
System.out.println("Rendering Circle...");
}
class Main {
s1.render();
c1.render();
During inheritance in Java, if the same method is present in both the superclass and the subclass. Then,
the method in the subclass overrides the same method in the superclass. This is called method
overriding.
class Language {
@Override
}
}
class Main {
j1.displayInfo();
l1.displayInfo();
In a Java class, we can create methods with the same name if they differ in parameters. For example,
This is known as method overloading in Java. Here, the same method will perform different operations
based on the parameter.
class Pattern {
System.out.print("*");
}
// method with single parameter
System.out.print(symbol);
class Main {
d1.display();
System.out.println("\n");
d1.display('#');
}}
The abstract class in Java cannot be instantiated (we cannot create objects of abstract classes). We use
the abstract keyword to declare an abstract class. For example,
// throws an error
// abstract method
// regular method
void method2() {
A method that doesn't have its body is known as an abstract method. We use the same abstract keyword
to create abstract methods. For example,
If a class contains an abstract method, then the class should be declared abstract. Otherwise, it will
generate an error. For example,
// error
class Language {
// abstract method
Though abstract classes cannot be instantiated, we can create subclasses from it. We can then access
members of the abstract class using the object of the subclass. For example,
obj.display();
System.out.println("SportsBike Brake");
System.out.println("MountainBike Brake");
}
class Main {
m1.brake();
s1.brake();
Java Encapsulation:
Encapsulation is one of the key features of object-oriented programming. Encapsulation refers to the
bundling of fields and methods inside a single class.
It prevents outer classes from accessing and changing fields and methods of a class. This also helps to
achieve data hiding.
class Area {
int length;
int breadth;
this.length = length;
this.breadth = breadth;
class Main {
rectangle.getArea();
Java super: The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).
class Animal {
// overridden method
System.out.println("I am an animal");
// overriding method
@Override
System.out.println("I am a dog");
}
public void printMessage(){
display();
super.display();
class Main {
dog1.printMessage();
The Exception Handling in Java is one of the powerful mechanism to handle the runtime errors so
that the normal flow of the application can be maintained.
In Java, an exception is an event that disrupts the normal flow of the program. It is an object which is
thrown at runtime.
The java.lang.Throwable class is the root class of Java Exception hierarchy inherited by two subclasses:
Exception and Error. The hierarchy of Java Exception classes is given below:
Types of Java Exceptions
There are mainly two types of exceptions: checked and unchecked. An error is considered as the
unchecked exception. However, according to Oracle, there are three types of exceptions namely:
1. Checked Exception
2. Unchecked Exception
3. Error
1) Checked Exception
The classes that directly inherit the Throwable class except RuntimeException and Error are known as
checked exceptions. For example, IOException, SQLException, etc. Checked exceptions are checked
at compile-time.
2) Unchecked Exception
The classes that inherit the RuntimeException are known as unchecked exceptions. For example,
ArithmeticException, NullPointerException, ArrayIndexOutOfBoundsException, etc. Unchecked
exceptions are not checked at compile-time, but they are checked at runtime.
3) Error
1.try:
The "try" keyword is used to specify a block where we should place an exception code. It means we can't
use try block alone. The try block must be followed by either catch or finally.
2.catch:
The "catch" block is used to handle the exception. It must be preceded by try block which means we can't use
catch block alone. It can be followed by finally block later.
3.finally:
The "finally" block is used to execute the necessary code of the program. It is executed whether an exception is
handled or not.
4.throw:
5.throws:
The "throws" keyword is used to declare exceptions. It specifies that there may occur an exception in
the method. It doesn't throw an exception. It is always used with method signature.
JavaExceptionExample.java
class Main {
try {
int divideByZero = 5 / 0;
catch (ArithmeticException e) {
finally {
When we throw an exception, the flow of the program moves from the try block to the catch block.
class Main {
// throw an exception
import java.io.*;
class Main {
try {
findFile();
catch (IOException e) {
System.out.println(e);
Multithreading in Java:
Multitasking:
Multitasking is a process of executing multiple tasks simultaneously. We use multitasking to utilize the
CPU. Multitasking can be achieved in two ways:
o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.
Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses
a shared memory area.
In Java, a thread always exists in any one of the following states. These states are:
1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated
Java Vector:
The Vector class is an implementation of the List interface that allows us to create resizable-arrays
similar to the ArrayList class.
Ex:
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> mammals= new Vector<>();
// Using the add() method
mammals.add("Dog");
mammals.add("Horse");
// Using index number
mammals.add(2, "Cat");
System.out.println("Vector: " + mammals);
// Using addAll()
Vector<String> animals = new Vector<>();
animals.add("Crocodile");
animals.addAll(mammals);
System.out.println("New Vector: " + animals);
}
}
Access Vector Elements:
import java.util.Iterator;
import java.util.Vector;
class Main {
public static void main(String[] args) {
Vector<String> animals= new Vector<>();
animals.add("Dog");
animals.add("Horse");
animals.add("Cat");
// Using get()
String element = animals.get(2);
System.out.println("Element at index 2: " + element);
// Using iterator()
Iterator<String> iterate = animals.iterator();
System.out.print("Vector: ");
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
import java.util.Set;
import java.util.HashSet;
class Main {
public static void main(String[] args) {
// Creating a set using the HashSet class
Set<Integer> set1 = new HashSet<>();
// Add elements to the set1
set1.add(2);
set1.add(3);
System.out.println("Set1: " + set1);
// Creating another set using the HashSet class
Set<Integer> set2 = new HashSet<>();
// Add elements
set2.add(1);
set2.add(2);
System.out.println("Set2: " + set2);
// Union of two sets
set2.addAll(set1);
System.out.println("Union is: " + set2);
}
}
The LinkedHashSet class of the Java collections framework provides functionalities of both
the hashtable and the linked list data structure.
However, linked hash sets maintain a doubly-linked list internally for all of its elements. The linked list
defines the order in which elements are inserted in hash tables.
Create a LinkedHashSet
In order to create a linked hash set, we must import the java.util.LinkedHashSet package first.
Once we import the package, here is how we can create linked hash sets in Java.
Notice, the part new LinkedHashSet<>(8, 0.75). Here, the first parameter is capacity and the second
parameter is loadFactor.
• capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
• loadFactor - The load factor of this hash set is 0.6. This means, whenever our hash table is filled
by 60%, the elements are moved to a new hash table of double the size of the original hash
table.
Here is how we can create a linked hash set containing all the elements of other collections.
import java.util.LinkedHashSet;
import java.util.ArrayList;
class Main {
evenNumbers.add(4);
Set Operations
The various methods of the LinkedHashSet class can also be used to perform various set operations.
Union of Sets:
Two perform the union between two sets, we can use the addAll() method. For example,
import java.util.LinkedHashSet;
class Main {
evenNumbers.add(2);
evenNumbers.add(4);
numbers.add(1);
numbers.add(3);
numbers.addAll(evenNumbers);
Intersection of Sets
To perform the intersection between two sets, we can use the retainAll() method. For example
import java.util.LinkedHashSet;
class Main {
primeNumbers.add(2);
primeNumbers.add(3);
evenNumbers.add(2);
evenNumbers.add(4);
evenNumbers.retainAll(primeNumbers);
Difference of Sets:
To calculate the difference between the two sets, we can use the removeAll() method. For example,
import java.util.LinkedHashSet;
class Main {
primeNumbers.add(3);
primeNumbers.add(5);
oddNumbers.add(1);
oddNumbers.add(3);
oddNumbers.add(5);
primeNumbers.removeAll(oddNumbers);
Subset:
To check if a set is a subset of another set or not, we can use the containsAll() method. For example,
import java.util.LinkedHashSet;
class Main {
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
primeNumbers.add(3);
Before you learn about Java Type Casting, make sure you know about data types.
Type Casting
The process of converting the value of one data type (int, float, double, etc.) to another data type is
known as typecasting.
In Java, there are 13 types of type conversion. However, in this tutorial, we will only focus on the major
2 types.
In Widening Type Casting, Java automatically converts one data type to another data type.
In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.
class Main {
In the case of Narrowing Type Casting, the higher data types (having larger size) are converted into
lower data types (having smaller size). Hence there is the loss of data. This is why this type of
conversion does not happen automatically.
class Main {
The File class of the java.io package is used to perform various operations on files and directories.
There is another package named java.nio that can be used to work with files. However, in this tutorial,
we will focus on the java.io package.
A file is a named location that can be used to store related information. For example,
main.java is a Java file that contains information about the Java program.
To create an object of File, we need to import the java.io.File package first. Once we import the
package, here is how we can create objects of file.
import java.io.File;
class Main {
public static void main(String[] args) {
try {
if (value) {
else {
catch(Exception e) {
e.getStackTrace();
import java.io.FileReader;
class Main {
try {
// Creates a reader using the FileReader
// Reads characters
input.read(array);
System.out.println(array);
input.close();
catch(Exception e) {
e.getStackTrace();
To write data to the file, we can use subclasses of either OutputStream or Writer.
import java.io.FileWriter;
class Main {
try {
output.close();
catch (Exception e) {
e.getStackTrace();
We can use the delete() method of the File class to delete the specified file or directory.
import java.io.File;
class Main {
if(value) {
else {
}}}