0% found this document useful (0 votes)
3 views11 pages

wrapper class

The document provides an overview of various Java concepts including wrapper classes, nested classes, garbage collection, event handling, generics, exception handling, threading, and GUI frameworks like AWT and Swing. It explains how wrapper classes encapsulate primitive types, the automatic memory management of garbage collection, and the event handling mechanism using the Delegation Event Model. Additionally, it covers the importance of generics for type safety, exception handling mechanisms, and the lifecycle of threads in Java.

Uploaded by

kiaansservice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

wrapper class

The document provides an overview of various Java concepts including wrapper classes, nested classes, garbage collection, event handling, generics, exception handling, threading, and GUI frameworks like AWT and Swing. It explains how wrapper classes encapsulate primitive types, the automatic memory management of garbage collection, and the event handling mechanism using the Delegation Event Model. Additionally, it covers the importance of generics for type safety, exception handling mechanisms, and the lifecycle of threads in Java.

Uploaded by

kiaansservice
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

wrapper class

In Java, a wrapper class is a class that encapsulates a primitive data


type within an object. Java is an object-oriented programming language,
and sometimes it's necessary to treat primitive data types as
objects. Wrapper classes provide this functionality. Each of the eight
primitive data types in Java has a corresponding wrapper class:
Primitive Type Wrapper Class

byte Byte

short Short

int Integer

long Long

float Float

double Double

char Character

boolean Boolean

Nested class

In Java, a nested class is a class defined within another class. This


allows for logical grouping of classes, especially when a nested class is
only used in the context of its enclosing class. Nested classes can be
either static (using the static keyword) or non-static (known as inner
classes).

Grabage Collection

Garbage collection in Java is an automatic memory management


process that reclaims memory occupied by objects that are no longer in
use. The Java Virtual Machine (JVM) automatically performs garbage
collection, freeing developers from manually managing memory
allocation and deallocation.
The process involves identifying and marking unreachable objects, and
then removing them to free up memory. This helps prevent memory
leaks and ensures efficient memory utilization. Garbage collection runs
in the background as a low-priority thread, triggered when the JVM
detects low memory or when explicitly called.

finalize() method

When an object is no longer referenced and becomes eligible for


garbage collection, the garbage collector calls the finalize() method
on that object, giving it a chance to release resources or perform other
cleanup tasks.

Package

In Java, a package serves as a mechanism to organize and group


related classes, interfaces, and sub-packages. It acts much like a folder
in a file system, providing a way to manage and structure code
effectively. Packages help prevent naming conflicts, control access to
classes, and promote code reusability.
Packages are declared using the package keyword at the beginning of
a Java source file. For example:

There are two main types of packages in Java:


 Built-in packages: These are pre-defined packages that come with the
Java Development Kit (JDK), such as java.lang, java.util,
and java.io.
 User-defined packages: These are packages created by developers to
organize their own code.
 package mypack;
 class A {
 public static void main(String[] args) {
 System.out.println("This is my package!");
 }
 }
An event is a change in the state of an object triggered by some
action such as Clicking a button, Moving the cursor, Pressing a key on
the keyboard, Scrolling a page, etc. In Java,
the java.awt.event package provides various event classes to handle
these actions.

Events in Java can be broadly classified into two categories based on


how they are generated:
1. Foreground Events: Foreground events are the events that require
user interaction to generate. Examples of these events include
Button clicks, Scrolling the scrollbar, Moving the cursor, etc.
2. 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.

Event Handling Mechanism


Event handling is a mechanism that allows programs to control events
and define what should happen when an event occurs. Java uses the
Delegation Event Model to handle events. This model consists of two
main components:
 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.
What is Event Handling?
Event Handling is the mechanism that controls the event and
decides what should happen if an event occurs. This mechanism
have the code which is known as event handler that is executed
when an event occurs.
Java Uses the Delegation Event Model to handle the events. This
model defines the standard mechanism to generate and handle the
events. Let's have a brief introduction to this model.
The Delegation Event Model has the following key participants
namely:

Source - The source is an object on which event occurs. Source is


responsible for providing information of the occurred event to it's
handler. Java provides classes for source object.
Listener - It is also known as event handler. Listener is responsible
for generating response to an event. From java implementation point
of view the listener is also an object. Listener waits until it receives
an event. Once the event is received , the listener process the event
an then returns.
Advantages of event Handling
The benefit of this approach is that the user interface logic is
completely separated from the logic that generates the event.

The GUI in Java processes the interactions with users


via mouse, keyboard and various user controls such
as button, checkbox, text field, etc. as the events. These
events are to be handled properly to implement Java as
an Event-Driven Programming.

Generic Programming

Java - Generics

Java Generic methods and generic classes enable programmers


to specify, with a single method declaration, a set of related
methods, or with a single class declaration, a set of related
types, respectively.

Generics also provide compile-time type safety that allows


programmers to catch invalid types at compile time.

Using Java Generic concept, we might write a generic method


for sorting an array of objects, then invoke the generic method
with Integer arrays, Double arrays, String arrays and so on, to
sort the array elements.

Advantage of Java Generics

 No scarification of type-safety
 No requirement of type-casting
 Compile-time checking
 Code reusability and improved performance

Types of Java Generics


Generic Methods

You can write a single generic method declaration that can be


called with arguments of different types. Based on the types of
the arguments passed to the generic method, the compiler
handles each method call appropriately.

Rules to Define Generic Methods

Following are the rules to define Generic Methods −

 All generic method declarations have a type parameter section


delimited by angle brackets (< and >) that precedes the
method's return type ( < E > in the next example).
 Each type parameter section contains one or more type
parameters separated by commas. A type parameter, also
known as a type variable, is an identifier that specifies a
generic type name.
 The type parameters can be used to declare the return type
and act as placeholders for the types of the arguments passed
to the generic method, which are known as actual type
arguments.
 A generic method's body is declared like that of any other
method. Note that type parameters can represent only
reference types, not primitive types (like int, double and char).

Exception Handling in Java

Exception handling in Java is a mechanism to handle runtime errors,


maintaining the normal flow of the application. It
uses try, catch, finally, throw, and throws keywords. Exceptions
are categorized into checked (compile-time) and unchecked (runtime)
exceptions.

Exception Handling is a mechanism to handle runtime errors such a


ClassNotFoundException, IOException, SQLException,
RemoteException, etc.

 try: Encloses code that might throw an exception.


 catch: Handles a specific type of exception thrown within
the try block. Multiple catch blocks can handle different exception
types.
 finally: Executes code regardless of whether an exception is thrown or
caught, often used for cleanup operations.
 throw: Explicitly throws an exception.
 throws: Declares that a method might throw a specific exception,
requiring the caller to handle it.

Feature throw throws


When there is a need to Used to declare exceptions that
Purpose
explicitly throw an exception. a method might throw.
Used in method signature
Used as a statement followed by
Syntax followed by the exception
an exception object.
classes.
Used in a method declaration
Used within a method or block
Applicability to indicate potential
to raise an exception.
exceptions.
Can declare multiple
Single Exception Can handle only one exception
exceptions separated by
Handling at a time.
commas.
Stops execution of the current Allows the method to
Execution Flow method and looks for a catch propagate the exception to the
block. caller.
Essential for handling Provides information to callers
Error Handling
exceptions in try-catch blocks. about potential exceptions.

Difference Between Checked and Unchecked Exceptions


Featur
e Checked Exception Unchecked Exception

Behavi Checked exceptions are Unchecked exceptions are


our checked at compile time. checked at run time.

Base Derived
Derived from Exception
class from RuntimeException

External factors like file I/O


Programming bugs like logical
and database connection
errors cause unchecked
cause the checked
Exceptions.
Cause Exception.

Handli Checked exceptions must be


ng handled using a try-catch
No handling is required
Requir block or must be declared
ement using the throws keyword

Examp IOException, SQLException, NullPointerException, ArrayInd


les FileNotFoundException. exOutOfBoundsException.

Threading
Threading in Java enables concurrent execution of multiple parts of a
program. Threads are lightweight processes that share the same memory
space, allowing for efficient communication and resource sharing. Java
provides the Thread class and the Runnable interface to create and manage
threads.

Creating Threads
 Extending the Thread class: A class can extend the Thread class and override
the run() method to define the task performed by the thread.

class MyThread extends Thread {

public void run() {


System.out.println("Thread is running");
}

public static void main(String[] args) {


MyThread thread = new MyThread();
thread.start(); // Start the thread
}
}

 Implementing the Runnable interface: A class can implement


the Runnable interface and provide the implementation for the run() method.

class MyRunnable implements Runnable {


@Override
public void run() {
System.out.println("Thread is running");
}

public static void main(String[] args) {


MyRunnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start(); // Start the thread
}
}

Thread Lifecycle
Threads go through different states during their lifecycle:
 New: Thread is created but not yet started.
 Runnable: Thread is ready to run and waiting for CPU time.
 Running: Thread is currently executing.
 Blocked/Waiting: Thread is waiting for a resource or condition.
 Terminated: Thread has completed execution or has been terminated.
 New State
As we use the Thread class to construct a thread entity, the thread is born and is
defined as being in the New state. That is, when a thread is created, it enters a new
state, but the start() method on the instance has not yet been invoked.
 Runnable State
A thread in the runnable state is prepared to execute the code. When a new thread's
start() function is called, it enters a runnable state.
In the runnable environment, the thread is ready for execution and is awaiting the
processor's availability (CPU time). That is, the thread has entered the queue (line)
of threads waiting for execution.
 Running State
Running implies that the processor (CPU) has assigned a time slot to the thread for
execution. When a thread from the runnable state is chosen for execution by the
thread scheduler, it joins the running state.
In the running state, the processor allots time to the thread for execution and runs its
run procedure. This is the state in which the thread directly executes its operations.
Only from the runnable state will a thread enter the running state.
 Blocked State
When the thread is alive, i.e., the thread class object persists, but it cannot be
selected for execution by the scheduler. It is now inactive.
 Dead State
When a thread's run() function ends the execution of sentences, it automatically dies
or enters the dead state. That is, when a thread exits the run() process, it is
terminated or killed. When the stop() function is invoked, a thread will also go dead.

Multithreading in Java

In Java, multithreading is the method of running two or more threads at the same
time to maximize CPU utilization. As a result, it is often referred to as Concurrency
in Java. Each thread runs in parallel with the others. Since several threads do not
assign different memory areas, they conserve memory. Furthermore, switching
between threads takes less time.

Here is an example of Multithreading in Java.


AWT also known as Abstract window toolkit. It is a platform dependent API used
for developing GUI (graphical user interface) or applications that are window based.
It was developed by Sun Microsystems In 1995 and is heavy weighted.The main
difference between AWT and Swing is that AWT is purely used for GUI whereas
Swing is used for both, GUI as well as for making web application.

What is Swing?
In Java, a swing is a light-weighted, GUI (graphical user interface) that is used for
creating different applications. It has platform-independent components and enables
users to create buttons as well as scroll bars.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy