Java Unit 1 Notes for BTech CSE (AI & ML) | BEU 3rd Semester Notes

Download Java Unit-1 handwritten notes PDF for BTech CSE (AI & ML) students under Bihar Engineering University (BEU). Covers introduction to Java, history of Java, Java buzzwords, basics of Java programming, etc as per new syllabus 2025–26.

Updated on

Unit- 1.0 Concepts and Java Programming: Introduction to Java: History of java, Java buzzwords, basics of Java programming, difference between procedural and object-oriented programming paradigm, need for OOPs paradigm, OOPs features, advantages of oops, JDK, JRE and JVM, data types, variables, operators, control structures including selection, looping, java methods, compilation, and execution of simple program.

Introduction to Java

Java is a high-level, object-oriented programming language designed to create secure, portable, and reliable software. It follows the principle of “write once, run anywhere,” which means a program written in Java can run on different systems without modification.

Java applications are widely used in web development, mobile apps, enterprise systems, and many other platforms due to its strong memory management, built-in security features, and simple syntax.

• Developed by Sun Microsystems in 1995 by James Gosling
• Designed to be platform independent through the Java Virtual Machine
• Used for building desktop, web, and mobile applications
• Provides strong security and automatic memory management

History of Java

Java began as a project aimed at creating software that could run on many different types of devices without needing separate versions. It was originally designed for embedded systems but later evolved into a major programming language for general-purpose use.

Its platform independence, security features, and simplicity made it popular worldwide. Over time, Java versions improved performance, added new libraries, and expanded support for web, mobile, and enterprise applications.

• Started in 1991 at Sun Microsystems under the Green Project
• Created by James Gosling and his team
• First name was Oak, inspired by an oak tree outside Gosling’s office
• Renamed to Java in 1995 because Oak was already trademarked
• Designed to solve platform dependency by using the Java Virtual Machine
• Initially focused on consumer electronic devices
• Officially released as Java 1.0 in January 1996
• Promoted with the slogan “Write Once, Run Anywhere”
• Gained popularity with the introduction of applets for web browsers
• Further matured with Java 2 (J2SE, J2EE, J2ME) in 1998
• Oracle Corporation acquired Sun Microsystems in 2010 and took over Java development
• Java versions continued with regular updates including Java 8, Java 11, Java 17, and later long-term support releases
• Today used in enterprise applications, Android development, cloud systems, and large-scale distributed platforms

Java Buzzwords

Java is described using several key features known as buzzwords. These buzzwords capture the main goals behind Java’s design and explain why it became a widely used programming language.

They highlight Java’s focus on simplicity, security, portability, reliability, and performance. Understanding these buzzwords helps you see what makes Java different from older languages and why it is suitable for building applications on various platforms.

• Simple
• Object-oriented
• Platform independent
• Secure
• Robust
• Multithreaded
• Portable
• High performance
• Architecture neutral
• Distributed
• Dynamic

Features of Java

  • Simple: Java was designed to be easy to learn for programmers familiar with C/C++, by removing complex and error-prone features like explicit pointers and header files.

  • Object-Oriented: The language is based entirely on the object-oriented programming (OOP) paradigm, where everything revolves around classes and objects.

  • Platform-Independent / Architecture-Neutral: Java achieves this "write once, run anywhere" capability through the use of an intermediate representation called bytecode. This bytecode is executed by the Java Virtual Machine (JVM), which is available for many different operating systems and hardware architectures.

  • Robust: Java is designed for reliability by implementing strong memory management (automatic garbage collection), strong type checking, and comprehensive exception handling.

  • Secure: Programs run within a confined execution environment (the "sandbox" model enforced by the JVM) which restricts access to system resources and protects against malicious code.

  • Multithreaded: The language has built-in support for concurrent, multi-threaded programming, allowing programs to perform multiple tasks simultaneously.

  • Portable: Beyond platform independence, Java ensures consistency by defining fixed sizes for all primitive data types, eliminating system-dependent variations found in other languages like C/C++.

  • Rich API and Standard Libraries: Java provides extensive built-in libraries for various programming needs.

  • Frameworks for Enterprise and Web Development: Java supports frameworks that simplify enterprise and web application development.

  • Open-Source Libraries: Java has a wide range of libraries to extend functionality and speed up development.

  • Maintainability and Scalability: Java’s structured design allows easy maintenance and growth of applications.

  • Interpreted / High Performance: The Java bytecode is interpreted by the JVM, but modern JVMs use Just-In-Time (JIT) compilation to convert frequently executed bytecode into native machine code on the fly for better performance.

  • Distributed: Java handles TCP/IP protocols and features like Remote Method Invocation (RMI), which facilitate the creation of distributed applications across networks.

  • Dynamic: Java is capable of dynamically linking code and loading new classes as a program runs, allowing for flexible, evolving software environments. 

Procedural Programming

Procedural programming is a programming approach where a problem is solved by writing a set of instructions in a step-by-step manner. The program is divided into procedures or functions, and the focus is on the sequence of actions to be performed. Data is usually kept separate from functions, and functions operate on that data. This approach works well for smaller programs but becomes difficult to manage as the project grows because data is not well protected and code reuse is limited.

• Follows a top-down approach
• Program divided into functions or procedures
• Focuses on steps and logic flow, not on data
• Data is usually exposed and can be accessed freely
• Does not support concepts like classes and objects
• Harder to manage large and complex applications
• Less secure because data hiding is not supported
• Limited code reusability
• Examples of procedural languages: C, Pascal, Fortran

 

Object-Oriented Programming (OOP)

Object-oriented programming is a programming approach that organizes software into objects that contain both data and the functions that operate on that data. Instead of focusing on step-by-step procedures, OOP models real-world entities through classes and objects, making programs easier to build, maintain, and expand. It supports features like encapsulation, abstraction, inheritance, and polymorphism, which help in creating secure, reusable, and modular code.

• Uses a bottom-up design approach
• Program is built using classes and objects
• Data and functions are bundled together inside objects
• Supports data hiding and abstraction
• Improves code reusability through inheritance
• Allows method overloading and overriding through polymorphism
• Makes large applications easier to maintain
• Encourages modular and organized design
• Examples of OOP languages: Java, C++, Python

Difference Between Procedural Programming and Object-Oriented Programming

Procedural programming focuses on a sequence of steps or instructions to solve a problem, while object-oriented programming focuses on objects that contain both data and functions.

Procedural programming separates data from functions and becomes harder to manage in large applications. OOP organizes code into reusable objects, supports data hiding, and makes complex software easier to develop and maintain.

Procedural Programming (PP)

Object-Oriented Programming (OOP)

Follows a top-down approach

Follows a bottom-up approach

Program is divided into functions or procedures

Program is divided into classes and objects

Focuses on functions and logic flow

Focuses on objects and their interactions

Data is separate from functions

Data and functions are combined inside objects

Does not support data hiding

Supports data hiding using encapsulation

Less secure because data is openly accessible

More secure due to private and protected members

Reusability is limited

High reusability through inheritance

Does not support abstraction, inheritance, or polymorphism

Fully supports abstraction, inheritance, and polymorphism

Difficult to manage for large applications

Easier to maintain large and complex applications

Less flexible for real-world modeling

Models real-world entities effectively

Examples: C, Pascal, Fortran

Examples: Java, C++, Pytho

Need for OOPs Paradigm

The OOP paradigm is needed because modern software systems have become large, complex, and harder to manage using traditional procedural programming.

By combining data and functions into objects, OOP helps create software that is more organized, secure, reusable, and easier to maintain.

It supports features like encapsulation, inheritance, and polymorphism, which reduce repetition and allow developers to build scalable applications that reflect real-world structures.

• Helps manage large and complex applications
• Combines data and functions in one unit for better organization
• Supports data hiding to improve security
• Reduces code duplication through inheritance
• Makes programs easier to update and maintain
• Encourages modular programming
• Matches real-world entities, making design more natural
• Improves code reusability and flexibility
• Enables better teamwork and structured development

OOP Features

OOP features provide the foundation for building organized, reusable, and secure programs. These features allow developers to group data with functions, hide internal details, create new classes from existing ones, and write flexible code that behaves differently based on context. Together, these features make object-oriented programming suitable for developing large and maintainable applications.

• Class
• Object
• Encapsulation
• Abstraction
• Inheritance
• Polymorphism
• Message passing

 

Class

A class is a blueprint or template used to create objects. It defines the data and the functions that belong to the objects created from it. A class itself does not store real data; it only describes what the objects will contain and how they will behave.

• Contains variables and methods
• Does not take memory until an object is created
• Helps organize code into logical units
• Allows creation of multiple objects with the same structure

Object

An object is an instance of a class that holds actual data and can perform actions defined in the class. Each object created from a class has its own copy of the data and can interact with other objects in a program.

• Created from a class
• Occupies memory
• Represents real-world entities
• Can access methods and variables of its class

 

Encapsulation

Encapsulation is the process of keeping data and methods together inside a class while restricting direct access from outside. It protects the data by allowing access only through methods, improving security and control.

• Achieved using private, protected, and public keywords
• Hides internal data from direct modification
• Increases security and data protection
• Makes code easier to manage

Abstraction

Abstraction represents only the essential features of an object while hiding unnecessary details. It simplifies complex systems by showing only what is required for the user and hiding how the logic actually works.

• Provides a clear view of important functions
• Hides internal implementation
• Achieved using abstract classes and interfaces
• Makes software easier to understand and use

Inheritance

Inheritance allows a new class to take the properties and methods of an existing class. It helps reduce code duplication and supports the creation of hierarchical relationships between classes.

• Helps reuse existing code
• Supports multilevel and hierarchical structures
• Child class extends the parent class
• Allows method overriding

 

Polymorphism

Polymorphism allows the same function or method to behave differently depending on the object or the situation. It makes the code flexible by supporting multiple forms of the same action.

• Two types: compile-time and run-time
• Achieved using method overloading and overriding
• Improves flexibility and readability
• Reduces repetitive code

Message Passing

Message passing is the process of objects communicating with each other by sending and receiving information through method calls. It allows interaction between different parts of a program.

• Objects request actions from each other
• Achieved through method invocation
• Supports modular and cooperative design
• Helps objects work together in solving tasks

 

Advantages of Oops

Object-Oriented Programming (OOP) in Java offers numerous advantages centered around structuring code into self-contained objects, leading to better organization, reusability, and maintainability. 

The primary benefits are derived from the four pillars of OOP: 

  • Modularity and Code Organization: OOP breaks down large systems into smaller, manageable, and self-contained units (objects). This modular structure makes the code easier to understand, manage, and debug.

  • Code Reusability (Inheritance): Inheritance allows new classes to inherit properties and behaviors from existing classes, reducing the need to write redundant code and saving development time.

  • Data Hiding and Security (Encapsulation): Encapsulation bundles data and methods that operate on that data into a single class and restricts direct access to internal states. This protects data integrity, prevents unauthorized modification, and simplifies troubleshooting by localizing potential issues.

  • Flexibility and Extensibility (Polymorphism): Polymorphism allows objects of different classes to be treated as objects of a common superclass, enabling a single interface to represent multiple data types. This makes the code more adaptable and easier to extend with new classes or functionality.

  • Simplified Complexity (Abstraction): Abstraction helps manage complex systems by hiding unnecessary implementation details and exposing only the essential features. This allows developers to focus on high-level logic and simplifies the design process.

  • Easier Troubleshooting and Maintenance: The self-contained nature of objects means that when an issue arises, developers can often isolate the problem to a specific object or class, speeding up debugging and reducing the risk of unintended side effects when making changes.

  • Real-World Modeling: OOP naturally models real-world entities and their relationships, which makes designing software more intuitive and easier to map to actual problem domains.

  • Scalability: The modular and well-organized structure of OOP makes it easier to scale applications and manage large, complex projects effectively.

  • Improved Collaboration: The division of work into independent classes and modules facilitates teamwork, allowing multiple developers to work on different parts of the project simultaneously without interfering with each other's code.

  • Message passing: Message passing techniques is used for communication between objects which makes the interface descriptions with external systems much simpler.

Basics of Java Programming

• A Java program must be written inside a class
• File name must match the public class name
• Java is case-sensitive
• Statements end with a semicolon
• Blocks of code are written inside { }
• Execution always starts from public static void main(String[] args)

Basic Java Program Syntax

Syntax:

class ClassName {

    public static void main(String[] args) {

        System.out.println("Hello Java");

    }

}

• class ClassName defines the class
• public static void main(String[] args) is the entry point
• System.out.println() prints output
• Curly braces define blocks

 

Class Syntax

class ClassName {

    // variables

    // methods

}

• Class name should start with a capital letter
• Contains variables and methods
• Only one public class per file

 

Main Method Syntax

public static void main(String[] args)

public allows JVM to access it
static allows calling without creating an object
void means no return value
String[] args stores command-line input

 

Printing in Java

System.out.println("Message");

System.out.print("Message");

println prints with a new line
print prints on the same line

Saving a Java File and File Naming Rules

A Java program must be saved with the same name as the public class inside the file. The file must have the .java extension because the Java compiler only reads .java source files.

When saving a Java file, you must ensure the class name and file name match exactly, including uppercase and lowercase letters, because Java is case-sensitive.

  • A Java file must be saved with .java extension

  • File name must match the public class name

  • Example: class name MyProgram → file name MyProgram.java

  • Only one public class is allowed per file

  • If there is no public class, file can have any name

  • Java is case-sensitive, so Main.java and main.java are different

Compiling a Java Program

Compilation converts human-readable Java code into bytecode. This step is necessary because the JVM cannot understand .java files directly. The Java compiler javac checks for syntax errors and generates a .class file containing bytecode.

  • Compile using the command: javac FileName.java

  • Compiler creates a .class file with bytecode

  • Bytecode is platform independent

  • Syntax errors must be fixed before successful compilation

  • Example: javac MyProgram.java produces MyProgram.class

Java Interpreter and JVM

Java uses an interpreter called the Java Virtual Machine (JVM) to run bytecode. The JVM reads the .class file and converts bytecode into machine code for your operating system. This is why Java programs can run on any device that has a JVM.

  • JVM interprets and runs bytecode

  • Converts bytecode into machine code (line by line or JIT compiled)

  • Makes Java platform independent

  • Different operating systems have different JVM implementations

  • JVM also manages memory and garbage collection

Execution of a Java Program

Execution begins when the user runs the java command. The JVM loads the class, finds the main method, and starts executing statements inside it. The whole process involves class loading, bytecode verification, interpretation, and execution.

  • Execute using: java ClassName

  • Do not include .class or .java while running

  • JVM first loads the class using the class loader

  • Bytecode is verified for security

  • JVM executes bytecode using the interpreter or JIT compiler

  • Program starts from public static void main(String[] args)

 

Full Flow of Writing and Running a Java Program

This is the complete life cycle from writing to executing:

  • Write the code inside a class

  • Save the file as ClassName.java

  • Compile using: javac ClassName.java

  • Compiler produces: ClassName.class

  • Run using: java ClassName

  • JVM reads bytecode and executes the program

Understanding the Hello World Program in Java

When we learn any programming language, the first step is writing a simple program to display "Hello World". So, here is a simple Java program that displays "Hello World" on the screen.

// A Java program to print Hello World!

public class HelloWorld {

    public static void main(String[] args) {

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

    }

}

Output
Hello World!

How to run the above code?

  • Java Compiler "javac" compiles it into bytecode "HelloWorld.class".

  • JVM (Java Virtual Machine) reads the .class file and interprets the bytecode.

  • JVM converts bytecode to machine readable code i.e. "binary" (001001010) and then execute the program.

Famous Applications Built Using Java

  • Android Apps: Most of the Android mobile apps are built using Java.

  • Netflix: This uses Java for content delivery and backend services.

  • Amazon: Java language is used for its backend systems.

  • LinkedIn: This uses Java for handling high traffic and scalability.

  • Minecraft: This is one of the world’s most popular games that is built in Java.

  • Spotify: This uses Java in parts of its server-side infrastructure.

  • Uber: Java is used for backend services like trip management.

  • NASA WorldWind: This is a virtual globe software built using Java.

What Can We Do with Java?

  • Mobile App Development: Android development using Android Studio.

  • Desktop GUI Applications: With libraries like JavaFX and Swing.

  • Enterprise Applications: Backbone of banking, ERP and large-scale business software.

  • Game Development: With engines like LibGDX and jMonkeyEngine.

  • Internet of Things (IoT): Java can run on embedded systems and devices.

  • Scientific Applications: Java is used in tools that process large amounts of scientific data.

JDK (Java Development Kit)

The Java Development Kit (JDK) is a comprehensive software package for developers that provides all the tools, compilers, and libraries needed to write, compile, debug, and run Java applications. 

It contains all the tools and libraries a programmer needs, including the compiler, JVM, and development utilities.

Without the JDK, writing and building Java programs is not possible because it provides the essential components required for creating Java applications.

  • Stands for Java Development Kit.

  • It works together with the JVM (Java Virtual Machine) and JRE (Java Runtime Environment) as part of the core Java setup.

  • Required for writing, compiling, and running Java programs.

  • Contains the Java compiler (javac).

  • JDK = JRE + JVM + Development Tools

  • Provides tools like debugger, jar tool, documentation generator.

  • Used only by developers, not by end users.

  • Installed separately for each JDK version (e.g., JDK 8, JDK 11, JDK 17).

  • Available for Windows, macOS, and Linux.

 

Contents of JDK

The JDK includes all components that are essential for creating a Java application.

  • Java Runtime Environment (JRE)

  • A private JVM used only by the JDK

  • Java compiler (javac)

  • Java interpreter/loader (java)

  • Archiver tool (jar)

  • Documentation generator (javadoc)

  • Debugging tools

  • Extra libraries useful to developers (internationalization, IDL libraries)

 

The JDK is the core component for Java programming and includes the following main parts: 

  • Java Runtime Environment (JRE): This provides the necessary environment to run Java programs and includes the Java Virtual Machine (JVM) and core class libraries.

  • Development Tools: These are command-line utilities for creating the application:

    • javac: The Java compiler, which translates Java source code (.java files) into platform-independent bytecode (.class files).

    • java: The application launcher/interpreter that starts the JRE and executes the bytecode.

    • jar: The archiver tool used to package related class files and resources into a single Java Archive (.jar) file for easy distribution.

    • javadoc: The documentation generator that creates HTML API documentation from comments in the source code.

    • jdb: The debugger for finding and fixing errors in Java programs.

    • Other tools for monitoring, management, and security, such as jconsole, jps, and keytool. 

 

 

Popular JDK Distributions

Different vendors provide their own builds of the JDK.

  • Oracle JDK

  • OpenJDK (official open-source version)

  • Amazon Corretto

  • Azul Zulu

  • Azul Zing

  • IBM J9

Compile and Run Java Code Using JDK

The JDK provides the compiler to convert source code into bytecode.

  • Create a Java file (e.g., Hello.java)

  • Write the program inside a class

  • Use the javac command to compile the file

  • Bytecode (.class file) is created after successful compilation

  • Run the program using the java command without typing .class

 

Example Program:

class Hello {

    public static void main(String[] args) {

        System.out.println("Hello Geek!");

    }

}

 

Compilation:

"C:\Program Files\Java\jdk-11.0.9\bin\javac.exe" Hello.java

Execution:

java Hello

JAR (Java Archive) in JDK

JDK includes the jar tool to package classes into a single archive file.

  • A JAR file groups multiple .class files together

  • Used for distributing Java applications

  • Can compress files and structure them logically

  • Can be added to classpath using -cp

Example to create JAR:

•       jar --create --file Hello.jar Hello.class

Example to run JAR:

•       java -cp Hello.jar Hello

 

 

JRE (Java Runtime Environment)

The Java Runtime Environment (JRE) is the software needed to run Java applications. It provides the Java Virtual Machine (JVM), core class libraries, and supporting files that provide an environment to execute the java program, acting as a software layer between the program and the operating system.

This platform-independent nature is a key feature, as the JRE translates Java bytecode so it can run on any operating system without modification. 

The Java Runtime Environment is a part of the Java platform that provides everything needed to run Java applications.

It does not include development tools like the compiler but contains the necessary libraries, class files, and the Java Virtual Machine (JVM) required for executing Java programs.

When you run a Java application, the JRE loads the required classes, verifies security rules, manages memory, and works with the JVM to convert bytecode into machine code.

It provides the runtime environment where Java applications can execute safely and consistently across different systems.

  • Stands for Java Runtime Environment.

  • Required only for running Java programs, not for developing them.

  • Contains JVM + core class libraries + supporting files.

  • Does not include tools like javac (compiler) and jar.

  • Used by end users who only want to run Java applications.

  • Ensures Java programs run identically on all operating systems.

  • Provides bytecode loading, class execution, and runtime services.

  • Part of both JDK and standalone installations.

  • Works closely with the JVM to execute compiled Java bytecode.

  • Provides an environment to execute the java program.

 

How it works

  • Functions as a bridge: The JRE acts as a bridge between a Java application and the user's operating system, providing all necessary resources like memory and system access.

  • Core components: It consists of the Java Virtual Machine (JVM), the Java standard class libraries, and other supporting files.

  • Platform independence: Because the JRE handles the translation of Java bytecode into the machine code of a specific operating system, a Java program compiled using the JRE can run on any system that has a compatible JRE installed.

  • The three main components of Java: The JRE is one of three components for Java development and execution. The others are the Java Development Kit (JDK) (for writing and compiling code) and the Java Virtual Machine (JVM) (which runs the applications). 

 

Components of JRE

The JRE includes several important parts that work together to run Java programs.

  • Java Virtual Machine (JVM)

  • Core Java class libraries

  • Supporting files and configuration files

  • Java class loader subsystem

  • Security managers and access controllers

  • Native libraries required for OS-level interaction

  • Runtime libraries like java.lang, java.io, java.util, java.net, etc.

 

Role of JRE in Java Program Execution

When a Java application runs, the JRE performs several steps to ensure correct and secure execution.

  • Loads required class files into memory

  • Manages classpath and library paths

  • Performs bytecode verification for security

  • Provides runtime class loading through class loaders

  • Coordinates with JVM to convert bytecode into machine code

  • Manages memory allocation using runtime data areas

  • Handles exceptions and system-level errors

  • Provides an environment for garbage collection

  • Ensures platform independence by standardizing runtime behavior

 

What JRE Includes

The JRE contains everything needed after the program is compiled.

  • JVM executable

  • Java class loader

  • Bytecode verifier

  • Standard class libraries

  • Native method libraries

  • Property files and security policies

  • Runtime images and resource files

 

JRE vs JDK

Students often confuse JRE with JDK, but their purpose is different.

  • JDK is used for development; JRE is used for execution

  • JDK contains JRE + development tools

  • JRE cannot compile programs; it can only run them

  • If you only want to run Java applications, JRE is enough

  • Developers always install the JDK because it includes the JRE

 

Types / Packages of JRE

Different editions of Java contain their own runtime environments.

  • Java SE Runtime Environment (Standard Edition)

  • Java EE Runtime Environment (Enterprise Edition)

  • Java ME Runtime Environment (Mobile Edition)

Each edition provides libraries specific to that platform.

 

How JRE Works Internally

This describes the internal working of JRE during program execution.

  • Program bytecode is given to the JRE

  • Class loader loads required classes into memory

  • Bytecode verifier checks bytecode integrity

  • Execution engine (inside JVM) begins processing instructions

  • Runtime libraries provide built-in functions

  • Memory manager allocates and releases memory

  • Garbage collector removes unused objects

  • Execution continues until program ends

 

Importance of JRE

The JRE makes Java’s platform-independent and secure behavior possible.

  • Enables execution: Without the JRE, Java applications cannot run. It is the essential software that provides the runtime environment required to execute Java code.

  • Simplifies development: It solved the problem of developers having to write separate code for each operating system, allowing for "write once, run anywhere" portability.

  • Provides necessary tools: It includes a vast standard library with classes for common tasks like input/output, data structures, and database interaction, which are used by virtually all Java programs. 

  • Ensures consistent program execution on any device

  • Manages all runtime needs of Java applications

  • Provides a secure environment using access controllers

  • Allows Java programs to run without recompilation

  • Acts as the link between Java bytecode and the operating system

 

When Do You Install JRE?

JRE is useful when the system only needs to run Java applications.

  • Used by end users running Java applications

  • Required for running .jar applications

  • Needed for running Java-based desktop apps, tools, and IDEs

  • Not required for writing or compiling Java code

 

Example: Running a Java Program Using JRE

If you run a Java application using the java command, it is actually the JRE doing the work.

  • User runs: java Hello

  • JRE sees Hello.class

  • JRE loads class through class loader

  • Bytecode is verified

  • JVM starts executing instructions

  • Output is displayed

The JRE handles the entire runtime process.

JVM

The Java Virtual Machine (JVM) is a core component of the Java Runtime Environment (JRE) that allows Java programs to run on any platform without modification.

JVM acts as an interpreter between Java bytecode and the underlying hardware.

When you run a Java program, the JVM loads the compiled bytecode, checks it for safety, prepares memory, and then executes it using an internal execution engine.

The JVM ensures that Java programs can run on any device by translating the platform-independent bytecode into platform-specific machine code.

It also manages memory automatically, handles errors, and supports multithreading, which allows multiple pieces of code to run at the same time.

  • Java source (.java) -> compiled by javac -> bytecode (.class)

  • JVM loads the bytecode, verifies it, links it, and then executes it

  • Execution may involve interpreting bytecode or using Just-In-Time (JIT) compilation to convert “hot” code into native machine code for performance

  • Garbage collection runs in the background to reclaim memory from unused objects

  • Reads and loads the .class (bytecode) file

  • Verifies bytecode for illegal instructions

  • Converts bytecode to machine code using interpreter and JIT compiler

  • Allocates memory for objects and variables

  • Manages stack frames for method calls

  • Performs garbage collection to free unused memory

  • Handles runtime exceptions

  • Interacts with the operating system for input/output

  • Ensures platform independence

JVM → Executes bytecode

JRE → JVM + libraries required to run Java programs

JDK → JRE + development tools (compiler, debugger, jar, etc.)

Architecture of JVM

The JVM architecture describes all the internal components that help the JVM load, verify, translate, and execute Java bytecode. It includes the class loader, runtime memory areas, execution engine, garbage collector, and interfaces for native code. Each part plays a fixed role in making Java programs run smoothly and securely.

 

Components of JVM Architecture

1. Class Loader Subsystem

The class loader brings class files (.class) into JVM memory during runtime. It loads only when needed and avoids loading the same class twice.

  • Loads classes from disk, network, JAR files

  • Performs three steps: Loading, Linking, Initialization

  • Linking includes verification, preparation, and resolution

  • Supports dynamic loading of classes

  • Ensures bytecode is safe and correctly structured

 

2. Runtime Data Areas (JVM Memory Model)

These are the different memory regions used while executing a program. Some areas are shared by all threads while others are private to each thread.

Method Area (Shared)

  • Stores class metadata, static variables, method bytecode

  • Contains runtime constant pool

  • Shared by all threads

Heap (Shared)

  • Stores objects and arrays

  • Biggest memory area

  • Garbage collector works here

Java Stack (Thread-private)

  • Contains stack frames for each method call

  • Stores local variables, operand stack, return values

  • Each thread has its own stack

PC Register (Thread-private)

  • Holds memory address of current instruction executing

  • Each thread has its own PC register

Native Method Stack (Thread-private)

  • Used when Java calls methods written in C/C++ via JNI

  • Stores native method information

 

3. Execution Engine

The execution engine is the heart of the JVM. It executes bytecode and converts it to machine code.

Interpreter

  • Reads bytecode instructions one by one

  • Slower but simple and memory efficient

JIT Compiler (Just-In-Time Compiler)

  • Converts frequently executed bytecode sections into machine code

  • Makes the program run faster

  • Works with HotSpot JVM to optimize performance

Profiler & Optimizer

  • Monitors program execution

  • Identifies “hot spots” and optimizes them

Garbage Collector

  • Automatically finds and removes unused objects

  • Prevents memory leaks

  • Runs in the background

 

4. Native Method Interface (JNI)

This part allows Java to interact with native languages like C or C++ when needed.

  • Connects Java code with OS-specific native code

  • Supports hardware interaction

  • Used for tasks not possible in pure Java

 

5. Native Method Libraries

These are platform-specific libraries that support native operations.

  • Stored as .dll in Windows, .so in Linux, .dylib in macOS

  • JNI loads them when Java calls native methods

 

Flow of JVM Execution (Step-by-Step)

This is the exact sequence JVM follows when running a program.

  • Load .class file

  • Class loader loads required classes

  • Bytecode verifier checks for security rules

  • Class is prepared and resolved

  • Memory is allocated in heap and stack

  • Execution engine starts running bytecode

  • Interpreter + JIT handle instruction execution

  • Garbage collector cleans unused objects

  • Program continues until main() ends

Data Types in Java

Data types define the type of data a variable can store and how much memory it will occupy.

Java is a strongly typed language, which means every variable must be declared with a data type before use.This allows the compiler to check errors, ensure safe operations, and optimize memory.

Java data types are mainly divided into primitive and non-primitive types

  1. Primitive Data Types: Store simple values directly in memory.

  2. Non-Primitive (Reference) Data Types: Store memory references to objects.


Primitive Data Types

Primitive data types store simple values and are built directly into the Java language and are fixed in size. They are stored in stack memory and are faster to access.

1. byte

  • Size: 1 byte

  • Range: -128 to 127

  • Used for saving memory in large arrays

2. short

  • Size: 2 bytes

  • Range: -32,768 to 32,767

  • Used in place of int when memory is limited

3. int

  • Size: 4 bytes

  • Range: -2,147,483,648 to 2,147,483,647

  • Most commonly used integer type

4. long

  • Size: 8 bytes

  • Used for large integers

  • Ends with ‘L’ (example: 10000L)

5. float

  • Size: 4 bytes

  • Stores decimal values with single precision

  • Ends with ‘f’ or ‘F’ (example: 3.14f)

6. double

  • Size: 8 bytes

  • Stores decimal values with double precision

  • Default type for decimal numbers

7. char

  • Size: 2 bytes

  • Stores a single Unicode character

  • Written in single quotes (example: 'A')

8. boolean

  • Size not fixed (JVM dependent)

  • Stores true or false

  • Used for conditions and logic

 

Non-Primitive Data Types

Non-primitive types store objects and are created by programmers. They occupy heap memory and can store multiple values.

1. String

  • Stores multiple characters

  • Immutable in Java

  • Example: "Hello"

2. Arrays

  • Stores multiple values of same type

  • Example: int[] a = {1,2,3};

3. Class

  • Used to create objects

  • Defines properties and behaviors

4. Interface

  • Contains abstract methods

  • Used for abstraction and multiple inheritance

5. Wrapper Classes

  • Convert primitive types into objects

  • Examples: Integer, Double, Boolean

 

Difference Between Primitive and Non-Primitive Data Types

Primitive Data Types

Non-Primitive Data Types

Basic built-in data types provided by Java

Created by programmers or provided as classes

Store simple values

Store complex values or objects

Stored in stack memory

Stored in heap memory

Have fixed size

Size varies depending on object

Faster to access

Slower because they store references

Hold actual value

Hold the reference (address) of the data

Cannot be null except using wrapper classes

Can be null

Do not have methods

Have built-in methods and behaviors

Eight types: byte, short, int, long, float, double, char, boolean

Examples: String, arrays, classes, interfaces, wrapper classes

Used for basic computations

Used to build complex structure

Variables in Java

Variables in Java is the name of memory locations used to hold data during program execution.

Each variable must be declared with a data type, which determines the kind of value it can store.

Java is a strongly typed language, so variables must be declared before use and follow strict rules for naming, accessing, and assigning values.

Variables help programs store information temporarily while methods and operations are being executed.

 

A variable in Java has three components,

  1. Data Type: Defines the kind of data stored (e.g., int, String, float).

  2. Variable Name: A unique identifier following Java naming rules.

  3. Value: The actual data assigned to the variable.

Syntax:

data_type variable_name;

Example

int age = 50;

class Geeks {

    public static void main(String[] args) {

       

        // Declaring and initializing variables

       

        // Integer variable 

        int age = 25;      

       

        // String variable 

        String name = "GeeksforGeeks";

       

        // Double variable

        double salary = 50000.50;    

        // Displaying the values of variables

        System.out.println("Age: " + age);         

        System.out.println("Name: " + name);       

        System.out.println("Salary: " + salary);

    }

}

Output

Age: 25

Name: GeeksforGeeks

Salary: 50000.5

 

 

Types of Variables in Java

Local Variable
A local variable is a variable declared inside the body of a method, constructor,  block, or as a method parameter, and it can be used only within that method, constructor, or block.

Important Concepts

  • Created when the method or block starts execution

  • Stored in stack memory

  • Destroyed when the method or block ends

  • Cannot be accessed outside its scope

  • Must be initialized before use

Syntax

dataType variableName;

or

dataType variableName = value;

Example

class Test {

    void show() {

        int x = 10;

        System.out.println(x);

    }

}

Instance Variable
An instance variable is a variable declared inside a class but outside all methods, constructors, and blocks, and each object of the class has its own separate copy of that variable.

  • Belongs to an object, not to the class

  • Each object gets its own copy

  • Created when an object is created

  • Stored in heap memory

  • Gets a default value if not initialized

 

Syntax

class ClassName {

    dataType variableName;

}

 

Example

class Student {

    int age;   // instance variable

    String name;  // instance variable

 

    void display() {

        System.out.println(age + " " + name);

    }

}

Static Variable
A static variable is a variable declared inside a class using the static keyword, and it is shared by all objects of that class. Only one copy of a static variable exists in memory, and all objects access and modify the same variable.

Important Concepts

  • Declared using the static keyword

  • Belongs to the class, not to any single object

  • Only one copy is created for the whole class

  • Memory is allocated once, when the class is loaded

  • All objects share the same value

  • Stored in the method area

  • Gets a default value if not initialized

  • Can be accessed using the class name

Syntax

class ClassName {

    static dataType variableName;

}

 

Example

class Student {

    static String college = "ABC";

    int age;

}

 

class Test {

    public static void main(String[] args) {

        Student s1 = new Student();

        Student s2 = new Student();

 

        s1.age = 20;

        s2.age = 22;

 

        Student.college = "XYZ";

 

        System.out.println(s1.age);       // 20

        System.out.println(s2.age);       // 22

        System.out.println(Student.college); // XYZ

    }

}

 

Explanation of Example

  • college is a static variable

  • Only one copy of college exists

  • Both s1 and s2 share the same college value

  • Changing college affects all objects

 

 

Rules for Defining Variables in Java
Rules for defining variables specify how variable names must be written and declared so that the Java compiler can correctly identify and use them.

  • A variable name must start with a letter (a–z or A–Z), underscore (_), or dollar sign ($)

  • A variable name cannot start with a digit

  • Variable names can contain letters, digits, underscore, and dollar sign

  • No spaces are allowed in variable names

  • Java keywords cannot be used as variable names

  • Variable names are case-sensitive

  • Variable names must be unique within the same scope

  • A variable must be declared before it is used

  • A data type must be specified while declaring a variable

 

Examples
Valid variable names:

  • int count;

  • float totalMarks;

  • String studentName;

Invalid variable names:

  • int 2num;

  • int total marks;

  • int class;

 

Types of variable

Local Variable
A local variable is a variable declared inside a method, constructor, block, or as a method parameter, and it can be used only within that method, constructor, or block.

Important Concepts

  • Method parameters are also local variables

  • Created when the method is called

  • Destroyed when the method finishes execution

  • Accessible only within the method or block

  • Must be initialized before use

Syntax

returnType methodName(dataType parameter) {

    dataType localVariable;

}

Example

class Test {

    void add(int a) {   // 'a' is a local variable (parameter)

        int b = 10;     // 'b' is a local variable

        System.out.println(a + b);

    }

}

Instance Variable
An instance variable is a variable declared inside a class but outside all methods, constructors, and blocks. It is associated with an object of the class, meaning every object created from the class has its own separate copy of that variable, which stores object-specific data.

Important Concepts

  • Declared inside a class but outside methods

  • Memory is allocated when an object is created

  • Each object has its own separate copy

  • Changes made by one object do not affect other objects

  • Used to store object-specific data

  • Stored in heap memory

  • Gets default values if not explicitly initialized

Syntax

class ClassName {

    dataType variableName;

}

Example

class Student {

    int age;        // instance variable

    String name;    // instance variable

}

 

class Test {

    public static void main(String[] args) {

        Student s1 = new Student();

        Student s2 = new Student();

 

        s1.age = 20;

        s2.age = 22;

 

        System.out.println(s1.age);  // 20

        System.out.println(s2.age);  // 22

    }

}

Explanation of Example

  • age is an instance variable

  • s1 and s2 are two different objects

  • Both objects have their own age variable

  • Changing s1.age does not change s2.age

 

Static Variable
A static variable is a variable declared inside a class using the static keyword, and it is shared by all objects of that class. Only one copy of a static variable exists in memory, and all objects access and modify the same variable.

Important Concepts

  • Declared using the static keyword

  • Belongs to the class, not to any single object

  • Only one copy is created for the whole class

  • Memory is allocated once, when the class is loaded

  • All objects share the same value

  • Stored in the method area

  • Gets a default value if not initialized

  • Can be accessed using the class name

 

Syntax

class ClassName {

    static dataType variableName;

}

 

Example

class Student {

    static String college = "ABC";

    int age;

}

 

class Test {

    public static void main(String[] args) {

        Student s1 = new Student();

        Student s2 = new Student();

 

        s1.age = 20;

        s2.age = 22;

 

        Student.college = "XYZ";

 

        System.out.println(s1.age);       // 20

        System.out.println(s2.age);       // 22

        System.out.println(Student.college); // XYZ

    }

}

Explanation of Example

  • college is a static variable

  • Only one copy of college exists

  • Both s1 and s2 share the same college value

  • Changing college affects all objects

 

Operators in Java
Operators in Java are special symbols used to perform operations on variables and values. They are used for calculations, comparisons, logical decisions, assignments, and bit-level operations in a program.

Types of Operators in Java

 

1. Arithmetic Operators

  • Used to perform basic mathematical calculations.

  • + Addition

  • - Subtraction

  • * Multiplication

  • / Division

  • % Modulus

  • Example

int a = 10, b = 3;

System.out.println(a + b);   // 13

System.out.println(a % b);   // 1

 

2. Relational (Comparison) Operators

  • Used to compare two values and return a boolean result.

  • == Equal to

  • != Not equal to

  • > Greater than

  • < Less than

  • >= Greater than or equal to

  • <= Less than or equal to

Example

int x = 5, y = 10;

System.out.println(x < y);   // true

 

3. Logical Operators

  • Used to combine multiple conditions.

  • && Logical AND

  • || Logical OR

  • ! Logical NOT

Example

int a = 5, b = 10;

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

 

4. Assignment Operators

  • Used to assign values to variables.

  • = Assign

  • += Add and assign

  • -= Subtract and assign

  • *= Multiply and assign

  • /= Divide and assign

Example

int a = 10;

a += 5;   // a = 15

 

5. Unary Operators

  • Operate on a single operand.

  • + Unary plus

  • - Unary minus

  • ++ Increment

  • -- Decrement

  • ! Logical NOT

Example

int a = 5;

a++;

System.out.println(a);   // 6

 

6. Bitwise Operators

  • Used to perform operations at the bit level.

  • & Bitwise AND

  • | Bitwise OR

  • ^ Bitwise XOR

  • ~ Bitwise NOT

Example

int a = 5, b = 3;

System.out.println(a & b);   // 1

 

7. Shift Operators

Used to shift bits left or right.

  • << Left shift

  • >> Right shift

  • >>> Unsigned right shift

Example

int a = 8;

System.out.println(a << 1);   // 16

 

8. Ternary (Conditional) Operator

Used as a shorthand for if-else conditions.

condition ? value1 : value2

Example

int a = 10, b = 20;

int max = (a > b) ? a : b;

 

9. instanceof Operator

Used to test whether an object belongs to a specific class.

Example

String s = "Java";

System.out.println(s instanceof String);   // true

Control Structures in Java

Control structures in Java are programming constructs that control the flow of execution of a program. They decide the order in which statements are executed based on conditions, repetitions, or jumps. Control structures allow a program to make decisions, repeat tasks, and control execution logically instead of running statements sequentially.

 

Types of Control Structures in Java

Java control structures are mainly divided into three types:

  • Selection (Decision-Making) Control Structures

  • Looping (Iteration) Control Structures

  • Jump (Branching) Control Structures

 

1. Selection Control Structures

Selection control structures are used to execute different blocks of code based on a condition. They allow the program to choose one path of execution among multiple alternatives.

Types of Selection Control Structures

  • if statement

  • if-else statement

  • else-if ladder

  • Nested if statement

  • switch statement

if Statement

The if statement is a decision-making control structure that executes a block of code only when a specified condition evaluates to true.

  • Used for decision making in a program

  • The condition must return true or false

  • Statements inside the if block execute only when the condition is true

  • If the condition is false, the block is skipped

  • Curly braces { } define the scope of the if statement

  • Suitable when only one condition needs to be checked

Syntax

if (condition) {

    // statements

}

Example

class Test {

    public static void main(String[] args) {

        int age = 20;

 

        if (age >= 18) {

            System.out.println("Eligible to vote");

        }

    }

}

Output: Eligible to vote

 

if-else Statement

The if-else statement is a decision-making control structure that executes one block of code when a condition is true and another block of code when the condition is false.

  • Used when two alternative actions are required

  • The condition must evaluate to true or false

  • The if block executes when the condition is true

  • The else block executes when the condition is false

  • Only one block executes at a time

  • Helps in making clear decisions in programs

Syntax

if (condition) {

    // statements when condition is true

} else {

    // statements when condition is false

}

Example

class Test {

    public static void main(String[] args) {

        int number = 10;

 

        if (number % 2 == 0) {

            System.out.println("Even number");

        } else {

            System.out.println("Odd number");

        }

    }

}

Output

Even number

else-if Ladder

The else-if ladder is a decision-making control structure used to test multiple conditions one by one and execute the block of code for the first true condition.

  • Used to check multiple conditions

  • Conditions are checked from top to bottom

  • Only the first true condition is executed

  • Remaining conditions are skipped after a match

  • The final else runs when all conditions are false

  • Suitable for multi-way decision making

Syntax

if (condition1) {

    // statements

} else if (condition2) {

    // statements

} else if (condition3) {

    // statements

} else {

    // statements

}

Example

class Test {

    public static void main(String[] args) {

        int marks = 75;

 

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

        }

    }

}

Output

Grade B

Nested if Statement

The nested if statement is a decision-making control structure in which one if statement is placed inside another if or else block. It is used when a decision depends on multiple conditions that must be checked in a specific order.

  • Used when one condition depends on another condition

  • An if statement can be written inside another if or else

  • Inner condition is checked only if the outer condition is true

  • Allows complex decision making

  • Useful when multiple related conditions must be tested

Syntax

if (condition1) {

    if (condition2) {

        // statements

    }

}

Example

class Test {

    public static void main(String[] args) {

        int age = 20;

        int weight = 55;

 

        if (age >= 18) {

            if (weight >= 50) {

                System.out.println("Eligible for blood donation");

            }

        }

    }

}

Output

Eligible for blood donation

 

switch statement

A switch statement in Java is a decision-making statement that allows a program to choose one block of code to run from many options based on the value of a single variable or expression. It is mainly used when you want to compare one value with multiple fixed values, instead of writing many if-else statements, which makes the code cleaner and easier to read.

  • It works by matching the value of an expression with different case labels.

  • Each case represents a possible value of the variable.

  • When a match is found, the statements under that case are executed.

  • The break statement is used to stop execution after a matched case; without it, execution continues to the next case (called fall-through).

  • The default case runs when none of the cases match the value.

  • It supports data types like int, char, byte, short, String, and enum.

  • It is best used when there are many fixed choices for one variable.

Syntax

switch (expression) {

    case value1:

        // code

        break;

    case value2:

        // code

        break;

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

}

Output

Wednesday

2. Looping Control Structures

Looping control structures are used to execute a block of code repeatedly as long as a specified condition is true. They reduce code repetition and are used when the same task needs to be performed multiple times.

Types of Looping Control Structures

  • for loop

  • while loop

  • do-while loop

  • Nested loops

 

for loop

A for loop in Java is a looping statement used to execute a block of code again and again for a fixed number of times. It is mainly used when you already know how many times the loop should run, which makes the code short, clear, and easy to understand.

  • It has three parts: initialization, condition, and update.

  • Initialization runs only once and is used to set the loop variable.

  • The condition is checked before every iteration; if it is true, the loop continues.

  • The update part changes the loop variable after each iteration.

  • If the condition becomes false, the loop stops automatically.

  • It is commonly used for counting, array traversal, and repeating tasks.

Syntax

for (initialization; condition; update) {

    // code to be executed

}

 

public class ForLoopExample {

    public static void main(String[] args) {

 

        // for loop to print numbers from 1 to 5

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

            System.out.println(i);

        }

 

    }

}

Output

1

2

3

4

5

 

This program starts execution from the main method. The loop variable i is initialized to 1, the loop continues as long as i is less than or equal to 5, and after every iteration i is increased by 1. When the condition becomes false, the loop stops automatically.

 

while loop

A while loop in Java is a looping statement used to repeat a block of code as long as a given condition remains true. It is mainly used when you do not know in advance how many times the loop will run, because the condition is checked before each iteration.

  • The condition is checked first before executing the loop body.

  • If the condition is true, the loop body executes.

  • If the condition is false at the start, the loop body will not run even once.

  • It is useful for input-based loops and situations where the number of iterations is uncertain.

Syntax

while (condition) {

    // code to be executed

}

 

Example

public class WhileLoopExample {

    public static void main(String[] args) {

 

        int i = 1;

 

        while (i <= 5) {

            System.out.println(i);

            i++;

        }

 

    }

}

Output

1

2

3

4

5

This program starts from the main method. The variable i is initialized to 1. The while loop keeps running as long as i is less than or equal to 5, and after each iteration the value of i is increased by 1. When the condition becomes false, the loop stops.

 

do-while loop

A do-while loop in Java is a looping statement that executes a block of code at least one time, no matter whether the condition is true or false. This happens because the condition is checked after the loop body runs.

  • The loop body runs first.

  • The condition is checked at the end of the loop.

  • If the condition is true, the loop repeats.

  • If the condition is false, the loop stops.

  • It is useful when the code must run at least once, like menu programs or input validation.

Syntax

do {

    // code to be executed

} while (condition);

Full Java example

public class DoWhileLoopExample {

    public static void main(String[] args) {

 

        int i = 1;

 

        do {

            System.out.println(i);

            i++;

        } while (i <= 5);

 

    }

}

Output

1

2

3

4

5

This program prints numbers from 1 to 5. The loop executes first and then checks the condition, which ensures that the loop runs at least once.

 

A nested loop in Java means placing one loop inside another loop. The outer loop runs first, and for each single run of the outer loop, the inner loop runs completely. Nested loops are commonly used when working with tables, patterns, and multi-dimensional data.

  • One loop is written inside the body of another loop.

  • The outer loop controls how many times the inner loop repeats.

  • For each iteration of the outer loop, the inner loop executes fully.

  • They are often used to print patterns and to work with 2D arrays.

 

Syntax

for (initialization; condition; update) {

 

    for (initialization; condition; update) {

        // inner loop statements

    }

 

    // outer loop statements

}

The outer loop runs first, and for each iteration of the outer loop, the inner loop executes completely.

 

Example

public class NestedLoopExample {

    public static void main(String[] args) {

 

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

 

            for (int j = 1; j <= 3; j++) {

                System.out.println("i = " + i + ", j = " + j);

            }

 

        }

 

    }

}

Output

i = 1, j = 1

i = 1, j = 2

i = 1, j = 3

i = 2, j = 1

i = 2, j = 2

i = 2, j = 3

i = 3, j = 1

i = 3, j = 2

i = 3, j = 3

This program shows how the inner loop runs completely for every single iteration of the outer loop.

 

3. Jump (Branching) Control Structures

Jump control structures are used to transfer control from one part of the program to another. They interrupt the normal flow of execution.

Types of Jump Control Structures

  • break

  • continue

  • return

1. break Statement

The break statement is used to immediately terminate a loop or a switch statement and transfer control to the statement that follows it.

  • Used inside loops and switch statements

  • Stops further execution of the loop or switch

  • Control moves to the next statement after the loop or switch

Syntax

break;

Example

class Test {

    public static void main(String[] args) {

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

            if (i == 3) {

                break;

            }

            System.out.println(i);

        }

    }

}

Output

1

2

 

2. continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next iteration.

  • Used only inside loops

  • Skips remaining statements of the current iteration

  • Loop continues with the next iteration

Syntax

continue;

Example

class Test {

    public static void main(String[] args) {

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

            if (i == 3) {

                continue;

            }

            System.out.println(i);

        }

    }

}

Output

1

2

4

5

 

3. return Statement

The return statement is used to exit from a method and optionally return a value to the calling method.

  • Used inside methods

  • Terminates method execution

  • Can return a value or nothing (void)

Syntax

return;

or

return value;

Example

class Test {

    static int add(int a, int b) {

        return a + b;

    }

 

    public static void main(String[] args) {

        int sum = add(5, 3);

        System.out.println(sum);

    }

}

Output

8

Important points

  • Selection structures make decisions

  • Looping structures repeat execution

  • Jump statements control flow interruption

  • Control structures are essential for logical programming

  • Without control structures, programs run sequentially only

 

Java Methods

Java Methods are blocks of code that perform a specific task and run only when they are called. They help in organizing the program, reducing repeated code, and making the program easier to understand and maintain. A method can take input values, process them, and may return a result to the caller.

  • A method is defined inside a class.

  • It has a name, return type, and optional parameters.

  • The method body contains the code to be executed.

  • Methods are called using their name.

  • They improve code reusability and readability.

  • Methods can return a value or return nothing using void.

General Syntax

modifier returnType methodName(parameters) {

    // method body

}

A Java method is written, prepared, and used in three simple steps: declaring, defining, and calling.

This makes the program clean and easy to understand because the same logic can be reused many times.

  • Declaring a method
    Declaring a method means writing its name, return type, and parameters. It tells Java what the method looks like.

  • Defining a method
    Defining a method means writing the actual code inside the method body that performs the task.

  • Calling a method
    Calling a method means using the method name to execute it from another part of the program, usually from the main method.

 


Modifier-  A modifier specifies the access level and behavior of a method. It controls from where the method can be accessed and whether an object is required to call it.

  • public – the method can be accessed from anywhere in the program.

  • private – the method can be accessed only within the same class.

  • protected – the method can be accessed within the same package or by subclasses.

  • static – the method belongs to the class and can be called without creating an object.

  • final – the method cannot be overridden.

  • abstract – the method has no body and must be implemented in a subclass.

 

Full Java example

public class MethodDemo {

 

    // Method declaration and definition

    static int add(int a, int b) {

        // This line adds two numbers

        int sum = a + b;

 

        // Returning the result to the caller

        return sum;

    }

 

    public static void main(String[] args) {

 

        // Method calling

        int result = add(10, 20);

 

        // Printing the returned value

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

    }

}

Output

Sum = 30

In this program, the method add is declared and defined above the main method, and it is called inside main to perform addition and return the result.

Why Use Methods?

  • Code Reusability: Write once, use multiple times without repeating code so that code reusability increase.

  • Modularity: Dividing a program into separate methods allows each method to handle a specific task, making the code more organized and easier to manage.

  • Readability: Smaller, named methods make the code easier to read and understand.

  • Maintainability: It’s easier to fix bugs or update code when it's organized into methods.

Types of Methods in Java

Predefined methods in Java are methods that are already written and provided by the Java standard library to perform common operations, so programmers can use them directly without writing their code.

Example of predefined method

public class PredefinedMethodExample {

    public static void main(String[] args) {

 

        System.out.println("Java");      // predefined method

        int len = "Hello".length();      // predefined method

        double sq = Math.sqrt(9);        // predefined method

 

    }

}

 

User-defined methods in Java are methods that are created by the programmer to perform a specific task according to the requirement of the program.

Example of user-defined method

public class UserDefinedMethodExample {

 

    static int multiply(int a, int b) {   // user-defined method

        return a * b;

    }

 

    public static void main(String[] args) {

 

        int result = multiply(4, 5);      // calling user-defined method

        System.out.println(result);

    }

}

Predefined methods save time by providing ready-made functionality, while user-defined methods help in organizing and reusing program logic.

 

 

NotesNav

NotesNav

Madhepura college of engineering

Frequently Asked Questions