My Java Notes
My Java Notes
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.
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
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.
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.
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.
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:
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
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.
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:
=
+=
-=
*=
/=
%=
<<=
>>=
>>>=
&=
^=
|=
1. if Statements:
Syntax:
if (condition) {
} else {
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:
break;
case value2:
break;
default:
EXAMPLE:
int dayOfWeek = 3;
switch (dayOfWeek) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
default:
System.out.println("Invalid day");
int i = 1;
do {
System.out.println(i);
i++;
while (i <= 5) {
System.out.println(i);
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.
CreateObjectExample1.java
Note: The method creates a copy of the object not a new object.
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.
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.
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.
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
class GFG {
int[] arr;
arr[0] = 10;
arr[1] = 20;
// so on...
arr[2] = 30;
arr[3] = 40;
arr[4] = 50;
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[][];
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
sb.append("Hello");
sb.append(" ");
sb.append("world");
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 {
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 {
sb.insert(1, "Java");
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 {
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 {
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 {
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 {
System.out.println(sb.capacity()); // default 16
sb.append("Hello");
System.out.println(sb.capacity()); // now 16
System.out.println(sb.capacity());
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.
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:
```
2. **Abstract Methods:**
- Abstract methods are declared without a body and end with a semicolon.
```
3. **Instantiation:**
```
4. **Inheritance:**
@Override
System.out.println("Drawing a circle.");
}
```
5. **Constructors:**
- Abstract classes can have constructors, and they are typically used to initialize
fields.
```java
String name;
this.name = name;
// Abstract method
```
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.
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:
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 Shape {
void draw();
interface Color {
@Override
@Override
this.color = color;
}
// Additional methods specific to ColoredShape
System.out.println("ColoredShape information");
coloredShape.draw();
coloredShape.setColor("Red");
coloredShape.displayInfo();
```
In this example:
- The `Shape` interface declares a method `draw`.
- 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:
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.
});
anotherThread.start();
} 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:
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:
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.
class Counter {
count++;
return count;
class SynchronizedCounter {
count++;
}
return count;
counter.increment();
});
counter.increment();
});
thread1.start();
thread2.start();
// Wait for threads to finish
thread1.join();
thread2.join();
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:
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
} catch (IOException e) {
In the following example, we use the Scanner class to read the contents of the text file we
created in the previous chapter:
Example
Maiort Java, 10. FileNotFoundException; // Import this class to handle errors import
java.util.Scanner; // Import the Scanner class to read text files
try {
while (myReader.hasNextLine()) {
myReader.close();
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.
1. **Applet Definition:**
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.
- 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.
import java.applet.Applet;
import java.awt.Graphics;
<html>
<head></head>
<body>
</applet>
</body>
</html>
import java.applet.Applet;
import java.awt.Graphics;
message = getParameter("message");
if (message == null) {
In HTML:
<html>
<head></head>
<body>
</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.
1. **`Frame` Class:**
2. **`Graphics` Class:**
- The `Graphics` class is used for drawing shapes, text, and images on a component.
import java.awt.Frame;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
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.
import java.applet.Applet;
import java.awt.Frame;
import java.awt.Graphics;
frame.setSize(300, 200);
frame.setVisible(true); }
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;
Frame frame = new Frame("Info Window"); // Create components (label and text field)
frame.add(label);
frame.add(textField);
frame.setLayout(null);
frame.addWindowListener(new WindowAdapter() {
System.exit(0);}});
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.