Semester Question Bank 2 Solution
Semester Question Bank 2 Solution
static int n1 = 0, n2 = 1, n3 = 0;
if (count > 0) {
n3 = n1 + n2;
n1 = n2;
n2 = n3;
printFibonacci(count - 1);
printFibonacci(count - 2);
Output: 0 1 1 2 3 5 8 13 21 34
JDBC is a Java API to connect and execute the query with the database.
It is a part of JavaSE (Java Standard Edition). JDBC API uses JDBC drivers to connect with the
database.
We can use JDBC API to access tabular data stored in any relational database.
By the help of JDBC API, we can save, update, delete and fetch data from the database.
Java does not support multiple inheritance of classes, meaning a class cannot directly inherit
from more than one class. However, Java does support multiple inheritance of interfaces,
allowing a class to implement multiple interfaces and inherit method signatures from each
interface. This approach avoids the complexities associated with multiple inheritance of classes.
interface interface1 {
void method1();
interface interface2 {
void method2();
myObj.method1();
myObj.method2();
}
Output:
Implementation of method 1
Implementation of method 2
A constructor in Java is a special method that is used to initialize objects. The constructor is
called when an object of a class is created. It can be used to set initial values for object
attributes:
// creating a constructor
int x;
public j028() {
x = 5;
System.out.println(obj.x);
Output: 5
Java is platform independent because it is different from other languages like C, C++, etc. which
are compiled into platform specific machines while Java is a write once, run anywhere language.
A platform is the hardware or software environment in which a program runs. There are two
types of platforms software-based and hardware-based. Java provides a software-based
platform.
The Java platform differs from most other platforms in the sense that it is a softwarebased
platform that runs on top of other hardware-based platforms.
It has two components: 1. Runtime Environment 2. API(Application Programming Interface)
Java code can be executed on multiple platforms, for example, Windows, Linux, Sun Solaris,
Mac/OS, etc.
Java code is compiled by the compiler and converted into bytecode. This bytecode is a platform-
independent code because it can be run on multiple platforms, i.e., Write Once and Run
Anywhere (WORA).
The main() method is the starting point of any Java program. The JVM starts the execution of any
Java program form the main() method. Without the main() method, JVM will not execute the
program.
It is a default signature that is predefined in the JVM. It is called by JVM to execute a program
line by line and ends the execution after completion of the method.
Yes, we can overload the main() method. But remember that the JVM always calls the original
main() method. It does not call the overloaded main() method.
If we want to execute the overloaded main() method, it must be called from the original main()
method.
Example:-
if (args) {
System.out.println(args);
System.out.println(str);
System.out.println(args);
System.out.println("Hello");
j029.main(true);
j029.main("Alice");
j029.main(17);
It does this by identifying objects that are no longer being referenced by any other object in the
program and then removing them from memory.
This process is performed automatically by the Java Virtual Machine (JVM), so programmers do
not need to worry about manually managing memory.
• Improved performance:
By freeing up memory that is no longer being used, garbage collection can improve the
performance of the program.
Garbage collection can help to prevent memory leaks, which can occur when a program does
not release memory that is no longer needed.
• Simplified programming:
Garbage collection is an important part of the Java programming language and it is one of the
things that makes Java a popular choice for developing applications.
The main() method is static in Java because it allows the Java Virtual Machine (JVM) to call it
without creating an instance of the class that contains the main method. This is important
because the JVM starts executing a Java program by calling the main() method, and it does not
create any instances of classes until after the main() method has started executing.
If the main() method were not static, the JVM would need to create an instance of the class that
contains the main method before it could call the main() method. This would be a problem
because the JVM does not know which class to instantiate, since there may be multiple classes in
the program that contain a main() method.
By making the main() method static, the JVM can call the main() method without having to
create an instance of any class. This allows the JVM to start executing the Java program
immediately, without having to wait for any classes to be instantiated.
By understanding the difference between the two, one can choose the right unit of execution for
your task.
The most common use of the ‘this’ keyword is to eliminate the confusion between class
attributes and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter).
‘this’ can also be used to :
The idea behind inheritance in Java is that you can create new classes that are built upon existing
classes. When you inherit from an existing class, you can reuse methods and fields of the parent
class. Moreover, you can add new methods and fields in your current class also.
Inheritance represents the IS-A relationship which is also known as a parent-child relationship.
Example : Programmer is the subclass and Employee is the superclass. The relationship between
the two classes is Programmer IS-A Employee. It means that Programmer is a type of Employee.
class Employee {
}
}
Output:
1) It doesn't block the user because threads are independent and you can perform multiple
operations at the same time, so it saves time.
2) Threads are independent, so it doesn't affect other threads if an exception occurs in a single
thread.
Overall, multithreading is a powerful tool that can be used to improve the performance and
responsiveness of your Java programs.
In Java, an exception is an event that occurs during the execution of a program, that disrupts the
normal flow of the program's instructions.
Exceptions are used to handle errors and other exceptional events. When an exception occurs,
the normal flow of the program is interrupted, and the exception is thrown.
There are two types of exceptions in Java: checked exceptions and unchecked exceptions.
try {
} catch (IOException e) {
} finally {
1. Extending the Thread class.: This involves creating a new class that extends the Thread
class and overriding its run() method. The run() method is where the code for the thread
will be executed.
@Override
To start the thread, you can call the start() method on the thread object.
myThread.start();
2. Implementing the Runnable interface.: This involves creating a class that implements the
Runnable interface. The Runnable interface has a single method, run(), which is where
the code for the thread will be executed.
Here is an example of how to implement a thread by implementing the Runnable
interface:
class MyRunnable implements Runnable {
@Override
public void run() {
// Code to be executed by the thread
}
}
To start the thread, you can create a Thread object and pass the Runnable object to the
constructor. Then, you can call the start() method on the Thread object.
MyRunnable myRunnable = new MyRunnable();
Thread myThread = new Thread(myRunnable);
myThread.start();
( same as Q 10 )
An interface in Java is a reference type that is used to define a set of abstract methods. Interfaces
are used to achieve abstraction and multiple inheritance in Java.
Interfaces are also used in Java to achieve multiple inheritance. Multiple inheritance is the ability
of a class to inherit from more than one parent class. This is not possible in Java with classes, but
it is possible with interfaces.
interface Animal {
void makeSound();
This interface defines a single abstract method, makeSound(). Any class that implements the
Animal interface must provide an implementation for the makeSound() method.
@Override
System.out.println("Woof!");
}
The Dog class implements the Animal interface by providing an implementation for the
makeSound() method.
Interfaces are a powerful feature of Java that can be used to achieve abstraction and multiple
inheritance.
Pure Object Oriented Language or Complete Object Oriented Language are Fully Object Oriented
Language that supports or have features that treats everything inside the program as objects.
It doesn’t support primitive datatype(like int, char, float, bool, etc.). There are seven qualities to
be satisfied for a programming language to be pure object-oriented. They are:
1. Encapsulation/Data Hiding
2. Inheritance
3. Polymorphism
4. Abstraction
5. All predefined types are objects
6. All user defined types are objects
7. All operations performed on objects must be only through methods exposed at the objects.
Java supports properties 1, 2, 3, 4 and 6 but fails to support properties 5 and 7 given above. Java
language is not a Pure Object Oriented Language as it contains these properties:
• Primitive Data Type ex. int, long, bool, float, char, etc as Objects: In Java, we have predefined
types as non-objects (primitive types).
• The static keyword: When we declare a class as static, then it can be used without the use of
an object in Java.
• Wrapper Class: In Java, you can use Integer, Float, etc. instead of int, float etc.
Yes, we can declare a main() method as final in Java. The final keyword is used to prevent a
method from being overridden in a subclass. Since the main() method is a static method, it
cannot be overridden anyway, so declaring it final has no effect on the execution of the program.
System.out.println("Hello, world!");
There are a few reasons why you might want to declare the main() method as final. One reason is
to make it clear that the method is not intended to be overridden. Another reason is to prevent
accidental overrides, which could lead to unexpected behavior.
However, there are also some potential drawbacks to declaring the main() method as final. One
drawback is that it can make it more difficult to test the code. For example, if you want to test
the behavior of the main() method in a subclass, you will not be able to do so if the method is
declared final.
24. What is the reason behind declaring the main() method static?
The main() method is the entry point for a Java application, and it is declared static because it
does not belong to any particular instance of the class. When the Java Virtual Machine (JVM)
starts, it looks for a class with a static main() method and executes it. If no class is found with a
static main() method, the JVM throws an error.
There are several reasons why the main() method is declared static:
• Efficiency:
Declaring the main() method static allows the JVM to execute it without creating an instance
of the class. This saves memory and improves performance.
• Convenience:
Declaring the main() method static allows it to be called directly from the class, without
needing to create an object. This makes it more convenient to write code.
• Compatibility:
Declaring the main() method static ensures that it is compatible with all Java compilers and
runtime environments.
5 Marks Question
1. Explain Multi threading using interface.
The Runnable interface in Java serves as a functional interface for objects representing tasks
that can be executed by a thread. It declares a single abstract method, run(), which contains the
code that the thread will execute when started. By implementing this interface, you define the
behavior of the thread.
We create a new class which implements java.lang.Runnable interface and override run()
method. Then we instantiate a Thread object and call start() method on this object.
try {
catch (Exception e) {
System.out.println("Exception is caught");
object.start();
}
}
If we implement the Runnable interface, our class can still extend other base classes.
Using runnable will give you an object that can be shared amongst multiple threads.
2. What is java ‘ instance of ‘operator ? Explain with example. Why do we need exception handling in java?
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
class Animal {}
Output: true
// instanceof operator
/*
In this example: We have a class hierarchy with a base class Animal and two
subclasses Dog and Cat.
We use the instanceof operator to test whether the animal object is an instance of
Animal, Dog, or Cat classes.
*/
class Animal {}
class Dog extends Animal {}
else
Output:
1. Error Detection and Reporting: Exception handling allows Java programs to detect and report
errors that occur during runtime. Instead of crashing the program or causing unexpected
behavior, exceptions provide a mechanism to identify and handle errors in a controlled manner.
2. Error Recover: Exception handling enables programs to recover from errors and continue
execution. By catching exceptions and implementing appropriate error-handling logic,
developers can gracefully handle exceptional situations without terminating the program
abruptly.
3. Program Robustness: Exception handling promotes the development of robust and resilient
software. It allows developers to anticipate potential errors and design their programs to handle
them effectively, thereby improving the reliability and stability of the software.
4. Separation of Concerns: Exception handling separates error-handling logic from the main
program logic, making the code cleaner and easier to understand. By encapsulating error-
handling code within exception handling blocks, developers can maintain a clear separation
between normal program flow and error-handling behavior.
5. Debugging and Diagnostics: Exception handling provides valuable information for debugging
and diagnosing problems in Java programs. When an exception occurs, it generates a stack trace
that includes information about the source of the error, helping developers identify and fix
issues more efficiently.
try {
catch (ArithmeticException e) {
In the main() method, we call divide(10, 0) which attempts to divide by zero, causing an
ArithmeticException.
We use a try block to contain the potentially problematic code (the division operation).
Inside the try block, if an ArithmeticException occurs, control is transferred to the catch block
where we handle the exception by printing an error message.
Overall, exception handling is essential for writing robust, reliable, and maintainable Java
programs that can gracefully handle errors and unexpected situations during runtime. It plays a
crucial role in ensuring the stability, resilience, and usability of Java applications.
In other words, polymorphism allows you to define one interface and have multiple
implementations.
class AnimeCharacter {
@Override
System.out.println("Starbust Stream!");
@Override
System.out.println("Hinokami Kagura");
}
@Override
System.out.println("Black Meteorite");
character1.specialAttack();
character2.specialAttack();
character3.specialAttack();
Output:
Starbust Stream!
Hinokami Kagura!
Black Meteorite!
We have a superclass AnimeCharacter with a method specialAttack() that prints a generic attack
message.
We have three subclasses, Kirito, Tanjiro, and Asta, each of which overrides the specialAttack()
method with their specific attack messages.
In the main() method of the j034 class, you create objects of each subclass and assign them to
references of type AnimeCharacter.
When you call the specialAttack() method on each AnimeCharacter reference, Java determines
the actual type of the object at runtime and calls the appropriate overridden method
(specialAttack() of Kirito, Tanjiro, or Asta class).
This demonstrates how polymorphism allows you to treat objects of different subclasses
uniformly through their common superclass, enabling flexibility and code reuse.
Your code effectively showcases the concept of polymorphism by providing different
implementations of the specialAttack() method for different anime characters.
If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.
In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
Here is an explanation of strings in Java, along with some examples of their functions:
// Find the index of the first occurrence of a specified character or substring in the
string.
// Find the index of the last occurrence of a specified character or substring in the
string.
The final keyword in java is used to restrict the user. The java final keyword can be used in
many context.
Final can be a variable, method or a class.
void speed() {
speedlimit = 400;
}
void run(){
lamborgini.run();
8. What are the differences between Heap and Stack Memory in Java?
Stack and heap memory are two different types of memory allocation in Java. The main
difference between the two is that stack memory is used for storing local variables and
function calls, while heap memory is used for storing objects and class instances.
Stack memory is allocated when a method is called, and it is deallocated when the method
returns. This means that stack memory is very fast and efficient, but it can only be used for
storing short-lived data.
Heap memory, on the other hand, is allocated dynamically at runtime. This means that heap
memory can be used to store objects of any size, and it can be accessed from anywhere in the
application. However, heap memory is slower and less efficient than stack memory.
In general, you should use stack memory for storing local variables and function calls, and you
should use heap memory for storing objects and class instances.
Here are some examples of when you would use each type of memory:
Stack memory:
• Storing local variables in a method
• Storing the parameters to a method
• Storing the return value of a method
Heap memory:
• Storing objects
• Storing class instances
• Storing arrays
Java does not support multiple inheritance because it can lead to the diamond problem. The
diamond problem is a situation where a class inherits from two classes that have a common
ancestor, leading to conflicts in the inheritance of methods
class Parent1 {
System.out.println("Parent1");
class Parent2 {
System.out.println("Parent2");
super.fun();
In this example, the Child class inherits from both the Parent1 and Parent2 classes. Both of
these classes have a fun() method. When we call the fun() method on a Child object, the
compiler does not know which fun() method to call. This is because the Child class inherits
two different implementations of the fun() method.
The diamond problem can be avoided by using interfaces. Interfaces are similar to classes, but
they cannot have any concrete methods. Instead, interfaces only have abstract methods. This
means that when a class implements an interface, it must provide its own implementation of
the interface's methods.
For example, we could rewrite the above code using interfaces as follows:
interface Fun {
System.out.println("Parent1");
System.out.println("Parent2");
System.out.println("Child");
}
}
In this example, the Child class implements the Fun interface. This means that the Child class
must provide its own implementation of the fun() method. When we call the fun() method on
a Child object, the compiler will call the fun() method that is implemented by the Child class.
Using interfaces to avoid the diamond problem is a common practice in Java. Interfaces allow
us to achieve the same result as multiple inheritance, but without the complications.
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
abstract class achieves partial abstraction (0 to 100%) whereas interface achieves fully
abstraction (100%).
Example :-
interface A {
// methods are by default, public and abstract
void a();
void b();
}
class C extends B {
public void b() {
System.out.println("Hello! I am B.");
}
}
15 marks Question
The life cycle of a thread refers to the various states a thread goes through during its execution. A
thread is a lightweight process that can run concurrently with other threads. Threads are often
used to improve the performance of an application by allowing multiple tasks to be executed
simultaneously.
• New: A new thread is created in the new state. It remains in this state until the program
starts the thread.
• Runnable: A runnable thread is a thread that is ready to run. It is waiting for the CPU to
schedule it.
• Running: A running thread is a thread that is currently executing its code.
• Waiting: A waiting thread is a thread that is waiting for an event to occur. For example, a
thread may be waiting for another thread to finish executing, or it may be waiting for I/O to
complete.
• Terminated: A terminated thread is a thread that has finished executing its code.
@Override
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
}In this example, a new thread is created and then started. The main thread then prints a
message and waits for the new thread to finish executing. Once the new thread has finished
executing, the main thread prints another message.
This example shows how threads can be used to improve the performance of an application by
allowing multiple tasks to be executed simultaneously. In this example, the main thread is able to
continue executing while the new thread is printing its message. This allows the application to be
more responsive to the user.
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.
Example :-
import java.applet.Applet;
import java.awt.*;
// Initialization
System.out.println("Initializing applet...");
// Starting
System.out.println("Starting applet...");
// Painting
// Stopping
System.out.println("Stopping applet...");
// Destroying
System.out.println("Destroying applet...");
• Initialization (init):
The init() method is called when the applet is first loaded into the web browser. In our
example, it prints "Initializing applet..." to the console.
• Starting (start):
After initialization, the start() method is called. This method is where the main functionality
of the applet begins. In our example, it prints "Starting applet..." to the console.
• Painting:
The paint(Graphics g) method is called whenever the applet needs to be painted or
refreshed. In our example, it draws the string "Hello, Java Applet!" at coordinates (20, 20) on
the applet's canvas.
• Stopping (stop):
If the applet is minimized, covered by another window, or the user navigates away from the
web page, the stop() method is called. In our example, it prints "Stopping applet..." to the
console.
• Destroying (destroy):
When the web page containing the applet is closed, refreshed, or the browser is closed, the
destroy() method is called. In our example, it prints "Destroying applet..." to the console.
This lifecycle ensures that the applet goes through proper initialization, execution, and cleanup
stages, allowing it to function correctly within a web browser environment.
1. Try-Catch Block:
• The try-catch block is used to handle exceptions that may occur within a specific block of
code.
• The code that might throw an exception is enclosed within the `try` block, and potential
exceptions are caught and handled in the `catch` block.
• Here's an example:
try {
catch (ArithmeticException e) {
• You can have multiple catch blocks to handle different types of exceptions separately.
• Each catch block can handle a specific type of exception, allowing you to provide tailored
error messages or recovery actions.
• Here's an example:
try {
catch (IOException e) {
// Handle IOException
catch (SQLException e) {
// Handle SQLException
catch (Exception e) {
// Handle any other exceptions
3. Finally Block:
• The finally block is used to execute code that should always run, regardless of whether an
exception occurred or not.
• This block is typically used for resource cleanup tasks, such as closing files or releasing
database connections.
• Here's an example:
try {
catch (Exception e) {
finally {
// Cleanup code
closeResources();
4. Throwing Exceptions:
• You can manually throw exceptions using the `throw` keyword to indicate that an error
condition has occurred.
• This is useful for signaling errors or exceptional conditions in your code.
• Here's an example:
if (divisor == 0) {
if (divisor == 0) {
These are some of the fundamental concepts and techniques in exception handling in Java.
Understanding and effectively using exception handling can lead to more robust and reliable
software.
Swing is a Java Foundation Classes [JFC] library and an extension of the Abstract Window
Toolkit [AWT]. Java Swing offers much-improved functionality over AWT, new components,
expanded components features, and excellent event handling with drag-and-drop support.
import java.io.*;
import javax.swing.*;
Output:
Extra Questions for End Semester
( 15 marks Question )
An interface is a blueprint of a class. It has static constants and abstract methods. The abstract
methods are declared without an implementation.
An interface can be used to achieve multiple inheritance. Multiple inheritance is a feature that
allows a class to inherit from more than one class.
interface Animal {
@Override
System.out.println("Woof!");
@Override
animal.run();
Output:
Woof!
In this example, the Animal interface defines two methods: animalSound() and run(). The Dog
class implements the Animal interface and provides the implementation for the two methods.
The Animal interface can be used by any class that needs to implement the functionality of an
animal. For example, a Cat class could also implement the Animal interface and provide its own
implementation for the animalSound() and run() methods.
Interfaces are a powerful feature of Java that can be used to achieve abstraction, security, and
multiple inheritance.
5. Elaborate the Applet Architecture with its life cycle with examples.
Applet Architecture:
Applets are small Java programs that are primarily used to provide interactive features to
web applications. They are embedded within HTML pages and run inside a web browser. The
architecture of an applet involves several components and follows a specific life cycle.
• Applet Class: At the heart of the applet architecture is the Applet class, which is a
subclass of java.applet.Applet. This class provides methods that allow applets to
initialize themselves, start, stop, and destroy themselves, among other things.
• Applet Container: The applet container is responsible for managing the applet's
execution. This container could be a web browser or an applet viewer.
• HTML Document: Applets are embedded within HTML documents using the <applet>
tag, which specifies various attributes such as the applet's class name, width, height, and
parameters.
• Applet Viewer: An applet viewer is a standalone program provided by Java for testing
and running applets outside of a web browser.
This method is called when the applet is first created and loaded by the underlying
software. This method performs one-time operations such as creating the user interface
or setting the font.
• start()
This method contains the actual code of the applet that should run. The start() method
executes immediately after the init() method.
• paint()
This method is used for painting any shapes like square, rectangle, trapezium, eclipse,
etc..
• stop()
This method is used to stop the Applet. It is invoked when Applet is stop or browser is
minimized.
• destroy()
// initialized objects
Example:
import java.applet.Applet;
import java.awt.Graphics;
( 5 marks question )
There can be a lot of usage of Java this keyword. In Java, this is a reference variable that refers to
the current object. Usage of Java this keyword
Sure, let's briefly explain each of the six usages of the `this` keyword in Java:
1. Referring to Current Class Instance Variable:
• `this` can be used to refer to the instance variables of the current class.
• This is useful when there is a naming conflict between instance variables and local
variables or parameters.
• For example:
private int x;
// Method invocation
// Method implementation
private int x;
public MyClass() {
public MyClass(int x) {
• `this` can be passed as an argument in method calls to provide the current object's
reference.
• This is often used to facilitate interactions between different methods or objects.
• For example:
anotherMethod(this);
• Similarly, `this` can be passed as an argument in constructor calls to provide the current
object's reference.
• This is useful for establishing relationships between objects during construction.
• For example:
public MyClass() {
this.myClass = myClass;
private int x;
this.x = x;
return this;
These usages demonstrate how the `this` keyword is essential for managing object state,
facilitating method calls and constructor invocation, and establishing relationships between
objects in Java programs.
try {
catch (IOException e) {
// Handle IOException
}
catch (SQLException e) {
// Handle SQLException
Here is an example of handling multiple exceptions using a single catch block with multiple
exception types:
try {
Handling multiple exceptions in a single catch block can reduce code duplication and make your
code more concise. However, it is important to note that you should only use this feature if the
exceptions have similar handling code. If the exceptions have different handling code, you should
use multiple catch blocks.
Overall, using multiple exceptions in Java can be a good way to improve the readability,
maintainability, and performance of your code. However, it is important to use this feature
carefully and to avoid increasing the complexity of your code.
Example 1:
import java.io.File;
import java.io.FileReader;
import java.io.FileNotFoundException;
import java.io.IOException;
try {
catch (FileNotFoundException e) {
System.err.println("File not found: " + e.getMessage());
catch (IOException e) {
finally {
try {
if (fileReader != null) {
fileReader.close();
} catch (IOException e) {
• We use FileNotFoundException to handle the case when the specified file is not found.
• We use IOException to handle general IO errors that may occur during file reading.
• Using separate catch blocks for each type of exception allows us to provide specific error
messages and handle each type of error differently.
• In the finally block, we attempt to close the file reader. If an exception occurs while closing
the file, we handle it separately. This ensures that the file reader is always closed, even if an
exception occurs during file reading.
Example 2:
import java.util.Scanner;
try {
} catch (ArithmeticException e) {
} catch (NumberFormatException e) {
} finally {
scanner.close();
3. Examine the need for wrapper classes in any program with example.
Wrapper classes in Java are essential because they provide a way to represent primitive data
types as objects.
They serve several purposes, including enabling the use of collections, allowing for null values,
and providing utility methods for primitive types.
Suppose you have a scenario where you need to store integers in a collection such as an
ArrayList. Collections in Java can only store objects, not primitive data types like int. Here's where
wrapper classes come into play. By using wrapper classes, you can convert primitive data types
into objects, allowing you to use them in collections.
import java.util.ArrayList;
numbers.add(10);
numbers.add(20);
numbers.add(30);
System.out.println(number);
In this example:
Without wrapper classes, it would be impossible to store primitive data types like int in
collections.
Wrapper classes bridge the gap between primitive types and objects, making Java more flexible
and powerful.
Additionally, wrapper classes provide other functionalities such as Allowing null values.
4. Deduct the String handling operations and its types with examples.
Types of string handling operations in Java along with examples:
Example:
2. String Length: Finding the length of a string, i.e., the number of characters in the string.
Example:
System.out.println(length); // Output: 4
3. String Indexing: Accessing individual characters within a string using their index positions.
Example:
Example:
5. String Traversal: Iterating over each character in a string for processing or manipulation.
Example:
String string = "Java";
char ch = string.charAt(i);
System.out.println(ch);
6. String Comparison: Comparing two strings to determine if they are equal or if one precedes
Example:
Example:
if (string.contains(substring)) {
System.out.println("Substring found!");
Example:
These operations form the basis of string manipulation in Java and are used extensively in
various applications for text processing, data manipulation, and algorithm implementation.
5. Review the JDBC connectivity and show it with an example.
JDBC stands for Java Database Connectivity. JDBC is a Java API to connect and execute the query
with the database. In other words, JDBC is an API(Application programming interface) used in
Java programming to interact with databases.
The classes and interfaces of JDBC allow the application to send requests made by users to the
specified database.
The JDBC architecture consists of two-tier and three-tier processing models to access a database.
Java application that needs to communicate with the database has to be programmed using
JDBC API. JDBC Driver supporting data sources such as Oracle and SQL server has to be added in
java application for JDBC support which can be done dynamically at run time. This JDBC driver
intelligently communicates the respective data source.
package com.vinayak.jdbc;
import java.sql.*;
Class.forName(driverClassName);
// Obtain a connection
// Obtain a statement
Statement st = con.createStatement();
// Execute the query
con.close();
Example 2:
import java.sql.*;
try {
conn = DriverManager.getConnection(JDBC_URL);
stmt = conn.createStatement();
// 3. Create a table
String createTableSQL = "CREATE TABLE employees (id INTEGER PRIMARY KEY, name
stmt.executeUpdate(createTableSQL);
String insertDataSQL = "INSERT INTO employees (name, age) VALUES ('John', 30),
stmt.executeUpdate(insertDataSQL);
ResultSet rs = stmt.executeQuery(retrieveDataSQL);
while (rs.next()) {
int id = rs.getInt("id");
System.out.println("ID: " + id + ", Name: " + name + ", Age: " + age);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
} catch (SQLException e) {
e.printStackTrace();
6. Construct the Java Input and Output streams with their instances.
Certainly! Here's a simple example demonstrating Java input and output streams:
import java.io.*;
public class SimpleStreamExample {
public static void main(String[] args) {
try {
// Creating an instance of FileInputStream to read from a file
FileInputStream inputStream = new FileInputStream("input.txt");
// Reading from the input stream and writing to the output stream character by
character
int character;
while ((character = inputStream.read()) != -1) {
outputStream.write(character);
}
In this example:
7. With the servelets architecture discuss its life cycle with an example.
The servlet architecture is a web application architecture that uses Java servlets to generate
dynamic web pages. Servlets are Java programs that run on a web server and are responsible for
processing requests from web clients.
The life cycle of a servlet begins when the web server receives a request for a URL that is
mapped to a servlet. The web server then loads the servlet class and creates an instance of the
servlet. The servlet instance is then initialized by calling the init() method. The init() method is
used to initialize the servlet and to set up any resources that the servlet needs.
After the servlet has been initialized, the web server calls the service() method to process the
request. The service() method is responsible for generating the response to the request. The
response can be a dynamic web page, a file, or any other type of data.
After the service() method has been called, the web server may call the destroy() method to
destroy the servlet instance. The destroy() method is used to clean up any resources that the
servlet is using.
This servlet will be invoked when a web client requests the URL /myservlet. The init() method
will be called to initialize the servlet, the service() method will be called to process the request,
and the destroy() method will be called to clean up the servlet.
Example 2:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
resp.setContentType("text/html");
out.println(output);
System.out.println("Over");
The servlet architecture is a powerful and flexible architecture for building web applications.
Servlets can be used to generate dynamic web pages, process requests from web clients, and
access data from databases.
A servlet is a Java programming language class that extends the capabilities of servers that host
applications. Servlets can respond to any type of request, but are commonly used to extend
applications hosted by web servers.
Servlets are server side components which receives a request from a client, processes the
request and sends a content based response back to the client. The Servlet is a separate API, it is
not part of the standard Java API. The Servlet as it runs on the server side, is embedded inside a
Server.
Here is an example of a servlet that collects input from a user through an HTML form, queries
records from a database, and creates web pages dynamically:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
// ...
response.setContentType("text/html");
out.println("<html>");
out.println("<head>");
out.println("</head>");
out.println("<body>");
out.println("</body>");
out.println("</html>");
his servlet can be invoked by issuing a specific URL from the browser (HTTP client). For example,
if the servlet is deployed on a server at the address "localhost:8080", the servlet can be invoked
by issuing the following URL:
http://localhost:8080/HelloServlet
When the servlet is invoked, the doGet() method is called. The doGet() method gets the input
from the user, queries the database for records, and creates a web page. The web page is then
sent back to the browser.
9. Interpret synchronization concept with an example
Synchronization is a mechanism that ensures that only one thread can access a shared resource
at a time.
This is important because if multiple threads were to access the same resource at the same time,
it could lead to data corruption or other unexpected behavior.
class Counter {
count++;
return count;
counter.increment();
});
counter.increment();
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount());
This means that only one thread can execute the increment() method at a time. This ensures that
the counter is incremented correctly, even if multiple threads are trying to increment it at the
same time.
class Counter {
count++;
return count;
return count;
counter.increment();
});
counter.increment();
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println(counter.getCount());
In this example, the increment() method is synchronized. This means that only one thread can
execute the increment() method at a time. This ensures that the counter is incremented
correctly, even if multiple threads are trying to increment it at the same time.
Both event handling and adapter classes in Java are used to handle events. However, there
are some key differences between the two.
Event handling is a mechanism that allows you to respond to events that occur in your
program. For example, you can handle events such as mouse clicks, button presses, and
keyboard input.
Adapter classes are a type of class that provides a default implementation of an event
listener interface. This means that you can use an adapter class to handle events without
having to implement all of the methods in the event listener interface.
Here is a table comparing and contrasting event handling and adapter classes in Java:
Feature Event handling Adapter class
Implementation You must implement all of You can override only the
the methods in the event methods that you need to
listener interface handle
Flexibility More flexible, as you can Less flexible, as you can only
implement any of the override the methods that are
methods in the event provided by the adapter class
listener interface
| Example |
In general, event handling is a more flexible approach to handling events. However, adapter
classes can be a good choice if you only need to handle a few specific events.
In Java, operations are fundamental actions that can be performed on data, objects, or variables.
Here are some common types of operations in Java along with examples:
1. Arithmetic Operations:
2. Assignment Operations:
Examples:
int x = 10;
double y = 3.14;
3. Comparison Operations:
- Examples:
4. Logical Operations:
Examples:
5. String Operations:
Examples:
String concatenated = "Hello" + " " + "World"; // Concatenation
6. Array Operations:
Examples:
Arrays.sort(numbers); // Sorting
7. I/O Operations
Examples:
These examples demonstrate various types of operations commonly used in Java programming.
Depending on the specific requirements of an application, developers may use these operations
to manipulate data, control program flow, or interact with external resources.
The Common Gateway Interface (CGI) is a standard that facilitates communication between web
servers and external databases or information sources.
It acts as middleware, allowing web servers to interact with applications that process data and
send back responses.
The CGI standard was defined by the World Wide Web Consortium (W3C) and specifies how a
program interacts with a Hyper Text Transfer Protocol.
Features of CGI:
• It is a very well-defined and supported standard.
• CGI scripts are generally written in languages such as Perl, C, or shell scripts
• CGI allows applications to interface with HTML, enabling dynamic content generation for
web pages.
Advantages of CGI
Disadvantages of CGI
Alternatives to CGI
• FastCGI
• PHP
• Java Servlets
• Web Frameworks
There are two ways for two applets to communicate with each other in Java:
This interface provides methods that allow applets to get information about their
environment, including the other applets in the same document. Applets can use this
information to communicate with each other by calling methods on each other's objects.
JavaScript functions can be used to send messages between applets. This can be done by
using the window.postMessage() function to send a message to another applet, and then
using the window.addEventListener() function to listen for messages from other applets.
Here is an example of how to use the AppletContext interface to communicate between two
applets:
import java.applet.Applet;
import java.applet.AppletContext;
secondApplet.setBackground(Color.red);
This code will get the AppletContext object for the current applet, and then use it to get the
object for the second applet. Once it has the object for the second applet, it can call the
setBackground() method on that object to change the background color of the second applet.
<script>
function sendMessage(message) {
window.postMessage(message, "*");
window.addEventListener("message", function(event) {
alert(event.data);
});
</script>
This code will create two applets, and then use JavaScript to send a message from the first applet
to the second applet. When the second applet receives the message, it will display an alert box
with the message.
Note: Applets must originate from the same directory on the server in order to communicate
with each other.
15. With the multithreading architecture discuss its life cycle with an example.
Multithreading Architecture
• New: A new thread is created in the new state. It remains in this state until the program
starts the thread.
• Runnable: A runnable thread is a thread that is ready to run. It is waiting for the CPU to
schedule it.
• Running: A running thread is a thread that is currently executing its code.
• Waiting: A waiting thread is a thread that is waiting for an event to occur. For example, a
thread may be waiting for another thread to finish executing, or it may be waiting for I/O to
complete.
• Terminated: A terminated thread is a thread that has finished executing its code.
@Override
});
thread.start();
try {
thread.join();
} catch (InterruptedException e) {
}In this example, a new thread is created and then started. The main thread then prints a
message and waits for the new thread to finish executing. Once the new thread has finished
executing, the main thread prints another message.
To comprehend the role of adapter classes, one must first understand the concept of event
listeners in Java. An event listener is an interface that contains methods invoked when
certain events occur.
For instance, the WindowListener interface has seven different methods corresponding to
various window events, like window opening, closing, deiconifying, etc. If a class implements
this interface, it's required to provide implementations for all seven methods, even if it's only
interested in one event.
This is where adapter classes come in handy. Since they provide default (empty)
implementations for all event handling methods, you can create a subclass from an adapter
class, and override only those methods you're interested in.
Using Java Adapter Classes Let's take a look at a simple example of how to use a Java Adapter
Class. We will use the WindowAdapter class to close a window –
import java.awt.*;
import java.awt.event.*;
WindowExample() {
addWindowListener(new WindowAdapter(){
dispose();
});
setSize(400,400);
setLayout(null);
setVisible(true);
new WindowExample();
}
In this example, we create an anonymous subclass of WindowAdapter and override the
windowClosing method. This allows us to provide a specific implementation for window
closing while ignoring other window events.
18. Is hybrid inheritance involving multiple inheritance is possible? If so elaborate on it. Justify.
In the following Java program, we have achieved the hybrid inheritance by implementing the
combination of single and multiple inheritance (through interfaces).
In this program, we have taken the example of Human body that performs different
functionalities like eating, walking, talking, dancing etc. Human body may be either Male or
Female. So, Male and Female are the two interfaces of the HumanBody class. Both the child class
inherits the functionalities of the HumanBody class that represents the single Inheritance.
Suppose, Male and Female may have child. So, the Child class also inherits the functionalities of
the Male, Female interfaces. It represents the multiple inheritance.
The composition of single and multiple inheritance represents the hybrid inheritance.
class HumanBody {
interface Male {
interface Female {
obj.show();
obj.displayChild();
Output:
( 2 marks Question )
1. Explore the reason why char uses 2 bytes in Java and what is \u0000?
In Java, the `char` data type represents a single 16-bit Unicode character. The reason `char` uses
2 bytes (16 bits) in Java is because Java uses the UTF-16 encoding to represent characters. UTF-
16 is a variable-length character encoding that encodes characters in the Unicode code space
into one or two 16-bit code units. This allows Java to support a wide range of characters from
different languages and scripts.
The `\u0000` is an escape sequence in Java used to represent the null character. It's a way to
specify Unicode characters using their hexadecimal representation. In this case, `\u0000`
represents the null character, which has the Unicode value of 0. It's commonly used in Java for
various purposes, such as string termination or indicating the end of a string in null-terminated
strings. Additionally, in Java, it's used as the default value for the `char` data type.
2. List any two differences and similarities between Try….Catch and Throw….. Catch exceptions.
1. Try...Catch:
Syntax
try {
} catch (ExceptionType e) {
2. Throw...Catch:
Syntax:
try {
if (condition) {
} catch (ExceptionType e) {
Differences:
❖ Purpose:
➢ try...catch: Handles exceptions that occur within a block of code.
➢ throw...catch: Explicitly throws and catches exceptions within a method.
❖ Responsibility:
➢ try...catch: Programmer handles exceptions thrown within the try block.
➢ throw...catch: Programmer identifies and throws exceptions, caught elsewhere.
Similarities:
❖ Exception Handling:
➢ Both used for handling exceptions.
➢ Prevent abnormal program termination.
❖ Syntax:
➢ Similar structure with try, catch, and optionally throw keywords.
1. Platform Independence: Java's "write once, run anywhere" feature allows applications to run
on any device with a Java Virtual Machine (JVM), making it highly portable.
2. Object-Oriented Language: Java's OOP principles promote code organization, reusability, and
maintainability, facilitating the development of scalable and modular software.
3. Robust and Secure: Java's strong type system, automatic memory management, and built-in
security features ensure reliable and secure software development.
4. Rich Standard Library: Java's extensive standard library provides a wide range of pre-built
classes and methods for various programming tasks, reducing development time and effort.
5. Large Community and Ecosystem: Java has a large and active community of developers,
contributing to a vast ecosystem of frameworks, libraries, and tools, enhancing productivity and
providing solutions for diverse development needs.
5. List any two similarities and differences between C++ and Java.
➢ Similarities:
▪ Both C++ and Java are object-oriented programming languages.
▪ Both languages support the same primitive data types, such as int, float, and char.
➢ Differences:
▪ C++ is a compiled language, while Java is an interpreted language.
▪ C++ allows direct memory manipulation with pointers, while Java does not have pointers
and ensures memory safety through references.
➢ Efficiency:
Servlets are more efficient than traditional CGI programs because they are compiled into
Java bytecode and executed by the Java Virtual Machine (JVM). This means that they do not
need to be interpreted each time they are executed, which can save a significant amount of
time and resources.
➢ Scalability:
Servlets are scalable because they can be run on multiple servers. This means that they can
handle a large number of requests simultaneously without slowing down.
➢ Portability:
Servlets are portable because they are written in Java, which is a platform-independent
language. This means that they can be run on any server that supports the JVM.
➢ Security:
Servlets are secure because they run in the JVM, which is a secure environment. This means
that they are less vulnerable to attacks than CGI programs, which run in the operating
system.
➢ Flexibility:
Servlets are flexible because they can be used to implement a wide variety of web
applications. They can be used to handle requests, generate dynamic content, and access
databases.
7. Survey on AWT and Event handling bringing out any two similarities and differences between
each.
AWT and Event Handling are two important concepts in Java programming. AWT stands for
Abstract Window Toolkit and it is a set of classes that provide the basic building blocks for
creating graphical user interfaces (GUIs) in Java. Event Handling is the process of responding to
user input and other events that occur in a GUI.
Here are two similarities and two differences between AWT and Event Handling in Java:
Similarities:
• Both AWT and Event Handling are part of the Java Foundation Classes (JFC).
• Both AWT and Event Handling are used to create GUIs in Java.
Differences:
• AWT provides the basic building blocks for creating GUIs, while Event Handling is the process
of responding to user input and other events that occur in a GUI.
8. List the basic procedures and practices to build Object oriented concepts with examples.
• Object
• Classes
• Encapsulation
• Polymorphism
• Abstraction
• Inheritance ( except Multiple Inheritance )
➢ Encapsulation
Encapsulation is the process of bundling data and methods together into a single unit, called
a class. This helps to protect the data from being accessed or modified by unauthorized
code.
For example, you could create a class called Person that contains the data fields name, age,
and address. You could also create methods in the Person class to allow users to get and set
the values of these data fields.
this.name = name;
this.age = age;
this.address = address;
return name;
this.name = name;
return age;
this.age = age;
return address;
this.address = address;
➢ Inheritance
Inheritance is the process of creating a new class that inherits the properties and behaviors
of an existing class. This allows you to reuse code and create more complex classes without
having to start from scratch.
For example, you could create a class called Employee that inherits from the Person class.
The Employee class would inherit all of the data fields and methods of the Person class, plus
any additional data fields and methods that you define for the Employee class.
public Employee(String name, int age, String address, String jobTitle, double salary)
{
this.jobTitle = jobTitle;
this.salary = salary;
return jobTitle;
this.jobTitle = jobTitle;
return salary;
this.salary = salary;
➢ Abstraction
Abstraction is the process of hiding the implementation details of a class from the user. This
allows the user to focus on using the class without having to worry about how it works.
For example, you could create an abstract class called Animal. The Animal class would define
the basic properties and behaviors of an animal, such as the ability to eat and sleep. You
could then create concrete classes, such as Dog and Cat, that inherit from the Animal class
and implement the specific details of how each animal eats and sleeps.
public abstract class Animal {
@Override
@Override
@Override
@Override
➢ Polymorphism
For example, you could have a method that takes an Animal object as a parameter. This
method could then be used to call the eat() and sleep() methods on any object that inherits
from the Animal class, regardless of its specific type.
animal.sleep();
You could then call the doSomethingWithAnimal() method with a Dog object or a Cat object,
and the method would work correctly in both cases.
This can make it easier for other developers to understand and use your code.
10. Identify any two types of decision making statements and also state its resulting outcome with
an example.
➢ if-else statement: This statement allows you to execute a certain block of code if a condition
is true and another block of code 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");
In this example, if the value of x is greater than 0, the output will be "x is positive",
otherwise, it will be "x is non-positive".
➢ switch statement: This statement allows you to select one of many code blocks to be
executed.
Example:
int day = 4;
String dayName;
switch (day) {
case 1:
dayName = "Monday";
break;
case 2:
dayName = "Tuesday";
break;
case 3:
dayName = "Wednesday";
break;
case 4:
dayName = "Thursday";
break;
case 5:
dayName = "Friday";
break;
default:
dayName = "Invalid day";
In this example, if the value of day is 4, the output will be "Day is: Thursday". If day has any
other value not covered by the cases, the output will be "Day is: Invalid day".
11. Find out the end results of using the unary operators in an example.
Unary operators in Java are operators that operate on a single operand. Here are some common
unary operators and their end results:
1. Increment (++):
- Example:
int x = 5;
2. Decrement (--):
- Example:
int y = 8;
- Example:
int a = -10;
int b = 15;
- Reverses the logical state of its operand. If the operand is true, it becomes false, and vice versa.
- Example:
- Example:
These are the end results of using unary operators in Java, depending on the operator used and
the operand's value.
No, Java does not support pointers in the same way as languages like C or C++.
• In Java, the concept of pointers is abstracted away from the programmer, and direct memory
manipulation is not allowed for security and memory management reasons. Instead, Java
uses references, which are similar to pointers but with added safety features.
• Another reason why Java does not have pointers is because of performance. Pointers can be
used to access memory directly, which can be faster than accessing memory through
references. However, the performance difference is usually not significant, and the security
benefits of using references outweigh the performance benefits of using pointers.
• Finally, Java does not have pointers because it is a garbage-collected language. Garbage
collection is a process that automatically reclaims memory that is no longer being used.
Overall, Java does not have pointers because of security, performance, and garbage collection
concerns
13. Propose any example using Java package explaining when to use packages.
One example of when to use packages in Java is when you are working on a large project.
Packages can help you to organize your code and make it easier to find the classes that you need.
Another example of when to use packages is when you are working on a project with other
people. Packages can help you to avoid naming conflicts.
package com.example.myproject;
System.out.println("Hello, world!");
In this example, the MyClass class is in the com.example.myproject package. This means that the
class can be accessed by other classes in the same package, but it cannot be accessed by classes
in other packages.
To use the MyClass class from another package, you would need to import the package. For
example, the following code would import the com.example.myproject package:
import com.example.myproject;
myClass.myMethod();
Once the package has been imported, the MyClass class can be used just like any other class.
Packages are a powerful tool that can help you to organize your code and make it easier to use. If
you are working on a large project or a project with other people, you should consider using
packages.
14. Tell the alternate name of “compile time polymorphism” specifying an example for it.
Method overloading allows a class to have multiple methods with the same name but with
different parameters.
class Adder {
return a + b;
return a + b;
Both methods enable users to execute remote Java applets, with HTML embedding providing
simplicity and broad compatibility, while Java Web Start offers more features and control over
deployment.
16. List the basic procedures and practices to build implicit and explicit import statement
17. List the basic procedures and practices to build typecasting statements with examples.
Convert a value from one data type to another data type is known as type casting.
There are two types of type casting:
Converting a lower data type into a higher one is called widening type casting. It is also
known as implicit conversion or casting down. It is done automatically
byte -> short -> char -> int -> long -> float -> double
int x = 7;
long y = x;
float z = y;
Output
Converting a higher data type into a lower one is called narrowing type casting. It is also
known as explicit conversion or casting up. It is done manually by the programmer.
double -> float -> long -> int -> char -> short -> byte
double d = 166.66;
long l = (long)d;
Output
18. Tell the alternate name of “runtime polymorphism” specifying an example for it.
This mechanism in Java resolves a call to an overridden method at runtime, rather than compile
time. When an overridden method is called through a superclass reference, Java determines
which version of that method is to be executed based upon the type of the object being referred
to at the time the call occurs.
class Animal {
System.out.println("Animal sound");
@Override
System.out.println("Woof!");
}
}
@Override
System.out.println("Meow!");
In this example,
This is the most common way to run applets. To do this, you need to create an HTML file and
place the applet code in it. Then, you can open the HTML file in a web browser to run the
applet.
• Here are the steps on how to execute a local Java applet using an HTML file:
• Here are the steps on how to execute a local Java applet using the appletviewer tool:
Run the appletviewer tool with the name of the applet class as an argument. For example, to
run the applet AppletName.class, you would run the following command:
appletviewer AppletName.class
It is important to note that Java applets are no longer supported by most web browsers. This
is because applets can be a security risk. If you need to run a Java applet, you should use the
appletviewer tool.
20. Find out the end results of using the ternary operator in an example.
int x = 10;
int y = 20;
int z = (x > y) ? x : y;
System.out.println(z);
In this example, the ternary operator is used to assign the value of either x or y to the variable z,
depending on whether x is greater than y. If x is greater than y, then the value of z will be x.
Otherwise, the value of z will be y.
Output:
20
System.out.println(message);
In this example, the ternary operator is used to assign a different message to the variable
message, depending on whether the value of the variable name is equal to "Alice". If the value of
name is equal to “Alice", then the value of message will be "Hello, Alice!". Otherwise, the value
of message will be "Hello, stranger!".
Output:
Hello, Alice!
This is because the value of the variable name is equal to "Alice", so the value of message is
assigned to "Hello, Alice!".
The ternary operator can be a useful tool for simplifying code and making it more concise.
However, it is important to use it carefully, as it can be easy to make mistakes when using it.
21. Identify any two types of looping statements and also state its resulting outcomes with
examples.
Two common types of looping statements in Java are the `for` loop and the `while` loop.
1. For Loop:
The `for` loop is used when you know in advance how many times you want to execute a
block of code. The loop continues to execute as long as the condition remains true.
Example:
System.out.println(i);
Resulting Outcome:
4
5
In this example, the loop initializes `i` to `1`, checks if `i` is less than or equal to `5`, executes
the code block (`System.out.println(i)`), and then increments `i` by `1`. This process repeats
until `i` is no longer less than or equal to `5`.
2. While Loop:
The `while` loop is used when you don't know in advance how many times you want to
execute a block of code, but you know the condition under which you want to continue
looping.
Example:
int i = 1;
while (i <= 5) {
System.out.println(i);
i++;
Resulting Outcome:
In this example, the loop starts with `i` set to `1`. It then checks if `i` is less than or equal to
`5`. If true, it executes the code block (`System.out.println(i)`) and increments `i` by `1`. This
process continues until `i` is no longer less than or equal to `5`.
Both `for` and `while` loops are fundamental looping constructs in Java, each with its specific
use cases depending on whether you know the number of iterations in advance or not.
• Platform independence:
AWT allows developers to write GUI applications that run consistently across various
platforms. The reliance on native components ensures that the GUI looks native to the host
operating system, enhancing the user experience.
• Simplicity:
AWT is relatively straightforward to use, making it an excellent choice for beginners who want
to quickly build simple GUI applications.
AWT can easily be integrated with other Java libraries and APIs, adding functionality beyond
basic GUI components.
AWT provides a robust event-handling model that allows developers to respond to user input
and other events in a timely and efficient manner.
AWT is a mature and stable API that has been around for many years, making it a reliable
choice for developing GUI applications.