Unit 1 Java
Unit 1 Java
1
UNIT 1
1. INTRODUCTION TO JAVA :
Java is one of the most popular and widely used programming languages.
1. Simple and Easy to Learn: Java’s syntax is straightforward, influenced by C and C++.
2. Object-Oriented: It uses objects and classes, making code reusable, modular, and scalable.
3. Platform-Independent: Java programs can run on any device with a JVM.
4. Secure: Java provides built-in security features like bytecode verification and secure class
loading.
5. Robust: It has strong memory management and exception handling capabilities.
6. Multithreaded: Java supports concurrent programming, allowing multiple threads to run
simultaneously.
• Web Development: Backend development with frameworks like Spring and Hibernate.
• Mobile Applications: Android development (via Android SDK).
• Enterprise Applications: Used in financial and corporate systems.
• Game Development: Creating 2D and 3D games.
• Scientific Applications: Tools requiring high performance and security.
Java remains a popular language due to its versatility, stability, and extensive community support.
2
UNIT 1
2. EVOLUTION OF JAVA
This table summarizes the significant milestones and key features introduced during Java's
evolution. Let me know if you'd like further details on any specific version!
3
UNIT 1
1. Encapsulation: Bundles data and methods in a single unit (class) and restricts direct access
to data through access modifiers.
2. Inheritance: Allows one class to inherit properties and methods from another, promoting
code reusability.
3. Polymorphism: Allows a single method or function to behave differently based on the
context, enabling flexibility.
4. Abstraction: Hides implementation details and exposes only the essential features.
Java is a fully object-oriented language (except for a few primitive types) and adheres to the OOP
structure in the following ways:
1. Encapsulation in Java
• Java uses classes to encapsulate data (fields) and methods.
• Access modifiers (private, protected, public) control access to the internal details of a class,
promoting security and modularity.
2. Inheritance in Java
• Java allows classes to inherit properties and methods from other classes using the extends
keyword.
• It supports single inheritance directly (one class inherits another), while multiple inheritance
is achieved through interfaces to avoid ambiguity.
3. Polymorphism in Java
• Compile-time Polymorphism: Achieved through method overloading, where multiple
methods share the same name but differ in parameter lists.
• Runtime Polymorphism: Achieved through method overriding, where a subclass redefines a
method from its superclass.
4. Abstraction in Java
• Java uses abstract classes and interfaces to achieve abstraction.
• Abstract classes provide a blueprint for subclasses, while interfaces define a contract that
implementing classes must follow.
By combining these principles, Java implements a robust OOP structure, making it suitable for
building modular, reusable, and scalable applications.
4
UNIT 1
4. CHARACTERISTICS OF JAVA
This table highlights the key characteristics that make Java a versatile and widely used programming
language.
5
UNIT 1
The basics of Java programming involve understanding its foundational elements, which
provide the building blocks for developing Java applications. Here’s a breakdown:
1. Features of Java
3. Data Types
Java provides two types of data:
• Primitive Types: Includes integers (int), floating points (float), characters (char), and booleans
(boolean).
• Non-Primitive Types: Includes objects, arrays, and strings.
int age = 25;
float temperature = 36.6f;
char grade = 'A';
boolean isPassed = true;
4. Variables
Variables store data. They are declared with a type and optionally initialized:
int number = 10; // Declaration and initialization
5. Operators
Java includes:
• Arithmetic Operators: +, -, *, /, %
• Relational Operators: ==, !=, <, >, <=, >=
• Logical Operators: &&, ||, !
6. Control Statements
• Decision Making:
if (age > 18) {
System.out.println("Eligible to vote");
} else {
System.out.println("Not eligible");
}
• Loops
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
6
UNIT 1
7
UNIT 1
5. HOW JAVA PROGRAM IS COMPILED AND WHAT IS THE EXECUTION PROCESS? EXPLAIN.
The process of compiling and executing a Java program involves several steps, transforming human-readable
code into machine-executable output. Below is a step-by-step explanation:
2. Compilation
• The Java source code (.java file) is compiled into bytecode by the Java Compiler (javac).
• The bytecode is a platform-independent, intermediate representation of the program.
• The compiled output is saved in a .class file.
Command:
javac HelloWorld.java
Output:
HelloWorld.class (bytecode file).
3. Execution
• The Java Virtual Machine (JVM) executes the .class file.
• The JVM interprets the bytecode and translates it into machine-specific instructions at runtime.
Command:
java HelloWorld
Output:
The program runs and prints:
Hello, World!
This two-step process (compilation and execution) makes Java both platform-independent (via bytecode) and
machine-specific (via the JVM).
8
UNIT 1
The Java Virtual Machine (JVM) is a runtime environment for executing Java bytecode. It abstracts the
underlying hardware and operating system to provide platform independence and efficient execution. Here's
an overview of how JVM works and its architecture:
Workflow of JVM
1. Java Source Code Compilation:
o Java source code (.java file) is compiled by the Java Compiler (javac) into bytecode (.class
file`).
2. Bytecode Execution:
o The bytecode is platform-independent and executed by the JVM.
3. JVM Execution Steps:
o Class Loader loads .class files into the JVM.
o Runtime Data Areas store and manage the execution state.
o Execution Engine interprets or compiles bytecode into machine code.
o Native Interface connects to platform-specific libraries if required.
JVM Architecture
The JVM architecture consists of several components organized to execute bytecode effectively:
3. Execution Engine
The core of the JVM that interprets or compiles bytecode into machine code.
Component Description
Interpreter Executes bytecode line by line. Slower but ensures quick startup.
Just-In-Time (JIT) Converts frequently executed bytecode into native machine code for faster
Compiler execution.
Garbage Collector Manages memory by automatically reclaiming unused objects in the heap.
4. Native Interface
• Allows interaction between Java and platform-specific libraries (e.g., C/C++ code).
• Implemented using Java Native Interface (JNI).
9
UNIT 1
5. Native Libraries
• Platform-specific libraries required by the JVM for operations like file I/O, networking, and threading.
Advantages of JVM
• Platform Independence: Bytecode runs on any platform with a compatible JVM.
• Memory Management: Automatic garbage collection eliminates memory leaks.
• Security: Bytecode verification and sandboxing protect against malicious code.
This architecture ensures efficient execution, portability, and security for Java applications.
10
UNIT 1
7. CLIENT-SIDE PROGRAMMING
Client-side programming in Java refers to code that executes on the user's (client's) device rather than on a
server. It focuses on user interface (UI), interactions, and processing within a web browser or a standalone
application. Java provides several ways to implement client-side applications.
11
UNIT 1
Java is widely recognized for its platform independence, portability, and strong security features, which make it
a robust and reliable programming language. Here's a detailed explanation of these characteristics:
1. Platform Independence
• Definition: Platform independence means that a Java program written on one platform can run on any
other platform without modification.
• How It Works:
1. Compilation:
▪ Java source code (.java) is compiled into bytecode (.class) by the Java Compiler
(javac).
2. Execution:
▪ The Java Virtual Machine (JVM) interprets this bytecode into platform-specific
machine instructions.
o Since the JVM is available for various platforms (Windows, Linux, macOS), the bytecode
remains the same and can run anywhere a compatible JVM is installed.
• Significance:
o Eliminates the need for platform-specific code.
o Follows the principle of Write Once, Run Anywhere (WORA).
2. Portability
• Definition: Portability refers to the ability to move Java programs from one system to another without
requiring changes.
• How It Works:
o The use of bytecode ensures that programs can be executed across different hardware and
operating systems, as long as the system has a JVM.
o Java's standard libraries (e.g., I/O, networking) abstract platform-specific implementations,
allowing developers to write uniform code.
• Examples:
o A Java program compiled on Windows can run on Linux without recompilation.
3. Security
• Definition: Java provides built-in security mechanisms to protect applications from malicious code and
unauthorized access.
• How It Works:
o Class Loader:
▪ Separates the loading of classes from different sources (e.g., local files, network) and
prevents malicious code from interfering with trusted code.
o Bytecode Verifier:
▪ Checks the validity of the bytecode and ensures it adheres to Java’s security
constraints (e.g., no illegal memory access).
o Security Manager:
▪ Defines access control policies, such as file read/write permissions and network
access.
o Sandboxing:
▪ Untrusted code (e.g., applets) is run in a restricted environment to prevent it from
accessing system resources.
o Encryption and Authentication:
▪ Java supports secure communication protocols (e.g., SSL/TLS) and cryptographic
APIs for data encryption and authentication.
12
UNIT 1
• Examples:
o Java applets run in a sandbox to prevent unauthorized access.
o Secure Socket Layer (SSL) ensures secure web communication.
Comparison of Features
Feature Platform Independence Portability Security
Definition Write and execute code on Move programs across Protect applications from
any platform without platforms seamlessly. malicious or unauthorized
changes. activities.
Enabled By JVM and bytecode. Bytecode and platform- Class Loader, Bytecode Verifier,
agnostic libraries. Security Manager.
Significance Ensures wide compatibility Simplifies application Ensures safe execution of
and reuse of code. deployment and applications in untrusted
distribution. environments.
These features make Java a versatile, secure, and developer-friendly language for building platform-
independent applications.
13
UNIT 1
Hierarchy:
1. JVM → Core runtime engine.
2. JRE → JVM + Standard Libraries (for running Java applications).
3. JDK → JRE + Compiler and Development Tools (for creating Java applications).
14
UNIT 1
JAR (Java Archive) is a file format used to bundle multiple Java-related files (like class files, metadata, and
resources) into a single, compressed file. It simplifies the distribution, deployment, and execution of Java
applications.
15
UNIT 1
1. General Rules
• Names should be descriptive and convey the purpose or role of the identifier.
• Avoid using reserved keywords (e.g., class, int) as names.
• Use camelCase or PascalCase for identifiers, depending on the context.
• Follow the case sensitivity of Java (e.g., variable and Variable are different).
3. Examples
Class
public class StudentRecord {
// Class name is PascalCase
}
Method
public void calculateAverage() {
// Method name is camelCase
}
Variable
int studentAge = 20; // camelCase
Constant
public static final double PI = 3.14159; // UPPERCASE
Package
package com.example.application; // lowercase
Interface
public interface Printable {
// Interface name is PascalCase
}
17
UNIT 1
18
UNIT 1
1. Arithmetic Operators
Used to perform basic mathematical operations.
Operator Description Example Result
+ Addition a+b Sum
- Subtraction a-b Difference
* Multiplication a*b Product
/ Division a/b Quotient
% Modulus (remainder) a % b Remainder
3. Logical Operators
Used to combine multiple conditions.
Operator Description Example Result
&& Logical AND (a > b) && (b > c) true/false
` ` Logical OR
! Logical NOT !(a > b) Opposite of condition
4. Assignment Operators
Used to assign values to variables.
Operator Description Example Equivalent To
= Assign value a = 10; a = 10;
+= Add and assign a += 10; a = a + 10;
-= Subtract and assign a -= 10; a = a - 10;
*= Multiply and assign a *= 10; a = a * 10;
/= Divide and assign a /= 10; a = a / 10;
%= Modulus and assign a %= 10; a = a % 10;
5. Bitwise Operators
Operate on bits and perform bit-level operations.
Operator Description Example Result
& Bitwise AND a&b Bit-level AND
` ` Bitwise OR `a
^ Bitwise XOR a^b Bit-level XOR
~ Bitwise Complement ~a Inverts bits
<< Left shift a << 2 Shifts bits left
>> Right shift a >> 2 Shifts bits right
19
UNIT 1
6. Unary Operators
Operate on a single operand.
Operator Description Example
+ Unary plus +a
- Unary minus -a
++ Increment (pre/post) ++a, a++
-- Decrement (pre/post) --a, a--
! Logical NOT !true
7. Ternary Operator
A shorthand for if-else statements.
Syntax Example
variable = (condition) ? value1 : value2; max = (a > b) ? a : b;
8. instanceof Operator
Used to test whether an object is an instance of a specific class or subclass.
Example Description
obj instanceof ClassName Returns true if obj is an instance of ClassName.
9. Special Operators
• new: Creates new objects.
• sizeof: Not available in Java (handled internally).
• Dot (.): Accesses members of a class or object.
These operators provide a wide range of functionalities for performing calculations, decision-making, and
object manipulations in Java.
20
UNIT 1
Bytecode Verification Ensures bytecode adheres to Java rules, Prevents illegal memory access and
type safety, and memory safety before type safety violations.
execution.
Class Loader Loads classes securely, maintaining strict Prevents malicious or unauthorized
Subsystem namespace management. classes from being loaded.
Sandbox Model Executes untrusted code in a restricted Limits file system and network access,
environment. ensuring no harm to the host system.
Security Manager Enforces customizable security policies. Controls access to sensitive system
resources like files, sockets, and
environment variables.
Access Control Uses security policy files to define Restricts unauthorized operations
permissions for applications. based on predefined permissions.
Automatic Memory Uses garbage collection to manage Ensures safe and efficient memory
Management memory and prevent manual errors like management, reducing vulnerabilities.
memory leaks.
Cryptographic Provides APIs for secure communication Facilitates safe handling of sensitive
Security (e.g., encryption, decryption). data and secure data transmission.
Secure Class Loading Verifies and authenticates loaded classes Prevents execution of malicious or
using code signing. tampered code.
Preventing Code Validates and verifies bytecode before Protects against code injection attacks.
Injection execution.
Exception Handling Enforces strict rules for exception Prevents system crashes and ensures
handling. predictable program behaviour.
Platform Isolates the application from the host OS Provides a safe execution environment
Independence and vulnerabilities using platform- regardless of the underlying system.
Security independent bytecode.
21
UNIT 1
Java’s Security Architecture and Security Policy are designed to provide a robust framework for protecting Java
applications against malicious attacks and unauthorized access. These mechanisms enforce security constraints
during the runtime of Java programs.
1. Security Architecture
Java's Security Architecture ensures a secure runtime environment through various components and
mechanisms.
Component Description
Class Loader Dynamically loads Java classes securely into the JVM. It prevents unauthorized or
malicious classes from being loaded.
Bytecode Verifies bytecode before execution to ensure that it adheres to Java language rules, is
Verifier type-safe, and has no illegal access to memory.
Security A runtime component that enforces access controls based on the defined security
Manager policy.
Access Intercepts and validates access requests to resources like files, networks, and system
Controller properties.
Cryptographic Provides encryption, decryption, message digests, and secure communication
APIs capabilities.
Sandbox Model Restricts untrusted code (e.g., applets) to operate in a controlled environment, limiting
access to system resources.
Garbage Manages memory and ensures safe memory handling to prevent unauthorized access or
Collector memory leaks.
2. Security Policy
The Security Policy in Java defines the permissions granted to Java code at runtime. These permissions are
specified in a policy file, which can be customized by the user or system administrator.
Feature Description
Policy File A plain-text file specifying what actions code can perform. For example, read/write
access to files or network connections.
Permission Java provides predefined permission classes (e.g., FilePermission, SocketPermission,
Classes RuntimePermission) to control resource access.
Customizable Administrators can modify the policy file to grant or revoke permissions based on
application requirements.
Grant Syntax Permissions are granted using the grant keyword in the policy file.
2. Permission Types:
o FilePermission: Controls file read/write/delete operations.
o SocketPermission: Manages network access.
o RuntimePermission: Controls access to system-level resources.
22
UNIT 1
23
UNIT 1
Feature Description
Restricted Environment Untrusted code is executed in an isolated space where it cannot interact with
the system's resources.
Fine-Grained Access Security policies define what resources the code can access (e.g., files, network,
Control system properties).
Dynamic Enforcement The security manager dynamically enforces restrictions during runtime.
Customizable Policies Administrators can modify policy files to grant or revoke specific permissions for
the sandboxed code.
24
UNIT 1
System Properties Blocks access to sensitive properties (e.g., user home directory).
UI Components Limits interaction with native UI elements.
Executable Code Prohibits untrusted code from invoking native system-level operations.
Conclusion
The sandbox model is a cornerstone of Java's security architecture, allowing safe execution of untrusted code
by isolating it in a restricted environment. It plays a vital role in applications like applets and web-based Java
programs, ensuring system integrity and user data protection.
25