KEMBAR78
Unit 1 | PDF | Object Oriented Programming | Java Virtual Machine
0% found this document useful (0 votes)
8 views52 pages

Unit 1

alll java program is here

Uploaded by

layer86104
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)
8 views52 pages

Unit 1

alll java program is here

Uploaded by

layer86104
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/ 52

Fundamentals of Object in Java

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:

1. State (Attributes) – Information stored inside the object.

2. Behavior (Methods) – Actions the object can perform.

3. Identity – A unique reference that differentiates it from other objects.

• Example:
Imagine a Car:

o State → color: red, speed: 100 km/h

o Behavior → start(), brake(), accelerate()

2. Difference Between Class and Object

Class Object

Blueprint/template to create objects. Instance created from a class.

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.

Example: class Car {} Example: Car myCar = new Car();

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");

void accelerate(int increment) {

speed += increment;

System.out.println("Speed: " + speed);

public class Main {

public static void main(String[] args) {

Car myCar = new Car(); // Object creation

myCar.color = "Red"; // Setting state

myCar.speed = 0;

myCar.start(); // Calling behavior

myCar.accelerate(50); // Changing state

Output:

Car started
Speed: 50

5. Characteristics of an Object

1. State:

o The set of values of an object’s attributes.

o Example: color = "Blue", speed = 80.

2. Behavior:

o The actions performed by an object.

o Example: start(), stop(), accelerate().

3. Identity:

o Each object has a unique reference in memory.

o Even if two objects have the same state, they are different in memory.

6. Ways to Create Objects in Java

1. Using new keyword (Most common)

2. Student s1 = new Student();

3. Using Class.forName() method

4. Class.forName("Student").newInstance();

5. Using clone() method

o Creates a copy of an existing object.

6. Using Object Deserialization

o Restoring an object from a file or database.

7. Benefits of Using Objects

• Modularity – Code is divided into smaller, independent parts.

• Reusability – Same class can create multiple objects.

• Easier Maintenance – Changing one part of the class affects all its objects.

• Real-world mapping – Closer to human thinking.


8. Diagram

Class: Car

----------------

| color |

| speed |

----------------

| start() |

| accelerate() |

----------------

Object: myCar

----------------

| color = Red |

| speed = 0 |

----------------

| start() |

| accelerate() |

----------------

9. Quick Revision Points

• Object = State + Behavior + Identity.

• Class is just a plan; object is the actual building.

• Multiple objects can be created from the same class.

• Objects are stored in Heap Memory.

• Each object has its own copy of instance variables.

Object-Oriented Programming (OOP): Introduction

1. What is Object-Oriented Programming?


• Definition:
Object-Oriented Programming (OOP) is a programming paradigm where the entire program is
organized around objects rather than just functions or logic.

o Objects represent real-world entities.

o Each object contains data (state) and methods (behavior).

• Java is purely object-oriented (except for primitive data types).

• In OOP, the main focus is on data and operations on data.

2. Why OOP?

Before OOP, programming was done using Procedural Programming (like C language) where:

• Focus was on functions.

• Data and functions were separate.

• Code was difficult to maintain for large projects.

OOP solves these problems by:

• Combining data and methods into a single unit (object).

• Providing data hiding, reusability, and modularity.

3. Key Features of OOP

1. Class

o Blueprint/template for creating objects.

2. Object

o Instance of a class.

3. Encapsulation

o Wrapping data and methods together.

4. Abstraction

o Showing essential features, hiding implementation details.

5. Inheritance

o One class acquiring properties and methods of another.

6. Polymorphism
o Same action behaving differently in different situations.

4. Advantages of OOP

• Modularity: Code is divided into independent objects.

• Reusability: Classes can be reused in other programs.

• Maintainability: Easy to update or fix code.

• Scalability: Suitable for large and complex projects.

• Security: Encapsulation hides sensitive data.

5. OOP vs Procedural Programming

Procedural Programming OOP

Focuses on functions. Focuses on objects.

Data and functions are separate. Data and methods are combined in objects.

Not as secure. More secure (encapsulation).

Less reusability. High reusability.

Example: C Example: Java, C++, Python

6. Example

// Example of OOP in Java

class Student {

String name;

int age;

void displayInfo() {

System.out.println("Name: " + name + ", Age: " + age);

}
public class Main {

public static void main(String[] args) {

Student s1 = new Student(); // Creating object

s1.name = "Rahul";

s1.age = 20;

s1.displayInfo();

Output:

Name: Rahul, Age: 20

7. Real-World Analogy

Think of a Bank Account:

• State → accountNumber, balance.

• Behavior → deposit(), withdraw().

• All related data and actions are grouped inside one object.

8. Diagram

+-----------------------+

| Class: Car |

|-----------------------|

| color, model, speed | <-- State (Attributes)

|-----------------------|

| start(), brake() | <-- Behavior (Methods)

+-----------------------+

+----------------+

| Object: myCar |

| color = Red |
| model = BMW |

| speed = 0 |

+----------------+

9. Quick Revision Points

• OOP organizes programs into classes and objects.

• Improves security, modularity, and reusability.

• Java implements all major OOP principles.

10. Exam Tip

If asked “Explain OOP with examples” —


Write definition, features, advantages, comparison with procedural programming, and a simple Java
program.

1. Object-Oriented Paradigm

Definition

The Object-Oriented Paradigm is a programming approach where:

• The program is organized around objects, not just functions or logic.

• Objects represent real-world entities and contain:

o State (data/attributes)

o Behavior (methods/functions)

o Identity (unique memory reference)

In Java, everything is associated with classes and objects, which makes it a purely object-oriented
language (except for primitive types).

Key Principles of OOP Paradigm

1. Data is given more importance than functions.

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).

4. Code reusability is encouraged using inheritance.

5. Multiple objects can be created from a single class.

OOP Approach vs Procedural Approach

Procedural Programming Object-Oriented Programming

Program is divided into functions. Program is divided into objects.

Data and functions are separate. Data and functions are combined in objects.

Less secure (data can be accessed directly). More secure (encapsulation hides data).

Example: C Example: Java, C++, Python

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

| |

| ---> State + Behavior + Identity

+---> Interaction through methods


Advantages of the OOP Paradigm

• Promotes code reusability.

• Increases security by restricting data access.

• Easier to understand, debug, and maintain.

• Suitable for large, complex applications.

2. Basic Concepts of OOP

Object-Oriented Programming in Java is built on four main pillars and some supporting concepts.

2.1 Main Concepts (Pillars)

1. Class

• Definition: A blueprint/template for creating objects.

• Contains:

o Variables (attributes) → State

o Methods (functions) → Behavior

• Example:

class Car {

String color;

void start() {

System.out.println("Car started");

2. Object

• Definition: An instance of a class.

• Has state, behavior, and identity.

• Created using the new keyword.

• Example:
Car myCar = new Car();

myCar.color = "Red";

myCar.start();

3. Encapsulation

• Definition: Wrapping data and methods together in a single unit.

• Benefit: Protects data by restricting direct access (using private variables + getters/setters).

• Example:

class Student {

private int age;

public void setAge(int a) { age = a; }

public int getAge() { return age; }

4. Abstraction

• Definition: Showing only essential details, hiding internal working.

• 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).

• Benefits: Code reusability and extension.

• Example:
class Vehicle { void start() { } }

class Car extends Vehicle { }

6. Polymorphism

• Definition: Ability to perform a single action in multiple ways.

• Types:

o Compile-time: Method overloading.

o Runtime: Method overriding.

• Example:

class Shape { void draw() { } }

class Circle extends Shape { void draw() { System.out.println("Circle"); } }

2.2 Supporting Concepts

• Message Passing: Objects communicate by sending and receiving messages (method calls).

• Dynamic Binding: The method to be executed is determined at runtime.

• Data Hiding: Keeping internal details hidden using access modifiers.

3. Benefits of OOP

3.1 Key Benefits

1. Modularity: Program is divided into independent, self-contained objects.

2. Reusability: Same class can be reused in different programs.

3. Maintainability: Easy to modify or update code without affecting other parts.

4. Security: Encapsulation hides data from unauthorized access.

5. Scalability: Suitable for small to large projects.

6. Extensibility: Can easily add new features using inheritance and polymorphism.

3.2 Applications of OOP

1. Real-Time Systems
o Examples: Flight control systems, traffic control.

2. Graphical User Interface (GUI) Applications

o Examples: JavaFX, Swing applications.

3. Game Development

o Objects represent characters, enemies, weapons.

4. Simulation and Modeling

o Robotics, weather simulations.

5. Enterprise Applications

o Banking systems, inventory management, CRM.

6. Mobile Applications

o Android apps (Java/Kotlin) follow OOP.

7. Web Applications

o Using Java frameworks like Spring, JSP, Servlets.

Diagram:

[Applications of OOP]

-------------------------

| | |

Real-Time Games Enterprise

Systems GUI Apps Applications

Quick Revision Points

• OOP organizes programs around classes and objects.

• Four main pillars → Encapsulation, Abstraction, Inheritance, Polymorphism.

• Benefits → Reusability, Security, Maintainability.

• Used in games, simulations, enterprise, and mobile apps.

Exam Writing Tip


• Always define the concept first.

• Mention at least 3–5 points.

• Give a real-world example.

• If possible, add a small diagram or code snippet.

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.

2. Main Features of Java

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

Simple Easy to learn, no complex syntax like pointers

Object-Oriented Based on objects and classes

Platform Independent Runs on any OS via JVM

Secured Safe execution, no explicit pointers


Feature Description

Robust Reliable, strong memory management

Portable Runs anywhere without code change

High Performance JIT compiler improves speed

Distributed Networking support

Multi-threaded Multiple tasks simultaneously

Dynamic Classes loaded at runtime

Interpreted Executed by JVM

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!

5. Quick Revision Points


• Java is simple, object-oriented, portable, secure, robust.
• Uses bytecode + JVM for platform independence.
• Supports multi-threading and network programming.
• Memory management is automatic.

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. Types of Java Tokens


Java tokens are mainly divided into five categories:
1. Keywords
• Definition:
Reserved words in Java that have predefined meaning and cannot
be used as identifiers (names for variables, classes, etc.).
• Examples:
int, class, if, else, while, return, static, void, public, private, etc.
• Total Keywords: 67 (in Java 17, includes future reserved words like
goto, const).
Example:
public class Demo {
static int number = 10;
}
Here public, class, and static are keywords.

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

3. Table Summary of Java Tokens


Token Type Description Example

Keywords Reserved words with predefined meaning class, public

Identifiers Names for variables, methods, classes totalMarks

Literals Constant values in code 100, "Java"

Operators Symbols for operations +, ==

Separators Special symbols to separate code ;, {}, ()

4. Example Program Demonstrating All Tokens


public class TokenExample { // Keywords: public, class
public static void main(String[] args) { // Identifiers: TokenExample,
main, args
int age = 25; // int = Keyword, age = Identifier, 25 = Literal
double salary = 50000.5; // double = Keyword, salary = Identifier,
50000.5 = Literal
if (age > 18) { // if = Keyword, > = Operator
System.out.println("Eligible"); // . = Separator
}
}
}

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 {}.

2. Types of Java Statements


Java statements are mainly classified into three broad categories:

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

3. Control Flow Statements


• Definition: Statements that control the flow of execution of the
program.
• Sub-types:
A. Selection Statements
• Used for decision-making.
1. if statement
2. if (age >= 18) {
3. System.out.println("Eligible to vote");
4. }
5. if-else statement
6. if (marks >= 50)
7. System.out.println("Pass");
8. else
9. System.out.println("Fail");
10. Nested if statement
11. if (age > 0) {
12. if (age >= 18)
13. System.out.println("Adult");
14. }
15. if-else-if ladder
16. if (marks >= 90) System.out.println("A");
17. else if (marks >= 75) System.out.println("B");
18. else System.out.println("C");
19. switch statement
20. int day = 3;
21. switch(day) {
22. case 1: System.out.println("Monday"); break;
23. case 2: System.out.println("Tuesday"); break;
24. default: System.out.println("Invalid day");
25. }

B. Iteration (Looping) Statements


• Used to repeat a block of code.
1. for loop
2. for (int i = 1; i <= 5; i++) {
3. System.out.println(i);
4. }
5. while loop
6. int i = 1;
7. while (i <= 5) {
8. System.out.println(i);
9. i++;
10. }
11. do-while loop
12. int i = 1;
13. do {
14. System.out.println(i);
15. i++;
16. } while (i <= 5);
17. for-each loop (used with arrays/collections)
18. int[] nums = {1, 2, 3};
19. for (int n : nums) {
20. System.out.println(n);
21. }

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. }

3. Diagram: Java Statements Classification


Java Statements
|
+-- Expression Statements
| - Assignment
| - Method call
| - Object creation
|
+-- Declaration Statements
| - Variable declaration
| - Constant declaration
|
+-- Control Flow Statements
|
+-- Selection: if, if-else, switch
+-- Iteration: for, while, do-while, for-each
+-- Jump: break, continue, return

4. Example Program with All Types


public class StatementExample {
public static void main(String[] args) {
// Declaration statement
int num = 5;

// 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);
}
}
}

Implementing a Java Program, JVM, Command


Line Arguments, Constants, Variables & Data
Types

1. Implementing a Java Program

Steps to Create and Run a Java Program


Java program development follows these steps:
Step 1: Write the Source Code
• Use a text editor (Notepad, VS Code, IntelliJ) to write .java file.
public class Hello {
public static void main(String[] args) {
System.out.println("Hello Java!");
}
}

Step 2: Save the File


• Save with same name as public class and .java extension.
Example: Hello.java

Step 3: Compile the Source Code


• Use the Java Compiler (javac) to convert source code into
bytecode.
javac Hello.java
• Output: Hello.class file (bytecode).

Step 4: Run the Program


• Use the Java Interpreter (java) to execute bytecode in JVM.
java Hello

Diagram: Java Program Execution


Source Code (.java) --[javac]--> Bytecode (.class) --[JVM]--> Output

2. Java Virtual Machine (JVM)

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).

JVM Architecture Components


1. Class Loader → Loads .class files into JVM.
2. Method Area → Stores class-level data, static variables, method
code.
3. Heap → Stores objects and arrays.
4. Stack → Stores method calls and local variables.
5. Program Counter (PC) Register → Tracks current instruction.
6. Execution Engine → Executes bytecode (interpreter + JIT
compiler).
7. Native Method Interface & Libraries → Connects Java with native
OS libraries.

Diagram: JVM Architecture


+---------------------+
| Class Loader |
+---------------------+
| Method Area |
|---------------------|
| Heap |
|---------------------|
| Stack |
|---------------------|
| PC Register |
+---------------------+
| Execution Engine |
| (Interpreter + JIT)|
+---------------------+
| Native Interfaces |
+---------------------+

3. Command Line Arguments

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);
}
}

6. Data Types in Java

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 |

B. Non-Primitive (Reference) Data Types


• Definition: Types created from classes or arrays, can store
multiple values or objects.
• Examples:
o String
o Arrays
o User-defined classes
o Interfaces

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);
}
}

Quick Revision Points


• Java Program Execution: .java → .class → run in JVM.
• JVM: Executes bytecode, provides platform independence.
• Command Line Arguments: Passed via args[] in main.
• Constants: Declared with final, cannot change.
• Variables: Local, Instance, Static.
• Data Types: Primitive (8 types) + Non-primitive.

Java Basics: Detailed Notes

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.

4. Data Types in Java


Java has two main categories:
A. Primitive Data Types
Type Size Default Value Example

byte 1 byte 0 10

short 2 bytes 0 500

int 4 bytes 0 1000

long 8 bytes 0L 123456L

float 4 bytes 0.0f 3.14f

double 8 bytes 0.0d 3.1416

char 2 bytes '\u0000' 'A'

boolean 1 bit false true

B. Non-Primitive Data Types


• Strings, Arrays, Classes, Interfaces.
• Default value for non-primitive variables = null.

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";

6. Giving Value to Variables


You can assign values in two ways:
A. At Declaration
int age = 20;
B. Later in Program
int age;
age = 20;

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

10. Getting Value of Variables


You can:
• Assign value directly in code.
• Take input from user using Scanner.
Example:
import java.util.Scanner;
class InputExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter your name: ");
String name = sc.nextLine();
System.out.println("Hello, " + name);
}
}

11. Standard Default Values


Java assigns default values to instance variables (not to local variables).
Data Type Default Value

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

Constants Declared with final, cannot change.

Variables Named memory location, must be declared.

Data Types Primitive (8 types) & Non-primitive.

Declaration dataType name = value;

Value Assignment At declaration or later.

Scope Local, Instance, Static.

Symbolic Constants Named constants for better readability.

Type Casting Implicit (safe) & Explicit (possible loss).

Getting Values Direct or user input via Scanner.

Default Values Given only to instance variables.


Operators & Expressions in Java
1. Introduction
In Java, operators are special symbols that perform specific operations
on one, two, or three operands, producing a result.
An expression is a combination of variables, constants, operators, and
method calls that evaluates to a single value.
Example:
int a = 5, b = 3;
int sum = a + b; // '+' is an operator, 'a + b' is an expression

2. Types of Operators in Java


A. Arithmetic Operators
Used for basic mathematical operations.
Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division 5/3 1 (integer division)

% Modulus (Remainder) 5 % 3 2

B. Unary Operators
Work with only one operand.
Operator Description Example Result

Unary plus (positive


+ +a same as a
number)

negative
- Unary minus (negation) -a
value

++a (pre) / a++


++ Increment increases by 1
(post)
Operator Description Example Result

decreases by
-- Decrement --a / a--
1

! Logical NOT !true false

C. Relational Operators
Used for comparison (result is true or false).
Operator Description Example Result

== Equal to 5 == 3 false

!= Not equal to 5 != 3 true

> Greater than 5>3 true

< Less than 5<3 false

>= Greater or equal 5 >= 3 true

<= Less or equal 5 <= 3 false

D. Logical Operators
Used to combine multiple conditions.
Operator Description Example Result

&& Logical AND (a>0 && b>0) true if both true

|| Logical OR (a>0 || b>0) true if at least one true


Operator Description Example Result

! Logical NOT !(a>0) opposite of condition

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

& AND 5&3 1

| OR 5|3 7

^ XOR 5^3 6

~ NOT ~5 -6
Operator Description Example Result

<< Left shift 5 << 1 10

>> Right shift 5 >> 1 2

>>> Unsigned right shift -5 >>> 1 large positive

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

4. Operator Precedence & Associativity


When multiple operators appear in an expression:
1. Precedence decides which is evaluated first.
2. Associativity decides the order when precedence is the same.
Example:
int result = 5 + 2 * 3; // Multiplication before addition → 5 + 6 = 11

5. Quick Revision Table


Category Operators

Arithmetic +, -, *, /, %

Unary +, -, ++, --, !

Relational ==, !=, >, <, >=, <=

Logical &&, ||, !

Assignment =, +=, -=, *=, /=, %=

Bitwise &, |, ^, ~, <<, >>, >>>

Ternary ?:

You might also like