0% found this document useful (0 votes)
6 views16 pages

JAVA Chapter 1

The document provides an overview of Java programming, detailing its ecosystem, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It explains the compilation and execution flow of Java applications, the structure of Java identifiers, naming conventions, and the various data types in Java. Additionally, it emphasizes the importance of the main method as the entry point for Java programs.

Uploaded by

adityarajaj189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views16 pages

JAVA Chapter 1

The document provides an overview of Java programming, detailing its ecosystem, including the Java Development Kit (JDK), Java Runtime Environment (JRE), and Java Virtual Machine (JVM). It explains the compilation and execution flow of Java applications, the structure of Java identifiers, naming conventions, and the various data types in Java. Additionally, it emphasizes the importance of the main method as the entry point for Java programs.

Uploaded by

adityarajaj189
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 16

RASHTRIYA RAKSHA UNIVERSITY

Pioneering National Security and Police University of India An


institute of national importance.
National Security is Supreme!
Lavad – Dahegam, Gandhinagar – 382305

School of Information Technology,


Artificial Intelligence
&
Cyber Security
(SITAICS)
BACHELOR OF TECHNOLOGY
IN
COMPUTER SCIENCE & ENGINEERING
(WITH SPECIALIZATION IN CYBER SECURITY)

Semester-III
(Session 2025-26)

Java Programming
(G3AD12JPM)

Submitted by: Adityaraj jadeja


Enrollment No:25003111062032001

0|Page
Chapter 1
I. Introduction to the Java Ecosystem

A. The Vision of "Write Once, Run Anywhere" (WORA)

• Java, developed by Sun Microsystems in 1995, aims for "Write Once, Run
Anywhere" (WORA).
• This means Java code, once compiled into bytecode, can run on any machine
with a Java Virtual Machine (JVM), abstracting away underlying hardware
differences.
• WORA solved the problem of software needing recompilation for different
operating systems.

B. Overview of Key Components: JDK, JRE, and JVM

• The Java platform has three core components: Java Development Kit (JDK),
Java Runtime Environment (JRE), and Java Virtual Machine (JVM).
• They work together for Java application development and execution.
• JVM executes bytecode, JRE provides the runtime environment, and JDK offers
development tools.

II. The Java Virtual Machine (JVM): The Engine of Portability

A. Definition and Core Purpose

• The JVM is an abstract machine that executes Java bytecode.


• It does not directly understand Java source code (.java files); it requires
compiled bytecode (.class files).
• The JVM translates platform-independent bytecode into machine-specific
instructions.

B. Platform Dependency vs. Bytecode Independence

• The JVM itself is platform-dependent (e.g., different versions for Windows,


Linux, macOS).
• However, Java bytecode (.class files) is platform-independent.
• This means the same .class file can run on any machine with a compatible JVM.
• This design allows developers to write code once, while JVM vendors handle
platform-specific translation.

1|Page
C. Internal Architecture and Key Components

• The JVM includes the ClassLoader, Just-In-Time (JIT) Compiler, and Garbage
Collector.
• ClassLoader: Dynamically loads Java .class files into memory as needed.
• JIT Compiler: Improves performance by compiling frequently executed
bytecode into native machine code at runtime.
• Garbage Collector: Automatically manages memory, reclaiming space from
unreferenced objects.

D. The JVM Specification and Implementations

• The JVM Specification is an abstract definition of its requirements and


behavior.
• OpenJDK and Oracle JDK are examples of specific JVM implementations that
adhere to this specification.
• This standardization ensures bytecode compatibility across different JVMs,
promoting a healthy ecosystem.

III. The Java Runtime Environment (JRE): Enabling Program


Execution

A. Definition and Components

• The JRE is a software package providing the environment to run Java programs.
• It is an implementation of the JVM, designed for execution of Java applications.
• The JRE includes the JVM, Java class libraries (e.g., rt.jar, util, math, lang, awt,
swing), and other supporting files.

B. Role in Running Java Applications

• The JRE's primary role is to execute Java programs.


• Users must install JRE to run Java applications or applets.
• It is specifically for executing compiled Java files (bytecode).
• Includes deployment technologies like Java Plug-in and Java Web Start.

2|Page
C. Distinction from JDK

• The JRE is for running programs; it does not contain development tools like
compilers (javac) or debuggers.
• Developers cannot write or compile new Java programs using only the JRE.
• This separation allows for leaner deployments on end-user machines.

IV. The Java Development Kit (JDK): The Complete Development


Suite

A. Definition and Comprehensive Toolset

• The JDK is a comprehensive software development kit for developing and


running Java applications.
• It is a superset of the JRE, including the JVM, class libraries, and development
tools.
• Tools include the Java compiler (javac.exe), Java application launcher
(java.exe), debugger, and documentation generator.

B. Role in Developing and Compiling Java Applications

• The JDK is the primary environment for Java developers.


• It facilitates the entire development process, from source code creation to
executable bytecode.
• Its comprehensive nature simplifies workflow and ensures compatibility.

C. The Development Workflow: From Source Code to Execution

• Step 1: Write Source Code: Developer writes Java source code in a .java file.
• Step 2: Compile: The javac compiler (part of JDK) compiles .java files into
platform-independent bytecode (.class files).
• Step 3: Execute: The JRE loads and executes the .class file using the JVM.
• This two-step process ensures syntax correctness, type safety, platform
independence, and security.

3|Page
V. Java Compilation and Execution Flow

A. The Java Compiler (javac): Transforming Source to Bytecode

• javac (from JDK) converts .java source code into machine-independent


bytecode (.class files).
• Compilation Steps:
o Parse: Reads source files, converts characters to tokens, and builds an Abstract
Syntax Tree (AST).
o Enter: Adds symbols for definitions to a symbol table.
o Process Annotations: Processes annotations if requested.
• Output is .class files containing bytecode, which is independent of machine or
OS.

B. The JVM's Execution Lifecycle

• The main .class file is passed to the JVM for execution.

1. Class Loading: Loading Bytecode into Memory

• The JRE's ClassLoader loads necessary .class files into memory.


• Class Loading Functions:
o Loading: Creates a binary stream from the .class file, parses it, and creates a
java.lang.Class instance.
o Linking: Integrates the binary form of a class into the JVM's runtime state.
▪ Verification: Checks if the loaded class is well-formed and adheres to
Java/JVM semantic requirements (e.g., valid opcodes, correct branch targets).
▪ Preparation: Creates and initializes static fields to default values.
▪ Resolution (Optional): Checks symbolic references to other classes/interfaces.
o Initialization: Executes static initializers and initializers for static fields in
order.
• Class Loaders: Includes a primordial (bootstrap) class loader and user-defined
(non-primordial) class loaders.

2. Bytecode Execution: Interpretation vs. JIT Compilation

• After loading and verification, the JVM executes bytecode.


• Modern JVMs primarily use Just-In-Time (JIT) compilation for performance.

4|Page
C. The Just-In-Time (JIT) Compiler: Optimizing Runtime
Performance

1. Purpose and Mechanism

• The JIT compiler improves Java application performance by compiling


frequently executed bytecode into native machine code at runtime.
• Once compiled, the JVM calls this optimized native code directly.

2. Performance Enhancement and Trade-offs

• JIT compilation reduces performance penalties from repeated bytecode


interpretation.
• It balances initial compilation overhead with long-term performance gains.
• The JIT uses "hot spot" detection to identify and optimize frequently executed
code paths.

3. Optimization Levels and Sampling

• JIT compiles methods at various optimization levels (e.g., cold, warm, hot,
veryHot, scorching).
• Higher levels offer better performance but cost more CPU/memory.
• A sampling thread identifies "hot spots" for re-optimization.

4. Relationship with the JVM Interpreter

• The interpreter is used for initial bytecode execution or for less frequently called
methods.
• JIT is enabled by default; disabling it leads to significant performance
degradation.

VI. Java Identifiers and Naming Conventions: Crafting Readable


Code

A. Rules for Valid Java Identifiers

• Identifiers are names for variables, methods, classes, etc.


• Rules:

5|Page
o Must start with a letter (A-Z, a-z), underscore (_), or dollar sign ($). Cannot start
with a digit.
o Can contain letters, digits (0-9), underscores, or dollar signs after the first
character.
o Case-sensitive: myVariable and MyVariable are distinct.
o Cannot be Java-reserved words (keywords like class, int, void).
o No other special symbols or characters are allowed besides _ and $.
o No explicit length limit, but excessively long names hinder readability.

B. Standard Naming Conventions: Best Practices for Clarity and


Consistency

• Conventions make code easier to read, understand, and maintain.


• Prioritize meaningful and descriptive names.
• 1. Packages:
o All-lowercase ASCII letters.
o Use reverse domain name format (e.g., com.mycompany.utilities).
• 2. Classes:
o Nouns, mixed case (CamelCase/PascalCase), first letter of each internal word
capitalized.
o Simple, descriptive, use whole words.
• 3. Interfaces:
o Capitalized like class names (CamelCase/PascalCase).
o Typically describe an operation or capability.
• 4. Methods:
o Verbs, mixed case (lowerCamelCase), first letter lowercase, subsequent internal
words capitalized.
o Clearly describe the action.
• 5. Variables:
o Mixed case (lowerCamelCase), lowercase first letter, internal words capitalized
(except constants).
o Short, meaningful, mnemonic.
o Avoid starting with _ or $.
o Avoid single-character names except for temporary loop variables (e.g., i, j).
• 6. Constants:
o All uppercase, words separated by underscores (_) (ALL_CAPS).
o Typically static final.

C. Importance of Meaningful Names

• Adherence to conventions makes code self-documenting, facilitating


collaboration, debugging, and maintenance.
• Reduces cognitive load and improves team efficiency.

6|Page
VII. Java Data Types: Building Blocks of Information

A. Primitive Data Types: Fundamental Values

• Java has eight primitive data types for storing simple values.
• They are not objects and represent raw values, typically stored on the stack for
efficiency.

1. Integer Types

• byte: 8-bit signed integer; range -128 to 127. Default 0.


• short: 16-bit signed integer; range -32,768 to 32,767. Default 0.
• int: 32-bit signed integer; range −231 to 231−1 (approx. ±2.1 billion). Default 0.
Most common integer type.
• long: 64-bit signed integer; range −263 to 263−1 (approx. ±9.2 quintillion).
Default 0. Used for values exceeding int capacity. Suffixed with 'L' or 'l'.

2. Floating-Point Types

• float: 32-bit, single-precision (IEEE 754); approx. 1.4×10−45 to 3.4×1038.


Precision ~7 decimal digits. Default 0.0. Suffixed with 'f' or 'F'.
• double: 64-bit, double-precision (IEEE 754); approx. 4.9×10−324 to
1.8×10308. Precision ~15 decimal digits. Default 0.0. Default for decimals.

3. Character Type

• char: 16-bit unsigned Unicode character; range 0 to 65535. Cannot be negative.

4. Boolean Type

• boolean: Stores true or false. Default false. Logically 1 bit, often padded to 1
byte. Cannot be cast to other types.

7|Page
5. Summary of Java Primitive Data Types

Primitive Memory Size Default Range


Type Value

boolean 8 bits false true or false

byte 8 bits, signed 0 -128 to 127 inclusive


integer

char 16 bits, \u0000 or 0 to 65535


Unicode code
character point 0

short 16 bits, 0 -32,768 to 32,767 inclusive


signed integer

int 32 bits, 0 −231 to 231−1


signed integer

long 64 bits, 0 −263 to 263−1


signed integer

float 32 bit, IEEE 0.0 1.4×10−45 to 3.4028235×1038 (6-7


754, floating- significant decimal places)
point value

double 64 bit, IEEE 0.0 4.9×10−324 to


754 1.7976931348623157×10308 (15
significant decimal places)
19

B. Non-Primitive Data Types: Complex Structures and References

• Also called reference data types; store references to objects on the heap.
• Provide additional functionality through methods and attributes.
• Most are user-defined, but String is built-in.

1. Strings

• Sequences of characters in a single variable.


• Variable size, no null termination.

8|Page
• Syntax: String stringName = "characters";
• Example: String str1 = "Hello World"; or String str1 = new String("Scaler
Topics");

2. Arrays

• Store multiple values of the same data type contiguously.


• Accessed by index (starts from 0).
• Dynamically allocated at runtime; size specified by an integer.
• Syntax: dataType arrayName; or dataType arrayName = new dataType[size];
• Example: int numbers = {1, 2, 3, 4, 5};

3. Classes and Objects

• Class: User-defined blueprint for creating objects.


• Object: An instance of a class.
• Encapsulate properties (fields) and behaviors (methods).
• Example: class Car { String model;... } Car myCar = new Car("Toyota", 2020);

4. Interfaces

• Achieve abstraction; define a contract for behavior.


• Can contain abstract, default, static, and private methods (since Java 9).
• Example: interface Comparable { int compareTo(Object o); }

5. Key Differences from Primitive Data Types

• Storage: Primitives store values directly (stack); non-primitives store references


to objects (heap).
• Mutability: Non-primitives (objects) are generally mutable (except String).
Primitives hold values.
• Default Values: Primitives have predefined defaults (e.g., 0, false); non-
primitives default to null.
• Functionality: Non-primitives offer methods/attributes; primitives offer basic
storage/arithmetic.
• Inheritance: Non-primitives (classes) support inheritance; primitives do not.

9|Page
VIII. The main Method: The Program's Entry Point

A. Syntax and Structure: public static void main(String args)

• The public static void main(String args) method is the primary entry point for
any Java program.
• The JVM looks for and starts execution from this method.
• Its syntax must be strictly followed.

B. Dissecting Each Keyword and Component

• public: Access modifier; allows JVM to access and execute the method from
anywhere.
o If not public, JVM cannot find it, resulting in a "Main method not found" error.
• static: Indicates the method belongs to the class, not an object instance.
o Allows JVM to call main directly without creating a class instance first.
o If not static, an error "Main method is not static" occurs.
• void: Return type; means the main method does not return any value.
o Program ends when main completes, so no return value is needed.
• main: Predefined, mandatory name for the program's entry point.
o JVM specifically looks for a method named main.
• String args: Parameter representing an array of String objects.
o Allows command-line arguments to be passed to the program at runtime.
o String... args (varargs) is also valid.
o args can be any valid variable name.

C. Significance in Java Application Execution

• The main method's rigid signature is a universal contract between the Java
application and the JVM.
• Ensures a predictable and standardized entry point for execution, testing, and
deployment.
• Can contain core logic or bootstrap other methods.

IX. Type Conversion and Casting in Java: Managing Data Type


Compatibility

• Java is strongly typed; every variable has a defined type.


• Type conversion (casting) converts a value from one data type to another.

10 | P a g e
• Done implicitly (automatically) or explicitly (manually).

A. Implicit (Widening) Conversion: Automatic and Safe

1. Definition and Conditions

• Automatic conversion from a smaller data type to a larger, compatible one.


• Conditions:
o Data types must be compatible (e.g., numeric types).
o Smaller type assigned to a larger type.

2. Rules for Automatic Promotion

• byte to short, int, long, float, double.


• short to int, long, float, double.
• int to long, float, double.
• long to float, double.
• float to double.
• byte, short, char operands promote to int in expressions.

3. No Risk of Data Loss

• The target type can accommodate all values from the source type.

4. Example Code: Implicit Widening Conversion

Java

public class WideningExample {


public static void main(String args) {
int smallInt = 100;
long largeLong = smallInt; // int to long
float largeFloat = largeLong; // long to float
double largeDouble = largeFloat; // float to double

System.out.println("smallInt: " + smallInt);


System.out.println("largeLong: " + largeLong);
System.out.println("largeFloat: " + largeFloat);
System.out.println("largeDouble: " + largeDouble);
}
}

11 | P a g e
Output:

smallInt: 100
largeLong: 100
largeFloat: 100.0
largeDouble: 100.0

B. Explicit (Narrowing) Casting: Manual with Potential Risks

1. Definition and Purpose

• Manual conversion from a larger data type to a smaller one.


• Required because it may lead to data loss.
• Used for incompatible types or when accepting potential data loss.

2. Syntax

• (targetType) value
• Example: int i = (int) d;

3. Risks of Data Loss

• Truncation: Fractional part discarded when casting floating-point to integer.


• Overflow/Underflow: Incorrect results if value exceeds target type's range.
Java doesn't check.

4. Example Code: Explicit Narrowing Casting with Truncation

Java

public class NarrowingExample {


public static void main(String args) {
double largeDouble = 1234.5678;
int smallInt;
smallInt = (int) largeDouble; // double to int

12 | P a g e
System.out.println("largeDouble: " + largeDouble);
System.out.println("smallInt (truncated): " + smallInt);
}
}

Output:

largeDouble: 1234.5678
smallInt (truncated): 1234

5. Example Code: Explicit Narrowing Casting with


Overflow/Underflow

Java

public class NarrowingOverflowExample {


public static void main(String args) {
int largeInt = 200; // Value within byte range (byte max 127)
byte b1 = (byte) largeInt;
System.out.println("int 200 to byte: " + b1); // Output: -56 (200 - 256)

int veryLargeInt = 300; // Value outside byte range


byte b2 = (byte) veryLargeInt;
System.out.println("int 300 to byte: " + b2); // Output: 44 (300 % 256 = 44)

double d = 323.142;
byte b3 = (byte) d; // double to byte
System.out.println("double 323.142 to byte: " + b3); // Output: 67 (323 % 256 =
67)
}
}

Output:

int 200 to byte: -56


int 300 to byte: 44
double 323.142 to byte: 67

13 | P a g e
C. Comparison of Implicit (Widening) vs. Explicit (Narrowing)
Casting

Aspect Implicit (Widening) Explicit (Narrowing) Casting


Casting

Also Known As Automatic Type Manual Type Conversion


Conversion

Direction of Smaller type to larger Larger type to smaller type


Conversion type

Risk of Data Loss No risk of data loss May result in data loss (e.g.,
truncation, overflow)

Syntax No explicit syntax Explicit syntax required:


Requirement required (automatic) (targetType) value

Compiler Performed automatically Requires programmer's


Behavior by the compiler explicit instruction
4

D. Best Practices for Type Casting

• Use explicit casting cautiously; understand data loss potential.


• Check type compatibility (e.g., instanceof for objects) to avoid
ClassCastException.
• Prefer wrapper classes (Integer.parseInt(), String.valueOf()) for String
conversions.
• Use BigInteger and BigDecimal for arbitrary precision/size.
• Implement proactive boundary checks to prevent overflow/underflow.

X. Conclusion and Exam Preparation Strategies

A. Recap of Core Concepts

• Understand JDK, JRE, JVM: JDK for development, JRE for runtime, JVM for
bytecode execution.

14 | P a g e
• Compilation (javac) to bytecode, then JVM execution (with JIT optimization)
ensures platform independence.
• Adhere to Java naming rules for readable, maintainable code.
• Master primitive (fixed-size, value-based) and non-primitive (flexible,
reference-based) data types for efficient memory and robust design.
• The main method (public static void main(String args)) is the program's
universal entry point.
• Understand implicit (safe, automatic widening) and explicit (manual, risky
narrowing) type conversion.

B. Tips for Effective Study and Problem Solving

• Hands-on Coding: Write and execute programs, experiment with data types
and casting.
• Practice Identifier Naming: Consistently apply Java naming conventions.
• Trace Execution Flow: Visualize JVM, ClassLoader, and JIT roles from .java
to native code.
• Review Code Examples: Predict outputs, especially for data loss scenarios.
• Understand the "Why": Focus on the rationale behind concepts (e.g., why
JVM is platform-dependent, why explicit casting is needed).

15 | P a g e

You might also like