Introduction to Java Programming
✅ What You'll Learn:
- What Java is and its features
- Java history and evolution
- How Java works (JVM, JRE, JDK)
- Basic structure of a Java program
- Compiling and running Java
- Basic syntax and data types
🔹 1. What is Java?
Java is a high-level, object-oriented, platform-independent programming language developed by Sun Microsystems (now owned by Oracle). It was released in 1995.
It is used for:
- Web applications
- Desktop apps
- Mobile apps (especially Android)
- Enterprise systems
- Game development
🔹 2. Features of Java (also called Java buzzwords)
| Feature | Description |
|---|---|
| Simple | Easy to learn if you know C/C++ |
| Object-Oriented | Everything in Java is an object |
| Platform-Independent | Write once, run anywhere (thanks to the JVM) |
| Secure | Java has built-in security features like bytecode verification |
| Robust | Handles errors using exception handling and has strong memory management |
| Multithreaded | Can perform multiple tasks at once |
| Architecture-Neutral | Java code runs the same on all hardware |
| Interpreted | Compiled to bytecode, then interpreted/executed by the JVM |
| High Performance | Just-In-Time (JIT) compilers improve performance |
| Distributed | Has built-in support for networking |
| Dynamic | Java can load classes at runtime |
🔹 3. Java Architecture
🌐 JVM, JRE, and JDK
| Term | Meaning |
|---|---|
| JVM (Java Virtual Machine) | Executes Java bytecode; makes Java platform-independent |
| JRE (Java Runtime Environment) | Contains JVM + libraries required to run Java programs |
| JDK (Java Development Kit) | Contains JRE + development tools (compiler, debugger) |
➡️ You write code → compile it → get bytecode → run it with JVM
🔹 4. Basic Java Program Structure
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Explanation:
public class HelloWorld: Java classmain(): Entry point of a Java programSystem.out.println: Prints to console
🔹 5. Compiling and Running Java
✅ Steps:
- Save your code as
HelloWorld.java - Compile:
javac HelloWorld.java
3. Run:
java HelloWorld
🔹 6. Java Syntax Basics
- Case-sensitive
- File name must match the public class name
- Statements end with
; - Blocks use
{}
🔹 7. Data Types in Java
🧾 Primitive Data Types:
| Type | Size | Example |
|---|---|---|
int |
4 bytes | int x = 5; |
float |
4 bytes | float f = 5.6f; |
double |
8 bytes | double d = 5.99; |
char |
2 bytes | char c = 'A'; |
boolean |
1 bit | boolean b = true; |
Also:
byte,short,long
Bytecode in Java
- it's a key concept that makes Java platform-independent and secure.
💡 What is Bytecode in Java?
Bytecode is a set of instructions that the Java compiler (javac) generates after compiling your .java file.
🟢 It’s not machine code, but an intermediate representation understood by the Java Virtual Machine (JVM).
🔄 Flow from Source Code to Execution:
Java Source Code (.java)
↓ [Compiled by javac]
Java Bytecode (.class)
↓ [Executed by JVM]
Machine Code (CPU Instructions)
✅ Key Characteristics of Bytecode:
| Feature | Description |
|---|---|
| Platform-Independent | The same .class file can run on any OS with a JVM (Windows, Linux, Mac, etc.) |
| Portable | Bytecode is compact and designed to travel over networks |
| Secure | JVM checks the bytecode for security before running it |
| Efficient | JVM can optimize bytecode using a JIT (Just-In-Time) compiler for better performance |
📁 Example:
Let's say you have a simple Java file:
HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello Java!");
}
}
When you compile it:
javac HelloWorld.java
It produces a file:
HelloWorld.class
That .class file contains bytecode, like this (if viewed in a bytecode viewer):
0: getstatic #2 // Field java/lang/System.out:Ljava/io/PrintStream;
3: ldc #3 // String Hello Java!
5: invokevirtual #4 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
8: return
This is what the JVM understands and executes.
🔍 Tools to See Bytecode:
javapis a built-in Java tool:
bash
javap -c HelloWorld
Shows the compiled bytecode instructions.
📦 Summary
- Bytecode is .class file content created by the
javaccompiler. - It allows Java to be Write Once, Run Anywhere.
- JVM converts bytecode into machine code for execution.
- JVMs exist for all platforms, making bytecode universally runnable.
Key Features of Java
🌟 Features of Java (Java Buzzwords)
| Feature | Description |
|---|---|
| 1. Simple | Easy to learn, especially if you know C/C++; removes complex features like pointers. |
| 2. Object-Oriented | Everything in Java is part of a class or object; supports concepts like inheritance, polymorphism, encapsulation, and abstraction. |
| 3. Platform-Independent | Java code is compiled into bytecode which runs on any platform via the JVM (Write Once, Run Anywhere). |
| 4. Secure | Java has a security manager, bytecode verification, and no direct memory access (no pointers). |
| 5. Robust | Strong memory management, type checking, and exception handling reduce crashes and bugs. |
| 6. Multithreaded | Built-in support for multithreading helps in developing high-performance concurrent applications. |
| 7. Architecture-Neutral | Bytecode is not dependent on processor architecture — runs on any machine with JVM. |
| 8. Portable | Java programs can be easily moved from one system to another without changes. |
| 9. High Performance | Java is faster than traditional interpreted languages; JIT (Just-In-Time compiler) boosts speed. |
| 10. Distributed | Java provides built-in libraries for networking and building distributed applications (like RMI, sockets). |
| 11. Dynamic | Java supports runtime loading of classes, and linking is done dynamically. |
🧠 Easy Way to Remember — "SOP RAM SHPDD":
Simple
Object-Oriented
Platform-Independent
Robust
Architecture-Neutral
Multithreaded
Secure
High Performance
Portable
Distributed
Dynamic
✅ Example-Based Understanding:
- Platform Independent: Write code on Windows → Compile → Run it on Linux or Mac with JVM
- Robust: Try dividing by 0? Java will throw an
ArithmeticException, preventing a crash - Multithreaded: Java can run multiple threads (like downloading and playing music) simultaneously
Object-Oriented Programming (OOP) concepts in Java
🔷 What is Object-Oriented Programming?
OOP is a programming paradigm based on the concept of "objects". These objects contain data (fields/attributes) and code (methods/behaviors).
Java is a pure object-oriented language (except for primitive types).
✅ Four Pillars of OOP in Java
| Concept | Meaning | Example Keywords |
|---|---|---|
| Encapsulation | Hiding internal data using access modifiers | private, public, get/set |
| Abstraction | Hiding complex implementation and showing only essential details | abstract, interface |
| Inheritance | Acquiring properties from another class | extends, super |
| Polymorphism | One thing with many forms (method overloading/overriding) | @Override, same method name |
Let’s break these down with explanations and examples 👇
🔸 1. Encapsulation — Data Hiding
- Bundling data and methods into a single unit (class)
- Use
privatefields andpublicgetter/setter methods to control access
✅ Example:
class Person {
private String name; // data is hidden
public String getName() { // controlled access
return name;
}
public void setName(String name) {
this.name = name;
}
}
📌 Why?
- Protects data from unauthorized access
- Helps in maintaining control over fields
🔸 2. Abstraction — Hiding Implementation Details
- Focus on what the object does, not how it does it.
-
Achieved using:
-
Abstract classes (with abstract methods)
- Interfaces (pure abstraction)
✅ Example (Using Interface):
interface Animal {
void makeSound(); // abstract method
}
class Dog implements Animal {
public void makeSound() {
System.out.println("Bark");
}
}
📌 Why?
- Simplifies complex systems
- Improves modularity and reusability
🔸 3. Inheritance — "Is-A" Relationship
- One class inherits fields and methods from another
- Promotes code reusability
✅ Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Dog barks");
}
}
📌 Why?
- Reduces code duplication
- Enables polymorphism
🔸 4. Polymorphism — Many Forms
Two types:
- Compile-time (Static): Method Overloading
- Run-time (Dynamic): Method Overriding
✅ Method Overloading (same method name, different parameters)
class MathUtils {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
✅ Method Overriding (subclass changes parent class method)
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
📌 Why?
- Flexibility in method behavior
- Supports dynamic binding at runtime
🔹 Additional OOP Terms (Java-Specific)
| Term | Description |
|---|---|
| Class | Blueprint for creating objects |
| Object | Instance of a class |
| Constructor | Special method to initialize objects |
| this | Refers to the current object |
| super | Refers to the parent class |
📘 Summary Diagram (Pillars of OOP):
Object-Oriented Programming
/ | \
Encapsulation Abstraction
| |
[private] [abstract/interface]
\ /
Inheritance
|
Polymorphism
Java Development Kit (JDK)
💻 What is JDK (Java Development Kit)?
The JDK is a software development kit used to develop, compile, debug, and run Java programs.
✅ It includes:
- JRE (Java Runtime Environment)
- Development tools (like
javac,java,javadoc,javap) - Libraries and APIs
🔁 Relationship Between JDK, JRE, and JVM:
┌────────────────────────────────────┐
│ JDK │
│ ┌────────────┐ ┌──────────────┐ │
│ │ JRE │ │ Dev Tools │ │
│ │ ┌──────┐ │ │ (javac, etc.)│ │
│ │ │ JVM │ │ └──────────────┘ │
│ └────────────┘ │
└────────────────────────────────────┘
📦 Components of JDK
| Component | Description |
|---|---|
| javac | Java compiler — compiles .java files into .class bytecode |
| java | JVM launcher — runs .class files |
| javadoc | Tool to generate API documentation |
| javap | Disassembler to view bytecode |
| jshell | REPL tool (Java 9+) for trying Java interactively |
| jar | Used to bundle multiple class files into a JAR (Java Archive) |
🖥️ How to Use the JDK (Typical Workflow):
- Write Code in a
.javafile:
java
public class Hello {
public static void main(String[] args) {
System.out.println("Hello Java");
}
}
- Compile with JDK's
javactool:
bash
javac Hello.java
- Run with JDK's
javatool:
bash
java Hello
🆚 JDK vs JRE vs JVM
| Feature | JDK | JRE | JVM |
|---|---|---|---|
| Full form | Java Development Kit | Java Runtime Environment | Java Virtual Machine |
| Contains | JRE + development tools | JVM + libraries | Execution engine only |
| Used for | Writing and running code | Running code only | Interpreting bytecode |
| Developer needs | ✅ Yes | ❌ No (runtime only) | 🚀 Internal engine |
🔢 Versions and Vendors
- Oracle JDK
- OpenJDK (free and open source)
- Other vendors: Amazon Corretto, Azul Zulu, etc.
You can download the latest JDK from Oracle or use OpenJDK via package managers.
📝 Summary
- JDK = Java Development Kit
- It contains everything needed to develop Java apps
- It includes the compiler, JRE, JVM, tools, and APIs
- It is essential for Java developers
Lexical Issues
- It is important because it's the first step in Java compilation — where the code is broken down into meaningful pieces.
🧠 What are Lexical Issues in Java?
Lexical issues refer to the rules and problems related to the structure of the smallest units of code, called tokens.
A lexeme is a sequence of characters that forms a token. A token is a meaningful unit like a keyword, identifier, literal, or symbol.
✅ Examples of tokens:
- Keywords:
if,while,class - Identifiers:
main,x,System - Literals:
10,"Hello",true - Operators:
+,-,== - Separators:
;,{},()
🔍 Common Lexical Elements in Java
| Element | Description | Example |
|---|---|---|
| Keywords | Reserved words in Java | class, public, return |
| Identifiers | Names given to variables, methods, classes | myVar, sum, Main |
| Literals | Constant values | 42, 3.14, "Java" |
| Operators | Symbols for operations | +, -, *, == |
| Separators | Symbols that separate blocks | ;, {}, () |
| Comments | Non-executing notes for programmers | //, /* */ |
| Whitespace | Spaces, tabs, and newlines used to separate tokens | (e.g., space between int and x) |
⚠️ Common Lexical Errors
Lexical issues occur when Java's lexer (lexical analyzer) can't understand a part of the code.
| Error Type | Description | Example |
|---|---|---|
| Invalid Identifier | Starts with number or has special char | int 2name; ❌ |
| Unterminated String | A string without closing quotes | "Hello ❌ |
| Illegal Character | Unknown symbol in code | int $x = 5; (valid in some cases, but $ often discouraged) |
| Unrecognized Token | Unexpected character sequence | int @value; ❌ |
🧱 Compilation Phases (Where Lexical Analysis Happens)
- Lexical Analysis (deals with tokens) → Lexer
- Syntax Analysis (deals with grammar rules) → Parser
- Semantic Analysis (deals with meaning and type checks)
So, lexical issues = problems in step 1, before the code even reaches syntax checking.
✅ Summary
- Lexical issues are errors related to Java tokens
- Java breaks code into keywords, identifiers, literals, operators, etc.
- If tokens are malformed or invalid, you'll get lexical errors
- These are caught by the compiler in the very first stage