0% found this document useful (0 votes)
13 views

JAVA

The document provides a comprehensive overview of Java programming, covering its characteristics, fundamentals, and key components such as JVM, JRE, and JDK. It details the Java program compilation and execution process, security features, and the sandbox model, alongside fundamental concepts like data types, literals, and variables. Additionally, it discusses advanced topics including multithreading, JDBC, and Java Collection API interfaces.

Uploaded by

aggarwalmanas287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

JAVA

The document provides a comprehensive overview of Java programming, covering its characteristics, fundamentals, and key components such as JVM, JRE, and JDK. It details the Java program compilation and execution process, security features, and the sandbox model, alongside fundamental concepts like data types, literals, and variables. Additionally, it discusses advanced topics including multithreading, JDBC, and Java Collection API interfaces.

Uploaded by

aggarwalmanas287
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

JAVA

UNIT 1
• Overview of Java:
• Characteristics of Java:
• JVM, JRE, JDK
• Parameters used in First Java Program
• Basic Java Program Understanding
• Java program Compilation and Execution Process
• JVM as an interpreter and emulator
• Instruction Set
• class File Format
• Security Promises of the JVM
• Class loaders and security aspects
• Sandbox model

UNIT 2
• Java Fundamentals: Data Types, Literals, and Variables
• Operators
• Control of Flow
• Classes and Instances
• Inheritance
• Throw and Throws clauses
• User defined Exceptions
• Applets

UNIT - 3
• Threads
• Runnable Interface
• Thread Communication
• AWT Components
• Component Class and Container Class:
• Layout Manager Interface and Default Layouts:
• Insets and Dimensions:
• Border Layout:
• Flow Layout:
• Card Layout:
• Grid Bag Layout:
• AWT Events:
• Event Models:
• Listeners:
• Class Listener:
• Adapters:
• Action Event Methods:
• Focus Event Methods:
• Key Event Methods:
• Mouse Events:
• Window Events:

UNIT - 4
• Input/Output Streams:
• Stream Filters:
• Data Input and Output Stream:
• Print Stream:
• Random Access File:
• JDBC (Database connectivity with MS-Access, Oracle, MS-SQL Server)
• Object Serialization
• Sockets
• Development of client Server applications
• Design of multithreaded server
• Remote Method invocation
• Java Native interfaces and Development of a JNI based application
• Java Collection API Interfaces

UNIT 1
Overview of Java
Java is a class-based, object-oriented programming language that is designed
to have as few implementation dependencies as possible. It is intended to let
application developers Write Once and Run Anywhere (WORA), meaning that
compiled Java code can run on all platforms that support Java without the need
for recompilation.
Java was developed by James Gosling at Sun Microsystems Inc. in May
1995 and later acquired by Oracle Corporation and is widely used for
developing applications for desktop, web, and mobile devices.

Java is known for its simplicity, robustness, and security features, making it a
popular choice for enterprise-level applications. Java applications are compiled
to byte code that can run on any Java Virtual Machine. The syntax of Java is
similar to C/C++.
Java makes writing, compiling, and debugging programming easy. It helps to
create reusable code and modular programs.

Characteristics of Java
1. Platform Independence: One of the key features of Java is its ability to
run on any platform that supports Java Virtual Machine (JVM). This platform
independence is achieved by compiling Java source code into bytecode, which
can be executed on any system with a compatible JVM.
2. Object-Oriented Programming (OOP): Java is designed around the
principles of object-oriented programming, which allows developers to model
real-world entities as objects and organize code into reusable and modular
components. Concepts like classes, objects, inheritance, and polymorphism are
integral to Java's OOP paradigm.
3. Simple and Readable Syntax: Java has a straightforward syntax that is
easy to learn and read. It borrows many syntax conventions from languages like
C and C++, making it familiar to programmers from those backgrounds. The
language promotes clean and organized code through its syntax rules.
4. Robustness and Memory Management: Java's robustness is achieved
through features like exception handling, automatic memory management
(garbage collection), and strong type checking. Exceptions help in dealing with
errors and exceptions that may occur during program execution, while garbage
collection relieves developers from manually managing memory allocation and
deallocation.
5. Rich Standard Library: Java comes with a vast standard library that
provides a wide range of pre-built classes and functions for common
programming tasks. This library includes utilities for input/output operations,
data structures, networking, multithreading, and more. Utilizing the standard
library saves development time and effort.
6. Security: Java emphasizes security and provides built-in mechanisms
for secure programming. It includes features like bytecode verification,
sandboxing, and security managers, which help in creating secure and trusted
applications.
7. Scalability and Performance: Java's scalability and performance have
improved over the years. The Just-In-Time (JIT) compiler optimizes bytecode at
runtime, translating it into machine code for efficient execution. Additionally,
Java supports multi-threading, enabling developers to write concurrent and
efficient programs.
8. Community and Ecosystem: Java has a large and active developer
community, which contributes to its rich ecosystem. There are numerous
frameworks, libraries, and tools available for Java development, making it
easier to build complex applications quickly.
JVM, JRE, JDK
1. JVM: The JVM (Java Virtual Machine) is a crucial component of the
Java platform. It provides a runtime environment for executing Java bytecode.
The JVM interprets or compiles Java bytecode into machine code and handles
memory management, security, and other runtime functionalities. It ensures
that Java programs are platform-independent, as bytecode can be executed on
any system with a compatible JVM.

2. JRE: The JRE (Java Runtime Environment) is a software package that


includes the JVM, libraries, and other components necessary for running Java
applications. It is a subset of the Java Development Kit (JDK) and is primarily
used by end-users who only need to run Java programs, not develop them.

3. JDK: The JDK (Java Development Kit) is a software development kit


that includes tools, libraries, and the JRE. It is used by developers to create,
compile, and debug Java applications. The JDK contains the necessary
components for both development and execution of Java programs.
• Difference between them

Aspect JDK JRE JVM

Used to Used to Responsible


develop Java run Java for running Java
Purpose applications applications code

Platform Platform- Platform- Platform-


Dependency dependent dependent Independent

It It It runs the
includes includes java byte code
development libraries to run and make java
tools like Java application to
(compiler) + application + work on any
Includes JRE JVM platform.

Running Convert
Writing
a Java bytecode into
and compiling
application on native machine
Java code
Use Case a system code

Basic Java Program


class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
Let's see what is the meaning of class, public, static, void, main, String[],
System.out.println().

• class keyword is used to declare a class in Java.


• public keyword is an access modifier that represents visibility. It
means it is visible to all.
• static is a keyword. If we declare any method as static, it is known
as the static method. The core advantage of the static method is
that there is no need to create an object to invoke the static
method. The main() method is executed by the JVM, so it doesn't
require creating an object to invoke the main() method. So, it
saves memory.
• void is the return type of the method. It means it doesn't return
any value.
• main represents the starting point of the program.
• String[] args or String args[] is used for command line argument.
We will discuss it in coming section.
• System.out.println() is used to print statement. Here, System is a
class, out is an object of the PrintStream class, println() is a
method of the PrintStream class. We will discuss the internal
working of System.out.println() statement in the coming section.
Java program Compilation and Execution Process:

The compilation and execution process in Java involves several steps. Let's break it
down:

1. Writing Java Source Code:

To begin, you need to write your Java program's source code. This is done
in a plain text file with a .java extension. You can use any text editor or
integrated development environment (IDE) for this purpose.

2. Compiling Java Source Code:

The next step is to compile the Java source code into bytecode. Bytecode is
a platform-independent representation of your program that can be
executed by the Java Virtual Machine (JVM).

To compile the source code, you use the Java compiler (javac) that comes
with the Java Development Kit (JDK). In the command prompt or terminal,
navigate to the directory where your source code file is located and
execute the following command:
3. Java Virtual Machine (JVM):

The JVM is responsible for executing Java bytecode. It acts as an interpreter


for the bytecode and provides a runtime environment for your program.

When you run a Java program, you need to have a JVM installed on your
machine. The JVM takes care of loading and executing the bytecode.

4.Running Java Bytecode:

To run the compiled bytecode, you use the java command followed by the
name of the class containing the main method (the entry point of your
program).

In the command prompt or terminal, navigate to the directory where your


.class file is located and execute the following command:

accordingly.

JVM as an interpreter and emulator

1. JVM as an Interpreter:

The JVM interprets Java bytecode instructions one by one and executes them. It
reads the bytecode, understands the instruction, and performs the
corresponding operation. This interpretation happens at runtime.

2. JVM as an Emulator:

The JVM can also be considered an emulator in the sense that it emulates a
virtual computing environment in which the Java program runs. It creates a
virtual representation of the underlying hardware and provides a runtime
environment for executing Java programs

Instruction Set
An instruction set in Java refers to the low-level operations that the Java Virtual
Machine (JVM) can execute.

Types of Instructions in Java

Java instructions (bytecode) fall into different categories:

1. Load and Store Instructions

o These instructions move data between variables and the stack.

o Example: iload (loads an integer), istore (stores an integer).

2. Arithmetic and Logical Instructions

o Perform mathematical operations like addition, subtraction,


multiplication, and logical operations.
o Example: iadd (integer addition), isub (integer subtraction), iand
(bitwise AND).

3. Type Conversion Instructions

o Convert data from one type to another (e.g., int to float).

o Example: i2f (convert int to float), d2i (convert double to int).

4. Object Creation and Manipulation Instructions

o Create and manage objects in Java.

o Example: new (create a new object), getfield (access object field).

5. Control Flow Instructions

o Handle loops and conditional statements.

o Example: if_icmpgt (if integer compare greater), goto (jump to


another instruction).

class File Format


A class file in Java is a compiled version of a Java program. When you write Java
code (.java file) and compile it using javac, it generates a .class file containing Java
bytecode. The JVM reads this bytecode and executes it.

Structure of a Java Class File:


Security Promises of the JVM:
Java is designed to be secure so that programs don’t harm your computer or steal
your data. It follows several security rules to protect users and systems. Here’s
how Java keeps things safe in simple terms :

1. Bytecode Verification (No Harmful Code Allowed)

✅ Promise: Java checks every program before running it.

2. No Direct Access to Memory (Prevents Crashes & Attacks)

✅ Promise: Java doesn’t let programs access memory directly.


3. Sandboxing (Keeps Programs in a Safe Zone)

✅ Promise: Java runs code in a controlled environment.

4. Automatic Garbage Collection (No Memory Leaks)

✅ Promise: Java automatically cleans up unused memory.

5. Security Manager (Permission Control)

✅ Promise: Java controls what a program can and cannot do.


Class loaders and security aspects:
Java Class Loaders & Security –

What is a Class Loader?

A Class Loader in Java is like a delivery person that brings Java classes into
memory when needed. It loads .class files so the Java program can use
them.

Types of Class Loaders

Java has three main types of class loaders:

1. Bootstrap ClassLoader → Loads core Java classes (e.g.,


java.lang.String).

2. Extension ClassLoader → Loads extra Java libraries (ext folder


classes).

3. Application ClassLoader → Loads user-written Java programs (.class


files).

Security Aspects of Class Loaders

How Class Loaders Keep Java Secure?

1. Prevents Untrusted Code from Running


o Java only loads trusted classes from allowed locations.

o This stops harmful code from being executed.

2. Sandboxing for Untrusted Code


o Java can run code in a restricted environment (sandbox), limiting what
it can access.

o Example: A Java applet cannot delete system files.

3. Bytecode Verification
o Before loading a class, Java checks if it follows security rules.

o Prevents hackers from injecting bad code.

4. Custom Class Loaders for Extra Security


o Developers can create custom class loaders to filter out untrusted
code.

✅ Stops viruses from running in Java apps


✅ Ensures only trusted code is executed
✅ Prevents hacking attempts through custom class loaders
Sandbox model:

Java Sandbox Model :

🔒 What is the Sandbox Model?


The Java Sandbox is like a playground with security fences. It lets Java programs
run safely without harming your system.

How Does It Work?

Java restricts what a program can do based on where it comes from:

1. Trusted Code (Your computer) → Full access to files, network, and system.

2. Untrusted Code (Downloaded from the internet) → Limited access (can’t


delete files, read passwords, etc.).

Key Security Features

✅ Class Loaders → Stops untrusted code from loading bad classes.


✅ Bytecode Verifier → Checks for harmful code before running.
✅ Security Manager → Decides what actions a program is allowed to do.
Why is the Sandbox Model Important?

✔ Prevents viruses & malware


✔ Protects your files & data
✔ Safe for running Java in browsers & networks
UNIT-2:
Java Fundamentals
Java is built on three main concepts:
1. Data Types (What kind of data we store)
2. Literals (The actual values we store)
3. Variables (Containers that hold values)
Data Types:
Java has two categories of data types: primitive types and reference types.
1. Primitive Types:

 byte - 8-bit integer, range: -128 to 127.


 short - 16-bit integer, range: -32,768 to 32,767.
 int - 32-bit integer, range: -2³¹ to 2³¹-1.
 long - 64-bit integer, range: -2⁶³ to 2⁶³-1.
 float - 32-bit floating-point number, suitable for decimal values.
 double - 64-bit floating-point number, more precision than float.
 char - 16-bit Unicode character, stores a single character.
 boolean - Represents true or false values.
1. Reference Types:

Classes: Objects of user-defined classes.


Arrays: Ordered collections of elements.
Interfaces: Reference types that define a contract for classes
implementing them.
Strings: Represents sequences of characters

What are Literals?


Literals are just fixed values that we assign to variables.
Examples of Literals:
 Integer Literal: 10, -5, 200 (Numbers)
 Floating-Point Literal: 3.14, 2.5 (Decimal numbers)
 Character Literal: 'A', '#', '9' (Single characters)
 Boolean Literal: true, false (Logical values)
 String Literal: "Hello", "Java is fun!" (Text value)
. What are Variables?
A variable is like a box that holds a value. We can change its value
anytime.
Declaring a Variable in Java
int age = 25; // age is a variable storing the value 25

SIMPLEST JAVA PROGRAM GIVEN BELOW:


public class StudentInfo {
public static void main(String[] args) {
String name = "Alice";
int age = 20;
char grade = 'A';
boolean isStudent = true;

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


System.out.println("Age: " + age);
System.out.println("Grade: " + grade);
System.out.println("Is a Student? " + isStudent);
}
}

WRAPPER CLASSES:
In Java, Wrapper Classes are used to convert primitive data
types into object.
Java has 8 primitive data types (int, char, float, etc.). But
sometimes, we need objects instead of primitives.

What is an Array?
An array is like a box that holds multiple values of the same
type. Instead of creating separate variables, we store them in
one single variable.
EXAMPLE:
int num1 = 10;
int num2 = 20;
int num3 = 30;
int[] numbers = {10, 20, 30};

Strings in Java
A String is a sequence of characters (text). It is an object in Java.
EXAMPLE:
String name = "Alice";

OPERATORS:
Operators in Java are symbols that perform operations on values or
variables. Think of them as tools that help in calculations and logic.
1. Types of Operators in Java:
ARITHMETIC OPERATORS:

ASSIGNMENT OPERATORS:
COMPARISON OPERATORS:

LOGICAL OPERATORS:
BITWISE OPERATORS:

CONTROL FLOW IN JAVA


Control flow in Java means how the program decides what to do next.
Java follows a top-to-bottom execution, but sometimes, we need to
change the flow using conditions and loops.
1. IF /ELSE STATEMENTS:

2. LOOPS :
3.JUMP STATEMENTS:
Break statement: Terminates the execution of a loop or switch
statement and transfers control to the next statement after the
loop or switch.
Continue Statement: (Skips one loop iteration).
Return : (Exits the method).

Classes & Instances in Java


1. What is a Class?
A class is like a blueprint (plan) for creating objects. It defines properties
(variables) and actions (methods).
Example: Think of a Class as a Car Design
 Class (Blueprint): Defines what a car should have (color, engine,
wheels).
 Objects (Instances): Actual cars made from that design (Red Car,

Blue Car).
EXAMPLE:
class Car {
String color; // Property
int speed; // Property

void drive() { // Method


System.out.println("Car is moving...");
}
}
2. What is an Instance (Object)?
An instance (object) is a real thing created from a class.
Example: Creating a Car Object
public class Main {
public static void main(String[] args) {
Car myCar = new Car(); // Creating an instance
myCar.color = "Red"; // Assigning values
myCar.speed = 100;

System.out.println("Car color: " + myCar.color);


myCar.drive(); // Calling method
}
}

Inheritance in Java
Inheritance means one class (child) can use the properties & methods
of another class (parent).
Example: Think of Family Inheritance
 Father (Parent Class) has a house.

 Son (Child Class) automatically gets the house.


// Parent class
class Animal {
void eat() {
System.out.println("I can eat");
}
}

// Child class (inherits from Animal)


class Dog extends Animal {
void bark() {
System.out.println("I can bark");
}
}

// Main class
public class Main {
public static void main(String[] args) {
Dog myDog = new Dog(); // Creating an object of Dog
myDog.eat(); // Inherited from Animal
myDog.bark(); // Defined in Dog class
}
}

How to Use Inheritance in Java?


We use the extends keyword to inherit a class.

Working :
Animal is the parent class (also called superclass).
Dog is the child class (also called subclass) that inherits eat() from Animal.
Dog can use both eat() (from parent) and bark() (its own method)
TYPES OF INHERITANCE

Single Inheritance : class B extends A {}

// Parent class

class Animal {

void eat() {

System.out.println("Eating...");

}
// Child class inheriting from
Animal

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

// Main class to test the


inheritance

public class
SingleInheritanceExample {

public static void main(String[]


args) {

Dog d = new Dog();

d.eat(); // Inherited
method from Animal class

d.bark(); // Method of Dog


class

}
Multilevel Inheritance : class C extends B {}
// Grandparent class
class Animal {

void eat() {

System.out.println("Eating...");

// Parent class inheriting from


Animal

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

// Child class inheriting from Dog

class Puppy extends Dog {

void weep() {

System.out.println("Weeping...");

}
// Main class to test multilevel
inheritance

public class
MultilevelInheritanceExample {

public static void main(String[]


args) {

Puppy p = new Puppy();

p.eat(); // Inherited from


Animal class

p.bark(); // Inherited from


Dog class

p.weep(); // Method of
Puppy class

}
: class B extends A,
Hierarchical Inheritance
class C extends A
// Parent class

class Animal {

void eat() {

System.out.println("Eating...");

}
// Child class 1 inheriting from Animal

class Dog extends Animal {

void bark() {

System.out.println("Barking...");

// Child class 2 inheriting from Animal

class Cat extends Animal {

void meow() {

System.out.println("Meowing...");

// Main class to test hierarchical


inheritance

public class
HierarchicalInheritanceExample {

public static void main(String[] args) {

Dog d = new Dog();

d.eat(); // Inherited from Animal


class
d.bark(); // Method of Dog class

Cat c = new Cat();

c.eat(); // Inherited from Animal


class

c.meow(); // Method of Cat class

NOTE.

Java does NOT support Multiple Inheritance (class C extends


A, B ).
Java does not support multiple inheritance with classes to avoid complexity
and ambiguity, commonly known as the Diamond Problem. However, it
does support multiple inheritance with interfaces.

1. Multiple Inheritance (with Classes)


 If a class were to inherit from two classes that have methods with the
same signature, the compiler would be confused about which method
to use. This is called the Diamond Problem.

2. How Java Handles It


 Java allows multiple inheritance through interfaces. This is safe
because interfaces only declare methods without implementations
 Starting with Java 8, interfaces can have default methods, but even
then, Java provides rules to resolve conflicts.

Example:
interface A {

default void show() {

System.out.println("Interface A");

interface B {

default void show() {

System.out.println("Interface B");

class C implements A, B {

// Override to resolve conflict

public void show() {

A.super.show(); // Call A's show method

B.super.show(); // Call B's show method

public class MultipleInheritanceExample {


public static void main(String[] args) {

C obj = new C();

obj.show();

HYBRID INHERITANCE:
Hybrid inheritance is a combination of more than one type of inheritance
(e.g., multilevel + multiple).

In Java, hybrid inheritance is not supported with classes because it


involves multiple inheritance.

However, it can be achieved using interfaces.

Throw & Throws in Java


1. throw (For Throwing Exceptions)

Used to manually throw an exception in Java.

EXAMPLE:
class Test {

static void checkAge(int age) {

if (age < 18) {

throw new ArithmeticException("Not eligible to vote!");

} else {

System.out.println("You can vote!");

}
public static void main(String[] args) {

checkAge(16); // Throws an exception

Output: Exception: Not eligible to vote!

2. throws (For Declaring Exceptions)


Used in method signature to warn that the method may throw an
exception.

EXAMPLE:

class Test {

static void divide(int a, int b) throws ArithmeticException {

System.out.println(a / b); // May throw exception if b = 0

public static void main(String[] args) {

divide(10, 0); // Throws exception

Output: Exception: / by zero

User-Defined Exceptions in Java


// Custom Exception Class

class InvalidAgeException extends Exception {

public InvalidAgeException(String message) {

super(message);

// Main Class

public class VotingEligibility {

// Method to check voting eligibility

public static void checkAge(int age) throws InvalidAgeException {

if (age < 18) {

throw new InvalidAgeException("Age is less than 18. Not eligible to


vote.");

} else {

System.out.println("Eligible to vote.");
}

public static void main(String[] args) {

int age = 16; // Test age

try {

checkAge(age);

} catch (InvalidAgeException e) {

System.out.println("Exception Caught: " + e.getMessage());

Java allows us to create our own exceptions by extending the


Exception class.

1. Create a Custom Exception Class:

To define a custom exception, you need to create a new class that


extends an existing exception class or one of its subclasses.
2. Use throw to Raise the Exception
Use the throw keyword followed by an instance of your custom exception class
to throw the exception.

StringBuffer in Java

StringBuffer is used to modify (change) strings because String is


immutable (cannot be changed).
It is faster than normal String when doing many changes

How to Use StringBuffer?

Creating a StringBuffer:

StringBuffer sb = new StringBuffer("Hello");


Important Methods:
Method Description Example & Output
sb.append(" World"); → Hello
append() Adds text at the end
World
Adds text at a specific sb.insert(5, " Java"); → Hello
insert()
position Java
sb.replace(0, 5, "Hi"); → Hi
replace() Replaces part of the string
World
delete() Removes part of the string sb.delete(0, 5); → World
reverse() Reverses the string sb.reverse(); → olleH

Java Applets
An applet is a small Java program that runs inside a web browser or an
applet viewer.
Applets are used to add interactive features to web pages.
JAVA LIFECYCLE:

How Does an Applet Work?


1. User opens a web page with an applet embedded in it.
2. Applet runs inside the browser, showing graphics or interacting
with the user.
Simple Applet Example:
JAVA PROGRAM:
import java.applet.Applet;
import java.awt.Graphics;

public class HelloWorldApplet extends Applet {


public void paint(Graphics g) {
g.drawString("Hello World", 50, 50);
}
}
HTML Code to Run the Applet:

<html>
<body>
<applet code="HelloWorldApplet.class" width="300"
height="150">
</applet>
</body>
</html>
THE END OF UNIT-2

You might also like