Sr.
Key final finally finalize
no.
1. Definition final is the finally is the finalize is the
keyword and block in Java method in Java
access Exception which is used to
modifier which Handling to perform clean
is used to execute the up processing
apply important code just before
restrictions on whether the object is
a class, exception garbage
method or occurs or not. collected.
variable.
2. Applicable Final keyword Finally block is finalize()
to is used with always related method is used
the classes, to the try and with the
methods and catch block in objects.
variables. exception
handling.
3. Functionali (1) Once (1) finally block finalize method
ty declared, final runs the performs the
variable important code cleaning
becomes even if activities with
constant and exception respect to the
cannot be occurs or not. object before its
modified. (2) finally block destruction.
(2) final cleans up all
method cannot the resources
be overridden used in try
by sub class. block
(3) final class
cannot be
inherited.
4. Execution Final method Finally block is finalize method
is executed executed as is executed just
only when we soon as the before the
call it. try-catch block object is
is executed. destroyed.
It's execution is
not dependant
on the
exception.
Java final Example
Let's consider the following example where we declare final variable age.
Once declared it cannot be modified.
[Link]
public class FinalExampleTest {
1. //declaring final variable
2. final int age = 18;
3. void display() {
4.
5. // reassigning value to age variable
6. // gives compile time error
7. age = 55;
8. }
9.
10. public static void main(String[] args) {
11.
12. FinalExampleTest obj = new FinalExampleTest();
13. // gives compile time error
14. [Link]();
15. }
16. }
Output:
In the above example, we have declared a variable final. Similarly, we can
declare the methods and classes final using the final keyword.
Java finally Example
Let's see the below example where the Java code throws an exception and
the catch block handles that exception. Later the finally block is executed
after the try-catch block. Further, the rest of the code is also executed
normally.
[Link]
1. public class FinallyExample {
2. public static void main(String args[]){
3. try {
4. [Link]("Inside try block");
5. // below code throws divide by zero exception
6. int data=25/0;
7. [Link](data);
8. }
9. // handles the Arithmetic Exception / Divide by zero exception
10. catch (ArithmeticException e){
11. [Link]("Exception handled");
12. [Link](e);
13. }
14. // executes regardless of exception occurred or not
15. finally {
16. [Link]("finally block is always executed");
17. }
18. [Link]("rest of the code...");
19. }
20. }
Output:
Java finalize Example
[Link]
ADVERTISEMENT
1. public class FinalizeExample {
2. public static void main(String[] args)
3. {
4. FinalizeExample obj = new FinalizeExample();
5. // printing the hashcode
6. [Link]("Hashcode is: " + [Link]());
7. obj = null;
8. // calling the garbage collector using gc()
9. [Link]();
10. [Link]("End of the garbage collection");
11. }
12. // defining the finalize method
13. protected void finalize()
14. {
15. [Link]("Called the finalize() method");
16. }
17. }
Output:
String class in Java
Last Updated : 08 Apr, 2024
The string is a sequence of characters. In Java, objects of String
are immutable which means a constant and cannot be changed
once created.
Creating a String
There are two ways to create string in Java:
1. String literal
String s = “GeeksforGeeks”;
2. Using new keyword
String s = new String (“GeeksforGeeks”);
String Constructors in Java
1. String(byte[] byte_arr)
Construct a new String by decoding the byte array. It uses the
platform’s default character set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s_byte =new String(b_arr); //Geeks
2. String(byte[] byte_arr, Charset char_set)
Construct a new String by decoding the byte array. It uses
the char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = [Link]();
String s_byte_char = new String(b_arr, cs); //Geeks
3. String(byte[] byte_arr, String char_set_name)
Construct a new String by decoding the byte array. It uses
the char_set_name for decoding. It looks similar to the above
constructs and they appear before similar functions but it takes
the String(which contains char_set_name) as parameter while the
above constructor takes CharSet.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, "US-ASCII"); //Geeks
4. String(byte[] byte_arr, int start_index, int length)
Construct a new string from the bytes array depending on
the start_index(Starting location) and length(number of
characters from starting location).
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
String s = new String(b_arr, 1, 3); // eek
5. String(byte[] byte_arr, int start_index, int length, Charset
char_set)
Construct a new string from the bytes array depending on
the start_index(Starting location) and length(number of
characters from starting location).Uses char_set for decoding.
Example:
byte[] b_arr = {71, 101, 101, 107, 115};
Charset cs = [Link]();
String s = new String(b_arr, 1, 3, cs); // eek
String Methods in Java
1. int length()
Returns the number of characters in the String.
"GeeksforGeeks".length(); // returns 13
2. Char charAt(int i)
Returns the character at i th index.
"GeeksforGeeks".charAt(3); // returns ‘k’
3. String substring (int i)
Return the substring from the i th index character to end.
"GeeksforGeeks".substring(3); // returns “ksforGeeks”
4. String substring (int i, int j)
Returns the substring from i to j-1 index.
"GeeksforGeeks".substring(2, 5); // returns “eks”
5. String concat( String str)
Concatenates specified string to the end of this string.
String s1 = ”Geeks”;
String s2 = ”forGeeks”;
String output = [Link](s2); // returns “GeeksforGeeks”
11. int compareTo( String anotherString)
Compares two string lexicographically.
int out = [Link](s2);
// where s1 and s2 are
// strings to be compared
This returns difference s1-s2. If :
out < 0 // s1 comes before s2
out = 0 // s1 and s2 are equal.
out > 0 // s1 comes after s2.
13. String toLowerCase()
Converts all the characters in the String to lower case.
String word1 = “HeLLo”;
String word3 = [Link](); // returns “hello"
14. String toUpperCase()
Converts all the characters in the String to upper case.
String word1 = “HeLLo”;
String word2 = [Link](); // returns “HELLO”
15. String trim()
Returns the copy of the String, by removing whitespaces at both
ends. It does not affect whitespaces in the middle.
String word1 = “ Learn Share Learn “;
String word2 = [Link](); // returns “Learn Share Learn”
16. String replace (char oldChar, char newChar)
Returns new string by replacing all occurrences
of oldChar with newChar.
String s1 = “feeksforfeeks“;
String s2 = “feeksforfeeks”.replace(‘f’ ,’g’); // return
“geeksforgeeks”
// Java code to illustrate different constructors and methods
// String class.
import [Link].*;
import [Link].*;
// Driver Class
class Test
{
// main function
public static void main (String[] args)
{
String s= "GeeksforGeeks";
// or String s= new String ("GeeksforGeeks");
// Returns the number of characters in the String.
[Link]("String length = " + [Link]());
// Returns the character at ith index.
[Link]("Character at 3rd position = "
+ [Link](3));
// Return the substring from the ith index character
// to end of string
[Link]("Substring " + [Link](3));
// Returns the substring from i to j-1 index.
[Link]("Substring = " + [Link](2,5));
// Concatenates string2 to the end of string1.
String s1 = "Geeks";
String s2 = "forGeeks";
[Link]("Concatenated string = " +
[Link](s2));
// Returns the index within the string
// of the first occurrence of the specified string.
String s4 = "Learn Share Learn";
[Link]("Index of Share " +
[Link]("Share"));
// Returns the index within the string of the
// first occurrence of the specified string,
// starting at the specified index.
[Link]("Index of a = " +
[Link]('a',3));
// Checking equality of Strings
Boolean out = "Geeks".equals("geeks");
[Link]("Checking Equality " + out);
out = "Geeks".equals("Geeks");
[Link]("Checking Equality " + out);
out = "Geeks".equalsIgnoreCase("gEeks ");
[Link]("Checking Equality " + out);
//If ASCII difference is zero then the two strings are similar
int out1 = [Link](s2);
[Link]("the difference between ASCII value
is="+out1);
// Converting cases
String word1 = "GeeKyMe";
[Link]("Changing to lower Case " +
[Link]());
// Converting cases
String word2 = "GeekyME";
[Link]("Changing to UPPER Case " +
[Link]());
// Trimming the word
String word4 = " Learn Share Learn ";
[Link]("Trim the word " + [Link]());
// Replacing characters
String str1 = "feeksforfeeks";
[Link]("Original String " + str1);
String str2 = "feeksforfeeks".replace('f' ,'g') ;
[Link]("Replaced f with g -> " + str2);
}
}
Output
String length = 13
Character at 3rd position = k
Substring ksforGeeks
Substring = eks
Concatenated string = GeeksforGeeks
Index of Share 6
Index of a = 8
Checking Equality false
Checking Equality ...
No. StringBuffer StringBuilder
1) StringBuffer StringBuilder is non-
is synchronized i.e. thread synchronized i.e. not thread
safe. It means two threads safe. It means two threads can
can't call the methods of call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
2) StringBuffer is less StringBuilder is more
efficient than StringBuilder. efficient than StringBuffer.
3) StringBuffer was introduced in StringBuilder was introduced
Java 1.0 in Java 1.5
StringBuilder vs StringBuffer in Java
StringBuffer Class StringBuilder Class
StringBuilder was introduced in
StringBuffer is present in Java.
Java 5.
StringBuffer is synchronized. StringBuilder is asynchronized.
This means that multiple threads This means that multiple
cannot call the methods of threads can call the methods of
StringBuffer simultaneously. StringBuilder simultaneously.
Due to synchronization, Due to its asynchronous nature,
StringBuffer is called a thread StringBuilder is not a thread
safe class. safe class.
Since there is no preliminary
Due to synchronization,
check for multiple threads,
StringBuffer is lot slower than
StringBuilder is a lot faster than
StringBuilder.
StringBuffer.
StringBuffer Example
[Link]
//Java Program to demonstrate the use of StringBuffer class.
1. public class BufferTest{
2. public static void main(String[] args){
3. StringBuffer buffer=new StringBuffer("hello");
4. [Link]("java");
5. [Link](buffer);
6. }
7. }
Output:
hellojava
StringBuilder Example
[Link]
1. //Java Program to demonstrate the use of StringBuilder class.
2. public class BuilderTest{
3. public static void main(String[] args){
4. StringBuilder builder=new StringBuilder("hello");
5. [Link]("java");
6. [Link](builder);
7. }
8. }
Output:
hellojava
Packages In Java
Last Updated : 24 Apr, 2024
Package in Java is a mechanism to encapsulate a group of
classes, sub packages and interfaces. Packages are used for:
Preventing naming conflicts. For example there can be
two classes with name Employee in two packages,
[Link] and [Link]
Making searching/locating and usage of classes,
interfaces, enumerations and annotations easier
Providing controlled access: protected and default have
package level access control. A protected member is
accessible by classes in the same package and its
subclasses. A default member (without any access
specifier) is accessible by classes in the same package
only.
Packages can be considered as data encapsulation (or
data-hiding).
How packages work?
Package names and directory structure are closely related. For
example if a package name is [Link], then there are
three directories, college, staffand cse such that cse is present
in staff and staff is present inside college. Also, the
directory college is accessible through CLASSPATH variable, i.e.,
path of parent directory of college is present in CLASSPATH. The
idea is to make sure that classes are easy to locate.
Adding a class to a Package : We can add more classes to a
created package by using package name at the top of the
program and saving it in the package directory. We need a
new java file to define a public class, otherwise we can add the
new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are
the subpackages. These are not imported by default, they have
to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package
for protected and default access specifiers.
Example :
import [Link].*;
Adding a class to a Package : We can add more classes to a
created package by using package name at the top of the
program and saving it in the package directory. We need a
new java file to define a public class, otherwise we can add the
new class to an existing .java file and recompile it.
Subpackages: Packages that are inside another package are
the subpackages. These are not imported by default, they have
to imported explicitly. Also, members of a subpackage have no
access privileges, i.e., they are considered as different package
for protected and default access specifiers.
Example :
import [Link].*;
// Java program to demonstrate accessing of members when
// corresponding classes are imported and not imported.
import [Link];
public class ImportDemo
{
public ImportDemo()
{
// [Link] is imported, hence we are
// able to access directly in our code.
Vector newVector = new Vector();
// [Link] is not imported, hence
// we were referring to it using the complete
// package.
[Link] newList = new [Link]();
}
public static void main(String arg[])
{
new ImportDemo();
}
}
In Java, a package is a way to organize related classes and interfaces. Adding a class to a
package involves creating a class file and specifying the package at the top of the file. Here’s
a step-by-step guide to adding a class to a package in Java:
Step 1: Create a Package
1. Choose or Create the Directory Structure:
o Packages correspond to directory structures. For example, a package named
[Link] would correspond to a directory structure
com/example/myapp.
2. Create the Directory:
o Create the directory structure if it doesn’t exist. In your project directory, you might
have:
src/com/example/myapp
Step 2: Create a New Java Class in the Package
1. Create the Java File:
o Inside the appropriate directory (e.g., src/com/example/myapp), create a new
Java file for your class. Let’s call it [Link].
2. Specify the Package:
o At the top of the Java file, specify the package to which this class belongs.
3. Write the Class Code:
o Write your class code as usual, including the package declaration at the top.
Here’s an example:
// File: src/com/example/myapp/[Link]
package [Link];
public class MyClass {
public void displayMessage() {
[Link]("Hello from MyClass in the [Link]
package!");
}
}
Step 3: Compile the Class
1. Navigate to the Source Directory:
o Open a terminal or command prompt and navigate to the src directory.
2. Compile the Class:
o Use the javac command to compile the class. Make sure to include the full package
o javac com/example/myapp/[Link]
Step 4: Use the Class
1. Create a Main Class (Optional):
o You can create a main class to test your newly created class. For instance, you might
create [Link] in the src directory.
2. Import the Class:
o Import the class using its full package name.
3. Write the Main Method:
o Instantiate and use the class in the main method.
Example:
java
Copy code
// File: src/[Link]
import [Link];
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
[Link]();
}
}
4. Compile the Main Class:
o Compile the [Link] file.
sh
Copy code
javac [Link]
5. Run the Main Class:
o Run the compiled Main class.
sh
Copy code
java Main
Notes
IDE Integration:
o If you are using an Integrated Development Environment (IDE) like IntelliJ IDEA,
Eclipse, or NetBeans, you can create packages and classes through the IDE's
graphical interface. The IDE will handle the directory structure and package
declaration for you.
Classpath Consideration:
o Ensure that your classpath is set correctly if you are compiling and running from the
command line. When running the java command, you might need to specify the
classpath if your compiled classes are in a different directory.
By following these steps, you can successfully add a class to a package in Java and use it
within your application.
4o
Types of packages:
Built-in Packages
These packages consist of a large number of classes which are a
part of Java [Link] of the commonly used built-in packages
are:
1. [Link]: Contains language support classes(e.g
classes which defines primitive data types, math
operations). This package is automatically imported.
2. [Link]: Contains classes for supporting input / output
operations.
3. [Link]: Contains utility classes which implement data
structures like Linked List, Dictionary and support ; for
Date / Time operations.
4. [Link]: Contains classes for creating Applets.
5. [Link]: Contain classes for implementing the
components for graphical user interfaces (like
button , ;menus etc). 6)
6. [Link]: Contain classes for supporting networking
operations.
User-defined packages: These are the packages that are
defined by the user. First we create a
directory myPackage (name should be same as the name of the
package). Then create the MyClass inside the directory with the
first statement being the package names.
// Name of the package must be same as the directory
// under which this file is saved
package myPackage;
public class MyClass
{
public void getNames(String s)
{
[Link](s);
}
}
Now we can use the MyClass class in our program.
/* import 'MyClass' class from 'names' myPackage */
import [Link];
public class PrintName
{
public static void main(String args[])
{
// Initializing the String variable
// with a value
String name = "GeeksforGeeks";
// Creating an instance of class MyClass in
// the package.
MyClass obj = new MyClass();
[Link](name);
}
}
Note : [Link] must be saved inside
the myPackage directory since it is a part of the package.
1) Upcasting
Upcasting is a type of object typecasting in which a child object is
typecasted to a parent class object. By using the Upcasting, we can
easily access the variables and methods of the parent class to the child
class. Here, we don't access all the variables and the method. We access
only some specified variables and methods of the child
class. Upcasting is also known as Generalization and Widening.
[Link]
1. class Parent{
2. void PrintData() {
3. [Link]("method of parent class");
4. }
5. }
6.
7. class Child extends Parent {
8. void PrintData() {
9. [Link]("method of child class");
10. }
11. }
[Link] UpcastingExample{
13. public static void main(String args[]) {
14.
15. Parent obj1 = (Parent) new Child();
16. Parent obj2 = (Parent) new Child();
17. [Link]();
18. [Link]();
19. }
20.}
Output:
2) Downcasting
Upcasting is another type of object typecasting. In Upcasting, we assign
a parent class reference object to the child class. In Java, we cannot
assign a parent class reference object to the child class, but if we perform
downcasting, we will not get any compile-time error. However, when we
run it, it throws the "ClassCastException". Now the point is if
downcasting is not possible in Java, then why is it allowed by the
compiler? In Java, some scenarios allow us to perform downcasting. Here,
the subclass object is referred by the parent class.
Below is an example of downcasting in which both the valid and the
invalid scenarios are explained:
[Link]
ADVERTISEMENT
ADVERTISEMENT
1. //Parent class
2. class Parent {
3. String name;
4.
5. // A method which prints the data of the parent class
6. void showMessage()
7. {
8. [Link]("Parent method is called");
9. }
10.}
11.
12.// Child class
13. class Child extends Parent {
14. int age;
15.
16. // Performing overriding
17. @Override
18. void showMessage()
19. {
20. [Link]("Child method is called");
21. }
22.}
23.
[Link] class Downcasting{
25.
26. public static void main(String[] args)
27. {
28. Parent p = new Child();
29. [Link] = "Shubham";
30.
31. // Performing Downcasting Implicitly
32. //Child c = new Parent(); // it gives compile-time error
33.
34. // Performing Downcasting Explicitly
35. Child c = (Child)p;
36.
37. [Link] = 18;
38. [Link]([Link]);
39. [Link]([Link]);
40. [Link]();
41. }
42.}
Output:
[Link] Upcasting Downcasting
1. A child object is typecasted The reference of the parent class
to a parent object. object is passed to the child
class.
2. We can perform Upcasting Implicitly Downcasting is not
implicitly or explicitly. possible.
3. In the child class, we can The methods and variables of
access the methods and both the classes(parent and
variables of the parent child) can be accessed.
class.
4. We can access some All the methods and variables of
specified methods of the both classes can be accessed by
child class. performing downcasting.
5. Parent p = new Parent() Parent p = new Child()
Child c = (Child)p;
super and this keywords in Java
Last Updated : 10 Jun, 2024
In java, super keyword is used to access methods of the parent
class while this is used to access methods of the current class.
this keyword is a reserved keyword in java i.e, we can’t use it as
an identifier. It is used to refer current class’s instance as well as
static members. It can be used in various contexts as given
below:
to refer instance variable of current class
to invoke or initiate current class constructor
can be passed as an argument in the method call
can be passed as argument in the constructor call
can be used to return the current class instance
Example
Java
// Program to illustrate this keyword
// is used to refer current class
class RR {
// instance variable
int a = 10;
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
[Link](a);
// referring current class(i.e, class RR)
// static variable(i.e, b)
this.b = 600;
[Link](b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use
// 'this' in static context.
// this.a = 700;
new RR().GFG();
}
}
Output
100
600
super keyword
1. super is a reserved keyword in java i.e, we can’t use it
as an identifier.
2. super is used to refer super-class’s instance as well
as static members.
3. super is also used to invoke super-class’s method or
constructor.
4. super keyword in java programming language refers to
the superclass of the class where the super keyword is
currently being used.
5. The most common use of super keyword is that it
eliminates the confusion between the superclasses and
subclasses that have methods with same name.
super can be used in various contexts as given below:
it can be used to refer immediate parent class instance
variable
it can be used to refer immediate parent class method
it can be used to refer immediate parent class
constructor.
Example
Java
// Program to illustrate super keyword
// refers super-class instance
class Parent {
// instance variable
int a = 10;
// static variable
static int b = 20;
}
class Base extends Parent {
void rr()
{
// referring parent class(i.e, class Parent)
// instance variable(i.e, a)
[Link](super.a);
// referring parent class(i.e, class Parent)
// static variable(i.e, b)
[Link](super.b);
}
public static void main(String[] args)
{
// Uncomment this and see here you get
// Compile Time Error since cannot use 'super'
// in static context.
// super.a = 700;
new Base().rr();
}
}
Output
10
20
Lifecycle and States of a Thread in Java
Last Updated : 18 Mar, 2024
A thread in Java at any point of time exists in any one of the
following states. A thread lies only in one of the shown states at
any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State
The diagram shown below represents various states of a thread at
any instant in time.
Implementing the Thread States in Java
In Java, to get the current state of the thread,
use [Link]() method to get the current state of the
thread. Java provides [Link] class that
defines the ENUM constants for the state of a thread, as a
summary of which is given below:
1. New
Thread state for a thread that has not yet started.
public static final [Link] NEW
2. Runnable
Thread state for a runnable thread. A thread in the runnable
state is executing in the Java virtual machine but it may be
waiting for other resources from the operating system such as a
processor.
public static final [Link] RUNNABLE
3. Blocked
Thread state for a thread blocked waiting for a monitor lock. A
thread in the blocked state is waiting for a monitor lock to enter
a synchronized block/method or reenter a synchronized
block/method after calling [Link]().
public static final [Link] BLOCKED
4. Waiting
Thread state for a waiting thread. A thread is in the waiting
state due to calling one of the following methods:
[Link] with no timeout
[Link] with no timeout
[Link]
public static final [Link] WAITING
5. Timed Waiting
Thread state for a waiting thread with a specified waiting time. A
thread is in the timed waiting state due to calling one of the
following methods with a specified positive waiting time:
[Link]
[Link] with timeout
[Link] with timeout
[Link]
[Link]
public static final [Link] TIMED_WAITING
6. Terminated
Thread state for a terminated thread. The thread has completed
execution.
Declaration: public static final [Link] TERMINATED
Example
Below is the implementation of the thread states mentioned
above:
Java
// Java program to demonstrate thread states
class thread implements Runnable {
public void run()
{
// moving thread2 to timed waiting state
try {
[Link](1500);
}
catch (InterruptedException e) {
[Link]();
}
[Link](
"State of thread1 while it called join() method on thread2
-"
+ [Link]());
try {
[Link](200);
}
catch (InterruptedException e) {
[Link]();
}
}
}
public class Test implements Runnable {
public static Thread thread1;
public static Test obj;
public static void main(String[] args)
{
obj = new Test();
thread1 = new Thread(obj);
// thread1 created and is currently in the NEW
// state.
[Link](
"State of thread1 after creating it - "
+ [Link]());
[Link]();
// thread1 moved to Runnable state
[Link](
"State of thread1 after calling .start() method on it - "
+ [Link]());
}
public void run()
{
thread myThread = new thread();
Thread thread2 = new Thread(myThread);
// thread1 created and is currently in the NEW
// state.
[Link](
"State of thread2 after creating it - "
+ [Link]());
[Link]();
// thread2 moved to Runnable state
[Link](
"State of thread2 after calling .start() method on it - "
+ [Link]());
// moving thread1 to timed waiting state
try {
// moving thread1 to timed waiting state
[Link](200);
}
catch (InterruptedException e) {
[Link]();
}
[Link](
"State of thread2 after calling .sleep() method on it - "
+ [Link]());
try {
// waiting for thread2 to die
[Link]();
}
catch (InterruptedException e) {
[Link]();
}
[Link](
"State of thread2 when it has finished it's execution - "
+ [Link]());
}
}
Output
State of thread1 after creating it - NEW
State of thread1 after calling .start() method on it -
RUNNABLE
State of thread2 after creating it - NEW
State of thread2 after calling .start() method on it -
RUNNABLE
State of thread2 after calling .sleep() method on it -
TIMED_WAITING
State of thread1 while it called join() method on thread2 -
WAITING
State of thread2 when it has finished it's execution -
TERMINATED
Applet Life Cycle in Java
In Java, an applet is a special type of program embedded in the web page
to generate dynamic content. Applet is a class in Java.
The applet life cycle can be defined as the process of how the object is
created, started, stopped, and destroyed during the entire execution of its
application. It basically has five core methods namely init(), start(), stop(),
paint() and destroy().These methods are invoked by the browser to
execute.
Along with the browser, the applet also works on the client side, thus
having less processing time.
Methods of Applet Life Cycle
There are five methods of an applet life cycle, and they are:
ADVERTISEMENT
ADVERTISEMENT
o init(): The init() method is the first method to run that initializes the
applet. It can be invoked only once at the time of initialization. The web
browser creates the initialized objects, i.e., the web browser (after
checking the security settings) runs the init() method within the applet.
o start(): The start() method contains the actual code of the applet and
starts the applet. It is invoked immediately after the init() method is
invoked. Every time the browser is loaded or refreshed, the start() method
is invoked. It is also invoked whenever the applet is maximized, restored,
or moving from one tab to another in the browser. It is in an inactive state
until the init() method is invoked.
o stop(): The stop() method stops the execution of the applet. The stop ()
method is invoked whenever the applet is stopped, minimized, or moving
from one tab to another in the browser, the stop() method is invoked.
When we go back to that page, the start() method is invoked again.
o destroy(): The destroy() method destroys the applet after its work is
done. It is invoked when the applet window is closed or when the tab
containing the webpage is closed. It removes the applet object from
memory and is executed only once. We cannot start the applet once it is
destroyed.
o paint(): The paint() method belongs to the Graphics class in Java. It is
used to draw shapes like circle, square, trapezium, etc., in the applet. It is
executed after the start() method and when the browser or applet
windows are resized.
o class TestAppletLifeCycle extends Applet {
o public void init() {
o // initialized objects
o }
o public void start() {
o // code to start the applet
o }
o public void paint(Graphics graphics) {
o // draw the shapes
o }
o public void stop() {
o // code to stop the applet
o }
o public void destroy() {
o // code to destroy the applet
o }
o }
o Implementation:
o Example 1: In order to begin with Java Applet, let’s
understand a simple code to make the Applet
o Java
// Java Program to Make An Applet
// Importing required classes from
packages
import [Link].*;
import [Link].*;
// Class 1
// Helper class extending Applet class
public class AppletDemo extends Applet
// Note: Every class used here is a
derived class of applet,
// Hence we use extends keyword Every
applet is public
{
public void init()
{
setBackground([Link]);
setForeground([Link]);
}
public void paint(Graphics g)
{
[Link]("Welcome", 100,
100);
}
}
// Save file as [Link] in
local machine
o HTML
<html>
<applet code = AppletDemo
width = 400
height = 500>
</applet>
</html>
<!-- Save as [Link] -->
o Compilation methods:
o Now in order to generate output, do follow below
undersigned to compile and run the above file:
o Method 1: Using command
o Method 2: Include the applet code in our java program.
o Methods are as follows:
o Method 1: Using the command
o Compilation:
o c:> [Link]
o Execution:
o Double click on [Link]
o This won't work on browser as we don't have the proper
plugins.
import [Link].*;
import [Link].*;
import [Link].*;
// Class definition for MyInteractiveApplet, extending Applet
public class MyInteractiveApplet extends Applet implements ActionListener
{
TextField textField;
Button button;
// Initialize method setting up UI components
public void init() {
// Set layout manager
setLayout(new FlowLayout());
// Create text field
textField = new TextField(20);
add(textField);
// Create button
button = new Button("Click Me!");
add(button);
// Register button action listener
[Link](this);
}
// Action performed method for button click
public void actionPerformed(ActionEvent e) {
String input = [Link](); // Get text from text field
showStatus("You entered: " + input); // Display input as status
message
}
}
// Java Program to illustrate using super
// many number of times
class Parent {
// instance variable
int a = 36;
// static variable
static float x = 12.2f;
}
class Base extends Parent {
void GFG()
{
// referring super class(i.e, class Parent)
// instance variable(i.e, a)
super.a = 1;
[Link](a);
// referring super class(i.e, class Parent)
// static variable(i.e, x)
super.x = 60.3f;
[Link](x);
}
public static void main(String[] args)
{
new Base().GFG();
}
}
Output
1
60.3
// Java Program to illustrate using this
// many number of times
class RRR {
// instance variable
int a = 10;
// static variable
static int b = 20;
void GFG()
{
// referring current class(i.e, class RR)
// instance variable(i.e, a)
this.a = 100;
[Link](a);
// referring current class(i.e, class RR)
// static variable(i.e, b)
this.b = 600;
[Link](b);
// referring current class(i.e, class RR)
// instance variable(i.e, a) again
this.a = 9000;
[Link](a);
}
public static void main(String[] args)
{
new RRR().GFG();
}
}
Output
100
600
9000
Java InetAddress class
Java InetAddress class represents an IP address. The
[Link] class provides methods to get the IP of any host
name for example [Link], [Link],
[Link], etc.
An IP address is represented by 32-bit or 128-bit unsigned number. An
instance of InetAddress represents the IP address with its corresponding
host name. There are two types of addresses: Unicast and Multicast. The
Unicast is an identifier for a single interface whereas Multicast is an
identifier for a set of interfaces.
Moreover, InetAddress has a cache mechanism to store successful and
unsuccessful host name resolutions.
Java InetAddress Class Methods
Method Description
public static InetAddress It returns the instance of
getByName(String host) throws InetAddress containing
UnknownHostException LocalHost IP and name.
public static InetAddress It returns the instance of
getLocalHost() throws InetAdddress containing local
UnknownHostException host name and address.
public String getHostName() It returns the host name of the
IP address.
public String getHostAddress() It returns the IP address in
string format.
Example of Java InetAddress Class
Let's see a simple example of InetAddress class to get ip address of
[Link] website.
[Link]
ADVERTISEMENT
1. import [Link].*;
2. import [Link].*;
3. public class InetDemo{
4. public static void main(String[] args){
5. try{
6. InetAddress ip=[Link]("[Link]");
7.
8. [Link]("Host Name: "+[Link]());
9. [Link]("IP Address: "+[Link]());
10. }catch(Exception e){[Link](e);}
11. }
12. }
Test it Now
Output:
Host Name: [Link]
IP Address: [Link]