Object Oriented Prog With JAVA
Object Oriented Prog With JAVA
Java was developed by James Gosling and his team at Sun Microsystem. On initial days it is called “Oak”,
Which is named after an oak tree that stood outside Gosling’s office.
Later that project went by the name “green” and was finally renamed “Java” from Java coffee that comes
from Indonesia.Java team members (also known as green team) initiated this project to develop a
language for Digital devices such as televisions, setup boxes etc. which was started by “cleaning up” the
C++ and day all wound-up with a new language called Java or Oak.
● Versions of Java:
1) Java 1.0 (1996): The first official version of Java known as Java 1.0. It introduced the Core features of
java, including platform independence (ability to run on different computer systems without modification),
automatic memory management through garbage collections and strong support for object oriented
programming.
2) Applets & web-browsers (1990s to early 2000s): Java became famous for its applets, which were
small Java programs that could Run within web browsers. This allowed interactive and dynamic content
on webpages however over time other web technologies like JavaScript gained popularity and Java
Applets declined.
3) Java-2 (1998): Java 2 also known as Java 1.2 and it works as a boost release, with many
improvements including swing GUI toolkit, the collections Framework for Data Structures and “assert”
keyword for testing code.
4) Enterprises Java (late 1990s to 2000s): Java started gaining traction(pull) in enterprise development
with the introduction of Java EE(Enterprises Edition). It enables the programmers to build large scale
server side applications.
5) Java Community Process(JCP) (1998): In 1998 Sun Microsystem established the JCP which allows
developers and organizations to participate in the evolution of Java by proposing and implementing new
features through Java specifications requests (JSRs).
6) Java-5 (2004): Java 5 code name “Tiger” introduced significant language enhancements including
generis(to make code more type safe and reusable) metadata and annotations for adding information to
code and enumerated types.
7) Oracle acquisition (2010): Oracle Corporation acquired Sun-Microsystem becoming the steward of
Java Platform in 2010.
8) Java-7 (2011): Java 7 brought notable features like “try-with-resources” statement for automatic
resource management, the “switch” statement with strings and support for dynamic language through
“invoked dynamic”.
9) Java-8 (2014): Java 8 release with introduction of “lambdas” and the stream API and new date and
time API.
10) Java-9 (2017): Java-9 featured with modular system (project Jigsaw) to improve scalability and
maintainability. It also introduced Java shell (Jshell) for interactive code execution.
11) Java-10 and Beyond: Java 10 focused on smaller enhancements including the introduction of
local-variable type inference var and the “var” keyword.
12) Open JDK & Community involvement: Oracle started to let more people from the community to
help make decisions about Java. They also made it open for anyone to use and improve through JDK.
In summary Java started as a smart idea in the 1990s, and has been getting better and easier to use
ever since. It can run on different types of computer and people keep adding new features to make it
even more powerful and useful for all sorts of computer programmers.
Java is strongly associated with the Internet, because the first application program written in Java was
“Hot- Java”.
● View webpages.
● Send and receive emails.
● Run Applets.
Applets: Java applet is a small special type of a program that is embedded in the web pages to generate
dynamic content. These are stored on remote computers which can be downloaded by using the internet
and once they are downloaded on local computer we can run them on a local computer.
Java changed the way of the internet and www, before Java: only static text and images webpages are
created.
After development of Java: Web Pages contain animations graphic and dynamic data can be used in web
pages.
Java works with the internet in various ways with its versatility and wide range of libraries and
frameworks. Here are some ways in which Java and internet are interconnected:-
1) Web Development: Java server pages (JSP) servlets and Java server faces (JSF) allow
developers to create dynamic web pages and Web Services.
2) Server-Side Processing: Many web servers and application servers are written in Java or
support Java applications. These servers receive https requests from client side, process
them using Java code and send back responses over the internet. example Apache Tomcat,
Jetty and wildfly.
3) Internet-Of-Things(IOT): Java is used in IOT development to create applications that
connect and interact with IOT devices and sensors Java can collect data from these devices
and transmit them over the internet and process it in the cloud. example-Televisions,
setup-boxes.
4) Mobile App Development: While Android primarily uses “Kotlin” for App-development.Java
was previously the primary language for Android development.
5) Security: Java includes security features for internet-based applications. It provides libraries
and tools for encryption, authentication and Secure communication.
6) Network communication: Applets can communicate with remote servers over the internet,
allowing them to fetch data resources from external sources. This made them useful for
accessing real time data such as stock-market updates or weather information.
In summary Java and internet are interconnected through a wide range of applications
and servers including web development, server side processing, Web Services, networking, IOT, mobile
app development and many other services.
Working:
● Program: Program is a .java file. It consists of the code that we have written in our IDE or
Notepad.
● Compiler: Java compiler (“Javac'') compiles our “.java” source code file. It takes our human
readable source code and translates it into a lower-level(which is readable by machine) code
known as bytecode. The output of this compilation is typically stored as a ".class” file.
● Bytecode: Bytecode is a set of platform-independent low level instructions that can be run on
any other platforms like Windows, MacOS, Linux.
● JVM: JVM is responsible for executing Java bytecode. It reads the bytecodes instructions
from the “.class” file and translates them into machine code that can run on the underlying
hardware. The JVM takes care of various tasks such as memory management through
garbage collection and security, to ensure that Java programs run correctly and securely.
● Machine Code: The machine generates its own machine code in which the bytecode is
running that means it's own machine dependent code to run the “.Java” file.
Advantages of bytecode:
1) It takes more time to run bytecode than the machine code, which is machine specific.
2) Mandatory installation of Java interpreter to run the bytecode.
3) Slow start-up: because it takes time to load and initialize the JVM.
4) Resource management: while the JVM handles memory management through garbage
collection, inefficient memory use or improper resource management can still lead to
performance issues, if not handled properly.
4) Features of Java
Java is a versatile and widely used programming language known for its platform Independence, strong
community support, and rich ecosystem of libraries and Framework which make the simple and Secure
hair are some of the key features of java:
1) Platform Independence: Java applications are compiled into bytecode, which can be
executed on any platform with a Java virtual machine(JVM). This “write once, run
anywhere”(WORA) capability makes Java highly portable across different operating systems
and devices.
2) Object-oriented: Java is an object-oriented programming language, which means it
encourages the use of objects and classes for structuring code.This promotes modularity,
code reusability and maintainability.
3) Simple and easy to learn: Java was designed to be easy to learn and use. Its syntax is
clean and easy to understand. According to Sun-Microsystem, Java language is a simple
programming language because Java syntax is based on C++ (easier for programmers to
learn after C++). Java has removed complicated and rarely used features. For e.g. explicit
pointers, operator overloading etc. There is no need to remove unreferenced objects because
there is an automatic garbage collection in Java.
4) Strongly-Typed: Java is a strongly typed language, which means that variables must be
declared with their data types before use of it. This helps catch typed-related errors at
compilation time, making the code more robust.
5) Automatic memory allocation: Java features automatic memory management through
garbage collection. The JVM allocates the memory that is no longer in use, reducing the risk
of memory leaks and simplifying memory management for developers.
6) RIch-Standard Library: Java provides a comprehensive standard library that includes
classes and methods for common programming tasks. This library covers areas such as data
structure, I/O, networking, and GUI development, which saves time and effort of developers.
7) Multi-threading: Java supports multi-threading, allowing developers to create concurrent,
threaded applications easily. This is valuable for building applications that can perform
multiple tasks simultaneously.
8) Dynamic Loading:Java supports dynamic loading of classes, which allows classes to be
loaded only when they are needed, enhancing resource efficiency.
9) Portability: Java's platform independence and the availability of JVM implementations for
various platforms make it highly portable.
10) Exception handling: Java includes a robust exception handling mechanism, which helps
developers to detect and gracefully handle errors and exceptional situations in their code.
This improves the reliability and maintainability of Java applications.
11) Versatility: Java can be used for a wide range of applications, including web development,
mobile development(android), enterprise softwares, scientific computing and many more.
12) Backward compatibility: Java places importance on backward compatibility, ensuring that
older java applications continue to work on newer versions without modifications.
13) Dynamic: Java is a dynamic language. It supports dynamic loading of classes. It means
classes are loaded on demand, and it also supports functions from its native language. I.e. C
and C++. Java supports dynamic compilation and automatic memory allocation through
garbage collection.
14) Community support: Java has a large and active developer community, which means there
is a wealth of resources, documentation, and online support available to developers.
These features made Java a popular choice for a wide range of application
development including web-application, mobile-application, server-side applications and more. Its
versatility combined with a strong emphasis on stability and security has contributed to its enduring
popularity in software development history.
4) Java Program structure:- In Java programs structure is defined by a set of conventions and
rules that dictate how code should be organized and returned. The primary goal of following a structured
approach is to make the code more readable, maintainable and easy to understand for both us and other
developers.
Typically structure of Java programs contains the following statement:-
1) Package declaration(optional): A class in Java can be placed in different
directories/packages based on the module they are used. For all the classes that belong to a
single parent source directory, a path from source directory is considered as a package
declaration.
Eg.: package com.example.myapp
2) Import statement: The package contains many predefined classes and interfaces. If we
want to use any classes of a particular package we need to import the class by using the
“import" keyword before the class name.
Eg.: import java.util.Scanner; //import scanner class only
import java.util; //import all classes in java.util package
3) Class declaration: In Java everything happens within a class. A program may contain more
than one class definition. We use the “class” keyword to define the class class is the blueprint
of a Java Program it contains information about user defined methods, variables, and
constants. Every Java program must contain at least one class that contains the main()
method. Eg.: public class MyClass {
public static void main(String[ ] args) {
// Program logic goes here{
}
}
4) Main method: The main method is where our program starts execution. It takes an array of
“string” arguments(args) that can be used to pass command line parameters to our program.
Eg. : public static void main(String[ ] args) {
// Program logic goes here
}
5) Program Logic: Inside the main method, we write the code expression that defines the
behavior of our program. This can include variable declaration, control flow statements,
method calls, cases, function expressions and more.
Eg. : public class MyClass {
// Instance variable
private int myField;
// Constructor
public MyClass(int initialValue) {
this.myField = initialValue;
}
// Instance method
public void doSomething() {
// Method logic goes here
}
// Static method
public static void staticMethod() {
// Static method logic goes here
}
}
6) Comments: comments are used to add explanations and documentations to our code, for
better readability and understandability. Java supports Single line comment (//) and multiline
comments ( /* */)
Eg: //this is an example of a single-line comment.
/* this is an example of
Multiline comment */
7) Access modifiers: Java uses access modifiers such as “public”, “private”, “protected”, and
package-private (default) to control the visibility and accessibility of classes, fields, and
methods.
8) Object creation : we can create objects (instances) of classes using the new keyword. For
example: MyClass obj = new MyClass(42);
9) Inheritance: Java supports inheritance, allowing one class to inherit the properties and
methods of another class. The “extends” keyword is used for inheritance.
eg : public class ChildClass extends ParentClass {
// Additional members and methods for the child class
}
10) Exceptional handling: Java provides mechanisms for handling exceptions using “try”,
“catch”, “finally”, and “throw” keywords to ensure robust error handling in programs.
scanner.close();
}
}
5) Java Class Library(JCL):- Java’s class library, also known as the Java standard library or
Java API(application programming interface) are a set of prewritten classes, interfaces and methods that
provide a wide range of functionality to Java developers. These libraries are an essential part of the Java
programming language and these libraries(JCL) are organized into packages, making it easy for
developers to access and use them in their
applications.
Packages: A package arranges a number of classes, interfaces and sub-packages of the same type
into a particular group. In simple language, it works pretty similar to the folder in File-explorer.
A java library is deployed in a JAR file format, JAR or Java archive format is like a zip file which contains
many java classes and its associated resources such as “.img”, “.txt” file, etc. into one file to distribute as
libraries. These JCL are dynamically loadable libraries, that java application call at runtime, some eg. of
JCL’s are:-
1) Java.lang: Contains fundamental classes that are automatically imported into every Java
program. This includes classes like “string”, “object,”integer:,”boolean” etc.
2) Java.util: Java.util provides collection frameworks, date and time utilities, Random numbers
generation etc. Some important classes include “list”, “set”, “map”, “date”, “calendar” etc.
3) Java.io: Java.io handles input and output operations including file reading and writing. Key
classes of Java.io include “file”, “inputStream”, “outputStream”, “reader”, “writer” etc.
4) Java.net: Contains classes for networking operations such as “Socket”, “ServerSocket”,
“URLConnection” etc.
5) Java.awt and Java.swing: These packages from the foundation, for Java's GUI capabilities.
“Java.awt” provides basic AWT components like “frame”, “button”, “text field” etc. While
“Javax.swing” provides more advanced swing components.
6) Java.sql: Java.sql offers classes and interfaces for database connectivity and interaction,
key classes include “connection”, “statement”, “resultSet”, etc.
7) Java.nio: Java.nio provides support for non-blocking I/O operations. It introduces buffers,
channels, and selectors for efficient I/O operations.
8) Java.security: Contains classes related to security, including cryptographic operations,
certificates, and secure random number generation.
9) Java.text: Deals with text, dates etc.
10) Java.math:Provides mathematical expressions.
Java’s class library(JCL) provides a robust foundation for building a wide range of applications from
command line utility to Complex Enterprises software and graphical user interfaces.
Developers can leverage these libraries to save time and effort by utilizing pre-built
functionality adhering to established standard and best practices.
Keywords: In Java, "keywords" refer to reserved words that have special meanings and purposes
within the language. These words are part of the Java language's syntax and cannot be used as
identifiers (such as variable names or class names) in Java code. Keywords are used to define
various elements and control structures in Java programs. Here are some common Java keywords:
6) Data Types:- A data type is a classification that specifies which type of data we are using, or
which type of data a variable can hold or what kind of values a particular expression can produce. Data
types are essential in Java because they determine how data is stored in memory and what operation can
be performed on the data types and ensure Data integrity, provide clarity to the programmers, and enable
the compiler or interpreter to allocate memory and generate efficient code.
OR
Data types are a set of values and a set of operations that can be performed on those values,
variables are nothing but reserved memory locations to store values. This means that when we
create a variable we reserve some space in memory for our data and expression .
There are two types of datatypes in Java:
1)Primitive(intrinsic) data types
2)Non-primitive(Reference/object/derived) data types
Characteristics Primitive Non-Primitive
Initialization Assigned default values if not initialized Assigned a “null” value if not explicitly
initialized.
Types of values Basic data types(integer, floating-point, char, Objects(instances of classes, interfaces,
boolean, etc) arrays, enumerations, etc)
Operations Support simple arithmetics & logical operations Operations performed through methods,
defined in referenced object classes.
Mutability These are immutable, their values cannot be These are mutable and their state can be
changed modified.
Default values Default to a specific value(eg. 0 for num, Default to null (no values)
‘/u000’ for char, false for boolean)
Size Generally takes a smaller size in memory. Generally takes a larger size in memory.
Performance Typically more efficient in terms of time and Slightly less efficient due to overhead of
memory dealing with obj and references.
Float IEEE 754 floating point 0.0f 32 -3. 4e+³8 to 3.4e+³8 a=222.5f
Scope Limited to block method, or Belongs to an instance(obj) of Belongs to the class itself, not to any
constructor where it is a class and exists as long as specific instance, and exists as long
declared. the instance exists. as the class is loaded in memory.
Declaration Declared within the Declared within the class but Declare within the class with the
method, constructor, or outside any method, “Static” keyword and outside any
block. constructor or block. method constructor or block.
Initialization Must be explicitly initialized Automatically initialized with Automatically initialized with default
before use. default value if not explicitly values if not explicitly set.
set.
Access Only accessible within the Accessible anywhere within Accessible anywhere within the c
block or method where it is the class. class and also externally if the
declared. access modifier allows.
Life-time Exists as long as the block Exists as long as the instance Exists as long as the class is loaded
or method exists. of the class exists. in the memory.
Storage Stored on stack. Stored on heap along with Stored in the method area(a part of
object. no-heap memory).
Modifier No modifier required. No modifier required. generally , declared with the “Static”
modifier.
Usage Typically used for Used to store unique Used when a value needs to be
temporary calculation or as characteristics or attributes of shared across all instances of a
loop counters. each object. class.
Scope of variable:In Java, the scope of a variable refers to the region of code within which the
variable can be accessed and used. The scope of a variable is determined by where it is declared and
how it is declared.
OR
Scope of a variable refers to the region of the program where the variable is accessible and
can be used. The scope of a variable is determined by where it is declared and can be categorized
into several types:
1. Local Variable Scope: Local variables are declared within a method, constructor, or block of
code. They are only accessible within that specific method, constructor, or block. Once we exit the
method or block where they are declared, the variable goes out of scope and cannot be accessed.
2. Instance Variable Scope: Instance variables are declared within a class but outside of any
method, constructor, or block. They are associated with an instance of the class and can be
accessed as long as we have an instance of the class. Their scope is tied to the lifetime of the object.
3. Class (Static) Variable Scope: Class variables, also known as static variables, are declared with
the `static` keyword within a class. They are shared among all instances of the class and can be
accessed using the class name itself. Their scope is at the class level and is not tied to any specific
instance.
4.Method Parameter Scope: Parameters of a method are also variables, and their scope is limited
to the method in which they are declared. They can be used within the method just like local
variables.
● Literals:In Java, literals are fixed, constant values that are used directly in wer code to
represent specific data values. Literals are used to initialize variables and constants or as
arguments in expressions. They provide a way to express data values in a straightforward
and easily understandable manner. For example,
char charValue = 'A'
double floatValue = 3.14;
int decimalValue = 42
boolean isTrue = true;
String escapeString = "This is a new line:\nSecond line";
8) Access modifiers in java-An access modifier in Java is a keyword or specifier that is used
to control the visibility and accessibility of classes, methods, fields, and constructors within a Java
program. Access modifiers determine which parts of a program can access a particular class member
(such as a field or method) and from where they can access it.Java provides four main access modifiers,
each with a specific scope and level of visibility:
1. public:
- The `public` access modifier has the widest scope and is the most permissive.
- Public members are accessible from anywhere within the same package and from other
packages.
- It is commonly used for classes, methods, and fields that need to be accessible from outside the
class or package.Example:
public class MyClass {
public int publicField;
public void publicMethod() {
// Code here
}
}
2.protected:
- The `protected` access modifier allows access within the same package and by subclasses (even
if they are in different packages).
- It is typically used to provide controlled access to members for subclasses.Example:
class Parent {
protected int protectedField;
protected void protectedMethod() {
// Code here
}
}
class Child extends Parent {
void accessProtectedMember() {
protectedField = 10; // Accessing the protected field from a subclass
protectedMethod(); // Accessing the protected method from a subclass
}
}
To summarize, access modifiers in Java help us control the visibility and accessibility of classes and
members, ensuring proper encapsulation and access control in wer code. These modifiers play a
crucial role in defining the level of information hiding and security in our Java programs.
9) Operators- Operators are the symbols that are used to perform some specific action on
operands according to user requirement.
OR
In Java, operators are symbols or special keywords that are used to perform various operations on
data or variables. They are used to manipulate and process data, make decisions, and perform
calculations in Java programs. Operators in Java can be categorized into several types based on the
operations they perform. Here are brief definitions of some of the most common operator types in
Java:
Assignment operators can also be combined with other operators to perform compound
assignments. These operators perform an operation and then assign the result back to the variable.
● compound assignment operators:Compound Assignment Operators (e.g., +=, -=, *=, /=, %=):
Combine an operation with assignment. For example, x += 5 is equivalent to x = x + 5.
3)Comparison operator: In Java, comparison operators are used to compare two values or
expressions and determine the relationship between them. These operators return a boolean result,
which is either `true` or `false`, based on whether the specified condition is satisfied. Comparison
operators are also known as relational operators, and they are used to compare values for equality,
inequality, and order. Here are the primary comparison operators in Java:
1. Equal to (==): The equal to operator checks whether two values are equal. It returns `true` if the
values are equal and `false` otherwise. For example:
int x = 5;
int y = 7;
boolean isEqual = (x == y); // isEqual is false
2. Not equal to (!=): The not equal to operator checks whether two values are not equal. It returns
`true` if the values are not equal and `false` if they are equal. For example:
int x = 5;
int y = 7;
boolean isNotEqual = (x != y); // isNotEqual is true
3. Greater than (>): The greater than operator checks if the left operand is greater than the right
operand. It returns `true` if the condition is met and `false` otherwise. For example:
int x = 10;
int y = 7;
boolean isGreater = (x > y); // isGreater is true
4. Less than (<): The less than operator checks if the left operand is less than the right operand. It
returns `true` if the condition is met and `false` otherwise. For example:
int x = 5;
int y = 7;
boolean isLess = (x < y); // isLess is true
5. Greater than or equal to (>=): The greater than or equal to operator checks if the left operand is
greater than or equal to the right operand. It returns `true` if the condition is met and `false`
otherwise. For example:
int x = 10;
int y = 10;
boolean isGreaterOrEqual = (x >= y); // isGreaterOrEqual is true
6. **Less than or equal to (<=)**: The less than or equal to operator checks if the left operand is less
than or equal to the right operand. It returns `true` if the condition is met and `false` otherwise. For
example:
int x = 5;
int y = 10;
boolean isLessOrEqual = (x <= y); // isLessOrEqual is true
4)Logical Operator: In Java, logical operators are used to perform logical operations on boolean
values. These operators allow us to combine and manipulate boolean expressions to make decisions
and control the flow of our program. Java has three primary logical operators: `&&` (logical AND), `||`
(logical OR), and `!` (logical NOT).frequently used in conditional statements. Here's a detailed
explanation of each:
1. Logical AND (`&&`):
- The logical AND operator returns `true` if both of its operands are `true`, and `false` otherwise.
- It is represented by `&&`.
- It is used to combine two or more boolean expressions, and the result is `true` only if all
expressions are `true`.Example:
boolean condition1 = true;
boolean condition2 = false;
boolean result = condition1 && condition2; // result is false
2. Logical OR (`||`):
- The logical OR operator returns `true` if at least one of its operands is `true`, and `false` if both
operands are `false`.
- It is represented by `||`.
- It is used to combine two or more boolean expressions, and the result is `true` if at least one of the
expressions is `true`.Example:
boolean condition1 = true;
boolean condition2 = false;
boolean result = condition1 || condition2; // result is true
3. Logical NOT (`!`):
- The logical NOT operator negates or flips the value of its operand. If the operand is `true`, it
returns `false`, and if the operand is `false`, it returns `true`.
- It is represented by `!`.
- It is used to invert the value of a boolean expression. Example:
boolean condition = true;
boolean result = !condition; // result is false.
5)Bitwise Operator: In Java, bitwise operators are used to perform operations on individual bits of
integer values (int, long, short, byte) at a binary level. These operators manipulate the binary
representation of numbers, changing or extracting specific bits within them. Java provides several
bitwise operators, including AND, OR, XOR, NOT, left shift, right shift, and unsigned right shift.
Here's an explanation of each bitwise operator:
1. Bitwise AND (`&`):
- Performs a bitwise AND operation on each pair of corresponding bits in two integers.
- The result bit is 1 only if both input bits are 1; otherwise, it's 0.Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a & b; // Binary result: 0001 (Decimal: 1)
2. Bitwise OR (`|`):
- Performs a bitwise OR operation on each pair of corresponding bits in two integers.
- The result bit is 1 if at least one of the input bits is 1.Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a | b; // Binary result: 0111 (Decimal: 7)
3. Bitwise XOR (`^`):
- Performs a bitwise XOR (exclusive OR) operation on each pair of corresponding bits in two
integers.
- The result bit is 1 if exactly one of the input bits is 1; otherwise, it's 0.Example:
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
int result = a ^ b; // Binary result: 0110 (Decimal: 6)
4. Bitwise NOT (`~`):
- Performs a bitwise NOT (complement) operation on a single integer.
- Inverts each bit, turning 0s into 1s and 1s into 0s.Example:
int a = 5; // Binary: 0101
int result = ~a; // Binary result: 1010 (Decimal: -6)
5. Left Shift (`<<`):
- Shifts the bits of an integer to the left by a specified number of positions.
- Fills in empty bit positions with zeros.Example:
int a = 5; // Binary: 0000 0101
int result = a << 2; // Binary result: 0001 0100 (Decimal: 20)
6. Right Shift (`>>`):
- Shifts the bits of an integer to the right by a specified number of positions.
- Fills in empty bit positions with the most significant bit (the sign bit for signed integers).Example:
int a = -16; // Binary: 1111 0000
int result = a >> 2; // Binary result: 1111 1100 (Decimal: -4)
7. Unsigned Right Shift (`>>>`):
- Similar to the right shift (`>>`) but fills in empty bit positions with zeros.
- Used for unsigned integers (treats the value as non-negative).Example:
int a = -16; // Binary: 1111 0000
int result = a >>> 2; // Binary result: 0011 1100 (Decimal: 60)
Bitwise operators are mainly used in low-level programming, embedded systems, and situations
where fine-grained bit manipulation is required. They are not as common in general Java
programming as other operators like arithmetic or logical operators.
6)Conditional operator: In Java, the conditional operator, also known as the ternary operator, is a
unique operator that provides a concise way to write conditional expressions. It allows us to evaluate
a condition and choose one of two values based on the result of the evaluation. The conditional
operator has the following syntax:
Example:
int x = 5;
int y = 7;
int result = (x > y) ? x : y;
In this example, if `x` is greater than `y`, `x` is assigned to `result`; otherwise, `y` is assigned to
`result`.
The conditional operator is often used as a shorthand for simple if-else statements. It's especially
useful in situations where we want to assign a value to a variable based on a condition without
writing a full if-else block.
7) Unary Operator: In Java, a unary operator is an operator that operates on a single operand,
which means it performs an operation on or with a single value. Unary operators are used to change
the value of the operand or extract information from it. Java supports several unary operators:
8) Instance Operator: In Java, the `instanceof` operator is used to test whether an object is an
instance of a particular class or implements a specific interface. It allows us to determine if an object
is compatible with a given class or interface type, which can be useful for type checking and ensuring
that we can safely perform certain operations on objects.
The `instanceof` operator returns a boolean value (`true` or `false`) based on whether the
object on the left is an instance of the specified type on the right.
Here's an example of how the `instanceof` operator is used:
class Animal {}
class Dog extends Animal {}
class Cat extends Animal {}
The `instanceof` operator is commonly used when working with polymorphism, interfaces, and class
hierarchies to determine the actual type of objects and make informed decisions in our Java
programs.
9) Type-cast operator: In Java, a type cast (or typecasting) is an operation that allows us to
explicitly change the data type of a value or an object reference from one type to another. This is
done when we want to treat a value or an object as if it were of a different data type. Type casting
can be useful in situations where we need to convert data from one type to another without losing
precision or causing errors.
1. Primitive Type Casting: This is used to convert one primitive data type to another primitive data
type. There are two forms of primitive type casting:
Widening (Implicit) Casting: This type of casting occurs when we convert a smaller data type to a
larger data type, and it is done automatically by the Java compiler because it does not result in data
loss.Example:
int x = 10;
double y = x; // Widening casting (int to double) is done automatically
- Narrowing (Explicit) Casting: This type of casting occurs when we convert a larger data type to a
smaller data type, and it requires explicit casting because it can result in data loss. To perform
narrowing casting, we need to use the cast operator `(datatype)` before the value we want to
convert.Example:
double x = 10.5;
int y = (int) x; // Narrowing casting (double to int) requires explicit casting
2. Reference Type Casting: This is used to convert one reference type (class or interface) to another
reference type. It is done when we want to treat an object of one class as an object of another class,
provided that there is an inheritance or interface relationship between the two classes. Reference
type casting is performed using the cast operator `(datatype)`.Example:
class Animal {}
class Dog extends Animal {}
10) Statements:
● Selection statement: Selection statements in Java are control flow structures that allow us
to control the flow of wer code based on certain conditions. They enable us to execute
different blocks of code depending on whether a condition is true or false. Java provides
several selection statements, including:
1.if Statement:- The `if` statement allows us to execute a block of code if a specified condition is
true. Optionally, we can provide an `else` block to execute if the condition is false.
Syntax:
if (condition) {
// Code to execute if the condition is true
} else {
// Code to execute if the condition is false (optional)
}
2. Nested-if:-A nested `if` statement in Java refers to the situation where one `if` statement is placed
inside another. This allows for more complex conditional logic, where one condition is evaluated only
if another condition is true.
Syntax:
if (condition1) {
// Code to execute if condition1 is true
if (condition2) {
// Code to execute if both condition1 and condition2 are true
}
}
3. if-else Statement:-The if-else statement allows a program to execute one block of code if a
specified condition is true, and a different block of code if the condition is false.
Syntax:
if (condition) {
// Code to execute if condition is true
} else {
// Code to execute if condition is false
}
5. switch Statement:- The `switch` statement is used when we have multiple possible execution
paths based on the value of a single expression. It evaluates the expression and matches it against a
list of cases. When a match is found, the corresponding block of code is executed.
Syntax:
switch (expression) {
case value1:
// Code to execute if expression matches value1
break;
case value2:
// Code to execute if expression matches value2
break;
// More cases...
default:
// Code to execute if none of the cases match (optional)
}
● Iterative statements: In Java, iterative statements are used to create loops that repeatedly
execute a block of code as long as a specified condition is true. These statements are
essential for implementing repetitive tasks and controlling the flow of a program. There are
three primary types of iterative statements in Java:
1. for loop:- The `for` loop is used when we know the number of times we want to repeat a
block of code. It consists of three parts: initialization, condition, and iteration, separated by
semicolons. Here's the basic syntax:
2. while loop:- The `while` loop is used when we want to repeat a block of code as long as a
specified condition is true. It evaluates the condition before entering the loop. Here's the basic
syntax:
while (condition) {
// Code to be repeated
}
3. do-while loop:- The `do-while` loop is similar to the `while` loop but evaluates the
condition after executing the block of code. This guarantees that the code block is executed
at least once. Here's the basic syntax:
do {
// Code to be repeated
} while (condition);
● Jump-Statement:- Jump statements in Java are used to control the flow of execution in a
program. They allow the program to jump to a specific line of code or terminate a loop or
method prematurely. There are three main types of jump statements in Java:
1. break:- The `break` statement is used to exit a loop prematurely, before its normal
termination condition is met. It is often used inside `switch` statements to exit the block of
code associated with a particular case.Example:
for (int i = 1; i <= 10; i++) {
if (i == 5) {
break; // This will exit the loop when i equals 5
}
System.out.println(i);
}
Output:
1
2
3
4
2. continue:- The `continue` statement is used to skip the rest of the current iteration of a
loop and move on to the next iteration.Example:
3. return:- The `return` statement is used inside a method to exit the method and return a
value (if the method has a non-void return type).Example:
11) Methods: Methods are blocks of code that perform specific tasks or operations. They are an
essential part of object-oriented programming and allow us to encapsulate behavior within a class.
Methods are defined within classes and are responsible for performing actions or returning values. Here's
the basic syntax for defining a method in Java:
These methods are provided to simplify common programming tasks and promote code
reuse.
● components of a method:
1.Access Modifier: This is an optional keyword that specifies the visibility or accessibility of the method.
Common access modifiers include:
- `public`: The method is accessible from any class.
- `private`: The method is only accessible within the same class.
- `protected`: The method is accessible within the same package and by subclasses.
- (default): If no access modifier is specified, the method is accessible within the same package
2. Return Type: This is the data type of the value that the method returns. If the method does not return a
value, we should use the `void` keyword.
3. Method Name: This is a unique identifier for the method within the class. It follows Java's naming
conventions and should start with a letter and use camelCase (e.g., `calculateTotal`, `printMessage`).
4. Parameter List: This is a list of input parameters enclosed in parentheses. Parameters are variables
that the method can use within its body to perform its task. If a method doesn't take any parameters, we
still need to include empty parentheses `()`.
5. Method Body: This is the block of code enclosed in curly braces `{}`. It contains the statements that
define what the method does. The method body is executed when the method is called.
6. Return Statement: If the return type is not `void`, the method can use the `return` statement to return
a value of the specified data type to the caller. The `return` statement also terminates the execution of the
method.
Example:
public int add(int num1, int num2) {
int sum = num1 + num2;
return sum;
}
In this example, `add` is a user-defined method that takes two integer parameters, `num1`
and `num2`, calculates their sum, and returns the result.
User-defined methods are essential for structuring our Java programs, improving code
readability, and promoting code reuse. They allow us to organize our code into logical units,
making it easier to understand and maintain.
1. Instance Methods: These methods are associated with instances (objects) of a class. They can
access instance variables and other instance methods. Most methods we create in Java classes are
instance methods.
2. Static Methods: Static methods belong to the class itself, rather than instances of the class. They can
only access static members (variables and methods) of the class and are called using the class name,
not an instance.
3. Getter and Setter Methods: These are special types of instance methods used to access (get) or
modify (set) the values of private instance variables. They are commonly used for encapsulation.
4. Constructor Methods: Constructors are special methods used to initialize objects when they are
created. They have the same name as the class and do not have a return type. we can have multiple
constructors with different parameter lists (overloading).
public MyClass() {
// Default constructor
}
public MyClass(int value) {
// Parameterized constructor
}
5. Method Overloading: Method overloading allows us to define multiple methods in the same class
with the same name but different parameter lists (number or types of parameters). The compiler
determines which method to call based on the arguments provided.
6. Varargs Methods: A varargs (variable-length argument) method allows us to pass a variable number
of arguments of the same type to a method. Inside the method, these arguments are treated as an array.
7. Recursive Methods: Recursive methods are methods that call themselves. They are often used for
solving problems that can be broken down into smaller, similar sub-problems.
8. Methods with Return Values:These methods return a value of a specified data type.They are used
when we want to perform a calculation or operation and return the result.Example:
public int add(int a, int b) {
return a + b;
}
9.Methods with Parameters:These methods accept input parameters (arguments) that can be used in
the method body.Parameters are variables that hold values passed to the method when it is called.public
void greet(String name) {
System.out.println("Hello, " + name + "!");
}
10.Methods with Multiple Parameters:These methods can accept more than one parameter, allowing
we to pass multiple values to the method.Example:
public double calculateAverage(int num1, int num2, int num3) {
return (num1 + num2 + num3) / 3.0;
}
11.Void Methods: Void methods do not return any value. They are used when a method is meant to
perform an action or task without producing a result.
12.Getter and Setter Methods: These methods are used to access (get) or modify (set) the values of
private instance variables of a class.
12) Class: A class is a blueprint or a template that defines the structure and behavior of objects. It
serves as a blueprint for creating objects. A class encapsulates data for the object and provides methods
to manipulate that data.
OR
A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For
example, Student is a class while a particular student named Ravi is an object.
Declaration:
Example:
// Constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// Method
public void sayHello() {
System.out.println("Hello, my name is " + name);
}
}
In this example, we have a `Person` class with two fields (`name` and `age`), a constructor to initialize
those fields, and a method `sayHello` that prints a greeting using the person's name.
Using of class:Using a class in Java involves several steps, including defining the class, creating objects
from that class, and utilizing those objects. Here are the steps to use a class in Java:
1. Define the Class: First, define the class by specifying its attributes (fields), constructors, and methods.
Here's an example class definition for a `Car`:
public class Car {
// Fields
String make;
String model;
int year;
// Constructor
public Car(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
// Method
public void start() {
System.out.println("Starting the " + year + " " + make + " " + model);
}
}
2. Create Objects (Instances): To use a class, we need to create objects (instances) of that class.
Objects are specific instances of the class with their own unique data. we create objects using the `new`
keyword followed by the class constructor. Here's how we can create two `Car` objects:
3. Access Fields and Methods: Once we have objects, we can access their fields and methods using
the dot notation (`.`). For example:
// Accessing fields
System.out.println("Car 1: " + car1.make + " " + car1.model + " " + car1.year);
System.out.println("Car 2: " + car2.make + " " + car2.model + " " + car2.year);
// Accessing methods
car1.start();
car2.start();
In this code, we're accessing the `make`, `model`, and `year` fields of `car1` and `car2`, as well as
calling the `start` method on both objects.
4. Use Objects for web Application Logic: we can use the objects we've created in web application
logic. For example, we might perform calculations or make decisions based on the data stored in the
objects.
Example:
// Access fields
System.out.println("Car 1: " + car1.make + " " + car1.model + " " + car1.year);
System.out.println("Car 2: " + car2.make + " " + car2.model + " " + car2.year);
// Access methods
car1.start();
car2.start();
}
}
When we run this program, it will create two `Car` objects, access their fields, and invoke their `start`
methods to display output indicating that the cars are starting.
○ Identity: An object identity is typically implemented via a unique ID. The value of the ID
is not visible to the external user. However, it is used internally by the JVM to identify
each object uniquely.
For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is used
to write, so writing is its behavior.
An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.
Object Definitions:
Creating object of class: To create an object of a class in Java, we need to follow these steps:
1. Define a Class: First, we need to define a class that describes the attributes and behaviors of the
objects we want to create. A class is like a blueprint for creating objects.
2. Create an Object: To create an object of the class, use the `new` keyword followed by the class's
constructor.
3. Access Object Members: we can access the attributes and methods of the object using the dot
(`.`) notation.
public class Main {
public static void main(String[ ] args) {
// Create an object of MyClass
MyClass myObject = new MyClass(42, "John Doe");
myObject.displayInfo();
}
}
The above code demonstrates how to create an object of a class, set its attributes, and call its
methods.
Remember that each object created from the class has its own set of attributes, and changes made
to one object do not affect others. Objects are instances of a class, and we can create multiple
objects of the same class with different attribute values and behaviors.
A garbage collector is a component of the Java Virtual Machine (JVM) responsible for automatically
managing memory by reclaiming memory occupied by objects that are no longer in use or accessible by
the program. The primary purpose of the garbage collector is to prevent memory leaks and allow
developers to write Java code without the need for manual memory management, such as explicit
memory allocation and deallocation.
Definition: A garbage collector in Java is a part of the JVM that automatically identifies and reclaims
memory occupied by objects that are no longer reachable or referenced by the program, ensuring
efficient memory usage and eliminating the risk of memory-related errors.
1. Automatic Memory Management: The garbage collector handles memory allocation and
deallocation automatically, making it easier for developers to write memory-safe and robust Java
programs.
2. Detection of Unreachable Objects: The garbage collector periodically scans the heap (the
region of memory where objects are allocated) to identify objects that are no longer reachable from
the root references in the program. These root references include local variables, instance variables,
and static variables.
3. Reclamation of Memory: Once the garbage collector identifies objects that are no longer
reachable, it releases the memory occupied by these objects, making it available for future memory
allocations.
4. Mark and Sweep Algorithm: The most common garbage collection algorithm used in Java is the
"Mark and Sweep" algorithm. During this process, the garbage collector marks objects that are still in
use and then sweeps through the memory to remove unreferenced objects.
5. Finalization: Before an object is collected, its `finalize()` method (if overridden) is called. This
allows objects to perform cleanup operations before being reclaimed. However, relying on `finalize()`
is discouraged in modern Java development.
6. Tuning: Java provides various garbage collection settings and options to fine-tune the garbage
collection process based on the specific needs of an application. Developers can choose different
garbage collection algorithms and adjust memory-related parameters to optimize performance and
reduce pause times during garbage collection.
14) Garbage Collector: Garbage collection is a process of destroying the unused objects.
● In java, garbage collection is performed automatically by JVM.
● When there is no reference to an object, then that object is assumed to be no longer needed
and the memory occupied by that object will be released. This technique is called Garbage
collection.
● JVM calls Garbage Collector(GC) method to free the memory occupied by the unreferenced
object.
● gc() method is present in the system and runtime classes.
● JVM calls the gc()method, and the gc() method calls the finalize() method.
● finalize() method is present in the object class.
● After the finalize() method is executed, gc() method performs its task, i.e sweeping out
unreferenced objects.
Ways to know garbage:
Student obj1= new Student();
1.obj1=null;
2.obj1-obj2;
3.new Student();
Example:
Class A
{
public static void main(String args[ ])
{
A obj1= new A();
A obj2= new A();
obj1= null;
obj2=null;
Public void finalize()
{ System.out.println(“this is a finalize method”);
}
System.gc();
}
}
15) Arrays: An array is a data structure that allows we to store a collection of elements of the same
data type under a single variable name. These elements are stored in contiguous memory locations, and
we can access them by their index position within the array.
1. Single-Dimensional Arrays:A single-dimensional array is a list of elements of the same type that are
accessed by a single index or subscript. It is also known as a one-dimensional array.
Declaration syntax: `dataType[ ] arrayName;` or `dataType arrayName[ ];`
Example:
int[ ] numbers = new int[5]; // Creates an integer array of size 5
Remember that in Java, arrays have a fixed size once they are created, and we cannot change their size
dynamically. If we need a dynamically resizable collection of elements, we might want to consider using
other data structures, such as ArrayList from the Java Collections Framework.
Arrays in Java are zero-indexed, which means that the first element is accessed using index `0`, the
second element with index `1`, and so on. The last element of an array with `n` elements is accessed
using index `n-1`.
Array of Character:
components:
we can access individual elements of the character array using their index, just like we would with any
other array in Java. For example:
Remember that in Java, arrays are zero-indexed, so the first element is at index 0, the second element is
at index 1, and so on.
16) Strings: In Java, a string is a sequence of characters,and its index starts from zero.String is a
predefined class in Java, but we can also use it as datatype, and it is represented by the `String` class.
Strings are used to store and manipulate text-based data. String is an object that represents a sequence
of characters. It is part of the `java.lang` package Here's how we can define strings in Java:
In this example, the `greeting` variable holds the string "Hello, World!".
While this method is less commonly used for creating strings, it can be useful in certain situations where
we need more control over memory allocation.
Strings in Java are immutable, which means their values cannot be changed after they are created.
However, we can perform various operations on strings, such as concatenation, substring extraction, and
comparison, using methods provided by the `String` class.
Characteristics:
1. Immutable: Strings in Java are immutable, which means that once a string object is created, its value
cannot be changed. If we want to modify a string, we create a new string object.
2. String Literal: we can create a string using double quotes. For example: `"Hello, World!"`. This is
known as a string literal.
3. String Object: we can also create a string using the `new` keyword, which creates a string object. For
example: `String str = new String("Hello, World!");`.
4. Concatenation: we can concatenate strings using the `+` operator. For example:
5. Length: we can find the length (number of characters) of a string using the `length()` method. For
example:
6. Indexing: we can access individual characters in a string using their index (position). In Java, indexing
starts at 0. For example:
7. String Methods: The String class provides many useful methods for working with strings, such as
`substring()`, `indexOf()`, `toUpperCase()`, `toLowerCase()`, etc.
9. String Literals Pool: Java maintains a special memory area called the "string pool" where string
literals are stored. When we create a string literal, Java checks if it already exists in the pool. If it does, it
reuses the existing object. This can save memory.
Remember, because strings are immutable, any operation that appears to modify a string actually creates
a new string object. This can be inefficient for a large number of operations, which is why `StringBuilder`
and `StringBuffer` are preferred in such cases.
Operations on String:
In Java, we can perform various operations on strings, such as manipulation, searching, splitting, and
formatting. Here are some common operations on strings in Java:
1. **Concatenation**: You can combine two or more strings using the `+` operator or the `concat()`
method.
2. **Substring**: You can extract a portion of a string using the `substring()` method, specifying the
starting and ending indexes.
3. **Length**: You can find the length (number of characters) of a string using the `length()` method.
4. **Character Access**: You can access individual characters in a string using their index (position). In
Java, indexing starts at 0.
5. **String Comparison**: You can compare strings for equality using the `equals()` method or
`equalsIgnoreCase()` for case-insensitive comparison.
7. **Replacing**: You can replace characters or substrings within a string using the `replace()` method.
8. **Splitting**: You can split a string into an array of substrings based on a delimiter using the `split()`
method.
9. **Trimming**: You can remove leading and trailing whitespace characters from a string using the
`trim()` method.
10. **Formatting**: You can format strings using `String.format()` or `printf()`-style formatting.
11. **Converting to/from Other Types**: You can convert strings to other data types using methods like
`parseInt()` and `valueOf()`. Conversely, you can convert other types to strings using the `toString()`
method.
12. **String Case Conversion**: You can convert the case of strings using `toUpperCase()` and
`toLowerCase()` methods.
String text = "Hello, World!";
String uppercase = text.toUpperCase(); // "HELLO, WORLD!"
String lowercase = text.toLowerCase(); // "hello, world!"
These are some of the most common operations you can perform on strings in Java. Depending on your
specific needs, you may need to use these operations in various combinations to manipulate and work
with strings effectively.
4) String Buffer Class: A string buffer is a mutable sequence of characters that provides a way
to efficiently manipulate strings. It is part of the Java Standard Library and is implemented by the
`StringBuffer` class. The key characteristic of a string buffer is its ability to modify the contents of the
string without creating a new string object each time a modification is made. This makes string buffers
more efficient than regular strings when performing multiple concatenations or modifications.
Here are some important characteristics and methods associated with the `StringBuffer` class:
1. Mutable: Unlike regular Java strings (`String`), which are immutable (cannot be changed once
created), `StringBuffer` allows you to modify the content of the string it holds.
2. Thread-Safe: `StringBuffer` is designed to be thread-safe, meaning it can be safely used in
multi-threaded environments without the need for external synchronization. However, this thread safety
comes at the cost of some performance overhead.
3. Performance: `StringBuffer` is more efficient than using regular string concatenation (e.g., using the
`+` operator) when you need to make frequent modifications to a string, as it avoids the creation of new
string objects.
- `append(String str)`: Appends the specified string to the end of the buffer.
- `insert(int offset, String str)`: Inserts the specified string at the given offset within the buffer.
- `delete(int start, int end)`: Removes characters from the buffer within the specified range.
- `replace(int start, int end, String str)`: Replaces characters within the specified range with the
specified string.
- `length()`: Returns the current length (number of characters) of the buffer.
- `toString()`: Converts the `StringBuffer` object to a regular string so that you can use it in contexts
where a `String` is required.
Example:
public class StringBufferExample {
public static void main(String[] args) {
StringBuffer stringBuffer = new StringBuffer("Hello, ");
stringBuffer.append("world!"); // Appends "world!" to the end of the buffer.
UNIT-2
1) Existing class(predefined): In Java, an existing class refers to a class that has already
been defined and is available for use in your program. These classes are part of the Java Standard
Library or may be classes that you or other developers have created in your project. Existing classes
provide a set of methods and attributes that you can use to perform various tasks or implement
functionality in your Java program without having to redefine everything from scratch.
For example, you can use existing classes like `String`, `ArrayList`, `File`, and many others to work
with strings, collections, and file operations, respectively. These classes are provided by the Java
API and can be used in your programs after importing the necessary packages.
Here's an example of using an existing class, `ArrayList`, to create and manipulate a list of integers:
```java
import java.util.ArrayList; // Import the ArrayList class
In this example, `ArrayList` is an existing class that is used to create and work with lists of integers.
You import it using the `import` statement, create an instance of it, and then use its methods (`add`,
`get`, etc.) to interact with the list. Existing classes like `ArrayList` simplify programming by providing
pre-defined functionality for common tasks.
1) Existing class:In Java, a class is a blueprint or template for creating objects. An existing
class in Java refers to a class that has already been defined and implemented in your codebase or
within a library. These classes can be used to create objects (instances) that inherit the properties
and behaviors defined in the class.
Here's a basic example of how to define an existing class in Java:
// Constructor
public MyClass(int initialValue) {
this.myField = initialValue;
}
// Methods
public void doSomething() {
System.out.println("Doing something with myField: " + myField);
}
In this example, `MyClass` is an existing class that defines a blueprint for creating objects. It has a
private field `myField`, a constructor for initializing this field, and two methods (`doSomething`,
`getMyField`, and `setMyField`) to manipulate and access the field.
You can create instances of this class and use them in your code like this:
In this code, you create an instance of the `MyClass` class using the `new` keyword, and then you
can access its methods and fields using the instance. Existing classes are fundamental building
blocks in Java programming, allowing you to encapsulate data and behavior into reusable
components.
There are several types of inheritance in Java, each serving different purposes:
1. **Single Inheritance**:
- Single inheritance means that a class can inherit from only one superclass.
- In Java, classes can extend at most one superclass.
- For example:
```java
class Subclass extends Superclass {
// Subclass inherits from Superclass
}
```
2. **Multilevel Inheritance**:
- In multilevel inheritance, a subclass inherits from another subclass, creating a chain of
inheritance.
- For example:
```java
class A {
// ...
}
class B extends A {
// B inherits from A
}
class C extends B {
// C inherits from B, which inherits from A
}
```
3. **Hierarchical Inheritance**:
- Hierarchical inheritance involves multiple subclasses inheriting from a single superclass.
- Each subclass may have its own additional members and behaviors.
- For example:
```java
class Animal {
// ...
}
interface Swimmable {
void swim();
}
3)Superclass or subclass:
definition The class from which other classes inherit Class that inherits attributes and
properties and behavior. methods from a base class.
Keyword/syntax Defined using the “class” keyword. Defined using the “class” keyword
with “extends” to specify the base
class
purpose Provides a common template or blueprint for Extends the functionality of the base
creating derived classes class by adding new attributes and
methods or by overriding inherited
methods.
Access to base class Derived class inherits public and protected Inherits members from the base class
member members of the base class. Private members and can access public and protected
of the base class are not accessible in derived members, Private members are not
class accessible.
Method overriding Base class methods can be overridden in the Derived class can override inherited
derived class to provide custom methods to provide its own
implementations implementation(method overriding)
Inheritance types Provides a “is-a” relationship, indicating that a Extends the base class, specializing
derived class is a type of the base class. or adding features to it.
Number of base A class can have one base class(single Extends the base class, specializing
classes inheritance) or adding features to it.
Code reusability Promotes code reusability by providing a Allows for code reuse while extending
common structure or modifying behaviour
class Animal {
String name;
In this example, `Animal` is the base class (superclass), and `Dog` is the derived class (subclass).
`Dog` inherits from `Animal` and extends its functionality by adding the `breed` attribute and the
`bark()` method.
When we are designing a class hierarchy, choosing a base class (also known as a superclass) is an
important decision. The base class serves as a template for derived classes (subclasses) and
defines common behaviors and characteristics that subclasses inherit. Here are some considerations
and guidelines for choosing a base class in Java:
3. Encapsulation:
- The base class should encapsulate shared behavior and data that is relevant to all subclasses.
Make sure to declare class members (fields and methods) with appropriate access modifiers (public,
protected, private) to control visibility and access.
5. Common Interfaces:
- Consider defining common interfaces that your classes can implement. This is especially useful
when your classes belong to different inheritance hierarchies but still share some functionality.
Example
class Animal {
private String name;
@Override
public void speak() {
System.out.println(name + " barks");
}
}
@Override
public void speak() {
System.out.println(name + " meows");
}
}
In this example, `Animal` is the base class, and `Dog` and `Cat` are subclasses that inherit common
behavior from `Animal`.
```java
class Animal {
void eat() {
System.out.println("Animal is eating.");
}
}
This creates a multiple levels of inheritance hierarchy: `Dog` inherits from `Mammal`, which inherits
from `Animal`. As a result, `Dog` has access to the methods and properties of both its parent classes
(`Mammal` and `Animal`) in addition to its own methods.
Keep in mind that while multiple levels of inheritance can be useful for organizing and reusing code,
it should be used judiciously to avoid creating overly complex and tightly coupled class hierarchies.
In some cases, composition or interface-based design may be preferred over deep inheritance
hierarchies to achieve better code maintainability and flexibility.
1. Abstract Classes: Java provides the `abstract` keyword to define abstract classes. An abstract
class cannot be instantiated directly; instead, it serves as a template for other classes to inherit from.
Abstract classes can have abstract methods (methods without a body) that must be implemented by
any concrete subclass.
2. Abstract Methods: Abstract methods are declared without a method body, using the `abstract`
keyword. Subclasses of an abstract class must provide concrete implementations for all abstract
methods.
3. Interface: Java also supports abstraction through interfaces. An interface defines a contract of
methods that classes implementing the interface must adhere to.
interface Drawable {
void draw();
}
4. Concrete Classes: Concrete classes are classes that provide implementations for all the methods
declared in abstract classes or interfaces. These classes can be instantiated and used directly.
class Circle extends Shape {
private double radius;
@Override
public double area() {
return Math.PI * radius * radius;
}
}
In summary, abstraction in Java allows you to create a hierarchy of classes and interfaces, where
abstract classes and methods define the common structure and behavior that subclasses or
implementing classes must follow. This concept helps in managing complexity, promoting code
reusability, and enforcing a clear separation between the interface and implementation of classes.
An abstract class is a class that cannot be instantiated on its own and is often used as a blueprint for
other classes. It allows you to define methods with or without implementations that can be overridden
by its subclasses. Abstract classes are used to achieve abstraction in object-oriented programming,
where you define a common interface or structure that multiple related classes can share.
Here's how you create an abstract class and use it for abstraction in Java:
```java
abstract class Shape {
// Abstract method (no implementation)
public abstract double calculateArea();
In this example, we've created an abstract class called `Shape`. It contains an abstract method
`calculateArea()` and a regular method `display()`.
2. Create Subclasses:
Subclasses of an abstract class must provide concrete implementations for all the abstract
methods declared in the abstract class. Otherwise, the subclass must also be declared as abstract.
class Circle extends Shape {
private double radius;
@Override
public double calculateArea() {
return Math.PI * radius * radius;
}
}
@Override
public double calculateArea() {
return length * width;
}
}
In this example, we have two subclasses, `Circle` and `Rectangle`, that extend the `Shape` abstract
class. Each subclass provides its own implementation for the `calculateArea()` method.
circle.display();
System.out.println("Circle Area: " + circle.calculateArea());
rectangle.display();
System.out.println("Rectangle Area: " + rectangle.calculateArea());
}
}
In this example, we create instances of `Circle` and `Rectangle`, but we declare them as `Shape`.
This demonstrates polymorphism and abstraction, as we can call the `calculateArea()` method on
these objects without knowing their specific types.
Abstract classes are a powerful tool for achieving abstraction and providing a common interface for
related classes while allowing each subclass to implement its own behavior.
6) Final Modifier:The `final` modifier is used to restrict the behavior of a class, method, or
variable. When you declare a class, method, or variable as `final`, it means that it cannot be further
modified or extended. The exact behavior of `final` depends on where it is applied:
1. **Final Variables:**
- When applied to a variable, it means that the variable's value cannot be changed after it is
initialized. It essentially makes the variable a constant.Example:
final int MAX_VALUE = 100;
// You can't change the value of MAX_VALUE later in the code.
2. **Final Methods:**
- When applied to a method, it means that the method cannot be overridden by subclasses. It
enforces that the method's implementation is fixed and cannot be changed in subclasses. Example:
class Parent {
final void display() {
System.out.println("This is a final method.");
}
}
3. **Final Classes:**
- When applied to a class, it means that the class cannot be extended (i.e., no subclasses can be
created). It's often used to prevent inheritance for security or design reasons. Example:
The primary motivations for using the `final` modifier include ensuring immutability, preventing
method overriding or subclassing, and sometimes improving performance by allowing certain
optimizations by the compiler.
In summary, `final` is a keyword in Java that is used to make variables, methods, or classes
immutable or unextendable, depending on where it is applied.
7) Package: A package is nothing but a physical folder structure (directory) that contains a
group of related classes, interfaces, and sub-packages according to their functionality. It provides a
convenient way to organize your work. The Java language has various in-built packages.
For example, java.lang, java.util, java.io, and java.net. All these packages are defined as a very clear
and systematic packaging mechanism for categorizing and managing.
1.Predefined: Predefined packages are packages that are provided by the Java Standard Library
(Java API) and are automatically available for use in your Java programs without requiring any
explicit import statements. These packages contain classes and interfaces that provide a wide range
of functionality for common programming tasks. Here are some of the most commonly used
predefined packages in Java:
1. `java.lang`: This package is automatically imported into all Java programs and includes
fundamental classes like `Object`, `String`, `Integer`, `Double`, and others. It also provides essential
classes and exceptions for Java programs.
2. `java.util`: This package contains classes and interfaces for working with data structures like lists,
sets, maps, and various utility classes for tasks like date and time handling, random number
generation, and more.
3. `java.io`: This package provides classes for input and output operations, including reading and
writing files, working with streams, and handling file system operations.
4. `java.net`: This package is used for networking in Java, providing classes for working with sockets,
URLs, and network communication.
5. `java.awt` and `javax.swing`: These packages are used for creating graphical user interfaces
(GUIs) in Java. `java.awt` contains the Abstract Window Toolkit (AWT) classes, while `javax.swing`
provides more advanced Swing components for GUI development.
6. `java.sql`: This package contains classes and interfaces for database connectivity and working
with relational databases using JDBC (Java Database Connectivity).
7. `java.security`: This package offers classes for implementing security features in Java
applications, including cryptography and authentication.
8. `java.math`: This package contains classes for arbitrary-precision arithmetic, which is useful for
handling very large numbers with precision.
9. `java.text`: This package provides classes for formatting and parsing text, numbers, and dates
according to different locales.
10. `java.util.concurrent`: This package includes classes and interfaces for concurrent and
multithreaded programming, such as thread pools, synchronization primitives, and concurrent data
structures.
11. `java.nio`: This package offers classes for non-blocking I/O operations, which are essential for
building scalable and efficient network applications.
12. `java.beans`: This package is used for developing JavaBeans, which are reusable software
components.
2.User-Defined:In Java, user-defined packages are custom packages created by developers to
organize and encapsulate their classes and interfaces into logical groups. These packages help in
managing the complexity of larger Java applications by providing a structured way to organize and
access related classes. Here's how you can create and use user-defined packages in Java:
1. **Create a Package**: To create a user-defined package, you need to follow these steps:
- Choose a unique package name for your application or project. Conventionally, package names are
in reverse domain name format, e.g., `com.example.myapp`.
- Organize your Java source code files into directories that match the package structure. For
example, if your package is `com.example.myapp`, your source code files should be located in a
directory structure like this:
com
└── example
└── myapp
├── MyClass1.java
├── MyClass2.java
└── ...
- At the beginning of each Java source file that you want to include in the package, specify the
package declaration. For example, in `MyClass1.java`:
package com.example.myapp;
2. **Compile and Use the Package**: After creating your package and organizing your classes, you
can compile the Java files. Use the `javac` command with the `-d` option to specify the output
directory for the compiled classes. For example:
This will compile your classes and place the compiled `.class` files in the appropriate directory
structure matching the package.
3. **Import and Use Classes**: To use classes from your user-defined package in other Java
classes, you can import them using the `import` statement. For example:
import com.example.myapp.MyClass1;
import com.example.myapp.MyClass2;
User-defined packages are helpful for maintaining code organization, avoiding naming conflicts, and
improving code readability in larger Java projects. They also facilitate the reuse of code across
different parts of an application or even in different applications when the packages are
well-designed and organized.
1. Maintenance: Java packages are used for proper maintenance. If any developer newly joined a
company, he can easily reach the files needed.
2. Reusability: We can place the common code in a common folder so that everybody can check
that folder and use it whenever needed.
3. Name conflict: Packages help to resolve the naming conflict between the two classes with the
same name. Assume that there are two classes with the same name Student.java. Each class will be
stored in its own packages such as stdPack1 and stdPack2 without having any conflict of names.
5. Access Protection: A package provides access protection. It can be used to provide visibility
control. The members of the class can be defined in such a manner that they will be visible only to
elements of that package.
To add and use classes from a package in your Java project, you need to perform the following
steps:
1. **Import the Package**: In the Java file where you want to use classes from a package, use the
`import` statement to import the specific classes or the entire package. This is typically done at the
top of your Java file. For example:
import com.example.myapp.Person;
// or
// import com.example.myapp.*;
The first line imports the `Person` class from the `com.example.myapp` package, while the second
line imports all classes within the `com.example.myapp` package.
2. **Use the Imported Classes**:Once you've imported the package or specific classes, you can
use them in your Java code. Here's an example using the `Person` class from the previous example:
person.sayHello();
3. **Compile and Run the Java File**:Compile the Java file that uses the classes from the package.
If you're using an IDE, it usually handles compilation for you. If you're using the command line, you
can compile the file like this:
```
javac Main.java
```
```
java Main
```
By following these steps, you can add and use classes from a package in your Java project. The
`import` statement allows you to bring in classes or packages from other parts of your project or
external libraries, making it easier to organize and reuse code.
Access protection in packages: Access protection in packages is controlled through the use of
access modifiers on classes, interfaces, methods, and variables. Access modifiers specify the level
of visibility and access that classes, methods, and fields have within a package and to other
packages. There are four main access modifiers in Java:
1. `public`: The class, method, or field is accessible from anywhere, both within and outside the
package.
2. `protected`: The class, method, or field is accessible within the package and also by subclasses,
even if they are in different packages.
3. `default` (no modifier): If no access modifier is specified, the class, method, or field is accessible
only within the package (package-private).
4. `private`: The class, method, or field is accessible only within the declaring class and is not
accessible from other classes, even within the same package.
Here's a more detailed explanation of how these access modifiers work in packages:
1. `public`: If you declare a class, method, or field as `public`, it can be accessed from any other
class, regardless of whether it is in the same package or a different package.
```java
```
2. `protected`: When you declare a class member as `protected`, it can be accessed within the
same package, as well as by subclasses, even if those subclasses are in different packages.
```java
package mypackage;
```
```java
package otherpackage;
import mypackage.ProtectedClass;
void someMethod() {
```
```java
package mypackage;
class DefaultClass {
void defaultMethod() {
```
4. `private`: When a class member is declared as `private`, it is accessible only within the declaring
class and not accessible from any other class, even if they are in the same package.
```java
```
These access modifiers help you control the visibility and access levels of classes, methods, and
fields within your packages, allowing you to implement encapsulation and manage the level of
abstraction in your Java programs effectively.
When you run a Java program, the JVM searches for the classes and resources required by your
program in the directories and JAR files listed in the `CLASSPATH`. If a class or resource is not
found in the specified locations, you'll get a "Class not found" or "NoClassDefFoundError" error.
Here's an example of how you can set the `CLASSPATH` environment variable:
On Windows:
```bash
set CLASSPATH=C:\path\to\directory1;C:\path\to\directory2;C:\path\to\mylib.jar
```
```bash
export CLASSPATH=/path/to/directory1:/path/to/directory2:/path/to/mylib.jar
```
You can also specify the `CLASSPATH` when running a Java application using the `-cp` or
`-classpath` option:
```bash
```
It's important to note that specifying the `CLASSPATH` as an environment variable can affect the
entire system, so it's generally a good practice to set it temporarily or within a specific script or
command to avoid unintended consequences. Additionally, modern Java development practices
often use build tools like Apache Maven or Gradle, which manage dependencies and the classpath
for you, reducing the need to manually configure the `CLASSPATH`.
8) Interfaces: An interface is a blueprint for a class that defines a set of methods that must be
implemented by any class that implements the interface. It provides a way to achieve abstraction and
define a contract that classes must adhere to. Interfaces are declared using the `interface` keyword
and can contain method declarations, but these methods have no implementation. Classes that
implement an interface must provide concrete implementations for all the methods declared in the
interface.
interface MyInterface {
void method1();
int method2();
1. **Normal Interface**: This is the most common type of interface. It can have method declarations
without any default implementations. Any class that implements this interface must provide concrete
implementations for all of its methods.
interface MyInterface {
void method1();
int method2();
```
2. **Functional Interface**: A functional interface is a special type of interface that has exactly one
abstract method. It can have multiple default or static methods, but it must have only one abstract
method. Functional interfaces are often used in Java to work with lambda expressions and functional
programming concepts. The `@FunctionalInterface` annotation can be used to indicate that an
interface is intended to be functional.
@FunctionalInterface
interface MyFunctionalInterface {
void method1();
3. **Marker Interface**: Marker interfaces are interfaces that do not declare any methods. They are
used to mark classes for some specific behavior or characteristics. For example, the `Serializable`
interface in Java is a marker interface that indicates that a class can be serialized.
interface Serializable {
// No methods declared
```
4. **Default Methods**: Java 8 introduced a feature that allows interfaces to have default method
implementations. These methods have the `default` keyword before their declaration and provide a
default implementation that can be optionally overridden by implementing classes.
interface MyInterface {
void method1();
5. **Static Methods**: Java 8 also introduced static methods in interfaces. Static methods in
interfaces are declared with the `static` keyword and can be called on the interface itself, not on
implementing classes.
interface MyInterface {
}
6. **Nested Interfaces**: Java allows you to define interfaces within other interfaces or classes.
These nested interfaces are sometimes used to group related functionality.
interface OuterInterface {
void outerMethod();
interface InnerInterface {
void innerMethod();
These are the main types of interfaces in Java, each serving different purposes and allowing you to
define contracts and behaviors for classes that implement them.
Implementing an Interfaces: We can implement an interface by creating a class that uses the
`implements` keyword, followed by the interface name. When a class implements an interface, it
must provide concrete implementations for all the methods declared in that interface. Here's a
step-by-step guide on how to implement an interface in Java:
1. Define an interface:
Start by creating an interface that declares the methods you want the implementing class to
provide. Here's an example:
double calculateArea();
double calculatePerimeter();
Create a class that implements the interface by using the `implements` keyword. This class must
provide concrete implementations for all the methods declared in the interface. For example:
this.radius = radius;
}
@Override
@Override
In this example, the `Circle` class implements the `Shape` interface and provides its own
implementations for the `calculateArea()` and `calculatePerimeter()` methods.
You can now create instances of the class and use the methods declared in the interface:
This code creates a `Circle` object, calculates its area and perimeter, and prints the results.
That's how you implement an interface in Java. It allows you to define a contract that classes must
adhere to, ensuring a certain level of consistency and compatibility among different classes that
implement the same interface.
Multiple interfaces in java: An interface is a reference type that specifies a set of abstract
methods (methods without a body) that a class implementing the interface must provide concrete
implementations for. A class can implement multiple interfaces, which means it can inherit and
implement the abstract methods declared in each of those interfaces. This concept is known as
multiple interface inheritance.
interface Interface1 {
void method1();
interface Interface2 {
void method2();
In this example, we've defined two interfaces, `Interface1` and `Interface2`, each of which declares a
single abstract method (`method1` and `method2`, respectively).
@Override
@Override
In this example, `MyClass` implements both `Interface1` and `Interface2` and provides concrete
implementations for the `method1` and `method2` methods declared in these interfaces.
By implementing multiple interfaces, a class can inherit and provide implementations for the methods
declared in each interface, allowing for flexible and modular code design.
Constants in interfaces: An interface can declare constants, which are implicitly `public`,
`static`, and `final`. These constants are effectively like global variables that are associated with the
interface itself. Any class that implements the interface can access these constants.
void someMethod();
In this example, `MAX_VALUE` and `DEFAULT_NAME` are constants. They are implicitly `public`,
`static`, and `final`, so you don't need to explicitly use those modifiers. They can be accessed like
`MyInterface.MAX_VALUE` or `MyInterface.DEFAULT_NAME`.
Extending interface: In Java, you can extend interfaces using the `extends` keyword, similar to
how you extend classes with the `extends` keyword. When one interface extends another interface, it
means that the extending interface inherits the abstract methods and constants (if any) declared in
the extended interface. Extending an interface allows you to add more abstract methods to the new
interface, effectively incorporating the methods of the parent interface(s) while adding new methods
or refining the existing ones. Here's how you can extend interfaces in Java:
1. Creating a Parent Interface:Define the parent interface that you want to extend. This interface
can have one or more abstract methods.
void method1();
void method2();
2. Creating a Child Interface: To extend the parent interface, create a child interface using the
`extends` keyword. You can add new abstract methods to the child interface in addition to inheriting
the methods from the parent interface.
void newMethod();
}
In the example above, `ChildInterface` extends `ParentInterface` using `extends` and also introduces
a new abstract method `newMethod()`.
3. Implementing Interfaces: Classes that implement the child interface (`ChildInterface` in this
case) must provide implementations for all abstract methods declared in both the parent
(`ParentInterface`) and child interfaces.
@Override
@Override
@Override
Nested Interface: In Java, you can define nested interfaces within other interfaces, classes, or
even enums. A nested interface is an interface that is declared inside another interface, class, or
enum. Nested interfaces are used to logically group related constants, methods, or types within a
parent interface or class. They can be accessed using the dot notation, like
`OuterInterface.InnerInterface`.
```java
interface OuterInterface {
void outerMethod();
// Nested interface
interface InnerInterface {
void innerMethod();
}
}
```
In the example above, `InnerInterface` is a nested interface within `OuterInterface`. You can
implement both the outer and inner interfaces in a class like this:
```java
class MyClass implements OuterInterface, OuterInterface.InnerInterface {
@Override
public void outerMethod() {
System.out.println("Implementing outerMethod");
}
@Override
public void innerMethod() {
System.out.println("Implementing innerMethod");
}
}
```
To use the nested interface, you would typically access it through the outer interface, like this:
This allows you to group related functionality and provide a more structured and organized
codebase. Nested interfaces are commonly used in Java when defining constants or specifying
behavior for nested classes or enums.
Methods in interfaces: In Java, you can declare methods within interfaces. These methods are
called "abstract methods" and do not have a method body. Classes that implement these interfaces
are required to provide concrete implementations for these methods. Java 8 introduced a feature
called "default methods" and "static methods" in interfaces, which allow you to provide method
implementations directly within the interface itself.
1. Abstract Methods:
- These are traditional interface methods that have no method body (no implementation).
- Any class that implements the interface must provide concrete implementations for all abstract
methods declared in that interface.
interface MyInterface {
- Default methods have a method body and are marked with the `default` keyword.
- Classes that implement the interface can choose to override these default methods, but it's not
mandatory.
- Default methods were introduced to provide backward compatibility when adding new methods to
existing interfaces without breaking existing implementations.
Example:
interface MyInterface {
- They are called on the interface itself and are not inherited by implementing classes.
- These methods are typically used for utility functions related to the interface.
Example:
interface MyInterface {
When you implement an interface, you must provide concrete implementations for all abstract
methods, but you have the option to override default methods if needed.
Here's an example of a class implementing an interface with all three types of methods:
@Override
System.out.println("Implementing abstractMethod.");
In summary, interfaces in Java can contain abstract methods, default methods, and static methods.
These features provide more flexibility and backward compatibility when designing and evolving
interfaces in your code.
Variables in interfaces: Interface variables are implicitly considered as `public`, `static`, and
`final`. These variables are also known as "constant variables" because they are declared with the
`final` keyword and cannot be modified once they are assigned a value. Since they are `static`, they
belong to the interface itself rather than any specific instance of a class that implements the
interface. Here's the syntax for declaring interface variables:
```java
```
1. `public`: Interface variables are implicitly `public`, which means they can be accessed from any
class that implements the interface.
2. `static`: Interface variables are implicitly `static`, which means they belong to the interface itself
and can be accessed using the interface name, not through instances of classes that implement the
interface.
3. `final`: Interface variables are implicitly `final`, which means their values cannot be changed once
they are assigned a value. They are constants.
4. Initialization: Interface variables must be initialized at the point of declaration. You cannot declare
an uninitialized interface variable.
Here's how you can access an interface variable from a class that implements the interface:
```java
```
In this example, `MyClass` implements `MyInterface` and can access the `MY_CONSTANT` variable
from the interface directly using the interface name.
UNIT-3
1) Exception: An exception is an event that occurs during the execution of a program and
disrupts the normal flow of the program's instructions. When an exceptional event occurs, an object
representing that event is created, and the normal program flow is interrupted to handle the
exception. Exceptions are used to handle errors, unexpected conditions, or exceptional situations
that may arise during the execution of a Java program.
1. Checked Exceptions: These are exceptions that are checked at compile-time. Any method that
may throw a checked exception must declare it using the `throws` keyword in its method signature,
or handle it using a `try-catch` block. Examples of checked exceptions include `IOException`,
`FileNotFoundException`, and `SQLException`.
```java
try {
// Code that may throw a checked exception
} catch (IOException e) {
// Handle the exception
}
```
2. Unchecked Exceptions (Runtime Exceptions): These exceptions are not checked at
compile-time, and the program is not required to declare or catch them explicitly. They typically
indicate programming errors or unexpected runtime conditions. Examples include
`NullPointerException`, `ArrayIndexOutOfBoundsException`, and `ArithmeticException`.
```java
try {
// Code that may throw an unchecked exception
} catch (NullPointerException e) {
// Handle the exception
}
```
Java provides a built-in exception hierarchy, with the `Throwable` class at the top. It has two main
subclasses: `Error` and `Exception`. Errors represent severe, unrecoverable issues (e.g.,
`OutOfMemoryError`), while exceptions represent recoverable problems that can be handled by the
program.
Developers can create their custom exceptions by extending the `Exception` class or one of its
subclasses. Custom exceptions are useful when you want to handle specific situations in your
application.
2) Exception handling: Handling exceptions in Java is an essential part of writing robust and
reliable code. You can deal with exceptions using `try`, `catch`, `finally` blocks, and also by using the
`throws` clause to declare exceptions that a method may throw. Here's how you can deal with
exceptions in Java:
1. Using `try-catch` Blocks: We can use `try` and `catch` blocks to handle exceptions. The `try`
block contains the code that may throw an exception, and the `catch` block handles the exception if it
occurs. You can catch specific exceptions or use a generic `catch` block to catch any exception.
```java
try {
// Code that may throw an exception
} catch (ExceptionType1 e1) {
// Handle ExceptionType1
} catch (ExceptionType2 e2) {
// Handle ExceptionType2
} catch (Exception e) {
// Handle all other exceptions (generic catch)
}
```
2. Using `finally` Block: We can also use a `finally` block after a `try-catch` block. The code in the
`finally` block is executed regardless of whether an exception occurred or not. It is typically used for
cleanup operations.
```java
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle the exception
} finally {
// Cleanup code (e.g., closing resources)
}
```
3. Rethrowing Exceptions: We can rethrow an exception within a `catch` block to propagate it up
the call stack while still allowing you to perform some actions before doing so.
```java
try {
// Code that may throw an exception
} catch (Exception e) {
// Handle the exception
throw e; // Rethrow the exception
}
```
4. Using the `throws` Clause: If a method may throw a checked exception but doesn't want to
handle it, it can declare the exception using the `throws` clause. This informs the caller that the
method may throw the exception, and the caller is responsible for handling it.
```java
public void someMethod() throws CustomException {
// Code that may throw a CustomException
}
```
5. Creating Custom Exceptions: We can create your custom exceptions by extending the
`Exception` class or one of its subclasses. Custom exceptions allow you to handle specific situations
in your application gracefully.
```java
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
```
6. Using `try-with-resources` (Java 7 and later): When working with resources that implement the
`AutoCloseable` interface (e.g., `InputStream`, `OutputStream`, `java.sql.Connection`), you can use
the `try-with-resources` statement to automatically close these resources when you're done with
them.
```java
try (FileInputStream fis = new FileInputStream("file.txt")) {
// Use fis for reading
} catch (IOException e) {
// Handle the exception
}
// fis is automatically closed here
```
7. Logging and Error Reporting: It's a good practice to log exceptions or report errors so that you
can diagnose and debug issues in your application. Java provides various logging frameworks like
`java.util.logging`, `log4j`, and `SLF4J` for this purpose.
```java
try {
// Code that may throw an exception
} catch (Exception e) {
// Log the exception
logger.error("An exception occurred:", e);
}
3) Creating custom exceptions: A custom exception in Java is an exception that you
define in your code to represent specific error conditions that can occur within your application. By
creating custom exceptions, you can provide more meaningful error messages and better organize
your error-handling logic. Custom exceptions are typically derived from the built-in Exception class or
one of its subclasses like RuntimeException.
Suppose we want to create a custom exception for a hypothetical situation where a bank account
balance becomes negative. We'll call this exception `NegativeBalanceException`.
```java
// NegativeBalanceException.java
public class NegativeBalanceException extends Exception {
public NegativeBalanceException() {
super("Error: Account balance is negative.");
}
Next, let's create a bank account class that might throw this custom exception:
```java
// BankAccount.java
public class BankAccount {
The error class represents critical conditions Exception class represents concerning
that cannot be caught and handled by code of conditions raised by the application itself. These
the program. can be caught and handled within the code to
ensure that application run smoothly.
Errors are usually raised by the environment in Exceptions are caused by the code of the
which the application is running. application itself.
It is not possible to recover from an error. The use of try-catch blocks can handle
exceptions and recover the application from
them.
Errors occur at runtime and are not known by Exceptions can be unchecked or checked. They
the compiler hence they are classified as may or may not be caught by the computer.
“Unchecked”.
1. **User Threads**: These are regular threads created by the application developer to perform
specific tasks. User threads are the most common type of threads in Java applications.
```java
Thread userThread = new Thread(() -> {
// Thread's task
});
userThread.start();
```
2. **Daemon Threads**: Daemon threads are background threads that run in the background and
don't prevent the JVM from exiting when all user threads have finished executing. They are typically
used for tasks that don't require the program to wait for their completion.
```java
Thread daemonThread = new Thread(() -> {
// Daemon thread's task
});
daemonThread.setDaemon(true);
daemonThread.start();
```
3. **Main Thread**: The main thread is automatically created by the JVM when a Java program
starts. It's the thread from which the `main()` method is invoked.
```java
public static void main(String[] args) {
// Main thread's task
}
```
4. **Thread Pools**: Java provides a mechanism for managing and reusing threads efficiently using
thread pools. Thread pools are a collection of pre-initialized worker threads ready to execute tasks.
They come in various types, such as `ExecutorService`, `ThreadPoolExecutor`, and
`ScheduledExecutorService`, which allow you to submit tasks for execution.
```java
ExecutorService executorService = Executors.newFixedThreadPool(4);
executorService.submit(() -> {
// Task to be executed by a thread from the pool
});
```
These are the primary types of threads in Java. Multithreading in Java allows developers to write
concurrent applications that can perform tasks concurrently, leading to improved performance and
responsiveness. However, it also requires careful synchronization and management to avoid
potential issues like race conditions and deadlocks. Java provides various synchronization
mechanisms and concurrency utilities to help developers write robust multithreaded code.
6)Thread Life cycle: In Java, threads are lightweight processes that allow for concurrent
execution of code. The lifecycle of a thread in Java can be divided into several states, and a thread
can transition between these states during its lifetime. Here are the various states in the lifecycle of a
Java thread:
1. **New:** A thread is in the "New" state when it is created but has not yet started executing. This is
the initial state of a thread.You can create a new thread by instantiating a class that extends `Thread`
or by implementing the `Runnable` interface and passing it to a `Thread` object.
```java
Thread thread = new Thread(new MyRunnable());
```
2. **Runnable:** After calling the `start()` method on a thread, it moves to the runnable state. In this
state, the thread is eligible to run,but the Java Virtual Machine (JVM) has not yet scheduled it for
execution.Threads in this state can be waiting for CPU time.
```java
thread.start();
```
3. **Running:**When the thread is executing its code, it is in the running state. Only one thread can
be in this state at a given time, as Java threads are preemptive and time-sliced by the operating
system.
4. **Blocked:** A thread enters the "Blocked" state when it is waiting for a monitor lock to enter a
synchronized block or method. Threads in this state are waiting for their turn to acquire a lock.
5. **Waiting:** Threads can enter the "Waiting" state when they explicitly wait for another thread to
notify them using methods like `wait()`, `join()`, or `park()`. They are waiting for a specific condition to
be met.
6. **Timed Waiting:** This state is similar to the "Waiting" state, but threads in "Timed Waiting" will
wait for a specified amount of time before transitioning back to the "Runnable" state. Methods like
`sleep()` and `wait(long millis)` can put a thread into this state.
7. **Terminated/Dead:** A thread enters the "Terminated" or "Dead" state when it has completed its
execution or when an uncaught exception terminates it. Once a thread is in this state, it cannot be
restarted.You can check if a thread has terminated using the `isAlive()` method.
```java
if (!thread.isAlive()) {
// Thread has terminated.
}
```
Here's a simplified diagram of the Java thread lifecycle:
The thread lifecycle in Java refers to the various states that a thread can go through during its
lifetime, from its creation to its termination. These states are typically represented as constants in the
`Thread` class and are used to manage and understand the behavior of threads in a Java program.
The thread lifecycle consists of the following states:
Example:
```java
class MyThread extends Thread {
@Override
public void run() {
// Code to be executed by the thread
}
}
7) Main Thread: The "main thread" refers to the first and primary thread that is automatically
created by the Java Virtual Machine (JVM) when a Java program starts. The main thread is
responsible for executing the main method of the class specified as the entry point when you run a
Java application. It serves as the initial point of execution for your program. The main thread carries
out several essential tasks:
1. **Starting the Program**: The main thread is responsible for initiating the execution of your Java
program. When you run a Java application, the JVM creates the main thread and begins executing
the `main` method of your specified class.
2. **Sequential Execution**: The main thread executes the code in the `main` method sequentially,
one statement at a time. It can call methods, create objects, and perform any operations defined in
your program.
3. **Termination**: The main thread is the last thread to terminate when your program finishes its
execution. Once the `main` method completes or an uncaught exception occurs, the main thread
exits, and the program terminates. Any other threads you create in your program must finish their
work before the main thread exits.
4. **UI Applications**: In graphical user interface (GUI) applications, the main thread is often
responsible for managing the user interface components and responding to user interactions. For
instance, in Java Swing or JavaFX applications, the main thread handles UI rendering and event
handling.
5. **Joining Threads**: In multi-threaded applications, you can use the `join()` method to make the
main thread wait for the completion of other threads. This is useful when you need to coordinate the
execution of multiple threads.
In this example, the `main` method runs in the main thread and executes the code sequentially. It
prints messages to the console, demonstrating the order of execution.
Controlling Main thread: In Java, the main thread is the first thread that is created when a
Java program starts. It's responsible for executing the `main()` method of the program and can also
be used to create and manage other threads.
To control the main thread in Java, you can use various mechanisms and techniques. Here are some
common ways to control the main thread:
1. **Thread.sleep()**: The sleep() method is a static method provided by the Thread class. It allows
you to pause the execution of the current thread for a specified amount of time, giving up the CPU to
allow other threads to run.This can be useful for adding delays in your program.
The syntax for using sleep() is as follows:
Example:
```java
public class MainThreadControl {
public static void main(String[] args) {
System.out.println("Starting the program...");
try {
Thread.sleep(2000); // Sleep for 2 seconds
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Program finished.");
}
}
```
2. **Thread.join()**: In Java, the `join()` method is used to wait for a thread to finish its execution
before the current thread proceeds further. When you call `join()` on a thread, the current thread will
pause and wait until the specified thread has completed its execution. This is particularly useful when
you want to ensure that certain tasks are completed in a specific order or when you need the results
of a thread's execution before continuing with the rest of your program.
thread1.start();
thread2.start();
Purpose Pauses the execution of the current thread. Waits for the completion of another thread.
Time Unit Accepts a time duration in milliseconds. Does not specify a time unit; waits until the
joined thread completes.
Lock Release Does not release the lock held by the Does not release the lock held by the thread on
thread. which ‘join()’ is called. Other threads cannot
acquire the lock during ‘sleep’ or “join”
Usage Introducing delays or timing constraints. Ensuring that certain threads complete their
Scenario work before proceeding
Method Type Static method; called on the “Thread” Instance method; called on a specific “Thread”
class. object.
Exception Does not throw “InterruptedException” May throw “InterruptedException” if the waiting
Handling thread is interrupted. We need to handle this
exception when using join().
8) Creating a thread: In Java, a thread is a lightweight, independent execution unit that allows
your program to perform multiple tasks concurrently. Threads are a fundamental part of Java's
multithreading capabilities, which enable you to write programs that can perform multiple operations
simultaneously, making efficient use of available CPU resources. To create a thread in Java, you
typically have two approaches:
Keep in mind that multi-threading can introduce complexities related to thread synchronization, data
sharing, and potential race conditions. It's important to use threads carefully and consider
concurrency issues to ensure the correctness and reliability of your Java programs.
9) Creating Multiple Thread: Creating multiple threads in Java refers to the process of
spawning multiple independent units of execution within a Java program. These threads can run
concurrently, allowing your program to perform multiple tasks simultaneously or take advantage of
multi-core processors, which can lead to improved performance and responsiveness.
In Java, you can create multiple threads using two main approaches:
You can create a new class that extends the `Thread` class and overrides the `run()` method to
define the code that the thread will execute. Then, you can instantiate and start multiple instances of
this custom thread class.
```java
class MyThread extends Thread {
public void run() {
// Code to be executed by the thread
}
}
```java
class MyRunnable implements Runnable {
public void run() {
// Code to be executed by the thread
}
}
Using these methods, you can create and manage multiple threads in your Java application,
enabling concurrent execution of tasks and potentially improving program performance. Be aware of
synchronization and coordination mechanisms like locks and barriers when dealing with multiple
threads to avoid issues like data races and thread interference.
10) Thread Priorities: In multithreading, thread priorities are used to determine the scheduling
order of threads by the operating system's thread scheduler. Threads with higher priorities are given
preference in execution over threads with lower priorities. Thread priorities are often represented as
integer values, where a higher integer typically corresponds to a higher priority. However, it's
important to note that thread priorities are platform-dependent, and their exact behavior may vary
across different operating systems.
Java defines thread priorities using integer values ranging from 1 to 10, where 1 is the lowest priority,
and 10 is the highest priority. These priorities are grouped into three main categories:
1. **MIN_PRIORITY (1)**: This is the minimum priority value, representing the lowest priority thread.
2. **NORM_PRIORITY (5)**: This is the default priority value for threads. If you don't explicitly set a
priority, threads are given this priority.
3. **MAX_PRIORITY (10)**: This is the maximum priority value, representing the highest priority
thread.
To create a synchronized block, you specify an object as a monitor (or lock), and only one thread can
enter the synchronized block if it holds the monitor. Other threads will wait until the monitor is
released. The basic syntax for a synchronized block is as follows:
```java
synchronized (monitorObject) {
// Code that needs to be synchronized
}
```
Here's an example of how you can use block-level synchronization in Java:
```java
public class SynchronizedExample {
private static int sharedCounter = 0;
private static Object lock = new Object();
thread1.start();
thread2.start();
}
}
```
In this example:
1. We have a shared counter (`sharedCounter`) that multiple threads will attempt to increment
concurrently.
2. We create a `lock` object that will serve as the monitor for the synchronized block.
3. Two threads (`thread1` and `thread2`) are created, and they both execute the `incrementTask`,
which increments `sharedCounter` within a synchronized block. This ensures that only one thread at
a time can execute the critical section of code.
3. Static Synchronization: You can synchronize static methods or blocks to control access to static
data shared among multiple threads. Static synchronization locks on the class object instead of an
instance.
java
public static synchronized void staticSynchronizedMethod() {
// Synchronized code block for static method
}
4. Reentrant Synchronization: Java supports reentrant synchronization, which means that a thread
can acquire the same lock multiple times without blocking itself. This helps in avoiding deadlocks
when a method calls another synchronized method within the same class.
1. **Input in Java:** Input refers to the process of receiving data from external sources, such as a
user via the keyboard or from a file. In Java, you can use classes like `Scanner` or `BufferedReader`
to read input from various sources.
“Scanner" is a predefined class in java which is available in the “java.util” package.used to get
input from the user.
Rules for using scanner class:
1.must have to create object of scanner class
Syntax:Scanner object_ name = new Scanner(System.in);
2. Scanner class methods:
1. nextLine(); //use to get string from user
2. nextInt(); //use to get integer from user
3. nextFloat(); //use to get floating value
4. nextBoolean(); //use to get boolean value from user
5. nextDouble(); //use to get double value from user
3.Import the scanner class package at the top of the program.
Syntax: import java.util Scanner;
4.Wrong input gives “InputMismatch” exception.
Example:
```java
import java.util.Scanner;
Example:
```java
public class OutputExample {
public static void main(String[] args) {
String message = "Hello, World!";
16) I/O Classes: In Java, input and output classes typically refer to classes or mechanisms
used for handling input (data coming into a program) and output (data leaving a program). These
classes are crucial for reading data from various sources and displaying results to users. Here's an
overview of input and output classes in Java:
1. Input Classes:
- `java.util.Scanner`: This class is commonly used to read input from various sources, such as the
console or files. It provides methods for reading different data types like integers, floating-point
numbers, and strings.
17) Stream: In Java, a stream is a sequence of data elements that can be read from or written to.
Streams are an integral part of the Java I/O (Input/Output) system and are used for reading and
writing data to and from various sources, such as files, network connections, and memory.
1. Byte Streams:
- Byte streams are used to read and write raw binary data, typically represented as bytes (8 bits).
They are suitable for handling all kinds of data, including text files, images, audio, and video files.
- `InputStream` and `OutputStream` are the abstract base classes for all byte stream classes.
- Common byte stream classes include `FileInputStream`, `FileOutputStream`,
`ByteArrayInputStream`, `ByteArrayOutputStream`, `BufferedInputStream`, and
`BufferedOutputStream`, among others.
int data;
while ((data = fis.read()) != -1) {
fos.write(data);
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
2. Character Streams:
- Character streams are used specifically for reading and writing text-based data. They work with
character encoding and provide a more convenient way to work with text files.
- `Reader` and `Writer` are the abstract base classes for all character stream classes.
- Common character stream classes include `FileReader`, `FileWriter`, `BufferedReader`,
`BufferedWriter`, `InputStreamReader`, and `OutputStreamWriter`, among others.
- Character streams automatically handle character encoding and decoding, which is important
when dealing with text files that may use different character encodings like UTF-8, UTF-16, etc.
Here are some classes you should know that can be used to read character data:
● Reader: An abstract class to read a character stream.
● InputStreamReader: Class used to read the byte stream and converted to character stream.
● FileReader: A class to read the characters from a file.
● BufferedReader: This is a wrapper over the Reader class that supports buffering capabilities.
In many cases this is the most preferable class to read data because more data can be read
from the file in one read() call, reducing the number of actual I/O operations with the file
system.
And here are some classes you can use to write character data to a file:
● Writer: This is an abstract class to write the character streams.
● OutputStreamWriter: This class is used to write character streams and also convert them to
byte streams.
● FileWriter: A class to actually write characters to the file.
● BufferedWriter: This is a wrapper over the Writer class, which also supports buffering
capabilities. This is the most preferable class to write data to a file since more data can be
written to the file in one write() call. And like the BufferedReader, this reduces the number of
total I/O operations with the file system.
int data;
while ((data = fr.read()) != -1) {
fw.write(data);
}
fr.close();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
Aspect Byte Streams Character Streams
Text Handling Not suitable for handling text Specifically designed for
since no character encoding is reading/writing text data.
applied.
Byte streams deal with raw binary data and are used for reading and writing non-text data like
images, audio, and binary files. They are not suitable for handling text because they don't consider
character encoding.
Character streams, on the other hand, are designed for reading and writing text data. They handle
character encoding and are aware of the character-level content, making them suitable for text
processing tasks.
Advantage of using Stream: Input and Output (I/O) streams in Java are essential for reading and
writing data to and from various sources, such as files, network connections, and console
input/output. Here are some advantages of using I/O streams in Java:
1. **Abstraction**: Java I/O streams provide a high-level abstraction for handling input and output,
making it easier to work with different types of data sources without worrying about low-level details.
2. **Consistency**: The Java I/O stream classes provide a consistent interface for reading and
writing data, regardless of the data source. This uniformity simplifies code maintenance and makes it
easier to switch between different types of I/O sources.
3. **Efficiency**: Java I/O streams are designed for efficiency. They often use buffering to minimize
the number of actual read and write operations, which can significantly improve performance when
working with large volumes of data.
4. **Flexibility**: Java I/O streams support a wide range of data types and data sources. You can
use them to work with text, binary data, and objects, and interact with files, sockets, and other I/O
devices.
5. **Standardization**: Java provides a standardized set of I/O stream classes that are part of the
Java Standard Library (e.g., `InputStream`, `OutputStream`, `Reader`, `Writer`). This standardization
makes it easy for developers to learn and use I/O operations across different projects.
6. **Extensibility**: You can create custom I/O stream classes by extending existing stream classes
or implementing specific interfaces. This allows you to adapt I/O operations to suit your application's
needs.
7. **Exception Handling**: Java I/O streams handle exceptions gracefully. They use checked
exceptions, which forces developers to handle potential errors, making code more robust.
8. **Character Encoding Support**: When working with character data, Java I/O streams support
various character encodings (e.g., UTF-8, UTF-16), ensuring that data is correctly read and written in
different character sets.
9. **Serialization**: Java I/O streams are crucial for object serialization and deserialization, allowing
you to save and load object data to and from files or send objects over the network.
10. **Integration with Other Libraries**: Java I/O streams can be easily integrated with other Java
libraries and frameworks, allowing you to build complex I/O operations within your applications.
11. **Cross-Platform**: Java I/O streams are platform-independent, making it possible to write code
that works on different operating systems without modification.
12. **Security**: Java provides security features for I/O streams, such as permission-based access
control and the ability to set security policies for file access.
In summary, Java I/O streams provide a versatile and efficient way to work with input and output
operations, offering consistency, flexibility, and robust error handling. They are a fundamental part of
Java for handling data in various forms and from various sources in a standardized and efficient
manner.
18) RandomAccessFile: The `RandomAccessFile` class is part of the `java.io` package and
provides a way to read and write files in a random access manner.
This means that you can read and write data at any position within a file, not just sequentially from
the beginning to the end. `RandomAccessFile` is different from other file I/O classes like
`FileInputStream` and `FileOutputStream`, which only support sequential access
In other simple words, RandomAccessFile class allows creating files that can be used for reading
and writing data with random access.Random access means access to stored data in any order that
the user desires. That is, we can access data in the file in any order while using the file. Such a file is
known as a random access file.
A random-access file is a file that can be used for both reading and writing using the
RandomAccessFile class in java.
`RandomAccessFile` has two modes: "r" for read-only and "rw" for read-write. Here are the two main
types of `RandomAccessFile` instances:
1. **Read-Only (`"r"` mode):** You can create a `RandomAccessFile` instance in read-only mode to
only read data from an existing file.
Here are some of the commonly used methods of the `RandomAccessFile` class:
- `read()`: Reads a byte of data from the current file pointer position and returns it as an integer.
- `read(byte[] buffer)`: Reads a chunk of data into the provided byte array from the current file
pointer position.
- `read(byte[] buffer, int offset, int length)`: Reads a specific number of bytes into the byte array,
starting at the given offset.
- `seek(long position)`: Moves the file pointer to the specified position in the file.
- `write(int b)`: Writes a byte of data to the file at the current file pointer position.
- `write(byte[] buffer)`: Writes the contents of the byte array to the file, starting at the current file
pointer position.
- `write(byte[] buffer, int offset, int length)`: Writes a specific number of bytes from the byte array
to the file, starting at the given offset.
- `close()`: Closes the `RandomAccessFile` instance, releasing any system resources associated
with it.
The class whose objects you want to store and retrieve must implement the `Serializable` interface.
This interface doesn't have any methods; it's just a marker interface that indicates that the objects of
this class can be serialized.
```java
import java.io.Serializable;
this.name = name;
this.age = age;
```
```java
import java.io.*;
} catch (IOException e) {
e.printStackTrace();
```
```java
import java.io.*;
e.printStackTrace();
if (obj != null) {
}
}
```
Remember to replace `"object.ser"` with the actual file path where you want to store and retrieve
your objects. Make sure that the classes you serialize and deserialize are consistent (i.e., they have
the same structure) to avoid class versioning issues.
Unit-4
❖ Applets:
● An applet is a Java program that is embedded into the webpage to create dynamic content. It runs
inside the web browser and works on the client-side, and it is used to create a dynamic website.
● It can be executed by browsers running under many platforms, including Linux, Windows, Mac OS
etc.
● The applet works on the client-side, and that’s why it has less response time.
● An applet is a Java class that extends the java.applet.Applet class.
● The applet does not use the main() method because when an applet is loaded, it automatically calls
certain methods of the applet class to start and executes the applet code. An applet has its own life
cycle.
● Local Applet – When we create applets on our own and then embed them into web pages,
this type of Applet is called a local Applet. Local applets are developed and stored on the
local system. In the case of local Applets, the web page doesn’t need to get the information
from the internet, and they search for local applets from all the directories of the local
computer.
● Remote Applet – Remote applets are developed by another developer and stored in a
remote computer connected to the internet. We can download these applets when connected
to the internet and run them in our local system.
Life Cycle: The applet life cycle is defined as the changes in stages of the applet during its execution.
In other words, the applet life cycle is the process of how the applet is created, started, stopped, and
destroyed during the entire execution of its application.
An applet goes through 4 stages during its life cycle, which are the followings :
1. Born or Initialization state: It is the first stage of an applet in the applet life cycle. In this state, an
applet is just initialized or entered into the initialization state when it is first loaded. init() method is
used to initialize an applet.
At this stage following actions may be taken –
● Load images or font
● Set up colors
● Set up initial values
● Create object as required by the applet
Initialization occurs only once in the applet’s life cycle.
2. Running state: It is the second stage of an applet in the applet life cycle. In this state, the applet
starts running. start() method is used to run an applet.
3. Idle state: It is the third state of an applet in the applet life cycle. In this state, an applet becomes
idle, which means it stopped running. stop() method is used to stop an applet.
4. Dead state: In this state, the applet is removed from memory. destroy() method is used to destroy
the applet. This occurs automatically when we quit the browser.
Like initialization, destroying state occurs only once in the applet’s life cycle.
1. init()
● init() method is used to initialize an applet.
● This is the first method of an applet to be called.
● This method is called only once in the applet life cycle.
Syntax:
import java.applet.Applet;
2. start()
● This method is used to start an applet.
● The applet enters into a running state when the start() method is invoked.
● This method can be used more than once. It is also used to resume the applet.
Syntax:
import java.applet.Applet;
3. paint()
● This method is used to paint any shapes such as rectangles, squares, eclipses etc.
● paint() method has one parameter of the type Graphics Class. This Graphics class enables
the painting features in an applet.
Syntax:
import java.applet.Applet;
import java.awt.Graphics;
4. stop()
● This method is used to stop the applet.
● It is invoked every time the browser is stopped, minimized, or when there is an abrupt failure
in the application.
● This method is invoked automatically when we leave the current web page on which the
applet was running.
Syntax:
import java.applet.Applet;
5. destroy()
● This method is used to destroy the applet.
● It can be called only once.
● This method is called automatically when we want to quit the browser.
Syntax:
import java.applet.Applet;
Example:
1. In your HTML file, embed the Java applet using the `<applet>` tag, and use `<param>` tags to
pass parameters to it. For example:
```html
<applet code="MyApplet.class" width="300" height="200">
<param name="param1" value="Hello">
<param name="param2" value="World">
</applet>
```
In this example, we have defined two parameters: `param1` with the value "Hello" and `param2` with
the value "World." These parameters can be accessed from your Java applet.
2. In your Java applet code (e.g., `MyApplet.java`), you can retrieve these parameters using the
`getParameter` method provided by the `java.applet.Applet` class:
```java
import java.applet.Applet;
import java.awt.Graphics;
In this Java applet code, we use the `init` method to retrieve the values of the parameters `param1`
and `param2` using the `getParameter` method. Then, we use these values to display text on the
applet canvas.
When you run this HTML page with the applet, it will display "Hello World" on the applet canvas since
we passed "Hello" and "World" as parameters.
Simple Applet Program: A simple applet program in Java refers to a small software application
designed to be embedded within a web page and run within a web browser. Java applets were
commonly used in the past to add interactive elements and animations to web pages. However, they
have largely fallen out of favor due to security concerns and compatibility issues with modern web
browsers. Despite this, a simple Java applet typically consists of the following key components:
1. **Import Statements**: Java applets often start with import statements to include necessary
libraries and packages.
2. **Applet Class**: The applet is defined as a Java class that extends the `java.applet.Applet`
class.
3. **Initialization**: The `init` method is typically used for initialization tasks, such as setting up initial
variables or loading resources.
4. **Painting**: The `paint` method is where the applet draws graphics and displays content on the
web page. You use the `Graphics` object to draw shapes, text, and images.
5. **HTML Embedding**: To display the applet in a web browser, you need to embed it within an
HTML page using the `<applet>` tag. This tag specifies the applet's dimensions, codebase, and
other attributes.
6. **Compilation**: After writing the Java code for the applet, you need to compile it into a `.class`
file using a Java compiler.
7. **Web Hosting**: The compiled `.class` file and the HTML file that embeds the applet should be
hosted on a web server.
8. **Browser Execution**: Users can view the applet by opening the HTML page in a web browser
with Java applet support. The applet runs within the browser and can interact with the user or display
dynamic content.
AWT: AWT (Abstract Window Toolkit) is a part of Java's standard library that provides a set of classes and
methods for creating graphical user interfaces (GUIs) in Java applications.AWT is part of the Java
Foundation Classes (JFC), which also includes Swing.Java AWT components are platform-dependent i.e.
components are displayed according to the view of operating system. AWT is heavyweight i.e. its
components are using the resources of the underlying operating system (OS).
Platform independent:
1.Java Virtual Machine (JVM): Java programs run on a Java Virtual Machine (JVM), which
abstracts the underlying hardware and operating system. This allows Java applications, including
AWT-based ones, to be written once and run on any platform that has a compatible JVM. The JVM
ensures that the Java code executes consistently across different platforms.
2. Abstract APIs: AWT provides an abstract layer for GUI. Java applications interact with AWT
through Abstract API which are platform independent. Abstract API allows Java to isolate
platform-specific details, making code portable across different systems.
3. Platform-Independent Libraries:The Libraries of AWT are written in Java which they are totally
platform-independent. Because of this, it ensures that AWT functionality remains consistent across
different environments.
4.Native Peer Components: AWT relies on native peer components to interact with the underlying
operating system's GUI. These native peer components are platform-specific and provide a bridge
between the platform-independent Java code and the platform-dependent GUI system. Java's AWT
uses these native components to render GUI elements like buttons, windows, and dialogs.
5.Write Once, Run Anywhere (WORA): One of the key principles of Java is "Write Once, Run
Anywhere." This means that Java code written on one platform can be compiled into bytecode and
executed on any platform with a compatible JVM. AWT adheres to this principle, allowing developers
to write GUI code in Java that works on various operating systems without modification.
AWT Hierarchy:
The AWT hierarchy is a class inheritance structure that represents the relationship between various
classes used in AWT. At the top of the hierarchy is the `java.awt.Component` class, which is the
superclass for all AWT components. Here is a simplified representation of the AWT hierarchy:
1. **java.awt.Component**:
- Component is the base class for all AWT components. It provides the fundamental behavior for
visual elements in AWT.
- It includes methods for handling events, painting, and basic layout.
2. **java.awt.Container**:
- Container is a subclass of Component. It represents a component that can contain other AWT
components.
- It provides methods for managing layouts and adding components to a container.
3. **java.awt.Window**:
- Window is a subclass of Container. It represents a top-level window in a GUI application.
- It can be a frame, dialog, or any other window-like container.
4. **java.awt.Frame**:
- Frame is a subclass of Window. It represents a top-level window with a title and possibly a border.
- It's one of the most commonly used classes for creating GUI applications.
5. **java.awt.Dialog**:
- Dialog is a subclass of Window. It represents a pop-up dialog box, which is typically used to get
user input or display messages.
6. **java.awt.Panel**:
- Panel is a subclass of Container. It represents a simple container that is used to group other
components.
7. **java.awt.Canvas**:
- Canvas is a subclass of Component. It represents a blank area where custom graphics can be
drawn.
9. **java.awt.MenuComponent**:
- MenuComponent is a superclass for Menu, MenuItem, and CheckboxMenuItem, which are used
to create menus in a GUI.
This hierarchy provides a structured way to organize and interact with GUI components in Java. It
allows you to create complex GUI applications by combining and customizing these components.
Keep in mind that this is a simplified overview, and the actual AWT hierarchy includes additional
classes and interfaces for handling events, graphics, and other aspects of GUI programming in Java.
AWT Controls: AWT controls, also known as AWT components or widgets, are the graphical elements
that you can use to create user interfaces in AWT-based Java applications. These controls allow users to
interact with the application by providing various input and output mechanisms. Here are some common
AWT controls:
1. **Button**: An AWT Button is a simple control that represents a clickable button. You can add
ActionListener to it to handle button click events.
2. **Label**: A Label is a non-interactive control used to display text or an image. It is typically used
for providing information or captions in the user interface.
3. **TextField**: A TextField is an input control that allows users to enter single-line text. You can
use it for input forms or for user input.
4. **TextArea**: A TextArea is similar to a TextField but allows multiple lines of text input. It is useful
for entering longer text or for displaying multiline text.
7. **Choice**: A Choice is a drop-down list that allows users to select one option from a list of
predefined choices.
8. **List**: A List is a control that provides a scrollable list of items from which users can select one
or multiple items.
9. **Scrollbar**: A Scrollbar is a control used for scrolling content in components like ScrollPane or
TextArea.
10. **Panel**: A Panel is a container control that can hold other AWT controls. It is used to organize
controls within a container.
11. **Canvas**: A Canvas is an area where you can draw graphics and custom elements using
AWT's graphics capabilities.This is als a Special type of Class which is also derived from a Windows
Class and this is not a part of AWT hierarchy class and this is one another type of window which is
used for creating a blank Area and this will Creates an Empty Area for doing drawing. It provides us
a blank window which can be drawn upon it. And it inherits the Properties from the Paint Method
from the Graphics Class which is Located in the Component Class.
12. **ScrollPane**: A ScrollPane is a container that provides scrollbars for viewing the content of its
child component, which may not fit entirely within its visible area.
13. **FileDialog**: A FileDialog is used for opening or saving files through a dialog box.
14. **MenuBar**: A MenuBar is used to create menu systems within a GUI application, with menus
containing menu items.
15. **Menu**: A Menu is a dropdown list of menu items that can be added to a MenuBar or another
Menu.
16. **MenuItem**: A MenuItem represents an individual item within a Menu. It can trigger actions
when selected.
The Abstract Window Toolkit (AWT) is a Java package that provides a set of classes and methods
for creating graphical user interfaces (GUIs) and for drawing objects on the screen. AWT plays a
crucial role in creating and managing graphical components in Java applications. When it comes to
drawing objects, AWT provides several key classes and functionalities:
1. **Graphics Class**: AWT includes the `Graphics` class, which is used for drawing various
shapes, text, and images on components such as `Canvas`, `Panel`, and `Frame`. You can obtain a
`Graphics` object from a component's `paint()` method and use it to draw on that component.
2. **Graphics Context**: The `Graphics` object represents a graphics context, which maintains
information about the drawing state, such as the current color, font, and clipping area. You can set
attributes like colors and fonts before drawing objects.
3. **Drawing Shapes**: AWT supports drawing various shapes, including lines, rectangles, ellipses,
polygons, and arcs, using methods like `drawLine()`, `drawRect()`, `drawOval()`, `drawPolygon()`,
and `drawArc()`.
4. **Drawing Text**: You can use the `drawString()` method to draw text on a component. You can
specify the text, position, and font for the text.
5. **Images and Icons**: AWT allows you to display images and icons on components using
classes like `Image`, `ImageIcon`, and `drawImage()` methods.
6. **Double Buffering**: AWT supports double buffering, which can be used to reduce flickering
when drawing complex scenes. You can create off-screen images and draw on them before
displaying the final result on the screen, providing a smoother rendering experience.
7. **Event Handling**: AWT components often rely on event handling to trigger updates and
drawing. Events such as mouse clicks, keyboard inputs, and window resizing can trigger the `paint()`
method or custom painting logic.
8. **Layout Management**: AWT provides layout managers to control the placement and sizing of
components within a GUI. This ensures that drawn objects are arranged properly within the
container.
WINDOW FUNDAMENTALS
Java Abstract window toolkit package is used for displaying the data within a GUI Environment.
Features of AWT Package are as Followings:
1. It provides us a set of user interface components including windows buttons, text, fields,
scrolling list etc.
2. It provides us the way to lay out these above components.
3. It provides the way to create the events upon these components.
The main purpose for using the AWT is for displaying all the components on the screen. AWT
defines all the windows according to a class hierarchy; those are useful at a specific level or we can
say arranged according to their functionality.
The most commonly used interface is the panels that are used by applets and those are derived from
frames which creates a standard window. The hierarchy of this Awt is:-
As you see this Figure this Hierarchical view displays all the classes and also their SubClasses. All
the Classes are Contained as a Multi-Level inheritance , As You see that Component Class
contains a Panel Class which again Contains an Applet Class so that in the AWT Package are
Stored in the form of Multi-values inheritance.
Component Class
This is the super class which defines all the methods for developing the methods those are related
with the components and the methods those are related with the Actual Position of the Control and
this also provides the various methods to Setup the Sized, Colors either this may a Background or a
Foreground Color. It includes all the components those are displayed on the screen and it also
defines various types of public methods for managing events such as mouse and keyboard window
etc. the Various Methods those are Contained in the Component Class are :-
1. Void SetSize(int Width, int Height) : this Method is used to Set the Size by taking the height
and width of a Control for Example height of Textbox and width of Textbox. With this Method
we Can set the height and width of any Control.
2. Void SetLocation (int x,int y): Used to Set the location on the Applet and this will take the
Coordinates in the Form of x and y.
3. Void setBounds(int x,int y,int width,int height) : this Method will also set the Actual Location in
the Applet by Specifying the X and y Coordinate and also Specify the Width and Height of the
Control.
4. Void setForeground(Color c) : this Method is used to set the Font Color or Text Color of a
Control.
5. Void setBackground(Color c) : This Method is used to set the Background Color of a Control
whether this may Control or any Window Like an Applet,Panel etc.
Container
It is a subclass of components which Inherits the various Properties from that Class and it provides
for laying out the components that are contained by using the various layout managers. Means how
the Components will be displayed in the applet and in which Manner the Components will be
displayed in the window. or Position of the Controls without setting the X and y Axis is determined by
the Layout Manager and. The Container Provides very important Methods to add or Remove the
Components from the Applet or from any other Window. The various Methods those are Contained in
the Container class are :
1. Void add (object o) :this Method is used to Add a Control in the Applet of in any Container.
2. Void remove(object o) : This is used if a user wants to Remove an Control from a Container
For Example if a user wants to Remove the Control from an Applet then he may use this
Method.
3. void removeAll() : This Method doesn't take any argument and this will remove all the
Controls from the Container.
Panel
It is a subclass of container and it is the super class of Applet. It is a window that does not have a
title-bar, menu-bar or border. Generally a Panel is used for displaying Multiple Windows in a Single
Window and a Panel may have any Layout. And for Adding any Control in the Panel we have to use
the Add Method and there are also some important Methods those are Provided by the Panel Class
those are Explained below :-
1. Panel() : This is the Name of Class For Using you have to Create the object first.
2. Void setLocation : Method is used to set the Location of a control in the Panel.
3. Void setSize() : This will take two Arguments and those Arguments will Specify the Width and
Height of the Panel.
4. Void setBounds : This Method is used to set the Bounds of a Control in the Panel For
Example X and y Axis and Width and Height of a Control.
Window
Window is also a Subclass of a Container and window class creates a top level window. These are
not directly created, for this the subclass of window name frame is used and dialogs are used . This
is used for displaying a Sub Windows from a Main Window and the various Methods of Window are
as follows:-
1. Void Pack() : This Method is used for adjusting the Size of Window according to the number
of Controls in the Container or in the Applet or in the other window.
2. Void show() : This Method is used for displaying a Window.
3. Void dispose() : This Method is used for de-allocate the Memory Space which is Consumed
by the Controls of the Window.
import java.awt.*;
frame.addWindowListener(new java.awt.event.WindowAdapter() {
public void windowClosing(java.awt.event.WindowEvent windowEvent) {
System.exit(0);
}
});
}
}
In this example:
1. We import the `Frame` class from the `java.awt` package, which is used to create a window.
2. We create a `Frame` object named `frame`.
3. We set the size of the frame using the `setSize` method. In this case, the frame will be 400 pixels
wide and 300 pixels tall.
4. Finally, we make the frame visible by calling `setVisible(true)`.
Here's an example of how you can create a simple window with a label and a button:
```java
import java.awt.*;
// Create a label
Label label = new Label("This is a label");
// Create a button
Button button = new Button("Click me");
You can compile and run this code to see a simple AWT window with a label and a button.
Keep in mind that AWT is an older GUI library in Java. For more complex GUI applications, you
might consider using Swing or JavaFX, which provide more modern and powerful components.
Layout manager: The Layout managers enable us to control the way in which visual components are
arranged in the GUI forms by determining the size and position of components within the containers.
1.FlowLayout: It arranges the components in a container like the words on a page. It fills the top line
from left to right and top to bottom. The components are arranged in the order as they are added i.e.
first components appear at top left, if the container is not wide enough to display all the components, it
is wrapped around the line. Vertical and horizontal-gap between components can be controlled. The
components can be left, center or right aligned.
2.BorderLayout: It arranges all the components along the edges or the middle of the container i.e.
top, bottom, right and left edges of the area. The components added to the top or bottom gets its
preferred height, but its width will be the width of the container and also the components added to the
left or right gets its preferred width, but its height will be the remaining height of the container. The
components added to the center gets neither its preferred height or width. It covers the remaining area
of the container.
3.GridLayout: It arranges all the components in a grid of equally sized cells, adding them from the left
to right and top to bottom. Only one component can be placed in a cell and each region of the grid will
have the same size. When the container is resized, all cells are automatically resized. The order of
placing the components in a cell is determined as they were added.
4.GridBagLayout: It is a powerful layout which arranges all the components in a grid of cells and
maintains the aspect ration of the object whenever the container is resized. In this layout, cells may be
different in size. It assigns a consistent horizontal and vertical gap among components. It allows us to
specify a default alignment for components within the columns or rows.
5.BoxLayout: It arranges multiple components in either vertically or horizontally, but not both. The
components are arranged from left to right or top to bottom. If the components are aligned horizontally,
the height of all components will be the same and equal to the largest sized components. If the
components are aligned vertically, the width of all components will be the same and equal to the
largest width components.
6.CardLayout: It arranges two or more components having the same size. The components are
arranged in a deck, where all the cards of the same size and the only top card are visible at any time.
The first component added in the container will be kept at the top of the deck. The default gap at the
left, right, top and bottom edges are zero and the card components are displayed either horizontally or
vertically.
MenuBars and Menus: In AWT (Abstract Window Toolkit), menus are graphical user interface (GUI)
components used to provide a list of options or commands to the user. Menus are typically used in
desktop applications to organize and present various actions or choices that can be performed within the
application. AWT provides classes and interfaces for creating menus and menu items. Here are the key
components and concepts related to menus in AWT:
2. Menu (`Menu`):
- A menu is a dropdown list of options that appear when you click on a menu item in the menu bar or
another menu.
- A menu can contain multiple menu items and submenus.
- You can create a menu using the `Menu` class.
5. Submenu:
- A submenu is a menu that is nested within another menu.
- Submenus are used to group related menu items together.
- You can add submenus to a menu by creating instances of the `Menu` class and adding them as
items to the parent menu.
Here's a basic example of how to create a menu bar with menus and menu items in AWT:
```java
import java.awt.*;
fileMenu.add(newItem);
fileMenu.add(openItem);
fileMenu.add(saveItem);
fileMenu.addSeparator();
fileMenu.add(exitItem);
menuBar.add(fileMenu);
frame.setMenuBar(menuBar);
frame.setSize(300, 200);
frame.setVisible(true);
}
}
```
Differentiate:
1) Differentiate checkbox and Radio Buttons
Multiple options can be selected Only one option can be selected within a
Selection Type
simultaneously. group.
Suitable for selecting multiple independent Used when users must make a single
Usage
options. choice from mutually exclusive options.
Independent of each other; selecting one Mutual exclusivity; selecting one deselects
Behavior
does not affect others. others in the group.
Cell Size All cells have the same size. Cells can have varying sizes.
Components are
Control over how components resize within
Resizing Behavior automatically stretched to fill
their cells.
cells.
Easier to use for basic More complex and powerful for advanced
Complexity
layouts. layouts.
Simple grids where all cells Complex layouts with varying component
Ideal Use Cases
have the same size. sizes and alignment requirements.