Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
95 views

My Java Notes

The document discusses the history and evolution of the Java programming language. It describes how Java was initially used for applets and web development. It then covers key Java concepts like bytecode, classes, methods, and the Java class library which provides commonly used functionality.

Uploaded by

Nikhil Bhardwaj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views

My Java Notes

The document discusses the history and evolution of the Java programming language. It describes how Java was initially used for applets and web development. It then covers key Java concepts like bytecode, classes, methods, and the Java class library which provides commonly used functionality.

Uploaded by

Nikhil Bhardwaj
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 52

Unit-1

Introduction: Genesis and Evolution of Java Language, Internet & Java, Byte-code, its Features, Java
Program Structure and Java’s Class Library, Data Types, Variables, and Operators, Operator Precedence;
Selection Statements, Scope of Variable, Iterative Statement; Defining Classes & Methods, Creating
Objects of a Class, Defining and Using a Class, Automatic Garbage Collection.

Arrays and Strings: Arrays, Arrays of Characters, String Handling Using String Class, Operations on String
Handling Using, String Buffer Class.

Java and internet

Applets: In the early days of the internet, Java applets were a popular way to add dynamic
content to web pages. An applet is a small program written in Java that can be embedded in a
web page and executed by a web browser. This allowed developers to create interactive and
multimedia-rich content that could run on any platform with a Java-enabled browser.

Java Servlets and JSP (JavaServer Pages): As web development evolved, Java became a key
player in server-side programming. Java Servlets are server-side programs that handle client
requests and generate dynamic web content. JSP is a technology that simplifies the process of
developing web pages with Java by allowing developers to embed Java code in HTML pages.
Java Networking APIs: Java provides a rich set of networking APIs that facilitate
communication over the internet. These APIs enable developers to create applications that can
communicate over various protocols, such as HTTP, FTP, and more.

BYTECODE

In Java, bytecode is an intermediate representation of a program that is generated by the Java


compiler. Java source code is compiled into bytecode, which is then executed by the Java Virtual
Machine (JVM). This allows Java programs to be platform-independent, as the bytecode can be
executed on any system that has a compatible JVM.

1.Java Compiler: When you write a Java program, you save it with a .java extension.
The Java compiler ( javac) then translates this source code into bytecode. This bytecode
is stored in files with a .class extension.

// HelloWorld.java
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
After running javac HelloWorld.java, you get HelloWorld.class, which contains the
bytecode.
2.Java Virtual Machine (JVM): The JVM is responsible for executing Java bytecode. It is
platform-specific, but the same bytecode can run on any system with a compatible JVM. The
JVM interprets the bytecode or, in some cases, uses Just-In-Time (JIT) compilation to translate
the bytecode into machine code for the specific hardware.

3.Bytecode Instructions: Java bytecode consists of a set of instructions that the JVM can
understand and execute. These instructions are low-level operations such as load, store,
arithmetic, method invocation, etc. They are designed to be platform-independent and are not
tied to the architecture of a specific machine.

Structure of Java Program


Classes contain data members and methods that operate on the data
members of the class. Methods may contain data type declarations
and executable statements. To write a Java program, we first define
classes and then put them together.

Documentation Section
 The documentation section comprises a set of comment lines giving the name of the program,
the author and other details, which the programmer would like to refer to at a later stage.
 Comments must explain why and what of classes and how of algorithms. This would greatly help
in maintaining the program.
 Java also uses a third style of comment // known as documentation comment.
 This form of comment is used for generating documentation automatically.
Package Statement
 The first statement allowed in a Java file is a package statement.
 This statement declares a package name and informs the compiler that the classes defined here
belong to this package. Example package student;
 The package statement is optional. That is, our classes do not have to be part of a package.
Import Statements
 The next thing after a package statement (but before any class definitions) may be a number of
import statements.
 This is similar to the #include statement in C. Example import student.test;
 This statement instructs the interpreter to load the test class contained in the package student.
 Using import statements, we can have access to classes that are part of other named packages.
Interface Statements
 An interface is like a class but includes a group of method declarations.
 This is also an optional section and is used only when we wish to implement the multiple
inheritance feature in the program.
Class Definitions
 A Java program may contain multiple class definitions.
 Classes are the primary and essential elements of a Java program.
 These classes are used to map the objects of real-world problems.
 The number of classes used depends on the complexity of the problem.
Main Method Class
 Since every Java stand-alone program requires a main method as its starting point, this class is
the essential part of a Java program.
 A simple Java program may contain only this part.
 The main method creates objects of various classes and establishes communications between
them.
 On reaching the end of main, the program terminates and the control passes back to the
operating system.
First Java Program

Class Definition
 This line uses the keyword class to declare that a new class is being defined.
class First
 First is an identifier that is the name of the class. The entire class definition, including all
of its members, will be between the opening curly brace { and the closing curly brace } .
Main Method
 In Java programming language, every application must contain a main method whose
signature is:
public static void main(String[] args)
 The keyword public is an access specifier, just as it is when you use it to define the First
class.
 The keyword static means that a method is accessible and usable even though no
objects of the class exist.
 The keyword void indicates that the main() method does not return any value when it is
called.
 The name of the method is main().
 In the method header, the contents between the parentheses, String[] args, represent
the type of argument that can be passed to the main() method, just as the string “First
Java application” is an argument passed to the println() method.
 The next line of code is shown here. Notice that it occurs inside main( ).
System.out.println("First Java application");
Java class Library
In Java, a class library (also known as a standard library or API - Application Programming Interface) is a
collection of pre-compiled classes, interfaces, and methods that provide commonly used functionality.
These libraries are bundled with the Java Development Kit (JDK) and are essential for Java developers to
build robust and efficient applications.

Some key components of the Java Class Library include:

1. **java.lang:** This package contains fundamental classes that are automatically imported into every
Java program. Examples include Object (the root class for all Java classes), String, Math, and System.

2. **java.util:** This package contains utility classes and data structures like ArrayList, HashMap, and
Date. It also includes the Collections framework, which provides interfaces and classes for implementing
various collection types (lists, sets, queues, etc.).

3. **java.io:** This package provides classes for input and output operations, including file I/O.
Examples include FileInputStream, FileOutputStream, and BufferedReader.

4. **java.net:** This package contains classes for networking tasks. It includes classes for working with
URLs, sockets, and other network-related operations.
5. **java.awt and javax.swing:** These packages provide classes for building graphical user interfaces
(GUIs). AWT (Abstract Window Toolkit) is the original GUI library, and Swing is an extension of AWT with
additional features.

6. **java.sql:** This package provides classes for database access and manipulation through JDBC (Java
Database Connectivity).

7. **java.security:** This package contains classes for implementing security features, such as
encryption and digital signatures.

8. **java.nio:** This package provides the New I/O API for scalable and asynchronous I/O operations.

9. **java.time:** Introduced in Java 8, this package provides classes for working with dates, times, and
durations.

When developing Java applications, developers leverage these classes and packages to perform
common tasks without having to implement everything from scratch. This not only saves time but also
promotes consistency and reliability across Java applications.

Operators
Operators are special symbols or keyword that are used to
perform operations on variables and values . the operator are
used to process data and the data on which these operations
are performed are called operands.
In Java, a unary operator is an operator that operates on a single operand. Here's an example of a
unary operator in Java using the negation operator ( -):

1. Unary Plus Operator (+): This operator is used to indicate a positive value.
However, it is rarely used, as the absence of a sign implies a positive value.

int positiveNumber = 5;
int result = +positiveNumber; // result is 5
2. Unary Negation Operator (-): This operator is used to negate the value of its
operand.

int positiveNumber = 5;
int negatedNumber = -positiveNumber; // negatedNumber is -5
3. Increment Operator (++): This operator is used to increment the value of its
operand by 1.

int x = 5;
x++; // Increment x by 1, now x is 6
Increment x by 1, now x is 6
4. Decrement Operator (--): This operator is used to decrement the value of its
operand by 1.

int y = 10;
y--; // Decrement y by 1, now y is 9
y by 1, now y is 9
5. Logical Complement Operator (!): This operator is used to invert the value
of a boolean.

boolean flag = true;


boolean invertedFlag = !flag; // invertedFlag is false

These are examples of unary operators in Java. Unary operators operate on a


single operand, and their behavior depends on the specific operator used.

You
Arithmetic operator in java
In Java, arithmetic operators are used to perform mathematical operations on
numeric data types. Here are the common arithmetic operators in Java:

1. Addition Operator (+): Adds two operands.


int a = 5;
int b = 10;
int sum = a + b; // sum is 15
// sum is 15
2. Subtraction Operator (-): Subtracts the right operand from the left operand.
int x = 15;
int y = 7;
int difference = x - y; // difference is 8
3. Multiplication Operator (*): Multiplies two operands.
int p = 8;
int q = 4;
int product = p * q; // product is 32
4. Division Operator (/): Divides the left operand by the right operand. Note
that if both operands are integers, the result will be an integer (truncating any
remainder).
int dividend = 20;
int divisor = 3;
int quotient = dividend / divisor; // quotient is 6
5. Modulus Operator (%): Returns the remainder when the left operand is
divided by the right operand.
int dividend = 20;
int divisor = 3;
int remainder = dividend % divisor; // remainder is 2
6. Increment Operator (++): Increases the value of the operand by 1.
int count = 5;
count++; // Increment count by 1, now count is 6
7. Decrement Operator (--): Decreases the value of the operand by 1.
int total = 10;
total--; // Decrement total by 1, now total is 9

These are the basic arithmetic operators in Java. They are used to perform
operations such as addition, subtraction, multiplication, division, modulus,
increment, and decrement on numeric values.

You

logical operator in java


Logical operators in Java are used to perform logical operations on boolean
values. There are three main logical operators in Java:
1. Logical AND (&&): Returns true if both operands are true.
boolean a = true;
boolean b = false;
boolean result = a && b; // result is false
2. Logical OR (||): Returns true if at least one of the operands is true.
boolean x = true;
boolean y = false;
boolean result = x || y; // result is true
3. Logical NOT (!): Returns true if the operand is false, and false if the operand
is true.
boolean flag = true;
boolean invertedFlag = !flag; // invertedFlag is false

These operators are commonly used in conditional statements and


expressions to control the flow of a program based on certain conditions.
Here's an example that combines logical operators:

relational operator in java


Relational operators in Java are used to compare two values and determine
the relationship between them. These operators return a boolean result (either
true or false) based on the comparison. Here are the relational operators in
Java:

1. Equal to (==): Checks if two operands are equal.


int a = 5;
int b = 7;
boolean isEqual = (a == b); // isEqual is false
2. Not equal to (!=): Checks if two operands are not equal.
int x = 10;
int y = 10;
boolean notEqual = (x != y); // notEqual is false
3. Greater than (>): Checks if the left operand is greater than the right operand.
double p = 15.5;
double q = 10.2;
boolean isGreater = (p > q); // isGreater is true
4. Less than (<): Checks if the left operand is less than the right operand.
int m = 8;
int n = 12;
boolean isLess = (m < n); // isLess is true
5. Greater than or equal to (>=): Checks if the left operand is greater than or
equal to the right operand.
int num1 = 20;
int num2 = 20;
boolean greaterOrEqual = (num1 >= num2); // greaterOrEqual is true
6. Less than or equal to (<=): Checks if the left operand is less than or equal to
the right operand.
int value1 = 30;
int value2 = 40;
boolean lessOrEqual = (value1 <= value2); // lessOrEqual is true

These operators are commonly used in conditional statements, loops, and


other constructs to make decisions based on the relationships between values.

bitwise operator in java


Bitwise operators in Java operate on individual bits of integer operands. They
are used to perform bit-level operations, which can be useful in certain low-
level programming scenarios. Here are the bitwise operators in Java:

1. Bitwise AND (&): Performs a bitwise AND operation.


int a = 5; // binary: 0101
int b = 3; // binary: 0011
int result = a & b; // result: 0001 (1 in decimal)
2. Bitwise OR (|): Performs a bitwise OR operation.
int x = 5; // binary: 0101
int y = 3; // binary: 0011
int result = x | y; // result: 0111 (7 in decimal)
3. Bitwise XOR (^): Performs a bitwise exclusive OR operation.
int p = 5; // binary: 0101
int q = 3; // binary: 0011
int result = p ^ q; // result: 0110 (6 in decimal)
4. Bitwise NOT (~): Flips the bits of its operand, changing 1s to 0s and vice
versa.
int number = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101
int result = ~number; // result: 1111 1111 1111 1111 1111 1111 1111 1010 (-6
in decimal)
5. Left Shift (<<): Shifts the bits of the left operand to the left by a specified
number of positions, filling the vacant positions with zeros.
int original = 5; // binary: 0000 0000 0000 0000 0000 0000 0000 0101
int shifted = original << 2; // shifted: 0000 0000 0000 0000 0000 0000 0001
0100 (20 in decimal)
6. Right Shift (>>): Shifts the bits of the left operand to the right by a specified
number of positions. The vacant positions are filled with the sign bit (the
leftmost bit).
int original = -16; // binary: 1111 1111 1111 1111 1111 1111 1111 0000
int shifted = original >> 2; // shifted: 1111 1111 1111 1111 1111 1111 1111
1100 (-4 in decimal)
7. Unsigned Right Shift (>>>): Shifts the bits of the left operand to the right by
a specified number of positions. The vacant positions are filled with zeros,
regardless of the sign bit.
int original = -16; // binary: 1111 1111 1111 1111 1111 1111 1111 0000
int shifted = original >>> 2; // shifted: 0011 1111 1111 1111 1111 1111 1111
1100 (1073741820 in decimal)

Bitwise operators are typically used in situations where individual bits in binary
representations need to be manipulated for various purposes, such as low-
level hardware interfacing or performance optimization in certain algorithms.
They are not as commonly used in everyday application-level programming.

operator precedence in java


ChatGPT
Operator precedence in Java determines the order in which operators are
evaluated in an expression. Operators with higher precedence are evaluated
before operators with lower precedence. If operators have the same
precedence, their associativity determines the order of evaluation (left-to-right
or right-to-left).

Here's a general overview of operator precedence in Java, from highest to


lowest:

1. Postfix operators:
 expr++
 expr--
2. Unary operators:
 ++expr
 --expr
 +expr
 -expr
 ~expr (bitwise NOT)
 !expr (logical NOT)
 (type) expr (type cast)
3. Multiplicative operators:
 * (multiplication)
 / (division)
 % (modulus)
4. Additive operators:
 + (addition)
 - (subtraction)
5. Shift operators:
 << (left shift)
 >> (signed right shift)
 >>> (unsigned right shift)
6. Relational operators:
 < (less than)
 > (greater than)
 <= (less than or equal to)
 >= (greater than or equal to)
 instanceof
7. Equality operators:
 == (equal to)
 != (not equal to)
8. Bitwise AND (&)
9. Bitwise XOR (^)
10.Bitwise OR (|)
11.Logical AND (&&)
12.Logical OR (||)
13.Conditional operator (? :)
14.Assignment operators:
 =
 +=
 -=
 *=
 /=
 %=
 <<=
 >>=
 >>>=
 &=
 ^=
 |=

The order of evaluation can be influenced by parentheses. Expressions within


parentheses are evaluated first.

It's crucial to be aware of operator precedence, especially when writing


complex expressions, to ensure that the program behaves as expected. If in
doubt, it's a good practice to use parentheses to make the order of evaluation
explicit and avoid potential issues.
Selction Statements
In Java, selection statements are used to control the flow of execution based on certain
conditions. There are two main types of selection statements in Java: if statements and
switch statements.

1. if Statements:

The if statement is used to make decisions in your code based on a condition.

Syntax:

if (condition) {

// code to be executed if the condition is true

} else {

// code to be executed if the condition is false

EXAMPLE:

int x = 10;

if (x > 0) {

System.out.println("x is positive");

} else {

System.out.println("x is non-positive");

switch Statements:

The switch statement is used when you have a variable and you want to perform
different actions based on its value.
Syntax:

switch (variable) {

case value1:

// code to be executed if variable equals value1

break;

case value2:

// code to be executed if variable equals value2

break;

// additional cases as needed

default:

// code to be executed if none of the cases match

EXAMPLE:

int dayOfWeek = 3;

switch (dayOfWeek) {

case 1:

System.out.println("Monday");

break;

case 2:
System.out.println("Tuesday");

break;

// ... other cases for other days

default:

System.out.println("Invalid day");

EXAMPLE OF DO-WHILE LOOP


public class DoWhileLoopExample {

public static void main(String[] args) {

int i = 1;

do {

System.out.println(i);

i++;

} while (i <= 5);

EXAMPLE OF WHILE LOOP


public class WhileLoopExample {

public static void main(String[] args) {


int i = 1;

while (i <= 5) {

System.out.println(i);

i++;

EXAMPLE OF FOR LOOP

public class ForLoopExample {

public static void main(String[] args) {

for (int i = 1; i <= 5; i++) {

System.out.println(i);

Classes in Java
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.
Properties of Java Classes
1. Class is not a real-world entity. It is just a template or blueprint or prototype
from which objects are created.
2. Class does not occupy memory.
3. Class is a group of variables of different data types and a group of methods.
4. A Class in Java can contain:
 Data member
 Method
 Constructor
 Nested Class
 Interface
Class Declaration in Java
access_modifier class <class_name>
{
data member;
method;
constructor;
nested class;
interface;}
Java Objects
An object in Java is a basic unit of Object-Oriented Programming and
represents real-life entities. Objects are the instances of a class that are created
to use the attributes and methods of a class. A typical Java program creates
many objects, which as you know, interact by invoking methods. An object
consists of :
1. State: It is represented by attributes of an object. It also reflects the
properties of an object.
2. Behavior: It is represented by the methods of an object. It also reflects the
response of an object with other objects.
3. Identity: It gives a unique name to an object and enables one object to
interact with other objects.

Crating Objects
Java provides five ways to create an object.

o Using new Keyword


o Using clone() method
o Using newInstance() method of the Class class
o Using newInstance() method of the Constructor class
o Using Deserialization

Using new Keyword


Using the new keyword is the most popular way to create an object or instance of the
class. When we create an instance of the class by using the new keyword, it allocates
memory (heap) for the newly created object and also returns the reference of that
object to that memory. The new keyword is also used to create an array. The syntax for
creating an object is:

1. ClassName object = new ClassName();


Let's create a program that uses new keyword to create an object.

CreateObjectExample1.java

1. public class CreateObjectExample1


2. {
3. void show()
4. {
5. System.out.println("Welcome to javaTpoint");
6. }
7. public static void main(String[] args)
8. {
9. //creating an object using new keyword
10. CreateObjectExample1 obj = new CreateObjectExample1();
11. //invoking method using the object
12. obj.show();
13. }
14. }

Using clone() Method


The clone() method is the method of Object class. It creates a copy of an object and returns the
same copy. The JVM creates a new object when the clone() method is invoked. It copies all the
content of the previously created object into new one object. Note that it does not call any
constructor. We must implement the Cloneable interface while using the clone() method. The
method throws CloneNotSupportedException exception if the object's class does not support
the Cloneable interface. The subclasses that override the clone() method can throw an exception
if an instance cannot be cloned.

Note: The method creates a copy of the object not a new object.

We use the following statement to create a new object.

1. ClassName newobject = (ClassName) oldobject.clone();

Using newInstance() Method of Class class


The newInstance() method of the Class class is also used to create an object. It calls the
default constructor to create the object. It returns a newly created instance of the class
represented by the object. It internally uses the newInstance() method of the
Constructor class.

We can create an object in the following ways:


1. ClassName object = ClassName.class.newInstance();

To create the object, we use the newInstance() method of the Class class. It works only when
we know the name of the class and the class has a public default constructor.
Garbage collection in Java is the process by which Java programs perform
automatic memory management. Java programs compile to bytecode that can
be run on a Java Virtual Machine, or JVM for short. When Java programs run
on the JVM, objects are created on the heap, which is a portion of memory
dedicated to the program. Eventually, some objects will no longer be needed.
The garbage collector finds these unused objects and deletes them to free up
memory.
What is Garbage Collection?
In C/C++, a programmer is responsible for both the creation and destruction of
objects. Usually, programmer neglects the destruction of useless objects. Due
to this negligence, at a certain point, sufficient memory may not be available to
create new objects, and the entire program will terminate abnormally,
causing OutOfMemoryErrors.
But in Java, the programmer need not care for all those objects which are no
longer in use. Garbage collector destroys these objects. The main objective of
Garbage Collector is to free heap memory by destroying unreachable objects.
The garbage collector is the best example of the Daemon thread as it is always
running in the background.
How Does Garbage Collection in Java works?
Java garbage collection is an automatic process. Automatic garbage collection
is the process of looking at heap memory, identifying which objects are in use
and which are not, and deleting the unused objects. An in-use object, or a
referenced object, means that some part of your program still maintains a
pointer to that object. An unused or unreferenced object is no longer referenced
by any part of your program. So the memory used by an unreferenced object
can be reclaimed. The programmer does not need to mark objects to be deleted
explicitly. The garbage collection implementation lives in the JVM.

Types of Activities in Java Garbage Collection

Two types of garbage collection activity usually happen in Java. These are:
1. Minor or incremental Garbage Collection: It is said to have occurred when
unreachable objects in the young generation heap memory are removed.
2. Major or Full Garbage Collection: It is said to have occurred when the
objects that survived the minor garbage collection are copied into the old
generation or permanent generation heap memory are removed. When
compared to the young generation, garbage collection happens less
frequently in the old generation.

Important Concepts Related to Garbage Collection in Java


1. Unreachable objects: An object is said to be unreachable if it doesn’t
contain any reference to it. Also, note that objects which are part of the island of
isolation are also unreachable.

Integer i = new Integer(4);


// the new Integer object is reachable via the reference in 'i'
i = null;
// the Integer object is no longer reachable.

2. Eligibility for garbage collection: An object is said to be eligible for


GC(garbage collection) if it is unreachable. After i = null, integer object 4 in the
heap area is suitable for garbage collection in the above image.
Ways to make an object eligible for Garbage Collector
 Even though the programmer is not responsible for destroying useless
objects but it is highly recommended to make an object unreachable(thus
eligible for GC) if it is no longer required.
 There are generally four ways to make an object eligible for garbage
collection.
1. Nullifying the reference variable
2. Re-assigning the reference variable
3. An object created inside the method
4. Island of Isolation
We can also request JVM to run Garbage Collector. There are two ways to do it
:
1. Using System.gc() method: System class contain static method gc() for
requesting JVM to run Garbage Collector.
2. Using Runtime.getRuntime().gc() method: Runtime class allows the
application to interface with the JVM in which the application is running.
Advantages of Garbage Collection in Java
The advantages of Garbage Collection in Java are:
 It makes java memory-efficient because the garbage collector removes the
unreferenced objects from heap memory.
 It is automatically done by the garbage collector(a part of JVM), so we don’t
need extra effort.

ARRAYS
Array in Java is a group of like-typed variables referred to by a common name.
Arrays in Java work differently than they do in C/C++. Following are some
important points about Java arrays.
 In Java, all arrays are dynamically allocated. (discussed below)
 Arrays may be stored in contiguous memory [consecutive memory
locations].
 Since arrays are objects in Java, we can find their length using the object
property length. This is different from C/C++, where we find length using
sizeof.
 A Java array variable can also be declared like other variables with [] after
the data type.
 The variables in the array are ordered, and each has an index beginning with
0.
 Java array can also be used as a static field, a local variable, or a method
parameter.
 The size of an array must be specified by int or short value and not long.
 The direct superclass of an array type is Object.
 Every array type implements the interfaces Cloneable
and java.io.Serializable .
 This storage of arrays helps us randomly access the elements of an array
[Support Random Access].
 The size of the array cannot be altered(once initialized). However, an array
reference can be made to point to another array.
An array can contain primitives (int, char, etc.) and object (or non-primitive)
references of a class depending on the definition of the array. In the case of
primitive data types, the actual values might be stored in contiguous memory
locations(JVM does not guarantee this behavior). In the case of class
objects, the actual objects are stored in a heap segment .
One-Dimensional Arrays:
The general form of a one-dimensional array declaration is
type var-name[];
OR
type[] var-name;
An array declaration has two components: the type and the name. type declares
the element type of the array. The element type determines the data type of
each element that comprises the array. Like an array of integers, we can also
create an array of other primitive data types like char, float, double, etc., or
user-defined data types (objects of a class). Thus, the element type for the
array determines what type of data the array will hold.

Instantiating an Array in Java


When an array is declared, only a reference of an array is created. To create or
give memory to the array, you create an array like this: The general form
of new as it applies to one-dimensional arrays appears as follows:
var-name = new type [size];

Here, type specifies the type of data being allocated, size determines the
number of elements in the array, and var-name is the name of the array
variable that is linked to the array. To use new to allocate an array, you must
specify the type and number of elements to allocate.
Example:
int intArray[]; //declaring array
intArray = new int[20]; // allocating memory to array

OR
int[] intArray = new int[20]; // combining both statements in one

// Java program to illustrate creating an array

// of integers, puts some values in the array,

// and prints each value to standard output.

class GFG {

public static void main(String[] args)

// declares an Array of integers.

int[] arr;

// allocating memory for 5 integers.

arr = new int[5];


// initialize the first elements of the array

arr[0] = 10;

// initialize the second elements of the array

arr[1] = 20;

// so on...

arr[2] = 30;

arr[3] = 40;

arr[4] = 50;

// accessing the elements of the specified array

for (int i = 0; i < arr.length; i++)

System.out.println("Element at index " + i

+ " : " + arr[i]);

Arrays of Objects
An array of objects is created like an array of primitive-type data items in the
following way.
Student[] arr = new Student[5]; //student is a user-defined class

Syntax:
- data type[] arrName;
- datatype arrName[];
- datatype [] arrName;

Multidimensional Arrays
Multidimensional arrays are arrays of arrays with each element of the array
holding the reference of other arrays. These are also known as Jagged Arrays.
A multidimensional array is created by appending one set of square brackets
([]) per dimension.
Syntax :
datatype [][] arrayrefvariable;
or
datatype arrayrefvariable[][];

int[][] intArray = new int[10][20]; //a 2D array or matrix


int[][][] intArray = new int[10][20][10]; //a 3D array

STRING BUFFER
StringBuffer is a class in Java that represents a mutable sequence of
characters. It provides an alternative to the immutable String class, allowing you
to modify the contents of a string without creating a new object every time.
Here are some important features and methods of the StringBuffer
class:
1. StringBuffer objects are mutable, meaning that you can change the contents
of the buffer without creating a new object.
2. The initial capacity of a StringBuffer can be specified when it is created, or it
can be set later with the ensureCapacity() method.
3. The append() method is used to add characters, strings, or other objects to
the end of the buffer.
4. The insert() method is used to insert characters, strings, or other objects at a
specified position in the buffer.
5. The delete() method is used to remove characters from the buffer.
6. The reverse() method is used to reverse the order of the characters in the
buffer.
Here is an example of using StringBuffer to concatenate strings:
 Java

public class StringBufferExample {

public static void main(String[] args)

StringBuffer sb = new StringBuffer();

sb.append("Hello");

sb.append(" ");
sb.append("world");

String message = sb.toString();

System.out.println(message);

Output

Hello world
There are several advantages of using StringBuffer over regular
String objects in Java:
1. Mutable: StringBuffer objects are mutable, which means that you can modify
the contents of the object after it has been created. In contrast, String
objects are immutable, which means that you cannot change the contents of
a String once it has been created.
2. Efficient: Because StringBuffer objects are mutable, they are more efficient
than creating new String objects each time you need to modify a string. This
is especially true if you need to modify a string multiple times, as each
modification to a String object creates a new object and discards the old
one.
3. Thread-safe: StringBuffer objects are thread-safe, which means multiple
threads can access it simultaneously( they can be safely accessed and
modified by multiple threads simultaneously). In contrast, String objects are
not thread-safe, which means that you need to use synchronization if you
want to access a String object from multiple threads.
Overall, if you need to perform multiple modifications to a string, or if you need
to access a string from multiple threads, using StringBuffer can be more
efficient and safer than using regular String objects.
StringBuffer is a peer class of String that provides much of the functionality of
strings. The string represents fixed-length, immutable character sequences
while StringBuffer represents growable and writable character
sequences. StringBuffer may have characters and substrings inserted in the
middle or appended to the end. It will automatically grow to make room for such
additions and often has more characters preallocated than are actually needed,
to allow room for growth.
StringBuffer class is used to create mutable (modifiable) strings. The
StringBuffer class in Java is the same as the String class except it is mutable
i.e. it can be changed.
Important Constructors of StringBuffer class
 StringBuffer(): creates an empty string buffer with an initial capacity of 16.
 StringBuffer(String str): creates a string buffer with the specified string.
 StringBuffer(int capacity): creates an empty string buffer with the specified
capacity as length.
1. append() method
The append() method concatenates the given argument with this string.
Example:
 Java

import java.io.*;

class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello ");

sb.append("Java"); // now original string is changed

System.out.println(sb);

Output

Hello Java
2. insert() method
The insert() method inserts the given string with this string at the given position.
Example:
 Java

import java.io.*;
class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello ");

sb.insert(1, "Java");

// Now original string is changed

System.out.println(sb);

Output

HJavaello
3. replace() method
The replace() method replaces the given string from the specified beginIndex
and endIndex-1.
Example:
 Java

import java.io.*;

class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello");


sb.replace(1, 3, "Java");

System.out.println(sb);

Output

HJavalo
4. delete() method
The delete() method of the StringBuffer class deletes the string from the
specified beginIndex to endIndex-1.
Example:
 Java

import java.io.*;

class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello");

sb.delete(1, 3);

System.out.println(sb);

Output

Hlo
5. reverse() method
The reverse() method of the StringBuilder class reverses the current string.
Example:
 Java

import java.io.* ;

class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer("Hello");

sb.reverse();

System.out.println(sb);

Output

olleH
6. capacity() method
 The capacity() method of the StringBuffer class returns the current capacity
of the buffer. The default capacity of the buffer is 16. If the number of
characters increases from its current capacity, it increases the capacity by
(oldcapacity*2)+2.
 For instance, if your current capacity is 16, it will be (16*2)+2=34.
Example:
 Java

import java.io.*;
class A {

public static void main(String args[])

StringBuffer sb = new StringBuffer();

System.out.println(sb.capacity()); // default 16

sb.append("Hello");

System.out.println(sb.capacity()); // now 16

sb.append("java is my favourite language");

System.out.println(sb.capacity());

// Now (16*2)+2=34 i.e (oldcapacity*2)+2

Output

16
16
34
Some Interesting Facts about the StringBuffer class
Do keep the following points in the back of your mind:
 java.lang.StringBuffer extends (or inherits from) Object class.
 All Implemented Interfaces of StringBuffer class: Serializable, Appendable,
CharSequence.
 public final class StringBuffer extends Object implements Serializable,
CharSequence, Appendable.
 String buffers are safe for use by multiple threads. The methods can be
synchronized wherever necessary so that all the operations on any particular
instance behave as if they occur in some serial order.
 Whenever an operation occurs involving a source sequence (such as
appending or inserting from a source sequence) this class synchronizes only
on the string buffer performing the operation, not on the source.
 It inherits some of the methods from the Object class which such as clone(),
equals(), finalize(), getClass(), hashCode(), notifies(), notifyAll().
Remember: StringBuilder, J2SE 5 adds a new string class to Java’s already
powerful string handling capabilities. This new class is called StringBuilder. It is
identical to StringBuffer except for one important difference: it is not
synchronized, which means that it is not thread-safe. The advantage
of StringBuilder is faster performance. However, in cases in which you are
using multithreading, you must use StringBuffer rather than StringBuilder.
Constructors of StringBuffer class
1. StringBuffer(): It reserves room for 16 characters without reallocation
StringBuffer s = new StringBuffer();
2. StringBuffer( int size): It accepts an integer argument that explicitly sets the
size of the buffer.
StringBuffer s = new StringBuffer(20);
3. StringBuffer(String str): It accepts a string argument that sets the initial
contents of the StringBuffer object and reserves room for 16 more characters
without reallocation.
StringBuffer s = new StringBuffer("GeeksforGeeks");

UNIT-2
Classes and Inheritance: Using Existing Classes, Class Inheritance, Choosing Base Class, Multiple Levels
of Inheritance, Abstraction through Abstract Classes, Using Final Modifier.

Packages: Understanding Packages, Defining a Package, Packaging up Your Classes, Adding Classes from
a Package to Your Program, Understanding CLASSPATH, Standard Packages, Access Protection in
Packages.

Interface Fundamentals: Creating an Interface, Implementing an Interface, Using Interface References,


Implementing Multiple Interfaces, Constants in Interfaces, Interfaces can be extended, Nested
Interfaces, Final Thoughts on Interfaces.
Abstract class

In Java, an abstract class is a class that cannot be instantiated on its own and is
meant to be subclassed by other classes. It may contain abstract methods
(methods without a body) that must be implemented by its concrete (non-
abstract) subclasses. Abstract classes provide a way to define a common interface
for a group of related classes while allowing some level of implementation to be
shared among the subclasses.

Here are key features and rules associated with abstract classes in Java:

1. **Declaring an Abstract Class:**

- An abstract class is declared using the `abstract` keyword.

- It can have both abstract and concrete methods.

- Abstract classes can also have fields (attributes) and constructors.

abstract class MyAbstractClass {

// Abstract method (no method body)

public abstract void myAbstractMethod();

// Concrete method with an implementation

public void myConcreteMethod() {

System.out.println("This is a concrete method.");

```
2. **Abstract Methods:**

- Abstract methods are declared without a body and end with a semicolon.

- Subclasses must provide concrete implementations for all abstract methods.

abstract class Shape {

// Abstract method (to be implemented by subclasses)

public abstract void draw();

```

3. **Instantiation:**

- Abstract classes cannot be instantiated directly using the `new` keyword.

- You can only create instances of concrete subclasses.

// This would result in a compilation error

// Shape shape = new Shape();

```

4. **Inheritance:**

- Abstract classes are meant to be extended by other classes.

- Subclasses must either provide concrete implementations for all abstract


methods or be declared abstract themselves.

class Circle extends Shape {

// Concrete implementation of the abstract method

@Override

public void draw() {

System.out.println("Drawing a circle.");
}

```

5. **Constructors:**

- Abstract classes can have constructors, and they are typically used to initialize
fields.

- Constructors of abstract classes are invoked when an instance of a concrete


subclass is created.

```java

abstract class Animal {

String name;

public Animal(String name) {

this.name = name;

// Abstract method

public abstract void makeSound();

```

Abstract classes are useful when you want to provide a common base for a set of
related classes, ensuring that certain methods are implemented in each subclass
while allowing shared implementation to be defined in the abstract class. They
play a crucial role in achieving abstraction and creating a hierarchical structure in
your class design.

CLASSPATH: CLASSPATH is an environment variable which is used by Application


ClassLoader to locate and load the .class files. The CLASSPATH defines the path, to find
third-party and user-defined classes that are not extensions or part of Java platform.
Include all the directories which contain .class files and JAR files when setting the
CLASSPATH.

You need to set the CLASSPATH if:

o You need to load a class that is not present in the current directory or any sub-
directories.
o You need to load a class that is not in a location specified by the extensions
mechanism.

The CLASSPATH depends on what you are setting the CLASSPATH. The CLASSPATH has
a directory name or file name at the end. The following points describe what should be
the end of the CLASSPATH.

o If a JAR or zip, the file contains class files, the CLASSPATH end with the name of
the zip or JAR file.
o If class files placed in an unnamed package, the CLASSPATH ends with the
directory that contains the class files.
o If class files placed in a named package, the CLASSPATH ends with the directory
that contains the root package in the full package name, that is the first package
in the full package name.

The default value of CLASSPATH is a dot (.). It means the only current directory
searched. The default value of CLASSPATH overrides when you set the CLASSPATH
variable or using the -classpath command (for short -cp). Put a dot (.) in the new setting
if you want to include the current directory in the search path.

If CLASSPATH finds a class file which is present in the current directory, then it will load
the class and use it, irrespective of the same name class presents in another directory
which is also included in the CLASSPATH.

If you want to set multiple classpaths, then you need to separate each CLASSPATH by a
semicolon (;).

The third-party applications (MySQL and Oracle) that use the JVM can modify the
CLASSPATH environment variable to include the libraries they use. The classes can be
stored in directories or archives files. The classes of the Java platform are stored in rt.jar.
There are two ways to ways to set CLASSPATH: through Command Prompt or by setting
Environment Variable.

CHAT GPT

In Java, the classpath is a parameter that tells the Java Virtual Machine (JVM) where to look for
user-defined classes and packages. It is a collection of directories and JAR (Java Archive) files
that the JVM uses to locate class files.

The classpath can be set using the -classpath or -cp option when running a Java program
from the command line. It can include directories, JAR files, and ZIP files, separated by the
system-dependent path separator (semicolon ';' on Windows, colon ':' on Unix-like systems).

Here's an example of how to set the classpath when running a Java program:

bash
java -cp /path/to/classes:/path/to/lib/library.jar MyClass

In this example:

 /path/to/classes is the directory containing the compiled .class files.


 /path/to/lib/library.jar is a JAR file containing additional classes.
 MyClass is the name of the main class to be executed.

You can also set the classpath in a manifest file when creating a JAR file. The manifest
file is a special file inside the JAR that contains metadata about the JAR file and can
include a Class-Path attribute to specify the classpath.

In Java, the language does not support multiple inheritance for classes, meaning a class cannot
directly extend more than one class. However, Java supports multiple inheritance through
interfaces. By using interfaces, a class can implement multiple interfaces, allowing it to inherit
behaviors from multiple sources.

Here's an example to illustrate how multiple inheritance can be achieved using interfaces:

```java

// Interface representing a shape

interface Shape {
void draw();

// Interface representing a color

interface Color {

void setColor(String color);

// Class implementing both Shape and Color interfaces

class ColoredShape implements Shape, Color {

private String color;

// Implementation of draw method from Shape interface

@Override

public void draw() {

System.out.println("Drawing a colored shape");

// Implementation of setColor method from Color interface

@Override

public void setColor(String color) {

this.color = color;

System.out.println("Setting color to: " + color);

}
// Additional methods specific to ColoredShape

public void displayInfo() {

System.out.println("ColoredShape information");

public class MultipleInheritanceExample {

public static void main(String[] args) {

// Creating an instance of ColoredShape

ColoredShape coloredShape = new ColoredShape();

// Calling methods from both Shape and Color interfaces

coloredShape.draw();

coloredShape.setColor("Red");

// Calling a method specific to ColoredShape

coloredShape.displayInfo();

```

In this example:
- The `Shape` interface declares a method `draw`.

- The `Color` interface declares a method `setColor`.

- The `ColoredShape` class implements both `Shape` and `Color` interfaces and provides
concrete implementations for the methods declared in both interfaces.

By using interfaces, you can achieve a form of multiple inheritance in Java. This allows classes to
inherit behavior from multiple sources without the issues related to the diamond problem
(ambiguity) that can occur with multiple inheritance in some other languages.

Main thread

In Java, the main thread refers to the primary thread that is created when a Java application
starts. This main thread is responsible for the execution of the `main` method, which serves as
the entry point for the program. The `main` method is declared as:

public static void main(String[] args) {

// Program logic goes here

Here's a brief explanation of the main thread in Java:

1. **Entry Point:** The main thread begins executing the program by invoking the `main`
method. This method contains the starting point for the execution of the program.

2. **Single Threaded:** By default, a Java program starts with a single thread—the main thread.
However, you can create additional threads in your program to perform tasks concurrently.

3. **Execution Flow:** The main thread executes the statements in the `main` method
sequentially. If the `main` method spawns additional threads, these threads may run
concurrently with the main thread.

4. **Termination:** The main thread continues executing until the `main` method completes or
until the `System.exit()` method is called, explicitly terminating the entire program.

Here's a simple example:

public class MainThreadExample {

public static void main(String[] args) {


// Code executed by the main thread

System.out.println("Main thread is running.");

// Creating a new thread

Thread anotherThread = new Thread(() -> {

// Code executed by the new thread

System.out.println("Another thread is running.");

});

// Starting the new thread

anotherThread.start();

// Code executed by the main thread

System.out.println("Main thread continues to run.");

} In this example, the main thread prints messages, creates a new thread (`anotherThread`), starts
the new thread, and then continues its own execution. The new thread runs concurrently with
the main thread and prints its message.

In Java, thread priorities and synchronization are important concepts when dealing with multi-
threaded programming. Let's discuss each of these concepts:

### Thread Priorities:

In Java, threads can have different priorities ranging from `Thread.MIN_PRIORITY` (1) to
`Thread.MAX_PRIORITY` (10), with `Thread.NORM_PRIORITY` (5) being the default. The thread
scheduler uses these priorities to determine the order in which threads are scheduled for
execution. Higher priority threads are given preference, but it's important to note that thread
priorities are not guarantees of execution order.
Here's an example of setting thread priorities:

class PriorityExample implements Runnable {

public void run() {

System.out.println(Thread.currentThread().getName() + " is running");

public static void main(String[] args) {

Thread thread1 = new Thread(new PriorityExample(), "Thread 1");

Thread thread2 = new Thread(new PriorityExample(), "Thread 2");

// Setting thread priorities

thread1.setPriority(Thread.MIN_PRIORITY); // Priority 1

thread2.setPriority(Thread.MAX_PRIORITY); // Priority 10

// Starting threads

thread1.start();

thread2.start();

In this example, `Thread 1` is set to the minimum priority, and `Thread 2` is set to the maximum
priority.

### Synchronization:

When multiple threads share resources or data, synchronization is necessary to prevent data
corruption or inconsistent states. The `synchronized` keyword is used in Java to achieve
synchronization.

#### Example without Synchronization:


```java

class Counter {

private int count = 0;

public void increment() {

count++;

public int getCount() {

return count;

public class WithoutSynchronization {

public static void main(String[] args) throws InterruptedException {

Counter counter = new Counter();

#### Example with Synchronization:

class SynchronizedCounter {

private int count = 0;

public synchronized void increment() {

count++;
}

public synchronized int getCount() {

return count;

public class WithSynchronization {

public static void main(String[] args) throws InterruptedException {

SynchronizedCounter counter = new SynchronizedCounter();

// Creating two threads that increment the counter

Thread thread1 = new Thread(() -> {

for (int i = 0; i < 100000; i++) {

counter.increment();

});

Thread thread2 = new Thread(() -> {

for (int i = 0; i < 100000; i++) {

counter.increment();

});

// Start the threads

thread1.start();

thread2.start();
// Wait for threads to finish

thread1.join();

thread2.join();

// Display the final count

System.out.println("Counter value: " + counter.getCount());

In this example, the `increment` and `getCount` methods are synchronized, ensuring that only
one thread can access these methods at a time, preventing race conditions and ensuring
consistent results.

Remember that while synchronization helps in avoiding data corruption, it can also introduce
performance overhead, so it should be used judiciously. Additionally, other synchronization
mechanisms, such as locks or the `java.util.concurrent` package, provide more advanced options
for managing concurrent access to shared resources.

I/O in java
In Java, Input/Output (I/O) refers to the mechanisms for reading data from various
sources and writing data to various destinations. Input typically involves receiving data
into a program from external sources, such as the keyboard, files, or network
connections. Output involves sending data from a program to external destinations,
such as the console, files, or network endpoints.

Java provides a comprehensive set of classes and interfaces in the java.io package to
handle I/O operations. The I/O operations in Java can be broadly classified into two
categories:

Byte-oriented I/O: In byte-oriented I/O, data is read or written as a stream of



bytes. This is suitable for binary data or non-textual data. InputStream and
OutputStream: These are the abstract classes at the top of the byte-oriented I/O
hierarchy.
 FileInputStream and FileOutputStream: Used for reading from and writing to
files, respectively.
Character-oriented I/O: In character-oriented I/O, data is read or written as a stream of
characters. This is suitable for textual data.
 Reader and Writer: The abstract classes at the top of the character-oriented I/O
hierarchy.
 FileReader and FileWriter: Used for reading from and writing to files,
respectively.
Write To a File

In the following example, we use the Filewriter class together with its write() method to write
some text to the file we created in the example above. Note that when you are done writing to
the file, you should close it with the close() method:Example

import java.io.FileWriter; // Import the FileWriter class

import java.io.IOException; // Import the IOException class to handle errors

public class WriteToFile {

public static void main(String[] args) {

try { FileWriter myWriter = new FileWriter("filename.txt");

mywriter.write("Files in Java might be tricky, but it is fun enough!");

myWriter.close();System.out.println("Successfully wrote to the file.");

} catch (IOException e) {

System.out.println("An error occurred.");

e.printStackTrace();}} The output will be:successfully wrote this file.

Java Read Files

In the following example, we use the Scanner class to read the contents of the text file we
created in the previous chapter:

Example

import java.io.File; // Import the File class

Maiort Java, 10. FileNotFoundException; // Import this class to handle errors import
java.util.Scanner; // Import the Scanner class to read text files

public class ReadFile {

public static void main(String[] args) {

try {

File myobj = new File("filename.txt");


Scanner myReader = new Scanner(myObj);

while (myReader.hasNextLine()) {

String data = myReader.nextLine(); System.out.println(data);}

myReader.close();

} catch (FileNotFoundException e) { System.out.println("An error occurred.");e.printStackTrace();}}

The output will be:

Files in Java might be tricky, but it is fun enough!

Java applets were a feature of Java that allowed developers to embed Java programs (applets)
into web pages. Applets have become obsolete due to security concerns, and modern web
development relies on other technologies like HTML5, CSS3, and JavaScript. Nevertheless, I can
provide you with a brief overview of the basics of Java applets and their life cycle.

### Applet Basics:

1. **Applet Definition:**

- An applet is a Java program that runs embedded in a web page.

- Applets are client-side programs, executed in the web browser.

2. **Applet Characteristics:**

- Applets are portable, as they run on any system with a Java-enabled browser.

- They are secure due to the Java sandbox, which restricts applet capabilities.

### Applet Architecture:

1. **Applet Class Hierarchy:**

- Applets extend the `Applet` class or its subclasses, such as `JApplet`.

- They interact with the applet viewer or web browser through the `Applet` class.

2. **Applet Container:**

- Applets run within a container provided by the applet viewer or web browser.

- The container manages the applet's life cycle and provides a graphical environment.
### Applet Life Cycle:

1. **Initialization:**

- `init()` method: Initializes the applet, called once when the applet is first loaded.

2. **Start:**

- `start()` method: Called after `init()`, and each time the user returns to the page.

3. **Stop:**

- `stop()` method: Called when the user navigates away from the page.

4. **Destroy:**

- `destroy()` method: Called when the applet is unloaded or the page is closed.

### Simple Applet and Display Methods:

import java.applet.Applet;

import java.awt.Graphics;

public class SimpleApplet extends Applet {

public void paint(Graphics g) {

g.drawString("Hello, Applet!", 20, 20);}}

### The HTML `<APPLET>` Tag:

To embed the applet in an HTML page:

<html>

<head></head>

<body>

<applet code="SimpleApplet.class" width="300" height="200">


Your browser does not support the <code>applet</code> tag.

</applet>

</body>

</html>

### Passing Parameters to Applets:

import java.applet.Applet;

import java.awt.Graphics;

public class ParameterizedApplet extends Applet {

private String message;

public void init() {

// Get parameter from HTML

message = getParameter("message");

if (message == null) {

message = "Default Message"; }}

public void paint(Graphics g) { g.drawString(message, 20, 20);}}

In HTML:

<html>

<head></head>

<body>

<applet code="ParameterizedApplet.class" width="300" height="200">

<param name="message" value="Custom Message">

Your browser does not support the <code>applet</code> tag.

</applet>

</body>
</html>

Note: Modern browsers no longer support Java applets, so these examples might not work in
current environments. It's recommended to explore other web technologies for building
interactive and dynamic web applications.

The Abstract Window Toolkit (AWT) is a set of classes and methods in Java for creating graphical
user interfaces (GUIs). It provides a way to create and manage windows, buttons, text fields, and
other GUI components. Here, I'll provide an overview of working with AWT classes, particularly
creating a frame window and displaying information within it.

### AWT Classes and Window Fundamentals:

1. **`Frame` Class:**

- The `Frame` class is a top-level window with a title and a border.

- It is part of the `java.awt` package.

2. **`Graphics` Class:**

- The `Graphics` class is used for drawing shapes, text, and images on a component.

- It is part of the `java.awt` package.

### Creating a Frame Window:

import java.awt.Frame;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class MyFrame extends Frame {

public MyFrame() { // Set the frame title

super("My AWT Frame"); // Set the size of the frame

setSize(400, 300) // Make the frame visible

setVisible(true); // Add a window listener to handle the closing event


addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) { System.exit(0);}};

public static void main(String[] args) {

new MyFrame();}}

In this example, a simple `Frame` is created with a title, size, and visibility. The `WindowAdapter`
class is used to handle the window-closing event, and the `System.exit(0)` method is called to
terminate the program when the window is closed.

### Creating a Frame Window in an Applet:

import java.applet.Applet;

import java.awt.Frame;

import java.awt.Graphics;

public class FrameInApplet extends Applet {

public void init() {

// Create a frame within the applet

Frame frame = new Frame("Frame in Applet");

frame.setSize(300, 200);

// Add a label to the frame

frame.add(new java.awt.Label("Hello from Frame!"));

// Make the frame visible

frame.setVisible(true); }

public void paint(Graphics g) {

// Paint method for the applet

g.drawString("Hello from Applet!", 20, 20);}}

In this example, an applet (`FrameInApplet`) is created, and within its `init()` method, a separate
`Frame` is created. The `Frame` contains a label with the text "Hello from Frame!" and is made
visible.
### Displaying Information within a Window:

import java.awt.Frame;

import java.awt.Label;

import java.awt.TextField;

import java.awt.event.WindowAdapter;

import java.awt.event.WindowEvent;

public class InfoWindow {

public static void main(String[] args) { // Create a frame

Frame frame = new Frame("Info Window"); // Create components (label and text field)

Label label = new Label("Enter your name:");

TextField textField = new TextField(); // Add components to the frame

frame.add(label);

frame.add(textField);

// Set layout (null layout for simplicity)

frame.setLayout(null);

label.setBounds(20, 50, 150, 20);

textField.setBounds(180, 50, 150, 20);

// Add a window listener to handle the closing event

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent e) {

System.exit(0);}});

// Set frame size, make it visible _ frame.setSize(400, 150); _ frame.setVisible(true);}}


In this example, a frame is created with a label and a text field for user input. The layout is set to
`null` for simplicity, and the `setBounds()` method is used to position and size the components
within the frame.

These examples illustrate the basics of creating frames, adding components, and handling
window events using AWT classes in Java. However, note that Java Swing (`javax.swing` package)
provides a more modern and flexible set of GUI components compared to AWT.

You might also like