JAVA CLASS NOTES
-KARUNAKAR PUSULURI
What is a Language?
🔹 Introduction
Language is one of the most powerful tools ever developed by humans. It serves as the
foundation of all communication, whether verbal or written, personal or professional, human
or machine. In the context of computer science, understanding the concept of "language" lays
the groundwork for learning programming languages, software design, logic building, and
more.
🔹 1.1 Definition of Language
A language can be defined as a structured system of symbols, governed by rules, that enables
humans (or machines) to communicate ideas, emotions, intentions, and information. It
provides a mechanism for expressing thoughts through a commonly accepted medium — such
as words, gestures, or symbols.
In linguistics, language refers to natural languages like English, Hindi, or Spanish, which evolve
over time, used for interpersonal communication. In contrast, in computing, language refers
to formal systems used to instruct a machine to perform specific tasks.
🔹 1.2 Characteristics of a Language
Every language, whether natural or artificial, possesses the following core features:
1. Alphabet / Symbols
Every language has a basic set of characters or symbols.
● In natural languages, this is the alphabet (A-Z, a-z, punctuation).
● In programming languages, these include letters, digits, operators (+, -, *, etc.), and
special symbols ({, }, ;, etc.).
2. Syntax
Syntax refers to the set of rules that determine the correct arrangement of symbols and words
in a language. Just as in English, a sentence must have a subject and verb, programming
languages also require specific syntax like semicolons at the end of statements or specific
order of commands.
Example:
✅
● English: "He is eating."
● Programming: int x = 5; ✅
Syntax errors occur when rules are violated.
3. Semantics
Semantics refers to the meaning of the syntactically correct sentence or instruction.
A sentence may be grammatically correct but semantically incorrect.
Example:
● English: "The sky eats quickly." → grammatically correct but semantically meaningless
● Code: int x = "Hello"; → valid syntax, but semantically wrong in many languages
4. Pragmatics (mostly in human languages)
It relates to contextual meaning — how meaning changes with tone, situation, or intent.
This component doesn’t apply much to computer languages as they are literal and rigid.
🔹 1.3 Natural Language vs Formal Language
Feature Natural Language Formal (Programming) Language
Developed By Humans (evolution over time) Humans (intentionally designed)
Structure Often flexible, context-based Strict syntax and semantics
Purpose Human-to-human communication Human-to-machine instruction
Tolerance to High – mistakes understood via Low – syntax errors cause failure
Error context
Example English, Hindi Java, C++, Python
🔹 1.4 Language in the Context of Computing
In computing, the term "language" refers specifically to programming languages, which are
formal languages composed of instructions that produce a variety of outputs. These
languages are used to implement algorithms and to control the behavior of a machine
(usually a computer).
Computers, at the lowest level, understand only binary — strings of 0s and 1s. However,
binary is hard for humans to read and write. So, programming languages act as a medium of
translation between human logic and machine instructions.
🔹 1.5 Why is a Language Required in Computing?
1. To Instruct Machines: Computers cannot understand natural language directly.
Programming languages serve as a bridge.
2. To Write Algorithms: They help express problem-solving logic in a precise manner.
3. To Improve Productivity: High-level languages make it easier and faster to write, test,
and debug programs.
4. To Achieve Reusability: Languages provide structures like functions and modules for
reusable code.
5. To Standardize Communication: A programming language provides a universal
standard that can be understood by developers around the world.
🔹 1.6 Evolution of Language in Computing
1. Machine Language (1st Generation)
● Binary (0s and 1s) directly understood by the computer.
● Example: 10111001 0000111
2. Assembly Language (2nd Generation)
● Low-level code using mnemonics.
● Example: MOV A, B
3. High-Level Languages (3rd Generation)
● Human-readable, portable, and easier to write.
● Example: Java, C, Python
4. Very High-Level / 4GL (4th Generation)
● Focused on specifying what should be done, not how.
● Example: SQL, MATLAB
🔹 1.7 Importance of Language in Programming
● Precision: A language ensures that a task is described clearly.
● Automation: Once written, the instructions can be executed repeatedly.
● Efficiency: A proper language saves time in development and debugging.
● Platform Compatibility: Some languages (like Java) allow code to run on any platform.
● Modularity: With support for functions, classes, and modules, languages allow
scalable applications
🔹 1.8 Real-World Analogy
Let’s compare it to a cooking recipe:
Cooking Programming
Ingredients Variables
Recipe steps Program
instructions
Chef CPU / Compiler
Cooking time Execution time
Final dish Program output
What is a Program and What is a Programming Language?
🔹 2.1 Introduction
The digital world around us—from smartphones and web browsers to banking systems and
satellites—is powered by programs written in programming languages. To understand
software development, it's essential to understand what a program is, and what a
programming language is. This chapter explores both concepts in detail, their purpose, their
relationship, and why programming languages are indispensable in the world of computing.
🔹 2.2 What is a Program?
📖 Definition:
A program is a well-defined, finite set of instructions written in a programming language that
tells a computer what to do. These instructions are designed to perform a specific task or
solve a particular problem when executed by the computer.
🔎 Detailed Explanation:
● A program is essentially a recipe for the computer.
● It contains a sequence of commands or logic that the computer follows step-by-step.
● The output of a program depends on the input provided, the logic defined, and the
language used.
Components of a Program:
Component Description
Instructions Step-by-step operations (e.g., add, print, calculate,
compare)
Variables Named memory locations to store and manipulate data
Control Structures Direct the flow of program execution (e.g., if-else, loops)
Functions/Methods Logical blocks that group reusable code
Input/Output Mechanisms for interacting with users or files
🧠 Example (Simple Program in Java):
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
➡ This program contains:
● A class definition (HelloWorld)
● A main method (entry point)
● A print statement to display text
🧾 Real-Life Analogy:
Real-Life Task Program Equivalent
Following a recipe Executing a program
Recipe steps Instructions in program
Cook Processor/CPU
Ingredients Input/Variables
Final Dish Output/Result
🔹 2.3 What is a Programming Language?
📖 Definition:
A programming language is a formal language consisting of a set of syntax rules, keywords,
and semantics, used to write programs that can be understood and executed by a computer.
It acts as a medium through which humans communicate instructions to machines.
🔍 Why a Special Language is Required?
● Computers understand only binary (0s and 1s), not human language.
● Programming languages abstract away the complexity of binary and provide a
human-readable structure.
● They bridge the gap between human intention and machine execution.
💬 Classification of Programming Languages:
Type Description Example
Low-Level Language Close to machine code, difficult to Assembly
understand
High-Level Language Closer to English, easier to use Java, Python, C++
Domain-Specific Specialized for particular tasks SQL (databases), HTML
Scripting Language Used for automation or light coding JavaScript, Python
📑 Elements of a Programming Language:
Element Description
Syntax Rules for writing valid code
Keywords Reserved words with special meaning (e.g., if, for, while)
Operators Symbols that perform operations (+, -, *, /)
Data Types Define the kind of data being used (e.g., int, float, boolean)
Control Structures Direct program flow (e.g., conditionals, loops)
Libraries/APIs Predefined code that provides functionality (e.g., java.util.*)
🔹 2.4 Relationship Between Program and Programming Language
● A program is like a story.
● A programming language is like the language used to write that story.
Just like a story can be written in English, Hindi, or French…
A program can be written in Java, Python, or C++.
📚 Example:
Task Language Code Example
Print a Java System.out.println("Hello");
message
Python print("Hello")
C++ cout << "Hello";
All do the same thing, but use different syntax because they're written in
different programming languages.
🔹 2.5 Why Are There So Many Programming Languages?
● Each language is designed with specific goals in mind:
○ Speed & Performance (C, C++)
○ Simplicity & Rapid Development (Python)
○ Web Interactivity (JavaScript)
○ Enterprise-Scale Applications (Java)
○ Different tasks require different tools — just like you wouldn’t use a hammer to
cut paper, you shouldn’t use C to build a website UI.
🔹 2.6 Interpreters and Compilers
Programming languages need to be translated into machine language before they can be
executed.
Term Description
Compiler Translates entire code at once into machine code (e.g., Java,
C++)
Interpreter Translates line-by-line during execution (e.g., Python,
JavaScript)
Bytecode Intermediate code (Java) executed by the JVM
JVM Java Virtual Machine – runs Java bytecode on any platform
🔹 2.7 Summary
● A program is a set of written instructions that tell a computer what to do.
● A programming language is the tool used to write those instructions in a format the
machine can understand.
● Programming languages are designed with different goals — speed, simplicity,
security, portability, etc.
● A good understanding of programs and languages is essential for anyone entering the
field of software development.
📝 Exercise:
Q1. Define a program and explain its key components with examples.
Q2. What is the difference between a compiler and an interpreter?
Q3. List 5 programming languages and their main areas of use.
Types of Programming Languages
🔹 3.1 Introduction
Programming languages are not all the same—they are developed with different goals, levels
of abstraction, and programming styles in mind. Understanding the types of programming
languages helps developers choose the right tool for a specific task.
In this chapter, we’ll explore the various classifications of programming languages, each based
on different criteria, such as how close the language is to machine code (abstraction), the
programming paradigm it follows, and the area of application.
🔹 3.2 Classification Based on Level of Abstraction
➤ 1. Low-Level Languages
These are languages that are close to machine-level instructions and offer very little
abstraction. They are often used for direct hardware control.
a. Machine Language (1st Generation)
● Directly written in binary (0s and 1s).
● Specific to hardware architecture (non-portable).
● Extremely difficult and error-prone.
● Fastest in execution as it's directly understood by the CPU.
🧾 Example: 10110000 01100001 ➡ Loads data into a register.
b. Assembly Language (2nd Generation)
● Uses mnemonic codes instead of binary.
● Slightly more readable (e.g., MOV, ADD, JMP).
● Still hardware-specific.
● Requires an assembler to convert to machine code.
🧾 Example: MOV AL, 61h
✅ Use Case: Embedded systems, device drivers, system boot code.
➤ 2. High-Level Languages
These are languages that are more abstract and human-readable. They provide structures like
variables, control statements, functions, etc.
● Portable across systems.
● Easier to write, debug, and maintain.
● Requires a compiler or interpreter.
🧾 Examples: Java, Python, C++, C#, JavaScript
✅ Use Case: Application software, mobile apps, enterprise systems.
➤ 3. Middle-Level Languages
These languages combine low-level and high-level features. They provide access to
hardware-level functions and also support higher-level abstractions.
🧾 Example:
C language – allows pointer manipulation (low-level) and structured programming
(high-level).
🔹 3.3 Classification Based on Programming Paradigm
A programming paradigm is a style or "way" of programming. Languages are often designed
to support one or more paradigms.
➤ 1. Procedural Programming Languages
● Based on the concept of procedure calls (functions).
● Code is executed step-by-step in a linear fashion.
● Focus on what to do and how to do it.
🧾 Examples: C, Pascal, BASIC
🧠 Features:
● Uses variables and loops.
● Emphasizes procedures (functions).
● Less emphasis on data security.
✅ Use Case: System software, simple programs.
➤ 2. Object-Oriented Programming (OOP) Languages
● Based on the concept of objects and classes.
● Emphasizes data encapsulation, inheritance, polymorphism, and abstraction
🧾 Examples: Java, C++, C#, Python
🧠 Features:
● Promotes code modularity and reusability.
● Ideal for large and complex systems.
● Easier maintenance and scaling.
✅ Use Case: Enterprise apps, desktop GUI apps, Android development.
➤ 3. Functional Programming Languages
● Focuses on pure functions and immutable data.
● Avoids changing state and mutable data.
● Uses recursion instead of loops.
🧾 Examples: Haskell, Lisp, Erlang, Scala
🧠 Features:
● No side effects.
● Emphasizes declarative style (what to do, not how).
● Encourages concise and bug-free code.
✅ Use Case: Mathematical computations, concurrency-heavy systems.
➤ 4. Scripting Languages
● Primarily used for automation, web scripting, and quick prototyping.
● Typically interpreted.
● Less concern for strict typing or structure.
🧾 Examples: JavaScript, Python, PHP, Bash
🧠 Features:
● Lightweight.
● Easy to write.
● Often embedded in larger applications.
✅ Use Case: Web development, task automation, DevOps scripting.
➤ 5. Logic Programming Languages
● Based on formal logic and rules.
● Programmer defines what should be true, and the language determines how to satisfy
that.
🧾 Examples: Prolog
🧠 Features:
● Uses facts and rules.
● Common in AI and knowledge-based systems.
✅ Use Case: Expert systems, theorem proving.
🔹 3.4 Classification Based on Application Usage
➤ 1. System Programming Languages
● Designed to create operating systems, compilers, and hardware-level software.
🧾 Examples: C, Assembly
✅ Use Case: Windows kernel, UNIX, drivers.
➤ 2. Application Programming Languages
● Used for building end-user applications such as desktop software, mobile apps, games,
etc.
🧾 Examples: Java, Python, C#
✅ Use Case: Android apps, banking software, CRM systems.
➤ 3. Web Development Languages
● Used for creating websites and web applications.
🧾 Examples:
● Frontend: HTML, CSS, JavaScript
● Backend: PHP, Python, Ruby, Java
✅ Use Case: E-commerce websites, social platforms, SaaS applications.
➤ 4. Database Languages
● Used for interacting with databases, managing records, and performing queries.
🧾 Example: SQL (Structured Query Language)
✅ Use Case: CRUD operations, database schema design.
🔹 3.5 Summary Table
Classification Type Categories
Abstraction Level Low-level, Middle-level, High-level
Programming Paradigm Procedural, Object-Oriented, Functional, Scripting, Logic
Usage/Application System programming, Application development, Web,
Database
📝 Exercises
1. Classify the following languages based on level and paradigm: Java,
Assembly, C, Python
2. Differentiate between procedural and object-oriented languages with
examples.
3. Explain why scripting languages are preferred for automation tasks.
4. Write a short note on functional programming and its benefits.
Which Programming Language to Choose and Why Java?
🔹 4.1 Introduction
There are hundreds of programming languages available today—some general-purpose, some
domain-specific. Choosing the right one can be challenging. The decision depends on various
factors such as:
● The type of application you want to develop
● Your experience and learning curve
● Community support
● Performance needs, and more.
In this chapter, we’ll first discuss how to choose a language and then focus on why Java is one
of the most preferred languages in the software industry.
🔹 4.2 How to Choose the Right Programming Language
Choosing a programming language is like choosing the right tool for the job. Here's what you
should consider:
➤ 1. Project Requirements
● System-level software? → Use C or Rust.
● Web development? → Use JavaScript, Python, PHP.
● Mobile development? → Use Java (Android), Swift (iOS).
● Enterprise-scale backend? → Use Java, C#, Python.
➤ 2. Platform Compatibility
● Need cross-platform support? → Use Java, Python.
● Specific to Windows/macOS/Linux? → Choose accordingly.
➤ 3. Performance Needs
● For speed-critical tasks (e.g., games, simulations): Use C/C++.
● For balanced performance and ease: Use Java or Go.
➤ 4. Learning Curve
● For beginners: Python, JavaScript, Java.
● For experienced developers: Scala, Rust, C++.
➤ 5. Community and Ecosystem
● Popular languages have more resources, frameworks, and support.
● Java, Python, and JavaScript have large communities and extensive libraries.
➤ 6. Job Market and Demand
● In-demand languages increase your employability.
● Java, Python, and JavaScript are among the top in job listings.
🔹 4.3 Why Choose Java?
Java has been one of the most widely used programming languages since its release in 1995.
It is versatile, powerful, and ideal for various types of applications.
✅ Major Reasons to Choose Java:
➤ 1. Platform Independence (WORA)
● Java follows the principle of Write Once, Run Anywhere.
● Java code is compiled into bytecode, which runs on the Java Virtual Machine (JVM).
● This means the same Java program can run on Windows, macOS, Linux, Android, etc.,
without modification.
🧾 Example: You can develop a banking application in Java and deploy it on multiple
operating systems without rewriting it.
➤ 2. Object-Oriented Programming (OOP)
● Java is built entirely on the OOP model.
● It supports principles like Encapsulation, Inheritance, Polymorphism, and Abstraction.
● This encourages modular, maintainable, and reusable code.
🧾 Example: You can create classes like User, Account, and Transaction, each handling its data
and behavior.
➤ 3. Robust and Secure
● Java offers automatic memory management through Garbage Collection.
● Exception handling allows developers to build reliable programs.
● Java does not support pointers, which prevents memory leaks and vulnerabilities.
● Security features include bytecode verification, class loaders, and security APIs.
🧾 Example: Java is widely used in banking and enterprise applications due to its secure
architecture.
➤ 4. Rich Standard Library (Java API)
● Java provides thousands of classes and packages for:
○ File I/O
○ Networking
○ Data Structures
○ Database Access (JDBC)
○ GUI Development (Swing, JavaFX)
○ Multithreading and Concurrency
🧾 Example: You can build a complete desktop app with built-in Java libraries—no need for
third-party tools.
➤ 5. Multithreading and Concurrency
● Java supports multithreading, which allows multiple threads (mini-processes) to run
simultaneously.
● Essential for modern apps like chat servers, game engines, and real-time systems.
🧾 Example: Java can handle 1000+ users chatting at the same time using threads.
➤ 6. Versatility
Java is not limited to one domain. It can be used for:
Application Type Tools/Frameworks
Desktop Applications JavaFX, Swing
Web Applications Spring Framework, JSP, Servlets
Mobile Applications Android SDK
Enterprise Java EE / Jakarta EE
Applications
Cloud Applications Spring Boot, Microservices
Scientific Apps Apache Commons Math, Java
3D
➤ 7. Large Community and Support
● Over 9 million Java developers worldwide.
● Massive online support, forums, tutorials, and documentation.
● Frequent updates and active development under Oracle and OpenJDK.
➤ 8. Tooling and IDE Support
● Excellent support from IDEs like:
○ IntelliJ IDEA
○ Eclipse
○ NetBeans
These tools help with code completion, debugging, testing, refactoring, etc.
➤ 9. Performance
● Java used to be slower, but with JIT (Just-In-Time) compiler and optimizations, Java
performance is close to native code in many cases.
➤ 10. Backward Compatibility
● Programs written in older versions (e.g., Java 6) often work on newer JVMs.
● This ensures long-term reliability and enterprise adoption.
🔹 4.4 Summary Table: Why Java?
Feature Java Advantage
Portability Write Once, Run Anywhere (via JVM)
OOP Clean, organized, modular code
Security No pointers, strong type system, sandbox
execution
Performance Improved through JIT compiler
Libraries & Tools Rich APIs and frameworks
Community Massive support and learning resources
Application Domains Web, Mobile, Cloud, Enterprise, Desktop
📝 Exercises
1. Explain the principle of “Write Once, Run Anywhere” in your own words.
2. What are the benefits of Java being Object-Oriented?
3. Why is Java suitable for large-scale enterprise applications?
4. List five real-world applications that can be built using Java.
5. Compare Java with Python for web application development.
Features of Java
🔹 5.1 Introduction
Java has remained a dominant programming language for decades due to its powerful
features that balance performance, security, and simplicity. Whether you're developing
desktop apps, mobile apps, or enterprise systems, Java offers a robust set of capabilities.
This chapter explores the core features that make Java one of the most reliable and widely
used languages in the world.
🔹 5.2 Key Features of Java (with Detailed Explanations)
✅ 1. Simple
● Java was designed to be easy to learn and use.
● It removes complex features from C/C++, such as:
○ No pointers
○ No operator overloading
○ No multiple inheritance (replaced by interfaces)
● Syntax is clean, readable, and consistent.
🧾 Example: Unlike C++, where memory management is manual, Java handles memory
automatically using Garbage Collection.
✅ 2. Platform Independent
● Java programs are compiled into bytecode instead of platform-specific machine code.
● This bytecode is executed by the Java Virtual Machine (JVM).
● As long as a device has a JVM, it can run Java programs regardless of the operating
system.
🧾 Example: A Java program compiled on Windows can run on Linux or macOS without
modification.
✅ 3. Object-Oriented
Java is fully based on Object-Oriented Programming (OOP), which promotes clean and
modular code.
Core OOP principles Java supports:
● Encapsulation – Bundling data and code together
● Inheritance – Reusing properties from parent classes
● Polymorphism – Performing a single action in different ways
● Abstraction – Hiding internal details and exposing only the functionality
🧾 Example: A Vehicle class can be a parent to Car and Bike classes that inherit common
properties.
✅ 4. Robust
Java emphasizes early error checking, exception handling, and memory management, making
applications stable and error-free.
Key points:
● Uses strong type checking
● Detects many issues at compile-time
● Has automatic garbage collection
● Eliminates memory leaks and crashes due to bad pointer use
🧾 Example: If you try to use a variable without initializing it, Java will throw a compile-time
error.
✅ 5. Secure
Java was built with security in mind, especially for distributed environments like the internet.
Security features:
● No explicit pointers
● Bytecode verification by JVM
● Classloader for loading classes safely
● Security Manager to define access control policies
● Built-in APIs for cryptography, authentication, and secure communication
🧾 Example: Java applets used to run in browsers under a sandbox environment with limited
access.
✅ 6. Multithreaded
Multithreading = multiple threads executing simultaneously.
Java makes it easy to create and manage threads using:
● Thread class
● Runnable interface
● ExecutorService, synchronized keyword, etc.
Benefits:
● Efficient use of CPU
● Smooth user experience in GUI applications
● Useful for servers, games, chat apps, and real-time data processing
🧾 Example: In a music player app, one thread plays audio while another manages the UI.
✅ 7. High Performance
Java is not as fast as C/C++, but it's much faster than purely interpreted languages because of:
● Just-In-Time (JIT) compiler – Compiles bytecode to native machine code at runtime
● Efficient memory management
● Continuous improvements in JVM performance
🧾 Example: Modern Java applications can handle millions of users in web servers like
Apache Tomcat.
✅ 8. Distributed
Java supports building network-based applications with ease.
● Provides classes for networking (in java.net)
● Supports technologies like RMI (Remote Method Invocation) and CORBA
● Often used in distributed systems like enterprise applications and microservices
🧾 Example: A Java server application can call remote services running on different machines.
✅ 9. Dynamic
Java supports dynamic linking and loading of classes at runtime.
● Classes can be loaded on demand
● Supports reflection – allows inspection and modification of classes at runtime
● Enables flexible and adaptable software
🧾 Example: Frameworks like Spring use reflection to manage dependency injection at
runtime.
🔹 5.3 Bonus Features of Java
In addition to the major features, Java also supports:
Feature Explanation
Portable Bytecode ensures the same program runs everywhere
JVM exists
Scalable Ideal for small tools to large-scale enterprise systems
Rich API From data structures to GUIs to networking—Java
provides everything
Tool-rich IDEs, build tools (Maven, Gradle), testing frameworks
Ecosystem (JUnit)
Backward Older code runs on newer JVM versions without needing
Compatibility major changes
🧠 Exercises for Practice
1. What makes Java robust compared to C or C++?
2. Explain how Java supports multithreading with an example.
3. Describe the role of JVM in platform independence.
4. What is the difference between robust and secure in Java context?
5. How does Java support distributed computing?
History of Java
🔹 6.1 Introduction
Understanding the history of Java helps us appreciate why it was created, how it evolved, and
why it remains one of the most important programming languages in the world today. Java
wasn't just a random creation — it was born out of real-world needs for portability, simplicity,
and security.
🔹 6.2 Origins of Java
● Java was created by James Gosling, along with Mike Sheridan and Patrick Naughton, in
1991 at Sun Microsystems, which is now owned by Oracle Corporation.
● The project was initially called "Project Green".
● The first language name was Oak, inspired by an oak tree outside Gosling’s office.
Why Oak?
● Oak was designed for embedded systems and consumer electronics like televisions,
set-top boxes, remote controls, etc.
● Oak was intended to solve the portability issue across devices — write once, run
anywhere.
● However, the name "Oak" was already trademarked, so the name was changed to Java
in 1995.
🔹 6.3 Why the Name “Java”?
● The name Java was chosen from a list of suggestions like Silk, DNA, and Ruby.
● The name refers to Java coffee, which the developers consumed heavily during
development.
● The name represents energy, liveliness, and a sense of innovation.
🔹 6.4 Major Milestones in Java’s History
Year Event
1991 Project Green started by Sun Microsystems
1995 Oak renamed to Java; first public release (Java 1.0)
1996 Java Development Kit (JDK 1.0) released
1997 Java becomes an official ISO and ANSI standard
2004 Java 5 introduced generics, metadata, enumerated types
2006 Java becomes open-source under the GNU General Public
License (OpenJDK)
2009 Oracle acquires Sun Microsystems
2011 Java 7 released with improved performance and new
features
2014 Java 8 released with Lambda expressions, Streams,
Optional
2017 Oracle introduces six-month release cycle for Java updates
2019 Java 12 released with new memory optimizations
2021+ Java 17 becomes the latest Long-Term Support (LTS)
version
🔹 6.5 Why Java Gained Popularity Quickly
1. Platform Independence
Java’s “Write Once, Run Anywhere” (WORA) principle was revolutionary.
2. Security Model
Java introduced a sandbox environment for running potentially unsafe code safely.
3. Web Integration
Java Applets (now obsolete) allowed interactive web content in early browsers.
4. Rich Libraries & APIs
Java came bundled with built-in tools for GUI (AWT, Swing), networking, and file
handling.
5. Enterprise-Readiness
Java Enterprise Edition (J2EE) made it ideal for large-scale enterprise applications.
6. Community Support
An active and growing community led to rapid bug fixes, tutorials, and third-party
libraries.
🔹 6.6 Java Versions Timeline (Brief Overview)
Version Year Highlights
JDK 1.0 1996 Initial release
JDK 1.1 1997 Inner classes, JDBC
Java 2 (JDK 1.2) 1998 Swing, Collections Framework
Java 5 2004 Generics, Annotations, Enum
Java 6 2006 Performance improvements
Java 7 2011 try-with-resources, switch with String
Java 8 2014 Lambdas, Stream API, Date/Time API
Java 9 2017 Project Jigsaw (modularity)
Java 11 2018 LTS version, HTTP Client API
Java 17 2021 LTS, new pattern matching
Java 21 2023 Next LTS release with advanced features
🔹 6.7 Fun Facts About Java
● Java was initially meant for TV remotes, not websites or apps.
● Java is named after coffee, not the island or code.
● Over 3 billion devices run Java — from Android phones to smart cards.
● It’s taught in schools, used in banks, and powers space missions.
🧠 Exercises
1. Who invented Java, and what was its original name?
2. What problem was Java designed to solve in the early 1990s?
3. What does WORA mean, and why is it important?
4. List at least three reasons Java gained popularity so fast.
5. Name any four major features introduced in Java 8.
Difference Between Java and C
🔹 7.1 Introduction
Java and C are two powerful and widely-used programming languages. While both share a
similar syntax, they were designed with different goals and operate in fundamentally
different ways. Comparing these two languages helps in understanding their design
philosophies, use cases, memory management strategies, and programming paradigms.
🔹 7.2 Design Philosophy
Feature Java C
Goal Build portable, secure, Create fast, low-level
object-oriented system software
applications
Target Audience Application developers System programmers
(cross-platform) (hardware-level
control)
Execution Model Compiles to bytecode, Compiles to machine
runs on JVM code, runs directly on
OS
🔹 7.3 Feature-by-Feature Comparison
✅ 1. Programming Paradigm
● Java is Object-Oriented Programming (OOP) based.
○ Everything revolves around classes and objects.
○ Features like encapsulation, inheritance, and polymorphism are core.
● C is Procedural Programming based.
○ Focuses on step-by-step instructions using functions.
○ No built-in concept of objects or classes.
✅ 2. Platform Dependency
● Java is platform-independent due to its JVM (Java Virtual Machine).
○ Code runs on any machine with JVM installed (WORA - Write Once, Run
Anywhere).
● C is platform-dependent.
○ Code must be compiled separately for each operating system and processor
type.
✅ 3. Memory Management
● Java:
○ Uses Automatic Garbage Collection (GC).
○ No explicit use of pointers.
○ Memory leaks are reduced by JVM’s memory management system.
● C:
○ Manual memory management using malloc(), calloc(), free().
○ Explicit use of pointers, which increases flexibility but also risk (e.g.,
segmentation faults, memory leaks).
✅ 4. Compilation and Execution
● Java:
○ Source code → Bytecode → Executed by JVM (interpreted or JIT-compiled).
○ Slightly slower due to JVM overhead, but safer.
● C:
○ Source code → Compiled directly into native machine code.
○ Runs faster but is more prone to low-level bugs.
✅ 5. Syntax and Language Complexity
● Java:
○ Syntax is strict and verbose, but safe.
○ Forces good practices (e.g., error handling, data types).
○ No preprocessor directives (#include, #define).
● C:
○ Simpler and smaller syntax.
○ Offers low-level control, but fewer safety mechanisms.
○ Uses macros and preprocessor directives.
✅ 6. Error Handling
● Java:
○ Has a robust built-in exception handling system.
○ Uses try-catch-finally blocks.
● C:
○ No formal exception system.
○ Error handling is done manually using return codes (if (x == -1)).
✅ 7. Use Cases
Java C
Web applications Operating systems
Android apps Embedded systems
Enterprise software Hardware drivers
Games, GUIs Firmware
Distributed systems Low-level device control
✅ 8. Performance
● Java:
○ Slower than C due to runtime overhead.
○ Modern JVMs with JIT compilation have improved performance significantly.
● C:
○ Extremely fast and efficient.
○ Ideal for systems where performance and resource use are critical.
✅ 9. Pointers
● Java: No pointer support (for safety reasons).
● C: Full pointer support (including pointer arithmetic).
✅ 10. Security
● Java: More secure due to runtime checks, no pointers, and sandboxing.
● C: Less secure due to manual memory access and pointer misuse risks.
🧠 Exercises
1. Why is Java considered safer than C?
2. Explain why Java is platform-independent but C is not.
3. What are the key risks of using pointers in C?
4. In which scenarios would you prefer using C over Java, and why?
5. How does Java's memory management system improve application stability?
Flavours of Java (Java Editions)
🔹 8.1 Introduction
Java is not a single monolithic platform. Instead, it comes in different editions (also referred
to as "flavours") to suit various types of development — from building simple desktop apps to
large-scale enterprise applications and even programming small embedded devices.
Each flavour provides a specific set of libraries, tools, and APIs tailored to different application
requirements.
🔹 8.2 Main Flavours of Java
✅ 1. Java Standard Edition (Java SE)
🔸 Description:
Java SE is the core foundation of the Java platform. It provides all the basic libraries, APIs,
and tools needed to develop general-purpose applications.
🔸 Key Features:
● Core packages like java.lang, java.util, java.io
● Object-Oriented Programming support
● Multithreading and concurrency tools
● Data Structures and Collections Framework
● File I/O operations
● JDBC (Java Database Connectivity)
● Networking (java.net)
● Exception handling and security features
🔸 Use Cases:
● Desktop applications
● Console-based applications
● Foundation for other editions (Java EE, Java FX)
🔸 Tools:
● JDK (Java Development Kit)
● JRE (Java Runtime Environment)
● JVM (Java Virtual Machine)
✅ 2. Java Enterprise Edition (Java EE)
Now known as Jakarta EE after being transferred to the Eclipse Foundation.
🔸 Description:
Java EE is an extension of Java SE, providing APIs and runtime environments for building
large-scale, distributed, multi-tiered, secure enterprise applications.
🔸 Key Features:
● Servlets and JSP (JavaServer Pages)
● EJB (Enterprise JavaBeans)
● JPA (Java Persistence API)
● JMS (Java Message Service)
● JTA (Java Transaction API)
● Web Services (REST, SOAP)
● Dependency injection, context lifecycle management
🔸 Use Cases:
● Web applications (e.g., e-commerce websites)
● Large enterprise software (banking, insurance)
● Middleware and backend services
🔸 Application Servers:
● Apache Tomcat
● GlassFish
● JBoss (WildFly)
● WebLogic
✅ 3. Java Micro Edition (Java ME)
🔸 Description:
Java ME is a lightweight subset of Java SE designed for resource-constrained devices such as
embedded systems and mobile devices.
🔸 Key Features:
● Configurations like CLDC (Connected Limited Device Configuration)
● Profiles like MIDP (Mobile Information Device Profile)
● Optimized for low memory and processing power
● Lightweight virtual machine (KVM)
🔸 Use Cases:
● Early mobile apps (pre-smartphone era)
● Set-top boxes
● IoT (Internet of Things) devices
● Smart cards, Blu-ray players
🔸 Current Status:
● Largely outdated for modern smartphones, which now use Android (Java-based) or
Kotlin.
✅ 4. JavaFX
🔸 Description:
JavaFX is a modern toolkit for building rich graphical user interfaces (GUIs) using Java. It is
intended to replace older GUI systems like Swing and AWT.
🔸 Key Features:
● Modern UI components (charts, forms, tables, web view)
● CSS-based styling
● FXML (an XML-based UI markup language)
● 2D and 3D graphics support
● Media playback support
● Animation and effects
🔸 Use Cases:
● Desktop GUI applications
● Educational tools
● Visualization dashboards
🔸 Tools:
● Scene Builder (drag-and-drop GUI editor)
● Integrates with IDEs like IntelliJ IDEA, Eclipse
🔹 8.3 Other Java-Related Platforms
🔹 Android (Java-based)
● Android apps are written primarily in Java (or Kotlin) and run on the Android Runtime
(ART).
● Uses a different VM (Dalvik or ART), not the standard JVM.
● Android SDK offers a modified version of Java APIs.
🔹 8.4 Summary Table
Java Edition Target Area Primary Use Cases
Java SE Desktop, command-line, Core applications, libraries, tools
general-purpose
Java EE / Jakarta Enterprise & web servers Web apps, distributed enterprise
EE software
Java ME Embedded & small devices IoT devices, smart cards, legacy
mobile devices
JavaFX Rich GUI for desktops Modern desktop applications with
advanced UIs
Android Smartphones & tablets Mobile app development
(Java-based)
🧠 Exercises
1. What is the purpose of Java SE, and how does it differ from Java EE?
2. Why is Java ME no longer popular for mobile development?
3. What are the advantages of using JavaFX over Swing?
4. List three key APIs included in Java EE.
5. Which Java edition would you choose to build a smart TV app, and why?
Introduction to Java Programming
🔹 1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language developed
by James Gosling at Sun Microsystems and officially released in 1995.
The key philosophy behind Java is WORA — Write Once, Run Anywhere. This means that once
you write Java code, it can be run on any machine with a Java Virtual Machine (JVM),
regardless of the underlying hardware or operating system.
Java is known for being:
● Secure
● Robust
● Multithreaded
● Portable
● Platform-independent
🔹 2. Components of Java
Java has three major components that work together to compile and run Java programs:
✅ 2.1 JDK (Java Development Kit)
● A complete software development kit used for developing Java applications.
● Contains:
○ Java Compiler (javac) – Converts .java files to .class bytecode.
○ JVM (Java Virtual Machine) – Runs bytecode.
○ JRE (Java Runtime Environment) – Libraries and files needed for runtime.
○ Other tools: debugger (jdb), documentation generator (javadoc), etc.
✅ 2.2 JRE (Java Runtime Environment)
● Provides the runtime environment to execute Java programs.
● Includes:
○ JVM
○ Core class libraries (like java.lang, java.io, etc.)
● Does not contain compiler or development tools.
✅ 2.3 JVM (Java Virtual Machine)
● The engine that runs Java bytecode.
● Converts platform-independent bytecode into native machine code.
● Handles memory management, garbage collection, security, etc.
🔹 3. Basic Syntax of a Java Program
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Welcome to Java!");
🔹 4. Deep Explanation of the Java Code
Let's now dissect this line by line, deeply and clearly, with the "why" behind every keyword.
✅ 4.1 class HelloWorld
🔹 What is a Class?
● A class is a blueprint or template from which objects are created.
● It defines properties (fields) and behaviors (methods) of objects.
● In Java, everything must be written inside a class, because Java is purely
object-oriented (except for primitive data types).
Example:
class Car {
int speed;
void drive() {
System.out.println("Driving...");
Here, Car is a class with a variable speed and a method drive().
✅ 4.2 public
🔹 What is public?
● It is an access modifier.
● Determines visibility/scope of a class, method, or variable.
● public means it can be accessed from anywhere.
👉 The JVM is external to your class. It needs to access your main() method to start
execution. Hence, main() must be public.
✅ 4.3 static
🔹 What is static?
● static means that the method or variable belongs to the class, not to any object.
● It allows the JVM to call the main() method without creating an object of the class.
🧠 Why static?
Normally, to call a method in Java, you need to create an object:
HelloWorld obj = new HelloWorld();
obj.main(...); // Not possible here
● But since JVM cannot create an object of your class before it runs the program, Java
made the main() method static, so it can be executed directly using the class name.
✅ 4.4 void
🔹 What is void?
● void is the return type of a method.
● It means the method does not return any value.
● Since the main() method is the entry point and not expected to return anything to the
JVM, it is void.
✅ 4.5 main(String[] args)
🔹 What is main?
● It is the entry point of any standalone Java application.
● JVM starts execution from the main() method.
🔹 Why String[] args?
● This is used to accept command-line arguments.
It's an array of strings, where each value is passed during program execution:
java HelloWorld Hi Hello
// args[0] = "Hi", args[1] = "Hello"
🧠 Note:
You can also write this as:
String args[]
Both are valid.
✅ 4.6 System.out.println("Welcome to Java!");
Let’s break it down:
🔹 System
● A final class in java.lang package.
● Contains standard input, output, and error streams.
🔹 out
● A static object of PrintStream class.
● Represents standard output stream, usually the console.
🔹 println()
● A method that prints the given message and then moves to the next line.
● print() would print without a newline.
🔹 "Welcome to Java!"
● A string literal that gets printed.
So this line prints:
Welcome to Java!
🔹 5. How JVM Executes Java Programs
1. You write your code in a .java file.
2. You compile it using javac HelloWorld.java, which creates a .class file containing
bytecode.
3. You run it using java HelloWorld.
4. The JVM:
○ Loads the .class file.
○ Looks for the main() method using its signature: public static void main(String[]
args).
○ Calls it directly (because it is public and static).
○ Starts program execution from that method.
🔹 7. Real-World Analogy
Imagine:
● Class = A machine design
● Object = A machine built using the design
● static = A machine part that works without building the machine
● public = Everyone can see and use this part
● JVM = The engineer who comes to start the machine, but needs a public button
(main()) he can press without building anything
How Java Code Compiles and Executes
Understanding what happens behind the scenes when we write a .java file and run it is crucial
for mastering Java. Let’s break this down deeply and clearly.
✅ 1. Java Program Execution Flow
🔸 Step-by-step:
Step What Happens? Tool/Process Involved
1. You write Java code in a file Text editor / IDE
named HelloWorld.java.
2. You compile it using the javac Java Compiler (part of
command: JDK)
javac HelloWorld.java
3. Compiler generates Intermediate Output
HelloWorld.class file.
This file contains bytecode, not
readable text.
4. You run the program using: Java Virtual Machine
(JVM)
java HelloWorld
5. JVM loads the .class file and Class Loader + Bytecode
looks for: Verifier
public static void main(String[]
args) method.
6. JVM starts executing code from Execution Phase
main() method.
✅ 2. Important Tools Used
🛠️ javac — Java Compiler
● Converts human-readable .java source code into .class bytecode.
● Bytecode is platform-independent.
● It performs:
○ Syntax checking
○ Semantic checking
○ Optimization (basic)
🛠️ java — Java Launcher (JVM)
● This command starts the JVM and passes your class to it.
● JVM performs:
○ Class loading (loads the .class file)
○ Bytecode verification (security check)
○ Just-In-Time compilation (JIT): converts bytecode to native code for execution.
○ Execution of main() method
✅ 3. Compilation vs. Execution (Detailed Flow)
HelloWorld.java --[javac]--> HelloWorld.class --[java]--> JVM loads bytecode -->
Executes main()
✅ Example:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Compilation and Execution Flow");
When you compile:
javac HelloWorld.java
📁 Output: HelloWorld.class
When you run:
java HelloWorld
💻 Output:
Compilation and Execution Flow
✅ 4. What Happens Internally in JVM?
🔸 Class Loader Subsystem:
● Loads .class file into method area.
● Divides memory into sections:
○ Heap (for objects)
○ Stack (for method calls)
○ Method Area (for class-level data like static)
🔸 Bytecode Verifier:
● Checks for security:
○ No illegal memory access
○ No infinite recursion
○ No access to restricted methods
🔸 JIT Compiler:
● Improves speed by converting frequently executed bytecode to native code.
● Runs during execution (Just-In-Time).
✅ 5. Why Java Is Platform-Independent?
Because of the .class (bytecode) file.
● .class files are not specific to any OS or hardware.
● JVM is platform-specific (Windows JVM, Linux JVM, Mac JVM).
So Java code is:
Write Once (compile to bytecode), Run Anywhere (any JVM)
✅ 6. What Happens If You Don’t Compile?
If you try to run without compiling:
java HelloWorld
And HelloWorld.class doesn't exist or is outdated → ❌ Error: class not found or wrong
version
✅ 7. Summary Diagram
Your Code
┌────────────────┐
│ HelloWorld.java│
└────────────────┘
Compile using javac
┌────────────────┐
│HelloWorld.class│ ← contains bytecode
└────────────────┘
│
Run using JVM
┌─────────────────────┐
│ Java Virtual Machine │
└─────────────────────┘
Looks for main() method
Starts execution from main
Why Java Needs public static void main(String[] args) – Every Keyword Explained
This is the entry point of any standalone Java application, and every word in it has a specific
purpose. Let’s break it down like a textbook with examples, memory-level meaning, and
real-world analogies.
🧠 Full Signature:
public static void main(String[] args)
🔸 public – Access Modifier
● Meaning: Makes the method visible to the JVM and other classes.
● If we don't use public, JVM (which is outside your class) cannot access the main()
method → Error!
● Access Modifiers in Java:
○ public: Accessible from anywhere
○ private: Accessible only inside the class
○ protected: Accessible in the same package or by subclasses
○ default (no keyword): Accessible only within the same package
🧠 Real-Life Analogy:
If your method is not public, it’s like keeping the main entrance to a house locked – JVM (the
guest) cannot come in and start anything.
🔸 static – Belongs to the Class, Not to the Object
● Meaning: Tells the JVM that this method belongs to the class itself, not to an object.
● So, JVM can call this method without creating an object of the class.
● If main() were not static, you’d have to create an object to run it, but you need main()
to create objects — this causes a circular dependency (problem).
🧠 Real-Life Analogy:
It’s like an emergency instruction written on the door of a building (class) — you don’t need
to go inside and find someone (object) to read it.
🔸 void – No Return Type
● Meaning: This method doesn't return any value.
● If you write int main(), you must return a value. But main() is just used to start
execution — no return expected.
🧠 Analogy:
You press a button (main), and it starts a machine. You don't expect the button to give you
back a report.
🔸 main – Method Name
● This is a predefined method name.
● JVM specifically looks for main(String[] args) to begin execution.
● If you change the name to start() or begin(), JVM will not find it → ❌ Error.
🔸 String[] args – Command Line Arguments
● Accepts input from the command line when running the program.
● args is just a variable name (can be anything), but String[] is mandatory.
🔹 Example:
public class Demo {
public static void main(String[] args) {
System.out.println("Hello, " + args[0]);
Command:
java Demo Karunakar
Output
Hello, Karunakar
🧬 Deep Internal: How JVM Calls This Method?
When you run: java HelloWorld
JVM:
1. Loads HelloWorld.class
2. Looks for: public static void main(String[] args)
3. Calls it directly without creating an object
4. Execution begins!
If main() is:
● Not public → JVM can't access it
● Not static → JVM must create object → but you need main() to do that → ❌
● Not void → Compilation may pass but JVM doesn't know how to handle return → ❌
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, Java!");
Explanation:
● class HelloWorld – Declares a class (template)
● public static void main... – Entry point
● System.out.println() – Prints a line
🔍 Understanding System.out.println()
Structure: System.out.println("Message");
Part Meaning
System A class in java.lang package
out A static object of PrintStream, representing console
println() A method of PrintStream to print a line
Other Forms:
System.out.print("Hello"); // no newline
System.out.println("World"); // newline after printing
Formatting:
System.out.println("Name\t: Karunakar"); // Adds a tab
System.out.println("Path\nC:\\Program"); // Adds newline
When you run a Java program, it’s like turning on a machine:
1. JVM = Engine
2. Class = Machine Setup
3. main() = Power Button
4. System.out.println() = The light/sound/display that responds
1. What is a class in Java?
🔹 Definition:
A class is a blueprint or template that defines the structure and behavior (data +
actions) of objects.
🔹 Structure:
class ClassName {
// variables (fields or attributes)
// methods (functions or behaviors)
🔹 Example:
class Car {
String color;
int speed;
void drive() {
System.out.println("Car is driving");
🔹 Real-world Analogy:
A class is like an architect’s plan for a house. You don’t live in the plan; you live
in the house (object) built using that plan.
✅ 2. What is an interface in Java?
🔹 Definition:
An interface is a contract that defines a set of abstract methods (by default),
which must be implemented by the classes that use it.
🔹 Key Points:
● Cannot have method bodies (except default/static methods).
● Supports multiple inheritance.
● Used for abstraction and loose coupling.
🔹 Structure:
interface Vehicle {
void start();
void stop();
🔹 Implementing an Interface:
class Car implements Vehicle {
public void start() {
System.out.println("Car started");
}
public void stop() {
System.out.println("Car stopped");
🔹 Analogy:
An interface is like a remote control – it defines what buttons exist, but not how
the device reacts. That’s up to the actual device (class).
✅ 3. What is an enum in Java?
🔹 Definition:
An enum (short for enumeration) is a special data type used to define a fixed set
of constants.
🔹 Structure:
enum Day {
MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY
🔹 Example Usage:
Day today = Day.MONDAY;
System.out.println("Today is: " + today);
🔹 Real-world Analogy:
enum is like a dropdown menu in a form – you must choose from a predefined
list of values.
✅ 4. What is a record in Java?
🔹 Introduced in Java 14 (preview), stable in Java 16.
🔹 Definition:
A record is a special type of class designed to store immutable data — a quick
way to create data carrier classes without boilerplate code (constructors,
getters, toString, equals, hashCode).
🔹 Structure:
record Person(String name, int age) {}
🔹 Usage:
Person p = new Person("Karunakar", 25);
System.out.println(p.name());
System.out.println(p.age());
🔹 Real-world Analogy:
A record is like a read-only ID card — it holds your name and age but doesn’t
change.
✅ 5. Access Modifiers in Java
Access modifiers control visibility/scope of classes, methods, and variables.
Modifier Scope Used Access Level
With
public Everywhere Class, Accessible from any class
Method, in any package
Variable
default (no Package-level Class, Accessible within same
keyword) Method, package
Variable
protected Inheritance + Method, Accessible in same package
package Variable and subclasses
private Class-level Method, Accessible only within
Variable same class
🔹 Example:
public class Person {
private String name; // only accessible within this class
String city; // default/package-private
protected int age; // accessible in subclasses or same package
public void display() { // accessible anywhere
System.out.println("Name: " + name);
interface Printable {
void print();
enum Role {
STUDENT, TRAINER
record User(String name, Role role) {}
class Report implements Printable {
public void print() {
System.out.println("Printing report...");
public class Main {
public static void main(String[] args) {
User u = new User("Karunakar", Role.TRAINER);
System.out.println(u.name() + " is a " + u.role());
Report r = new Report();
r.print();
Variables in Java (Theoretical Notes)
🔶 1. What is a Variable?
In programming, a variable is a symbolic name that refers to a memory location
where data can be stored and manipulated during the execution of a program. It
acts as a container for storing values that can be modified or reused later.
In Java, variables are strongly typed, meaning that each variable must be
declared with a specific data type, such as int, float, or String, which defines
what kind of data it can hold.
🧠 Think of a variable as a labeled box in memory — you label it
(name), define what it can store (data type), and fill it with a value.
🔶 2. Why Do We Need Variables?
● To store user input or results of calculations
● To reuse values without hardcoding them
● To manipulate data dynamically
● To improve code readability and maintainability
Variables are the core component of logic-building in any programming
language, acting as bridges between input, processing, and output.
🔶 3. Classification of Variables in Java
Variables in Java can be broadly classified into two main categories:
+--------------------+
| Variables |
+--------------------+
+----------------+----------------+
| |
Global Variables Local Variables
| |
+-------+--------+ +----------+-----------+
| | | |
Instance Variables Static Local Variable Parameter Variable
(Non-static) (Class Var)
🔷 A. Global Variables
Global variables are declared within a class but outside any method, constructor,
or block. They are accessible throughout the class.
There are two subtypes of global variables:
🔹 1. Instance Variables
● Declared without static inside a class.
● Each object of the class gets its own copy.
● Memory is allocated when an object is created.
● They have default values if not explicitly initialized.
public class Student {
String name; // instance variable
int age; // instance variable
Here, name and age are different for each student object.
🔹 2. Static Variables (Class Variables)
● Declared with the static keyword inside a class.
● Shared among all instances (objects) of the class.
● Memory is allocated only once, at class loading time.
● Used for values that are common to all objects.
Example:
public class Student {
static String college = "ABC College"; // static variable
Every student belongs to the same college, so it makes sense to make it static.
🔷 B. Local Variables
Local variables are declared within a method, constructor, or block and are only
accessible within that scope. They are created when the method is called and
destroyed when the method ends.
🔹 1. Local Variable
● Used inside methods or blocks.
● Must be explicitly initialized before use.
● No default values provided
Example:
void show() {
int count = 10; // local variable
System.out.println(count);
Here, count exists only within the show() method.
🔹 2. Parameter Variable
● These are variables passed to methods or constructors as parameters.
● Treated as local to the method or constructor.
Example:
void greet(String name) { // parameter variable
System.out.println("Hello, " + name);
Here, name is a parameter variable that is passed to the method during the
method call.
🔶 4. Syntax for Declaring Variables
<datatype> <variableName> = <value>;
● Datatype – defines the type of value (e.g., int, float, boolean).
● Variable name – user-defined identifier (e.g., count, name).
● Value (optional) – initial value to assign.
Examples:
int age = 25;
String city = "Hyderabad";
boolean isActive = true;
🔶 5. How to Access Variables
● Local variables – Directly within their scope.
● Instance variables – Through object reference.
● Static variables – Through class name (or directly in same class).
Example:
class Car {
String model; // instance
static int wheels = 4; // static
void display() {
System.out.println(model + " has " + wheels + " wheels.");
Car c1 = new Car();
c1.model = "Honda";
c1.display();
System.out.println(Car.wheels); // Accessing static
🔶 6. Rules for Naming and Declaring Variables in Java
Rule Explanation Example
✅ Must start with a No digits at start name, _value,
letter, _, or $ $result
❌ Cannot use E.g., int, class, int class = 5; ❌
reserved keywords public
✅ Case-sensitive Name ≠ name Both are
different
✅ Use camelCase For better studentName,
convention readability totalAmount
✅ No spaces allowed Use underscore or first_name or
camelCase firstName
❌ Cannot start with 2num is invalid Use num2
number instead
🔶 7. Memory Allocation of Variables
Variable Memory Area Allocated Destroyed When
Type When
Local Stack Method Method completion
invocation
Instance Heap Object Object garbage collected
creation
Static Method Area Class loading Class unloading / end of
program
Data Types in Java
🔶 1. Introduction to Data Types
In Java, a data type specifies the kind of value a variable can hold. Since Java is a strongly
typed language, it requires all variables to be declared with a type before they can be used.
This helps in maintaining type safety and avoiding runtime errors.
📌 A data type defines the size, type of data, and the operations that can be
performed on the data.
🔶 2. Why Do We Need Data Types?
Just like we use different types of containers to store different items in real life
(e.g., bottles for liquids, boxes for books), in programming, data types help
define the right kind of memory structure for storing values and deciding the
valid operations on them.
Benefits of data types:
● Ensures memory optimization
● Provides clarity and correctness
● Enables error checking during compilation
● Promotes type safety
🔶 3. Classification of Data Types in Java
Java classifies data types into two broad categories:
+----------------+
| Data Types |
+----------------+
+----------------+----------------+
| |
+--------+--------+ +---------+---------+
| Primitive Types | | Reference Types |
+-----------------+ +-------------------+
| byte | | Arrays |
| short | | Classes |
| int | | Interfaces |
| long | | Enums |
| float | | Records |
| double | +-------------------+
| char |
| boolean |
+-----------------+
🔷 4. Primitive Data Types
Primitive types are basic building blocks of data manipulation in Java. There are
eight primitive data types categorized based on the nature of the data.
📌 A. Integer Types
Data Size Range Default Description
Type
byte 1 byte -128 to 0 Smallest whole
127 number type
short 2 bytes -32,768 to 0 Useful for
32,767 memory-constrain
ed environments
int 4 bytes -2^31 to 0 Default for integer
2^31 - 1 values
long 8 bytes -2^63 to 0L Used for large
2^63 - 1 integer values
B. Floating-Point Types
Data Size Precision Default Description
Type
float 4 bytes ~6-7 digits 0.0f Used for
saving
memory in
large
floating-point
arrays
double 8 bytes ~15 digits 0.0d Default for
floating-point
values
📌 C. Character Type
Data Size Range Default Description
Type
char 2 bytes 0 to '\u0000' Represents a single
65,535 16-bit Unicode
(Unico character
de)
📌 D. Boolean Type
Data Type Size Values Default Description
boolean JVM-specif true / false Represents
ic (1 bit false logical
logical) values
🔷 5. Reference Data Types
These types refer to objects in memory, unlike primitive types which store actual
values. Reference data types include:
1. Classes
User-defined blueprints from which objects are created.
class Student {
String name;
}
2. Interfaces
Contain abstract methods and are used for implementing polymorphism.
interface Animal {
void sound();
3. Arrays
Used to store multiple values of the same data type.
int[] numbers = {1, 2, 3};
4. Enums
Define a fixed set of constants.
enum Days { MON, TUE, WED }
5. Records (Java 14+)
Immutable data holders with compact syntax.
record Person(String name, int age) {}
Type Casting in Java
🔶 1. Introduction
In Java, Type Casting refers to converting one data type into another. This is a
common and necessary operation when handling different kinds of data and
performing operations across various types. Java being a strongly-typed
language, does not allow mixing of types implicitly in many situations. Hence,
casting ensures that you can convert values from one type to another safely.
📌 Example: Converting a float to an int, or a char to an int.
🔶 2. Why Type Casting?
Type casting is required in the following cases:
● When you want to perform arithmetic or logical operations between
different data types.
● When assigning values from one type to another where automatic
conversion isn't possible.
● When optimizing memory usage (e.g., converting a double to float).
● When interfacing with external systems like databases or files that store
data in different formats.
🔶 3. Types of Type Casting in Java
Java provides two main types of casting:
pgsql
CopyEdit
+----------------------+
| Type Casting |
+----------------------+
+------------+-------------+
| |
+-----------------+ +----------------------+
| Widening Casting| | Narrowing Casting |
| (Implicit) | | (Explicit) |
+-----------------+ +----------------------+
🔷 4. Widening Type Casting (Implicit Casting)
✅ Definition:
Widening casting happens automatically when converting a smaller data type to
a larger one. This is also called upcasting.
✅ Syntax:
smallType variable = value; largeType newVariable = variable;
✅ Example:
int num = 10;
long bigNum = num; // int to long (no manual cast required)
float f = bigNum; // long to float
✅ Order of Widening:
byte → short → int → long → float → double
✅ Why is it safe?
● There's no risk of data loss.
● Java automatically performs this when types are compatible.
🔷 5. Narrowing Type Casting (Explicit Casting)
❌ Definition:
Narrowing casting must be done manually, where a larger data type is converted
to a smaller one. Also called downcasting.
❌ Syntax:
largeType variable = value;
smallType newVariable = (smallType) variable;
❌ Example:
double pi = 3.14159;
int intPi = (int) pi; // Result: 3
❗ Risk:
● Possible loss of data or precision.
● May lead to runtime errors or unexpected results.
🔶 6. Real-World Analogy
● Widening Casting: Pouring water from a cup into a bucket — always fits,
no overflow.
● Narrowing Casting: Pouring water from a bucket into a cup — might
overflow if not careful (i.e., loss of data).
🔷 7. Detailed Examples
✅ Example 1: Widening
byte a = 10;
int b = a; // Widening from byte to int
System.out.println(b); // 10
❌ Example 2: Narrowing
int x = 150;
byte y = (byte) x;
System.out.println(y); // Output: -106 (due to overflow)
🧠 Explanation:
● Byte range: -128 to 127
● 150 is beyond the byte range, so it wraps around
✅ Example 3: Char to Int
char ch = 'A';
int ascii = ch;
System.out.println(ascii); // Output: 65
🔷 8. Type Casting Between Non-Primitive Types
Java also allows casting between reference types (non-primitives), but this
happens via inheritance and interfaces, and includes:
● Upcasting: Subclass to superclass (Implicit)
● Downcasting: Superclass to subclass (Explicit, with type checks)
Example:
class Animal {}
class Dog extends Animal {}
Animal a = new Dog(); // Upcasting
Dog d = (Dog) a; // Downcasting
⚠️ Use instanceof to prevent runtime ClassCastException.
🔷 9. Type Promotion in Expressions
When performing arithmetic operations, smaller data types are promoted
automatically.
Example:
byte a = 10;
byte b = 20;
int result = a + b; // a and b promoted to int automatically
🔎 Even if both a and b are byte, the result is int.
File and Folder Operations Using Terminal (Command Line
Interface)
This chapter covers everything you need to know about managing files and
folders through terminal commands, including navigating, creating, editing,
renaming, copying, deleting, and more. Suitable for Windows CMD,
Linux/macOS terminals, and cross-platform tools like Git Bash or VS Code
Terminal.
🔶 1. Introduction
The terminal (also called the command line or shell) is a text-based interface
that lets users interact with the file system and OS using commands.
Why use the terminal?
● Faster than GUI for repetitive tasks
● Useful in programming and DevOps workflows
● Essential in Linux/Unix environments
🔷 2. Basic Navigation Commands
🔹 pwd – Print Working Directory
Shows the current directory you're in.
pwd
Example Output: /Users/karunakar/Documents
🔹 ls – List Contents of Directory (Linux/mac)
ls
Common flags:
● ls -l → Long listing with details
● ls -a → Show hidden files (starting with .)
📌 On Windows, use:
dir
🔹 cd – Change Directory
cd folderName # Go into folder
cd .. # Go up one level
cd ../.. # Go two levels up
cd / # Go to root
cd ~ # Go to home directory
cd - # Go to previous directory
🔹 Relative vs Absolute Path
● Relative: cd ../images
● Absolute: cd /Users/karunakar/Documents/images
🔷 3. File & Folder Creation
🔹 mkdir – Make Directory
mkdir folderName
✅ Create multiple:
mkdir folder1 folder2 folder3
✅ Nested folders (Linux/mac):
mkdir -p parent/child/grandchild
🔹 touch – Create File (Linux/mac)
touch file.txt
📌 Windows (alternative):
type nul > file.txt
🔹 echo – Create and Write to a File
echo "Hello World" > hello.txt
🔷 4. Open Files & Folders
🔹 start . – Windows
Open the current folder in File Explorer
🔹 open . – macOS
Open current folder in Finder
Open current folder in Visual Studio Code (if installed)
🔷 5. Renaming Files and Folders
🔹 mv (Linux/mac)
Used for both moving and renaming.
✅ Rename a file:
mv oldname.txt newname.txt
✅ Rename a folder:
mv oldFolder newFolder
🔹 ren – Windows
ren oldname.txt newname.txt
ren oldfolder newfolder
🔷 6. Copying Files and Folders
🔹 cp – Copy Files (Linux/mac)
cp file1.txt file2.txt
✅ Copy folder: cp -r sourceFolder destinationFolder
🔹 copy – Windows
copy file1.txt file2.txt
🔹 xcopy – Copy folders in Windows
xcopy folder1 folder2 /E /I
🔷 7. Moving Files and Folders
🔹 mv – (Linux/mac)
mv file.txt ../ # Move up one level
mv file.txt folder/ # Move into another folder
🔹 move – (Windows)
move file.txt folder\
🔷 8. Deleting Files and Folders
🔹 rm – (Linux/mac)
rm file.txt # Delete file
rm -r foldername # Delete folder recursively
rm -rf folder # Force delete (⚠ Dangerous)
🔹 del – Windows (for files)
del file.txt
🔹 rmdir – Remove Empty Folder rmdir emptyFolder
✅ For folders with content in Windows:
rmdir /S folderName
🔷 9. Viewing File Content
🔹 cat – Display file content
cat file.txt
🔹 more, less – Paginated view
less largefile.txt
🔹 type – (Windows)
type file.txt
🔷 10. Editing Files (via CLI)
Linux/macOS: nano, vim, or vi
nano file.txt
vim file.txt
Windows:
notepad file.txt
🔷 11. Hidden Files and Folders
🔹 Create hidden file (Linux/mac)
touch .hiddenfile
🔹 View hidden files
ls -a
📌 On Windows, files starting with . are not auto-hidden — you must use:
attrib +h filename
🔷 12. Permission Management (Linux/mac)
🔹 chmod – Change file permissions
chmod 755 file.sh
🔹 chown – Change ownership
chown user:group file.txt
🔷 13. Miscellaneous Commands
Command Description
clear or cls Clear the terminal screen
history Show previously run commands
whoami Show current user
date Show current date and time
tree Show folder structure in tree format
man command Manual/help page for a command
exit Exit the terminal
🔷 14. Real World Examples (Scenarios)
1. Create a project structure:
mkdir -p myapp/src myapp/tests
cd myapp
touch README.md index.js
code .
2. Move all .txt files to a backup folder:
mkdir backup
mv *.txt backup/
3. Rename an entire folder:
mv draft-version final-version
4. Delete all .log files in folder:
rm *.log
Operators in Java
🔶 1. Introduction
In Java, an operator is a special symbol or keyword that is used to perform specific operations
on one or more operands. These operands can be constants, variables, or expressions.
Operators form the foundation of decision-making and computation in programming.
Without operators, we cannot perform logical operations, arithmetic evaluations, value
comparisons, or bit manipulations.
Operators are integral to writing expressions, which are evaluated to yield a value.
Understanding the types, usage, and precedence of operators is crucial to writing correct and
efficient Java programs.
🔶 2. Definition
Operator:
An operator in Java is a symbol that tells the compiler to perform a specific
mathematical, relational, logical, or bitwise operation and produce a result.
Operand:
An operand is a value or variable on which the operator acts.
Example:
int result = 10 + 20;
Here:
● + is the operator.
● 10 and 20 are operands.
● result is the variable storing the outcome.
🔶 3. Classification of Operators
Java supports a rich set of operators which are categorized based on the type of operations
they perform:
1. Arithmetic Operators
2. Relational (Comparison) Operators
3. Logical Operators
4. Assignment Operators
5. Unary Operators
6. Ternary Operator
7. Bitwise Operators
8. Shift Operators
9. instanceof Operator
10.Miscellaneous Operators
🔶 4. Arithmetic Operators
Arithmetic operators are used to perform basic mathematical operations such as addition,
subtraction, multiplication, division, and modulus.
➤ Operators and Their Functions:
Operator Description Syntax Example Result Description
+ Addition a + b Adds a and b
- Subtraction a - b Subtracts b from a
* Multiplicatio a * b Multiplies a and b
n
/ Division a / b Divides a by b
% Modulus a % b Remainder of a divided by
b
🔹 Important Notes:
● The / operator performs integer division if both operands are integers.
● The % operator is useful to determine whether a number is even or odd.
📌 Example:
int a = 10, b = 3;
System.out.println("Sum: " + (a + b)); // Sum: 13
System.out.println("Modulus: " + (a % b)); // Modulus: 1
🔶 5. Relational (Comparison) Operators
These operators are used to compare two values. They return a boolean result: true if the
condition is satisfied, and false otherwise.
➤ Common Relational Operators:
Operator Description Example Result
== Equal to a == b true/fals
e
!= Not equal to a != b true/fals
e
> Greater than a > b true/fals
e
< Less than a < b true/fals
e
>= Greater than or equal a >= b true/fals
to e
<= Less than or equal to a <= b true/fals
e
📌 Example:
int age = 25;
if (age >= 18) {
System.out.println("Eligible to vote");
}
🔶 6. Logical Operators
Logical operators are used to combine two or more conditions/boolean expressions. They are
primarily used in decision-making and conditional statements such as if, while, etc.
➤ Logical Operators:
Operator Name Description
&& Logical AND Returns true if both conditions are
true
` `
! Logical NOT Reverses the logical state of the
operand
📌 Example:
int age = 20;
int marks = 80;
if (age >= 18 && marks >= 60) {
System.out.println("Qualified");
}
🔶 7. Assignment Operators
Assignment operators are used to assign values to variables. The most basic assignment
operator is =, but Java also supports compound assignment operators that combine
arithmetic operations with assignment.
➤ Common Assignment Operators:
Operator Description Equivalent Expression
= Simple assignment a = b
+= Addition and assignment a += b → a = a +
b
-= Subtraction and a -= b
assignment
*= Multiplication and assign a *= b
/= Division and assign a /= b
%= Modulus and assign a %= b
🔶 8. Unary Operators
Unary operators operate on a single operand. These are commonly used to increment or
decrement values, or to perform logical negation.
➤ Types of Unary Operators:
Operator Description
+ Unary plus (indicates positive)
- Unary minus (negates a number)
++ Increment (prefix or postfix)
-- Decrement (prefix or postfix)
! Logical NOT (negates boolean value)
📌 Prefix vs Postfix:
● Prefix: ++a → value is incremented before use.
● Postfix: a++ → value is used first, then incremented.
🔶 9. Ternary Operator
The ternary operator is the only conditional operator in Java that takes three operands. It is
used as a shorthand for if-else.
➤ Syntax:
(condition) ? value_if_true : value_if_false;
📌 Example:
int age = 16;
String result = (age >= 18) ? "Adult" : "Minor";
🔶 10. Bitwise Operators
Bitwise operators are used to perform operations on individual bits of integers.
➤ Bitwise Operators:
Operator Name Description
& AND Sets bit if both bits are 1
` ` OR
^ XOR Sets bit if bits are
different
~ NOT Inverts all the bits
🔶 11. Shift Operators
Shift operators are used to shift the bits of a number left or right.
Operator Description
<< Left shift
>> Right shift
(sign-propagating)
>>> Unsigned right shift
🔶 12. instanceof Operator
The instanceof operator is used to test whether an object is an instance of a specific class
or subclass.
📌 Syntax:
object instanceof ClassName
📌 Example:
String s = "Java";
System.out.println(s instanceof String); // true
🔶 13. Operator Precedence and Associativity
Precedence determines the order in which operations are performed. Associativity
determines the direction (left-to-right or right-to-left) in which operators of the same
precedence are evaluated.
Precedence Level Operators Associativity
Highest [], (), . Left to Right
++, -- (post) Left to Right
++, --, +, -, !, ~ Right to Left
Medium *, /, % Left to Right
+, - Left to Right
<, >, <=, >=, Left to Right
instanceof
==, != Left to Right
&& Left to Right
Lower ?: (ternary) Right to Left
Lowest =, +=, -=, etc. Right to Left
Control Statements in Java
Control statements are a fundamental part of any programming language. In Java, control
statements are used to control the flow of execution of the program based on specific
conditions. They allow you to make decisions, repeat actions, and jump to specific parts of
code.
Types of Control Statements
Java provides three major categories of control statements:
1. Decision-Making Statements
2. Looping Statements
3. Branching Statements
1. Decision-Making Statements
Decision-making statements allow the program to make decisions and execute particular
blocks of code based on boolean expressions.
1.1 if Statement
The if statement is the simplest form of decision-making. It executes a block of code only if
the given condition evaluates to true.
Syntax:
if (condition) {
// code to be executed if condition is true
}
Example:
int age = 20;
if (age >= 18) {
System.out.println("Eligible to vote");
}
1.2 if-else Statement
The if-else statement provides two paths of execution: one if the condition is true, and
another if the condition is false.
Syntax:
if (condition) {
// executes if condition is true
} else {
// executes if condition is false
}
Example:
int number = -10;
if (number >= 0) {
System.out.println("Positive Number");
} else {
System.out.println("Negative Number");
}
1.3 if-else-if Ladder
Used when multiple conditions need to be checked. It executes the first block where the
condition is true.
Syntax:
if (condition1) {
// code
} else if (condition2) {
// code
} else {
// default code
}
Example:
int marks = 85;
if (marks >= 90) {
System.out.println("Grade A");
} else if (marks >= 75) {
System.out.println("Grade B");
} else if (marks >= 60) {
System.out.println("Grade C");
} else {
System.out.println("Fail");
}
1.4 switch Statement
The switch statement allows you to select one of many code blocks to be executed.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
default:
// default code
}
Example:
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");
}
2. Looping Statements
Looping statements allow a set of instructions to be executed repeatedly until a condition is
met.
2.1 for Loop
Best used when the number of iterations is known.
Syntax:
for (initialization; condition; increment/decrement) {
// code
}
Example:
for (int i = 1; i <= 5; i++) {
System.out.println("Count: " + i);
}
2.2 while Loop
Used when the number of iterations is not known in advance.
Syntax:
while (condition) {
// code
}
Example:
int i = 1;
while (i <= 5) {
System.out.println("Count: " + i);
i++;
}
2.3 do-while Loop
Executes the loop at least once, even if the condition is false.
Syntax:
do {
// code
} while (condition);
Example:
int i = 1;
do {
System.out.println("Count: " + i);
i++;
} while (i <= 5);
3. Branching Statements
Branching statements are used to alter the normal flow of execution by jumping to another
part of the code.
3.1 break Statement
Terminates the loop or switch statement prematurely.
Example (Loop):
for (int i = 1; i <= 10; i++) {
if (i == 5) break;
System.out.println(i);
}
Example (Switch):
switch (grade) {
case 'A':
System.out.println("Excellent");
break;
case 'B':
System.out.println("Good");
break;
default:
System.out.println("Needs Improvement");
}
3.2 continue Statement
Skips the current iteration and jumps to the next iteration.
Example:
for (int i = 1; i <= 5; i++) {
if (i == 3) continue;
System.out.println(i);
}
3.3 return Statement
Exits from the current method and optionally returns a value.
Example:
public int add(int a, int b) {
return a + b;
}
METHODS
In Java, a method is a collection of statements grouped together to perform a specific task. It
enhances modularity, code reuse, and maintainability.
A method in Java is similar to a function in other programming languages.
Java methods are always part of a class and can be executed when they are called or invoked
from other parts of the code.
📚 2. GENERAL METHOD SYNTAX
modifier returnType methodName(parameter1, parameter2, ..., parameterN) {
// method body
// logic or instructions
return value; // required if returnType is not void
}
🔍 Description of Terms:
Term Meaning
modifier Access specifier: public, private, protected, or none (default)
returnType Type of value returned: int, String, double, void, etc.
methodName Identifier, written in camelCase
parameters Inputs provided to method; can be 0 or more
method body The code to be executed when the method is invoked
return Exits the method and returns value if specified
🧩 3. TYPES OF METHODS IN JAVA
Java methods can be classified based on multiple criteria.
🔷 A. Based on Definition
1. Predefined Methods
These are methods already available in Java libraries (like System.out.println(), Math.sqrt(),
etc.).
📌 Example:
System.out.println("Java is fun!"); // println() is a predefined method
2. User-defined Methods
Created by the programmer to perform specific tasks.
📌 Example:
public void greetUser() {
System.out.println("Welcome!");
}
🔷 B. Based on Access
Modifier Access Level
public Accessible from anywhere
private Accessible only within the same class
protected Accessible in the same package or through
inheritance
default (no Accessible only in the same package
modifier)
🔷 C. Based on Return Type
1. Void Methods
These do not return any value.
📌 Example:
public void displayMessage() {
System.out.println("Hello, World!");
}
2. Return Type Methods
These return a value of a specific type.
📌 Example:
public int add(int a, int b) {
return a + b;
}
🔷 D. Based on Parameters
1. Parameterless Methods
public void sayHello() {
System.out.println("Hello!");
}
2. Parameterized Methods
public void greet(String name) {
System.out.println("Hello, " + name);
}
🔷 E. Based on Static/Instance
1. Static Methods
● Belong to the class.
● Can be called without creating an object.
● Useful for utility/helper functions.
📌 Example:
public static void printInfo() {
System.out.println("Static method called");
}
2. Instance Methods
● Belong to an object of the class.
● Require object creation to be accessed.
📌 Example:
public class Student {
String name;
public void displayName() {
System.out.println("Student Name: " + name);
}
}
🔁 4. METHOD CALLING
● Inside the main() method or another method.
● Use the method name (with parameters if any).
Static Method Call:
MethodName(); // if in same class
ClassName.MethodName(); // if in different class
Instance Method Call:
ClassName obj = new ClassName();
obj.methodName();
🔃 5. METHOD OVERLOADING
Method Overloading allows multiple methods with the same name but different parameter
lists.
📌 Rules:
● Number of parameters must differ
● OR type of parameters must differ
📌 Example:
public class Calculator {
public int multiply(int a, int b) {
return a * b;
}
public double multiply(double a, double b) {
return a * b;
}
public int multiply(int a, int b, int c) {
return a * b * c;
}
}
🔄 6. RECURSIVE METHODS
A method that calls itself to solve a problem in smaller parts.
📌 Example: Factorial using recursion
public int factorial(int n) {
if (n == 1)
return 1;
else
return n * factorial(n - 1);
}
🧠 7. RETURN STATEMENT
Used to:
● Exit from a method
● Send a value back to the calling code (except for void)
📌 Example:
public int add(int x, int y) {
return x + y;
}
🧪 8. PRACTICAL EXAMPLES
Example 1: Sum of 2 numbers
public class Example {
public static int sum(int a, int b) {
return a + b;
}
public static void main(String[] args) {
int result = sum(10, 20);
System.out.println("Sum: " + result);
}
}
Example 2: Check Even/Odd
public class CheckEvenOdd {
public static boolean isEven(int n) {
return n % 2 == 0;
}
public static void main(String[] args) {
System.out.println(isEven(10)); // true
System.out.println(isEven(5)); // false
}
}
Example 3: Instance Method Demo
public class Circle {
double radius;
public double getArea() {
return Math.PI * radius * radius;
}
public static void main(String[] args) {
Circle c = new Circle();
c.radius = 5.0;
System.out.println("Area: " + c.getArea());
}
}
🧾 9. DIFFERENCE: STATIC vs NON-STATIC METHODS
Feature Static Method Instance Method
Belongs to Class Object
Accessed by ClassName.method( object.method()
)
Can access Static members only Both static &
instance
Object ❌ No ✅ Yes
required?