Java All Unit_removed
Java All Unit_removed
By confining the
code within the sandbox, the model provides a layer of protection against
malicious actions.
The sandbox model is particularly useful when executing untrusted code, such
as applets in web browsers or code from unknown sources. It allows for the
execution of potentially risky code while mitigating the risks and maintaining the
overall security of the system.
It's worth noting that the effectiveness of the sandbox model relies on proper
configuration, adherence to security best practices, and regular updates to
address potential vulnerabilities in the JVM.
UNIT 2
Java Fundamentals: Data Types, Literals, and Variables
Java is a statically-typed programming language, which means that you need to
declare the type of a variable before using it. Java provides several built-in data
types to store different kinds of values. Let's explore the fundamentals of data
types, literals, and variables in Java:
Data Types:
Java has two categories of data types: primitive types and reference types.
1. Primitive Types:
JAVA 23
2. Reference Types:
Literals:
Literals are constant values that are directly written into your code. They
represent specific values of different data types.
For example:
Variables:
Variables are named memory locations used to store data. Before using a
variable, you must declare it with its data type. Here's the syntax to declare a
variable:
dataType variableName;
For example:
int age;
double salary;
boolean isStudent;
JAVA 24
For example:
Once a variable is declared, you can assign new values to it using the
assignment operator (=):
variableName = newValue;
For example:
age = 30;
salary = 5500.0;
isStudent = false;
Java supports type inference with the introduction of the var keyword in Java
10. It allows the compiler to infer the data type based on the assigned value.
For example:
Variables can be used in expressions and can be reassigned with new values
throughout the program.
Remember to follow the naming conventions for variables, such as starting with
a lowercase letter and using camel case (e.g., myVariable).
Understanding data types, literals, and variables is crucial for writing Java
programs. It enables you to store and manipulate different kinds of data in your
applications.
Wrapper Classes:
In Java, wrapper classes are used to represent the primitive data types as
JAVA 25
objects. They provide a way to encapsulate primitive values and provide
additional functionality through methods defined in the wrapper class. The
wrapper classes are part of the java.lang package and include the following:
Wrapper classes are commonly used when you need to perform operations such
as converting a primitive type to a string, parsing a string to a primitive type, or
using collections that require objects rather than primitives.
For example, to convert an int to a String, you can use the Integer wrapper
class:
Arrays:
Arrays in Java are used to store multiple elements of the same type. They
provide a way to work with collections of values in a structured manner. Here are
some key points about arrays in Java:
You specify the data type followed by the variable name and square
brackets indicating the array dimensions.
JAVA 26
// Declaration and initialization
int[] numbers = {1, 2, 3, 4, 5};
You can retrieve or modify the value at a specific index using the array
variable and the index in square brackets.
1. Array Length:
1. Multidimensional Arrays:
The enhanced for loop (for-each loop) allows iterating over the elements
of an array without explicitly using the index.
JAVA 27
for (int number : numbers) {
System.out.println(number);
}
Arrays provide a convenient way to work with collections of values in Java. They
allow efficient storage and retrieval of data and are extensively used in various
programming scenarios.
Operators
1. Arithmetic Operators:
JAVA 28
int count = 5;
count++; // count is now 6
count--; // count is now 5
2. Assignment Operators:
Assignment (=): Assigns the value of the right operand to the left
operand.
Compound Assignment Operators (e.g., +=, -=, *=, /=): Performs the
operation and assigns the result to the left operand.
int value = 5;
value += 3; // value is now 8
3. Comparison Operators:
Greater than (>), Less than (<), Greater than or equal to (>=), Less than
or equal to (<=): Compare the values of two operands.
4. Logical Operators:
JAVA 29
boolean result = (true && false); // result is false
Left Shift (<<): Shifts the bits of the left operand to the left by a specified
number of positions.
JAVA 30
Right Shift (>>): Shifts the bits of the left operand to the right by a specified
number of positions.
Control of Flow
Control Flow in Java refers to the order in which statements are executed in a
program. It allows you to make decisions, repeat statements, and break the
normal flow of execution. There are several constructs in Java that help you
control the flow of your program. Here are the main control flow constructs:
1. Conditional Statements:
if (condition) {
// code to be executed if the condition is true
} else {
// code to be executed if the condition is false
}
JAVA 31
switch (expression) {
case value1:
// code to be executed if expression matches value1
break;
case value2:
// code to be executed if expression matches value2
break;
default:
// code to be executed if expression doesn't match any case
}
2. Looping Statements:
while (condition) {
// code to be executed as long as the condition is true
}
Do-while loop: Similar to the while loop, but the condition is evaluated
after executing the block of code, so it always executes at least once.
do {
// code to be executed
} while (condition);
3. Jump Statements:
JAVA 32
Break statement: Terminates the execution of a loop or switch statement
and transfers control to the next statement after the loop or switch.
break;
Continue statement: Skips the remaining code within a loop and moves
to the next iteration.
continue;
return value;
4. Branching Statements:
if (condition1) {
// code to be executed if condition1 is true
} else if (condition2) {
// code to be executed if condition2 is true
} else {
// code to be executed if none of the conditions are true
}
These control flow constructs give you the ability to make decisions, repeat
code, and alter the flow of execution in your Java programs. By using these
constructs effectively, you can create programs that perform different actions
based on various conditions and iterate over data structures efficiently.
JAVA 33
Classes and Instances
In Java, classes and instances are fundamental concepts of object-oriented
programming. Let's understand what they mean:
1. Classes:
It provides the definition of how objects of that class should behave and
interact with each other.
Classes are declared using the class keyword followed by the class
name.
// methods
void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
2. Instances (Objects):
It is created from a class using the new keyword, and each instance has
its own set of attributes (instance variables) and can perform actions
(invoke methods) defined in the class.
Multiple instances of the same class can exist, each with its own state
(values of attributes).
JAVA 34
Instances are created dynamically at runtime when the program needs
them.
person2.name = "Jane";
person2.age = 30;
Each instance has its own set of instance variables, and changes made
to one instance do not affect other instances.
By defining classes and creating instances, you can model and represent real-
world entities or concepts in your Java programs. Classes provide the structure,
and instances allow you to work with individual objects based on that structure.
private : The member can only be accessed within the same class.
JAVA 35
final : The member's value cannot be changed.
Anonymous inner classes are often used for event handling or defining
small, one-time-use classes.
3. Interfaces:
JAVA 36
A class implements an interface using the implements keyword and
provides implementations for all the methods declared in the interface.
interface Shape {
void draw(); // Abstract method declaration
}
4. Abstract Classes:
JAVA 37
In the example above, the Animal class is declared as abstract with an
abstract method sound() . The Cat class extends the Animal class and
provides an implementation for the sound() method.
Inheritance
Inheritance is a fundamental concept in object-oriented programming that allows
you to create new classes based on existing classes. It enables code reuse and
the establishment of hierarchical relationships between classes. Inheritance is
achieved through the process of deriving new classes from existing classes,
where the new classes inherit the properties and behavior of the existing
classes. Let's delve into the details of inheritance:
The superclass is the existing class from which the subclass is derived.
The subclass inherits all the non-private fields and methods from the
superclass and can add its own unique fields and methods.
2. Inheritance Syntax:
Here's an example:
JAVA 38
class Superclass {
// superclass members
}
3. Inherited Members:
The subclass can directly use the inherited members without redefining
them, unless they are overridden.
4. Overriding Methods:
To override a method, the method in the subclass must have the same
signature (name, return type, and parameters) as the method in the
superclass.
class Superclass {
void display() {
System.out.println("Superclass method");
}
}
JAVA 39
5. Access Modifiers in Inheritance:
6. Inheritance Hierarchies:
The subclass inherits both the members of its immediate superclass and
all the members of the superclass hierarchy above it.
In Java, there are several types of inheritance that you can use to establish
relationships between classes. These types include:
1. Single Inheritance:
Example:
JAVA 40
class Superclass {
// superclass members
}
This is done to avoid ambiguity and complexities that can arise from
multiple inheritance.
Example:
interface Interface1 {
// interface1 members
}
interface Interface2 {
// interface2 members
}
3. Multilevel Inheritance:
Each class serves as the superclass for the next class in the hierarchy.
Example:
JAVA 41
class Superclass {
// superclass members
}
4. Hierarchical Inheritance:
Each subclass shares the properties and behavior of the superclass and
can add its own unique features.
Example:
class Superclass {
// superclass members
}
Example:
JAVA 42
class Superclass {
// superclass members
}
interface Interface1 {
// interface1 members
}
interface Interface2 {
// interface2 members
}
It's important to note that Java does not support direct multiple inheritance for
classes, but it allows for implementing multiple interfaces, achieving a similar
effect. The choice of inheritance type depends on the specific requirements and
design of your program.
1. throw Clause:
Syntax:
JAVA 43
throw exception;
Example:
2. throws Clause:
The throws clause is used in the method declaration to indicate that the
method may throw one or more types of exceptions.
When a method with a throws clause calls another method that throws a
checked exception, the calling method must handle or declare the
exception using its own throws clause.
Syntax:
Example:
In the example above, the readFile method declares that it may throw
an IOException . Any method calling readFile must either handle the
JAVA 44
IOException or declare it in its own throws clause.
The throw clause is used to raise exceptions explicitly, while the throws clause
is used to declare the exceptions that a method can throw. Together, they
facilitate exception handling and ensure that exceptions are appropriately caught
and handled in the program.
It's worth noting that checked exceptions (exceptions that are subclasses of
Exception but not subclasses of RuntimeException ) must be declared using the
throws clause or caught using a try-catch block, whereas unchecked exceptions
(subclasses of RuntimeException ) do not need to be declared or caught.
You can add additional fields, constructors, and methods to your custom
exception class as needed.
Example:
Once you have defined your custom exception class, you can throw
instances of that exception when necessary.
JAVA 45
Use the throw keyword followed by an instance of your custom
exception class to throw the exception.
Example:
Example:
try {
someMethod();
} catch (CustomException e) {
// Handle the custom exception
}
Example:
By creating your own exception classes, you can handle specific exceptional
situations in a more tailored and meaningful way. Custom exceptions allow you
JAVA 46
to communicate and handle exceptional conditions specific to your application
domain.
1. Creating a StringBuffer:
Example:
The append() method is used to add characters at the end of the existing
content.
Example:
JAVA 47
StringBuffer sb = new StringBuffer("Hello");
sb.append(" World"); // "Hello World"
sb.insert(5, ","); // "Hello, World"
sb.delete(5, 7); // "Hello World"
sb.replace(6, 11, "Java"); // "Hello Java"
method.
Example:
4. Thread Safety:
However, this thread safety comes at the cost of performance due to the
synchronization overhead.
If you don't require thread safety, you can use the non-thread-safe
alternative, StringBuilder , which provides similar functionality but without
the synchronization.
5. Performance Considerations:
JAVA 48
string and can be used in both single-threaded and multi-threaded scenarios.
Tokenizer
The StringTokenizer class in Java is used to break a string into smaller tokens or
parts, based on a specified delimiter. It provides a simple and convenient way to
tokenize strings. Here's an overview of the StringTokenizer class:
1. Creating a StringTokenizer:
To create a StringTokenizer object, you need to pass the input string and
the delimiter to its constructor.
Example:
2. Retrieving Tokens:
You can use the hasMoreTokens() method to check if there are more
tokens available in the input string.
The nextToken() method is used to retrieve the next token from the input
string.
Example:
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
// Process the token
}
3. Changing Delimiters:
You can change the delimiter by using the overloaded constructor or the
setDelimiter() method.
Example:
JAVA 49
String input = "Hello-World-Java";
StringTokenizer tokenizer = new StringTokenizer(input, "-");
4. Counting Tokens:
You can use the countTokens() method to get the total number of tokens
remaining in the tokenizer.
Example:
Example:
6. Retrieving Delimiters:
Example:
while (tokenizer.hasMoreTokens()) {
String token = tokenizer.nextToken();
if (tokenizer.hasMoreTokens()) {
String delimiter = tokenizer.nextDelimiter();
// Process the delimiter
}
}
JAVA 50
process delimited data or extract specific parts from a string.
However, note that the StringTokenizer class is considered legacy and has been
largely replaced by the String.split() method and regular expressions ( Pattern
and Matcher classes) for more advanced string parsing and splitting
requirements.
Applets
Applets are small Java programs that are designed to run within a web browser.
They were a popular way to add interactive content to web pages in the past, but
their usage has significantly decreased due to security concerns and the
emergence of alternative technologies. Nevertheless, understanding applets and
their lifecycle can provide insights into the history of web development. Let's
delve into the details of applets, their lifecycle, and security concerns:
1. Applets:
Applets are Java programs that are embedded in HTML web pages and
run in a sandboxed environment within a web browser.
Applets were rendered using the Java Applet Viewer or a web browser
with Java plugin support.
2. Applet Lifecycle:
JAVA 51
another page or closes the browser window.
3. Security Concerns:
JAVA 52
It's important to note that as of Java 11, the Java Plugin and Applet API have
been deprecated and removed from the Java Development Kit (JDK). Therefore,
applets are no longer supported in modern browsers.
Here are a couple of examples to illustrate the usage of applets and their
lifecycle:
import java.applet.Applet;
import java.awt.Graphics;
import java.applet.Applet;
import java.awt.Graphics;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
JAVA 53
addMouseListener(this);
}
JAVA 54