1. What is Programming Language?
2. Types of programming languages
3. Java Introduction
4. History of Java
5. Principles of Java
6. Java Installation
7. Java Program Execution Flow
8. JDK vs JRE JVM Architecture
9. Identifiers & Keywords
10. Data Types
11. Variables
12. Methods
13. Arrays
14. Strings Handling
15. Object Oriented Principles
16. Constructors
17. Interfaces
18. Programs related to OOPs
19. Final classes
20. Abstract Class
21. Exception handling
22. Multi-Threading
23. Synchronization
24. Lock mechanism
25. Serialization
26. Wrapper classes
27. Auto Boxing, Un-Boxing
28. Java Memory Management
29. Class Loader Implementation
30. Variable Arguments
31. File IO Operations
32. Introduction to Collection Framework
33. List
34. Set
35. Map
37. Properties
37. Internal implementation of collection framework (List, Map, Set etc)
38. Java 8 Features Introduction
39. Lambda Expressions
40. Functional Interfaces
41. Default & Static Methods
42. Method References
43. Date and Time API change
44. Stream API
45. Optional class
46. SplIterator
Initial release
Java is a programming language and platform known for its high-level, robust, object-oriented, and secure nature.
Java was developed by Sun Microsystems (now a subsidiary of Oracle) in 1995. James Gosling, known as the father of Java, initially named it Oak. However, due to trademark issues, the name was changed to Java.
The history of Java is very interesting. Java was originally designed for interactive television, but it was too advanced technology for the digital cable television industry at the time. The history of Java starts with the Green Team.
Java team members (also known as Green Team), initiated this project to develop a language for digital devices such as set-top boxes, televisions, etc. However, it was best suited for internet programming.
Later, Java technology was incorporated by Netscape.
The principles for creating Java programming were "Simple, Robust, Portable, Platform-independent, Secured, High Performance, Multithreaded, Architecture Neutral, Object-Oriented, Interpreted, and Dynamic".
Java was developed by James Gosling, who is known as the father of Java, in 1995. James Gosling and his team members started the project in the early '90s.
It is mainly responsible for three activities.
Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method area. For each “.class” file, JVM stores the following information in the method area.
The fully qualified name of the loaded class and its immediate parent class.
Whether the “.class” file is related to Class or Interface or Enum. Modifier, Variables and Method information etc. After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory. Please note that this object is of type Class predefined in java.lang package. These Class object can be used by the programmer for getting class level information like the name of the class, parent name, methods and variable information etc. To get this object reference we can use getClass() method of Object class Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load request to extension class loader and extension class loader delegate request to the bootstrap class loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to the extension class loader and then to the system class loader. At last, if the system class loader fails to load class, then we get run-time exception java.lang.ClassNotFoundException.
| Modifiers | Within Class | Within Package | Outside Package by subclass only | Outside Package |
|---|---|---|---|---|
| Private | Yes | No | No | No |
| Default | Yes | Yes | No | No |
| Protected | Yes | Yes | Yes | No |
| Public | Yes | Yes | Yes | Yes |
Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:
The primitive data types include boolean, char, byte, short, int, long, float, and double.
The non-primitive data types include String,Classes, Interfaces, and Arrays.
In Java language, primitive data types are the building blocks of data manipulation. These are the most basic data types available in the Java language.
The boolean data type represents true or false values.
The byte data type is an 8-bit signed two's complement integer.
The char data type represents a single 16-bit Unicode character.
The short data type is a 16-bit signed two's complement integer.
The int data type is a 32-bit signed two's complement integer.
The long data type is a 64-bit signed two's complement integer.
The float data type is a single-precision 32-bit IEEE 754 floating-point.
The double data type is a double-precision 64-bit IEEE 754 floating-point.
| Data Type | Default Value | Default Size |
|---|---|---|
| boolean | false | 1 bit |
| char | '\u0000' | 2 bytes |
| byte | 0 | 1 byte |
| short | 0 | 2 bytes |
| int | 0 | 4 bytes |
| long | 0L | 8 bytes |
| float | 0.0f | 4 bytes |
| double | 0.0d | 8 bytes |
| Primitive Type | Wrapper Class |
|---|---|
| boolean | Boolean |
| char | Character |
| byte | Byte |
| short | Short |
| int | Integer |
| long | Long |
| float | Float |
| double | Double |
Auto-boxing:the process of Converting primitive types to wrapper classes automatically
Auto-unboxing: the process of Converting wrapper classes to primitive types automatically
public class AutoBoxingUnboxingExample {
public static void main(String[] args) {
// Auto-boxing: Converting primitive types to wrapper classes automatically
Byte wrappedByte = 123; // byte to Byte
Short wrappedShort = 1000; // short to Short
Integer wrappedInt = 42; // int to Integer
Long wrappedLong = 123456789L; // long to Long
Float wrappedFloat = 3.14f; // float to Float
Double wrappedDouble = 2.71828; // double to Double
Character wrappedChar = 'A'; // char to Character
Boolean wrappedBoolean = true; // boolean to Boolean
// Displaying values after auto-boxing
System.out.println("Wrapped Byte: " + wrappedByte);
System.out.println("Wrapped Short: " + wrappedShort);
System.out.println("Wrapped Integer: " + wrappedInt);
System.out.println("Wrapped Long: " + wrappedLong);
System.out.println("Wrapped Float: " + wrappedFloat);
System.out.println("Wrapped Double: " + wrappedDouble);
System.out.println("Wrapped Character: " + wrappedChar);
System.out.println("Wrapped Boolean: " + wrappedBoolean);
// Auto-unboxing: Converting wrapper classes to primitive types automatically
byte unwrappedByte = wrappedByte; // Byte to byte
short unwrappedShort = wrappedShort; // Short to short
int unwrappedInt = wrappedInt; // Integer to int
long unwrappedLong = wrappedLong; // Long to long
float unwrappedFloat = wrappedFloat; // Float to float
double unwrappedDouble = wrappedDouble; // Double to double
char unwrappedChar = wrappedChar; // Character to char
boolean unwrappedBoolean = wrappedBoolean; // Boolean to boolean
// Displaying values after auto-unboxing
System.out.println("Unwrapped Byte: " + unwrappedByte);
System.out.println("Unwrapped Short: " + unwrappedShort);
System.out.println("Unwrapped Integer: " + unwrappedInt);
System.out.println("Unwrapped Long: " + unwrappedLong);
System.out.println("Unwrapped Float: " + unwrappedFloat);
System.out.println("Unwrapped Double: " + unwrappedDouble);
System.out.println("Unwrapped Character: " + unwrappedChar);
System.out.println("Unwrapped Boolean: " + unwrappedBoolean);
}
}
Out put
=============
Wrapped Byte : 123
Wrapped Short : 1000
Wrapped Integer : 42
Wrapped Long : 123456789
Wrapped Float : 3.14
Wrapped Double : 2.71828
Wrapped Character : A
Wrapped Boolean : true
Unwrapped Byte : 123
Unwrapped Short : 1000
Unwrapped Integer : 42
Unwrapped Long : 123456789
Unwrapped Float : 3.14
Unwrapped Double : 2.71828
Unwrapped Character: A
Unwrapped Boolean : true
| Keyword | Keyword | Keyword | Keyword | Keyword | Keyword | Keyword | Keyword |
|---|---|---|---|---|---|---|---|
| abstract | assert | boolean | break | byte | case | catch | char |
| class | const | continue | default | do | double | else | enum |
| extends | final | finally | float | for | goto | if | implements |
| import | instanceof | int | interface | long | native | new | package |
| private | protected | public | return | short | static | strictfp | super |
| switch | synchronized | this | throw | throws | transient | try | void |
| volatile | while |
1.boolean: Java boolean keyword is used to declare a variable as a boolean type. It can hold True and False values only.
2.break: Java break keyword is used to break the loop or switch statement. It breaks the current flow of the program at specified conditions.
3.byte: Java byte keyword is used to declare a variable that can hold 8-bit data values.
4.case: Java case keyword is used with the switch statements to mark blocks of text.
5.catch: Java catch keyword is used to catch the exceptions generated by try statements. It must be used after the try block only.
6.char: Java char keyword is used to declare a variable that can hold unsigned 16-bit Unicode characters.
7.class: Java class keyword is used to declare a class.
8.continue: Java continue keyword is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
9.default: Java default keyword is used to specify the default block of code in a switch statement.
10.do: Java do keyword is used in the control statement to declare a loop. It can iterate a part of the program several times.
11.double: Java double keyword is used to declare a variable that can hold 64-bit floating-point number.
12.else: Java else keyword is used to indicate the alternative branches in an if statement.
13.enum: Java enum keyword is used to define a fixed set of constants. Enum constructors are always private or default.
14.extends: Java extends keyword is used to indicate that a class is derived from another class or interface.
15.final: Java final keyword is used to indicate that a variable holds a constant value. It is used with a variable. It is used to restrict the user from updating the value of the variable.
16.finally: Java finally keyword indicates a block of code in a try-catch structure. This block is always executed whether an exception is handled or not.
17.float: Java float keyword is used to declare a variable that can hold a 32-bit floating-point number.
18for: Java for keyword is used to start a for loop. It is used to execute a set of instructions/functions repeatedly when some condition becomes true. If the number of iteration is fixed, it is recommended to use for loop.
19.if: Java if keyword tests the condition. It executes the if block if the condition is true.
20.implements: Java implements keyword is used to implement an interface.
21.import: Java import keyword makes classes and interfaces available and accessible to the current source code.
22.instanceof: Java instanceof keyword is used to test whether the object is an instance of the specified class or implements an interface.
23.int: Java int keyword is used to declare a variable that can hold a 32-bit signed integer.
24.interface: Java interface keyword is used to declare an interface. It can have only abstract methods.
25.long: Java long keyword is used to declare a variable that can hold a 64-bit integer.
26.abstract: Java abstract keyword is used to declare an abstract class. An abstract class can provide the implementation of the interface. It can have abstract and non-abstract methods.
27.native: Java native keyword is used to specify that a method is implemented in native code using JNI (Java Native Interface).
28.new: Java new keyword is used to create new objects.
29.null: Java null keyword is used to indicate that a reference does not refer to anything. It removes the garbage value.
30.package: Java package keyword is used to declare a Java package that includes the classes.
31.private: Java private keyword is an access modifier. It is used to indicate that a method or variable may be accessed only in the class in which it is declared.
32.protected: Java protected keyword is an access modifier. It can be accessible within the package and outside the package but through inheritance only. It can't be applied with the class.
33.public: Java public keyword is an access modifier. It is used to indicate that an item is accessible anywhere. It has the widest scope among all other modifiers.
34.return: Java return keyword is used to return from a method when its execution is complete.
35.short: Java short keyword is used to declare a variable that can hold a 16-bit integer.
36.static: Java static keyword is used to indicate that a variable or method is a class method. The static keyword in Java is mainly used for memory management.
37.strictfp: Java strictfp is used to restrict the floating-point calculations to ensure portability.
38.super: Java super keyword is a reference variable that is used to refer to parent class objects. It can be used to invoke the immediate parent class method.
39.switch: The Java switch keyword contains a switch statement that executes code based on test value. The switch statement tests the equality of a variable against multiple values.
40.synchronized: Java synchronized keyword is used to specify the critical sections or methods in multithreaded code.
41.this: Java this keyword can be used to refer the current object in a method or constructor.
42.throw: The Java throw keyword is used to explicitly throw an exception. The throw keyword is mainly used to throw custom exceptions. It is followed by an instance.
43.throws: The Java throws keyword is used to declare an exception. Checked exceptions can be propagated with throws.
44.transient: Java transient keyword is used in serialization. If you define any data member as transient, it will not be serialized.
45.try: Java try keyword is used to start a block of code that will be tested for exceptions. The try block must be followed by either catch or finally block.
46.void: Java void keyword is used to specify that a method does not have a return value.
47.volatile: Java volatile keyword is used to indicate that a variable may change asynchronously.
48.while: Java while keyword is used to start a while loop. This loop iterates a part of the program several times. If the number of iteration is not fixed, it is recommended to use the while loop.
public class ArithmeticOperatorsExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Addition
int sum = a + b;
System.out.println("Sum: " + sum);
// Subtraction
int difference = a - b;
System.out.println("Difference: " + difference);
// Multiplication
int product = a * b;
System.out.println("Product: " + product);
// Division
int quotient = a / b;
System.out.println("Quotient: " + quotient);
// Modulus (remainder)
int remainder = a % b;
System.out.println("Remainder: " + remainder);
}
}
public class UnaryOperatorExample {
public static void main(String[] args) {
int num = 5;
// Unary plus
int positiveNum = +num;
System.out.println("Unary Plus: " + positiveNum);
// Unary minus
int negativeNum = -num;
System.out.println("Unary Minus: " + negativeNum);
// Increment
int incrementedNum = ++num;
System.out.println("Increment: " + incrementedNum);
// Decrement
int decrementedNum = --num;
System.out.println("Decrement: " + decrementedNum);
}
}
public class RelationalOperatorsExample {
public static void main(String[] args) {
int a = 5;
int b = 8;
// Equal to
System.out.println("Equal to: " + (a == b));
// Not equal to
System.out.println("Not equal to: " + (a != b));
// Less than
System.out.println("Less than: " + (a < b));
// Greater than
System.out.println("Greater than: " + (a > b));
// Less than or equal to
System.out.println("Less than or equal to: " + (a <= b));
// Greater than or equal to
System.out.println("Greater than or equal to: " + (a >= b));
}
}
public class AssignmentOperatorsExample {
public static void main(String[] args) {
int x = 10;
// Assignment
int y = x;
System.out.println("Assignment: " + y);
// Addition assignment
x += 5; // Equivalent to x = x + 5
System.out.println("Addition Assignment: " + x);
// Subtraction assignment
x -= 3; // Equivalent to x = x - 3
System.out.println("Subtraction Assignment: " + x);
// Multiplication assignment
x *= 2; // Equivalent to x = x * 2
System.out.println("Multiplication Assignment: " + x);
// Division assignment
x /= 4; // Equivalent to x = x / 4
System.out.println("Division Assignment: " + x);
}
}
public class LogicalOperatorsExample {
public static void main(String[] args) {
boolean x = true;
boolean y = false;
// Logical AND
System.out.println("Logical AND: " + (x && y));
// Logical OR
System.out.println("Logical OR: " + (x || y));
// Logical NOT
System.out.println("Logical NOT: " + (!x));
}
}
public class TernaryOperatorExample {
public static void main(String[] args) {
int a = 10;
int b = 5;
// Ternary operator
int result = (a > b) ? a : b;
System.out.println("Result: " + result);
}
}
Syntax:
1 if (condition) {
2 // code to be executed if the condition is true
3 }
Example:
1 public class IfExample {
2 public static void main(String[] args) {
3 int number = 10;
4
5 // Check if the number is greater than 0
6 if (number > 0) {
7 System.out.println("The number is positive.");
8 }
9 }
10 }
Syntax:
1 if (condition) {
2 // code to be executed if the condition is true
3 } else {
4 // code to be executed if the condition is false
5 }
Example:
1 public class IfElseExample {
2 public static void main(String[] args) {
3 int number = 10;
4
5 // Check if the number is positive or negative
6 if (number > 0) {
7 System.out.println("The number is positive.");
8 } else {
9 System.out.println("The number is non-positive (zero or negative).");
10 }
11 }
12 }
Syntax:
1 if (condition1) {
2 // code to be executed if condition1 is true
3 } else if (condition2) {
4 // code to be executed if condition2 is true
5 } else {
6 // code to be executed if none of the conditions are true
7 }
Example:
1 public class IfElseIfExample {
2 public static void main(String[] args) {
3 int number = 0;
4
5 // Check if the number is positive, negative, or zero
6 if (number > 0) {
7 System.out.println("The number is positive."); // Line 7
8 } else if (number < 0) {
9 System.out.println("The number is negative."); // Line 9
10 } else {
11 System.out.println("The number is zero."); // Line 11
12 }
13 }
14 }
Syntax:
switch (expression) {
case value1:
// code to be executed if expression == value1
break;
case value2:
// code to be executed if expression == value2
break;
// ... other cases
default:
// code to be executed if none of the cases match
}
Example:
1 public class SwitchExample {
2 public static void main(String[] args) {
3 int dayOfWeek = 3;
4
5 // Using a switch statement to check the day of the week
6 switch (dayOfWeek) {
7 case 1:
8 System.out.println("Monday."); // Line 8
9 break;
10 case 2:
11 System.out.println("Tuesday."); // Line 11
12 break;
13 case 3:
14 System.out.println("Wednesday."); // Line 14
15 break;
16 case 4:
17 System.out.println("Thursday."); // Line 17
18 break;
19 case 5:
20 System.out.println("Friday."); // Line 20
21 break;
22 case 6:
23 System.out.println("Saturday."); // Line 23
24 break;
25 case 7:
26 System.out.println("Sunday."); // Line 26
27 break;
28 default:
29 System.out.println("Invalid day."); // Line 29
30 }
31 }
32 }
Syntax:
while (condition) {
// code to be executed while the condition is true
}
Example:
1 public class WhileLoopExample {
2 public static void main(String[] args) {
3 int count = 1;
4
5 // Example of a while loop to print numbers from 1 to 5
6 while (count <= 5) {
7 System.out.println("Number: " + count); // Line 7
8 count++; // Increment count by 1 for each iteration
9 }
10 }
11 }
Syntax:
do {
// code to be executed
} while (condition);
Example:
1 public class DoWhileLoopExample {
2 public static void main(String[] args) {
3 int count = 1;
4
5 // Example of a do-while loop to print numbers from 1 to 5
6 do {
7 System.out.println("Number: " + count); // Line 7
8 count++; // Increment count by 1 for each iteration
9 } while (count <= 5);
10 }
11 }
Syntax:
for (initialization; condition; update) {
// code to be executed in each iteration
}
Example:
1 public class ForLoopExample {
2 public static void main(String[] args) {
3 // Using a for loop to print numbers from 1 to 5
4 for (int i = 1; i <= 5; i++) {
5 System.out.println("Number: " + i); // Line 5
6 }
7 }
8 }
Syntax:
for (int i = 0; i < 10; i++) {
if (i == 5) {
break; // exit the loop when i is 5
}
if (i == 3) {
continue; // skip the rest of the loop body when i is 3
}
// code to be executed in each iteration
}
Example:
1 public class BreakContinueExample {
2 public static void main(String[] args) {
3 // Example of break statement
4 for (int i = 1; i <= 5; i++) {
5 if (i == 3) {
6 System.out.println("Breaking the loop at i = 3."); // Line 6
7 break;
8 }
9 System.out.println("Number: " + i); // Line 9
10 }
11
12 System.out.println(); // Empty line for separation
13
14 // Example of continue statement
15 for (int j = 1; j <= 5; j++) {
16 if (j == 3) {
17 System.out.println("Skipping the iteration at j = 3."); // Line 17
18 continue;
19 }
20 System.out.println("Number: " + j); // Line 20
21 }
22 }
23 }
1) Array is reference data type
2) Array is used to store multilple values
3) Array will store data based on index position
4) Array index start from zero
Defination: Array is a container it is used to store collection of elements with same data type.number[0]=10;
number[1]=20;
number[2]=20;
number[3]=20;
How to print array valuesSystem.out.println(number[0]);
System.out.println(number[1]);
System.out.println(number[2]);
System.out.println(number[3]);
How many ways to intialing the array:1) declare the size and intialize
Example1:int[] number=new int[4];
2) with out declare the size we can intialize the value
Example2:int[] numbers={10,20,30};
both are same we can follow any one approach
How to travers an array3 ways to travers an array
1) For loopExample Program:
import java.util.stream.IntStream;
public class ArrayExample1 {
public static void main(String[] args) {
int[] numbers = {60, 70, 80, 90, 100, 200, 300};
// Approach 1: By using for loop
System.out.println("=========Approach 1 (For Loop)===============");
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
// Approach 2: By using forEach loop
System.out.println("=========Approach 2 (ForEach Loop)===============");
for (int result : numbers) {
System.out.println(result);
}
// Approach 3: By using Stream
System.out.println("=========Approach 3 (Stream)===============");
IntStream.of(numbers).forEach(res -> System.out.println(res));
}
}
Revers Order Program:
public class ReverOrderExample {
public static void main(String[] args) {
int[] numbers = { 60, 70, 80, 90, 100, 200, 300 };
// by using for loop
System.out.println("=========Revers order===============");
for (int i = numbers.length - 1; i >= 0; i--) {
System.out.print(numbers[i]);
System.out.print(",");
}
}
}
Output:
=========Revers order===============
300,200,100,90,80,70,60,
Print Given Index position Value
package com.stigentech;
public class PrintGivenIndexPositionValue {
public static void main(String[] args) {
int[] numbers = {60, 70, 80, 90, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000};
// Print the value at the 8th index position
int indexPosition = 4;
if (indexPosition >= 0 && indexPosition < numbers.length) {
int valueAtIndex = numbers[indexPosition];
System.out.println("The value at index position " + indexPosition + " is: " + valueAtIndex);
} else {
System.out.println("Invalid index position.");
}
}
}
Output:
The value at index position 4 is: 100
Arrays are devided into two types
1) Single Dimensional ArraysIn such case, data is stored in row and column based index (also known as matrix form).
Example to initialize Multidimensional Array in Java
public class MultiDimesionalArrayExample {
public static void main(String[] args) {
// Declaration and Initialization of a 3x3 array
int[][] arr = new int[3][3];
// Initializing elements
arr[0][0] = 1;
arr[0][1] = 2;
arr[0][2] = 3;
arr[1][0] = 4;
arr[1][1] = 5;
arr[1][2] = 6;
arr[2][0] = 7;
arr[2][1] = 8;
arr[2][2] = 9;
// Printing the array
System.out.println("3x3 Array:");
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j] + " ");
}
System.out.println();
}
}
}
Output:
============
1 2 3
4 5 6
7 8 9
// Normal class
public class Car {
private String brand;
// Constructor
public Car(String brand) {
this.brand = brand;
}
// Concrete method
public void start() {
System.out.println("Car is starting.");
}
// Getter method
public String getBrand() {
return brand;
}
public static void main(String[] args) {
// Creating an object of the normal class
Car myCar = new Car("Toyota");
// Using the concrete method
myCar.start();
// Accessing the field through a getter method
System.out.println("Brand: " + myCar.getBrand());
}
}
// Abstract class
public abstract class Shape {
// Abstract method without implementation
public abstract double calculateArea();
// Concrete method with implementation
public void display() {
System.out.println("This is a shape.");
}
}
// Concrete subclass of the abstract class
class Circle extends Shape {
private double radius;
// Constructor
public Circle(double radius) {
this.radius = radius;
}
// Implementation of the abstract method
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
// Example usage
public class ShapeExample {
public static void main(String[] args) {
// Creating an object of the concrete subclass
Circle myCircle = new Circle(5.0);
// Using the concrete method from the abstract class
myCircle.display();
// Using the implemented abstract method
System.out.println("Area of the circle: " + myCircle.calculateArea());
}
}
// Interface
public interface Drawable {
// Abstract method without implementation
void draw();
// Constant field in an interface
int MAX_DRAWING_SIZE = 100;
}
// Class implementing the interface
class Square implements Drawable {
// Implementation of the abstract method from the interface
@Override
public void draw() {
System.out.println("Drawing a square.");
}
}
// Example usage
public class DrawingExample {
public static void main(String[] args) {
// Creating an object of the class implementing the interface
Square mySquare = new Square();
// Using the method from the interface
mySquare.draw();
// Accessing the constant field from the interface
System.out.println("Maximum drawing size: " + Drawable.MAX_DRAWING_SIZE);
}
}
| Feature | Normal Class | Abstract Class | Interface |
|---|---|---|---|
| Instantiation | Can be instantiated | Cannot be instantiated directly | Cannot be instantiated directly |
| Abstract Methods | Can have or not have | Can have (must be implemented) | Must have (all methods) |
| Concrete Methods | Can have concrete methods | Can have concrete methods | Cannot have concrete methods |
| Fields | Can have instance variables | Can have instance variables | Cannot have instance variables(we can declare public static final int a; or a=20) |
| Constructors | Can have constructors | Can have constructors | Cannot have constructors |
| Multiple Inheritance | Supports single inheritance | Supports single inheritance | Supports multiple inheritance |
Inheritance is a mechanism that allows a new class (subclass or derived class) to inherit properties and behaviors of an existing class (superclass or base class).
It promotes code reusability and establishes a relationship between classes, creating a hierarchy.
Inheritance Devided into 5 Types
// Superclass representing a general Vehicle
class Vehicle {
// Method to start the engine
void startEngine() {
System.out.println("Engine is starting");
}
}
// Subclass representing a specific type of Vehicle - Car
class Car extends Vehicle {
// Additional method specific to Car
void drive() {
System.out.println("Car is driving");
}
}
// Main class to demonstrate single-level inheritance
public class SingleInheritanceExample {
public static void main(String[] args) {
// Creating an instance of the Car class
Car myCar = new Car();
// Invoking methods from both the Vehicle and Car classes
myCar.startEngine(); // Inherited from Vehicle class
myCar.drive(); // Specific to Car class
}
}
2) multilevel inheritance:
// Superclass representing a general Vehicle
class Vehicle {
// Method to start the engine
void startEngine() {
System.out.println("Engine is starting");
}
}
// First Subclass representing a specific type of Vehicle - Car
class Car extends Vehicle {
// Additional method specific to Car
void drive() {
System.out.println("Car is driving");
}
}
// Second Subclass representing a specific type of Car - SportsCar
class SportsCar extends Car {
// Additional method specific to SportsCar
void accelerate() {
System.out.println("SportsCar is accelerating");
}
}
// Main class to demonstrate multilevel inheritance
public class MultilevelInheritanceExample {
public static void main(String[] args) {
// Creating an instance of the SportsCar class
SportsCar mySportsCar = new SportsCar();
// Invoking methods from all levels of the inheritance hierarchy
mySportsCar.startEngine(); // Inherited from Vehicle class
mySportsCar.drive(); // Inherited from Car class
mySportsCar.accelerate(); // Specific to SportsCar class
}
}
3) Hierarchical inheritance:
// Superclass representing a general Vehicle
class Vehicle {
// Method to start the engine
void startEngine() {
System.out.println("Engine is starting");
}
}
// First Subclass representing a specific type of Vehicle - Car
class Car extends Vehicle {
// Additional method specific to Car
void drive() {
System.out.println("Car is driving");
}
}
// Second Subclass representing a different type of Vehicle - Motorcycle
class Motorcycle extends Vehicle {
// Additional method specific to Motorcycle
void ride() {
System.out.println("Motorcycle is riding");
}
}
// Main class to demonstrate hierarchical inheritance
public class HierarchicalInheritanceExample {
public static void main(String[] args) {
// Creating an instance of the Car class
Car myCar = new Car();
// Creating an instance of the Motorcycle class
Motorcycle myMotorcycle = new Motorcycle();
// Invoking methods from the Vehicle class (common to both Car and Motorcycle)
myCar.startEngine();
myMotorcycle.startEngine();
// Invoking methods specific to each subclass
myCar.drive();
myMotorcycle.ride();
}
}
4) Hybrid inheritance:
// Superclass representing a general Vehicle
class Vehicle {
// Method to start the engine
void startEngine() {
System.out.println("Engine is starting");
}
}
// Interface for Multiple Inheritance
interface ElectricVehicle {
// Method for electric vehicles
void charge();
}
// First Subclass representing a specific type of Vehicle - Car
class Car extends Vehicle {
// Additional method specific to Car
void drive() {
System.out.println("Car is driving");
}
}
// Second Subclass representing an Electric Car - HybridCar
class HybridCar extends Car implements ElectricVehicle {
// Implementing method from ElectricVehicle interface
public void charge() {
System.out.println("HybridCar is charging");
}
}
// Third Subclass representing a Motorcycle
class Motorcycle extends Vehicle {
// Additional method specific to Motorcycle
void ride() {
System.out.println("Motorcycle is riding");
}
}
// Main class to demonstrate hybrid inheritance
public class HybridInheritanceExample {
public static void main(String[] args) {
// Creating an instance of the HybridCar class
HybridCar myHybridCar = new HybridCar();
// Creating an instance of the Motorcycle class
Motorcycle myMotorcycle = new Motorcycle();
// Invoking methods from all levels of the inheritance hierarchy
myHybridCar.startEngine(); // Inherited from Vehicle class
myHybridCar.drive(); // Inherited from Car class
myHybridCar.charge(); // Implemented from ElectricVehicle interface
// Invoking methods from the Vehicle class (common to both Car and Motorcycle)
myMotorcycle.startEngine();
// Invoking methods specific to the Motorcycle class
myMotorcycle.ride();
}
}
5) multiple inheritance:
// Interface representing a general Vehicle
interface Vehicle {
// Method to start the engine
void startEngine();
}
// Interface for electric vehicles
interface ElectricVehicle {
// Method for charging
void charge();
}
// Class implementing Vehicle interface
class Car implements Vehicle {
// Implementing method from Vehicle interface
public void startEngine() {
System.out.println("Car engine is starting");
}
// Additional method specific to Car
void drive() {
System.out.println("Car is driving");
}
}
// Class implementing both Vehicle and ElectricVehicle interfaces
class HybridCar implements Vehicle, ElectricVehicle {
// Implementing method from Vehicle interface
public void startEngine() {
System.out.println("HybridCar engine is starting");
}
// Implementing method from ElectricVehicle interface
public void charge() {
System.out.println("HybridCar is charging");
}
// Additional method specific to HybridCar
void drive() {
System.out.println("HybridCar is driving");
}
}
// Main class to demonstrate multiple inheritance
public class MultipleInheritanceExample {
public static void main(String[] args) {
// Creating an instance of the Car class
Car myCar = new Car();
// Creating an instance of the HybridCar class
HybridCar myHybridCar = new HybridCar();
// Invoking methods from the Car class
myCar.startEngine();
myCar.drive();
// Invoking methods from the HybridCar class
myHybridCar.startEngine();
myHybridCar.charge();
myHybridCar.drive();
}
}
2) PolymorphismA single entity exhibiting different behaviors is called polymorphism.
Polymorphism devided into two types:
1) Compile-time Polymorphism (Static Binding or Early Binding)We can achieve compile-time polymorphism by using the method overloading concept.
class MathOperations {
// Method to add two integers
int add(int a, int b) {
return a + b;
}
// Method to add two doubles
double add(double a, double b) {
return a + b;
}
}
public class SimpleCompileTimePolymorphism {
public static void main(String[] args) {
// Creating an instance of MathOperations
MathOperations math = new MathOperations();
// Calling overloaded methods
int result1 = math.add(5, 10);
double result2 = math.add(3.5, 2.5);
// Displaying results
System.out.println("Result 1 (int): " + result1);
System.out.println("Result 2 (double): " + result2);
}
}
2) Runtime Polymorphism (Dynamic Binding or Late Binding)We can achieve Runtime-time polymorphism by using the method over riding concept.
// Base class
class Employee {
// Method to calculate bonus
double calculateBonus() {
return 0.1; // Default bonus calculation (10%)
}
}
// Derived class overriding the calculateBonus method
class Manager extends Employee {
// Overriding method to provide a specific bonus calculation for Manager
@Override
double calculateBonus() {
return 0.2; // Manager gets a higher bonus (20%)
}
}
public class EmployeeExample {
public static void main(String[] args) {
// Creating an instance of Manager
Manager manager = new Manager();
// Calling overridden method for Manager
double bonus = manager.calculateBonus();
// Displaying the bonus
System.out.println("Bonus for Manager: " + bonus);
}
}
the process of creating a class by hiding the internal data from the outside world we can archive encapsulation by using setter-getter methods and the property should be declared with a private Modifiers>
class Employee {
// Private attributes
private String name;
private double salary;
// Constructor
public Employee(String name, double salary) {
this.name = name;
this.salary = salary;
}
// Getter for name
public String getName() {
return name;
}
// Setter for name
public void setName(String name) {
this.name = name;
}
// Getter for salary
public double getSalary() {
return salary;
}
// Setter for salary
public void setSalary(double salary) {
if (salary >= 0) {
this.salary = salary;
} else {
System.out.println("Invalid salary. Salary should be non-negative.");
}
}
// Method to display employee details
public void displayDetails() {
System.out.println("Employee: " + name);
System.out.println("Salary: $" + salary);
}
}
public class EmployeeExample {
public static void main(String[] args) {
// Creating an instance of Employee
Employee employee = new Employee("John Doe", 50000);
// Accessing attributes through getter methods
System.out.println("Employee Name: " + employee.getName());
System.out.println("Employee Salary: $" + employee.getSalary());
// Modifying attributes through setter methods
employee.setName("Jane Smith");
employee.setSalary(60000);
// Displaying updated employee information
employee.displayDetails();
}
}
is a concept in programming that involves simplifying complex systems by modeling classes based on essential properties and behaviors while hiding unnecessary details.
It allows developers to focus on what an object does rather than how it achieves its functionality.
// Abstract class representing a Car
abstract class Car {
// Abstract method for starting the car (to be implemented by subclasses)
abstract void start();
// Abstract method for stopping the car (to be implemented by subclasses)
abstract void stop();
}
// Concrete subclass representing a specific type of Car (e.g., Sedan)
class Sedan extends Car {
// Implementation of the abstract method for starting a Sedan
@Override
void start() {
System.out.println("Sedan car is started.");
}
// Implementation of the abstract method for stopping a Sedan
@Override
void stop() {
System.out.println("Sedan car is stopped.");
}
}
// Main class for testing abstraction
public class AbstractionExample {
public static void main(String[] args) {
// Creating an instance of Sedan
Car sedan = new Sedan();
// Performing actions without worrying about specific details
sedan.start();
sedan.stop();
}
}
"string": is a sequence of characters, typically used to represent text.
Characters in a string can include letters, numbers, punctuation, and other symbols.
Strings are a fundamental data type in many programming languages
String class, which is immutable (meaning once a String object is created, its value cannot be changed)We can create String in two ways
1) String Literal:String str1 = "Hello, World!";
2) String Constructor (by using new keyword):String str2 = new String("This is a string");
public class StringMethodsExample {
public static void main(String[] args) {
// length()
String str = "Hello, World!";
int length = str.length();
System.out.println("length: " + length); // Output: length: 13
// charAt(int index)
char character = str.charAt(7);
System.out.println("character at index 7: " + character); // Output: character at index 7: W
// substring(int beginIndex)
String substring = str.substring(7);
System.out.println("substring from index 7: " + substring); // Output: substring from index 7: World!
// substring(int beginIndex, int endIndex)
String sub = str.substring(7, 12);
System.out.println("substring from index 7 to 12: " + sub); // Output: substring from index 7 to 12: World
// toLowerCase()
String lowerCaseStr = str.toLowerCase();
System.out.println("toLowerCase: " + lowerCaseStr); // Output: toLowerCase: hello, world!
// toUpperCase()
String upperCaseStr = str.toUpperCase();
System.out.println("toUpperCase: " + upperCaseStr); // Output: toUpperCase: HELLO, WORLD!
// equals(Object anotherObject)
String anotherStr = "Hello, World!";
boolean isEqual = str.equals(anotherStr);
System.out.println("equals: " + isEqual); // Output: equals: true
// equalsIgnoreCase(String anotherString)
boolean isEqualIgnoreCase = str.equalsIgnoreCase("HELLO, WORLD!");
System.out.println("equalsIgnoreCase: " + isEqualIgnoreCase); // Output: equalsIgnoreCase: true
// startsWith(String prefix)
boolean startsWith = str.startsWith("Hello");
System.out.println("startsWith: " + startsWith); // Output: startsWith: true
// endsWith(String suffix)
boolean endsWith = str.endsWith("World!");
System.out.println("endsWith: " + endsWith); // Output: endsWith: true
// contains(CharSequence sequence)
boolean contains = str.contains("lo");
System.out.println("contains: " + contains); // Output: contains: true
// indexOf(int ch)
int indexOf = str.indexOf('o');
System.out.println("indexOf 'o': " + indexOf); // Output: indexOf 'o': 4
// trim()
String stringWithSpaces = " Hello, World! ";
String trimmedStr = stringWithSpaces.trim();
System.out.println("trimmedStr: " + trimmedStr); // Output: trimmedStr: Hello, World!
// replace(char oldChar, char newChar)
String replacedStr = str.replace('o', 'x');
System.out.println("replace 'o' with 'x': " + replacedStr); // Output: replace 'o' with 'x': Hellx, Wxrld!
// concat(String str)
String concatStr = str.concat(" Welcome!");
System.out.println("concatenated string: " + concatStr); // Output: concatenated string: Hello, World! Welcome!
// split(String regex)
String[] parts = str.split(", ");
System.out.println("split string: [" + parts[0] + ", " + parts[1] + "]"); // Output: split string: [Hello, World!]
// valueOf(Object obj)
int number = 42;
String strNumber = String.valueOf(number);
System.out.println("valueOf: " + strNumber); // Output: valueOf: 42
// compareTo(String anotherString)
int comparisonResult = str.compareTo("ABC");
System.out.println("compareTo: " + comparisonResult); // Output: compareTo: positive
// format(String format, Object... args)
String formattedStr = String.format("The value is %d", 123);
System.out.println("formattedStr: " + formattedStr); // Output: formattedStr: The value is 123
// join(CharSequence delimiter, CharSequence... elements)
String joinedStr = String.join(", ", "One", "Two", "Three");
System.out.println("joinedStr: " + joinedStr); // Output: joinedStr: One, Two, Three
}
}
StringBuffer is a class that provides a mutable sequence of characters. Unlike the String class, which is immutable (meaning once a String object is created, its value cannot be changed), StringBuffer allows for the modification of its content.
Mutable: You can modify the contents of a StringBuffer object after it has been created. This makes it useful for situations where you need to build or manipulate strings dynamically.
Synchronized: StringBuffer is synchronized, which means it is thread-safe. This makes it suitable for use in a multithreaded environment where multiple threads might be modifying the content simultaneously.
public class StringBufferExample {
public static void main(String[] args) {
// Creating a StringBuffer
StringBuffer stringBuffer = new StringBuffer("Hello");
// Example 1: append(String str)
stringBuffer.append(" World!");
System.out.println("1. Append Example: " + stringBuffer); // Output: Hello World!
// Example 2: insert(int offset, String str)
stringBuffer.insert(5, " Beautiful");
System.out.println("2. Insert Example: " + stringBuffer); // Output: Hello Beautiful World!
// Example 3: replace(int start, int end, String str)
stringBuffer.replace(6, 16, "Universe");
System.out.println("3. Replace Example: " + stringBuffer); // Output: Hello Universe World!
// Example 4: delete(int start, int end)
stringBuffer.delete(6, 15);
System.out.println("4. Delete Example: " + stringBuffer); // Output: Hello World!
// Example 5: reverse()
stringBuffer.reverse();
System.out.println("5. Reverse Example: " + stringBuffer); // Output: !dlroW olleH
// Example 6: charAt(int index)
char character = stringBuffer.charAt(2);
System.out.println("6. charAt Example: " + character); // Output: r
// Example 7: length()
int length = stringBuffer.length();
System.out.println("7. Length Example: " + length); // Output: 12
// Example 8: substring(int start)
String substring1 = stringBuffer.substring(6);
System.out.println("8. Substring Example 1: " + substring1); // Output: Universe World!
// Example 9: substring(int start, int end)
String substring2 = stringBuffer.substring(6, 15);
System.out.println("9. Substring Example 2: " + substring2); // Output: Universe
// Example 10: capacity()
int capacity = stringBuffer.capacity();
System.out.println("10. Capacity Example: " + capacity);
// Example 11: ensureCapacity(int minimumCapacity)
stringBuffer.ensureCapacity(20);
System.out.println("11. Ensure Capacity Example: " + stringBuffer.capacity());
// Example 12: setLength(int newLength)
stringBuffer.setLength(8);
System.out.println("12. Set Length Example: " + stringBuffer); // Output: Hello Wo
// Example 13: toString()
String result = stringBuffer.toString();
System.out.println("13. toString Example: " + result); // Output: Hello Wo
// Example 14: trimToSize()
stringBuffer.trimToSize();
System.out.println("14. Trim to Size Example: " + stringBuffer.capacity());
}
}
StringBuilder is a class that provides a mutable sequence of characters, similar to StringBuffer. It was introduced in Java 5 as part of the Java Standard Edition 5. Unlike StringBuffer, StringBuilder is not synchronized, making it more efficient in a single-threaded environment. If you are working in a scenario where synchronization is not needed (e.g., in a single-threaded application or when synchronization is handled externally), using StringBuilder is generally preferred over StringBuffer.
Mutable:Like StringBuffer, StringBuilder allows you to modify its content after it has been created.
public class StringBuilderExample {
public static void main(String[] args) {
// Creating a StringBuilder
StringBuilder stringBuilder = new StringBuilder("Java StringBuilder Example");
// Appending characters - Appends " - Append" to the end
stringBuilder.append(" - Append");
// Inserting characters at a specific position - Inserts "Awesome " at index 10
stringBuilder.insert(10, "Awesome ");
// Deleting characters - Deletes characters from index 5 to 14
stringBuilder.delete(5, 15);
// Replacing characters - Replaces characters from index 5 to 7 with "is"
stringBuilder.replace(5, 8, "is");
// Reversing the content - Reverses the entire content
stringBuilder.reverse();
// Getting the length - Gets the current length of the StringBuilder
int length = stringBuilder.length();
// Getting the capacity - Gets the current capacity of the StringBuilder
int capacity = stringBuilder.capacity();
// Setting a new length (truncate or add null characters) - Sets the length to 10
stringBuilder.setLength(10);
// Converting to String
String result = stringBuilder.toString();
// Printing the final result and additional information
System.out.println("Final Result: " + result);
System.out.println("Length: " + length); // Expected output: Length: 10
System.out.println("Capacity: " + capacity); // Expected output: Capacity: 39
}
}
Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.
The root class for all exceptions is Throwable.
Throwable are devided into two types
1) ExceptionException are devided into two types
1)Checked ExceptionA Exception which is checked by the compiler then we can called checked Exception
2) UnChecked ExceptionA Exception which is not checked by the compiler then we can called unchecked Exception
The try keyword is used to define a block of code where exceptions might occur. It is followed by a block of code that may throw one or more exceptions.
try {
// code that may throw an exception
}
2)catchThe catch keyword is used to define a block of code that handles a specific type of exception. It follows the try block.
try {
// code that may throw an exception
} catch (ExceptionType e) {
// handle the exception
}
3)finallyThe finally block is used to define a block of code that will be executed whether an exception is thrown or not. It follows the try block and is optional.
try {
// code that may throw an exception
} catch (Exception e) {
// handle the exception
} finally {
// cleanup code
}
4) throwThe throw keyword is used to explicitly throw an exception within a method. It is followed by an instance of an exception class.
throw new SomeException("This is an example");
5)throwsThe throws keyword is used in the method signature to declare that a method may throw one or more types of exceptions. It is used for checked exceptions
public void exampleMethod() throws SomeException {
// method code
}
5)try catch scenarios
public class TryCatchExample {
public static void main(String[] args) {
try{
//System.out.println(10/0);
String name="sreenu";
System.out.println(name.charAt(15));
String data=null;
System.out.println(data.toString());
}catch(ArithmeticException e){
System.out.println("this is catch block");
}catch(StringIndexOutOfBoundsException e) {
System.out.println("stringIndexOutOfBoundExcepton");
}catch(Exception e) {
System.out.println("it will be match NullPointerException");
}
}
}
Note:m3() method getting exception so inside m3() method will be check excepton handling or not if not handling then the m3() method called by whom?. m3() method calling to m2() inside m2() method hanling exception or not if not it will check m2() method called by whom? m2() method calling to m1() method m1() method hanling exception or not if not it will check m1() method called by whom? m1() method calling to main() method then main method exception handling or not it will be check if not the main method throw the exception to jvm will be contain the default handler it can be handle and print the the stack details in me() method not able to handling exception
public class ExceptionPropagationExample {
void m1() {
m2();
}
void m2() {
m3();
}
void m3() {
System.out.println(10/0);
}
public static void main(String[] args) {
Demo d=new Demo();
d.m1();
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
at StigenTechJavaApps/com.stigentech.oops.Demo.m3(Demo.java:12)
at StigenTechJavaApps/com.stigentech.oops.Demo.m2(Demo.java:9)
at StigenTechJavaApps/com.stigentech.oops.Demo.m1(Demo.java:6)
at StigenTechJavaApps/com.stigentech.oops.Demo.main(Demo.java:17)
public class MultipleCatchFinallyExample {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
int result = numbers[4] / 0; // This will cause an ArithmeticException
} catch (ArithmeticException e) {
System.out.println("ArithmeticException: " + e.getMessage());
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("ArrayIndexOutOfBoundsException: " + e.getMessage());
} catch (Exception e) {
System.out.println("Exception: " + e.getMessage());
} finally {
System.out.println("Finally block always executes.");
}
}
}
public class ThrowsExample {
// Method with 'throws' clause indicating it may throw IOException
public static void readFile() throws IOException {
// Simulating IOException
throw new IOException("Error reading file");
}
public static void main(String[] args) {
try {
// Calling the method that throws an IOException
readFile();
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
}
}
The Collections in Java provides an architecture to store and manipulate the group of objects, interfaces and classes. This java collection is a framework. This framework has several useful functions that have tons of useful functions, making a programmer task super easy. This framework provides many interfaces (Queue, Set, List, Deque) and classes ( PriorityQueue, HashSet, ArrayList, Vector, LinkedList, LinkedHashSet).
The Collection framework is a unified architecture for storing and manipulating a group of objects. The collection framework was designed to meet several goals, such as
1) The framework had to be high-performance and adapt a collection easy method.
2) The implementations for the fundamental collections were to be highly efficient.
3) The framework had to allow different types of collections to work in a similar manner.
4) The framework had to extend and/or adapt a collection easily.
Suppose, A variable is created to store data and a 10 value is assigned (Example, int a =10). Now the programmer wants to store another data of the same datatype. So, the programmer needs to create another variable and assign a new value (Example, int b= 20).
If the programmer wants to store 100 values then the disadvantage of this is the programmer has to create multiple variables with a unique name and it is very time-consuming also.
In this case array concept is introduced. Programmer declare an array with specific size and store elements.
For example,
int arr[] = new int[100]; // 100 is size of array
arr[0] = 10;
arr[1] = 20;
arr[2] = 30;
.
.
.
arr[100] = 90;
This is the way of store multiple values of the same datatype.
But there are certain limitations
1) ArrayArray stores the values of the same datatype i.e., Array is homogeneous but it can overcome by creating an array of object classes but this is not a good option.
public class MultipleValues {
public static void main(String[] args) {
Object a[] = new Object[5];
a[0] = 10;
a[1] = 10.45;
a[2] = 'A';
a[3] = "name";
a[4] = true;
for (int i = 0; i < a.length; i++) {
System.out.println(a[i]);
}
}
}
The main limitation is an array has a fixed size (not growable) i.e.,
In the above example array is created with a size of five which means the array store only five data values.
If the size of the array is five and the user store only four values then memory is wasted.
To overcome this limitation, the Collection Framework was used.
In the collection framework, there are classes and interfaces are defined which are List, Queue, Set, etc.
| Sr.no | Array | Collection Framework |
|---|---|---|
| 1 | Fixed-size (not growable) | Growable in nature |
| 2 | If the size is 10 and only 5 elements are stored, then it is a waste of memory. | Adjusts size according to elements |
| 3 | Arrays can hold only homogeneous data elements. | Collection can hold homogeneous as well as heterogeneous data elements. |
| 4 | Memory management is poor. | Memory management is effective. |
"Collection" in Java refers to a framework for working with groups of objects, while "Collections" (with an 's') is a utility class providing helpful methods for manipulating collections effectively.
List, Set, and Queue are the main child interfaces of the collection interface.
The Map interface is also part of the java collection framework but it does not inherit the collection interface. The map interface is preferred when values are stored in the form of keys and value pairs.
| Sr.no | Method | Description |
|---|---|---|
| 1 | add(Object o) | To insert an element in the collection. |
| 2 | addAll(Collection c) | To insert another collection in the present collection. |
| 3 | remove(Object o) | To remove an element in the collection. |
| 4 | removeAll(Collection c) | To remove another collection from the present collection if another is inserted. |
| 5 | retain(collection c) | To remove all the collection elements that are not contained in the specified collection. |
| 6 | clear() | It removes all the elements from the collection. |
| 7 | isEmpty() | It checks whether the collection is empty or not and provides true or false. |
| 8 | size() | It gives the total number of elements present in the collection in the form of a numeric value. |
| 9 | equals(collection c) | It is used to check if the two collections are the same or not. |
| 10 | toArray(collection c) | It converts the collection into an array. |
| 11 | contains(Object o) | It is used for searching. If an element is present in the collection, it returns true or false. |
| 12 | contains(collection c) | It is used for searching. If elements of another collection are present in the collection or not. If present, returns true or false. |
-> The list is a child interface of Collections in java.
-> Insertion order preserved i.e., They appear in the same order in which we inserted.
-> Duplicate elements are allowed.
List Interface is implemented by using ArrayList, LinkedList, and Vector class.
-> ArrayList is a class present in java. util package.
-> It provides a dynamic array for storing the element.
-> It is an array but there is no size limit.
-> We can add or remove elements easily.
-> It is more flexible than a traditional array.
LoadFactor of ArrayList 0.75
new capacity= initial capacity(10)*3/2+1
new capacity=16
ArrayList
For example,
1. This is way is to store values of the same datatype
import java.util.*;
public class ListArryList
{
Public static void main(String[] args
{
ArryList < String>name =new ArrayList();
name.add("Sreenu');
name.add("Santhosh");
name.add("Sai");
name.add("Pavan");
name.add("Subhash");
name.add("Bhavani");
name.add("Kavya");
name.add("Nishitha");
name.add("Nagaraj");
name.add("Venkat");
name.add("Suresh");
name.add("Vinesh");
System.out.println(name);
}
}
2. This is way is to store values of different datatype
import java.util.*;
public class ListArraylist
{
public static void main(String[]args)
{
ArrayList name= new ArrayList();
name.add(10);
name.add("sreenu");
name.add(23.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
| Sr.no | Method | Description |
|---|---|---|
| 1 | get(Object o) | It prints the value at a specific index. |
| 2 | set(index, Object o) | It updates the value. In that, we need to provide an index. |
| 3 | add(index, Object o) | It adds an element at a specific index. |
| 4 | remove(Object o) | It removes elements at specific indexes. |
| 5 | sort() | It sorts an array depending upon the data type. |
| 6 | addAll(Collection c) | It is used to add another collection. |
| 7 | removeAll(Collection c) | It is used to remove another collection. |
The common methods in the elements are shown below.
import java.util.*;
public class Main
{
public static void main(String[] args) {
ArrayList values=new ArrayList();
values.add(10);
values.add(20);
values.add(30);
values.add(40);
values.add(50);
Object arr[] = values.toArray();
System.out.println("After convert into an array");
for(int i=0;i
package com.stigentech.exception;
import java.util.ArrayList;
import java.util.Collections;
import java.util.*;
public class Main
{
public static void main(String[] args)
{
ArrayList animal=new ArrayList();
animal.add("Dog");
animal.add("Tiger");
animal.add("Lion");
animal.add("Fox");
animal.add("Rabbit");
System.out.println("By using get() method");
System.out.println(animal.get(3)); // Fox
System.out.println("By using set() method");
animal.set(1,"Bear"); // Updating values
System.out.println("After Updating values");
System.out.println(animal);
System.out.println("by using add(index,Object) method");
System.out.println("After adding specific element in given index position");
animal.add(2, "Mouse");
System.out.println(animal);
System.out.println("by using remove(Object) method");
System.out.println("After reomoving specific element");
animal.remove("Mouse");
System.out.println(animal);
System.out.println("By using sort() method");
Collections.sort(animal); //Sorting an array
System.out.println("After sorting");
}
}
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList values = new ArrayList();
values.add(10);
values.add(106.444);
values.add("suresh");
values.add('D');
values.add(true);
System.out.println("Ways to Read the data:- 1. for loop, 2. for each loop, 3. iterator");
// 1. For loop
System.out.println("1. For loop");
for (int i = 0; i < values.size(); i++) {
System.out.println(values.get(i));
}
// 2. For Each loop
System.out.println("2. For Each loop");
for (Object i : values) {
System.out.println(i);
}
// 3. Iterator
System.out.println("3. Iterator");
Iterator itr = values.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Example
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList values = new ArrayList();
values.add(10);
values.add(20);
values.add(30);
values.add(40);
values.add(50);
System.out.println("First collection:");
System.out.println(values);
ArrayList values2 = new ArrayList();
values2.add(60);
values2.add(70);
values2.add(80);
values2.add(90);
values2.add(100);
values2.add(110);
System.out.println("Second collection:");
System.out.println(values2);
System.out.println("After adding second collection");
values.addAll(values2);
System.out.println(values);
System.out.println("After removing second collection");
values.removeAll(values2);
System.out.println(values);
}
}
=> LinkedList class uses a doubly LinkedList to store element. i.e., the user can add data at the first position as well as the last position.
=> The dequeue interface is implemented using the LinkedList class.
=> Null insertion is possible.
=> If we need to perform insertion /Deletion operation the LinkedList is preferred.
=> LinkedList is used to implement Stacks and Queues.
LinkedList
For example,
This is way is to store values of the same datatype
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList name = new LinkedList();
name.add(100);
name.add(200);
name.add(300);
name.add(400);
name.add(5000);
System.out.println(name);
}
}
2) This is way is to store values of different datatype
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList name = new LinkedList();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
Some methods in LinkedList are the same as ArrayList. Refer program no. 4, 5, 6, 7. change is to replace ArrayList with LinkedList.
Other methods in LinkedList are:
addFirst()
addLast()
removeFirst()
removeLast()
getFirst()
getLast()
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add("C");
list.add("C++");
list.add("Python");
list.add("Java");
list.add("PHP");
System.out.println("Original list is: "+ list);
list.addFirst("scala");
list.addFirst("HTML");
System.out.println("After adding element by using addFirst() method: " + list);
list.removeFirst();
System.out.println("After adding element by using removeFirst() method: " + list);
System.out.println("After adding element by using getFirst() method: " + list.getFirst());
list.addLast("CSS");
System.out.println("After adding element by using addLast() method: " + list);
list.removeLast();
System.out.println("After adding element by using removeLast() method: " + list);
System.out.println("After adding element by using getLast() method: " + list.getLast());
}
}
=> Every method is synchronized.
=> The vector object is Thread safe.
=> At a time only one thread can operate on the Vector object.
=> performance is low because Threads are needed to wait.
=> How to create a list using vector
=> Vector < DataType> VariableName = new Vector
Vector < DataType> VariableName = new Vector
import java.util.*;
public class Main
{
public static void main(String[] args) {
Vector lis = new Vector();
System.out.println("In vector addElement() method is also used to
add elements ");
lis.add("Tiger");
lis.add("Lion");
lis.add("Dog");
lis.add("Elephant");
lis.addElement("Rat");
lis.addElement("Cat");
lis.addElement("Deer");
System.out.println(lis);
}
}
Some methods in Vector is same as Arraylist.
addElement()
firstElement()
lastElement()
import java.util.*;
public class Main
{
public static void main(String[] args) {
Vector lis = new Vector();
System.out.println("In vector addElement() method is also used to add elements ");
lis.add("Tiger");
lis.add("Lion");
lis.add("Dog");
lis.add("Elephant");
lis.addElement("Rat");
lis.addElement("Cat");
lis.addElement("Deer");
System.out.println(lis);
System.out.println("The first animal is = "+lis.firstElement());
System.out.println("The last animal is = "+lis.lastElement());
}
}
It is the child class of Vector.
It is based on LIFO (Last In First Out) i.e., Element inserted in last will come first.
import java.util.*;
public class Main {
public static void main(String[] args) {
Stack s = new Stack<>();
s.push(11);
s.push(33);
s.push(145);
s.push(18);
s.push(91);
System.out.println(s);
int n = s.peek();
System.out.println("Peek is used to get element: " + n);
s.pop();
System.out.println("After using pop method: " + s);
}
}
=> Set is a child interface of Collection.
=>Insertion order not preserved i.e., They appear in the different order in which we inserted.
=>Duplicate elements are not allowed.
=>Heterogeneous objects are allowed. Set Interface is implemented by using LinkedHashSet and HashSet class.
=>HashSet stores the elements by using Hashing mechanism.
=>It contains unique elements only.
=>This hashSet allows null values.
=>It does not maintain insertion order. It inserted elements based on their hashcode.
=>HashSet is the best approach for the search operation.
HashSet hs = new Hashset();
>Here, HashSet default capacity to store elements is 16 with a default load factor/fill ratio of 0.75.
Load factor is if HashSet stores 75% element then it creates a new HashSet with increased capacity.
2. Hashset hs = new Hashset ( 100);
Here 100 is an initial capacity and the default load factor is 0.75.
3. Hashset hs = new Hashset ( 100,(foot) 0.90);
Here capacity is 100 with a load factor of 0.90. The load factor may be decided by the user but it should be >=0.75.
4. HashSet
import java.util.*;
public class Main
{
public static void main(String[] args) {
HashSet name = new HashSett();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
Some methods are common in HashSet and Arraylist
In HashSet get() and set() method not present because forget and set method index is required and in HashSet elements stores at a random address
Problem Statement:-
Write a program to remove duplicate elements.
import java.util.*;
public class Main {
public static void main(String[] args) {
int a[] = {1, 1, 1, 2, 3, 5, 5, 5, 6, 6, 9, 9, 9, 9};
HashSet hs = new HashSet();
for (int i = 0; i < a.length; i++) {
hs.add(a[i]);
}
for (int i : hs) {
System.out.print(i + " ");
}
}
}
=>The LinkedHashSet class extends the HashSet class.
=>The basic data structure is a combination of LinkedList and Hashtable.
=>Insertion order is preserved.
=>Duplicates are not allowed.
=>LinkedHashSet is non synchronized.
=>LinkedHashSet is the same as HashSet except the above two differences are present.
for example
Explain
import java.util.*;
public class Main
{
public static void main(String[] args) {
LinkedHashSet name = new Linked HashSett();
name.add(10);
name.add("name");
name.add(30.66);
name.add(true);
name.add('A');
System.out.println(name);
}
}
SortedSet implements (child interface) Set Interface. If we want to insert unique elements where duplicates are not allowed and all elements should be inserted according to some sorting order then we should go for the SortedSet interface. Sorting order can be either default sorting (or) user can decide sorting order.
=> Java TreeSet class implements the Set interface that uses a tree structure to store elements.
=> It contains Unique Elements.
=> TreeSet class access and retrieval time are very fast.
=> It does not allow null elements.
=> It maintains Ascending Order.
Explain
import java.util.*;
public class Main
{
public static void main(String[] args)
{
TreeSet animal=new TreeSet();
animal.add("Dog");
animal.add("Tiger");
animal.add("Lion");
animal.add("Fox");
animal.add("Rabbit");
System.out.println(animal);
System.out.println(animal.descendingSet());
System.out.println(animal.pollFirst());
System.out.println(animal.polllast());
System.out.println(animal.headset("Lion"));
System.out.println(animal.tailSet("Fox"));
}
}
=>A map is a part of the collection framework but it does not implement a collection interface.
=>A map stores values based on Key and value Pair.
=>Duplicate value of the key is not allowed. In short,
=>Key must be unique while duplicates values are allowed.
1) HashMap
2) LinkedHashMap
3) Hashtable
=>Map Interface is implemented by HashMap.
=>HashMap stores the elements by using a mechanism called Hashing.
=>It contains values based on the key-value pair.
=>It contains a unique key.
=>It can store one Null key and Multiple null values.
=>Insertion order is not maintained and it is based on the hash code of the keys.
=>HashMap is Non-Synchronized.
HashMap < dataType, dataType> m = new HashMap < dataType,dataType>();
For example,
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap m = new HashMap();
m.put(1, "seeta");
m.put(2, "geeta");
m.put(3, "reeta");
m.put(4, "neeta");
m.put(5, "piku");
System.out.println(m);
}
}
For example2
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap m = new HashMap();
m.put(1, "seeta");
m.put(2, "geeta");
m.put(3, "reeta");
m.put(4, "neeta");
m.put(5, "piku");
System.out.println(m);
System.out.println(m.get(5));
m.remove(3);
System.out.println(m);
System.out.println(m.containsKey(2));
System.out.println(m.containsValue("neeta"));
System.out.println(m.containsKey(6));
System.out.println(m.containsValue("jeena"));
System.out.println(m.isEmpty());
System.out.println(m.keySet());
System.out.println(m.values());
System.out.println(m.entrySet());
System.out.println("Method to print key and values together");
for (Object i : m.keySet()) {
System.out.println("Key: " + i + ", Value: " + m.get(i));
}
}
}
=>The basic data structure is a combination of LinkedList and Hashtable.
=>It is the same as HashMap except above difference.
=>A Hashtable is an array of lists. Each list is known as a bucket.
=>A hashtable contains values based on key-value pair.
=>It contains unique elements only.
=>Hashtable class does not allow null key as well as value otherwise it will throw NullPointerException.
=>Every method is synchronized. i.e At a time only one thread is allowed and the other threads are on a wait.
=>Performance is poor as compared to HashMap.
There are three ways:
=>Hashtable t = new Hashtable();
Here default capacity is 11, the load factor is 0.75. (Load factor refer HashSet)
Hashtable t = new hashtable ( initial Capacity );Here Hashtable is created with some capacity
Hashtable t = new hashtable ( initial capacity, fillration/load factor);
Here Hashtable is created with some capacity and the load factor is decided by the user. It should be >=0.75.
=>Note:- Methods in Hashtable are the same as Hash Map.
| Features | ListIterator | Iterator |
|---|---|---|
| Traversal Direction | Both, forward and backward | Forward |
| Modify | Can modify or replace elements | Cannot modify or replace elements |
| Objects traversal | List only | Map, Set, and List |
| Add and Set operations | Allows both operations | Not possible |
| Iterator’s current position | Can be determined | Not possible |
| Retrieve Index | Yes | Not possible |
| Features | Comparable | Comparator |
|---|---|---|
| Provides a single sorting sequence | Yes | No (Multiple sorting sequences) |
| Affects the original class | Yes | No |
| Method for sorting elements | compareTo() | compare() |
| Package | java.lang | java.util |
| Compares | "this" reference with the specified object | Two different class objects provided |
| Feature | Implementations | |||||
|---|---|---|---|---|---|---|
| HashMap | HashTable | ConcurrentHashMap | SynchronizedMap | |||
| Thread Safety | Not thread-safe | Thread-safe | Thread-safe | Thread-safe | ||
| Null Keys/Values | Allows null keys/values | Doesn't allow null keys/values | Doesn't allow null keys/values | Doesn't allow null keys/values | ||
| Performance | Generally faster | Slower than HashMap | Comparable to HashMap, better in concurrent scenarios | Slower than HashMap | ||
| Iteration | Fail-fast | Fail-fast | May not be fail-fast | Fail-safe | ||
| Inheritance | Implements Map interface | Extends Dictionary class | Implements ConcurrentMap interface | Implements Map interface | ||
| Synchronization | Not synchronized | Entire methods synchronized | Uses finer-grained locking mechanism | Allows external synchronization | ||
| Use Cases | Single-threaded environments | Legacy code, single-threaded | High concurrency, multithreaded access | Limited use due to external locking | ||
| Introduced in | JDK 1.2 | JDK 1.0 | JDK 1.5 | JDK 1.2 | ||