BCA — Java Programming Unit I
BCA
Punjab Technical University
JAVA PROGRAMMING
Complete Notes — Unit I
Topic 1: Java Programming Fundamentals [CO2]
Topic 2: Java Essentials [CO2]
Covers: Java fundamentals, OOP concepts, JVM/JRE/JDK, Java program structure,
data types, variables, operators, scope, and comments — with examples.
Page 1 of 14
BCA — Java Programming Unit I
Table of Contents
TOC \h \o "1-3"
Page 2 of 14
BCA — Java Programming Unit I
Topic 1: Java Programming Fundamentals [CO2]
1.1 Introduction to Java
Java is a high-level, object-oriented, platform-independent programming language developed by Sun
Microsystems. It was originally designed by James Gosling and his team in 1991, under the project named
“Oak”, and was later renamed “Java” in 1995.
Key idea — WORA: Java follows the principle of “Write Once, Run Anywhere.” A Java program is compiled
into an intermediate form called bytecode, which can run on any device that has a Java Virtual Machine
(JVM), regardless of the underlying hardware or operating system.
Why Java is so widely used
• Simple, secure, and robust language suitable for enterprise applications.
• Platform independence through bytecode and JVM.
• Strong support for multithreading and networking.
• Large standard library (Java API) and huge developer community.
• Used in web applications, Android app development, enterprise software, cloud computing, and
embedded systems.
1.2 Stage for Java (The Java Platform)
The “stage” for Java refers to the platform/environment on which Java programs are written, compiled, and
executed. The Java platform consists of three major components that work together:
Component Description
A complete software development package used to develop Java
JDK (Java Development
applications. It includes the compiler (javac), JRE, debugger, and other
Kit)
development tools.
JRE (Java Runtime Provides the libraries and JVM required to run Java applications. It does
Environment) NOT contain development tools like a compiler.
An abstract machine that provides a runtime environment to execute
JVM (Java Virtual
Java bytecode. It is responsible for platform independence; a different
Machine)
JVM exists for each OS, but the bytecode remains the same.
Relationship: JDK ⊃ JRE ⊃ JVM, i.e., JDK contains JRE, and JRE contains JVM along with the core class
libraries.
How a Java Program Executes (Stages)
1. Source Code (.java file) is written by the programmer.
2. Compiler (javac) compiles the source code into Bytecode (.class file).
Page 3 of 14
BCA — Java Programming Unit I
3. JVM loads the bytecode using the Class Loader.
4. Bytecode Verifier checks the code for security violations.
5. Interpreter/JIT Compiler converts bytecode into machine code.
6. The program finally executes on the underlying hardware/OS.
1.3 Origin of Java
• 1991: Project started at Sun Microsystems by James Gosling, Mike Sheridan, and Patrick Naughton,
originally called the “Green Project.”
• Goal: To create a language for programming consumer electronic devices (set-top boxes, smart
appliances) that was small, reliable, and architecture-neutral.
• Oak: The language was initially named “Oak” after an oak tree outside Gosling's office.
• 1995: Renamed to “Java” (since “Oak” was already trademarked) — inspired by Java coffee. Java was
officially released by Sun Microsystems.
• Influence: Java's syntax is heavily influenced by C and C++, but it removes many complex and unsafe
features such as pointers and manual memory management.
• 2010: Oracle Corporation acquired Sun Microsystems and has maintained Java ever since.
1.4 Challenges of Java
When Java was designed, the creators faced several technical challenges that shaped the language. These
challenges — and how Java addressed them — are summarized below:
Challenge How Java Solved It
Introduced bytecode + JVM so the same compiled program runs on any
Platform Dependency
platform without recompilation.
Removed pointers, added bytecode verification, a security manager,
Security
and runtime checks to prevent unauthorized access.
Automatic Garbage Collection removes the need for manual memory
Memory Management
allocation/deallocation, reducing memory leaks.
Eliminated multiple inheritance (of classes), operator overloading,
Complexity of C++
pointers, and header files to simplify the language.
Network-centric Built-in, extensive networking libraries ([Link]) to support distributed,
computing internet-based applications.
Strong compile-time and run-time type checking, exception handling
Reliability
mechanism.
Introduced Just-In-Time (JIT) compilation to speed up bytecode
Performance
execution close to native speed.
Page 4 of 14
BCA — Java Programming Unit I
1.5 Java Features (Buzzwords)
Sun Microsystems summarized Java's design goals in a set of keywords, commonly called Java
Buzzwords/Features:
Feature Explanation
Easy to learn syntax (similar to C/C++) without complex features like
Simple
pointers and operator overloading.
Everything in Java is treated as an object (except primitive types), based on
Object-Oriented classes, objects, inheritance, polymorphism, abstraction, and
encapsulation.
Java code is compiled into bytecode that can run on any device with a JVM
Platform Independent
— “Write Once, Run Anywhere.”
No explicit pointers, bytecode verification, class loaders, and a security
Secure
manager protect against malicious code.
Strong memory management, automatic garbage collection, exception
Robust handling, and strict compile-time checking reduce the chance of runtime
errors.
The compiler generates an architecture-neutral bytecode format that can
Architecture Neutral
run on many processors, given the presence of a JVM.
The same bytecode runs on any platform; no implementation-dependent
Portable
features (e.g., fixed size of primitive data types).
Java supports multithreading natively, allowing multiple tasks to run
Multithreaded
concurrently within a single program.
Built-in support for networking (RMI, sockets, [Link] package) to build
Distributed
distributed applications.
Java programs carry extensive run-time information that can be used to
Dynamic verify and resolve access to objects at run time; supports dynamic loading
of classes.
Java bytecode is interpreted by the JVM, enabling faster development
Interpreted
cycles and platform independence.
Use of bytecode (close to native code) along with JIT compilation gives
High Performance
Java performance comparable to compiled languages.
1.6 Java Program Development
Developing a Java program involves a defined cycle of writing, compiling, and running the code. The steps
are:
7. Edit: Write the Java source code using a text editor or an IDE (e.g., Eclipse, IntelliJ, VS Code) and save it
with a .java extension. The file name must match the public class name.
Page 5 of 14
BCA — Java Programming Unit I
8. Compile: Use the Java compiler (javac) to convert the source code into bytecode (.class file). Example:
javac [Link]
9. Load: The Class Loader (part of JVM) loads the .class file(s) needed for execution into memory.
10. Verify: The Bytecode Verifier checks that the code does not violate Java's security rules and does not
corrupt memory.
11. Execute: The JVM's interpreter (with JIT compiler support) executes the bytecode. Example: java Hello
Example: A Simple Java Program
public class Hello {
public static void main(String[] args) {
[Link]("Hello, World!");
}
}
Compilation: javac [Link] → produces [Link]
Execution: java Hello → Output: Hello, World!
1.7 Object-Oriented Programming (OOP)
Object-Oriented Programming is a programming paradigm based on the concept of “objects,” which
combine data (attributes/fields) and behaviour (methods) into a single unit. Java is a purely object-oriented
language (except for primitive data types).
Core Concepts of OOP
Concept Description
A blueprint or template that defines the properties (fields) and behaviours
Class
(methods) of objects.
A real-world entity / instance of a class that has state and behaviour, and
Object
occupies memory at run time.
Binding data and methods together into a single unit (class) and restricting
Encapsulation
direct access to data using access modifiers (private, public, etc.).
A mechanism where one class (subclass) acquires the properties and
Inheritance
behaviours of another class (superclass), promoting code reusability.
The ability of an object/method to take many forms — achieved through
Polymorphism
method overloading (compile-time) and method overriding (run-time).
Hiding internal implementation details and showing only essential features
Abstraction
to the user, achieved via abstract classes and interfaces.
Advantages of OOP
Page 6 of 14
BCA — Java Programming Unit I
• Improves code reusability through inheritance.
• Easier maintenance and modification due to modular design.
• Better data security through encapsulation.
• Models real-world entities more naturally, improving design clarity.
• Supports scalability for large, complex software systems.
Page 7 of 14
BCA — Java Programming Unit I
Topic 2: Java Essentials [CO2]
2.1 Elements of a Java Program
A typical Java program is built from the following basic elements, arranged in a defined structure:
12. Documentation Section: Comments describing the program (purpose, author, date) — optional but
good practice.
13. Package Statement: Declares the package to which the class belongs, e.g., package [Link];
(must be the first statement, if present).
14. Import Statements: Used to include classes from the Java API or other packages, e.g., import
[Link];
15. Class Definition: Defines the class using the class keyword; contains fields and methods.
16. Main Method (Entry Point): public static void main(String[] args) — the starting point of execution for
any standalone Java application.
17. Variable Declarations: Declaration of variables used to store data within the program.
18. Statements & Expressions: The actual logic/instructions of the program.
Example showing the structure
// Documentation section
package myapp; // package statement
import [Link]; // import statement
public class Student { // class definition
String name; // variable declaration
int rollNo;
public static void main(String[] args) { // main method
Student s = new Student(); // statement
[Link] = "Raj";
[Link]([Link]);
}
}
2.2 Java API (Application Programming Interface)
Java API is a vast collection of pre-written classes, interfaces, and packages provided by Java that
programmers can use directly instead of writing code from scratch. It is part of the JDK and forms the
standard library of Java.
Page 8 of 14
BCA — Java Programming Unit I
Commonly Used Packages in the Java API
Package Purpose
Provides fundamental classes (String, Math, Object, System, Thread);
[Link]
imported automatically into every program.
Provides utility classes — collections (ArrayList, HashMap), Scanner, Date,
[Link]
Random, etc.
Provides classes for input/output operations such as file handling and
[Link]
streams.
[Link] Provides classes for networking, e.g., sockets, URL handling.
[Link] / [Link] Provide classes for building Graphical User Interfaces (GUIs).
[Link] Provides classes to create and manage applets.
Note: To use classes from a package (other than [Link]), the import statement is generally required, e.g.,
import [Link];
2.3 Variables and Literals
Variables
Variable: A named memory location used to store data that can change during program execution. Every
variable in Java has a data type, a name, and a value.
Syntax:
dataType variableName = value;
Example:
int age = 20;
double price = 99.99;
char grade = 'A';
Rules for Naming Variables (Identifiers)
• Must begin with a letter, underscore (_), or dollar sign ($) — not a digit.
• Can contain letters, digits, underscores, and dollar signs after the first character.
• Cannot be a reserved keyword (e.g., class, int, public).
• Java is case-sensitive (age and Age are different variables).
• No spaces or special symbols (other than _ and $) are allowed.
Literals
Literal: A literal is a fixed/constant value that is directly assigned to a variable in the source code (the value
itself, as written in the program).
Page 9 of 14
BCA — Java Programming Unit I
Type of Literal Example Description
Whole numbers; can be decimal, octal (0 prefix), or
Integer Literal 10, -25, 0x1A, 017
hexadecimal (0x prefix)
Floating-point Literal 3.14, 2.5e3 Numbers with a decimal point or exponent
Character Literal 'A', '9', '\n' A single character enclosed in single quotes
String Literal "Hello" A sequence of characters enclosed in double quotes
Boolean Literal true, false Only two possible values
Represents the absence of a value (for reference
Null Literal null
types)
2.4 Primitive Data Types
Java has 8 primitive data types built into the language. They are not objects and directly hold the value in
memory.
Data Type Size Default Value / Range
byte 1 byte -128 to 127
short 2 bytes -32,768 to 32,767
int 4 bytes -2,147,483,648 to 2,147,483,647
-9,223,372,036,854,775,808 to
long 8 bytes
9,223,372,036,854,775,807
float 4 bytes Single-precision 32-bit IEEE 754
double 8 bytes Double-precision 64-bit IEEE 754
Single 16-bit Unicode character ('\u0000' to '\
char 2 bytes
uffff')
boolean 1 bit (JVM-dependent) true or false only
Note: Java's primitive data types have a fixed size regardless of the platform/OS — this is part of what makes
Java “portable.”
2.5 The String Class
String is a class in the [Link] package (not a primitive type) used to represent a sequence of characters.
Even though it is a class, Java provides special built-in support for string literals.
Page 10 of 14
BCA — Java Programming Unit I
Creating Strings
String s1 = "Hello"; // using string literal (stored in
String pool)
String s2 = new String("Hello"); // using 'new' keyword (stored in heap
memory)
Key Characteristics
• Immutability: Once created, a String object's value cannot be changed. Any modification creates a
new String object.
• String Pool: String literals are stored in a special memory area called the String Constant Pool to save
memory by reusing identical literals.
• Concatenation: Strings can be joined using the + operator or the concat() method.
Commonly Used String Methods
Method Description
length() Returns the number of characters in the string.
charAt(int index) Returns the character at the specified index.
substring(int begin, int end) Returns a portion of the string.
toUpperCase() / toLowerCase() Converts the string to upper/lower case.
equals(String s) / Compares two strings for equality.
equalsIgnoreCase(String s)
concat(String s) Joins the given string to the end of the current string.
trim() Removes leading and trailing whitespace.
indexOf(String s) Returns the index of the first occurrence of the given string.
Example:
String name = "Java Programming";
[Link]([Link]()); // 16
[Link]([Link]()); // JAVA PROGRAMMING
[Link]([Link](0, 4)); // Java
2.6 Variables — Types in Java
Based on where they are declared and their lifetime, Java variables are classified into three types:
Type Description
Declared inside a method, constructor, or block. Exists only during
Local Variable
execution of that block and must be initialized before use.
Page 11 of 14
BCA — Java Programming Unit I
Type Description
Declared inside a class but outside any method (non-static). Each object
Instance Variable
of the class gets its own copy. Gets a default value automatically.
Declared with the static keyword inside a class, outside any method.
Static (Class) Variable
Shared by all objects of the class — only one copy exists in memory.
class Demo {
int instanceVar = 10; // instance variable
static int staticVar = 20; // static variable
void show() {
int localVar = 30; // local variable
[Link](localVar + instanceVar + staticVar);
}
}
2.7 Constants
Constant: A value that cannot be changed once assigned. In Java, constants are created using the final
keyword.
Syntax:
final dataType CONSTANT_NAME = value;
Example:
final double PI = 3.14159;
final int MAX_USERS = 100;
• By convention, constant names are written in UPPERCASE with underscores separating words.
• Any attempt to reassign a final variable causes a compile-time error.
• Constants improve code readability and prevent accidental modification of fixed values.
2.8 Operators
Operators are special symbols that perform operations on operands (variables and values). Java provides
several categories of operators:
Category Operators Example
Arithmetic + - * / % a + b, a % b
Relational == != > < >= <= a>b
Logical && || ! (a>b) && (b>c)
Assignment = += -= *= /= %= a += 5
Page 12 of 14
BCA — Java Programming Unit I
Category Operators Example
Unary + - ++ -- ! ++a, a--
Bitwise & | ^ ~ << >> >>> a & b, a << 2
Ternary (Conditional) ?: result = (a>b) ? a : b
instanceof instanceof obj instanceof String
Example:
int a = 10, b = 3;
[Link](a + b); // 13 (Arithmetic)
[Link](a > b); // true (Relational)
[Link](a > b && b > 0); // true (Logical)
int max = (a > b) ? a : b; // Ternary -> 10
2.9 Scope of Variables & Blocks
Scope refers to the region/part of the program within which a variable is accessible/visible. In Java, scope is
determined by the block { } in which a variable is declared.
Types of Scope
Scope Type Description
Class-level scope Variable is accessible throughout the class (all methods, constructors,
(Instance/Static variables) blocks of that class), depending on access modifiers.
Method-level scope (Local Variable is accessible only within the method in which it is declared.
variables)
Variable declared inside { } (such as inside an if, for, or while block) is
Block-level scope
accessible only within that block.
Example illustrating block scope:
public class ScopeDemo {
int x = 100; // class-level (instance) scope
void display() {
int y = 50; // method-level scope
if (y > 0) {
int z = 10; // block-level scope (only inside if-
block)
[Link](x + y + z);
}
// z is NOT accessible here - out of scope
}
Page 13 of 14
BCA — Java Programming Unit I
Key Rule: A variable is only valid within the block { ... } in which it is declared, including any nested blocks
inside it; it ceases to exist once control leaves that block.
2.10 Types of Comments in Java
Comments are non-executable statements used to explain code and improve readability. The compiler
ignores comments during execution. Java supports three types of comments:
Type Syntax Use
Used to comment a single line of
Single-line Comment // comment text
explanation.
Multi-line Comment /* comment text */ Used to comment multiple lines at once.
Documentation Used to generate official documentation
/** comment text */
Comment using the javadoc tool.
Example:
// This is a single-line comment
/* This is a
multi-line comment */
/**
* This is a documentation comment.
* @author Raj
* @version 1.0
*/
public class CommentDemo {
public static void main(String[] args) {
[Link]("Comment demo"); // prints output
}
}
End of Unit I Notes
Page 14 of 14