UNIT III : JAVA
Java Programming: A Complete
Beginner's Guide
Welcome to the comprehensive world of Java programming! This guide will take you from absolute
beginner to confident Java developer. Java is one of the world's most popular programming languages,
powering everything from mobile applications to enterprise systems. Whether you're a student starting
your coding journey or a self-taught programmer looking to master Java fundamentals, this guide
provides everything you need to build a solid foundation in Java programming.
1
Gagan Public School, Khair Bypass Road, Aligarh
What is Java? Understanding the
Fundamentals
Java is a high-level, object-oriented programming language
developed by Sun Microsystems in 1995 (now owned by
Oracle). What makes Java special is its "write once, run
anywhere" philosophy, meaning code written on one
operating system can run on any other system that has
Java installed.
Java's popularity stems from its simplicity, reliability, and
platform independence. It's used by millions of developers
worldwide to create everything from Android apps to web
applications, desktop software, and large-scale enterprise
systems. Major companies like Google, Amazon, Netflix, and
LinkedIn rely heavily on Java for their core systems.
Platform Independent
The language emphasises readability and maintainability,
making it an excellent choice for beginners whilst remaining Runs on any device with JVM
powerful enough for complex professional applications.
Java's automatic memory management and robust error-
handling capabilities help prevent common programming Object-Oriented
mistakes that plague other languages.
Organised, reusable code
structure
2
Gagan Public School, Khair Bypass Road, Aligarh
JDK, JVM, and JRE: The Java
Ecosystem
Understanding the Java ecosystem is crucial for every developer. The three core components work
together to make Java programs possible, each serving a specific purpose in the development and
execution process.
JDK ( Java JVM ( Java Virtual JRE ( Java Runtime
Development Kit) Machine) Environment)
The complete development The runtime environment that Contains the JVM plus
environment containing executes Java bytecode. Acts standard libraries needed to
everything needed to as a bridge between your run Java applications. If you
develop Java applications. Java program and the only need to run Java
Includes the compiler (javac), operating system. Each programs (not develop them),
debugger, and development platform has its own JVM, JRE is sufficient. It's what
tools. Think of it as your enabling platform end-users typically install.
complete toolkit for writing independence.
Java programs.
When you write a Java program, the JDK compiler converts your source code into bytecode. The JVM
then interprets this bytecode and executes it on your specific operating system. This process is what
makes Java programs portable across different platforms without modification.
3
Gagan Public School, Khair Bypass Road, Aligarh
Object-Oriented Programming: The
Heart of Java
Object-Oriented Programming (OOP) is Java's fundamental paradigm, organising code into objects
that represent real-world entities. This approach makes programs more modular, reusable, and easier
to maintain. Understanding OOP concepts is essential for mastering Java programming.
Object
An instance of a class with
Class specific values for its
A blueprint or template that properties. Objects are the
defines the properties and actual entities that exist in
behaviours of objects. memory during program
Classes don't consume execution.
memory until objects are
created from them. Encapsulation
The practice of hiding
internal implementation
details whilst providing
controlled access through
public methods. Ensures
Abstract
data security and integrity.
Templates that define what
methods a class must Polymorphism
implement without specifying
The ability of objects to take
how, ensuring consistent
multiple forms, allowing the
interfaces across related
same method to behave
classes.
differently based on the
object calling it.
4
Gagan Public School, Khair Bypass Road, Aligarh
Classes and Objects in Detail
Understanding Classes Creating and Using Objects
A class serves as a blueprint for creating Objects are instances of classes that exist in
objects. It defines what data an object can hold your computer's memory during program
(attributes) and what actions it can perform execution. When you create an object, you're
(methods). Think of a class like an architectural allocating memory space and initialising it with
blueprint - it shows the structure and features, specific values for the class attributes.
but you need to build actual houses (objects)
Multiple objects can be created from the same
from it.
class, each maintaining independent state. This
Classes promote code reusability because you allows you to model real-world scenarios where
can create multiple objects from a single class similar entities exist with different
definition. Each object maintains its own copy of characteristics, such as multiple cars with
the class attributes, allowing for individual different colours and models.
customisation whilst sharing the same structure
and behaviour patterns. Car myCar = new Car();
Car friendsCar = new Car();
public class Car { myCar.startEngine();
private String colour;
private String model;
public void startEngine() {
System.out.println("Engine started!");
}
}
5
Gagan Public School, Khair Bypass Road, Aligarh
Encapsulation and Data Protection
Encapsulation is one of the fundamental principles of object-oriented programming, providing a
protective barrier around your data whilst controlling how it can be accessed and modified. This
concept ensures that the internal workings of a class remain hidden from external interference.
Data Validation
Public Methods Implement checks within
Private Variables Provide controlled access setter methods to validate
Mark class attributes as through public getter and input data before
private to prevent direct setter methods. These assignment. This prevents
access from outside the methods can include invalid data from corrupting
class. This protects your validation logic to ensure your object's state and
data from unauthorised only appropriate values are ensures consistent
modification and maintains assigned to your private behaviour across your
data integrity throughout variables. application.
your program's execution.
Remember: Good encapsulation means your class internals can change without breaking code that
uses your class, as long as the public interface remains consistent.
6
Gagan Public School, Khair Bypass Road, Aligarh
Polymorphism: One Interface,
Multiple Forms
Polymorphism allows objects of different classes to be treated as objects of a common base class
whilst maintaining their specific behaviours. This powerful concept enables flexible and extensible
code design, making your programs more adaptable to future changes and requirements.
Method Overriding Method Interface
Subclasses can provide
Overloading Implementation
specific implementations of Multiple methods with the Classes can implement
methods defined in their same name but different interfaces to guarantee
parent class. The correct parameters within the same they provide specific
method is chosen at class. The compiler methods. This ensures
runtime based on the actual determines which method consistent behaviour across
object type, not the to call based on the different implementations
reference type. arguments provided at whilst allowing for varied
compile time. internal logic.
Polymorphism promotes code reusability and flexibility. For example, you might have different types of
vehicles (car, bicycle, aeroplane) all implementing a common "move" method, but each moving in their
own specific way. Your program can work with any vehicle type without knowing the specific
implementation details.
7
Gagan Public School, Khair Bypass Road, Aligarh
Abstract Classes and Methods
Abstract classes represent incomplete concepts that
require further specification through inheritance. They
provide a way to define common structure and partial
implementation whilst forcing subclasses to complete the
missing pieces.
This approach ensures consistency across related classes
by requiring them to implement specific methods whilst
allowing flexibility in how those methods are implemented.
Abstract classes are particularly useful when you have a
group of related classes that share common
characteristics but differ in specific behaviours.
Think of an abstract class like a partially completed form -
Abstract Classes
it has some fields filled in (concrete methods) and some
Cannot be instantiated blank fields that must be completed by whoever uses it
directly but serve as (abstract methods). This guarantees that all completed
templates for other forms will have the required information whilst allowing
classes. They can contain customisation where appropriate.
both concrete and
abstract methods. abstract class Animal {
public void sleep() {
System.out.println("Sleeping...");
Abstract Methods }
Methods declared without
abstract void makeSound();
implementation.
}
Subclasses must provide
concrete implementations
for all inherited abstract
methods.
8
Gagan Public School, Khair Bypass Road, Aligarh
Java Data Types: Building Blocks of
Programs
Java's type system provides the foundation for all data manipulation in your programs. Understanding
data types is crucial for efficient memory usage, preventing errors, and writing robust applications that
handle different kinds of information appropriately.
Primitive Types Reference Types
Built-in data types that store simple values Store references (addresses) to objects in
directly in memory. Include byte, short, int, memory rather than the actual values. Include
long, float, double, boolean, and char. These classes, interfaces, arrays, and enumerations.
are the most efficient for basic data storage. More flexible but require more memory
overhead.
12,000,000,000,000,000,000
8,000,000,000,000,000,000
4,000,000,000,000,000,000
0
byte int long double
Memory Size (bits) Range (approximate)
Choosing the right data type is essential for program efficiency and correctness. Use the smallest
data type that can accommodate your expected range of values to optimise memory usage, but
ensure it's large enough to prevent overflow errors that could cause unexpected program behaviour.
9
Gagan Public School, Khair Bypass Road, Aligarh
Comments in Java: Documenting
Your Code
Comments are essential for creating maintainable, professional Java code. They explain what your
code does, why certain decisions were made, and how complex algorithms work. Well-commented
code becomes invaluable when you return to modify it months later or when other developers need to
understand your work.
Single-Line Multi-Line Documentation
Comments Comments Comments
Use double forward Enclosed between /* and Special comments
slashes (//) for brief */, these comments span starting with /** that
explanations on a single multiple lines. Ideal for generate API
line. Perfect for quick detailed explanations of documentation. Include
clarifications about complex logic, algorithm parameter descriptions,
variable purposes, descriptions, or return values, and usage
algorithm steps, or temporary code examples. Essential for
temporary notes during disabling during professional
development. debugging. development.
int age = 25; // User's /* This method /**
age in years calculates * Calculates area of
// TODO: Add compound interest a rectangle
validation for using the formula * @param length
negative ages A = P(1 + r/n)^(nt) The length in metres
where P is * @param width
principal, r is rate, The width in metres
etc. */ * @return The area
in square metres
*/
Best Practice: Write comments that explain the "why" behind your code, not just the "what".
Good code should be self-explanatory about what it does, but comments should clarify the
reasoning behind design decisions.
10
Gagan Public School, Khair Bypass Road, Aligarh
Setting Up Java Path: Temporary and
Permanent Configuration
Configuring your Java environment correctly is crucial for seamless development. The PATH variable
tells your operating system where to find Java executables, enabling you to run Java commands from
any location in your terminal or command prompt.
Temporary Path Setup Permanent Path Setup
Temporary path configuration lasts only for the Permanent configuration ensures Java remains
current terminal session. This method is useful accessible across all terminal sessions and
for testing different Java versions or when you system restarts. This is the preferred method for
need a quick setup without permanent system development environments.
changes.
Windows (System Properties):
Windows Command Prompt:
Open System Properties ³ Environment
Variables
set PATH=%PATH%;C:\Program
Edit PATH variable
Files\Java\jdk-11.0.1\bin
Add Java bin directory path
macOS/Linux Terminal: Restart command prompt
macOS/Linux (.bashrc or .zshrc):
export PATH=$PATH:/usr/lib/jvm/java-11-
openjdk/bin
export JAVA_HOME=/usr/lib/jvm/java-11-
openjdk
The temporary method is perfect for export PATH=$PATH:$JAVA_HOME/bin
experimentation and learning, as it won't affect
other applications or persist after you close the
terminal window.
Gagan Public School, Khair Bypass Road, Aligarh
Your First Java Program: Hello World
Writing your first Java program is an exciting milestone that marks the beginning of your programming
journey. The traditional "Hello World" program demonstrates the basic structure of Java applications
and introduces you to essential concepts like classes, methods, and output statements.
Create the Source File 1
Create a new file named
'HelloWorld.java' using any text editor.
2
The filename must exactly match the
Write the Program Code
class name, including capitalisation.
Type the complete program structure
including class declaration, main
method, and print statement. Pay
Compile the Program 3 attention to proper syntax and
Use the 'javac HelloWorld.java' command indentation.
to compile your source code into
bytecode. This creates a .class file.
4 Run the Program
Execute your program using 'java
HelloWorld' command. The JVM
interprets the bytecode and displays
your output.
1
Complete Hello World Program
public class HelloWorld {
public static void main(String[] args) { Class Required
System.out.println("Hello, World!");
Every Java program needs at least
System.out.println("Welcome to Java
one class
programming!");
}
1
}
This simple program demonstrates several fundamental
Java concepts. The public class HelloWorld declaration Main Method
creates a class that serves as the container for your code.
Entry point for program execution
The main method is the entry point where program
execution begins.
The System.out.println() statement displays text to the
console. This method is part of Java's standard library and
2
handles the complexities of output formatting and display File Steps
for you.
Compile to .class then run with JVM