Unit 1
Unit 1
1. Introduction
• Definition:
In Java, an object is a basic unit of Object-Oriented Programming (OOP).
It represents real-world entities like a car, pen, student, or bank account.
Every object has:
• Example:
Imagine a Car:
Class Object
No memory is allocated until an object is created. Memory is allocated when an object is created.
Defined using the class keyword. Created using the new keyword.
3. Syntax
Class Declaration:
class ClassName {
// Attributes (variables)
// Behaviors (methods)
Object Creation:
ClassName obj = new ClassName();
4. Example Program
class Car {
String color;
int speed;
void start() {
System.out.println("Car started");
speed += increment;
myCar.speed = 0;
Output:
Car started
Speed: 50
5. Characteristics of an Object
1. State:
2. Behavior:
3. Identity:
o Even if two objects have the same state, they are different in memory.
4. Class.forName("Student").newInstance();
• Easier Maintenance – Changing one part of the class affects all its objects.
Class: Car
----------------
| color |
| speed |
----------------
| start() |
| accelerate() |
----------------
Object: myCar
----------------
| color = Red |
| speed = 0 |
----------------
| start() |
| accelerate() |
----------------
2. Why OOP?
Before OOP, programming was done using Procedural Programming (like C language) where:
1. Class
2. Object
o Instance of a class.
3. Encapsulation
4. Abstraction
5. Inheritance
6. Polymorphism
o Same action behaving differently in different situations.
4. Advantages of OOP
Data and functions are separate. Data and methods are combined in objects.
6. Example
class Student {
String name;
int age;
void displayInfo() {
}
public class Main {
s1.name = "Rahul";
s1.age = 20;
s1.displayInfo();
Output:
7. Real-World Analogy
• All related data and actions are grouped inside one object.
8. Diagram
+-----------------------+
| Class: Car |
|-----------------------|
|-----------------------|
+-----------------------+
+----------------+
| Object: myCar |
| color = Red |
| model = BMW |
| speed = 0 |
+----------------+
1. Object-Oriented Paradigm
Definition
o State (data/attributes)
o Behavior (methods/functions)
In Java, everything is associated with classes and objects, which makes it a purely object-oriented
language (except for primitive types).
2. Data and methods are bundled together into a single unit called an object.
3. Objects communicate with each other through method calls (message passing).
Data and functions are separate. Data and functions are combined in objects.
Less secure (data can be accessed directly). More secure (encapsulation hides data).
Real-World Example:
• In a bank system,
o Procedural → separate functions for deposit, withdraw, etc., with global data.
o OOP → Account object contains both data (balance, account number) and methods
(deposit(), withdraw()).
Diagram:
[Object-Oriented Paradigm]
+---> Classes
| |
| ---> Objects
| |
Object-Oriented Programming in Java is built on four main pillars and some supporting concepts.
1. Class
• Contains:
• Example:
class Car {
String color;
void start() {
System.out.println("Car started");
2. Object
• Example:
Car myCar = new Car();
myCar.color = "Red";
myCar.start();
3. Encapsulation
• Benefit: Protects data by restricting direct access (using private variables + getters/setters).
• Example:
class Student {
4. Abstraction
• Achieved by:
o Abstract classes
o Interfaces
• Example:
interface Vehicle {
void start();
Here, the user knows the start() method exists but not how it works.
5. Inheritance
• Definition: One class (child) can acquire properties and methods of another class (parent).
• Example:
class Vehicle { void start() { } }
6. Polymorphism
• Types:
• Example:
• Message Passing: Objects communicate by sending and receiving messages (method calls).
3. Benefits of OOP
6. Extensibility: Can easily add new features using inheritance and polymorphism.
1. Real-Time Systems
o Examples: Flight control systems, traffic control.
3. Game Development
5. Enterprise Applications
6. Mobile Applications
7. Web Applications
Diagram:
[Applications of OOP]
-------------------------
| | |
Java Features
1. Introduction
• Java is a high-level, object-oriented, platform-independent
programming language developed by James Gosling at Sun
Microsystems in 1995.
• Java’s popularity comes from its robust features that make it
portable, secure, and reliable for application development.
1. Simple
• Java is easy to learn and has a clean syntax similar to C/C++ but
without complex parts like pointers, operator overloading, or
multiple inheritance.
• Automatic memory management through Garbage Collection.
Example:
You don’t need to manually free memory (like free() in C), Java handles
it automatically.
2. Object-Oriented
• Everything in Java is built around classes and objects.
• Supports the OOP concepts:
o Encapsulation
o Abstraction
o Inheritance
o Polymorphism
Example:
A Car class can have properties (color, model) and methods (start, stop).
3. Platform Independent
• Java code is compiled into bytecode by the Java Compiler, which
can run on any system with a Java Virtual Machine (JVM).
• “Write Once, Run Anywhere” (WORA) principle.
Diagram:
Java Source Code (.java) --[Compiler]--> Bytecode (.class) --[JVM]-->
Machine Code
4. Secured
• Java has:
o No explicit pointers (reduces risk of memory access issues).
o Bytecode verification by JVM.
o Security Manager to define access rules.
• Prevents malicious code execution.
5. Robust
• Java is reliable due to:
o Strong memory management.
o Exception handling (try-catch blocks).
o Type checking at compile-time and runtime.
• Prevents common errors like memory leaks.
6. Architecture Neutral
• Bytecode is the same regardless of the underlying operating
system or hardware.
7. Portable
• Java programs can run on any device with JVM without changes to
the code.
8. High Performance
• Uses Just-In-Time (JIT) compiler to convert bytecode into native
machine code at runtime, improving speed.
9. Distributed
• Java supports networking features (TCP/IP, HTTP).
• Classes in java.net package allow programs to communicate over a
network.
10. Multi-threaded
• Java allows multiple threads to run simultaneously.
• Helps in making interactive and fast applications (e.g., games,
animations).
11. Dynamic
• Java supports dynamic loading of classes at runtime.
• Can adapt to evolving environments.
12. Interpreted
• Java programs are executed by the JVM, which interprets
bytecode line by line (in combination with JIT for performance).
3. Summary Table
Feature Description
4. Example Program
class Demo {
public static void main(String[] args) {
System.out.println("Java is Simple, Secure, and Portable!");
}
}
Output:
Java is Simple, Secure, and Portable!
6. Exam Tip
If asked “Explain Java Features”,
Write definition, list all features with 1–2 line explanations,
and include WORA diagram + a small example.
Java Tokens
1. Introduction
• Definition:
In Java, a token is the smallest unit of a program that is
meaningful to the compiler.
o When we write a Java program, the compiler breaks the
source code into tokens for processing.
• Example:
In this code:
• int age = 20;
The tokens are:
int | age | = | 20 | ;
2. Identifiers
• Definition:
Names given to variables, methods, classes, packages, and
interfaces.
• Rules for Identifiers:
1. Can contain letters, digits, underscore (_), and dollar sign ($).
2. Must not start with a digit.
3. Cannot use keywords as identifiers.
4. Case-sensitive (Count ≠ count).
• Examples:
myVar, sum, DemoClass, _result, $price.
Example:
int marks = 90;
Here marks is an identifier.
3. Literals
• Definition:
Fixed constant values directly used in the program.
• Types of Literals in Java:
1. Integer Literals: 10, -25, 0xFF (hexadecimal), 0b1010 (binary)
2. Floating-point Literals: 3.14, -0.5, 2.0e3 (scientific notation)
3. Character Literals: 'A', '9', '\n' (escape sequence)
4. String Literals: "Hello", "Java123"
5. Boolean Literals: true, false
6. Null Literal: null
Example:
String name = "Ronix";
int age = 21;
boolean active = true;
4. Operators
• Definition:
Symbols that perform specific operations on operands (variables
or values).
• Categories:
1. Arithmetic Operators: +, -, *, /, %
2. Relational Operators: ==, !=, >, <, >=, <=
3. Logical Operators: &&, ||, !
4. Assignment Operators: =, +=, -=, *=, /=
5. Unary Operators: ++, --, +, -
6. Bitwise Operators: &, |, ^, ~, <<, >>, >>>
7. Ternary Operator: ? :
8. Instanceof Operator: instanceof
9. Type Cast Operator: (type)
Example:
int a = 10, b = 5;
System.out.println(a + b); // Output: 15
5. Separators (Punctuators)
• Definition:
Special symbols used to separate code components.
• Examples and Uses:
o ; → Statement terminator
o { } → Block of code
o ( ) → Method call or parameters
o [ ] → Array declaration/access
o , → Separator in variable declarations
o . → Member access operator
Example:
System.out.println("Hello"); // ; ends the statement
Java Statements
1. Introduction
• Definition:
A Java statement is a complete command or instruction that the
Java compiler can execute.
It can be:
o An action (e.g., print something, assign a value)
o A control instruction (e.g., if, loop)
o A declaration (e.g., int a = 5)
• Every statement in Java is usually terminated with a semicolon (;),
except for block and control statements which use {}.
1. Expression Statements
• Definition: Statements that perform actions like assignments,
method calls, object creation, or increment/decrement.
• Examples:
• int x = 5; // Assignment
• x++; // Increment
• System.out.println("Hello"); // Method call
• new Scanner(System.in); // Object creation
2. Declaration Statements
• Definition: Statements that declare variables or constants.
• Examples:
• int number; // Variable declaration
• final double PI = 3.1416; // Constant declaration
• String name = "Java"; // Declaration with initialization
C. Jump Statements
• Used to transfer control from one part of the program to another.
1. break
o Exits from a loop or switch.
2. for (int i = 1; i <= 10; i++) {
3. if (i == 5) break;
4. System.out.println(i);
5. }
6. continue
o Skips the current iteration and goes to the next loop
iteration.
7. for (int i = 1; i <= 5; i++) {
8. if (i == 3) continue;
9. System.out.println(i);
10. }
11. return
o Exits from the current method and optionally returns a
value.
12. int sum(int a, int b) {
13. return a + b;
14. }
// Expression statement
num++;
// Selection statement
if (num > 5) {
System.out.println("Greater than 5");
}
// Iteration statement
for (int i = 1; i <= 3; i++) {
System.out.println("Loop " + i);
}
// Jump statement
for (int i = 1; i <= 5; i++) {
if (i == 4) break;
System.out.println(i);
}
}
}
Definition
• JVM is a part of Java Runtime Environment (JRE) that executes
Java bytecode.
• It is platform-dependent (different for Windows, Mac, Linux) but
Java bytecode is platform-independent.
Key Responsibilities of JVM
1. Loads class files into memory.
2. Verifies bytecode for security.
3. Interprets or compiles bytecode into machine code (JIT Compiler).
4. Manages memory (Garbage Collection).
Definition
• Inputs provided to a Java program during execution from the
terminal.
• Passed to the main() method as a String array (String[] args).
Example
public class CommandExample {
public static void main(String[] args) {
System.out.println("First Arg: " + args[0]);
System.out.println("Second Arg: " + args[1]);
}
}
Execution
javac CommandExample.java
java CommandExample Hello World
Output:
First Arg: Hello
Second Arg: World
Note: Arguments are space-separated.
4. Constants in Java
Definition
• A constant is a variable whose value cannot be changed after
initialization.
• Declared using the final keyword.
Example
final double PI = 3.1416;
Rules
• Must be initialized at the time of declaration.
• Naming convention: UPPERCASE_WITH_UNDERSCORES (e.g.,
MAX_VALUE).
5. Variables in Java
Definition
• A variable is a named memory location used to store data.
Types of Variables
1. Local Variables
o Declared inside a method/block.
o Must be initialized before use.
2. Instance Variables
o Declared inside a class but outside methods.
o Belong to objects (different copy for each object).
3. Static Variables
o Declared with static keyword.
o Shared among all objects of a class.
Example
class Example {
static int staticVar = 10; // static variable
int instanceVar = 5; // instance variable
void show() {
int localVar = 1; // local variable
System.out.println(localVar);
}
}
Classification
Java data types are two types:
A. Primitive Data Types
• Definition: Basic built-in types that store simple values.
• 8 types:
| Type | Size | Example Value |
|----------|----------|---------------|
| byte | 1 byte | 10 |
| short | 2 bytes | 1000 |
| int | 4 bytes | 123456 |
| long | 8 bytes | 123456789L |
| float | 4 bytes | 3.14f |
| double | 8 bytes | 3.1416 |
| char | 2 bytes | 'A' |
| boolean | 1 bit | true/false |
Example Program
public class DataTypeExample {
public static void main(String[] args) {
int age = 20; // int
double pi = 3.1416; // double
char grade = 'A'; // char
boolean isJavaFun = true; // boolean
String name = "Java"; // non-primitive
System.out.println("Name: " + name + ", Age: " + age);
}
}
1. Introduction
• Java is a high-level, object-oriented, platform-independent
programming language.
• Developed by James Gosling at Sun Microsystems in 1995.
• Follows the Write Once, Run Anywhere (WORA) principle.
• Java source code is compiled into bytecode, which runs on the
Java Virtual Machine (JVM).
Key Features:
• Simple, Secure, Portable, Object-Oriented, Robust, Multithreaded,
High Performance.
2. Constants in Java
• Definition: A constant is a fixed value that does not change during
program execution.
• Declared using the final keyword.
Syntax:
final dataType CONSTANT_NAME = value;
Example:
final double PI = 3.1416;
final int MAX_USERS = 100;
Rules:
1. Must be initialized when declared.
2. Name should be in UPPERCASE.
3. Value cannot be reassigned.
3. Variables in Java
• Definition: A variable is a named location in memory used to store
data.
• Java variables must be declared before use.
byte 1 byte 0 10
5. Declaration of Variables
Variables must have:
1. Data Type → defines type of data (int, double, String, etc.).
2. Name → identifier.
3. Value (optional at declaration).
Syntax:
dataType variableName; // Declaration
dataType variableName = value; // Declaration with Initialization
Example:
int age;
String name = "Java";
7. Scope of Variables
Scope = part of the program where the variable is accessible.
Types:
1. Local Variables
o Declared inside a method/block.
o Accessible only within that method/block.
2. Instance Variables
o Declared inside a class but outside methods.
o Each object has its own copy.
3. Static Variables
o Declared with static keyword.
o Shared by all objects.
Example:
class ScopeExample {
static int staticVar = 10; // Static variable
int instanceVar = 5; // Instance variable
void show() {
int localVar = 1; // Local variable
System.out.println(localVar);
}
}
8. Symbolic Constants
• Symbolic constants are named constants.
• Improves code readability and maintainability.
Example:
final int MAX_SPEED = 120;
Instead of:
if(speed > 120) { ... }
We use:
if(speed > MAX_SPEED) { ... }
9. Type Casting
• Definition: Converting one data type to another.
Types:
1. Implicit Casting (Widening)
o Smaller type → Larger type (safe conversion).
o Example:
o int a = 10;
o double b = a; // int to double
2. Explicit Casting (Narrowing)
o Larger type → Smaller type (possible data loss).
o Example:
o double x = 9.78;
o int y = (int) x; // double to int
byte 0
short 0
int 0
long 0L
Data Type Default Value
float 0.0f
double 0.0d
char '\u0000'
boolean false
Object null
Note: Local variables must be initialized before use.
Summary Table
Topic Key Points
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
% Modulus (Remainder) 5 % 3 2
B. Unary Operators
Work with only one operand.
Operator Description Example Result
negative
- Unary minus (negation) -a
value
decreases by
-- Decrement --a / a--
1
C. Relational Operators
Used for comparison (result is true or false).
Operator Description Example Result
== Equal to 5 == 3 false
D. Logical Operators
Used to combine multiple conditions.
Operator Description Example Result
E. Assignment Operators
Assign values to variables (can also combine with arithmetic).
Operator Example Equivalent to
= a=5 a is 5
+= a += 3 a=a+3
-= a -= 3 a=a-3
*= a *= 3 a=a*3
/= a /= 3 a=a/3
%= a %= 3 a=a%3
F. Bitwise Operators
Work at the binary (bit) level.
Operator Description Example Result
| OR 5|3 7
^ XOR 5^3 6
~ NOT ~5 -6
Operator Description Example Result
G. Ternary Operator
Short form for if-else statement.
Syntax:
variable = (condition) ? value_if_true : value_if_false;
Example:
int max = (a > b) ? a : b;
3. Expressions
• Arithmetic expression: a + b * c
• Relational expression: a > b
• Logical expression: (a > b) && (c < d)
• Assignment expression: x += 5
Arithmetic +, -, *, /, %
Ternary ?: