Java Programming Unit-II
Java Programming 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.
1. Data Types:
• Primitive Data Types: These are the most basic data types built into the Java
language.
• Reference Data Types: These data types are non-primitive and are created
using predefined classes or user-defined classes.
• Arrays
• Objects
• Strings
2. Literals:
• Variables must be declared with a data type before they can be used.
• int age;
• double salary;
• boolean isStudent;
• char grade;
4. Variable Initialization:
• Must begin with a letter (A-Z or a-z), currency character ($) or underscore
(_).
• Case-sensitive.
7. Variable Scope:
• The scope of a variable refers to the part of the program where the variable is
accessible.
• 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:
• 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.
• Java provides a set of predefined wrapper classes for each primitive data type:
• Java automatically converts primitive data types into their corresponding wrapper
classes when needed. This process is called autoboxing.
• 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
• 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:
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:
• Arrays are declared using square brackets [] after the data type.
Example:
int [] numbers; // Declaration numbers = new int [5]; // Initialization with size 5
Example:
2. Accessing Elements:
• Syntax: arrayName[index]
Example:
3. Array Length:
Example:
{ System.out.println(numbers[i]); }
5. Multidimensional Arrays:
Example:
6. Arrays Class:
• The java.util.Arrays class provides utility methods for working with arrays, such as
sorting and searching.
• 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 (+):
Example:
2. Subtraction (-):
Example:
3. Multiplication (*):
Example:
4. Division (/):
• If both operands are integers, the result is an integer, and any fractional part is
truncated.
Example:
5. Modulus (%):
Example:
6. Increment (++):
7. Decrement (--):
Example:
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:
Example:
2. Logical OR (||):
• Returns true if at least one of the operands is true; otherwise, it returns false.
Example:
• 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:
Example:
int result = 5 & 3; // result is 1 // 5 in binary: 101 // 3 in binary: 011 // Bitwise AND: 001
5. Bitwise OR (|):
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)
• if-else Statement:
if (condition)
• else-if Ladder:
• Nested if Statements:
2. Switch Statement:
switch (expression)
3. Loops:
• for Loop:
• while Loop:
while (condition) { // code block to be executed }
• do-while Loop:
4. Branching Mechanisms:
• 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).
catch (ExceptionType e) {
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:
// Fields (variables)
// Constructors
// Methods
2. Fields (Variables):
• They can be of any data type, including primitive types, reference types, or other
classes.
Example:
String model;
int year;
double price;
3. Constructors:
• They have the same name as the class and do not have a return type.
Example:
String model;
int year;
double price;
this.model = model;
this.year = year;
this.price = price;
4. Methods:
Example:
String model;
int year;
double price;
Instances (Objects):
1. Definition:
• It represents a specific entity with its own unique state and behavior.
2. Instantiation:
• Instantiation is the process of creating an instance of a class using the new keyword.
Example:
3. Accessing Members:
• You can access fields and methods of an object using the dot (.) operator.
Example:
System.out.println(myCar.model);
myCar.displayInfo();
• Four access modifiers: public, protected, default (no modifier), and private.
Example:
// Method implementation
}
2. Non-Access Modifiers:
Example:
1. Definition:
• An anonymous inner class is a class without a name that is declared and instantiated
at the same time.
Syntax:
};
2. Example:
};
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.
Syntax:
2. Implementing Interfaces:
Syntax:
// Method implementations
3. Default Methods:
• Classes that implement the interface can choose to override the default method.
Syntax:
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:
Syntax:
2. Abstract Method:
Example:
3. Concrete Method:
• Concrete methods can access fields and other methods of the abstract class.
Example:
// Method implementation
• Subclasses must provide implementations for all abstract methods inherited from
the abstract class.
Example:
// 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:
• 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:
// Subclass members
• Public and protected members of the superclass are 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.
@Override
• Use the super () keyword to call the superclass constructor from the subclass
constructor.
Example:
public Subclass () {
super ();
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 {
// Constructor
this.brand = brand;
this.year = year;
// Getter methods
return brand;
return year;
// Subclass: Car
// Constructor
this.numberOfDoors = numberOfDoors;
// Subclass: Motorcycle
class Motorcycle extends Vehicle {
// Constructor
this.type = type;
// Main class
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:
if (age < 0) {
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:
// Method implementation
Example:
}
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.
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:
super(message);
Once you have defined your custom exception, you can use it in your code by throwing instances of it
when appropriate.
try {
In this example:
• In the catch block, we catch the custom exception and handle it by printing the exception
message.
• 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
super(message);
// Main method
try {
checkage (-5);
} catch (InvalidAgeException e) {
} finally {
In this example:
2. create a method checkAge(int age) that throws InvalidAgeException if the provided age is
negative.
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:
StringBuffer buffer1 = new StringBuffer(); // Empty StringBuffer with default capacity (16 characters)
StringBuffer Methods:
StringBuffer provides various methods for manipulating and accessing the content of the buffer:
• 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.
• 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:
• 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.
Example:
buffer.append(" 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:
StringTokenizer Methods:
1. hasMoreTokens():
• Returns true if there are more tokens available, otherwise returns false.
while (tokenizer.hasMoreTokens()) {
// Process tokens
2. nextToken():
3. countTokens():
Example:
while (tokenizer.hasMoreTokens()) {
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.
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>
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.
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;
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>
</head>
<body>
</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.
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.
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.