0% found this document useful (0 votes)
28 views29 pages

Java Programming Unit-II

The document discusses Java fundamentals including data types, literals, variables, wrapper classes, arrays, arithmetic operators, and logical operators. It provides details on each topic such as the different data types in Java, how to declare and initialize variables, the purposes of wrapper classes and how autoboxing works, how to declare and access array elements, and the different arithmetic and logical operators in Java.

Uploaded by

wimir16623
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
28 views29 pages

Java Programming Unit-II

The document discusses Java fundamentals including data types, literals, variables, wrapper classes, arrays, arithmetic operators, and logical operators. It provides details on each topic such as the different data types in Java, how to declare and initialize variables, the purposes of wrapper classes and how autoboxing works, how to declare and access array elements, and the different arithmetic and logical operators in Java.

Uploaded by

wimir16623
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

Unit-II

UNIT - II
Java Fundamentals, Data Types & Literals Variables, Wrapper Classes, Arrays, Arithmetic Operators, Logical Operators,
Control of Flow, Classes and Instances, Class Member Modifiers Anonymous Inner Class Interfaces and Abstract
Classes, inheritance, throw and throws clauses, user defined Exceptions, The String Buffer Class, tokenizer, applets,
Life cycle of applet and Security concerns.

Data Types, Literals, and Variables in Java


In Java, data types specify the type of data that a variable can hold, literals represent constant values,
and variables are named storage locations for data. Understanding these concepts is fundamental to
Java programming:

1. Data Types:

• Java has two categories of data types:

• Primitive Data Types: These are the most basic data types built into the Java
language.

• Numeric Types: byte, short, int, long, float, double

• Boolean Type: boolean

• Character Type: char

• Reference Data Types: These data types are non-primitive and are created
using predefined classes or user-defined classes.

• Arrays

• Objects

• Strings

2. Literals:

• Literals represent constant values in Java programs.

• Types of literals include:

• Integer Literals: e.g., 123, -456

• Floating-Point Literals: e.g., 3.14, -0.001

• Boolean Literals: true, false

• Character Literals: e.g., 'A', '\n', '\u0041' (Unicode)

• String Literals: e.g., "Hello", "Java"

• Null Literal: null


3. Variables:

• A variable is a named memory location that stores data.

• Variables must be declared with a data type before they can be used.

• Syntax for variable declaration: data_type variable_name;

• Example variable declarations:

• int age;

• double salary;

• boolean isStudent;

• char grade;

4. Variable Initialization:

• After declaration, variables can be initialized with an initial value.

• Example: int count = 0;

5. Variable Naming Rules:

• Variable names in Java must follow certain rules:

• Must begin with a letter (A-Z or a-z), currency character ($) or underscore
(_).

• Subsequent characters can be letters, digits (0-9), currency characters, or


underscores.

• Keywords cannot be used as variable names.

• Case-sensitive.

6. Variable Naming Conventions:

• Follow camelCase convention for variable names.

• Use meaningful names that describe the purpose of the variable.

• Start variable names with a lowercase letter.

7. Variable Scope:

• The scope of a variable refers to the part of the program where the variable is
accessible.

• Local variables: Declared within methods, constructors, or blocks; accessible only


within the enclosing block.

• Instance variables: Belong to an instance of a class; accessible by all methods of the


class.

• Class variables (static variables): Shared among all instances of a class; belong to the
class itself.
Wrapper classes:
Wrapper classes in Java provide a way to convert primitive data types into objects (reference types).
For example, when working with collections or when you need to pass primitive data types as
arguments to methods that require objects. Here's an overview of wrapper classes in Java:

1. Why Wrapper Classes:

• In Java, primitive data types (int, double, boolean, etc.) are not objects and do not
belong to any class hierarchy.

• Collections (like ArrayList, LinkedList) and other APIs often require objects instead of
primitive data types.

• Wrapper classes provide a way to convert primitive data types into objects, enabling
the use of primitives in contexts where objects are required.

2. Types of Wrapper Classes:

• Java provides a set of predefined wrapper classes for each primitive data type:

• Integer: for int

• Double: for double

• Float: for float

• Boolean: for boolean

• Character: for char

• Byte: for byte

• Short: for short

• Long: for long

3. Autoboxing and Unboxing:

• Java automatically converts primitive data types into their corresponding wrapper
classes when needed. This process is called autoboxing.

• Conversely, it automatically converts wrapper class objects back to primitive data


types when needed. This process is called unboxing.

• Autoboxing and unboxing make it easier to work with wrapper classes without
explicit conversions.

Example:

// Autoboxing: converting int to Integer Integer num = 10; // autoboxing // Unboxing: converting
Integer to int int value = num; // unboxing

4. Methods and Usage:


• Wrapper classes provide useful methods to work with primitive data types.

• For example, Integer class provides methods like parseInt(), to convert a String to an
int, and toString(), to convert an int to a String.

• Wrapper classes are immutable, meaning their values cannot be changed after
creation.

5. Comparison:

• When comparing wrapper class objects, use .equals() method instead of ==


operator, as == compares references, not values.

• Example: Integer a = new Integer (10); Integer b = new Integer (10);


System.out.println(a.equals(b)); // prints true

Arrays:
Arrays in Java are used to store multiple values of the same data type under a single name. It provide
a convenient way to work with collections of data. Here's an overview of arrays in Java:

1. Declaration and Initialization:

• Arrays are declared using square brackets [] after the data type.

• Syntax for declaration: datatype[] arrayName; or datatype arrayName[];

Example:

int [] numbers; // Declaration numbers = new int [5]; // Initialization with size 5

• Arrays can also be declared and initialized simultaneously.

Example:

int [] numbers = new int []{1, 2, 3, 4, 5}; // Initialization with values

2. Accessing Elements:

• Array elements are accessed using their index.

• Indexing starts from 0 and goes up to length-1.

• Syntax: arrayName[index]

Example:

int [] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers [0]); // Output: 1

3. Array Length:

• The length of an array can be obtained using the length property.

Example:

int [] numbers = {1, 2, 3, 4, 5}; int length = numbers.length;


System.out.println(length); // Output: 5

4. Iterating Through an Array:

• Arrays can be traversed using loops like for or foreach.

Example using for loop:

int [] numbers = {1, 2, 3, 4, 5}; for (int i = 0; i < numbers.length; i++)

{ System.out.println(numbers[i]); }

Example using foreach loop (enhanced for loop):

int [] numbers = {1, 2, 3, 4, 5};

for (int num : numbers) { System.out.println(num); }

5. Multidimensional Arrays:

• Java supports multidimensional arrays, i.e., arrays of arrays.

• Syntax for declaration: datatype[][] arrayName;

Example:

int[][] matrix = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} };

• Accessing elements in a multidimensional array requires multiple indices.

6. Arrays Class:

• The java.util.Arrays class provides utility methods for working with arrays, such as
sorting and searching.

7. Arrays vs. ArrayList:

• Arrays have fixed sizes and cannot be resized dynamically, whereas ArrayList
provides dynamic resizing.

• ArrayList provides more flexibility and functionality compared to arrays but comes
with a slight performance overhead.
Arithmetic operators:
Arithmetic operators in Java are used to perform mathematical operations on numeric operands.
These operators allow you to perform addition, subtraction, multiplication, division, and other
arithmetic operations. Here are the arithmetic operators in Java:

1. Addition (+):

• Adds two operands.

Example:

int result = 5 + 3; // result is 8

2. Subtraction (-):

• Subtracts the second operand from the first.

Example:

int result = 7 - 4; // result is 3

3. Multiplication (*):

• Multiplies two operands.

Example:

int result = 4 * 6; // result is 24

4. Division (/):

• Divides the first operand by the second.

• If both operands are integers, the result is an integer, and any fractional part is
truncated.

Example:

int result = 10 / 3; // result is 3 (integer division) double decimalResult = 10.0 / 3; //


decimalResult is 3.3333333333333335 (double division)

5. Modulus (%):

• Returns the remainder of the division operation.

Example:

int result = 10 % 3; // result is 1 (remainder of 10 divided by 3)

6. Increment (++):

• Increases the value of the operand by 1.

• It can be used as a prefix (++x) or postfix (x++).


Example:

int x = 5; x++; // x is now 6

7. Decrement (--):

• Decreases the value of the operand by 1.

• It can be used as a prefix (--x) or postfix (x--).

Example:

int x = 5; x--; // x is now 4

Logical operators
Logical operators in Java are used to perform logical operations on boolean operands. These
operators allow you to combine or manipulate boolean values to make logical decisions in your code.
Here are the logical operators in Java:

1. Logical AND (&&):

• Returns true if both operands are true; otherwise, it returns false.

Example:

boolean result = true && false; // result is false

2. Logical OR (||):

• Returns true if at least one of the operands is true; otherwise, it returns false.

Example:

boolean result = true || false; // result is true

3. Logical NOT (!):

• Returns the opposite of the operand's value. If the operand is true, it returns false,
and if the operand is false, it returns true.

Example:

boolean result = !true; // result is false

4. Bitwise AND (&):

• Performs a bitwise AND operation on corresponding bits of two operands.

• Returns 1 if both bits are 1; otherwise, it returns 0.

Example:

int result = 5 & 3; // result is 1 // 5 in binary: 101 // 3 in binary: 011 // Bitwise AND: 001

5. Bitwise OR (|):

• Performs a bitwise OR operation on corresponding bits of two operands.

• Returns 1 if at least one of the bits is 1; otherwise, it returns 0.


Example:

int result = 5 | 3; // result is 7 // 5 in binary: 101 // 3 in binary: 011 // Bitwise OR: 111

Control of flow:
Control of flow refers to the management of the execution sequence within a program. In Java,
control of flow is achieved through various constructs like conditional statements, loops, and
branching mechanisms. Here's an overview of control flow in Java:

1. Conditional Statements:

• if Statement:

if (condition)

{ // code block to execute if condition is true }

• if-else Statement:

if (condition)

{ // code block to execute if condition is true }

else { // code block to execute if condition is false }

• else-if Ladder:

if (condition1) { // code block to execute if condition1 is true }

else if (condition2) { // code block to execute if condition2 is true }

else { // code block to execute if all conditions are false }

• Nested if Statements:

if statements can be nested inside each other.

2. Switch Statement:

• Used to select one of many code blocks to be executed.

switch (expression)

case value1: // code block break;

case value2: // code block break;

default: // code block if expression doesn't match any case }

3. Loops:

• for Loop:

for (initialization; condition; update) { // code block to be executed }

• while Loop:
while (condition) { // code block to be executed }

• do-while Loop:

do { // code block to be executed } while (condition);

4. Branching Mechanisms:

• break Statement: Used to terminate the loop or switch statement.

• continue Statement: Skips the current iteration of the loop and proceeds to the next
iteration.

• return Statement: Exits the current method and returns a value (if any).

5. Control Flow in Exception Handling:

• try-catch Blocks: Used to handle exceptions.

try { // code that may throw an exception }

catch (ExceptionType e) {

// exception handling code

Classes and instances:


In Java, classes and instances (objects) are fundamental concepts of object-oriented programming
(OOP). Classes serve as blueprints for creating objects, while instances are individual objects created
from those blueprints. Let's delve into each of these concepts:

Classes:
1. Definition:

• A class is a blueprint or template that defines the structure and behavior of objects.

• It encapsulates data for the object and methods to manipulate that data.

Syntax:

public class ClassName {

// Fields (variables)

// Constructors

// Methods

2. Fields (Variables):

• Fields represent the state or data of the objects.

• They can be of any data type, including primitive types, reference types, or other
classes.
Example:

public class Car {

String model;

int year;

double price;

3. Constructors:

• Constructors are special methods used for initializing objects.

• They have the same name as the class and do not have a return type.

• Constructors are invoked when an object of the class is created.

Example:

public class Car {

String model;

int year;

double price;

public Car (String model, int year, double price) {

this.model = model;

this.year = year;

this.price = price;

4. Methods:

• Methods represent the behavior or functionality of objects.

• They can perform actions or manipulate the object's state.

Example:

public class Car {

String model;

int year;

double price;

public void displayInfo() {

System.out.println("Model: " + model);


System.out.println("Year: " + year);

System.out.println("Price: " + price);

Instances (Objects):
1. Definition:

• An instance, also known as an object, is a concrete realization of a class.

• It represents a specific entity with its own unique state and behavior.

Syntax for creating an instance:

ClassName objectName = new ClassName();

2. Instantiation:

• Instantiation is the process of creating an instance of a class using the new keyword.

Example:

Car myCar = new Car("Toyota", 2022, 25000.00);

3. Accessing Members:

• You can access fields and methods of an object using the dot (.) operator.

Example:

System.out.println(myCar.model);

myCar.displayInfo();

Class Member Modifiers:


1. Access Modifiers:

• Control the visibility of classes, methods, and fields.

• Four access modifiers: public, protected, default (no modifier), and private.

Example:

public class MyClass {

private int myPrivateField;

public void myPublicMethod() {

// Method implementation

}
2. Non-Access Modifiers:

• Provide additional functionality or restrictions to classes, methods, and fields.

• Common non-access modifiers: static, final, abstract.

Example:

public class MyClass {

static int staticField;

final double PI = 3.14;

abstract void abstractMethod();

Anonymous Inner Class:

1. Definition:

• An anonymous inner class is a class without a name that is declared and instantiated
at the same time.

• Often used for implementing interfaces or extending classes on-the-fly.

Syntax:

InterfaceName objectName = new InterfaceName() {

// Anonymous inner class implementation

};

2. Example:

• Implementing an interface using an anonymous inner class:

Runnable runnable = new Runnable () {

public void run () {

System.out.println("Anonymous inner class implementation of run method");

};

Interfaces:

1. Definition:

• An interface is a reference type similar to a class that can contain only abstract
methods, default methods, static methods, constants, and nested types.

• Used to define a contract for classes that implement them.

Syntax:

public interface InterfaceName {


// Method declarations

2. Implementing Interfaces:

• A class implements an interface by providing implementations for all its abstract


methods.

Syntax:

public class MyClass implements InterfaceName {

// Method implementations

3. Default Methods:

• Introduced in Java 8, default methods provide a default implementation in


interfaces.

• Classes that implement the interface can choose to override the default method.

Syntax:

public interface InterfaceName {

default void methodName() {

// Default method implementation

Abstract Class:
Abstract classes in Java are classes that cannot be instantiated directly and may contain one or more
abstract methods. They serve as templates for other classes to extend and provide implementations
for the abstract methods. Here's an overview of abstract classes in Java:

1. Definition:

• An abstract class is declared using the abstract keyword.

• It may contain both abstract methods and concrete methods (with


implementations).

• Abstract classes cannot be instantiated directly; they are meant to be subclassed.

Syntax:

public abstract class AbstractClassName {

// Abstract methods public abstract void abstractMethod();

// Concrete methods public void concreteMethod() {


// Method implementation

2. Abstract Method:

• An abstract method is a method declared without an implementation (no method


body).

• It is intended to be implemented by subclasses.

• Abstract methods are declared using the abstract keyword.

Example:

public abstract void abstractMethod();

3. Concrete Method:

• A concrete method is a method with an implementation provided in the abstract


class itself.

• Concrete methods can access fields and other methods of the abstract class.

• Subclasses inherit concrete methods and can override them if needed.

Example:

public void concreteMethod() {

// Method implementation

4. Extending Abstract Class:

• A subclass extends an abstract class using the extends keyword.

• Subclasses must provide implementations for all abstract methods inherited from
the abstract class.

• Subclasses may also override concrete methods if needed.

Example:

public class SubClassName extends AbstractClassName {

// Implement abstractMethod public void abstractMethod() {

// Method implementation

5. Purpose:
• Abstract classes provide a way to define a common interface for a group of related
classes.

• They promote code reusability and help establish a hierarchical relationship between
classes.

Inheritance:
Inheritance is a fundamental concept in object-oriented programming (OOP) that allows a new class
to inherit properties and behaviors (methods and fields) from an existing class. In Java, inheritance
enables code reuse, promotes modularity, and facilitates the creation of hierarchies of related classes.
Here's an overview of inheritance in Java:

1. Superclass and Subclass:

• Inheritance involves two classes: a superclass (also called a parent class) and a
subclass (also called a child class).

• The superclass is the existing class from which the subclass inherits.

• The subclass is the new class that extends or inherits from the superclass.

2. Extending a Class:

• To create a subclass, use the extends keyword followed by the superclass name.

Syntax:

public class Subclass extends Superclass {

// Subclass members

3. Access Modifiers and Inheritance:

• Inheritance affects the visibility of superclass members in the subclass.

• Public and protected members of the superclass are inherited by the subclass.

• Private members of the superclass are not inherited by the subclass.

• Default (package-private) members are inherited only if the subclass is in the same
package as the superclass.

4. Overriding Methods:

• Subclasses can override (provide a new implementation for) methods defined in the
superclass.

• The method signature (name, parameters, return type) in the subclass must match
the method signature in the superclass.

• Use the @Override annotation to indicate that a method overrides a superclass


method (optional but recommended).
Example:

public class Subclass extends Superclass {

@Override

public void overriddenMethod() {

// New implementation for the method

5. Calling Superclass Constructor:

• The subclass constructor must call a superclass constructor explicitly or implicitly.

• Use the super () keyword to call the superclass constructor from the subclass
constructor.

Example:

public Subclass () {

super ();

// Call superclass constructor

// Subclass constructor body

6. Types of Inheritance:

• Java supports single inheritance, where a subclass can inherit from only one
superclass.

• However, Java supports multiple inheritance through interfaces, where a class can
implement multiple interfaces.

Example:

Let's consider a scenario where we have a superclass Vehicle and two subclasses Car and Motorcycle.
Each class will have specific properties and methods, and the subclasses will inherit from the
superclass.

// Superclass: Vehicle

class Vehicle {

private String brand;

private int year;

// Constructor

public Vehicle (String brand, int year) {

this.brand = brand;
this.year = year;

// Getter methods

public String getBrand() {

return brand;

public int getYear() {

return year;

// Method to display vehicle information

public void displayInfo() {

System.out.println("Brand: " + brand);

System.out.println("Year: " + year);

// Subclass: Car

class Car extends Vehicle {

private int numberOfDoors;

// Constructor

public Car(String brand, int year, int numberOfDoors) {

super(brand, year); // Call superclass constructor

this.numberOfDoors = numberOfDoors;

// Method to display car information

public void displayCarInfo() {

displayInfo(); // Call superclass method

System.out.println("Number of doors: " + numberOfDoors);

// Subclass: Motorcycle
class Motorcycle extends Vehicle {

private String type;

// Constructor

public Motorcycle(String brand, int year, String type) {

super(brand, year); // Call superclass constructor

this.type = type;

// Method to display motorcycle information

public void displayMotorcycleInfo() {

displayInfo(); // Call superclass method

System.out.println("Type: " + type);

// Main class

public class Main {

public static void main(String[] args) {

Car myCar = new Car("Toyota", 2022, 4);

myCar.displayCarInfo(); // Display car information

System.out.println(); // Blank line for separation

Motorcycle myMotorcycle = new Motorcycle("Harley-Davidson", 2021, "Cruiser");

myMotorcycle.displayMotorcycleInfo(); // Display motorcycle information

In this example:

• The Vehicle class is the superclass, containing common properties and methods for all
vehicles.

• The Car class and Motorcycle class are subclasses of Vehicle, inheriting its properties and
methods.

• Each subclass (Car and Motorcycle) adds its specific properties (numberOfDoors and type)
and methods (displayCarInfo() and displayMotorcycleInfo()).

• The main method demonstrates creating instances of Car and Motorcycle classes and invoking
their respective methods to display vehicle information.
throw and throws clauses
In Java, the throw and throws clauses are used in exception handling to manage runtime errors and
propagate exceptions to the calling methods or the JVM. Let's explore each of these clauses:

throw Clause:
The throw clause is used to explicitly throw an exception within a method or block of code. It is
typically used when a program encounters an error condition and needs to terminate execution
abruptly by raising an exception.

Syntax:

throw throwableInstance;

Example:

public void checkAge(int age) {

if (age < 0) {

throw new IllegalArgumentException("Age cannot be negative");

In this example, the checkAge method throws an IllegalArgumentException if the provided age is
negative.

throws Clause:
The throws clause is used in method declarations to specify the types of exceptions that the method
may throw. It informs the caller that the method might throw certain exceptions, and the caller is
responsible for handling them.

Syntax:

void methodName() throws ExceptionType1, ExceptionType2, ... {

// Method implementation

Example:

public void readFile() throws IOException {

// Code that may throw IOException

}
In this example, the readFile method declares that it may throw an IOException during its execution.
The caller of this method must handle or propagate this exception.

Differences:

• throw is used to explicitly throw an exception within a method, while throws is used in method
declarations to specify the exceptions that the method might throw.

• throw is followed by an instance of an exception that is being thrown, whereas throws is


followed by a list of exception types separated by commas.

When to Use:

• Use throw when you want to raise a specific exception based on a certain condition or error.

• Use throws in method declarations to indicate that the method may potentially throw checked
exceptions, and the calling code should handle or propagate them.

User-defined exceptions:
User-defined exceptions, also known as custom exceptions, allow developers to create their own
exception types to handle specific error conditions that are not covered by built-in Java exceptions. By
defining custom exceptions, developers can provide more meaningful error messages and better
organize their exception handling logic. Here's how you can create and use user-defined exceptions in
Java:

Creating a User-Defined Exception:


To create a user-defined exception in Java, you typically create a new class that extends one of the
existing exception classes, such as Exception or RuntimeException. You can then add constructors and
methods to customize the behavior of your exception.

// Custom exception class

public class CustomException extends Exception {

// Constructor with a message

public CustomException(String message) {

super(message);

Using the Custom Exception:

Once you have defined your custom exception, you can use it in your code by throwing instances of it
when appropriate.

public class Example {


public static void main (String [] args) {

try {

// Simulating a condition that triggers the custom exception

throw new CustomException("This is a custom exception message");


} catch (CustomException e) {

// Handling the custom exception

System.out.println("Custom exception caught: " + e.getMessage());

In this example:

• create an instance of CustomException and throw it within a try-catch block.

• In the catch block, we catch the custom exception and handle it by printing the exception
message.

When to Use User-Defined Exceptions:

• Use user-defined exceptions when you encounter specific error conditions in your application
that are not adequately represented by existing Java exceptions.

• Use them to provide more descriptive error messages and improve the clarity and
maintainability of your code.

• They are particularly useful for handling domain-specific errors or enforcing business rules in
your application.

Create a customized exception and also make use of all the 5 exception keywords

// Custom exception class

class InvalidAgeException extends Exception {

// Constructor with a message

public InvalidAgeException(String message) {

super(message);

// Class demonstrating exception handling

public class ExceptionDemo {

// Method that throws the custom exception

public static void checkAge(int age) throws InvalidAgeException {


if (age < 0) {

throw new InvalidAgeException("Age cannot be negative");

// Main method

public static void main (String [] args) {

try {

// Method call that may throw the custom exception

checkage (-5);

} catch (InvalidAgeException e) {

// Catch block to handle the custom exception

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

} finally {

// Finally block to perform cleanup or finalization

System.out.println("Finally block executed");

In this example:

1. define a custom exception InvalidAgeException, which extends Exception.

2. create a method checkAge(int age) that throws InvalidAgeException if the provided age is
negative.

3. In the main method, we invoke checkAge(-5) within a try block.

4. catch the InvalidAgeException in the catch block and handle it by printing the exception
message.

5. include a finally block that always executes, regardless of whether an exception is thrown or
caught. It is commonly used for cleanup or finalization tasks.
The String Buffer Class
In Java, the StringBuffer class is a mutable sequence of characters. It is similar to the String class, but
unlike String, StringBuffer objects can be modified after they are created. This makes StringBuffer
suitable for situations where you need to manipulate strings dynamically. Here's an overview of the
StringBuffer class:

Creating a StringBuffer Object:


create a StringBuffer object using its constructors:

StringBuffer buffer1 = new StringBuffer(); // Empty StringBuffer with default capacity (16 characters)

StringBuffer buffer2 = new StringBuffer("Hello"); // StringBuffer initialized with a string

StringBuffer buffer3 = new StringBuffer(20); // StringBuffer with specified capacity

StringBuffer Methods:

StringBuffer provides various methods for manipulating and accessing the content of the buffer:

1. Appending and Inserting:

• append(String str): Appends the specified string to the end of the buffer.

• insert(int offset, String str): Inserts the specified string at the specified position.

2. Deleting and Replacing:

• delete(int start, int end): Deletes characters from the buffer between the specified
start and end indices.

• replace(int start, int end, String str): Replaces characters in the buffer with the
specified string.

3. Other Operations:

• length(): Returns the length (number of characters) in the buffer.

• capacity(): Returns the current capacity of the buffer.

• charAt(int index): Returns the character at the specified index.

• substring(int start): Returns a new String that contains a subsequence of characters


from the buffer.

• substring(int start, int end): Returns a new String that contains a subsequence of
characters from the buffer.

4. Modifying Buffer:
• setLength(int newLength): Sets the length of the buffer. If the new length is greater
than the current length, null characters are appended to the end. If the new length is
less than the current length, the buffer is truncated.

StringBuffer vs. StringBuilder:

• StringBuffer is thread-safe (synchronized), making it suitable for use in multi-threaded


environments where multiple threads may access the buffer concurrently.

• StringBuilder is similar to StringBuffer but is not thread-safe. It offers better performance in


single-threaded environments due to lack of synchronization.

Example:

StringBuffer buffer = new StringBuffer("Hello");

buffer.append(" World");

buffer.insert(5, "Java ");

System.out.println(buffer); // Output: Hello Java World

Tokenizer:
In Java, the StringTokenizer class is used to break a string into tokens (smaller parts) based on a
specified delimiter. It's a legacy class and has been largely replaced by the String.split() method and
regular expressions for tokenization tasks. However, StringTokenizer can still be useful in certain
scenarios. Here's how you can use StringTokenizer:

Creating a StringTokenizer Object:


Create a StringTokenizer object by providing the string to be tokenized and optionally specifying the
delimiter characters.

StringTokenizer tokenizer = new StringTokenizer("Hello,World,Java", ",");

StringTokenizer Methods:

1. hasMoreTokens():

• Returns true if there are more tokens available, otherwise returns false.

while (tokenizer.hasMoreTokens()) {

// Process tokens

2. nextToken():

• Returns the next token from the string.

String token = tokenizer.nextToken();

3. countTokens():

• Returns the number of tokens remaining in the tokenizer's string.


int count = tokenizer.countTokens();

Example:

StringTokenizer tokenizer = new StringTokenizer("Hello,World,Java", ",");

while (tokenizer.hasMoreTokens()) {

String token = tokenizer.nextToken();

System.out.println("Token: " + token);

Output:

Token: Hello

Token: World

Token: Java

Write a java program to produce the tokens from given long string.
import java.util.StringTokenizer;
public class TokenizerExample {
public static void main (String [] args) {
// Given long string
String longString = "This is a long string with multiple words and punctuation. "
+ "It contains various tokens that we want to extract.";
// Creating a StringTokenizer object with space as delimiter
StringTokenizer tokenizer = new StringTokenizer(longString);
// Iterating through tokens and printing them
System.out.println("Tokens from the given long string:");
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
System.out.println(token);
}
}
}
Applets
Applets are small Java programs that are primarily used to provide interactive content within web
browsers. They were a popular technology in the early days of the internet for creating dynamic and
interactive web pages. However, their usage has declined significantly due to security concerns and
advancements in web technologies.

Here's a basic overview of applets:

1. Applet Structure:

• An applet is a Java class that extends the java.applet.Applet class or implements the
javax.swing.JApplet interface.

• It typically includes methods such as init(), start(), stop(), and destroy() to handle its
lifecycle events.

2. Embedding Applets:

• Applets are embedded within HTML pages using the <applet> tag or the <object> tag.

Example:

<applet code="MyApplet.class" width="300" height="200">

Your browser does not support Java applets.

</applet>

3. Applet Lifecycle:

• init (): Called when the applet is initialized, typically used for initialization tasks such
as setting up GUI components.

• start (): Called when the applet is started or activated, such as when the web page
containing the applet is visited.

• stop (): Called when the applet is stopped or deactivated, such as when the user
navigates away from the web page.

• destroy (): Called when the applet is destroyed, typically used for cleanup tasks.

4. Applet Security:

• Applets run within a sandbox environment provided by the Java Runtime Environment
(JRE), which restricts their access to system resources for security reasons.

• Due to security vulnerabilities, modern web browsers have deprecated or disabled


support for Java applets, and many have removed support altogether.

5. Alternatives to Applets:
• Due to the decline in support for Java applets, alternative technologies such as HTML5,
JavaScript, and CSS are now used to create dynamic and interactive web content.

• For client-side interactivity, JavaScript frameworks like React, Angular, and Vue.js are
widely used.

Example:

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

public void paint (Graphics g) {

g.drawString("Hello, World!", 20, 20);

In this example:

• create a class named SimpleApplet that extends the Applet class provided by the java.applet
package.

• override the paint() method, which is called automatically by the applet framework to paint
the applet's graphical content.

• Inside the paint() method, we use the Graphics object (g) to draw the string "Hello, World!"
at coordinates (20, 20) on the applet.

To run this applet, you need to compile the Java source code into bytecode (SimpleApplet.class) and
embed it in an HTML file.

<!DOCTYPE html>

<html>

<head>

<title>Simple Applet Example</title>

</head>

<body>

<applet code="SimpleApplet.class" width="200" height="200">

Your browser does not support Java applets.

</applet>

</body>

</html>
Save the HTML file in the same directory as the compiled SimpleApplet.class file, and open the HTML
file in a web browser that supports Java applets. See the text "Hello, World!" displayed within the
applet area.

Life cycle of applet and Security concerns:

Life Cycle of an Applet:


The life cycle of an applet consists of several stages, from initialization to destruction:

1. Initialization (init()):

• The init() method is called when the applet is first loaded into memory.

• It is typically used for initializing variables, setting up GUI components, and other one-
time initialization tasks.

2. Starting (start()):

• The start() method is called after the init() method and whenever the applet needs to
be started or restarted.

• It is invoked when the applet becomes visible on the screen or when the user returns
to the web page containing the applet.

3. Running:

• While the applet is running, user interaction and event handling take place.

• The paint() method is called whenever the applet needs to be redrawn, such as when
it is first displayed or when it is resized.
4. Stopping (stop()):

• The stop() method is called when the applet needs to be stopped or deactivated.

• It is invoked when the user navigates away from the web page containing the applet
or when another window obscures the applet's window.

5. Destroying (destroy()):

• The destroy() method is called when the applet is about to be destroyed and removed
from memory.

• It is typically used for releasing resources, closing connections, and performing


cleanup tasks.

Security Concerns:
Java applets, while once popular for creating interactive web content, have largely fallen out of favor
due to security concerns. Some of the main security concerns associated with Java applets include:

1. Sandbox Restrictions:

• Java applets run in a restricted environment known as the sandbox, which limits their
access to system resources such as files, network connections, and user input/output.

2. Vulnerabilities:

• Historically, Java applets have been prone to security vulnerabilities, including remote
code execution, privilege escalation, and information disclosure.

3. Obsolete Technology:

• Modern web browsers have deprecated or removed support for Java applets due to
security concerns and the availability of alternative technologies such as HTML5,
JavaScript, and CSS for creating interactive web content.

4. User Consent:

• Even when Java applets were widely supported, running them required explicit user
consent and often triggered security warnings, leading to a poor user experience.

You might also like