0% found this document useful (0 votes)
10 views

Core Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security features. It supports various application types including standalone, web, enterprise, and mobile applications, and includes important components like JDK, JRE, and JVM. Key features of Java include its object-oriented nature, platform independence, simplicity, security, multithreading capabilities, and high performance.

Uploaded by

Bhavan Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Core Java

Java is a high-level, object-oriented programming language developed by Sun Microsystems in 1995, known for its portability and security features. It supports various application types including standalone, web, enterprise, and mobile applications, and includes important components like JDK, JRE, and JVM. Key features of Java include its object-oriented nature, platform independence, simplicity, security, multithreading capabilities, and high performance.

Uploaded by

Bhavan Reddy
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 77

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.

Real Time Java Applications:


There are mainly 4 types of applications that can be created using Java programming:
1) Standalone Application
Standalone applications are also known as desktop applications or window-based applications. These
are traditional software that we need to install on every machine. Examples of standalone application
are Media player, antivirus, etc. AWT and Swing are used in Java for creating standalone applications.
2) Web Application
An application that runs on the server side and creates a dynamic page is called a web application.
Currently, Servlet, JSP, Struts, Spring, Hibernate, JSF, etc. technologies are used for creating web
applications in Java.
3) Enterprise Application
An application that is distributed in nature, such as banking applications, etc. is called an enterprise
application. It has advantages like high-level security, load balancing, and clustering. In Java, EJB is
used for creating enterprise applications.
4) Mobile Application
An application which is created for mobile devices is called a mobile application. Currently, Android
and Java ME are used for creating mobile applications.

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

boolean false 1 bit

char '\u0000' 2 byte

byte 0 1 byte

short 0 2 byte

int 0 4 byte

long 0L 8 byte

float 0.0f 4 byte

double 0.0d 8 byte

ex: int age = 25; // Integer variable


String name = "Alice"; // String variable

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:

2. Non-Primitive (Reference) Data Types:


Strings, list, queue, set etc

Boolean Data Type:

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.

Java Scanner Methods to Take Input

The Scanner class provides various methods that allow us to read inputs of different types.

Method Description

nextInt() reads an int value from the user

nextFloat() reads a float value form the user

nextBoolean() reads a boolean value from the user

nextLine() reads a line of text from the user

next() reads a word from the user

nextByte() reads a byte value from the user

nextDouble() reads a double value from the user

nextShort() reads a short value from the user

nextLong() reads a long value from the user

Example 1: Java Scanner nextInt()

import java.util.Scanner;

class Main {

public static void main(String[] args) {

// creates a Scanner object

Scanner input = new Scanner(System.in);

System.out.println("Enter an integer: ");

// reads an int value

int data1 = input.nextInt();


System.out.println("Using nextInt(): " + data1);

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.

Operators in Java can be classified into 5 types:

1. Arithmetic Operators
2. Assignment Operators
3. Relational Operators
4. Logical Operators
5. Unary Operators
6. Bitwise Operators
7. Ternary Operator

1.Java Arithmetic Operators: +,-,*,/,%

class Main {

public static void main(String[] args) {

// declare variables

int a = 26, b = 10;

// addition operator

System.out.println("a + b = " + (a + b));

// subtraction operator

System.out.println("a - b = " + (a - b));

// multiplication operator

System.out.println("a * b = " + (a * b));

// division operator

System.out.println("a / b = " + (a / b));

// modulo operator

System.out.println("a % b = " + (a % b));


}

2.Assignment Operator: =,+=,-=,*=,%=,/=

class Main {

public static void main(String[] args) {

int a = 4;

int var;

// assign value using =

var = a;

System.out.println("var using =: " + var);

// assign value using =+

var += a;

System.out.println("var using +=: " + var);

// assign value using =*

var *= a;

System.out.println("var using *=: " + var);

3.Relational Operators: <,>,<=,>=,==,!=

class Main {

public static void main(String[] args) {

int a = 7, b = 11;

System.out.println("a is " + a + " and b is " + b);

// == operator

System.out.println(a == b); // false

// != operator
System.out.println(a != b); // true

// > operator

System.out.println(a > b); // false

// < operator

System.out.println(a < b); // true

// >= operator

System.out.println(a >= b); // false

// <= operator

System.out.println(a <= b); // true

4.Logical Operators: NAND, NOR, OR

Operator Example Meaning

&& (Logical expression1 && true only if both expression1 and


AND) expression2 expression2 are true

expression1 || true if either expression1 or expression2 is


|| (Logical OR)
expression2 true

! (Logical NOT) !expression true if expression is false and vice versa

Ex:

class Main {

public static void main(String[] args) {

// && operator

System.out.println((5 > 3) && (8 > 5)); // true

System.out.println((5 > 3) && (8 < 5)); // false

// || operator

System.out.println((5 < 3) || (8 > 5)); // true


System.out.println((5 > 3) || (8 < 5)); // true

System.out.println((5 < 3) || (8 < 5)); // false

// ! operator

System.out.println(!(5 == 3)); // true

System.out.println(!(5 > 3)); // false

5.Unary Operators: ++, --

class Main {

public static void main(String[] args) {

int a = 12, b = 12;

int result1, result2;

System.out.println("Value of a: " + a);

result1 = ++a;

System.out.println("After increment: " + result1);

System.out.println("Value of b: " + b);

result2 = --b;

System.out.println("After decrement: " + result2);

6.Bitwise Operator: &, |, ^, <<, >>

public class BitwiseOperatorsDemo {

public static void main(String[] args) {

int num1 = 12; // Binary: 1100

int num2 = 25; // Binary: 11001

// Bitwise AND
int andResult = num1 & num2;

System.out.println("Bitwise AND: " + andResult);

int orResult = num1 | num2;

System.out.println("Bitwise OR: " + orResult);

int xorResult = num1 ^ num2;

System.out.println("Bitwise XOR: " + xorResult);

int leftShiftResult = num1 << 2;

System.out.println("Left Shift num1 by 2: " + leftShiftResult);

int rightShiftResult = num2 >> 2;

System.out.println("Right Shift num2 by 2: " + rightShiftResult);

8.Ternary Operator: ?

public class Ternary{

public static void main(String[] args){

int year = 2029;

String result = year%4==0 ? “Leap year” : ”Not a leap year”;

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'.

We use double quotes to represent a string in Java. For example,

// create a string

String type = "Java programming";


Example: Create a String in Java

class Main {

public static void main(String[] args) {

// create strings

String first = "Java";

String second = "Python";

String third = "JavaScript";

// print strings

System.out.println(first); // print Java

System.out.println(second); // print Python

System.out.println(third); // print JavaScript

Java String Operations

Java provides various string methods to perform different operations on strings. We will look into some
of the commonly used string operations.

1. Get the Length of a String

To find the length of a string, we use the length() method. For example,

class Main {

public static void main(String[] args) {

// create a string

String greet = "Hello! World";

System.out.println("String: " + greet);

// get the length of greet

int length = greet.length();

System.out.println("Length: " + length);

}
}

2. Join Two Java Strings

We can join two strings in Java using the concat() method. For example,

class Main {

public static void main(String[] args) {

// create first string

String first = "Java ";

System.out.println("First String: " + first);

// create second

String second = "Programming";

System.out.println("Second String: " + second);

// join two strings

String joinedString = first.concat(second);

System.out.println("Joined String: " + joinedString);

3. Compare Two Strings

In Java, we can make comparisons between two strings using the equals() method. For example,

class Main {

public static void main(String[] args) {

// create 3 strings

String first = "java programming";

String second = "java programming";

String third = "python programming";

// compare first and second strings

boolean result1 = first.equals(second);


System.out.println("Strings first and second are equal: " + result1);

// compare first and third strings

boolean result2 = first.equals(third);

System.out.println("Strings first and third are equal: " + result2);

Control Statements | Control Flow in Java:

Java compiler executes the code from top to bottom. The statements in the code are executed according
to the order in which they appear.

Java provides three types of control flow statements.

1. Decision Making statements


o if statements
o switch statement
2. Loop statements
o do while loop
o while loop
o for loop
o for-each loop
3. Jump statements
o break statement
o continue statement

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.

Syntax of if statement is given below.

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. }

Ex: public class Student {

public static void main(String[] args) {

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:

1. public class Student {


2. public static void main(String[] args) {
3. int x = 10;
4. int y = 12;
5. if(x+y < 10) {
6. System.out.println("x + y is less than 10");
7. } else {
8. System.out.println("x + y is greater than 20");
9. }
10. }
11. }
3) if-else-if ladder:

The if-else-if statement contains the if-statement followed by multiple else-if statements.

Syntax of if-else-if statement is given below.

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:

1. public class Student {


2. public static void main(String[] args) {
3. String city = "Delhi";
4. if(city == "Meerut") {
5. System.out.println("city is meerut");
6. }else if (city == "Noida") {
7. System.out.println("city is noida");
8. }else if(city == "Agra") {
9. System.out.println("city is agra");
10. }else {
11. System.out.println(city);
12. }
13. }
14. }

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.

Syntax of Nested if-statement is given below.

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:

1. public class Student {


2. public static void main(String[] args) {
3. String address = "Delhi, India";
4.
5. if(address.endsWith("India")) {
6. if(address.contains("Meerut")) {
7. System.out.println("Your city is Meerut");
8. }else if(address.contains("Noida")) {
9. System.out.println("Your city is Noida");
10. }else {
11. System.out.println(address.split(",")[0]);
12. }
13. }else {
14. System.out.println("You are not living in India");
15. }
16. }
17. }

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.

The syntax to use the switch statement is given below.

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:

14. public class Student implements Cloneable {


15. public static void main(String[] args) {
16. int num = 2;
17. switch (num){
18. case 0:
19. System.out.println("number is 0");
20. break;
21. case 1:
22. System.out.println("number is 1");
23. break;
24. default:
25. System.out.println(num);
26. }
27. }
28. }

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.

1. for(initialization, condition, increment/decrement) {


2. //block of statements
3. }

Ex:

1. public class Calculattion {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. int sum = 0;
5. for(int j = 1; j<=10; j++) {
6. sum = sum + j;
7. }
8. System.out.println("The sum of first 10 natural numbers is " + sum);
9. }
10. }

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.

The syntax to use the for-each loop in java is given below.

1. for(data_type var : array_name/collection_name){


2. //statements
3. }
Ex:

1. public class Calculation {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. String[] names = {"Java","C","C++","Python","JavaScript"};
5. System.out.println("Printing the content of the array names:\n");
6. for(String name:names) {
7. System.out.println(name);
8. }
9. }
10. }

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.

The syntax of the while loop is given below.

1. while(condition){
2. //looping statements
3. }

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. while(i<=10) {
7. System.out.println(i);
8. i = i + 2;
9. }
10. }
11. }

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:

1. public class BreakExample {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. for(int i = 0; i<= 10; i++) {
5. System.out.println(i);
6. if(i==6) {
7. break;
8. }
9. }
10. }
11. }

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:

1. public class ContinueExample {


2. public static void main(String[] args) {
3. // TODO Auto-generated method stub
4. for(int i = 0; i<= 2; i++) {
5. for (int j = i; j<=5; j++) {
6. if(j == 4) {
7. continue;
8. }
9. System.out.println(j);
10. }
11. }
12. }
13. }

Java Arrays:

An array is a collection of similar types of data.

Declaration: dataType[] arrayName;

In Java, we can declare and allocate the memory of an array in one single statement. For example,

double[] data = new double[10];

How to Initialize Arrays in Java?

//declare and initialize and array

int[] age = {12, 4, 5, 2, 5};

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.

Example: Access Array Elements

class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5, 2, 5};

// access each array elements

System.out.println("Accessing Elements of Array:");

System.out.println("First Element: " + age[0]);

System.out.println("Second Element: " + age[1]);

System.out.println("Third Element: " + age[2]);

System.out.println("Fourth Element: " + age[3]);

System.out.println("Fifth Element: " + age[4]);

}
Example: Using For Loop

class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5};

// loop through the array

// using for loop

System.out.println("Using for Loop:");

for(int i = 0; i < age.length; i++) {

System.out.println(age[i]);

Example: Using the for-each Loop

class Main {

public static void main(String[] args) {

// create an array

int[] age = {12, 4, 5};

// loop through the array

// using for loop

System.out.println("Using for-each Loop:");

for(int a : age) {

System.out.println(a);

}
Example: Compute Sum and Average of Array Elements

class Main {

public static void main(String[] args) {

int[] numbers = {2, -9, 0, 5, 12, -25, 22, 9, 8, 12};

int sum = 0;

Double average;

// access all elements using for each loop

// add each element in sum

for (int number: numbers) {

sum += number;

// get the total number of elements

int arrayLength = numbers.length;

// calculate the average

// convert the average from int to double

average = ((double)sum / (double)arrayLength);

System.out.println("Sum = " + sum);

System.out.println("Average = " + average);

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,

double[][] matrix = {{1.2, 4.3, 4.0},

{4.1, -1.1}
};

Example: 2-dimensional Array

class MultidimensionalArray {

public static void main(String[] args) {

// create a 2d array

int[][] a = {{1, 2, 3}, {4, 5, 6, 9}, {7}, };

// calculate the length of each row

System.out.println("Length of row 1: " + a[0].length);

System.out.println("Length of row 2: " + a[1].length);

System.out.println("Length of row 3: " + a[2].length);

Example: Print all elements of 2d array Using Loop

class MultidimensionalArray {

public static void main(String[] args) {

int[][] a = {

{1, -2, 3},

{-4, -5, 6, 9},

{7},

};

for (int i = 0; i < a.length; ++i) {

for(int j = 0; j < a[i].length; ++j) {

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.

Creating an Object in Java:

o className object = new className();


o // for Bicycle class
o Bicycle sportsBicycle = new Bicycle();
o Bicycle touringBicycle = new Bicycle();

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 {

// stores the value for light

// true if light is on

// false if light is off

boolean isOn;

// method to turn on the light

void turnOn() {

isOn = true;

System.out.println("Light on? " + isOn);

// method to turnoff the light

void turnOff() {

isOn = false;

System.out.println("Light on? " + isOn);

public class Main {

public static void main(String[] args) {

// create objects led and halogen

Lamp led = new Lamp();

Lamp halogen = new Lamp();

// turn on the light by

// calling method turnOn()

led.turnOn();
// turn off the light by

// calling method turnOff()

halogen.turnOff();

Java Methods:

A method is a block of code that performs a specific task.

In Java, there are two types of 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

• modifier static returnType nameOfMethod (parameter1, parameter2, ...) {


• // method body
• }

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

1. public class Display


2. {
3. public static void main(String[] args)
4. {
5. show();
6. }
7. static void show()
8. {
9. System.out.println("It is an example of static method.");
10. }
11. }

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

1. public class InstanceMethodExample


2. {
3. public static void main(String [] args)
4. {
5. //Creating an object of the class
6. InstanceMethodExample obj = new InstanceMethodExample();
7. //invoking instance method
8. System.out.println("The sum is: "+obj.add(12, 13));
9. }
10. int s;
11. //user-defined method because we have not used static keyword
12. public int add(int a, int b)
13. {
14. s = a+b;
15. //returning the sum
16. return s;
17. }
18. }

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 {

private String name;

// constructor

Main() {

System.out.println("Constructor Called:");

name = "Programiz";

public static void main(String[] args) {

// constructor is invoked while

// creating an object of the Main class

Main obj = new Main();

System.out.println("The name is " + obj.name);

Types of Constructor

In Java, constructors can be divided into three types:

1. No-Arg Constructor
2. Parameterized Constructor
3. Default Constructor

1. Java No-Arg Constructors

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() {

// body of the constructor

Example: Java Private No-arg Constructor

class Main {

int i;

// constructor with no parameter

private Main() {

i = 5;

System.out.println("Constructor is called");

public static void main(String[] args) {

// calling the constructor without any parameter

Main obj = new Main();

System.out.println("Value of i: " + obj.i);

2. Java Parameterized Constructor:

A Java constructor can also accept one or more parameters. Such constructors are known as
parameterized constructors (constructors with parameters).

Example: Parameterized Constructor

class Main {

String languages;

// constructor accepting single value

Main(String lang) {

languages = lang;

System.out.println(languages + " Programming Language");


}

public static void main(String[] args) {

// call constructor by passing a single value

Main obj1 = new Main("Java");

Main obj2 = new Main("Python");

Main obj3 = new Main("C");

3. Java Default Constructor:

If we do not create any constructor, the Java compiler automatically creates a no-arg constructor during
the execution of the program.

This constructor is called the default constructor.

Example: Default Constructor

class Main {

int a;

boolean b;

public static void main(String[] args) {

// calls default constructor

Main obj = new Main();

System.out.println("Default Value:");

System.out.println("a = " + obj.a);

System.out.println("b = " + obj.b);

}
Important Notes on Java Constructors

• Constructors are invoked implicitly when you instantiate objects.


• The two rules for creating a constructor are:
1. The name of the constructor should be the same as the class.
2. A Java constructor must not have a return type.
• If a class doesn't have a constructor, the Java compiler automatically creates a default
constructor during run-time. The default constructor initializes instance variables with default
values. For example, the int variable will be initialized to 0
• A constructor cannot be abstract or static or final.

• A constructor can be overloaded but can not be overridden.

Java this Keyword:


In Java, this keyword is used to refer to the current object inside a method or a constructor. For example,
class Main {
int instVar;
Main(int instVar){
this.instVar = instVar;
System.out.println("this reference = " + this);
}
public static void main(String[] args) {
Main obj = new Main(8);
System.out.println("object reference = " + obj);
}
}

Java Access Modifiers

What are Access Modifiers?

In Java, access modifiers are used to set the accessibility (visibility)


of classes, interfaces, variables, methods, constructors, data members, and the setter methods. For
example,

class Animal {

public void method1() {...}

private void method2() {...}

}
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)

Private declarations are visible within the class only

Protected declarations are visible within the package or all subclasses

Public declarations are visible everywhere

Default Access Modifier

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");

Private Access Modifier:

When variables and methods are declared private, they cannot be accessed outside of the class. For
example,

class Data {

// private variable

private String name;

public class Main {

public static void main(String[] main){

// create an object of Data


Data d = new Data();

// access private variable and field from another class

d.name = "Programiz";

Protected Access Modifier:

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

protected void display() {

System.out.println("I am an animal");

class Dog extends Animal {

public static void main(String[] args) {

// create an object of Dog class

Dog dog = new Dog();

// access protected method

dog.display();

Public Access Modifier:

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 int legCount;

// public method

public void display() {

System.out.println("I am an animal.");

System.out.println("I have " + legCount + " legs.");

// Main.java

public class Main {

public static void main( String[] args ) {

// accessing the public class

Animal animal = new Animal();

// accessing the public variable

animal.legCount = 4;

// accessing the public method

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).

The extends keyword is used to perform inheritance in Java. For example,

class Animal {

// methods and fields


}

// use of extends keyword

// to perform inheritance

class Dog extends Animal {

// methods and fields of Animal

// methods and fields of Dog

Types of inheritance in java

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. }}

Q) Why multiple inheritance is not supported in java?

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 {

public void getType();

public void getVersion();

Implementing an Interface

Like abstract classes, we cannot create objects of interfaces.

To use an interface, other classes must implement it. We use the implements keyword to implement an
interface.

Ex:

interface Polygon {

void getArea(int length, int breadth);

// implement the Polygon interface

class Rectangle implements Polygon {

// implementation of abstract method

public void getArea(int length, int breadth) {

System.out.println("The area of the rectangle is " + (length * breadth));

class Main {
public static void main(String[] args) {

Rectangle r1 = new Rectangle();

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.

Example: Java Polymorphism

class Polygon {

// method to render a shape

public void render() {

System.out.println("Rendering Polygon...");

class Square extends Polygon {

// renders Square

public void render() {

System.out.println("Rendering Square...");

class Circle extends Polygon {

// renders circle

public void render() {

System.out.println("Rendering Circle...");
}

class Main {

public static void main(String[] args) {

// create an object of Square

Square s1 = new Square();

s1.render();

// create an object of Circle

Circle c1 = new Circle();

c1.render();

1. Java Method Overriding

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.

Example 1: Polymorphism using method overriding

class Language {

public void displayInfo() {

System.out.println("Common English Language");

class Java extends Language {

@Override

public void displayInfo() {

System.out.println("Java Programming Language");

}
}

class Main {

public static void main(String[] args) {

// create an object of Java class

Java j1 = new Java();

j1.displayInfo();

// create an object of Language class

Language l1 = new Language();

l1.displayInfo();

2. Java Method Overloading

In a Java class, we can create methods with the same name if they differ in parameters. For example,

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ... }

This is known as method overloading in Java. Here, the same method will perform different operations
based on the parameter.

Example 3: Polymorphism using method overloading

class Pattern {

// method without parameter

public void display() {

for (int i = 0; i < 10; i++) {

System.out.print("*");

}
// method with single parameter

public void display(char symbol) {

for (int i = 0; i < 10; i++) {

System.out.print(symbol);

class Main {

public static void main(String[] args) {

Pattern d1 = new Pattern();

// call method without any argument

d1.display();

System.out.println("\n");

// call method with a single argument

d1.display('#');

}}

Java Abstract Class and Abstract Methods

Java Abstract Class:

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,

// create an abstract class

abstract class Language {

// fields and methods

// try to create an object Language

// throws an error

Language obj = new Language();


An abstract class can have both the regular methods and abstract methods. For example,

abstract class Language {

// abstract method

abstract void method1();

// regular method

void method2() {

System.out.println("This is regular method");

Java Abstract Method:

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,

abstract void display();

Here, display() is an abstract method. The body of display() is replaced by ;.

If a class contains an abstract method, then the class should be declared abstract. Otherwise, it will
generate an error. For example,

// error

// class should be abstract

class Language {

// abstract method

abstract void method1();

Example: Java Abstract Class and 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,

abstract class Language {

// method of abstract class

public void display() {


System.out.println("This is Java Programming");

class Main extends Language {

public static void main(String[] args) {

// create an object of Main

Main obj = new Main();

// access method of abstract class

// using object of Main class

obj.display();

Example 3: Java Abstraction

abstract class MotorBike {

abstract void brake();

class SportsBike extends MotorBike {

// implementation of abstract method

public void brake() {

System.out.println("SportsBike Brake");

class MountainBike extends MotorBike {

// implementation of abstract method

public void brake() {

System.out.println("MountainBike Brake");
}

class Main {

public static void main(String[] args) {

MountainBike m1 = new MountainBike();

m1.brake();

SportsBike s1 = new SportsBike();

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.

Example 1: Java Encapsulation

class Area {

// fields to calculate area

int length;

int breadth;

// constructor to initialize values

Area(int length, int breadth) {

this.length = length;

this.breadth = breadth;

// method to calculate area

public void getArea() {


int area = length * breadth;

System.out.println("Area: " + area);

class Main {

public static void main(String[] args) {

// create object of Area

// pass value of length and breadth

Area rectangle = new Area(5, 6);

rectangle.getArea();

Java super: The super keyword in Java is used in subclasses to access superclass members
(attributes, constructors and methods).

Example 2: super to Call Superclass Method

class Animal {

// overridden method

public void display(){

System.out.println("I am an animal");

class Dog extends Animal {

// overriding method

@Override

public void display(){

System.out.println("I am a dog");

}
public void printMessage(){

// this calls overriding method

display();

// this calls overridden method

super.display();

class Main {

public static void main(String[] args) {

Dog dog1 = new Dog();

dog1.printMessage();

Exception Handling in Java:

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.

What is Exception Handling?

Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException,


IOException, SQLException, RemoteException, etc.

Hierarchy of Java Exception classes

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

Error is irrecoverable. Some example of errors are OutOfMemoryError, VirtualMachineError,


AssertionError etc.
Java Exception Keywords:

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:

The "throw" keyword is used to throw an exception.

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

1. public class JavaExceptionExample{


2. public static void main(String args[]){
3. try{
4. //code that may raise exception
5. int data=100/0;
6. }catch(ArithmeticException e){System.out.println(e);}
7. //rest code of the program
8. System.out.println("rest of the code...");
9. }
10. }
Example: Java Exception Handling using finally block

class Main {

public static void main(String[] args) {

try {

// code that generates exception

int divideByZero = 5 / 0;

catch (ArithmeticException e) {

System.out.println("ArithmeticException => " + e.getMessage());

finally {

System.out.println("This is the finally block");

3. Java throw and throws keyword

The Java throw keyword is used to explicitly throw a single exception.

When we throw an exception, the flow of the program moves from the try block to the catch block.

Example: Exception handling using Java throw

class Main {

public static void divideByZero() {

// throw an exception

throw new ArithmeticException("Trying to divide by 0");

public static void main(String[] args) {


divideByZero();

Example: Java throws keyword

import java.io.*;

class Main {

// declareing the type of exception

public static void findFile() throws IOException {

// code that may generate IOException

File newFile = new File("test.txt");

FileInputStream stream = new FileInputStream(newFile);

public static void main(String[] args) {

try {

findFile();

catch (IOException e) {

System.out.println(e);

Multithreading in Java:

Multithreading in Java is a process of executing multiple threads simultaneously.

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing and


multithreading, both are used to achieve multitasking.

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 Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)

o Each process has an address in memory. In other words, each process allocates a separate
memory area.
o A process is heavyweight.

2) Thread-based Multitasking (Multithreading)

o Threads share the same address space.


o A thread is lightweight.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't affect other threads. It uses
a shared memory area.

Life cycle of a Thread (Thread States):

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

Thread Scheduler in Java:


A component of Java that decides which thread to run or execute and which thread to wait is called
a thread scheduler in Java.

How to create a thread in Java


There are two ways to create a thread:
1. By extending Thread class
2. By implementing Runnable interface.

1) Java Thread Example by extending Thread class

1. Ex: class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

2) Java Thread Example by implementing Runnable interface

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi3 m1=new Multi3();
7. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
8. t1.start();
9. }
10. }
Java Wrapper Class: The wrapper classes in Java are used to convert primitive
types (int, char, float, etc) into corresponding objects.
Each of the 8 primitive types has corresponding wrapper classes.
int -> Integer
float -> Float
long -> Long
double -> Double
short -> Short
char -> Character
String -> String
Boolean -> Boolean
Collections:
A collection is a group of objects. In Java, these objects are called elements of the collection.
Types of Objects Stored in Collection (Container) Object
1. Homogeneous objects:
Homo means same. Homogeneous objects are a group of multiple objects that belong to the same
class.
For example, suppose we have created three objects Student s1, Student s2, and Student s3 of the
same class ‘Student’. Since these three objects belong to the same class that’s why they are called
homogeneous objects.
2. Heterogeneous objects:
Hetero means different. Heterogeneous objects are a group of different objects that belong to
different classes.
For example, suppose we have created two different objects of different classes such as one object
Student s1, and another one object Employee e1. Here, student and employee objects together are
called a collection of heterogeneous objects.
These objects can also be further divided into two types. They are as follows:
1. Duplicate objects:
The multiple objects of a class that contains the same data are called duplicate objects. For example,
suppose we create two person objects Person p1 and Person p2. Both of these objects have the same
data.
Person p1 = new Person( "abc");
Person p2 = new Person("abc");
Since the above two objects have the same data “abc” therefore, these are called duplicate objects.
2. Unique objects:
The multiple objects of a class that contains different data are called unique objects. For example:
Person p1 = new Person("abcd");
Person p2 = new Person("abcde");

What is Collections Framework in Java?


A framework in java is a set of several classes and interfaces which provide a ready-made
architecture.
Collection Hierarchy in Java
The hierarchy of the entire collection framework consists of four core interfaces such as Collection,
List, Set, Map, and two specialized interfaces named SortedSet and SortedMap for sorting.
# The basic interface of the collections framework is the Collection interface which is the root
interface of all collections in the API (Application programming interface).
# The Collection interface extends the Iterable interface. The iterable interface has only one method
called iterator(). The function of the iterator method is to return the iterator object. Using this iterator
object, we can iterate over the elements of the collection.
# List, Queue, and Set have three component which extends the Collection interface. A map is not
inherited by Collection interface.
Methods of Collection Interface in Java
The Collection interface consists of a total of fifteen methods for manipulating elements in the
collection. They are as follows:
1. add(): This method is used to add or insert an element in the collection. The general syntax for
add() method is as follow:
add(Object element) : boolean
If the element is added to the collection, it will return true otherwise false, if the element is already
present and the collection doesn’t allow duplicates.
2. addAll(): This method adds a collection of elements to the collection. It returns true if the
elements are added otherwise returns false. The general syntax for this method is as follows:
addAll(Collection c) : Boolean
3. clear(): This method clears or removes all the elements from the collection. The general form of
this method is as follows:
clear() : void
This method returns nothing.
4. equals(): It checks for equality with another object. The general form is as follows:
equals(Object element) : Boolean
5. isEmpty(): It returns true if a collection is empty. That is, this method returns true if the collection
contains no elements.
isEmpty() : boolean
6. iterator(): It returns an iterator. The general form is given below:
iterator() : Iterator
7. remove(): It removes a specified element from the collection. The general syntax is given below:
remove(Object element) : boolean
This method returns true if the element was removed. Otherwise, it returns false.
8. removeAll(): The removeAll() method removes all elements from the collection. It returns true
if all elements are removed otherwise returns false.
removeAll(Collection c) : boolean
9. retainAll(): This method is used to remove all elements from the collection except the specified
collection. It returns true if all the elements are removed otherwise returns false.
retainAll(Collection c) : boolean
10. size(): The size() method returns the total number of elements in the collection. Its return type
is an integer. The general syntax is given below:
size() : int
11. toArray(): It returns the elements of a collection in the form of an array. The array elements are
copies of the collection elements.
toArray() : Object[]
List Interface:
A list in Java is a collection for storing elements in sequential order. Sequential order means the
first element, followed by the second element, followed by the third element, and so on.

Implementation of the List Interface


1. Implementing the ArrayList Class
import java.util.List;
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// Creating list using the ArrayList class
List<Integer> numbers = new ArrayList<>();
// Add elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);
// Access element from the list
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
// Remove element from the list
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}

Iterate through an ArrayList


We can use the Java for-each loop to loop through each element of the arraylist. For example,
import java.util.ArrayList;
class Main {
public static void main(String[] args) {
// creating an array list
ArrayList<String> animals = new ArrayList<>();
animals.add("Cow");
animals.add("Cat");
animals.add("Dog");
System.out.println("ArrayList: " + animals);
// iterate using for-each loop
System.out.println("Accessing individual elements: ");
for (String language : animals) {
System.out.print(language);
System.out.print(", ");
}
}
}

2. Implementing the LinkedList Class


import java.util.List;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// Creating list using the LinkedList class
List<Integer> numbers = new LinkedList<>();
// Add elements to the list
numbers.add(1);
numbers.add(2);
numbers.add(3);
System.out.println("List: " + numbers);
// Access element from the list
int number = numbers.get(2);
System.out.println("Accessed Element: " + number);
// Using the indexOf() method
int index = numbers.indexOf(2);
System.out.println("Position of 3 is " + index);
// Remove element from the list
int removedNumber = numbers.remove(1);
System.out.println("Removed Element: " + removedNumber);
}
}

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(", ");
}
}
}

Java Stack Class:


The Java collections framework has a class named Stack that provides the functionality of the stack
data structure.
The Stack class extends the Vector class.
Stack Implementation
In stack, elements are stored and accessed in Last In First Out manner. That is, elements are added to
the top of the stack and removed from the top of the stack.
Creating a Stack
In order to create a stack, we must import the java.util.Stack package first. Once we import the package,
here is how we can create a stack in Java.
Stack<Type> stacks = new Stack<>();
Ex:
import java.util.Stack;
class Main {
public static void main(String[] args) {
Stack<String> animals= new Stack<>();
// Add elements to Stack
animals.push("Dog");
animals.push("Horse");
animals.push("Cat");
System.out.println("Stack: " + animals);
String element = animals.pop();
System.out.println("Removed Element: " + element);
String element = animals.peek();
System.out.println("Element at top: " + element);
int position = animals.search("Horse");
System.out.println("Position of Horse: " + position);
boolean result = animals.empty();
System.out.println("Is the stack empty? " + result);
}
}

Java Queue Interface


The Queue interface of the Java collections framework provides the functionality of the queue data
structure. It extends the Collection interface.
Classes that Implement Queue
Since the Queue is an interface, we cannot provide the direct implementation of it.
In order to use the functionalities of Queue, we need to use classes that implement it:
• ArrayDeque
• LinkedList
• PriorityQueue
Interfaces that extend Queue
The Queue interface is also extended by various subinterfaces:
• Deque
• BlockingQueue
• BlockingDeque

Implementation of the Queue Interface

1. Implementing the LinkedList Class


import java.util.Queue;
import java.util.LinkedList;
class Main {
public static void main(String[] args) {
// Creating Queue using the LinkedList class
Queue<Integer> numbers = new LinkedList<>();
// offer elements to the Queue
numbers.offer(1);
numbers.offer(2);
numbers.offer(3);
System.out.println("Queue: " + numbers);
// Access elements of the Queue
int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);
// Remove elements from the Queue
int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);
System.out.println("Updated Queue: " + numbers);
}
}

2. Implementing the PriorityQueue Class


import java.util.Queue;
import java.util.PriorityQueue;
class Main {
public static void main(String[] args) {
// Creating Queue using the PriorityQueue class
Queue<Integer> numbers = new PriorityQueue<>();
// offer elements to the Queue
numbers.offer(5);
numbers.offer(1);
numbers.offer(2);
System.out.println("Queue: " + numbers);
// Access elements of the Queue
int accessedNumber = numbers.peek();
System.out.println("Accessed Element: " + accessedNumber);

// Remove elements from the Queue


int removedNumber = numbers.poll();
System.out.println("Removed Element: " + removedNumber);
System.out.println("Updated Queue: " + numbers);
}
}
Java Deque Interface
The Deque interface of the Java collections framework provides the functionality of a double-ended
queue. It extends the Queue interface.
Methods of Deque
Since Deque extends the Queue interface, it inherits all the methods of the Queue interface.
• addFirst() - Adds the specified element at the beginning of the deque. Throws an exception if
the deque is full.
• addLast() - Adds the specified element at the end of the deque. Throws an exception if the
deque is full.
• offerFirst() - Adds the specified element at the beginning of the deque. Returns false if the
deque is full.
• offerLast() - Adds the specified element at the end of the deque. Returns false if the deque is
full.
• getFirst() - Returns the first element of the deque. Throws an exception if the deque is empty.
• getLast() - Returns the last element of the deque. Throws an exception if the deque is empty.
• peekFirst() - Returns the first element of the deque. Returns null if the deque is empty.
• peekLast() - Returns the last element of the deque. Returns null if the deque is empty.
• removeFirst() - Returns and removes the first element of the deque. Throws an exception if
the deque is empty.
• removeLast() - Returns and removes the last element of the deque. Throws an exception if the
deque is empty.
• pollFirst() - Returns and removes the first element of the deque. Returns null if the deque is
empty.
• pollLast() - Returns and removes the last element of the deque. Returns null if the deque is
empty.

Implementation of Deque in ArrayDeque Class


import java.util.Deque;
import java.util.ArrayDeque;
class Main {
public static void main(String[] args) {
// Creating Deque using the ArrayDeque class
Deque<Integer> numbers = new ArrayDeque<>();
// add elements to the Deque
numbers.offer(1);
numbers.offerLast(2);
numbers.offerFirst(3);
System.out.println("Deque: " + numbers);
// Access elements of the Deque
int firstElement = numbers.peekFirst();
System.out.println("First Element: " + firstElement);
int lastElement = numbers.peekLast();
System.out.println("Last Element: " + lastElement);
// Remove elements from the Deque
int removedNumber1 = numbers.pollFirst();
System.out.println("Removed First Element: " + removedNumber1);
int removedNumber2 = numbers.pollLast();
System.out.println("Removed Last Element: " + removedNumber2);
System.out.println("Updated Deque: " + numbers);
}
}

Java Set Interface


The Set interface of the Java Collections framework provides the features of the mathematical set in
Java. It extends the Collection interface.
Unlike the List interface, sets cannot contain duplicate elements.
Classes that implement Set
Since Set is an interface, we cannot create objects from it.
In order to use functionalities of the Set interface, we can use these classes:
• HashSet
• LinkedHashSet
• EnumSet
• TreeSet
Methods of Set
The Set interface includes all the methods of the Collection interface. It's because Collection is a super
interface of Set.
Some of the commonly used methods of the Collection interface that's also available in the Set interface
are:
• add() - adds the specified element to the set
• addAll() - adds all the elements of the specified collection to the set
• iterator() - returns an iterator that can be used to access elements of the set sequentially
• remove() - removes the specified element from the set
• removeAll() - removes all the elements from the set that is present in another specified set
• retainAll() - retains all the elements in the set that are also present in another specified set
• clear() - removes all the elements from the set
• size() - returns the length (number of elements) of the set
• toArray() - returns an array containing all the elements of the set
• contains() - returns true if the set contains the specified element
• containsAll() - returns true if the set contains all the elements of the specified collection
• hashCode() - returns a hash code value (address of the element in the set)
Set Operations:
The Java Set interface allows us to perform basic mathematical set operations like union, intersection,
and subset.
• Union - to get the union of two sets x and y, we can use x.addAll(y)
• Intersection - to get the intersection of two sets x and y, we can use x.retainAll(y)
• Subset - to check if x is a subset of y, we can use y.containsAll(x)

Implementation of the Set Interface

1. Implementing HashSet Class

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);
}
}

2. Implementing TreeSet Class


import java.util.Set;
import java.util.TreeSet;
import java.util.Iterator;
class Main {
public static void main(String[] args) {
// Creating a set using the TreeSet class
Set<Integer> numbers = new TreeSet<>();
// Add elements to the set
numbers.add(2);
numbers.add(3);
numbers.add(1);
System.out.println("Set using TreeSet: " + numbers);
// Access Elements using iterator()
System.out.print("Accessing elements using iterator(): ");
Iterator<Integer> iterate = numbers.iterator();
while(iterate.hasNext()) {
System.out.print(iterate.next());
System.out.print(", ");
}
}
}
Java LinkedHashSet

The LinkedHashSet class of the Java collections framework provides functionalities of both
the hashtable and the linked list data structure.

It implements the Set interface.

Elements of LinkedHashSet are stored in hash tables similar to HashSet.

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.

// LinkedHashSet with 8 capacity and 0.75 load factor

LinkedHashSet<Integer> numbers = new LinkedHashSet<>(8, 0.75);

Here, we have created a linked hash set named numbers.

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.

Creating LinkedHashSet from Other Collections

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 {

public static void main(String[] args) {

// Creating an arrayList of even numbers

ArrayList<Integer> evenNumbers = new ArrayList<>();


evenNumbers.add(2);

evenNumbers.add(4);

System.out.println("ArrayList: " + evenNumbers);

// Creating a LinkedHashSet from an ArrayList

LinkedHashSet<Integer> numbers = new LinkedHashSet<>(evenNumbers);

System.out.println("LinkedHashSet: " + numbers);

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 {

public static void main(String[] args) {

LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();

evenNumbers.add(2);

evenNumbers.add(4);

System.out.println("LinkedHashSet1: " + evenNumbers);

LinkedHashSet<Integer> numbers = new LinkedHashSet<>();

numbers.add(1);

numbers.add(3);

System.out.println("LinkedHashSet2: " + numbers);

// Union of two set

numbers.addAll(evenNumbers);

System.out.println("Union is: " + numbers);


}

Intersection of Sets

To perform the intersection between two sets, we can use the retainAll() method. For example

import java.util.LinkedHashSet;

class Main {

public static void main(String[] args) {

LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();

primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("LinkedHashSet1: " + primeNumbers);

LinkedHashSet<Integer> evenNumbers = new LinkedHashSet<>();

evenNumbers.add(2);

evenNumbers.add(4);

System.out.println("LinkedHashSet2: " + evenNumbers);

// Intersection of two sets

evenNumbers.retainAll(primeNumbers);

System.out.println("Intersection is: " + evenNumbers);

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 {

public static void main(String[] args) {

LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();


primeNumbers.add(2);

primeNumbers.add(3);

primeNumbers.add(5);

System.out.println("LinkedHashSet1: " + primeNumbers);

LinkedHashSet<Integer> oddNumbers = new LinkedHashSet<>();

oddNumbers.add(1);

oddNumbers.add(3);

oddNumbers.add(5);

System.out.println("LinkedHashSet2: " + oddNumbers);

// Difference between LinkedHashSet1 and LinkedHashSet2

primeNumbers.removeAll(oddNumbers);

System.out.println("Difference : " + primeNumbers);

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 {

public static void main(String[] args) {

LinkedHashSet<Integer> numbers = new LinkedHashSet<>();

numbers.add(1);

numbers.add(2);

numbers.add(3);

numbers.add(4);

System.out.println("LinkedHashSet1: " + numbers);

LinkedHashSet<Integer> primeNumbers = new LinkedHashSet<>();


primeNumbers.add(2);

primeNumbers.add(3);

System.out.println("LinkedHashSet2: " + primeNumbers);

// Check if primeNumbers is a subset of numbers

boolean result = numbers.containsAll(primeNumbers);

System.out.println("Is LinkedHashSet2 is subset of LinkedHashSet1? " + result);

Java Type Casting:

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.

1. Widening Type Casting

2. Narrowing Type Casting

Widening Type Casting

In Widening Type Casting, Java automatically converts one data type to another data type.

Ex: class Main {

public static void main(String[] args) {

// create int type variable

int num = 10;

System.out.println("The integer value: " + num);

// convert into double type

double data = num;

System.out.println("The double value: " + data);


}

Narrowing Type Casting

In Narrowing Type Casting, we manually convert one data type into another using the parenthesis.

Example: Converting double into an int

class Main {

public static void main(String[] args) {

// create double type variable

double num = 10.99;

System.out.println("The double value: " + num);

// convert into int type

int data = (int)num;

System.out.println("The integer value: " + data);

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.

Example 1: Type conversion from int to String

class Main {

public static void main(String[] args) {

// create int type variable

int num = 10;

System.out.println("The integer value is: " + num);

// converts int to string type

String data = String.valueOf(num);

System.out.println("The string value is: " + data);


}

Java File Class

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.

File and Directory

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.

A directory is a collection of files and subdirectories. A directory inside a directory is known as


subdirectory.

Create a Java File Object

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.

// creates an object of File using the path

File file = new File(String pathName);

Java File Operation Methods

Operation Method Package

To create file createNewFile() java.io.File

To read file read() java.io.FileReader

To write file write() java.io.FileWriter

To delete file delete() java.io.File

Example: Create a new File

// importing the File class

import java.io.File;

class Main {
public static void main(String[] args) {

// create a file object for the current location

File file = new File("newFile.txt");

try {

// trying to create a file based on the object

boolean value = file.createNewFile();

if (value) {

System.out.println("The new file is created.");

else {

System.out.println("The file already exists.");

catch(Exception e) {

e.getStackTrace();

Example: Read a file using FileReader

Suppose we have a file named input.txt with the following content.

// importing the FileReader class

import java.io.FileReader;

class Main {

public static void main(String[] args) {

char[] array = new char[100];

try {
// Creates a reader using the FileReader

FileReader input = new FileReader("input.txt");

// Reads characters

input.read(array);

System.out.println("Data in the file:");

System.out.println(array);

// Closes the reader

input.close();

catch(Exception e) {

e.getStackTrace();

Java write to files:

To write data to the file, we can use subclasses of either OutputStream or Writer.

Example: Write to file using FileWriter

// importing the FileWriter class

import java.io.FileWriter;

class Main {

public static void main(String args[]) {

String data = "This is the data in the output file";

try {

// Creates a Writer using FileWriter

FileWriter output = new FileWriter("output.txt");

// Writes string to the file


output.write(data);

System.out.println("Data is written to the file.");

// Closes the writer

output.close();

catch (Exception e) {

e.getStackTrace();

Java delete files

We can use the delete() method of the File class to delete the specified file or directory.

Example: Delete a file

import java.io.File;

class Main {

public static void main(String[] args) {

// creates a file object

File file = new File("file.txt");

// deletes the file

boolean value = file.delete();

if(value) {

System.out.println("The File is deleted.");

else {

System.out.println("The File is not deleted.");

}}}

You might also like