History, Features of Java, C++ vs Java & OOPs Concepts
Overview: In Java, a class can extend one class and implement several interfaces.
Introduction to Java
- Java is a high-level, class-based, object-oriented, and platform-independent programming language.
History of Java
- Java was developed by James Gosling (known as the Father of Java) and his team (Mike Sheridan and Patrick Naughton), collectively called…
- Original Goal (1991): The Green Team started the Green Project to create a small, reliable, and portable language for consumer electronic…
- Why “Oak”? James Gosling initially named the language Greentalk (with
.gtextension) and later renamed it Oak after an oak… - Why renamed to “Java” (1995)? “Oak” was already a registered trademark of Oak Technologies.
- Shift to the Internet (1995): With the rise of the World Wide Web, Sun Microsystems realized that the internet needed a portable and secure language that…
Features of Java (Java Buzzwords)
- The creators of Java published a whitepaper listing the core design goals of the language, famously called Java Buzzwords.
- Simple: Java is easy to learn because its syntax is clean and based on C++.
- Object-Oriented: In Java, everything is modeled as an Object that combines data (fields) and behavior (methods).
- Platform Independent: Unlike C/C++, which compile into OS-specific machine code (
.exe), Java compiles into intermediate Bytecode (.class),… - Secured: Java is ideal for networked environments because:
- It has no explicit pointers (preventing unauthorized memory access).
- Programs run inside a virtual JVM Sandbox.
- A Bytecode Verifier checks code for illegal access before execution.
View diagram · Figure 1.1: Core Features of Java (The Java Buzzwords)
C++ vs Java (Detailed Comparison)
- This is one of the most frequently asked questions in Unit 1 of DAVV BCA exams.
- 1. Platform Dependency: Platform Dependent (compiles directly into OS-specific machine code).
- 2. Programming Paradigm: Both Procedural and Object-Oriented (can write
main()outside a class). - 3. Pointers: Strongly supports explicit Pointers (
*ptr,&x) and pointer arithmetic. - 4. Memory Management: Manual memory allocation and deallocation using
newanddelete. - 5. Multiple Inheritance: Supports multiple inheritance directly using classes (causes the Diamond Problem).
- 6. Operator Overloading: Allows programmers to overload operators (
+,-,<<).
OOPs Concepts in Java (The 4 Pillars + Core Building Blocks)
- Object-Oriented Programming (OOP) is a programming methodology that organizes software design around real-world objects and data rather…
- A. Basic Building Blocks: Class and Object: Object: Any real-world entity that has State (attributes/data) and Behavior (actions/methods).
- Example: A
Studentobject has State (rollNo = 101,name = "Aarav") and Behavior (attendClass(),giveExam()). - Class: A logical blueprint, template, or prototype from which individual objects are created.
- Example: An architect’s building map is a Class, whereas the actual houses built using that map are Objects.
- B. The 4 Pillars of OOPs: Encapsulation brings state and behaviour together and abstraction presents essential operations.
- 1. Encapsulation (Data Wrapping & Hiding): Definition: Wrapping up data (variables) and code acting on the data (methods) together into a single unit (a
class), while… - Real-Life Example: A medical capsule wraps several medicines inside one shell.
View diagram · Figure 1.2: The 4 Pillars of Object-Oriented Programming (OOP)
How Java Works: JVM Concepts, JDK vs JRE & Java Platform Overview
Overview: The compiler turns a source file into bytecode.
How Java Works (Two-Stage Execution Model)
- In traditional languages like C or C++, the compiler translates source code directly into native machine code (
.exe), which only runs on the… - Step 1: Compilation (javac): You write your program in a plain text file with a
.javaextension (e.g.,Student.java). - The Java Compiler (
javac) checks your code for syntax errors and compiles it into an intermediate, platform-independent… - What is Bytecode? Bytecode is a highly optimized set of instructions designed to be executed by the Java Virtual Machine (JVM).
- Step 2: Execution / Interpretation (java / JVM): When you run the program using the
java Studentcommand, the Java Virtual Machine (JVM) installed on that computer loads the… - Using its Interpreter and JIT (Just-In-Time) Compiler, the JVM translates the universal Bytecode into native machine instructions…
- Important Viva Fact: Java is platform-independent, but the JVM is platform-dependent! (Windows has a different JVM installer than…
View diagram · Figure 1.3: How Java Achieves Platform Independence (WORA)
Java Virtual Machine (JVM) Architecture & Concepts
- The JVM (Java Virtual Machine) is an abstract computing machine (a software-based virtual computer) that provides the runtime environment in…
- 1. Class Loader Subsystem: Whenever you run a Java program, the Class Loader is responsible for finding and loading the required
.classfiles from the… - Loading: Reads the
.classfile and stores its binary data in the Method Area. - Linking (Verification, Preparation, Resolution): The Bytecode Verifier checks whether the generated bytecode is valid and does not violate security rules (e.g., no…
- Initialization: Assigns initial values to
staticvariables and executesstaticblocks. - 2. JVM Runtime Data Areas (Memory Areas): The JVM divides the memory it gets from the OS into 5 regions:
- Method Area: Stores class-level data such as class names, method code, static variables, and constant pool.
- Heap Area: The runtime data area where all Objects (
new) and Arrays are allocated memory.
View diagram · Figure 1.4: Internal Architecture of the Java Virtual Machine (JVM)
Java Platform Overview: JDK, JRE, and JVM
- What is the “Java Platform”?
- Formula: JDK = JRE + Development Tools (
javac,javadoc,jdb,jar) - Formula: JRE = JVM + Core Class Libraries (
rt.jar/java.base) - Full Form: Java Virtual Machine
- Primary Purpose: Executes
.classbytecode and manages memory/GC. - Who Needs It?: Internal engine inside JRE.
- Components: Class Loader + Memory Areas + Execution Engine (JIT & GC).
View diagram · Figure 1.5: Relationship Between JDK, JRE, and JVM
Editions of the Java Platform
- To serve different types of devices and applications, Oracle provides four editions of the Java Platform:
- Java SE (Standard Edition / Core Java):
- The foundation of Java.
- Java EE / Jakarta EE (Enterprise Edition / Advanced Java):
- Built on top of Java SE for large-scale, multi-tiered, secure enterprise and web applications (Servlets, JSP, EJB, Web Services used by…
- Java ME (Micro Edition):
- A lightweight subset of Java SE designed for small, resource-constrained embedded devices like smart cards, IoT sensors, TV set-top boxes,…
- JavaFX:
Java Program Structure, Compilation & Execution, PATH and CLASSPATH
Overview: If javac cannot be found, the shell may need the JDK’s bin directory on PATH.
Structure of a Java Program
- A well-organized Java source file (
.java) follows a standard structure divided into 6 sections. - Documentation Section (Suggested):
- Single-line comment:
// This is a single-line comment - Multi-line comment:
/* This spans multiple lines */ - Documentation comment:
/** Used by javadoc tool to generate HTML API docs */ - Package Statement (Optional):
- Import Statements (Optional):
- Note: The
java.langpackage (which containsString,System,Math,Object,Thread) is imported automatically by…
View diagram · Figure 1.6: Standard Structure of a Java Program
A Simple Java Program & Detailed Breakdown
- Let us write a simple Java program, save it as
HelloBCA.java, and understand every single word in it: - Meaning of Every Keyword in public static void main(String[] args): This is the #1 Viva and Short-Note Question in BCA Java exams:
public(Access Specifier):static(Keyword):void(Return Type):main(Method Name):String[] args(Command-Line Arguments):- Meaning of System.out.println(…):
System: A predefined final class inside thejava.langpackage (note the capitalS).
Compilation and Execution of a Java Program
- Golden Rule of Naming a .java File: If a class is declared as
public(e.g.,public class HelloBCA), the source file MUST be saved with the exact same name,… - Why?
- Step-by-Step Terminal Commands: Save the File: Save the code in a file named
HelloBCA.java. - Open Command Prompt / Terminal: Navigate to the folder where
HelloBCA.javais saved. - Compile the Program (
javac): - The Java compiler (
javac) checks for syntax errors. - Execute the Program (
java): - Notice: Do not write
.classor.javawith thejavacommand!
The Concept of PATH and CLASSPATH
- When working with Java from the command line, two environment variables are crucial:
PATHandCLASSPATH. - 1. What is PATH?: Purpose:
PATHis an Operating System (OS) environment variable that tells the OS (Windows/Linux) where to find **executable… - What happens if
PATHis not set? - How to set
PATH( points to JDK’sbindirectory): - 2. What is CLASSPATH?: Purpose:
CLASSPATHis a Java-specific environment variable used by the Java Compiler (javac) and the JVM (java) to… - What happens if
CLASSPATHis not set properly? - How to set
CLASSPATH(points to directories containing.classor.jarfiles):
Comparison: PATH vs CLASSPATH
- 1. Used By: Used by the Operating System (Windows, Linux, macOS).
- 2. What It Locates: Locates native JDK executable tools (
.exefiles) such asjavac.exe,java.exe,javadoc.exe,… - 3. Target Directory: Points to the
jdk\binfolder. - 4. Error If Missing:
'javac' is not recognized as an internal or external command. - 5. Can Be Overridden via CLI?: Cannot be overridden by a
javaflag.
Primitive Data Types, Variables, Constants, Operators & Expressions
Overview: With integer operands, 5 / 2 produces 2, which remains 2.0 if assigned afterwards to a double.
Data Types in Java
- Java is a statically and strongly typed language, which means every variable must have its data type declared before it is used, and the…
- Primitive Data Types (8 built-in types): Store simple raw values directly in memory (
byte,short,int,long,float,double,char,boolean). - Non-Primitive / Reference Data Types: Store memory references (addresses) to objects in the Heap (
String,Arrays,Classes,Interfaces). - Primitive Data Types (8 Types) Integers: byte (1B), short (2B), int (4B), long (8B)
- Non-Primitive (Reference) Types Classes: String, Scanner, Student
View diagram · Figure 1.7: Classification of Data Types in Java
The 8 Primitive Data Types in Detail
- Unlike C/C++, the size of primitive data types in Java is fixed across all operating systems and hardware architectures.
byte: Integershort: Integerint: Integerlong: Integerfloat: Floating-Pointdouble: Floating-Point- Why does
chartake 2 Bytes in Java (instead of 1 Byte like C/C++)?
Variables and Constants in Java
- A. Variables: A variable is a named memory location whose value can change during program execution.
- Syntax:
dataType variableName = value;(e.g.,int marks = 85;) - Where Declared?: Inside a method, constructor, or
{}block. - Memory Location: Stack memory.
- Default Value?: No default value! Must be initialized before use.
- Example:
int sum = 0;insidecalculate() - B. Constants (final Keyword): A constant is a variable whose value is fixed and cannot be modified once assigned.
Type Conversion and Type Casting
- Converting a value of one primitive data type into another is done in two ways:
- Implicit Type Conversion (Widening / Automatic):
- Order:
byte→short→int→long→float→double - Explicit Type Casting (Narrowing):
Operators and Expressions in Java
- An operator is a symbol that performs a specific operation on one, two, or three operands.
- 1. Arithmetic:
+,-,*,/(Quotient),%(Remainder) - 2. Unary:
++(Increment),--(Decrement),+,-,!(NOT) - 3. Assignment:
=,+=,-=,*=,/=,%= - 4. Relational (Comparison):
==,!=,>,<,>=,<= - 5. Logical (Short-Circuit):
&&(Logical AND), `\ - 6. Ternary (Conditional): `condition ?
Control Statements: Branching, Looping, Jumping & Labeled Statements
Overview: A for loop suits checking each mark in an array.
What are Control Statements?
- By default, the JVM executes statements sequentially from top to bottom.
- 1. Branching (Decision Making) if, if-else, if-else-if ladder, nested if, switch-case
- 2. Looping (Iteration) for loop, enhanced for-each loop, while loop, do-while loop
- 3. Jumping (Transfer of Control) break, continue, return, and Labeled break / continue
View diagram · Figure 1.8: Classification of Control Statements in Java
Branching (Decision-Making) Statements
- Branching statements evaluate a condition and choose which block of code to execute.
- A. The if-else Family: Simple
if: Executes a block only if the boolean condition istrue. if-else: Executes theifblock whentrue, otherwise executes theelseblock.if-else-ifLadder: Tests multiple conditions sequentially from top to bottom (ideal for grading systems).- Nested
if: Anifstatement inside anotherifstatement. - B. The switch Statement: A
switchstatement is a cleaner multi-way branch statement that compares the value of a single expression against multiple… - Data types allowed in Java
switch:byte,short,int,char,String(added in Java 7), andenum. - Why use
breakinsideswitch?
Looping (Iterative) Statements
- Loops allow a block of code to execute repeatedly as long as a specified boolean condition remains
true. - 1. for Loop (Entry-Controlled): Used when the exact number of iterations is known in advance.
- 2. Enhanced for Loop (for-each Loop): Introduced in Java 5 specifically for traversing Arrays and Collections without needing an index variable.
- 3. while Loop (Entry-Controlled): Used when the number of iterations is not known beforehand.
- 4. do-while Loop (Exit-Controlled): The loop body executes first, and the condition is checked at the end of each iteration.
- Type of Loop: Entry-Controlled Loop (condition checked at the top).
- Minimum Executions: 0 times (if condition is initially
false). - Semicolon at End: No semicolon after
while(condition).
Jumping Statements (break, continue, return)
- Jumping statements transfer control unconditionally from one part of the program to another.
breakStatement:continueStatement:returnStatement:
Labeled Statements in Java (Java’s Safe Alternative to goto)
- C and C++ have the
gotostatement, which can jump anywhere in a program and create unreadable “spaghetti code”. - Why Do We Need Labeled Statements?: Normally, an unlabeled
breakorcontinueonly affects the innermost loop in which it is written. - Output: Notice the difference:
-
- If we had written normal
break;, it would only exit thecolloop and continue withrow = 3.
- If we had written normal
-
- Because we wrote
break outerLoop;, Java immediately terminated both the inner and outer loops!
- Because we wrote
-
- Similarly,
continue outerLoop;skips the rest of the inner loop and jumps directly to the next iteration ofouterLoop.
- Similarly,