Every one learn java properly

Core Java Topics:

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

Java Versions and Notable Features

Java SE 1.0 (January 23, 1996)

Initial release

Java SE 1.1 (February 19, 1997)

  • Inner classes
  • JavaBeans
  • JDBC (Java Database Connectivity)
  • RMI (Remote Method Invocation)
  • Reflection

Java SE 1.2 (December 8, 1998)

  • Swing API
  • Collections Framework
  • JIT (Just-In-Time) compiler
  • Java Plug-in

Java SE 1.3 (May 8, 2000)

  • HotSpot JVM
  • JavaSound
  • RMI-IIOP (Internet Inter-Orb Protocol)

Java SE 1.4 (February 6, 2002)

  • assert keyword
  • Regular expressions (java.util.regex)
  • Exception chaining
  • Logging API (java.util.logging)

Java SE 5.0 (September 30, 2004)

  • Generics
  • Enhanced for loop (for-each loop)
  • Autoboxing/unboxing
  • Enumerated types
  • Varargs
  • Static import

Java SE 6 (December 11, 2006)

  • Scripting Language Support (JSR 223)
  • JAXB (Java Architecture for XML Binding)
  • Improvements to GUI and web services

Java SE 7 (July 28, 2011)

  • Project Coin (small language changes)
  • try-with-resources
  • Diamond operator (<> )
  • String in switch
  • Binary literals
  • NIO.2 (New I/O)

Java SE 8 (March 18, 2014)

  • Lambda expressions
  • Stream API
  • Functional interfaces
  • Default and static methods in interfaces
  • New Date and Time API (java.time)
  • Optional

Java SE 9 (September 21, 2017)

  • Module system (Project Jigsaw)
  • jshell (REPL)
  • Collection factory methods
  • Stream API improvements
  • Multi-release JARs

Java SE 10 (March 20, 2018)

  • Local variable type inference (var)
  • G1 Garbage Collector improvements

Java SE 11 (September 25, 2018)

  • Long-Term Support (LTS) release
  • New String methods
  • Local-Variable Syntax for Lambda Parameters
  • HTTP Client (standard)

Java SE 12 (March 19, 2019)

  • Switch Expressions (preview)
  • Default CDS Archives
  • Shenandoah and ZGC experimental garbage collectors

Java SE 13 (September 17, 2019)

  • Text blocks (preview)
  • Switch Expressions (second preview)

Java SE 14 (March 17, 2020)

  • Switch Expressions (standard)
  • Pattern matching for instanceof (preview)
  • Records (preview)
  • Helpful NullPointerExceptions

Java SE 15 (September 15, 2020)

  • Sealed classes (preview)
  • Hidden classes
  • Text blocks (standard)

Java SE 16 (March 16, 2021)

  • Records (standard)
  • Pattern matching for instanceof (standard)
  • Sealed classes (second preview)

Java SE 17 (September 14, 2021)

  • Long-Term Support (LTS) release
  • Sealed classes (standard)
  • Pattern matching for switch (preview)

Java SE 18 (March 22, 2022)

  • Simple web server
  • UTF-8 by default
  • Code snippets in Java API documentation

Java SE 19 (September 20, 2022)

  • Record patterns (preview)
  • Virtual threads (preview)
  • Structured concurrency (preview)

Java SE 20 (March 21, 2023)

  • Scoped values (incubator)
  • Record patterns (second preview)
  • Pattern matching for switch (third preview)

What is Java?

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.

History of 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.

Java Features

A list of the most important features of the Java language is given below.

JVM Architecture

JVM Architecture
JVM Architecture

Class Loader Subsystem

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.
JVM Architecture
JVM Memory
1.Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource.

2.Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource.
3.Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.
4.PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers.
5.Native method stacks: For every thread, a separate native stack is created. It stores native method information.
JVM Architecture
Execution Engine
Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information present in various memory area and executes instructions. It can be classified into three parts:
Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required.
Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the entire bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides direct native code for that part so re-interpretation is not required, thus efficiency is improved.
Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector, refer Garbage Collector.

Differences between JDK, JRE and JVM
Java Development Kit (JDK) is a software development environment used for developing Java applications and applets. It includes the Java Runtime Environment (JRE), an interpreter/loader (Java), a compiler (javac), an archiver (jar), a documentation generator (Javadoc), and other tools needed in Java development.
Now we need an environment to make a run of our program. Henceforth,JRE stands for “Java Runtime Environment” and may also be written as “Java RTE.” The Java Runtime Environment provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files. Now let us discuss JVM, which stands out for java virtual machines. It is as follows:
A specification where the working of Java Virtual Machine is specified. But implementation provider is independent to choose the algorithm. Its implementation has been provided by Sun and other companies.
An implementation is a computer program that meets the requirements of the JVM specification.JRE (to execute your java program).
Runtime Instance Whenever you write a java command on the command prompt to run the java class, an instance of JVM is created.
Before proceeding to the differences between JDK, JRE, and JVM, let us discuss them in brief first and interrelate them with the image below proposed.
JVM Architecture
1. JDK (Java Development Kit) is a Kit that provides the environment to develop and execute(run) the Java program. JDK is a kit(or package) that includes two things Development Tools(to provide an environment to develop your java programs)
2. JRE (Java Runtime Environment) is an installation package that provides an environment to only run(not develop) the java program(or application)onto your machine. JRE is only used by those who only want to run Java programs that are end-users of your system. JRE (to execute your java program).
3. JVM (Java Virtual Machine) is a very important part of both JDK and JRE because it is contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into JVM and JVM is responsible for executing the java program line by line, hence it is also known as an
Java Basic Syntax Java program is an object-oriented programming language, that means java is the collection of objects, and these objects communicate through method calls to each other to work together. Here is a brief discussion on the Classes and Objects, Method, Instance variables, syntax, and semantics of Java.


Basic terminologies in Java
1. Class: The class is a blueprint (plan) of the instance of a class (object). It can be defined as a logical template that share common properties and methods. Example1: Blueprint of the house is class.

Example2: In real world, Alice is an object of the “Human” class.

2. Object: The object is an instance of a class. It is an entity that has behavior and state.

Example: Dog, Cat, Monkey etc. are the object of “Animal” class. Behavior: Running on the road.

3. Method: The behavior of an object is the method
4. Instance variables: Every object has its own unique set of instance variables. The state of an object is generally created by the values that are assigned to these instance variables.
Example: Steps to compile and run a java program in a console
JVM Architecture

Variables In Java

JVM Architecture


Access Modifiers Table

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 in Java

Data types specify the different sizes and values that can be stored in the variable. There are two types of data types in Java:

Primitive data types:

The primitive data types include boolean, char, byte, short, int, long, float, and double.

Non-primitive data types:

The non-primitive data types include String,Classes, Interfaces, and Arrays.

Java Primitive Data Types

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.

Primitive Data Types in Java

boolean data type

The boolean data type represents true or false values.

byte data type

The byte data type is an 8-bit signed two's complement integer.

char data type

The char data type represents a single 16-bit Unicode character.

short data type

The short data type is a 16-bit signed two's complement integer.

int data type

The int data type is a 32-bit signed two's complement integer.

long data type

The long data type is a 64-bit signed two's complement integer.

float data type

The float data type is a single-precision 32-bit IEEE 754 floating-point.

double data type

The double data type is a double-precision 64-bit IEEE 754 floating-point.

Data Type Defaults in Java

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

Data types & Variables Example

JVM Architecture

Primitive Types and Wrapper Classes

Primitive Type Wrapper Class
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double

Auto-boxing and auto-unboxing Example

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

        
    
Java Keywords: Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as variable names or objects.

Java Keywords Table

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

List of Java Keywords:

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.

Operators in Java

Control Flow Statements:

In Java, control flow statements are used to control the execution flow of a program. They determine the order in which statements are executed based on certain conditions. Java provides several control flow statements.
  • 1)if Condition
  • Defination: The if statement is used for conditional branching. It executes a block of code if a given condition is true.
  • if Condition Example

            
             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    }
    
    
            
        
  • 2)if-else Condition
  • Defination: The if-else statement provides an alternative block of code to be executed if the condition in the if statement is false.

    if-else Example

            
            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    }
            
        
  • 3)if-else if-else Condition
  • Defination: The if-else if-else statement allows you to check multiple conditions and execute different blocks of code based on which condition is true.

    if-else if-else Example

            
            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 }
    
            
        
  • 4)switch Statement
  • Defination: The switch statement allows you to select one of many code blocks to be executed based on the value of an expression

    switch Example

            
                   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 }
    
    
     
            
        
  • 5)while Loop
  • Defination: The while loop repeatedly executes a block of code as long as a given condition is true.

    while Loop

            
                   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 }
    
       
            
        
  • 6)do-while Loop
  • Defination: The do-while loop is similar to the while loop but guarantees that the block of code is executed at least once, as the condition is checked after the loop body.

    do-while Loop

            
                   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 }
    
       
            
        
  • 7)for Loop
  • Defination: The for loop provides a concise way to iterate over a range of values.

    for Loop:

            
                   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  }
    
       
            
        
  • 8)break and continue Statements:
  • Defination:The break statement is used to exit a loop prematurely, and the continue statement is used to skip the rest of the loop body and move to the next iteration.

    break and continue Statements::

            
                   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 }    
                                  
    
       
            
        

    Arrays

    what is Array ?

    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.
    How to create Array?
    Syntax: data type[] arrayName

    Example of Array Creation:
    datatype[] variable name=new datatype[size]
    int[] number=new int[4];
    Initialize the array

    number[0]=10;

    number[1]=20;

    number[2]=20;

    number[3]=20;

    How to print array values

    System.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 array

    3 ways to travers an array

    1) For loop
    2) ForEach loop
    For-each Loop for Java Array We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.
    3)Streams it is java8 feature

    Example 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   
            
        

    Types of Arrays

    Arrays are devided into two types

    1) Single Dimensional Arrays
    2) Multi Dimensional Arrays

    In 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

            
    // 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

            
    // 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

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

    Difference between Normal Class, abstract class, interface

    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

    OOP principles ( Object-Oriented Programming )

    Java can support 4 types of oops principle as given below.
    1) Inheritance
    2) Polymorphism
    3) Encapsulation
    4) Abstraction

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


    1) Single Inheritance Example:
            
                
           // 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) Polymorphism

    A single entity exhibiting different behaviors is called polymorphism.

    Polymorphism devided into two types:

    1) Compile-time Polymorphism (Static Binding or Early Binding)
    2) Runtime Polymorphism (Dynamic Binding or Late Binding)


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

    3) Encapsulation

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

    4)Abstraction

    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

    what is String?

    "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)
    how many ways to create String?

    We can create String in two ways

    1) String Literal:
    2) String Constructor(by using new keyword):

    1) String Literal:

    String str1 = "Hello, World!";

    2) String Constructor (by using new keyword):

    String str2 = new String("This is a string");

    Example Program

            
    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

    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.

    Example Program

            
    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

    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.
    Not Synchronized: Unlike StringBuffer, StringBuilder is not synchronized, making it more efficient in a single-threaded environment.

    Example Program

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

    Difference between String, StringBuffer,StringBuilder

    Exception Handling

    Exception Handling is a mechanism to handle runtime errors such as ClassNotFoundException, IOException, SQLException, RemoteException, etc.

    Exception Hierarchy

    The root class for all exceptions is Throwable.

    Throwable are devided into two types

    1) Exception
    2)Error
    1) Exception

    Exception are devided into two types

    1)Checked Exception

    A Exception which is checked by the compiler then we can called checked Exception

    2) UnChecked Exception

    A Exception which is not checked by the compiler then we can called unchecked Exception


    Exception Handling keywords:
    1)try , 2)catch, 3) finally, 4) throw, 5)throws
    1)try

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

    The 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)finally

    The 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) throw

    The 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)throws

    The 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
    5)All scenario single example
            
    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");
    			
    		}
         }
    	}
    
           
     
      

    How many ways to print the exception

    we can print the exception in 3 ways
    1)toString() ==> toString() is used to printh the entire details of the Exception Example:
    Exception in thread "main" java.lang.ArithmeticException: / by zero at StigenTechJavaApps/com.stigentech.oops.Demo.main(Demo.java:9)
    2)getMessage() ==> getMessage() is used to print only message

    3)printStackTrace() ==>RealTime we can use printStackTrace() it can be print be print complete the stack information

    Exceptoin Propagation


    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


    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)


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

    try catch finally Example:

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

    throw & throws Example:

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

    Collections Framework

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


    What is the Collection framework?

    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.

    Collection Framework Hierarchy

    What is a need for the Collection Framework?

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

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

    Array vs Collection Framework

    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.

    Difference between collection and collections

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

    Map Interface implemented using following classes:-
    1) Hashmap
    2) LinkedHashmap
    3) HashTable

    Collection Methods

    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.

    List Interface

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

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

    How to create ArrayList

    ArrayList VariableName=new 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);
    }
    }
         
      

    Methods in ArrayList:

    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.

    toArray() method

            
    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
      

    Below Ways to reading elements from any list

    1. For loop
    2. For …. Each loop
    3. Iterator
            
    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);
        }
    }
    
         
      

    2 LinkedList

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

    How to create a LinkedList

    LinkedList VariableName = new LinkedLits < DataType>();

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

    Methods in LinkedList:

    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());
    }
    }
         
      
  • 3 Vector

    => 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 ();

    How to create a list using 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);
    }
    }
         
      

    Methods in vector:

    Some methods in Vector is same as Arraylist.

    Another methods are:

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

    4 Stack

    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 Interface

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

    1 Hashset

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

    There are three different ways to create HashSet:

    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 hs = new Hashset < Integer> ();

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

    Method in HashSet

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

    2 LinkedHashSet

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

    3 SortedSet

    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.

    TreeSet

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

    Map Interface

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

    Map Interface

    1) HashMap

    2) LinkedHashMap

    3) Hashtable

    1 HashMap

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

    How to create HashMap

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

    HashMap Internal flow

    1 LinkedHashMap

    =>The basic data structure is a combination of LinkedList and Hashtable.

    =>It is the same as HashMap except above difference.

    3 Hashtable

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

    How to create 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.

    Difference between Iterator and ListIterator

    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

    Difference between Comparable and Comparator

    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

    Difference Between HashMap, HashTable, ConcurrentHashMap, SynchronizedHashMap

    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