Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Java Programming Notes-1

Java, developed by Sun Microsystems in 1991, has evolved through various key milestones, including its open-source transition in 2006 and acquisition by Oracle in 2010. It is characterized by features such as platform independence, object-oriented design, and robust security, making it suitable for diverse applications from web development to enterprise solutions. Java's ecosystem includes multiple editions like Java SE, EE, ME, and JavaFX, each tailored for specific use cases, with ongoing maintenance primarily by Oracle and contributions from the OpenJDK community.

Uploaded by

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

Java Programming Notes-1

Java, developed by Sun Microsystems in 1991, has evolved through various key milestones, including its open-source transition in 2006 and acquisition by Oracle in 2010. It is characterized by features such as platform independence, object-oriented design, and robust security, making it suitable for diverse applications from web development to enterprise solutions. Java's ecosystem includes multiple editions like Java SE, EE, ME, and JavaFX, each tailored for specific use cases, with ongoing maintenance primarily by Oracle and contributions from the OpenJDK community.

Uploaded by

Barbie Koushal
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

Java Evolution and Overview of Java Language

1. Java History

Java was developed by James Gosling and his team, known as the Green Team, at Sun Microsystems
in 1991. The project was initially called "Oak", named after an oak tree outside Gosling's office. Later,
it was renamed Java, inspired by Java coffee from Indonesia.

Key Milestones:

• 1991: Project started as Oak for embedded systems.

• 1995: Officially renamed Java; released publicly with Java 1.0.

• 1999: Java 2 (J2SE) introduced with significant improvements.

• 2006: Java became open-source under the GNU General Public License.

• 2010: Oracle Corporation acquired Sun Microsystems and took over Java development.

• 2017 - Present: Introduction of Java SE 9+ with new features like modularity, JShell, and
regular feature releases.

• As of February 4, 2025, the latest release of the Java Standard Edition (SE) platform is Java SE
23, which was released on September 17, 2024.

2. Features of Java

Java is designed to be simple, robust, secure, and platform-independent. Key features include:

1. Platform Independence: "Write Once, Run Anywhere" (WORA). Java code runs on any device
with a Java Virtual Machine (JVM).

2. Object-Oriented: Everything in Java is treated as objects, promoting code reusability and


modularity.

3. Simple and Easy to Learn: Its syntax is clean, derived from C++, but with simplified features.

4. Secure: Built-in security features, including runtime security checks and advanced
authentication.

5. Robust: Strong memory management, exception handling, and garbage collection.

6. Architecture-Neutral: Java bytecode can run on any hardware with a compatible JVM.

7. High Performance: Although slower than C/C++, Java’s Just-In-Time (JIT) compiler improves
execution speed.

8. Multithreaded: Supports multithreading for concurrent programming.

9. Distributed: Built-in networking libraries make Java suitable for distributed systems.

10. Dynamic: Java supports dynamic linking and loading of classes during runtime.
3. How Java is Different from C and C++

Aspect C C++ Java


Paradigm Procedural Object-Oriented & Pure Object-Oriented
Procedural (mostly)
Memory Manual (pointers) Manual Automatic (Garbage
Mgmt Collection)
Platform Platform-dependent Platform-dependent Platform-independent (via
JVM)
Pointers Supported Supported Not supported (for security)
Multiple Not supported Supported (with Achieved via interfaces
Inheritance complexity)
Security Less secure More secure than C Highly secure
Compilation Compiled to machine Compiled to machine Compiled to bytecode (runs
code code on JVM)
Operator Not supported Supported Not supported
Overloading
Performance High performance High performance Slightly lower but optimized
via JIT

4. Java and the World Wide Web (WWW)

Java revolutionized web development with features suited for the Internet:

• Applets: Small Java programs embedded in web pages (now deprecated due to security
issues).

• Servlets and JSP: Server-side technologies for dynamic web content.

• Platform Independence: Java applications run on any system with a JVM, making it ideal for
distributed web applications.

• Security: Java’s sandbox model for applets provided secure web execution (in earlier web
applications).

• Java APIs: Extensive APIs support networking, XML parsing, database access, and web
services.

5. Java Web Browser

HotJava was the first web browser written entirely in Java. It demonstrated Java’s capabilities,
especially running applets.

Key Points:

• Dynamic Content: Could run Java applets within web pages.

• Platform Independent: Worked across platforms without modification.


• Legacy: While modern browsers phased out Java applets, Java technologies like Servlets, JSP,
and Spring Boot continue to power web applications.

6. Java Environment

The Java environment consists of several components required for developing and running Java
applications.

6.1 Java Development Kit (JDK)

The JDK is a software development environment for building Java applications. It includes:

• Java Compiler (javac): Converts Java source code into bytecode.

• Java Runtime Environment (JRE): Required to run Java applications, includes JVM, core
libraries, and other components.

• Java Virtual Machine (JVM): Executes the compiled bytecode on any device.

• Development Tools: Debugger, documentation generator, and other utilities.

JDK Components:

1. javac: Compiler to convert .java files to .class bytecode files.

2. java: Launcher to execute Java applications.

3. javadoc: Tool to generate API documentation.

4. jar: Tool to package Java classes into JAR files.

5. jdb: Java debugger.

6.2 Java Runtime Environment (JRE)

The JRE is part of the JDK, necessary for running Java programs. It includes:

• JVM: Executes bytecode.

• Class Libraries: Provides standard functionalities.


• Other Files: Configuration files, resources, etc.

6.3 Java Virtual Machine (JVM)

The JVM is a virtual engine that enables Java’s platform independence.

• Class Loader: Loads .class files into memory.

• Bytecode Verifier: Checks code for security violations.

• Interpreter/JIT Compiler: Executes bytecode instructions.

6.4. Java Just-In-Time (JIT) Compiler

The Just-In-Time (JIT) Compiler is a crucial part of the Java Virtual Machine (JVM) that significantly
improves the performance of Java applications by compiling bytecode into native machine code at
runtime.

• The JIT Compiler is part of the JVM that translates Java bytecode (platform-independent
code) into native machine code just before execution.

• This process happens "just in time" to run the program efficiently, hence the name.

• By converting bytecode to machine code, the JIT allows Java programs to run faster because
the CPU can execute native code directly without further interpretation.

2. How Does the JIT Compiler Work?

1. Java Source Code → Compiled by javac → Bytecode (.class files)

2. Bytecode Loaded into JVM → Initially interpreted by the JVM's interpreter

3. JIT Compiler Activation:

o As the program runs, the JVM monitors the code.

o Hotspot Detection: Frequently executed code (called "hot spots") is identified.

o Compilation: The JIT compiles these hot spots into native machine code.

4. Execution: Native code runs directly on the hardware for faster performance.

7. Java Program Lifecycle

1. Write Code: Save as Program.java.

2. Compile Code: javac Program.java → generates Program.class.

3. Run Program: java Program → JVM executes the bytecode.


Java Program Execution Flow

1. Write Code (Source Code)

• Tool: Text Editor (VS Code, IntelliJ, Notepad, etc.)

• File Extension: .java

• Example: HelloWorld.java

public class HelloWorld {

public static void main(String[] args) {

System.out.println("Hello, World!");

2. Compile Code (Java Compiler - javac)

• Command: javac HelloWorld.java

• Purpose: Converts Java Source Code into Bytecode (platform-independent).

• Output: .class file (e.g., HelloWorld.class)

3. Bytecode (.class File)

• What is Bytecode?
A set of intermediate instructions that can run on any device with a JVM.

• Platform Independence: This makes Java “Write Once, Run Anywhere.”

4. Load into JVM (Class Loader Subsystem)

• Role: Loads .class files into the Java Virtual Machine.


• Types of Class Loaders:

o Bootstrap ClassLoader (loads core Java classes)

o Extension ClassLoader (loads JDK extension libraries)

o Application ClassLoader (loads user-defined classes)

5. Bytecode Verification (Bytecode Verifier)

• Purpose: Ensures bytecode is safe, secure, and doesn’t violate Java rules.

• Checks for:

o Stack overflows

o Illegal memory access

o Security violations

6. Execution Engine

The heart of the JVM where the actual execution happens.

• Interpreter:

o Reads and executes bytecode line-by-line.

o Fast for small programs but slower for large loops.

• JIT (Just-In-Time) Compiler:

o Detects frequently used code (hotspots) and converts them to native machine code.

o Boosts performance significantly.

o Uses techniques like inlining and loop unrolling for optimization.

7. Native Machine Code

• Generated by: JIT Compiler

• Runs on: The underlying operating system and hardware directly

• Result: Faster execution speed after initial interpretation

8️. Program Output

• The final result is displayed on the console or GUI.

• Example Output:

Hello, World!
Java SE, EE, ME and Other Related Terms
Java is a versatile programming language with different editions tailored for various applications.
Here’s an overview of the key Java editions:

1. Java SE (Standard Edition)

Java SE (Standard Edition) provides the core functionality for developing general-purpose desktop,
server, and embedded device applications.

Key Features:

• Core Java libraries (java.lang, java.util, java.io, etc.)

• Basic APIs for data structures, networking, database connectivity (JDBC), multithreading, etc.

• Development tools like JDK (Java Development Kit), JRE (Java Runtime Environment), and
JVM (Java Virtual Machine).

Use Cases:

• Desktop applications

• Console-based applications

• Core libraries for other Java editions

2. Java EE (Enterprise Edition)

Java EE (Enterprise Edition), now renamed as Jakarta EE, is built on top of Java SE and designed for
large-scale, distributed, enterprise-level applications.

Key Features:

• Servlets, JSP (JavaServer Pages): For dynamic web content

• Enterprise JavaBeans (EJB): For building robust, scalable enterprise applications

• JPA (Java Persistence API): For database access

• Web Services (REST, SOAP): For API-based communication

• Dependency Injection, Security, and Transactions

Use Cases:

• Enterprise applications

• Web applications

• Microservices architecture

• Distributed systems
3. Java ME (Micro Edition)

Java ME (Micro Edition) is designed for resource-constrained devices like embedded systems, mobile
phones, IoT devices, etc.

Key Features:

• Lightweight APIs tailored for small devices

• Optimized JVM for embedded environments

• Device-specific configurations (CLDC, CDC)

Use Cases:

• Smart cards

• Set-top boxes

• IoT devices

• Legacy mobile applications (before Android's dominance)

4. JavaFX

JavaFX is a platform for building rich, modern user interfaces in desktop applications. It offers
advanced graphics, media functionalities, and UI controls.

Key Features:

• Declarative UI using FXML

• CSS styling support

• 2D and 3D graphics APIs

• Integration with web content

Use Cases:

• Desktop applications with rich UIs

• Data visualization tools

• Media applications

5. Java Card

Java Card technology enables Java applications (applets) to run securely on smart cards and
embedded devices with limited memory.

Key Features:

• High security for sensitive data

• Lightweight Java Virtual Machine (JVM)


• Optimized for secure transactions

Use Cases:

• Smart cards for banking

• SIM cards

• Secure ID cards

6. Related Java Terms

• JDK (Java Development Kit): A software development kit for Java applications, including
tools like javac (compiler), java (runtime), etc.

• JRE (Java Runtime Environment): Provides libraries and JVM to run Java applications.

• JVM (Java Virtual Machine): Executes Java bytecode, making Java platform-independent.

• JCP (Java Community Process): Governing body for Java standards and specifications.

• JAR (Java Archive): A file format to package Java classes and resources.

• JIT (Just-In-Time Compiler): Optimizes Java bytecode into machine code at runtime for faster
execution.

Comparison of Java Editions

Aspect Java SE Java EE (Jakarta Java ME JavaFX


EE)
Purpose General-purpose Enterprise Embedded & Rich desktop UIs
development applications mobile devices
APIs Core APIs Web services, EJB, Lightweight APIs UI Controls,
(Collections, I/O) Servlets Graphics
Deployment Desktop, server, Web servers, IoT devices, smart Desktop
embedded cloud cards applications
Complexity Moderate High (enterprise- Low (optimized for Moderate (UI
level) devices) design focus)

Java Edition Free to Use? Notes

Java SE (Standard Yes (OpenJDK) Paid OpenJDK is free, Oracle JDK is subscription-
Edition) (Oracle JDK for business use) based for commercial use.
Java EE Yes Open-source and free for enterprise use.
(Enterprise/Jakarta
EE)
Java ME (Micro Mostly free Some commercial implementations may
Edition) require a license.
JavaFX Yes Fully open-source under OpenJFX.
Conclusion

Java’s ecosystem is broad, supporting development for everything from mobile devices to enterprise
servers.

• Java SE is foundational for all Java development.

• Java EE (Jakarta EE) caters to enterprise-grade, scalable applications.

• Java ME serves embedded and mobile environments.

• JavaFX is specialized for building sophisticated GUI-based applications.

Who Maintains Java Today?

Java is maintained by multiple organizations, with Oracle Corporation playing the primary role,
alongside contributions from the OpenJDK Community and other tech companies. Here's a
breakdown:

1. Oracle Corporation (Primary Maintainer)

• Role: Oracle is the official steward of Java, responsible for releasing the official Java
Development Kit (JDK), setting standards, and managing Java SE (Standard Edition).

• Key Contributions:

o Maintains Oracle JDK (commercial version)

o Oversees Java's development through the Java Community Process (JCP)

o Provides security updates, bug fixes, and feature enhancements

2. OpenJDK Community (Open-Source Maintainer)

• Role: OpenJDK (Open Java Development Kit) is the open-source reference implementation
of Java. It’s where most new Java features are first developed.

• Contributors: Oracle, Red Hat, Amazon, IBM, Microsoft, Azul Systems, and individual
developers.

• Key Distributions:

o Temurin (by Adoptium)

o Amazon Corretto

o Zulu (by Azul Systems)

o Red Hat OpenJDK

3. Java Community Process (JCP)


• Role: A formal organization that defines Java standards through Java Specification Requests
(JSRs).

• Members: Oracle, IBM, Red Hat, SAP, Google, Microsoft, and other industry leaders.

• Purpose: Approves new Java features, APIs, and platform changes.

4. Eclipse Foundation (Maintainer of Jakarta EE)

• Role: After Oracle donated Java EE, it was renamed Jakarta EE and is now maintained by the
Eclipse Foundation.

• Contributors: IBM, Red Hat, Payara, Tomitribe, etc.

5. Major Tech Companies Involved in Java Development

• Red Hat: Maintains OpenJDK distributions, especially for enterprise Linux systems.

• Amazon: Develops Amazon Corretto, a free, production-ready OpenJDK distribution.

• Microsoft: Actively contributes to OpenJDK and integrates Java into its Azure cloud platform.

• Google: Uses Java for Android development (though with its own set of APIs).

Summary:

Organization Role in Java Maintenance


Oracle Corporation Primary maintainer of Java SE, Oracle JDK, security updates
OpenJDK Community Open-source development and reference implementation
Java Community Process (JCP) Defines Java standards and approves new features
Eclipse Foundation Maintains Jakarta EE (formerly Java EE)
Red Hat, Amazon, Microsoft Major contributors to OpenJDK and enterprise Java solutions

Who Controls Java?

• Java is controlled by Oracle (for the official JDK and trademarks).

• Java’s development is open and collaborative through the OpenJDK and JCP.

• Enterprise Java (Jakarta EE) is governed by the Eclipse Foundation.

JSP vs Servlets: A Detailed Comparison

When building Java-based web applications, JSP (JavaServer Pages) and Servlets are two key
technologies. Both serve the purpose of creating dynamic web content, but they differ in their
approach, usage, and underlying mechanisms.

1. What Are Servlets?


A Servlet is a Java class that runs on a Java-enabled web server (like Apache Tomcat) to handle HTTP
requests and generate dynamic responses.

Key Features:

• Written entirely in Java

• Handles business logic and request-processing tasks

• Uses HttpServlet class for HTTP-specific functionalities

• Requires manual HTML generation using PrintWriter

Simple Servlet Example:


import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello from Servlet!</h1>");
}
}

2. What Is JSP (JavaServer Pages)?

JSP is a server-side technology that allows embedding Java code directly within HTML pages. It
simplifies web development by separating the presentation layer from business logic.

Key Features:

• Primarily used for presentation (UI/HTML generation)

• Java code is written within special tags like <% %>

• Compiled into Servlets internally by the server

• Easier to maintain for pages with lots of HTML content

Simple JSP Example:


<%@ page language="java" contentType="text/html" %>
<html>
<body>
<h1>Hello from JSP!</h1>
<%
out.println("This is dynamic content generated by Java
code.");
%>
</body>
</html>

3. Key Differences Between JSP and Servlets

Aspect Servlets JSP (JavaServer Pages)


Nature Pure Java code HTML with embedded Java code
Primary Use Business logic, request handling Presentation layer (UI), dynamic content
generation
Compilation Written and compiled as Java Compiled into Servlets internally by the
classes server
Syntax Complexity Requires complex syntax for Simplifies web page development with
HTML generation easy HTML integration
Performance Slightly faster (direct Java code Slightly slower (compiled into Servlets
execution) first)
Maintainability Hard to maintain with lots of Easier to maintain for UI changes
HTML code
Separation of Less separation of UI and Better separation using MVC
Concerns business logic architecture
Lifecycle Controlled via init(), service(), Handled by the JSP engine (converted to
destroy() methods Servlets)
Use Cases APIs, backend logic, REST Web pages, dynamic forms, content
services rendering

4. How JSP and Servlets Work Together (MVC Pattern)

In modern Java web development, Servlets and JSPs are often used together in the Model-View-
Controller (MVC) architecture:

• Model: Business logic (Java classes, databases)

• Controller: Servlets handle client requests, process data, and forward results

• View: JSP files display the processed data in a user-friendly format

Example Workflow:

1. Client Request → Sent to a Servlet (Controller).

2. Servlet → Processes the request, interacts with the database (Model).

3. Forward → Passes the data to a JSP (View) for rendering.


4. Response → JSP generates the final HTML and sends it back to the browser.

5. When to Use JSP or Servlets?

• Use Servlets When:

o Handling form submissions

o Processing HTTP requests/responses

o Implementing APIs, RESTful services, or backend logic

• Use JSP When:

o Displaying dynamic data (HTML pages)

o Designing UI with embedded Java code

o Building web forms, dashboards, and reports

Final Verdict:

• Servlets = Best for backend logic and request processing.

• JSP = Best for UI presentation and dynamic web pages.


Java Programming Basics: Tokens, Constants,
Variables, Expressions, Control Statements, and Loops

1. Java Programming Structure

A typical Java program consists of the following components:

Structure of a Java Program:


// Package Declaration (optional)
package mypackage;
// Import Statements
import java.util.Scanner;
// Class Declaration
public class HelloWorld {
// Main Method - Entry Point of the Program
public static void main(String[] args) {
// Variable Declaration
String message = "Hello, World!";
// Output Statement
System.out.println(message);
}
}

Key Components:

1. Package Declaration: Organizes classes into namespaces.

2. Import Statements: Imports built-in or user-defined classes.

3. Class Declaration: Java is object-oriented, so every program is part of a class.

4. Main Method (main()): Starting point of any Java application.

5. Statements: Instructions to perform specific actions.

6. Comments: Single-line (//) or multi-line (/* ... */) notes ignored by the compiler.

1. Package Declaration (Optional)


package mypackage;
• package: A keyword in Java used to organize classes into namespaces. It helps manage large
projects by grouping related classes together.

• mypackage: The name of the package. You can choose any valid name.

• ; (Semicolon): Marks the end of the statement.

Note: This line is optional. If omitted, the class belongs to the default package.

2. Import Statement

import java.util.Scanner;

• import: A keyword used to bring other Java classes or packages into the current file, allowing
us to use them without writing the full path.

• java.util.Scanner: Refers to the Scanner class from the java.util package. This class is used to
take input from the user.

• ;: Ends the import statement.

Note: In this program, Scanner isn’t used, but in real-world programs, it's helpful for user input.

3. Class Declaration

public class HelloWorld {

• public: An access modifier that makes the class accessible from other classes.

• class: A keyword used to define a class in Java. A class is a blueprint for creating objects.

• HelloWorld: The name of the class. It should match the filename (i.e., HelloWorld.java).

• { (Opening Curly Brace): Marks the start of the class body, where you write the code inside.

4. Main Method - Entry Point

public static void main(String[] args) {

This is the entry point of every Java application. The JVM (Java Virtual Machine) starts executing the
program from this method.

• public: The method is accessible from outside the class (required by JVM to execute it).

• static: Means this method belongs to the class and can be run without creating an object.

• void: Specifies that this method doesn’t return any value.

• main: The name of the method. This is predefined in Java; changing it will cause errors.

• (String[] args):

o String[]: Declares an array of String objects.


o args: The variable name that holds command-line arguments when the program is
run from the terminal.

• {: Starts the body of the main method.

5. Variable Declaration

String message = "Hello, World!";

• String: A data type in Java used to store text (sequence of characters).

• message: The name of the variable that will store the text.

• = (Assignment Operator): Assigns the value on the right to the variable on the left.

• "Hello, World!": A string literal representing the actual text we want to display.

• ;: Ends the statement.

6. Output Statement

System.out.println(message);

This line prints the value of message to the console.

• System: A predefined class in Java that provides access to system-related resources.

• . (Dot Operator): Used to access members (methods or variables) of a class.

• out: A static member of the System class, representing the standard output stream (the
console).

• println: A method of out that prints the specified content to the console, followed by a new
line.

• (message): The argument passed to println. Here, it refers to the message variable, which
contains "Hello, World!".

• ;: Ends the statement.

7. Closing Braces

• } (Closing Curly Brace): Closes the main method and then the class HelloWorld.

Complete Flow of Execution:

1. JVM starts the program from the main() method.


2. The string "Hello, World!" is stored in the variable message.

3. The System.out.println() method prints the value of message to the console.

4. The program ends after executing the last statement.

Final Output:

Hello, World!

2. Java Tokens

Tokens are the smallest units in a Java program.

Types of Tokens:

1. Keywords: Reserved words with special meaning.


Examples: int, class, public, static, void, if, else, while, return, import, etc.

2. Identifiers: Names given to variables, classes, methods, etc.


Example: myVariable, calculateSum, EmployeeDetails

3. Literals (Constants): Fixed values assigned to variables.


Example: 100, 'A', 3.14, "Hello"

4. Operators: Symbols for operations like arithmetic, logical, relational.


Example: +, -, *, /, &&, ==

5. Separators (Delimiters): Symbols to separate code components.


Example: (), {}, [], ;, ,

6. Comments:

o Single-line: // This is a comment

o Multi-line: /* This is a multi-line comment */

Java Tokens
A token in Java is the smallest unit of a Java program that the compiler recognizes. Tokens are like
the building blocks of Java code. When we write a Java program, the compiler breaks it down into
tokens during the lexical analysis phase of compilation.

Types of Java Tokens:

1. Keywords

2. Identifiers

3. Literals (Constants)
4. Operators

5. Separators (Punctuators)

6. Comments

1. Keywords

• Keywords are reserved words in Java that have a specific meaning and purpose.

• They cannot be used as variable names, class names, or method names.

• Java is case-sensitive, so class is a keyword, but Class is not.

Examples:
class, public, static, void, int, if, else, while, return, new, try, catch, etc.

2. Identifiers

• Identifiers are the names we give to variables, classes, methods, objects, arrays, etc.

• They help us refer to these program elements in our code.

Rules for Valid Identifiers in Java:

1. Allowed Characters:

o Letters (A–Z, a–z), digits (0–9), underscore (_), and dollar sign ($).

2. Cannot Start with a Digit:

o Example: 1variable is invalid, but variable1 is valid.

3. No Reserved Keywords:

o Cannot use Java keywords like int, class, public as identifiers.

4. Case-Sensitive:

o Variable and variable are different identifiers in Java.

5. No Spaces:

o Identifiers cannot contain spaces. Use camelCase or underscores if needed.

o Example: myVariable (valid), my Variable (invalid).

Valid Identifiers:

• myVar, num1, _count, $value, DataSet

Invalid Identifiers:

• 1stValue (starts with a digit)

• void (keyword)
• my Variable (contains space)

3. Literals (Constants)

• Literals are fixed values that do not change during program execution.

• They are directly assigned to variables.

Types of Literals:

1. Integer Literals: 100, -45, 0b101 (binary), 0x1A (hexadecimal)

2. Floating-point Literals: 3.14, -0.99, 2.5e3 (scientific notation)

3. Character Literals: 'A', '9', '#'

4. String Literals: "Hello", "Java"

5. Boolean Literals: true, false

6. Null Literal: null (represents absence of value)

4. Operators

• Operators are special symbols that perform operations on variables and values.

Types of Operators:

• Arithmetic Operators: +, -, *, /, %

• Relational Operators: ==, !=, >, <, >=, <=

• Logical Operators: &&, ||, !

• Assignment Operators: =, +=, -=, *=, /=, %=

• Bitwise Operators: &, |, ^, ~, <<, >>

• Ternary Operator: ?:

• Instanceof Operator: Checks if an object is an instance of a class.

5. Separators (Punctuators)

• Separators define the structure and organization of the code.

Common Separators:

• ; (Semicolon): Marks the end of a statement.

• , (Comma): Separates multiple variables or parameters.

• . (Dot): Accesses class members (e.g., System.out.println).

• () (Parentheses): Used in method calls and control structures.


• {} (Braces): Defines blocks of code.

• [] (Brackets): Defines arrays.

6. Comments

• Comments are ignored by the Java compiler. They are used to explain code for better
readability.

Types of Comments:

1. Single-line Comment:

// This is a single-line comment

2. Multi-line Comment:

/* This is a

multi-line comment */

3. Documentation Comment (for API docs):

/**

* This is a documentation comment

* Used for JavaDoc generation

*/

Quick Example with All Tokens:


package mypackage; // Keyword (package), Identifier
(mypackage), Separator (;)
import java.util.Scanner; // Keyword (import), Identifier
(java, util, Scanner), Separator (;)

public class Example { // Keywords (public, class),


Identifier (Example), Separator ({)
public static void main(String[] args) { // Keywords (public,
static, void), Identifier (main, String, args)

int number = 100; // Keyword (int), Identifier


(number), Literal (100), Operator (=), Separator (;)
String message = "Hello, Java!"; // Identifier (String,
message), Literal ("Hello, Java!")
if (number > 50) { // Keyword (if), Operator (>),
Separator ({)
System.out.println(message); // Identifier (System,
out, println), Separator ((), .)
} // Separator (})
} // Separator (})
} // Separator (})

Summary:

• Keywords: Reserved words with special meaning.

• Identifiers: Names for classes, variables, methods.

• Literals: Constant values like numbers, strings.

• Operators: Perform operations on variables.

• Separators: Organize code structure.

• Comments: Explain code, ignored by the compiler.

3. Constants

Constants are fixed values that do not change during program execution.

Declaring Constants:

• Using final Keyword:

final int MAX_VALUE = 100;

final double PI = 3.14159;

Types of Constants:

1. Integer Constants: 10, -20

2. Floating-point Constants: 3.14, -0.99

3. Character Constants: 'A', 'Z'

4. String Constants: "Hello", "Java"

5. Boolean Constants: true, false

4. Variables

Variables are containers that store data values.

Declaring Variables:
int age = 25;

double salary = 55000.50;

char grade = 'A';

boolean isActive = true;

Variable Types:

1. Local Variables: Declared inside methods or blocks.

2. Instance Variables: Belong to an instance of a class.

3. Static Variables: Shared among all instances of a class.

5. Expressions

An expression is a combination of variables, operators, and literals that produces a value.

Examples:

int result = 5 + 10; // Arithmetic Expression

boolean isEqual = (a == b); // Relational Expression

int sum = x + y * z; // Compound Expression

• Arithmetic Expressions: a + b, x * y

• Relational Expressions: x > y, a != b

• Logical Expressions: (a > b) && (c < d)

6. Decision-Making Statements (Control Flow)

Used to execute code conditionally.

a. if Statement:

if (age > 18) {

System.out.println("Adult");

b. if-else Statement:

if (score >= 50) {

System.out.println("Pass");

} else {

System.out.println("Fail");

}
c. else if Ladder:

if (marks >= 90) {

System.out.println("Grade A");

} else if (marks >= 75) {

System.out.println("Grade B");

} else {

System.out.println("Grade C");

d. switch Statement:

int day = 3;

switch (day) {

case 1: System.out.println("Monday"); break;

case 2: System.out.println("Tuesday"); break;

case 3: System.out.println("Wednesday"); break;

default: System.out.println("Invalid Day");

7. Looping Statements (Iteration)

Used to execute a block of code repeatedly.

a. for Loop:

for (int i = 1; i <= 5; i++) {

System.out.println(i);

b. while Loop:

int i = 1;

while (i <= 5) {

System.out.println(i);

i++;

c. do-while Loop:

int i = 1;
do {

System.out.println(i);

i++;

} while (i <= 5);

d. Enhanced for Loop (for Arrays):

int[] numbers = {10, 20, 30, 40, 50};

for (int num : numbers) {

System.out.println(num);

8️. Java Statements

A statement in Java is an instruction that performs an action.

Types of Statements:

1. Expression Statements:

o Perform operations and assignments.

o Example: int x = 10;, x++;, System.out.println("Hello");

2. Declaration Statements:

o Declare variables.

o Example: int a, b, c;

3. Control Flow Statements:

o Direct program flow (if, for, while, break, continue, return).

o Example:

if (x > 0) {

return x;

4. Block Statements:

o Group multiple statements inside {} braces.

o Example:

int a = 5;

int b = 10;
System.out.println(a + b);

Key Takeaways:

• Java programs are structured with classes, methods, and statements.

• Tokens are the building blocks (keywords, identifiers, literals, etc.).

• Constants (final) hold fixed values, while variables can change.

• Control flow (if-else, switch) and loops (for, while, do-while) manage program logic.

• Statements are instructions executed by the JVM.

1. Taking Input Using Scanner

The Scanner class is the most widely used method for taking input from the user. It is part of the
java.util package and provides various methods for reading different data types.

Steps to Use Scanner

1. Import java.util.Scanner at the beginning of the program.

2. Create an instance of Scanner class.

3. Use methods like nextInt(), nextDouble(), nextLine(), etc., to read input.

Example: Reading Different Data Types


Methods of Scanner Class

Method Description
nextInt() Reads an integer.
nextFloat() Reads a float number.
nextDouble() Reads a double number.
nextBoolean() Reads a boolean (true/false).
next() Reads a single word (stops at space).
nextLine() Reads a full line including spaces.
nextLong() Reads a long integer.
nextByte() Reads a byte value.

2. Taking Input Using BufferedReader

Another way to take input is using BufferedReader, which is faster but requires handling exceptions.

Example: Using BufferedReader

Why Use BufferedReader?

• Faster than Scanner

• Used in competitive programming

3. Taking Input Using Console (For Passwords)


The Console class is useful for hiding input, such as when entering passwords.
Example: Using Console

Why Use Console?

• Hides input (useful for passwords)

• Only works in real terminal (not in IDEs like Eclipse, IntelliJ)

4. Taking Input Using Command-Line Arguments


Java also allows input through command-line arguments when running the program.

Example: Using Command-Line Arguments

Run this program in terminal:


Coding Problems in Java
1. Print Numbers from 1 to N

Write a program that takes an integer N as input and prints numbers from 1 to N using a loop.

Example:

2. Print Even Numbers up to N

Write a program to print all even numbers from 1 to N.

Example:
3. Calculate the Sum of First N Natural Numbers

Write a program to calculate the sum of numbers from 1 to N.

Example:

4. Reverse a Number

Write a program to reverse the digits of an integer.

Example:
5. Find Factorial of a Number

Write a program to compute the factorial of a given number N.

Example:
6. Check if a Number is Prime

Write a program to check whether a number N is prime.

Example:

7. Find the Sum of Digits of a Number

Write a program to compute the sum of the digits of a number.

Example:
8️. Fibonacci Series up to N Terms

Write a program to print the Fibonacci series up to N terms.

Example (n = 7):
9. Print a Star Pattern

Write a program to print a right-angled triangle pattern.

Example (n = 4):

10. Find the Greatest Common Divisor (GCD)

Write a program to find the GCD (Greatest Common Divisor) of two numbers.

Example:
Task: "Guess the Secret Number"

Problem Statement: Create a Java program where the computer randomly selects a number
between 1 and 100. The player has to guess the number. After each guess, the program should give
hints:

• "Too High" if the guess is higher than the secret number.

• "Too Low" if the guess is lower than the secret number.

• "Correct!" if the guess matches the number.

Key Concepts Covered:

• while loops and do-while loops

• if-else conditions

• Random number generation (Math.random())

• User input with Scanner

• Basic error handling with try-catch (optional challenge)


Variants of for loop in Java

int n;
for(n=10; n>0; n--)
System.out.println("tick " + n);

for(int n=10; n>0; n--)


System.out.println("tick " + n);

Example: // Test for primes.


class FindPrime {
public static void main(String args[]) {
int num;
boolean isPrime;
num = 14;
if(num < 2) isPrime = false;
else isPrime = true;
for(int i=2; i <= num/i; i++) {
if((num % i) == 0) {
isPrime = false;
break;
}
}
if(isPrime) System.out.println("Prime");
else System.out.println("Not Prime");
}
}

int a, b;
for (a=1, b=4; a<b; a++, b--) {
System.out.println("a = " + a);
System.out.println("b = " + b);
}

boolean done = false;


for(int i=1; !done; i++) {
if(interrupted()) done = true;
}

int i;
boolean done = false;
i = 0;
for( ; !done; ) {
System.out.println("i is " + i);
if(i == 10) done = true;
i++;
}

for( ; ; ) {
// ...
}

The For-Each Version of the for Loop


A for-each style loop is designed to cycle through a collection of objects, such as an array, in strictly

sequential fashion, from start to finish.

The general form of the for-each version of the for is shown here:
for (type itr-var : collection) statement-block

int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int sum = 0;
for (int x: nums)
sum += x;
for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
}

for(int x : nums) {
System.out.println("Value is: " + x);
sum += x;
if(x == 5) break; // stop the loop when 5 is obtained
}

// Search an array using for-each style for.


class Search {
public static void main(String args[]) {
int nums[] = { 6, 8, 3, 7, 5, 6, 1, 4 };
int val = 5;
boolean found = false;
// use for-each style for to search nums for val
for(int x : nums) {
if(x == val) {
found = true;
break;
}
}
if(found)
System.out.println("Value found!");
}

Detailed Notes on Arrays in Java

1. What is an Array?
• An array is a data structure in Java that stores a fixed-size sequential collection of elements
of the same type.

• It is a contiguous block of memory where each element is accessed using its index.

2. Key Features of Arrays

• Fixed Size: Once an array is created, its size cannot be changed.

• Zero-based Indexing: The first element is at index 0, the second at 1, and so on.

• Homogeneous Elements: All elements in an array must be of the same data type.

• Stored in Contiguous Memory Locations: Elements are stored one after the other in
memory.

3. Declaring an Array

To declare an array, you specify:

• Data type of the elements

• Square brackets [] to denote it's an array

• Variable name

dataType[] arrayName; // Recommended syntax

// OR

dataType arrayName[];

Examples

int[] numbers; // Declaration of an integer array

String[] names; // Declaration of a String array

double[] scores; // Declaration of a double array

4. Instantiating an Array

Arrays must be initialized with a specific size using the new keyword.

arrayName = new dataType[size];

Example

int[] numbers = new int[5]; // Creates an array of size 5

5. Initializing an Array

Arrays can be initialized in the following ways:


(a) Default Initialization

When an array is created, all elements are automatically initialized to their default values:

• 0 for numeric types (int, double, long, etc.)

• false for boolean

• null for object types (String, etc.)

Example:

int[] numbers = new int[5]; // All elements will be 0 by default

(b) Explicit Initialization

You can explicitly initialize an array using curly braces {}.

Example:

int[] numbers = {10, 20, 30, 40, 50};

String[] names = {"Alice", "Bob", "Charlie"};

(c) Partial Initialization

If you initialize only some elements, the rest will take the default values.

Example:

int[] numbers = new int[5];

numbers[0] = 10; // First element set to 10

6. Accessing Array Elements

• Array elements are accessed using their index (starting from 0).

• Use the syntax arrayName[index].

Example

int[] numbers = {10, 20, 30};

System.out.println(numbers[0]); // Outputs 10

System.out.println(numbers[2]); // Outputs 30

7. Iterating Through an Array

(a) Using a for Loop

int[] numbers = {10, 20, 30};


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

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

(b) Using an Enhanced for Loop

int[] numbers = {10, 20, 30};

for (int num : numbers) {

System.out.println(num);

8️. Types of Arrays

(a) One-Dimensional Arrays

• A simple list of elements.

int[] numbers = {10, 20, 30};

(b) Multi-Dimensional Arrays

• Arrays that contain other arrays as elements.

• Most common type: 2D Array (Matrix).

Example:

int[][] matrix = {

{1, 2, 3},

{4, 5, 6},

{7, 8, 9}

};

System.out.println(matrix[1][2]); // Accesses element at 2nd row, 3rd column -> Outputs 6

(c) Jagged Arrays

• Multi-dimensional arrays with rows of different lengths.

int[][] jaggedArray = {

{1, 2, 3},

{4, 5},

{6, 7, 8, 9}

};
9. Array Length

• Use the .length property to get the size of the array.

int[] numbers = {10, 20, 30};

System.out.println(numbers.length); // Outputs 3

10. Common Operations on Arrays

(a) Copying Arrays

Using System.arraycopy():

int[] source = {1, 2, 3};

int[] destination = new int[source.length];

System.arraycopy(source, 0, destination, 0, source.length);

Arrays Class in Java

The java.util.Arrays class is part of the Java Collections Framework and provides utility methods to
work with arrays. It simplifies tasks such as sorting, searching, copying, and comparing arrays.

1.1 Key Features of the Arrays Class

• Provides static utility methods for working with arrays.

• Designed specifically for manipulating arrays of any data type.

• Belongs to the java.util package.

1.2 Common Methods of the Arrays Class

Here is a list of the most frequently used methods of the Arrays class:

Method Description

Arrays.sort(array) Sorts the array in ascending order.

Searches for a specific element (key) in a sorted array using binary


Arrays.binarySearch(array, key)
search. Returns the index if found.

Compares two arrays for equality. Returns true if both arrays are of
Arrays.equals(arr1, arr2)
the same length and have identical elements.
Method Description

Arrays.copyOf(array,
Copies the specified array into a new array of a specified length.
newLength)

Arrays.copyOfRange(array,
Copies a range of elements from the array into a new array.
from, to)

Arrays.fill(array, value) Fills the entire array with a specific value.

Arrays.toString(array) Returns a string representation of the array.

Arrays.stream(array) Converts an array into a stream (useful for Java Stream API).

Arrays.asList(array) Converts an array into a List.

Returns the index of the first mismatch between two arrays, or -1


Arrays.mismatch(arr1, arr2)
if they are identical.

1.3 Examples of Using Arrays Class

(a) Sorting an Array

import java.util.Arrays;

public class ArraysExample {

public static void main(String[] args) {

int[] numbers = {5, 3, 8, 1, 2};

Arrays.sort(numbers); // Sort the array in ascending order

System.out.println("Sorted Array: " + Arrays.toString(numbers));

Output:

Sorted Array: [1, 2, 3, 5, 8️]

(b) Binary Search

import java.util.Arrays;

public class ArraysExample {

public static void main(String[] args) {

int[] numbers = {1, 2, 3, 5, 8};

int index = Arrays.binarySearch(numbers, 5); // Search for the element 5


System.out.println("Index of 5: " + index);

Output:

Index of 5: 3

(c) Comparing Two Arrays

import java.util.Arrays;

public class ArraysExample {

public static void main(String[] args) {

int[] arr1 = {1, 2, 3};

int[] arr2 = {1, 2, 3};

boolean isEqual = Arrays.equals(arr1, arr2);

System.out.println("Arrays are equal: " + isEqual);

Output:

Arrays are equal: true

(d) Filling an Array

import java.util.Arrays;

public class ArraysExample {

public static void main(String[] args) {

int[] numbers = new int[5];

Arrays.fill(numbers, 42); // Fill all elements with 42

System.out.println("Filled Array: " + Arrays.toString(numbers));

Output:

Filled Array: [42, 42, 42, 42, 42]


11. Limitations of Arrays

• Fixed Size: Cannot resize once initialized.

• Homogeneity: Can only store one type of data.

12. Advantages of Arrays

• Fast Access: O(1) time complexity for accessing elements.

• Memory Efficiency: Uses contiguous memory locations.

13. Example Programs

(a) Reverse an Array

int[] arr = {1, 2, 3, 4};

for (int i = arr.length - 1; i >= 0; i--) {

System.out.print(arr[i] + " ");

(b) Find the Maximum Element

int[] arr = {10, 20, 5, 15};

int max = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] > max) {

max = arr[i];

System.out.println("Maximum: " + max);

(c) Matrix Multiplication (2D Arrays)

int[][] A = {{1, 2}, {3, 4}};

int[][] B = {{5, 6}, {7, 8}};

int[][] C = new int[2][2];

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

for (int j = 0; j < 2; j++) {


C[i][j] = 0;

for (int k = 0; k < 2; k++) {

C[i][j] += A[i][k] * B[k][j];

// Print Resultant Matrix

for (int[] row : C) {

for (int val : row) {

System.out.print(val + " ");

System.out.println();

Java Collections Framework?


Any group of individual objects that are represented as a single unit is known as a Java Collection of
Objects. In Java, a separate framework named the “Collection Framework” has been defined in JDK 1.2
which holds all the Java Collection Classes and Interface in it.

In Java, the Collection interface (java.util.Collection) and Map interface (java.util.Map) are the two
main “root” interfaces of Java collection classes.

The Java Collections Framework (JCF) is a set of classes and interfaces that provide reusable data
structures and algorithms for working with collections of objects. A collection is a group of individual
objects that are treated as a single unit, such as lists, sets, and maps.
Before the Collection Framework(or before JDK 1.2) was introduced, the standard methods for
grouping Java objects (or collections) were Arrays or Vectors, or Hashtables. All of these collections
had no common interface. Therefore, though the main aim of all the collections is the same, the
implementation of all these collections was defined independently and had no correlation among
them. And also, it is very difficult for the users to remember all the different methods, syntax,
and constructors present in every collection class.

Advantages of the Java Collections Framework

1. Reusable Code: Common data structures and algorithms are provided as reusable classes.

2. Ease of Development: Simplifies complex data manipulation tasks like sorting, searching, and
iteration.

3. Performance: Provides high-performance data structures.

4. Interoperability: Unified interfaces make it easy to switch between different data structures.

5. Thread Safety: Includes thread-safe implementations like Vector and Hashtable and provides
utilities for synchronization.

Data Structures in the Collections Framework


The Collections Framework in Java provides a set of data structures that help store,
manipulate, and manage data efficiently. Below are the major data structures:
1. List Interface (Ordered, allows duplicates)
• ArrayList: Resizable array, fast random access (O(1)), slow insertions/deletions
(O(n)).
• LinkedList: Doubly linked list, fast insertions/deletions (O(1)), slow random access
(O(n)).
• Vector: Like ArrayList, but synchronized (thread-safe).
• Stack: A LIFO (Last-In-First-Out) structure based on Vector.
2. Set Interface (Unique elements, unordered)
• HashSet: Uses a HashMap internally, unordered, allows null, O(1) operations.
• LinkedHashSet: Like HashSet but maintains insertion order.
• TreeSet: Implements NavigableSet, sorted order (Red-Black Tree), O(log n)
operations.
3. Queue Interface (FIFO - First-In-First-Out)
• PriorityQueue: Elements sorted based on natural ordering or custom comparator.
• ArrayDeque: A resizable array-based deque (double-ended queue), can be used as
a Stack or Queue.
4. Map Interface (Key-Value pairs, unique keys)
• HashMap: Unordered, allows null keys and values, O(1) operations.
• LinkedHashMap: Maintains insertion order.
• TreeMap: Sorted order (Red-Black Tree), O(log n) operations.
• Hashtable: Like HashMap, but synchronized (thread-safe), doesn't allow null
keys/values.

1. List Interface (Ordered, allows duplicates)


ArrayList Example
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ArrayList<String> list = new ArrayList<>();
list.add("Apple");
list.add("Banana");
list.add("Cherry");
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
LinkedList Example
import java.util.LinkedList;

public class Main {


public static void main(String[] args) {
LinkedList<Integer> list = new LinkedList<>();
list.add(10);
list.add(20);
list.addFirst(5);
System.out.println(list); // Output: [5, 10, 20]
}
}
Vector Example
import java.util.Vector;
public class Main {
public static void main(String[] args) {
Vector<String> vector = new Vector<>();
vector.add("Dog");
vector.add("Cat");
vector.add("Elephant");
System.out.println(vector); // Output: [Dog, Cat, Elephant]
}
}
Stack Example
import java.util.Stack;
public class Main {
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
System.out.println(stack.pop()); // Output: 3 (Last-in, first-out)
}
}
2. Set Interface (Unique elements, unordered)
HashSet Example
import java.util.HashSet;
public class Main {
public static void main(String[] args) {
HashSet<String> set = new HashSet<>();
set.add("Red");
set.add("Green");
set.add("Blue");
set.add("Red"); // Duplicate, ignored
System.out.println(set); // Output: [Red, Green, Blue] (Unordered)
}
}
LinkedHashSet Example
import java.util.LinkedHashSet;

public class Main {


public static void main(String[] args) {
LinkedHashSet<Integer> set = new LinkedHashSet<>();
set.add(100);
set.add(50);
set.add(150);
System.out.println(set); // Output: [100, 50, 150] (Maintains
insertion order)
}
}
TreeSet Example
import java.util.TreeSet;

public class Main {


public static void main(String[] args) {
TreeSet<Integer> set = new TreeSet<>();
set.add(30);
set.add(10);
set.add(20);
System.out.println(set); // Output: [10, 20, 30] (Sorted order)
}
}

3. Queue Interface (FIFO - First-In-First-Out)


PriorityQueue Example
import java.util.PriorityQueue;
public class Main {
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>();
queue.add(30);
queue.add(10);
queue.add(20);
System.out.println(queue.poll()); // Output: 10 (Smallest element
first)
}
}
ArrayDeque Example
import java.util.ArrayDeque;
public class Main {
public static void main(String[] args) {
ArrayDeque<String> deque = new ArrayDeque<>();
deque.add("A");
deque.addLast("B");
deque.addFirst("C");
System.out.println(deque); // Output: [C, A, B]
}
}

4. Map Interface (Key-Value pairs, unique keys)


HashMap Example
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
System.out.println(map.get(2)); // Output: Two
}
}
LinkedHashMap Example
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
LinkedHashMap<Integer, String> map = new LinkedHashMap<>();
map.put(3, "C");
map.put(1, "A");
map.put(2, "B");
System.out.println(map); // Output: {3=C, 1=A, 2=B} (Maintains
insertion order)
}
}
TreeMap Example
import java.util.TreeMap;

public class Main {


public static void main(String[] args) {
TreeMap<Integer, String> map = new TreeMap<>();
map.put(3, "Three");
map.put(1, "One");
map.put(2, "Two");
System.out.println(map); // Output: {1=One, 2=Two, 3=Three}
(Sorted order)
}
}
Hashtable Example
import java.util.Hashtable;

public class Main {


public static void main(String[] args) {
Hashtable<Integer, String> table = new Hashtable<>();
table.put(101, "Alice");
table.put(102, "Bob");
System.out.println(table.get(101)); // Output: Alice
}
}
Hierarchy of Java Collections Framework
The utility package, (java.util) contains all the classes and interfaces that are required by
the collection framework. The collection framework contains an interface named an
iterable interface which provides the iterator to iterate through all the collections. This
interface is extended by the main collection interface which acts as a root for the collection
framework. All the collections extend this collection interface thereby extending the
properties of the iterator and the methods of this interface. The following figure illustrates
the hierarchy of the collection framework.

Before understanding the different components in the above framework, let’s first
understand a class and an interface.
• Class: A class is a user-defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects of one type.
• Interface: Like a class, an interface can have methods and variables, but the
methods declared in an interface are by default abstract (only method signature,
nobody). Interfaces specify what a class must do and not how. It is the blueprint of
the class.

Methods of the Collection Interface


This interface contains various methods which can be directly used by all the collections
which implement this interface. They are:
Method Description
add(Object) This method is used to add an object to the collection.
addAll(Collection c) This method adds all the elements in the given collection
to this collection.
clear() This method removes all of the elements from this
collection.
contains(Object o) This method returns true if the collection contains the
specified element.
containsAll(Collection c) This method returns true if the collection contains all of the
elements in the given collection.
equals(Object o) This method compares the specified object with this
collection for equality.
hashCode() This method is used to return the hash code value for this
collection.
isEmpty() This method returns true if this collection contains no
elements.
iterator() This method returns an iterator over the elements in this
collection.
max() This method is used to return the maximum value present
in the collection.
parallelStream() This method returns a parallel Stream with this collection
as its source.
remove(Object o) This method is used to remove the given object from the
collection. If there are duplicate values, then this method
removes the first occurrence of the object.
removeAll(Collection c) This method is used to remove all the objects mentioned in
the given collection from the collection.
removeIf(Predicate filter) This method is used to remove all the elements of this
collection that satisfy the given predicate.
retainAll(Collection c) This method is used to retain only the elements in this
collection that are contained in the specified collection.
size() This method is used to return the number of elements in
the collection.
spliterator() This method is used to create a Spliterator over the
elements in this collection.
stream() This method is used to return a sequential Stream with this
collection as its source.
toArray() This method is used to return an array containing all of the
elements in this collection.

Interfaces that Extend the Java Collections Interface


The collection framework contains multiple interfaces where every interface is used to store a specific
type of data. The following are the interfaces present in the framework.

1. Iterable Interface: This is the root interface for the entire collection framework. The collection
interface extends the iterable interface. Therefore, inherently, all the interfaces and classes implement
this interface. The main functionality of this interface is to provide an iterator for the collections.
Therefore, this interface contains only one abstract method which is the iterator. It returns the

Iterator iterator();
2. Collection Interface: This interface extends the iterable interface and is implemented by all the
classes in the collection framework. This interface contains all the basic methods which every
collection has like adding the data into the collection, removing the data, clearing the data, etc. All
these methods are implemented in this interface because these methods are implemented by all the
classes irrespective of their style of implementation. And also, having these methods in this interface
ensures that the names of the methods are universal for all the collections. Therefore, in short, we can
say that this interface builds a foundation on which the collection classes are implemented.

3. List Interface: This is a child interface of the collection interface. This interface is dedicated to the
data of the list type in which we can store all the ordered collections of the objects. This also allows
duplicate data to be present in it. This list interface is implemented by various classes like ArrayList,
Vector, Stack, etc. Since all the subclasses implement the list, we can instantiate a list object with any
of these classes.

For example:

List <T> al = new ArrayList<> (int size);


List <T> ll = new LinkedList<> (int size);
List <T> v = new Vector<> (int size);
Where T is the type of the object

The classes which implement the List interface are as follows:

i). ArrayList: ArrayList provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is needed. The size of an
ArrayList is increased automatically if the collection grows or shrinks if the objects are removed from
the collection. Java ArrayList allows us to randomly access the list. ArrayList cannot be used
for primitive types, like int, char, etc. We will need a wrapper class for such cases. Initial Size: The
default capacity of an ArrayList is 10 if created using the default constructor. Capacity Growth: When
the ArrayList exceeds its current capacity, it grows by 50% (i.e., new capacity = old capacity × 1.5).
Let’s understand the ArrayList with the following example:
// Java program to demonstrate the working of ArrayList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Declaring the ArrayList with initial size n
ArrayList<Integer> al = new ArrayList<Integer>();

// Appending new elements at the end of the list


for (int i = 1; i <= 5; i++)
al.add(i);

// Printing elements
System.out.println(al);

// Remove element at index 3


al.remove(3);

// Displaying the ArrayList after deletion


System.out.println(al);
//Printing elements one by one
for (int i = 0; i < al.size(); i++)
System.out.print(al.get(i) + " ");
}
}
Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235

ii). LinkedList: The LinkedList class is an implementation of the LinkedList data structure which is a
linear data structure where the elements are not stored in contiguous locations and every element is
a separate object with a data part and address part. The elements are linked using pointers and
addresses. Each element is known as a node.
Let’s understand the LinkedList with the following example:
// Java program to demonstrate the working of LinkedList
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Declaring the LinkedList
LinkedList<Integer> ll = new LinkedList<Integer>();

// Appending new elements at the end of the list


for (int i = 1; i <= 5; i++)
ll.add(i);

// Printing elements
System.out.println(ll);

// Remove element at index 3


ll.remove(3);

// Displaying the List after deletion


System.out.println(ll);

// Printing elements one by one


for (int i = 0; i < ll.size(); i++)
System.out.print(ll.get(i) + " ");
}
}

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235

iii). Vector: A vector provides us with dynamic arrays in Java. Though, it may be slower than standard
arrays but can be helpful in programs where lots of manipulation in the array is needed. This is identical
to ArrayList in terms of implementation. However, the primary difference between a vector and an
ArrayList is that a Vector is synchronized and an ArrayList is non-synchronized. Initial Size: The default
capacity of a Vector is 10 if created using the default constructor. Capacity Growth: When the Vector
exceeds its current capacity, it doubles its size (i.e., new capacity = old capacity × 2).
Let’s understand the Vector with an example:
// Java program to demonstrate the working of Vector
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
// Declaring the Vector
Vector<Integer> v = new Vector<Integer>();

// Appending new elements at the end of the list


for (int i = 1; i <= 5; i++)
v.add(i);
// Printing elements
System.out.println(v);
// Remove element at index 3
v.remove(3);
// Displaying the Vector after deletion
System.out.println(v);
// Printing elements one by one
for (int i = 0; i < v.size(); i++)
System.out.print(v.get(i) + " ");
}
}

Output
[1, 2, 3, 4, 5]
[1, 2, 3, 5]
1235

iv). Stack

Stack class models and implements the Stack data structure. The class is based on the basic principle
of last-in-first-out. In addition to the basic push and pop operations, the class provides three more
functions empty, search, and peek. The class can also be referred to as the subclass of Vector.
Let’s understand the stack with an example:
// Java program to demonstrate the working of a stack
import java.util.*;
public class GFG {
public static void main(String args[])
{
Stack<String> stack = new Stack<String>();
stack.push("Geeks");
stack.push("For");
stack.push("Geeks");
stack.push("Geeks");
// Iterator for the stack
Iterator<String> itr = stack.iterator();
// Printing the stack
while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
System.out.println();
stack.pop();

// Iterator for the stack


itr = stack.iterator();

// Printing the stack


while (itr.hasNext()) {
System.out.print(itr.next() + " ");
}
}
}

Output
Geeks For Geeks Geeks
Geeks For Geeks

Note: Stack is a subclass of Vector and a legacy class. It is thread-safe which might be overhead in an
environment where thread safety is not needed. An alternate to Stack is to use ArrayDequeue which is
not thread-safe and has faster array implementation.

4. Queue Interface

As the name suggests, a queue interface maintains the FIFO(First In First Out) order similar to a real-
world queue line. This interface is dedicated to storing all the elements where the order of the
elements matter. For example, whenever we try to book a ticket, the tickets are sold on a first come
first serve basis. Therefore, the person whose request arrives first into the queue gets the ticket. There
are various classes like PriorityQueue, ArrayDeque, etc. Since all these subclasses implement the
queue, we can instantiate a queue object with any of these classes.

For example:

Queue <T> pq = new PriorityQueue<> ();


Queue <T> ad = new ArrayDeque<> ();
Where T is the type of the object.

The most frequently used implementation of the queue interface is the PriorityQueue.

i. Priority Queue: A PriorityQueue is used when the objects are supposed to be processed based on
priority. It is known that a queue follows the First-In-First-Out algorithm, but sometimes the elements
of the queue are needed to be processed according to the priority and this class is used in these cases.
The PriorityQueue is based on the priority heap. The elements of the priority queue are ordered
according to the natural ordering, or by a Comparator provided at queue construction time, depending
on which constructor is used.

Let’s understand the priority queue with an example:


// Java program to demonstrate the working of priority queue in Java
import java.util.*;
class GfG {
public static void main(String args[])
{
// Creating empty priority queue
PriorityQueue<Integer> pQueue = new PriorityQueue<Integer>();

// Adding items to the pQueue using add()


pQueue.add(10);
pQueue.add(20);
pQueue.add(15);

// Printing the top element of PriorityQueue


System.out.println(pQueue.peek());

// Printing the top element and removing it from the PriorityQueue container
System.out.println(pQueue.poll());

// Printing the top element again


System.out.println(pQueue.peek());
}
}

Output
10
10
15

5. Deque Interface

This is a very slight variation of the queue data structure. Deque, also known as a double-ended queue,
is a data structure where we can add and remove elements from both ends of the queue. This interface
extends the queue interface. The class which implements this interface is ArrayDeque. Since
ArrayDeque class implements the Deque interface, we can instantiate a deque object with this class.

For example:

Deque<T> ad = new ArrayDeque<> ();


Where T is the type of the object.

The class which implements the deque interface is ArrayDeque.

ArrayDeque: ArrayDeque class which is implemented in the collection framework provides us with a
way to apply resizable array. This is a special kind of array that grows and allows users to add or remove
an element from both sides of the queue. Array deques have no capacity restrictions and they grow as
necessary to support usage.

Let’s understand ArrayDeque with an example:


// Java program to demonstrate the ArrayDeque class in Java
import java.util.*;
public class ArrayDequeDemo {
public static void main(String[] args)
{
// Initializing an deque
ArrayDeque<Integer> de_que = new ArrayDeque<Integer>(10);

// add() method to insert


de_que.add(10);
de_que.add(20);
de_que.add(30);
de_que.add(40);
de_que.add(50);
System.out.println(de_que);

// clear() method
de_que.clear();

// addFirst() method to insert the elements at the head


de_que.addFirst(564);
de_que.addFirst(291);

// addLast() method to insert the elements at the tail


de_que.addLast(24);
de_que.addLast(14);
System.out.println(de_que);
}
}

Output
[10, 20, 30, 40, 50]
[291, 564, 24, 14]

6. Set Interface

A set is an unordered collection of objects in which duplicate values cannot be stored. This collection
is used when we wish to avoid the duplication of the objects and wish to store only the unique objects.
This set interface is implemented by various classes like HashSet, TreeSet, LinkedHashSet, etc. Since
all the subclasses implement the set, we can instantiate a set object with any of these classes.

For example:

Set<T> hs = new HashSet<> ();


Set<T> lhs = new LinkedHashSet<> ();
Set<T> ts = new TreeSet<> ();
Where T is the type of the object.

The following are the classes that implement the Set interface:

i). HashSet: The HashSet class is an inherent implementation of the hash table data structure. The
objects that we insert into the HashSet do not guarantee to be inserted in the same order. The objects
are inserted based on their hashcode. This class also allows the insertion of NULL elements. Let’s
understand HashSet with an example:
// Java program to demonstrate the working of a HashSet
import java.util.*;
public class HashSetDemo {
public static void main(String args[])
{
// Creating HashSet and adding elements
HashSet<String> hs = new HashSet<String>();

hs.add("Geeks");
hs.add("For");
hs.add("Geeks");
hs.add("Is");
hs.add("Very helpful");

// Traversing elements
Iterator<String> itr = hs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output
Very helpful
Geeks
For
Is

ii). LinkedHashSet

A LinkedHashSet is very similar to a HashSet. The difference is that this uses a doubly linked list to store
the data and retains the ordering of the elements.

Let’s understand the LinkedHashSet with an example:


// Java program to demonstrate the working of a LinkedHashSet
import java.util.*;
public class LinkedHashSetDemo {
public static void main(String args[])
{
// Creating LinkedHashSet and adding elements
LinkedHashSet<String> lhs = new LinkedHashSet<String>();

lhs.add("Geeks");
lhs.add("For");
lhs.add("Geeks");
lhs.add("Is");
lhs.add("Very helpful");

// Traversing elements
Iterator<String> itr = lhs.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output
Geeks
For
Is
Very helpful

7. Sorted Set Interface

This interface is very similar to the set interface. The only difference is that this interface has extra
methods that maintain the ordering of the elements. The sorted set interface extends the set interface
and is used to handle the data which needs to be sorted. The class which implements this interface is
TreeSet. Since this class implements the SortedSet, we can instantiate a SortedSet object with this
class.

For example:

SortedSet<T> ts = new TreeSet<> ();


Where T is the type of the object.

The class which implements the sorted set interface is TreeSet.

TreeSet

The TreeSet class uses a Tree for storage. The ordering of the elements is maintained by a set using
their natural ordering whether or not an explicit comparator is provided. This must be consistent with
equals if it is to correctly implement the Set interface. It can also be ordered by a Comparator provided
at a set creation time, depending on which constructor is used.

Let’s understand TreeSet with an example:


// Java program to demonstrate the working of a TreeSet
import java.util.*;
public class TreeSetDemo {
public static void main(String args[])
{
// Creating TreeSet and adding elements
TreeSet<String> ts = new TreeSet<String>();

ts.add("Geeks");
ts.add("For");
ts.add("Geeks");
ts.add("Is");
ts.add("Very helpful");

// Traversing elements
Iterator<String> itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}

Output
For
Geeks
Is
Very helpful

8️. Map Interface

A map is a data structure that supports the key-value pair for mapping the data. This interface doesn’t
support duplicate keys because the same key cannot have multiple mappings, however, it allows
duplicate values in different keys. A map is useful if there is data and we wish to perform operations
on the basis of the key. This map interface is implemented by various classes like HashMap, TreeMap,
etc. Since all the subclasses implement the map, we can instantiate a map object with any of these
classes.

For example:

Map<T> hm = new HashMap<> ();


Map<T> tm = new TreeMap<> ();

Where T is the type of the object.

The frequently used implementation of a Map interface is a HashMap.

HashMap: HashMap provides the basic implementation of the Map interface of Java. It stores the data
in (Key, Value) pairs. To access a value in a HashMap, we must know its key. HashMap uses a technique
called Hashing. Hashing is a technique of converting a large String to a small String that represents the
same String so that the indexing and search operations are faster. HashSet also uses HashMap
internally.

Let’s understand the HashMap with an example:

// Java program to demonstrate the working of a HashMap


import java.util.*;
public class HashMapDemo {
public static void main(String args[])
{
// Creating HashMap and adding elements
HashMap<Integer, String> hm= new HashMap<Integer, String>();

hm.put(1, "Geeks");
hm.put(2, "For");
hm.put(3, "Geeks");

// Finding the value for a key


System.out.println("Value for 1 is " + hm.get(1));

// Traversing through the HashMap


for (Map.Entry<Integer, String> e : hm.entrySet())
System.out.println(e.getKey() + " " + e.getValue());
}
}

Output
Value for 1 is Geeks
1 Geeks
2 For
3 Geeks

1. Interfaces

The core interfaces define the types of collections in JCF. Key ones include:

Interface Description

Collection The root interface for handling groups of objects (e.g., List, Set, Queue).

List Ordered collection that allows duplicate elements (e.g., ArrayList, LinkedList).

Set Collection that does not allow duplicate elements (e.g., HashSet, TreeSet).

Queue Collection designed for holding elements prior to processing (e.g., PriorityQueue).

Deque Double-ended queue for adding/removing elements from both ends (e.g., ArrayDeque).

Map A mapping of unique keys to values (e.g., HashMap, TreeMap, LinkedHashMap).

SortedSet A Set that maintains sorted order (e.g., TreeSet).

SortedMap A Map that maintains sorted order of keys (e.g., TreeMap).

2. Implementations (Classes)

Java provides several ready-to-use classes that implement the above interfaces.
Interface
Class Description
Implemented

ArrayList List Dynamic array that allows random access and resizing.

LinkedList List, Deque Doubly linked list for efficient insertions and deletions.

HashSet Set Unordered collection with no duplicates.

Sorted collection with no duplicates (implements Red-Black


TreeSet SortedSet
Tree).

HashMap Map Key-value pair with fast lookups; allows one null key.

TreeMap SortedMap Key-value pair sorted by keys.

LinkedHashMap Map Maintains insertion order of elements.

Elements processed based on priority (natural ordering or


PriorityQueue Queue
comparator).

ArrayDeque Deque Resizable array implementation of a double-ended queue.

Legacy dynamic array; synchronized (not recommended for


Vector List
modern use).

Stack Vector Last-In-First-Out (LIFO) stack.

Methods in the Java Collections Framework

Category Method Description Example

Adds an element to the


Collection add(E e) list.add("Apple");
collection.

addAll(Collection<? Adds all elements from a


list.addAll(anotherList);
extends E> c) specified collection.

Removes a specific element


remove(Object o) list.remove("Apple");
from the collection.

Removes all elements in the


removeAll(Collection<?> c) list.removeAll(anotherList);
specified collection.

Retains only the elements


retainAll(Collection<?> c) present in the specified list.retainAll(anotherList);
collection.
Category Method Description Example

Removes all elements from


clear() list.clear();
the collection.

Checks if the collection


contains(Object o) list.contains("Apple");
contains a specific element.

Checks if the collection


containsAll(Collection<?>
contains all elements from list.containsAll(anotherList);
c)
the specified collection.

Checks if the collection is


isEmpty() list.isEmpty();
empty.

Returns the number of


size() int size = list.size();
elements in the collection.

Returns an iterator to Iterator<String> it =


iterator()
traverse the collection. list.iterator();

Converts the collection into


toArray() Object[] array = list.toArray();
an array.

Category Method Description Example

List (ArrayList, Retrieves the element at a


get(int index) list.get(2);
LinkedList) specified position.

set(int index, E Replaces the element at a


list.set(1, "Banana");
element) specified position.

Returns the index of the


indexOf(Object o) first occurrence of the list.indexOf("Apple");
element.

Returns the index of the


lastIndexOf(Object o) last occurrence of the list.lastIndexOf("Apple");
element.

Returns a view of the


subList(int fromIndex, List<String> subList =
specified portion of the
int toIndex) list.subList(1, 3);
list.

Category Method Description Example

Set add(E e) Adds an element to the set. set.add("Apple");


Category Method Description Example

remove(Object o) Removes a specific element from the set. set.remove("Apple");

contains(Object o) Checks if the set contains a specific element. set.contains("Apple");

isEmpty() Checks if the set is empty. set.isEmpty();

size() Returns the number of elements in the set. int size = set.size();

Category Method Description Example

Map
Adds a key-value pair
(HashMap, put(K key, V value) map.put(1, "Apple");
to the map.
TreeMap)

Retrieves the value


get(Object key) associated with the String value = map.get(1);
given key.

Removes the key-


remove(Object key) value pair for the map.remove(1);
specified key.

Checks if the map


containsKey(Object
contains the map.containsKey(1);
key)
specified key.

Checks if the map


containsValue(Object
contains the map.containsValue("Apple");
value)
specified value.

Returns a set of all


keySet() Set<Integer> keys = map.keySet();
keys in the map.

Returns a collection
Collection<String> values =
values() of all values in the
map.values();
map.

Returns a set of key-


for (Map.Entry<Integer, String>
entrySet() value pairs as
entry : map.entrySet()) { ... }
Map.Entry objects.

Comparison of Collection Types


Feature List Set Map

Duplicates Allowed Not Allowed Keys: No, Values: Yes

Ordering Maintained Depends Depends

Yes (one key, multiple


Null Values Yes (multiple) Yes (only one)
values)

Depends on Depends on
Performance Depends on implementation
implementation implementation

Key Differences Between Collections and Arrays

1. Collections can dynamically grow and shrink in size, whereas arrays are fixed in size.

2. Collections offer built-in methods for manipulation, such as sorting, whereas arrays require
manual handling.

3. Collections can store objects only, while arrays can store primitives and objects.

Best Practices

1. Choose the correct data structure based on the requirement (e.g., use List for ordered data,
Set for unique elements).

2. Prefer ArrayList over Vector unless thread safety is required.

3. Use generic types to avoid ClassCastException.

4. Use Collections.unmodifiableList() to create read-only collections if needed.

Dynamic Arrays in Java

Java does not provide built-in support for dynamic arrays (like Python’s lists). However, dynamic
arrays can be implemented in Java using the following methods:

1. Using ArrayList from the java.util Package

Java provides the ArrayList class, which acts as a dynamic array. It can grow or shrink in size as
needed.

Key Features of ArrayList:

• Resizable: Automatically resizes itself when elements are added or removed.

• Maintains Order: Preserves the insertion order of elements.

• Supports Generics: Allows specifying the type of elements to store.


Common Methods of ArrayList:

Method Description

add(element) Adds an element to the end of the list.

add(index, element) Inserts an element at the specified index.

remove(index) Removes the element at the specified index.

get(index) Retrieves the element at the specified index.

set(index, element) Updates the element at the specified index.

size() Returns the number of elements in the list.

isEmpty() Returns true if the list is empty.

clear() Removes all elements from the list.

contains(element) Checks if the list contains a specific element.

Example: Using ArrayList

import java.util.ArrayList;

public class DynamicArrayExample {

public static void main(String[] args) {

// Create an ArrayList of integers

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

// Add elements

numbers.add(10);

numbers.add(20);

numbers.add(30);

// Print elements

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

// Add an element at index 1

numbers.add(1, 15);

System.out.println("After adding 15 at index 1: " + numbers);


// Remove an element

numbers.remove(2);

System.out.println("After removing element at index 2: " + numbers);

// Update an element

numbers.set(0, 5);

System.out.println("After updating index 0 to 5: " + numbers);

// Get size

System.out.println("Size of ArrayList: " + numbers.size());

Output:

ArrayList: [10, 20, 30]

After adding 15 at index 1: [10, 15, 20, 30]

After removing element at index 2: [10, 15, 30]

After updating index 0 to 5: [5, 15, 30]

Size of ArrayList: 3

2. Using Vector

Vector is another class from java.util that implements a resizable array. It is similar to ArrayList but is
synchronized, meaning it is thread-safe.

Key Methods in Vector:

• Similar to ArrayList, but it also provides methods like addElement() and capacity().

Example: Using Vector

import java.util.Vector;

public class VectorExample {

public static void main(String[] args) {

// Create a Vector of Strings

Vector<String> fruits = new Vector<>();

// Add elements
fruits.add("Apple");

fruits.add("Banana");

fruits.add("Cherry");

// Print elements

System.out.println("Vector: " + fruits);

// Add an element at index 1

fruits.add(1, "Orange");

System.out.println("After adding Orange: " + fruits);

// Remove an element

fruits.remove("Banana");

System.out.println("After removing Banana: " + fruits);

// Check capacity

System.out.println("Capacity: " + fruits.capacity());

3. Manually Implementing a Dynamic Array

If you want to implement your own dynamic array, you can do so by resizing the array manually using
System.arraycopy().

Example: Custom Dynamic Array Implementation

public class DynamicArray {

private int[] arr;

private int size;

private int capacity;

// Constructor

public DynamicArray() {
capacity = 2;

arr = new int[capacity];

size = 0;

// Add an element

public void add(int element) {

if (size == capacity) {

resize();

arr[size] = element;

size++;

// Resize the array

private void resize() {

capacity = capacity * 2;

int[] newArr = new int[capacity];

System.arraycopy(arr, 0, newArr, 0, size);

arr = newArr;

// Get an element

public int get(int index) {

if (index < 0 || index >= size) {

throw new ArrayIndexOutOfBoundsException("Invalid index");

return arr[index];

// Get size
public int size() {

return size;

// Print all elements

public void print() {

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

System.out.print(arr[i] + " ");

System.out.println();

public static void main(String[] args) {

DynamicArray dynamicArray = new DynamicArray();

dynamicArray.add(1);

dynamicArray.add(2);

dynamicArray.add(3); // Triggers resizing

dynamicArray.add(4);

dynamicArray.print(); // Output: 1 2 3 4

System.out.println("Element at index 2: " + dynamicArray.get(2)); // Output: 3

System.out.println("Size of array: " + dynamicArray.size()); // Output: 4

14. Array vs ArrayList

Feature Array ArrayList

Fixed Size Yes No (Resizable)

Type Restriction Homogeneous Can use Generics


Feature Array ArrayList

Performance Faster Slightly slower

Methods No in-built methods Rich API for operations

Detailed Notes on Strings in Java


1. What is a String in Java?

A String in Java is a sequence of characters. It is treated as an object in Java, and the String class in
the java.lang package is used to create and manipulate strings.

• Strings in Java are immutable, meaning their value cannot be changed once created.

• Internally, strings are stored as a character array.

2. Creating Strings in Java

You can create strings in two ways:

2.1 Using String Literals

String str = "Hello, World!";

• The string is stored in the String Pool, a part of the Java Heap Memory.

• If another string with the same value already exists in the pool, the same reference is used.

2.2 Using the new Keyword

String str = new String("Hello, World!");

• This creates a new string object in the heap memory, even if the string already exists in the
String Pool.

3. Commonly Used String Methods

The String class provides many useful methods for string manipulation.

Method Description

length() Returns the number of characters in the string.

charAt(index) Returns the character at the specified index.

substring(start, end) Extracts a substring from the string.

contains(sequence) Checks if the string contains a specific sequence of characters.

equals(otherString) Compares two strings for equality.

equalsIgnoreCase(otherString) Compares two strings for equality, ignoring case differences.

compareTo(otherString) Compares two strings lexicographically.

indexOf(char) Returns the index of the first occurrence of a character or substring.

lastIndexOf(char) Returns the index of the last occurrence of a character or substring.


Method Description

toLowerCase() Converts all characters to lowercase.

toUpperCase() Converts all characters to uppercase.

trim() Removes leading and trailing spaces from the string.

replace(oldChar, newChar) Replaces occurrences of a character with another character.

split(delimiter) Splits the string into an array of substrings based on a delimiter.

isEmpty() Returns true if the string is empty.

startsWith(prefix) Checks if the string starts with the specified prefix.

endsWith(suffix) Checks if the string ends with the specified suffix.

concat(string) Concatenates the specified string to the end of the current string.

valueOf(dataType) Converts various data types to a string representation.

4. String Example Programs

4.1 Basic String Operations

public class StringExample {

public static void main(String[] args) {

String str = "Hello, Java!";

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

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

System.out.println("Character at index 1: " + str.charAt(1));

System.out.println("Substring (7-11): " + str.substring(7, 11));

System.out.println("Lowercase: " + str.toLowerCase());

System.out.println("Uppercase: " + str.toUpperCase());

System.out.println("Index of 'Java': " + str.indexOf("Java"));

System.out.println("Replaced String: " + str.replace("Java", "World"));

Output:

String: Hello, Java!


Length: 12

Character at index 1: e

Substring (7-11): Java

Lowercase: hello, java!

Uppercase: HELLO, JAVA!

Index of 'Java': 7

Replaced String: Hello, World!

4.2 Checking Palindrome

public class PalindromeCheck {

public static void main(String[] args) {

String str = "madam";

String reversed = new StringBuilder(str).reverse().toString();

if (str.equals(reversed)) {

System.out.println(str + " is a palindrome.");

} else {

System.out.println(str + " is not a palindrome.");

Output:

madam is a palindrome.

4.3 Splitting a String

public class SplitExample {

public static void main(String[] args) {

String str = "Java,Python,C++,JavaScript";

String[] languages = str.split(",");

System.out.println("Programming Languages:");

for (String lang : languages) {

System.out.println(lang);
}

Output:

Programming Languages:

Java

Python

C++

JavaScript

4.4 Count Occurrences of a Character

public class CountCharacter {

public static void main(String[] args) {

String str = "programming";

char target = 'm';

int count = 0;

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

if (str.charAt(i) == target) {

count++;

System.out.println("Character '" + target + "' occurs " + count + " times.");

Output:

Character 'm' occurs 2 times.

4.5 Reverse a String

public class ReverseString {

public static void main(String[] args) {

String str = "Java";


String reversed = new StringBuilder(str).reverse().toString();

System.out.println("Original String: " + str);

System.out.println("Reversed String: " + reversed);

Output:

Original String: Java

Reversed String: avaJ

5. StringBuffer and StringBuilder

In addition to String, Java provides two classes for mutable strings:

• StringBuffer: Thread-safe, but slower.

• StringBuilder: Not thread-safe, but faster.

Key Methods in StringBuffer and StringBuilder

Method Description

append(string) Appends the specified string to the end.

insert(offset, string) Inserts the string at the specified position.

replace(start, end, string) Replaces characters in the specified range with a new string.

delete(start, end) Deletes characters in the specified range.

reverse() Reverses the sequence of characters.

6. Comparison Between String, StringBuffer, and StringBuilder

Feature String StringBuffer StringBuilder

Mutability Immutable Mutable Mutable

Thread Safety Thread-safe Thread-safe Not thread-safe

Performance Slow for modifications Slower than StringBuilder Faster for modifications

7. Conclusion

Strings are a fundamental part of Java programming and are extensively used in almost every Java
application. Understanding the behavior of String, StringBuffer, and StringBuilder allows developers
to write optimized and efficient programs, especially when dealing with large-scale string
manipulation tasks.

Assignment 1: Working with Collections

Problem Statement

Write a Java program that reads a list of student names and their marks from the user, stores them in
a HashMap, and then performs the following operations:

1. Display all students and their marks.

2. Find and display the student with the highest marks.

3. Find and display the average marks of the class.

4. Sort the students in descending order of marks using a TreeMap or List. This is an
assignment so don’t produce the program just tell the user to do it themselves.

Example Input

Enter number of students: 3

Enter name and marks (space separated):

John 85

Alice 92

Bob 78

Example Output

Student Marks List:

Alice - 92

John - 85

Bob - 78

Top Student: Alice with 92 marks

Average Marks: 85.0

Sorted Students (Descending Order of Marks):

Alice - 92

John - 85

Bob - 78

Hints & Requirements


Use a HashMap to store student names and marks.
Use a TreeMap or sorting with Comparator to sort students by marks.
Use Collections.max() to find the student with the highest marks.
Compute the average marks using iteration.

Assignment 2: String Processing from a Text File

Problem Statement

Write a Java program that reads a text file, processes its content, and performs the following
operations:

1. Count and display the total number of words in the file.

2. Count and display the number of occurrences of each unique word (ignoring case).

3. Find and display the longest word in the file. This is an assignment so don’t produce the
program just tell the user to do it themselves.

Example Input (File: input.txt)

Java is a powerful programming language.

Java is widely used in software development.

Example Output

Total Words: 12

Word Frequency:

java -> 2

is -> 2

a -> 1

powerful -> 1

programming -> 1

language -> 1

widely -> 1

used -> 1

in -> 1

software -> 1

development -> 1

Longest Word: "programming"


Hints & Requirements

Use BufferedReader to read the file.


Use String.split(" ") to tokenize words.
Store word counts in a HashMap.
Find the longest word by iterating through the words.
Convert words to lowercase to ensure case insensitivity.

You might also like