Java Sem
Java Sem
Prepared by
Prof. Anjana U
Assistant Professor
Dept. of Computer Applications
COURSE CONTENT
UNIT-1 [12 Hours]
Introduction: Basics of object-oriented programming, comparison of procedure-oriented and
object oriented programming paradigms; Difference between C and Java Programming
languages; Features of Java; Objects and classes in Java, Structure of a Java program; Data
Types, variables and operators in java; Control structures- Branching and looping; Methods &
Constructors in java; Java Development Kit (JDK); Built-in classes in Java; Math, Character,
String, String Buffer and Scanner; Wrapper classes; The abstract, static and final classes;
Casting objects; The instance of operator; Usage of this keyword; Arrays in Java.
UNIT-2 [11 Hours]
Inheritance: Super and subclasses; visibility modifiers; Types of Inheritance- single, multiple,
hierarchical and hybrid inheritance; the interface concept in Java, Polymorphism: Compile time
and run time polymorphisms – Method overloading and method overriding. Package: Types of
packages; the util, awt and swing packages; Creating and importing user-defined packages. I/O
programming: Standard I/O streams in Java; Types of streams – Based on the type of
Operations and the type of file.
UNIT-3 [11 Hours]
Event handling: Major events in Java; Two Event Handling mechanisms- Event classes and
Event Listener Interfaces; Mouse and keyboard events; GUI: Panels; Frames; Layout managers
– Flow, border and grid layouts; Buttons; Checkboxes; Radio buttons; Labels; Text fields; Text
areas; Combo boxes; Scroll bars; Sliders; Menu, Dialog boxes. Applet programming:
Comparison of applets and applications; Applet life cycle; Developing and running applets.
String handling: String construction, string length, special string operations, character
extraction, string comparison, modifying string and string buffers.
UNIT-4 [11 Hours]
Exception handling: Types of Java exception – checked and unchecked exceptions; Usage of
try-catch-finally blocks. Multithreading: comparison of multithreading and multitasking; Life
cycle of a thread; two ways of creating thread – by extending the Thread class and by
implementing the Runnable Interface, Thread synchronization. Advanced concepts:
Collections in Java; Introduction to JavaBeans and Java security manager, Importance of
generic programming in java with examples.
Reference Books
1. Ken Arnold, James Gosling, “The Java Programming Language, Fourth Edition,
Addison Wisely, 2005.
2. R Herbert Schildt, ‘The Complete Reference Java, 7th Edition, McGraw Hill, 2007.
TABLE OF CONTENTS
UNIT – I
INTRODUCTION TO JAVA, OBJECTS AND CLASSES
1. Introduction
2. Concept of classes and objects
3. Procedure oriented Vs Object oriented language
4. Features of Java
5. Structure of Java program
6. Data types, variables and operators
7. Control structures and its types
8. Methods and Constructors
9. JDK toolkit
10. Built-in classes and Wrapper classes.
11. The abstract, static and final classes and its usage.
12. The instance of operator
13. “this” keyword and its importance.
*******
1. Introduction: Java is a programming language and a platform. Java is a high level,
robust, object-oriented and secure programming language.Java was developed by Sun
Microsystems (which is now the subsidiary of Oracle) in the year 1995. James
Gosling is known as the father of Java. Before Java, its name was Oak. Since Oak was
already a registered company, so James Gosling and his team changed the name from
Oak to Java.It is owned by Oracle, and more than 3 billion devices run Java.
It is used for:
Mobile applications (specially Android apps)
Desktop applications
Web applications
Web servers and application servers
Games
Database connection
And much, much more!
2. Classes and Objects: In object oriented programming, object and class plays vital
role in programming. These are the two main pillars of OOP. Without object and
class, we cannot create a program in Java.
Class:
A class in Java is a blueprint or a template for creating objects. It defines the structure
and behavior (data members and methods) that the objects of the class will have.
Classes encapsulate data and methods into a single unit.
Syntax:
class ClassName {
// Data members (fields)
// Methods
}
Object:
Adding new data and functions is not easy. Adding new data and function is easy.
4. Features of Java :
Object-Oriented
Java is based on object-oriented programming principles like inheritance,
encapsulation, polymorphism, and abstraction.
Simple
Java is easy to learn and eliminates complexities like pointers and multiple
inheritance.
Secured
Java provides security through features like bytecode verification, no direct memory
access, and a secure runtime environment.
Platform Independent
Java is "write once, run anywhere" because Java programs run on the JVM, making it
platform-independent.
Robust
Java emphasizes strong memory management, exception handling, and type-checking
to avoid errors.
Portable
Java code can run on any machine without modifications, thanks to its platform
independence and use of the JVM.
Architecture Neutral
Java ensures consistent output regardless of hardware or operating system.
Dynamic
Java supports dynamic loading of classes and runtime linking of libraries.
Interpreted
Java bytecode is interpreted by the JVM, making it portable and platform-
independent.
High Performance
Java achieves better performance through Just-In-Time (JIT) compilation and
optimization techniques.
Multithreaded
Java supports multithreading to perform multiple tasks simultaneously, improving
performance.
Distributed
Java enables the creation of distributed applications with networking capabilities,
using APIs like RMI and EJB.
These features make Java a popular programming language for developing reliable,
scalable, and secure applications.
Documentation Section
The documentation section is an important section but optional for a Java
program. It includes basic information about a Java program. The information
includes the author's name, date of creation, version, program name, company
name, and description of the program. It improves the readability of the
program. Whatever we write in the documentation section, the Java compiler
ignores the statements during the execution of the program. To write the
statements in the documentation section, we use comments. The comments
may be single-line, multi-line, and documentation comments.
defined methods, variables, and constants. Every Java program has at least one
class that contains the main() method.
Class Variables and Constants
In this section, we define variables and constants that are to be used later in the
program. In a Java program, the variables and constants are defined just after
the class definition. The variables and constants store values of the parameters.
It is used during the execution of the program. We can also decide and define
the scope of variables by using the modifiers. It defines the life of the
variables.
Main Method Class
In this section, we define the main() method. It is essential for all Java
programs. Because the execution of all Java programs starts from the main()
method. In other words, it is an entry point of the class. It must be inside the
class. Inside the main method, we create objects and call the methods
Integer Types
Character Type
char (2 bytes): Stores a single character using Unicode (e.g., 'A', '1').
Boolean Type
Variables in Java : A variable is a container that stores data. Variables are created using a
data type.
Types of Variables:
Local Variables
Declared inside methods, constructors, or blocks.
Scope: Limited to the block in which it is declared.
Instance Variables
Declared inside a class but outside methods.
Each object of the class gets its own copy.
Static Variables
Declared with the static keyword.
Shared among all objects of the class.
Example:
int age = 25; // Local variable
double salary = 50000.50; // Instance variable
static String college = "RNSFGC"; // Static variable
Operators in Java
Operators are special symbols or keywords used to perform operations on variables and
values.
Types of Operators
Arithmetic Operators :Used for basic mathematical operations:
+ (Addition), - (Subtraction), * (Multiplication), / (Division), %
(Modulus).
Example:
int a = 10, b = 3;
System.out.println(a + b); // Output: 13
System.out.println(a % b); // Output: 1
Relational (Comparison) Operators: Compare values and return a boolean
result. ==, !=, >, <, >=, <=
Example:
int x = 5, y = 10;
System.out.println(x > y); // Output: false
Logical Operators : Used for logical operations: && (AND), || (OR), !
(NOT).
Example:
boolean a = true, b = false;
System.out.println(a && b); // Output: false
System.out.println(!a); // Output: false
Assignment Operators : Assign values to variables. =, +=, -=, *=, /=, %=
Example:
int num = 10;
num += 5; // num = num + 5;
System.out.println(num); // Output: 15
Unary Operators : Operate on a single operand:+, -, ++, --
Example:
int x = 10;
x++;
System.out.println(x); // Output: 11
Bitwise Operators :Work on bits: &, |, ^, ~, <<, >>.
Ternary Operator :Short-hand for if-else:
Syntax: condition ? expression1 : expression2;
Example:
int a = 10, b = 20;
int max = (a > b) ? a : b;
System.out.println(max); // Output: 20
7. Control Structures and its types:
Control structures determine the flow of program execution in a systematic manner.
Java provides three main types of control structures:
Sequential Control
Selection (Decision-Making) Control
Looping (Iteration) Control
Output:
Grade B
switch Statement: Selects one block of code to execute based on a matching
value.
Example:
public class SwitchExample {
public static void main(String[] args) {
int day = 3;
switch (day) {
case 1: System.out.println("Monday"); break;
case 2: System.out.println("Tuesday"); break;
case 3: System.out.println("Wednesday"); break;
default: System.out.println("Other Day");
}
}
}
Output:
Wednesday
Output:
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5
}
Where :
returnType: Data type of the value returned (e.g., int, void, etc.). Use void if
no value is returned.
methodName: The name used to call the method.
parameters: Inputs passed to the method (optional)
Types of Methods:
Constructors
A constructor is a special method used to initialize objects. It is automatically
invoked when an object is created.
Types of Constructors:
The JDK contains a private Java Virtual Machine (JVM) and a few other
resources such as an interpreter/loader (java), a compiler (javac), an archiver (jar),
a documentation generator (Javadoc), etc. to complete the development of a Java
Application.
JRE
JRE is an acronym for Java Runtime Environment. It is also written as Java RTE. The Java
Runtime Environment is a set of software tools which are used for developing Java
applications. It is used to provide the runtime environment. It is the implementation of JVM.
It physically exists. It contains a set of libraries + other files that JVM uses at runtime.
JVM
JVM (Java Virtual Machine) is an abstract machine. It is called a virtual machine because it
doesn't physically exist. It is a specification that provides a runtime environment in which
Java bytecode can be executed. It can also run those programs which are written in other
languages and compiled to Java bytecode.
Loads code
Verifies code
Executes code
Provides runtime environment
10. Built in and Wrapper classes:
Built-in Classes
These are classes provided by the Java Standard Library to simplify
programming.
Examples include String, Math, System, and Scanner.
Example:
public class BuiltInExample {
public static void main(String[] args) {
int num1 = 25;
double result = Math.sqrt(num1); // Using built-in Math class
System.out.println("Square root of " + num1 + " is: " + result);
}
Wrapper Classes
Wrapper classes convert primitive data types into objects.They are
part of the java.lang package.
Primitive types (like int, char) have corresponding wrapper classes:
Example:
Output :
Wrapper Object: 10
Primitive Value: 10
11. The abstract, static and final classes and its usage:
Abstract Classes
Static Classes
class OuterClass {
static class InnerStaticClass {
Final Classes
12. The “instance of operator” : The instanceof operator in Java is used to check
whether an object is an instance of a specific class or an interface. It is a type
comparison operator that returns true if the object is an instance of the specified class,
subclass, or interface. Otherwise, it returns false.
Syntax:
object instanceof ClassName
void display() {
System.out.println("Name: " + this.name); // Refers to the current object
}
}
UNIT- II
UNIT – II
INHERITANCE AND POLYMORPHISM
1. Concept of Inheritance
2. Superclass and subclass
3. Visibility modifiers
4. Types of Inheritance
5. The concept of Interface
6. Polymorphism and its types
7. Method Overloading and Overriding
8. Packages and its types
9. Creating and importing user defined packages
10. I/O programming- Streams and its types
*******
1 . Concept of Inheritance:
Inheritance is the mechanism in java by which one class is allow to inherit the features (fields
and methods) of another class. It is process of deriving a new class from an existing class. A
class that is inherited is called a superclass and the class that does the inheriting is called a
subclass. Inheritance represents the IS-A relationship, also known as parent-child
relationship. The keyword used for inheritance is extends
Syntax: class Subclass-name extends Superclass-name
{
//methods and fields
}
Advantages of Inheritance:
• Code reusability - public methods of base class can be reused in derived
classes
• Data hiding – private data of base class cannot be altered by derived class
• Overriding--With inheritance, we will be able to override the methods of the
base class in the derived class
Example:
class Animal {
void eat() {
System.out.println("Animal eats");
}
}
class Test {
public static void main(String[] args) {
Dog d = new Dog();
d.eat(); // inherited method from Animal
d.bark(); // Dog's own method
}
}
2. Superclass and Subclass:
Superclass: The class that is inherited from. It contains common attributes and
methods which are inherited by its subclasses.
Subclass: The class that inherits properties and methods from the superclass. A
subclass can override methods of the superclass to provide specific behavior.
Example:
class Vehicle {
void move() {
System.out.println("Vehicle moves");
}
}
1. Private: The access level of a private modifier is only within the class. It
cannot be accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It
cannot be accessed from outside the package. If you do not specify any access
level, it will be the default.
3. Protected: The access level of a protected modifier is within the package and
outside the package through child class. If you do not make the child class, it
cannot be accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed
from within the class, outside the class, within the package and outside the
package.
class Test {
class Car {
System.out.println("Starting engine");
class Test {
class Vehicle {
class Test {
class Car {
class Test {
4. Types of Inheritance:
Single Inheritance: In single inheritance, a sub-class is derived from only one super
class. It inherits the properties and behavior of a single-parent class. Sometimes, it is
also known as simple inheritance. In the below figure, ‘A’ is a parent class and ‘B’ is
a child class. The class ‘B’ inherits all the properties of the class ‘A’.
Example:
class Animal {
void eat() {
System.out.println("Eating food...");
}
}
class Animal {
void eat() {
System.out.println("Eating food...");
}
}
// Single Inheritance
class Animal extends LivingBeing {
void eat() {
System.out.println("Animal is eating...");
}
}
Important Note: Java does not support multiple inheritance with classes due to
potential ambiguity in method inheritance, but multiple inheritance can be achieved by
using interfaces.
Example:
interface Animal {
void sound();
System.out.println("Bark");
System.out.println("Meow");
a = new Cat();
}}
Built-in Packages
User-defined Packages
Built-in Packages
Java provides a number of built-in packages that contain classes and interfaces for
performing common tasks such as input/output, networking, utilities, etc. Some
commonly used built-in packages are:
java.util: Contains utility classes such as collections, date, and time handling
classes.
java.io: Provides classes for input and output operations.
java.lang: Contains fundamental classes, such as String, Math, System, and
Object.
java.net: Contains classes for networking operations like Socket, URL, and
HttpURLConnection
Example:
User-defined Packages:
A user-defined package is created by the programmer to group related classes and
interfaces. To define a user-defined package, we use the package keyword.
Create the package: Define a package using the package keyword at the top of
the source file.
Create classes: Create classes within the package.
Import the package: Use the import keyword in other classes to access the
classes and interfaces of the package.
To create a package is quite easy: simply include a package command as the first
statement in a Java source file.
Any classes declared within that file will belong to the specifiedpackage.
The package statement defines a name space in which classes are stored.
If you omit the package statement, the class names are put into the
default package, which has no name.
This is the general form of the package statement.
package pkg;
Java uses file system directories to store packages.For example, the following
statement creates a package called MyPackage:
package MyPackage;
classes you declare to be part of MyPackage must be stored in a
directory called MyPackage.
Remember that case is significant, and the directory name must match the
package name exactly.
More than one file can include the same package statement. The package
statement simply specifies to which package the classes defined in a file
belong.
Example:
/*Mainclass.java*/
import shape.Square;
import shape.Triangle;
import shape.Circle;
square.getData((float)5.5);
triangle.getData((double)20.56,(double)23.90);
circle.getData((double)5.5);
/*Square.java*/
package shape;
float side;
side=temp;
return (side*side);
/*Triangle.java*/
package shape;
double base;
double height;
base=temp1;
height=temp2;
return ((1.0/2.0)*(base*height));
/*Circle.java*/
package shape;
double radius;
double height;
radius=temp;
return ((3.1427*(2.0*radius)*(2.0*radius))/4.00);}}
Example:
import java.io.*;
try {
int i;
fout.write(i);
fin.close();
fout.close();
} catch (IOException e) {
}}}
UNIT- III
UNIT – III
EVENT HANDLING AND APPLET LIFE CYCLE
1. Concept of Event handling
2. Two Event handling mechanisms
3. Event classes and Interfaces
4. GUI and Layout Managers
5. Applet Programming
6. Applet Vs Application programming
7. Applet lifecycle
8. Developing and running applets
9. String Handling and its operations
*******
1 . Concept of Event Handling:
Event handling in Java is a mechanism that allows a program to respond to user
actions such as clicks or by presses or system-generated events. This is an essential
part of creating interactive applications, especially in graphical user interfaces (GUIs).
The components of Event handling are:
Event: An occurrence like a button press or a mouse move.
Event Source: The component that generates the event (e.g., a button).
Event Listener: An object that listens for and handles events using
specific methods
The java.awt.event package can be used to provide various event classes.
Classification of Events
Foreground Events: Foreground events are the events that require user
interaction to generate, i.e., foreground events are generated due to interaction
by the user on components in Graphic User Interface (GUI). Interactions are
nothing but clicking on a button, scrolling the scroll bar, cursor moments, etc.
Background Events: Events that don’t require interactions of users to
generate are known as background events. Examples of these events are
operating system failures/interrupts, operation completion, etc.
2 . Two Event Handling Mechanisms:
Delegation Event model: It has source and Listeners. The Delegation Event model is
defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the
system.The GUI programming is inherently event-driven; whenever a user initiates an
activity such as a mouse activity, clicks, scrolling, etc., each is known as an event that
Source: Events are generated from the source. There are various sources like buttons,
checkboxes, list, menu-item, choice, scrollbar, text components, windows, etc., to
generate events.
Listeners: Listeners are used for handling the events generated from the source. Each
of these listeners represents interfaces that are responsible for handling events.
Steps involved in the Event Delegation model are:
1. We shold add apprproiate listener component. This is donw with the
help of “addxxxListener()” method, Similarly to remove a listener
from the component , we can use “removexxxListener()” method.
2. Implement the methods of the listener, especially the method which
handles the event
3. When an event is generated on the component, then the method in
step2 will be executed and the event is handled.
Important Event Classes and Interface
Example:
import java.awt.*;
import java.awt.event.*;
});
setVisible(true);
}
public static void main(String[] args) {
new MouseEventExample();
}
}
KEY EVENTS: Key events occur when a user interacts with the keyboard, such as pressing,
releasing, or typing a key. The listener methods for Key Events are:
keyPressed(KeyEvent e): Invoked when a key is pressed.
keyReleased(KeyEvent e): Invoked when a key is released.
keyTyped(KeyEvent e): Invoked when a key is typed (press and release).
Example:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class KeyEventExample extends JFrame {
public KeyEventExample() {
setTitle("Key Event Example");
setSize(400, 300);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JLabel label = new JLabel("Type something on the keyboard!", JLabel.CENTER);
label.setFont(new Font("Arial", Font.BOLD, 16));
add(label);
// Add KeyListener to handle key events
addKeyListener(new KeyAdapter() {
@Override
public void keyPressed(KeyEvent e) {
label.setText("Key Pressed: " + e.getKeyChar());
}
@Override
f.setSize(400, 300);
f.setVisible(true);
}
}
Common Methods:
import java.awt.*;
import java.awt.event.*;
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("Button Clicked!");
}
});
frame.add(btn);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Common Methods:
Example:
import java.awt.*;
f.add(label);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}
TextField: A TextField is a single-line text input field where users can type data.
Syntax
Common Methods:
Example:
import java.awt.*;
import java.awt.event.*;
f.add(tf);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}
TextArea : A TextArea is a multi-line text input area that can hold a large amount of
text.
Syntax
Common Methods:
Example:
import java.awt.*;
f.add(ta);
f.setSize(400, 300);
f.setLayout(null);
f.setVisible(true);
}
}
Common Methods:
Example:
import java.awt.*;
import java.awt.event.*;
checkbox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
System.out.println("Checkbox state: " + (checkbox.getState() ?
"Checked" : "Unchecked"));
}
});
frame.add(checkbox);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
List : A List is a GUI component that allows users to select one or more items from a
list of options.
Syntax
Common Methods:
Example:
import java.awt.*;
list.add("Option 1");
list.add("Option 2");
list.add("Option 3");
f.add(list);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
}
}
Choice : A Choice is a dropdown list where the user can select one option from a list
of choices.
Syntax
Common Methods:
Example:
import java.awt.*;
choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
f.add(choice);
f.setSize(300, 200);
f.setLayout(null);
f.setVisible(true);
}
}
Example:
import java.awt.*;
panel.add(label);
frame.add(panel);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
ComboBox (Choice): A Choice (ComboBox) is a dropdown list that allows users to
select one option from a list of choices.
Syntax
Common Methods:
Example:
import java.awt.*;
choice.add("Option 1");
choice.add("Option 2");
choice.add("Option 3");
frame.add(choice);
frame.setSize(300, 200);
frame.setLayout(null);
frame.setVisible(true);
}
}
Scroll Bars (Scrollbar) : A Scrollbar is used to provide a vertical or horizontal
scrolling mechanism for content that exceeds the visible area.
Syntax
Common Methods:
Example:
import java.awt.*;
frame.add(scrollbar);
frame.setSize(400, 300);
frame.setLayout(null);
frame.setVisible(true);
}
}
Menus (Menu, MenuBar, MenuItem) : Menus allow users to select options from a list
of commands or actions. It includes MenuBar (a container for menus), Menu (a
menu containing items), and MenuItem (individual items in a menu).
Syntax
Common Methods:
Example:
import java.awt.*;
import java.awt.event.*;
menu.add(openItem);
menu.add(exitItem);
menuBar.add(menu);
Common Methods:
Example:
import java.awt.*;
import java.awt.event.*;
dialog.add(closeButton);
dialog.setVisible(true); // Show dialog
}
}
TextArea: A TextArea is a multi-line text input area that can hold a large amount of
text. It is used when the user needs to enter or display multiple lines of text, such as in
a note-taking app or an editor.
Syntax
Common Methods:
Example:
import java.awt.*;
// Frame settings
frame.setSize(400, 300);
frame.setLayout(null); // Use null layout to manually set position
frame.setVisible(true); // Display the frame
}
}
5. Applet Programming: An Applet is a special type of Java program that runs inside a web
browser or applet viewer, rather than being run as a standalone application. Applets are
mainly used to provide interactive features and graphics in web pages. They are written in the
Java programming language and are executed on the client side, meaning that the browser
needs to have a Java runtime environment (JRE) installed to execute them.
6 . Applet Vs Appliation Program :
7. Applet Lifecycle: The applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of its application. It
basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute.
Methods of Applet Life Cycle
There are five methods of an applet life cycle, and they are:
init(): The init() method is the first method to run that initializes the applet. It can be
invoked only once at the time of initialization. The web browser creates the initialized
objects, i.e., the web browser (after checking the security settings) runs the init()
method within the applet.
start(): The start() method contains the actual code of the applet and starts the applet.
It is invoked immediately after the init() method is invoked. Every time the browser is
loaded or refreshed, the start() method is invoked. It is also invoked whenever the
applet is maximized, restored, or moving from one tab to another in the browser. It is
in an inactive state until the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that page,
the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage is
closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
String Creation:
Example:
String str1 = "Hello"; // String literal
String str2 = new String("World"); // Using new keyword
Replacing Characters:
Converting Case:
Trimming Whitespaces: removes any leading and trailing whitespace from the
string.
String Comparison:
Splitting a String:
// Trim spaces
String trimmed = str.trim();
System.out.println("Trimmed: '" + trimmed + "'"); // Output: 'Hello
World'
// Convert to lowercase
String lower = str.toLowerCase();
System.out.println("Lowercase: " + lower); // Output: hello world
// Substring
String sub = str.substring(1, 5);
For internal circulation only 60
Subject Name: OOPs Using Java
// String concatenation
String newStr = str.concat(" - Java");
System.out.println("Concatenated: " + newStr); // Output: Hello
World - Java
// Replace
String replaced = str.replace("World", "Java");
System.out.println("Replaced: " + replaced); // Output: Hello Java
// Split
String[] words = str.split(" ");
System.out.println("Split: ");
for (String word : words) {
System.out.println(word); // Output: "Hello", "World"
}
}}
Output:
Length: 13
Trimmed: 'Hello World'
Lowercase: hello world
Substring: ello
Concatenated: Hello World - Java
Replaced: Hello Java
Split:
Hello
World
UNIT- IV
UNIT – IV
EXCEPTION HANDLING AND THREADS
1. Concept of Exception handling
2. Checked and Unchecked Exception
3. Try-catch and finally blocks
4. Multi-threading
5. Multi-threading Vs Multi-tasking
6. Life Cycle of thread
7. Various methods to create thread
8. Thread Synchronization
9. Advanced concepts of Java- Introduction to JavaBeans, Security Manager
10. Importance of generic programming in java
********
2 . Types of Exceptions:
Checked Exceptions:
These exceptions are not checked at compile-time, meaning the programmer is not
required to handle them. They usually indicate programming bugs (like logic
errors or invalid operations).
KEYWORD DESCRIPTION
One of the primary mechanisms for handling exceptions in Java is the try-catch block.
The try block contains the code that may throw an exception, and the catch block is
used to handle the exception if it occurs. Here's a basic Example:
try {
} catch (ExceptionType e) {
You can handle multiple types of exceptions by providing multiple catch blocks, each
catching a different type of exception. This allows you to tailor your exception
handling logic based on the specific type of exception thrown. Here's an Example:
try {
} catch (IOException e) {
// Handle IOException
} catch (NumberFormatException e) {
// Handle NumberFormatException
} catch (Exception e) {
Multiple threads share the same Multiple processes run in their own
Concurrency
memory space and resources of a separate memory spaces and
Level
single process. resources.
Threads within a process share the Each process operates in its own
Resource
same resources, such as memory memory space and does not directly
Sharing
and file handles. share resources with others.
6 . Life cycle of Thread: A thread in Java goes through several stages during its lifetime:
A thread in Java at any point of time exists in any one of the following states. A thread lies
only in one of the shown states at any instant:
New State: When a new thread is created, it is in the new state. The thread has not
yet started to run when the thread is in this state. When a thread lies in the new state,
its code is yet to be run and hasn’t started to execute.
Runnable State: A thread that is ready to run is moved to a runnable state. In this
state, a thread might actually be running or it might be ready to run at any instant of
time. It is the responsibility of the thread scheduler to give the thread, time to run.
Blocked State: The thread will be in blocked state when it is trying to acquire a
lock but currently the lock is acquired by the other thread. The thread will move
from the blocked state to runnable state when it acquires the lock.
Waiting State: The thread will be in waiting state when it calls wait() method or
join() method. It will move to the runnable state when other thread will notify or
that thread will be terminated.
Timed Waiting State: A thread lies in a timed waiting state when it calls a method
with a time-out parameter. A thread lies in this state until the timeout is completed
7. Methods to Create Threads: Basically there are Two ways to create and use threads:
Extending the Thread class:A class can extend the Thread class and override its
run() method. When the thread is started using start(), the run() method is
executed in a new thread.
Example:
Example:
Example:
class Table {
System.out.println(n * i);
try {
Thread.sleep(400);
} catch(Exception e) {
System.out.println(e);
Table t;
MyThread1(Table t) {
this.t = t;
t.printTable(5);
Table t;
MyThread2(Table t) {
this.t = t;
t.printTable(100);
// Create MyThread1 and MyThread2 objects with the same Table object
t1.start();
t2.start();
Output:
5
10
15
20
25
100
200
300
400
500
9. Advanced Concepts in Java
Collection in Java:
The Java Collection Framework is a set of classes and interfaces that implement
commonly reusable collection data structures such as lists, sets, maps, and queues. It
provides a way to store and manipulate a group of data as a single unit.
Core Interfaces:
Common Implementations:
Utility Classes:
Java Bean:
Example:
// Default constructor
public Employee() {}
Security Manager:
Usage:
Example:
Generic Classes: Classes that can operate on any data type, defined with type
parameters. Example: ArrayList<T>.
Generic Methods: Methods that can operate on objects of various types,
defined with type parameters. Example: public <T> void print(T obj).
Bounded Type Parameters: You can restrict the types that can be used with
generics. Example: <T extends Number> restricts T to be a subtype of
Number.
Advantages:
Type Safety: Generics eliminate the need for casting and catch errors at
compile time.
Code Reusability: With generics, you can write classes and methods that
work with any type.
Example:
public T getValue() {
return value;
}
Type Safety: Generics ensure that type-related errors are caught at compile time,
preventing runtime issues like ClassCastException.
Elimination of Type Casting: With generics, explicit type casting is unnecessary,
reducing the chances of errors.
Reusability: Generics allow you to write code that works with any data type,
promoting code reusability and reducing duplication.
Improved Code Readability and Maintainability: Generics make code clearer by
specifying types explicitly, improving its readability and ease of maintenance.
Performance: By eliminating the need for type casting at runtime, generics help
improve performance.
Consistency: Generics ensure that collections and data structures are used
consistently with the correct types, preventing potential type mismatches.
Interoperability: Generics enable seamless integration with Java’s built-in
collections and libraries that use generics.
Increased Flexibility: Generics allow for more adaptable and flexible code that can
work with any type of data.
Code Reduction: Generics reduce the need for writing multiple versions of the same
code for different data types, leading to less code duplication.
Enhanced Debugging: Type errors are detected at compile time, making debugging
easier compared to runtime errors.