0% found this document useful (0 votes)
4 views13 pages

Java_Unit_1 (1)

The document provides an overview of Java, highlighting its key features such as platform independence, object-oriented design, and robust security. It covers the history of Java, the architecture of the Java Virtual Machine (JVM), and fundamental concepts like classes, objects, constructors, and OOP principles including encapsulation and inheritance. Additionally, it explains static variables and methods, the use of the 'this' keyword, and includes examples to illustrate these concepts.

Uploaded by

mayankit2023
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)
4 views13 pages

Java_Unit_1 (1)

The document provides an overview of Java, highlighting its key features such as platform independence, object-oriented design, and robust security. It covers the history of Java, the architecture of the Java Virtual Machine (JVM), and fundamental concepts like classes, objects, constructors, and OOP principles including encapsulation and inheritance. Additionally, it explains static variables and methods, the use of the 'this' keyword, and includes examples to illustrate these concepts.

Uploaded by

mayankit2023
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/ 13

UNIT-I

Introduction: Why Java?


Key Reasons to Choose Java:

Platform Independence
Java code is compiled into bytecode, which operates on the Java Virtual Machine (JVM).

“Write Once, Run Anywhere” (WORA) – Java programs can be executed on any device equipped
with a JVM.

Object-Oriented
Encourages modular, flexible, and reusable code.
Everything in Java (except primitives) is treated as an object.
Robust and Secure
Features strong memory management, exception handling, and garbage collection.
Offers built-in security features such as bytecode verification and runtime security
policies.
Simple and Familiar
The syntax is akin to C/C++, while eliminating complex features like pointers and multiple
inheritance.
Multithreaded
Java natively supports multithreaded programming, which is beneficial for gaming,
animation, and real-time applications.
Rich API and Libraries
Provides a vast standard library that encompasses everything from networking to data
structures.
Dynamic and Distributed
Crafted for use in the distributed environment of the internet, supporting remote
method invocation (RMI) and dynamic class loading.

History of Java
Early 1990s – The Birth of Java

Java was conceived by James Gosling and his team at Sun Microsystems in 1991, originally named the “Green
Project.” The first version was aimed at embedded systems for consumer electronics like set-top boxes and
televisions.

1996 – Java 1.0

Java was officially launched as Java 1.0 in 1995, marketed as a tool for crafting interactive
web content, with applets being particularly popular.

Evolution of Java Versions (Highlights)

Java 1.2 (1998) – Introduced the Swing toolkit and Collections Framework.
Java 5 (2004) – Added generics, enhanced for-loop, enums, and autoboxing.
Java 8 (2014) – Major update featuring Lambda expressions, Streams API, and a new
Date/Time API.
Java 11 (2018) – LTS version; removed Applet, added var, and introduced HTTP Client API.
Java 17 (2021) – LTS version; introduced sealed classes and pattern matching.
Java 21 (2023) – The latest LTS version with performance enhancements and new
features.

Java Virtual Machine (JVM)


What is JVM?

The Java Virtual Machine (JVM) is an abstract computing machine that enables a computer to
execute Java programs. It converts compiled bytecode (.class files) into machine code for
execution, ensuring Java's platform independence.

Role of JVM:

Loads the Class: The Class Loader subsystem imports .class files (bytecode) into the JVM.
Verifies the Bytecode: Ensures that the code is valid, secure, and complies with Java’s
security model.
Executes the Bytecode: Utilizes an interpreter or JIT (Just-In-Time) compiler to translate
bytecode into native machine code.
Memory Management: Allocates memory and manages Garbage Collection automatically.
Security Management: Enforces access restrictions and prevents unauthorized actions
through the Security Manager and Bytecode Verifier.

JVM Architecture (Components):

1. Class Loader: Imports class files into memory.


2. Method Area: Stores class structures such as metadata, method data, and runtime
constants.
3. Heap: The runtime data area for object allocation.
4. Stack: Holds local variables, operand stacks, and partial results.
5. PC Register: Contains the address of the currently executing JVM instruction.
6. Execution Engine: Executes bytecode using either an interpreter or JIT compiler.
7. Native Method Interface: Enables calls to native (non-Java) code like C/C++.
8. Native Method Libraries: Libraries for native functions.

Execution Flow:

1. Java file → .java


2. Compiled using javac → .class file (Bytecode)
3. .class file provided to JVM
4. JVM loads, verifies, and executes using interpreter or JIT

Note: “The JVM is the heart of Java’s cross-platform capabilities, allowing Java programs to
run in a controlled and secure manner.”

Important Points:

JVM is not platform-independent; however, the bytecode is.


Various JVMs are designed for different operating systems.
JVM is part of the Java Runtime Environment (JRE).

What is a Class?
1. A class in Java serves as a user-defined data type, encapsulating data (fields) and
behaviors (methods) into a single unit. Think of it as a template or blueprint for creating
individual objects.
2. A class outlines the structure and behavior of future objects.
3. No memory is allocated upon defining a class; memory is reserved when objects are
instantiated.

class ClassName {
// Fields (Instance Variables)
// Methods
}

class Car {
String model;
int year;
void displayInfo() {
System.out.println("Model: " + model + ", Year: " + year);
}
}

What is an Object?
An object is a runtime instance of a class, representing a specific implementation of the
class's structure. When a class is instantiated, an object is created with its unique copy of
instance variables and access to class methods.

Creating Objects Syntax:

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

Each Object:

1. Occupies memory.
2. Has its own identity and state.

Accessing Fields/Methods Syntax:

myCar.model = "Tesla";
myCar.year = 2023;
myCar.displayInfo();

Instance Variables

Instance variables are non-static fields declared within a class but outside any method,
constructor, or block. Each object (instance) of the class receives its own separate copy
of these variables.

Key Characteristics:

1. Memory is allocated when an object is instantiated.


2. Their values are specific to the object — changes made by one object do not impact
others.
3. Can have access modifiers like private, public, or protected.

Syntax

class Student {
String name; // instance variable
int rollNumber; // instance variable
}

Instance Methods

Instance methods are non-static methods that operate on instance variables of the class.
They require an object for invocation and can directly access all non-static members.

Key Characteristics:

1. Can read/write instance variables.


2. Can call other instance methods directly.
3. Cannot be invoked without an object.

Syntax
class Book {
String title;
int price;
void show() {
System.out.println("Book: " + title + ", Price: " + price);
}
}

Accessing Instance Members Syntax:

Book b1 = new Book();


b1.title = "Java for Beginners";
b1.price = 450;
b1.show(); // Calling instance method

Program: Instance Variables and Methods

class Employee {
String name;
double salary;
void setDetails(String empName, double empSalary) {
name = empName;
salary = empSalary;
}
void showDetails() {
System.out.println("Employee Name: " + name);
System.out.println("Salary: ₹" + salary);
}
}

public class Company {


public static void main(String[] args) {
Employee e1 = new Employee();
e1.setDetails("Amit", 50000);
e1.showDetails();
Employee e2 = new Employee();
e2.setDetails("Riya", 60000);
e2.showDetails();
}
}

Static Variables and Static Methods in Java


1. The static keyword in Java is utilized for memory management. It allows members of a
class (variables or methods) to be shared across all instances of that class without the
need for object instantiation.
2. When something is declared static, it belongs to the class itself rather than to individual
objects.

Static Variables (Class Variables)

1. Declared using the static keyword.


2. Only one copy exists, shared among all instances.
3. Useful for constants or values that should remain consistent across all objects.

Example

class Counter {
static int count = 0; // static variable
Counter() {
count++; // increments the same variable for all objects
System.out.println("Count: " + count);
}
}

Static Methods

1. Can be invoked without creating an object.


2. Can only access static data directly.
3. Cannot utilize this or super in static context because there is no instance.

Example:

class MathUtil {
static int square(int x) {
return x * x;
}
}

public class Test {


public static void main(String[] args) {
System.out.println("Square of 5: " + MathUtil.square(5));
}
}

What is a Constructor?
A constructor in Java is a special method used to initialize objects upon creation. It shares
the same name as the class and lacks a return type — not even void.
Key Characteristics of Constructors:

1. Automatically invoked upon object creation.


2. Shares the same name as the class.
3. Lacks a return type, not even void.
4. Can be overloaded (multiple constructors with different parameter lists).
5. Used to assign initial values to object fields.

Types of Constructors:

1.Default Constructor:
A) Automatically supplied by Java if no constructor is defined.
B) Initializes fields with default values (e.g., 0, null, false).

Example:

class Student {
String name;
int age;
// Default constructor (automatically provided if you don’t define any)
Student() {
name = "Unknown";
age = 0;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

2.Parameterized Constructor:
A) Used to initialize fields with custom values.

Example:

class Student {
String name;
int age;
Student(String n, int a) {
name = n;
age = a;
}
void show() {
System.out.println("Name: " + name + ", Age: " + age);
}
}
3.Constructor Overloading:
A) Java permits multiple constructors in the same class with varied parameter types or
counts.

Example:

class Box {
int length, width;
Box() {
length = width = 0;
}
Box(int l, int w) {
length = l;
width = w;
}
void show() {
System.out.println("Length: " + length + ", Width: " + width);
}
}

4.Using this() for Constructor Chaining:


A) Use this() to call another constructor within the same class.

Example:

class Employee {
String name;
int id;
Employee() {
this("Default", 0); // calls parameterized constructor
}
Employee(String name, int id) {
this.name = name;
this.id = id;
}
void show() {
System.out.println("Name: " + name + ", ID: " + id);
}
}

Note:

1. If you define any constructor, Java will not provide the default one.
2. Constructor overloading offers flexibility during object creation.
3. Using this() helps avoid code duplication and ensures clean initialization.
this Keyword in Java
The this keyword is a special reference variable in Java that refers to the current object — the
object on which a method or constructor is executed. It is useful in situations where the
context may be unclear, such as when instance variable names and parameters overlap. It
also aids in method chaining, constructor chaining, and passing the current object to other
methods or constructors.

Key Uses of this Keyword:

1. Referring to Instance Variables


2. Calling Another Constructor (this())
3. Passing Current Object as a Parameter

1. Referring to Instance Variables:

When method or constructor parameters share names with instance variables, this is used to
differentiate them.

Example:

class Student {
String name;
int age;
Student(String name, int age) {
this.name = name; // 'this.name' refers to the instance variable
this.age = age; // 'age' refers to the parameter
}
void display() {
System.out.println("Name: " + name + ", Age: " + age);
}
}

2. Calling Another Constructor (this()):

Used for constructor chaining, where one constructor invokes another within the same class
to avoid code duplication.

Example:

class Box {
int length, width;
Box() {
this(0, 0); // Must be the first line
}
Box(int l, int w) {
this.length = l;
this.width = w;
}
}

3. Passing Current Object as a Parameter:

The current object can be passed using this to methods that require an object reference as an
argument.

Example:

class A {
void show(A obj) {
System.out.println("Called with object: " + obj);
}
void call() {
show(this); // passing current object
}
}

Object-Oriented Programming (OOP) Principles in Java


Object-Oriented Programming is a programming paradigm focused on objects, which are
instances of classes. Java is a purely object-oriented language (aside from primitives) and
embraces the four core principles of OOP:

1. Encapsulation:

Encapsulation is the practice of binding data (variables) and code (methods) into a single unit
— a class — while restricting direct access to some of the object's components.

How Java Supports It:

By using private access specifiers for instance variables.


Access to variables is facilitated via public methods (getters/setters).

Example:

// Class with encapsulated fields


class Employee {
// Private fields - cannot be accessed directly
private String name;
private double salary;
// Public setter method - to set values
public void setName(String name) {
this.name = name;
}
public void setSalary(double salary) {
if (salary > 0) {
this.salary = salary;
}
}
// Public getter method - to access values
public String getName() {
return name;
}
public double getSalary() {
return salary;
}
}

// Main class to test encapsulation


public class EncapsulationDemo {
public static void main(String[] args) {
Employee emp = new Employee();
// Setting values using setters
emp.setName("Rohit");
emp.setSalary(75000);
// Getting values using getters
System.out.println("Employee Name: " + emp.getName());
System.out.println("Employee Salary: Rs" + emp.getSalary());
}
}

2. Inheritance:

Inheritance is a fundamental principle of Object-Oriented Programming that allows one class


(the subclass) to acquire the properties and behaviors (methods and fields) of another class
(the superclass).

Note:
This mechanism promotes code reuse, hierarchical classification, and extensibility.

Types of Inheritance in Java:

1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance (via interface)
Note: Java does not support Multiple Inheritance (via class) to avoid ambiguity.

Syntax:

class SuperClass {
// fields and methods
}
class SubClass extends SuperClass {
// inherits from SuperClass
}

Key Features:

1. Subclasses inherit all accessible fields and methods from the superclass.
2. A subclass can add new members or override existing ones.
3. Inheritance supports method overriding for dynamic behavior.

Single Inheritance:

Single Inheritance is the simplest and most widely used form of inheritance in Java. In single
inheritance, a single subclass inherits the members (fields and methods) of one superclass.

This relationship models an "is-a" connection — for instance, a Car is a Vehicle.

Why Use Single Inheritance?

1. Promote code reuse.


2. Reduce redundancy.
3. Simplify maintenance and extension of programs.

NOTE:

1. The subclass inherits all non-private fields and methods.


2. The subclass can introduce its own fields and methods.
3. It can override methods for specific behavior.
4. Constructors are not inherited, but the super keyword can be utilized to call them.

Example:

// Superclass (Parent)
class Animal {
String name;
void eat() {
System.out.println(name + " is eating.");
}
void sleep() {
System.out.println(name + " is sleeping.");
}
}

// Subclass (Child)
class Dog extends Animal {
void bark() {
System.out.println(name + " is barking.");
}
}

// Test class with main method


public class SingleInheritanceDemo {
public static void main(String[] args) {
Dog d = new Dog(); // creating subclass object
d.name = "Bruno"; // inherited field
d.eat(); // inherited method
d.sleep(); // inherited method
d.bark(); // subclass-specific method
}
}

Multilevel Inheritance:

Multilevel inheritance refers to a scenario where a class is derived from another class, which
itself is derived from a third class. This creates an inheritance chain of multiple levels.

Example:
Class C inherits from Class B, and Class B inherits from Class A.

// Base class
class Animal {
void eat() {
System.out.println("Animal eats food.");
}
}

// First derived class


class Mammal extends Animal {
void walk() {
System.out.println("Mammal walks on four legs.");
}
}

// Second derived class (inherits from Mammal → Animal)


class Dog extends Mammal {

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy