0% found this document useful (0 votes)
24 views

5 MARK JAVA

Uploaded by

abintomy06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views

5 MARK JAVA

Uploaded by

abintomy06
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

JAVA PROGRAMMING USING LINUX

5-MARK QUESTIONS generated by ChatGPT

1. Evaluate the milestones describing the Java programming language.

Java is a versatile, platform-independent programming language developed by Sun


Microsystems, released in 1995. Since then, Java has gone through significant
advancements, each marked by key milestones that expanded its capabilities and
broadened its usage. Java’s journey began with its “Write Once, Run Anywhere”
(WORA) promise, making it possible to write code that could run on any device or
operating system equipped with a Java Virtual Machine (JVM). This aspect made Java
especially popular in web applications and enterprise solutions.

In the late 1990s and early 2000s, Java 2 introduced Swing, a rich set of components for
building graphical user interfaces (GUIs). The Java Enterprise Edition (Java EE) followed,
establishing Java as a leading choice for developing enterprise applications with
features like Servlets, JavaServer Pages (JSP), and Enterprise JavaBeans (EJB). The
introduction of Java 5 in 2004 brought major changes with features like Generics,
Annotations, and the enhanced for loop, which greatly improved code readability and
performance.

More recent versions of Java, such as Java 8, 9, and 11, have introduced lambda
expressions, the Stream API, modules, and the adoption of the new var keyword for
local variables, making Java more flexible and modern. Java 17, released as a long-term
support (LTS) version, is an example of how Java continues to evolve, offering
modernized features that ensure it remains relevant for modern software development.

2. Explain the structure of a Java program.

A typical Java program follows a specific structure, which makes it organized and easy
to understand. Java code is written inside classes, and every program must contain at
least one class definition. Within a class, you find fields (variables) and methods
(functions) that define the behavior and properties of the class. The main method
serves as the entry point of the program; it is where the program starts executing.

The structure of a Java program can be divided into several sections. First, there are
package declarations, which group related classes together. Following this, import
statements bring in external classes and packages that the program may need to use.
After these declarations, the main class is defined with fields and methods that
implement the core functionality.

Java programs are typically modular, allowing developers to split complex functionality
into smaller classes and packages. This structure not only organizes code efficiently
but also facilitates maintenance and reusability. The use of comments in Java, both
single-line (//) and multi-line (/* ... */), is encouraged for better readability and
documentation within the code.

3. Explain the data types used in Java.

Java provides a wide range of data types to handle different kinds of data. Data types in
Java are divided mainly into two categories: primitive data types and reference data
types. Primitive data types are the basic types provided by Java, such as int, float,
double, char, and boolean, which are used to store simple values. For instance, int
is used for integer values, while double is used for larger and more precise decimal
numbers.

Reference data types, on the other hand, are used for more complex objects. These
include arrays, classes, interfaces, and strings. For example, a String in Java is a
reference type used to handle text. Reference data types are pointers that store the
address of the actual data instead of the data itself, unlike primitive types.

By having both primitive and reference data types, Java offers flexibility in programming,
allowing developers to choose the most suitable data type based on the requirements.
This variety of data types enhances the performance and efficiency of Java
applications, especially when dealing with large datasets or complex operations.

4. Write a Java program to print Armstrong numbers between 100 and


1000.

To find and print Armstrong numbers between 100 and 1000, we can write a Java
program that checks each number in this range. An Armstrong number is a number that
is equal to the sum of the cubes of its digits. For instance, 153 is an Armstrong number
because 13+53+33=1531^3 + 5^3 + 3^3 = 153 13+53+33=153. The program iterates
through numbers from 100 to 1000, calculates the sum of cubes of each digit, and
checks if it equals the original number. If it does, the number is printed.
Here’s a simple Java program for this:

public class ArmstrongNumbers {


public static void main(String[] args) {
for (int i = 100; i < 1000; i++) {
int number = i, sum = 0;
while (number != 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
if (sum == i) {
System.out.println(i);
}
}
}
}

This program uses a loop to go through each number in the range and a nested loop to
calculate the cube sum for each digit. If the sum matches the original number, it is
printed as an Armstrong number.

5. Explain different types of literals with examples.

In Java, literals represent fixed values that are assigned directly in the code. Literals can
be of different types, matching Java’s data types: integer, floating-point, character,
string, and boolean literals. Integer literals, such as 100, are numbers without a
fractional part, and they can be written in decimal, octal (prefix 0), or hexadecimal
(prefix 0x) format. For example, int num = 42; is an integer literal.

Floating-point literals represent decimal values, like 3.14 or 2.71, and they can be
written with or without an exponent (e.g., 1.5e2 for 1.5 * 10^2). Character literals,
enclosed in single quotes ('A'), represent single characters, while string literals,
enclosed in double quotes ("Hello"), represent sequences of characters.

Boolean literals, true and false, represent logical values and are commonly used in
control statements like if or while. These literals give Java flexibility in representing
diverse data types directly in the code, improving readability and reducing the need for
complex calculations or conversions.
6. Explain primitive data types.

Java provides eight primitive data types, which are the building blocks for all other data
handling in the language. These types are categorized based on the kind of values they
hold: byte, short, int, and long for integer values, float and double for decimal
values, char for single characters, and boolean for true/false values. Primitive data
types are not objects and are directly stored in memory, making them faster and more
efficient in operations.

The integer types (byte, short, int, and long) differ in their size and range. For
instance, int is a 32-bit signed integer, suitable for most integer calculations, while
long is a 64-bit integer, used when higher values are required. For floating-point
numbers, float is a 32-bit single-precision type, while double is a 64-bit double-
precision type, providing higher accuracy.

Characters in Java are represented by the char data type, which uses 16-bit Unicode
encoding to support characters from various languages. The boolean type is used for
logical values (true or false), commonly used in control structures like if statements
to make decisions based on conditions. Together, these primitive data types give Java
the versatility to handle both simple and complex calculations efficiently.

7. Describe the use of jump statements with examples.

In Java, jump statements are used to control the flow of execution by allowing the
program to “jump” to specific points within the code. The main jump statements are
break, continue, and return. The break statement is commonly used in loops or
switch statements to exit the loop or case block prematurely. For instance, when a
certain condition is met, break allows the program to stop further iterations and move
out of the loop.

The continue statement is used within loops to skip the current iteration and proceed
to the next one. For example, if a loop is iterating through numbers and we want to skip
the even ones, we can use continue to bypass them. The return statement is used in
methods to exit and optionally return a value to the calling code.

Here's a simple example illustrating break and continue in a for loop:

public class JumpStatementsExample {


public static void main(String[] args) {
for (int i = 1; i <= 10; i++) {
if (i == 5) break; // Stops the loop when i is 5
if (i % 2 == 0) continue; // Skips even numbers
System.out.println(i); // Prints only odd numbers up to
5
}
}
}

8. Explain looping statements with examples.

Java provides several looping statements to repeat blocks of code based on conditions.
The main looping statements are for, while, and do-while. The for loop is
commonly used when the number of iterations is known beforehand, while while and
do-while loops are used when the condition needs to be evaluated before each
iteration or after each iteration, respectively.

In a for loop, the syntax includes initialization, condition, and update steps, all in one
line. For example, for (int i = 0; i < 5; i++) will iterate five times. The while
loop, however, continues to iterate as long as its condition remains true. If the
condition is false from the start, it won’t execute at all. Conversely, the do-while loop
guarantees at least one iteration because the condition is checked at the end.

Here’s a sample program using each loop type:

public class LoopingStatementsExample {


public static void main(String[] args) {
// For loop
for (int i = 1; i <= 5; i++) {
System.out.println("For loop iteration: " + i);
}

// While loop
int j = 1;
while (j <= 5) {
System.out.println("While loop iteration: " + j);
j++;
}

// Do-while loop
int k = 1;
do {
System.out.println("Do-while loop iteration: " + k);
k++;
} while (k <= 5);
}
}

9. Explain the use of nested loops with an example.

Nested loops are loops placed inside other loops, allowing for complex iteration
patterns. This is often used in situations that require iterating over multi-dimensional
data structures, such as matrices or tables. Each iteration of the outer loop triggers the
complete execution of the inner loop. Nested loops are commonly used in matrix
multiplication, generating patterns, or iterating over nested arrays.

For example, in a matrix represented by a 2D array, a nested loop structure can be used
to access each element. The outer loop handles the rows, and the inner loop handles
the columns. Here’s a simple example where a nested loop is used to print a
multiplication table:

public class NestedLoopExample {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
for (int j = 1; j <= 5; j++) {
System.out.print(i * j + "\t");
}
System.out.println();
}
}
}

This program uses nested for loops to print a 5x5 multiplication table, with each line
corresponding to a row in the table.

10. Write a Java program to print Armstrong numbers between 100 and
1000.

An Armstrong number is a number equal to the sum of the cubes of its digits. For
example, 153 is an Armstrong number because 13+53+33=1531^3 + 5^3 + 3^3 =
15313+53+33=153. To find Armstrong numbers between 100 and 1000, we iterate
through each number, calculate the sum of the cubes of its digits, and compare it to the
original number.

Here’s the Java code for finding Armstrong numbers in this range:

public class ArmstrongNumbers {


public static void main(String[] args) {
System.out.println("Armstrong numbers between 100 and
1000:");
for (int i = 100; i < 1000; i++) {
int number = i, sum = 0;
while (number != 0) {
int digit = number % 10;
sum += digit * digit * digit;
number /= 10;
}
if (sum == i) {
System.out.println(i);
}
}
}
}

11. Write a Java program to print prime numbers between two limits.

To find prime numbers between two given limits, we check each number in the range to
see if it has any divisors other than 1 and itself. A prime number has no divisors other
than these two. This program takes two limits, iterates through the range, and checks
each number for primality.

Here’s the Java code to print prime numbers between two limits:

public class PrimeNumbers {


public static void main(String[] args) {
int lowerLimit = 10, upperLimit = 50;
System.out.println("Prime numbers between " + lowerLimit + "
and " + upperLimit + ":");

for (int i = lowerLimit; i <= upperLimit; i++) {


boolean isPrime = true;
for (int j = 2; j <= Math.sqrt(i); j++) {
if (i % j == 0) {
isPrime = false;
break;
}
}
if (isPrime && i > 1) {
System.out.println(i);
}
}
}
}

12. Write a Java program to find the smallest among three numbers.

Finding the smallest of three numbers is simple and can be done using conditional
statements. Here’s a Java program that takes three numbers as inputs and finds the
smallest.

public class SmallestNumber {


public static void main(String[] args) {
int a = 10, b = 20, c = 5;
int smallest = (a < b) ? (a < c ? a : c) : (b < c ? b : c);
System.out.println("The smallest number is: " + smallest);
}
}

13. Write a Java program to print the scorecard of a student using an


else-if ladder structure.

An else-if ladder allows us to assign a grade based on the score of a student. Here’s
a program that assigns grades based on score ranges:

public class ScoreCard {


public static void main(String[] args) {
int score = 85;
char grade;

if (score >= 90) {


grade = 'A';
} else if (score >= 80) {
grade = 'B';
} else if (score >= 70) {
grade = 'C';
} else if (score >= 60) {
grade = 'D';
} else {
grade = 'F';
}

System.out.println("The grade for score " + score + " is: "


+ grade);
}
}

14. Explain method overloading with an example.

Method overloading allows multiple methods with the same name but different
parameters in a single class. It provides flexibility to define methods for different types
of data. For instance, a method add can be overloaded to handle integers and doubles:

public class OverloadingExample {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public static void main(String[] args) {


OverloadingExample obj = new OverloadingExample();
System.out.println("Integer addition: " + obj.add(5, 10));
System.out.println("Double addition: " + obj.add(5.5,
10.5));
}
}
15. How will you implement multilevel inheritance in Java?

Multilevel inheritance occurs when a class is derived from another class, which is also
derived from another class, forming a chain of inheritance. In Java, this allows classes
to inherit properties and methods from multiple levels, which makes code more
reusable and modular. For example, if class A is the base class, B extends A, and C
extends B, then class C inherits the properties of both B and A.

Multilevel inheritance is useful when we want to build a hierarchy of classes that share
common behaviors but also introduce specialized features at each level. For example,
in a class hierarchy for animals, you can have a base class Animal, a subclass Mammal
(which inherits from Animal), and a subclass Dog (which inherits from Mammal).

Here’s an example of multilevel inheritance:class Animal {


void eat() {
System.out.println("Animal is eating");
}
}

class Mammal extends Animal {


void sleep() {
System.out.println("Mammal is sleeping");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("Dog is barking");
}
}

public class MultilevelInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.sleep(); // Inherited from Mammal
dog.bark(); // Defined in Dog
}
}
In this example, the Dog class inherits methods from both Mammal and Animal. This
demonstrates how multilevel inheritance enables classes to inherit features from
multiple ancestor classes.

16. Write a note on dynamic method dispatch.

Dynamic method dispatch is a mechanism in Java that allows a call to an overridden


method to be resolved at runtime, rather than compile-time. This is a core feature of
runtime polymorphism. When a subclass overrides a method from its superclass, the
method that gets executed is determined by the actual object type at runtime, not the
reference type.

This enables Java to support polymorphism, where the same method can behave
differently based on the object calling it. The actual method invoked depends on the
object's type, not the reference type. The reference type can be a superclass, but the
object it points to can be a subclass.

Here’s an example to illustrate dynamic method dispatch:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


void sound() {
System.out.println("Cat meows");
}
}

public class DynamicMethodDispatch {


public static void main(String[] args) {
Animal animal1 = new Dog();
Animal animal2 = new Cat();
animal1.sound(); // Calls Dog's sound method
animal2.sound(); // Calls Cat's sound method
}
}

In this example, even though the reference variables animal1 and animal2 are of type
Animal, the actual method that gets invoked depends on the object they point to at
runtime, which is either Dog or Cat. This is the essence of dynamic method dispatch.

17. Difference between String and StringBuffer?

In Java, both String and StringBuffer are used to handle text, but there are
significant differences between them. A String is immutable, meaning once it is
created, its value cannot be changed. Any modification to a String results in the
creation of a new String object. This can lead to inefficient memory usage when
performing frequent string concatenations or modifications, as new objects are
continuously created.

On the other hand, StringBuffer is mutable, meaning its value can be changed
without creating new objects. It is designed to be more efficient when performing
frequent modifications to strings, such as concatenation, because it allows in-place
changes to the string value.

Here’s an example to compare both:

public class StringVsStringBuffer {


public static void main(String[] args) {
// String example
String str = "Hello";
str += " World"; // Creates a new String object

// StringBuffer example
StringBuffer strBuffer = new StringBuffer("Hello");
strBuffer.append(" World"); // Modifies the existing
StringBuffer object

System.out.println("String: " + str);


System.out.println("StringBuffer: " + strBuffer);
}
}

In this example, the String object is modified by creating a new object, while the
StringBuffer modifies the existing object. For scenarios where you perform multiple
string manipulations, StringBuffer offers better performance.

18. Explain different types of built-in exceptions.

Java provides several built-in exceptions that are part of the java.lang package.
Exceptions in Java are classified into two main categories: checked exceptions and
unchecked exceptions.

Checked exceptions are exceptions that the compiler forces you to handle. These
exceptions are checked at compile-time, and you must either catch them using a try-
catch block or declare them in the method signature using the throws keyword.
Examples of checked exceptions include IOException, SQLException, and
FileNotFoundException.

Unchecked exceptions (also known as runtime exceptions) are exceptions that occur
during the program’s execution. These exceptions are not checked at compile time, and
the program may terminate if they are not handled. Examples of unchecked exceptions
include NullPointerException, ArrayIndexOutOfBoundsException, and
ArithmeticException.

Here’s an example demonstrating both types of exceptions:

import java.io.*;

public class BuiltInExceptions {


public static void main(String[] args) {
// Checked exception - IOException
try {
FileReader file = new FileReader("nonexistentfile.txt");
} catch (IOException e) {
System.out.println("Caught IOException: " +
e.getMessage());
}

// Unchecked exception - ArithmeticException


try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught ArithmeticException: " +
e.getMessage());
}
}
}

In this example, IOException is a checked exception, while ArithmeticException is


an unchecked exception. Java’s exception handling mechanism helps in writing robust
code by allowing developers to handle runtime errors gracefully.

19. Define Swing and its architecture.

Swing is a part of Java's Standard Library used to create graphical user interfaces
(GUIs). It is built on top of the AWT (Abstract Window Toolkit) and provides a richer set
of GUI components, such as buttons, text fields, and labels, with better look-and-feel
support. Swing is platform-independent, and unlike AWT, it doesn't rely on native OS
components. Instead, Swing components are entirely written in Java, making them
more portable.

The architecture of Swing consists of several components and classes, including


JFrame, JPanel, JButton, JLabel, and JTextField. These components are
lightweight and can be customized with various properties like size, color, and font.
Swing also provides the event-driven programming model, where user actions (like
clicks or typing) trigger events that are handled by event listeners.

Here’s an example of a basic Swing program:

import javax.swing.*;

public class SimpleSwingApp {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
JButton button = new JButton("Click Me!");

button.addActionListener(e ->
JOptionPane.showMessageDialog(frame, "Button clicked!"));

frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(button);
frame.setVisible(true);
}
}

In this example, a simple Swing application is created with a JFrame and a JButton.
When the button is clicked, a message dialog appears. This showcases the event-
driven nature of Swing programming.

20. Write an applet that receives two integer values as input and
displays the sum.

Java Applets are small programs that run within a web browser or an applet viewer.
Applets are not widely used today, as they were replaced by more modern technologies
like JavaFX and HTML5. However, for educational purposes, here’s an example of an
applet that receives two integer values as input and displays their sum.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class SumApplet extends Applet {


TextField num1, num2;
Button sumButton;
Label result;

public void init() {


num1 = new TextField(5);
num2 = new TextField(5);
sumButton = new Button("Sum");
result = new Label("Result: ");

sumButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
result.setText("Result: " + (n1 + n2));
}
});
add(new Label("Enter first number:"));
add(num1);
add(new Label("Enter second number:"));
add(num2);
add(sumButton);
add(result);
}
}

This applet creates a simple user interface with text fields to input two integers and a
button to compute their sum. When the button is clicked, the sum is displayed in a
label.

21. Describe various ways of drawing polygons.

In Java, you can draw polygons using the Graphics class, which is part of the AWT
package. The Graphics class provides various methods like drawPolygon() and
fillPolygon() that allow you to draw polygons with any number of sides. A polygon is
defined by its vertices, which are represented by a set of x and y coordinates.

The drawPolygon() method is used to draw the outline of a polygon, while


fillPolygon() is used to fill the interior of the polygon with color.

Here’s an example of drawing a triangle (a 3-sided polygon) in a Java applet:

import java.applet.*;
import java.awt.*;

public class PolygonExample extends Applet {


public void paint(Graphics g) {
int[] xPoints = {50, 150, 250};
int[] yPoints = {150, 50, 150};
int nPoints = 3;

// Drawing a triangle (polygon with 3 sides)


g.drawPolygon(xPoints, yPoints, nPoints);

// Filling the triangle with color


g.setColor(Color.RED);
g.fillPolygon(xPoints, yPoints, nPoints);
}
}

In this example, a triangle is drawn using the drawPolygon() method, and then filled
with red color using the fillPolygon() method. You can similarly draw other
polygons by adjusting the number of vertices and their positions.

22. Explain the data types used in Java.

In Java, data types are divided into two categories: primitive data types and reference
data types.

Primitive data types are predefined by Java and represent simple values. There are 8
primitive data types:

1. byte: 8-bit signed integer. It has a range from -128 to 127.


2. short: 16-bit signed integer. Its range is from -32,768 to 32,767.
3. int: 32-bit signed integer. This is the most commonly used integer type.
4. long: 64-bit signed integer. It has a large range and is used when a larger number
is required.
5. float: 32-bit floating point number. Used to store decimal values with single
precision.
6. double: 64-bit floating point number. It’s used for storing larger decimal
numbers with double precision.
7. char: 16-bit Unicode character. It is used to store a single character.
8. boolean: Used to store true or false values.

On the other hand, reference data types are used to refer to objects and arrays. A
reference type stores the memory address of an object, rather than the object itself.
Examples of reference types include class types, interface types, and array types.

public class DataTypesExample {


public static void main(String[] args) {
int number = 100; // primitive data type (int)
double price = 99.99; // primitive data type (double)
String message = "Hello, Java!"; // reference data type
(String)

System.out.println("Integer: " + number);


System.out.println("Double: " + price);
System.out.println("String: " + message);
}
}

In this example, int, double, and String are used to demonstrate both primitive and
reference data types. Java's strong typing system ensures that you declare the correct
type for each variable, which helps in avoiding errors during runtime.

23. Explain the character set of a Java program.

A character set in Java refers to a collection of characters that the Java programming
language can process and store. Java uses the Unicode character set, which is a global
standard designed to represent text in all modern languages. Unlike ASCII, which uses
only 7 or 8 bits per character, Unicode uses 16 bits (2 bytes) for each character,
allowing it to represent characters from virtually every language, including symbols and
emojis.

Unicode is essential for internationalization and localization of Java applications, as it


allows the same Java program to handle text in multiple languages seamlessly. For
example, Java can store characters like Chinese, Arabic, and European alphabets
without any special encoding or modifications.

Here's an example of using Unicode characters in a Java program:

public class CharacterSetExample {


public static void main(String[] args) {
char c1 = 'A'; // ASCII character
char c2 = '\u0041'; // Unicode for 'A'
char c3 = ' '; // Unicode for emoji

System.out.println("Character 1: " + c1);


System.out.println("Character 2: " + c2);
System.out.println("Character 3: " + c3);
}
}

In this program, the character A is represented both by its regular character literal and
its Unicode escape sequence (\u0041). Additionally, we display a Unicode emoji ( ).
This demonstrates the flexibility of Java’s character set, making it suitable for global
applications.
24. Write a Java program to find the smallest among 3 numbers.

To find the smallest among three numbers in Java, we can compare the numbers using
conditional statements such as if-else. This program will prompt the user for three
integers, compare them, and display the smallest value.

Here’s an example program to find the smallest of three numbers:

import java.util.Scanner;

public class SmallestNumber {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter first number: ");


int num1 = scanner.nextInt();
System.out.print("Enter second number: ");
int num2 = scanner.nextInt();
System.out.print("Enter third number: ");
int num3 = scanner.nextInt();

int smallest = num1;

if (num2 < smallest) {


smallest = num2;
}
if (num3 < smallest) {
smallest = num3;
}

System.out.println("The smallest number is: " + smallest);


}
}

This program uses basic conditional logic to determine the smallest number. It first
assumes num1 as the smallest and then compares it with num2 and num3. The result is
printed to the console.
25. Explain method overloading with an example.

Method overloading in Java occurs when two or more methods in the same class have
the same name but different parameters (either in number, type, or both). It allows a
class to perform similar operations with different types or numbers of inputs. Method
overloading increases the readability of the program by enabling the reuse of method
names.

For instance, a method add can be overloaded to accept integers, doubles, or even
strings. Java determines which method to call based on the method signature (the
method name and parameters).

Here's an example:

public class MethodOverloadingExample {


public int add(int a, int b) {
return a + b;
}

public double add(double a, double b) {


return a + b;
}

public String add(String a, String b) {


return a + b;
}

public static void main(String[] args) {


MethodOverloadingExample obj = new
MethodOverloadingExample();

System.out.println("Integer addition: " + obj.add(5, 10));


System.out.println("Double addition: " + obj.add(5.5,
10.5));
System.out.println("String addition: " + obj.add("Hello", "
World"));
}
}

In this example, the add method is overloaded to perform addition of integers, doubles,
and strings. Depending on the argument types passed, Java selects the appropriate
method to execute.
26. How will you implement hierarchical inheritance in Java?

Hierarchical inheritance in Java occurs when multiple classes inherit from a single
base class. In this type of inheritance, the base class provides common functionality,
and the derived classes can extend it while adding their own specific features. This
allows code reuse, as common behaviors are centralized in the parent class.

For example, in a class hierarchy representing animals, a base class Animal can be
inherited by subclasses Dog, Cat, and Bird.

Here’s an example to demonstrate hierarchical inheritance:

class Animal {
void eat() {
System.out.println("Animal is eating");
}
}

class Dog extends Animal {


void bark() {
System.out.println("Dog is barking");
}
}

class Cat extends Animal {


void meow() {
System.out.println("Cat is meowing");
}
}

public class HierarchicalInheritanceExample {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.bark(); // Specific to Dog

Cat cat = new Cat();


cat.eat(); // Inherited from Animal
cat.meow(); // Specific to Cat
}
}

In this example, both Dog and Cat classes inherit the eat method from the Animal
class, demonstrating hierarchical inheritance. Each subclass also has its own specific
behavior, such as bark for Dog and meow for Cat.

27. Explain about user-defined packages.

In Java, a package is a namespace that groups related classes and interfaces. While
Java provides several built-in packages, such as java.util and java.io, you can also
create your own user-defined packages to organize classes and avoid naming
conflicts. Creating packages helps in modularizing the code, improving code
readability, and maintaining it easily.

A user-defined package is declared using the package keyword at the beginning of a


Java file. The package name should follow Java's naming conventions, typically
lowercase letters, and can be hierarchical (e.g., com.mycompany.project).

Here’s an example of creating and using a user-defined package:

// File: com/example/Utility.java
package com.example;

public class Utility {


public void displayMessage() {
System.out.println("Hello from Utility class!");
}
}

// File: Main.java
import com.example.Utility;

public class Main {


public static void main(String[] args) {
Utility utility = new Utility();
utility.displayMessage();
}
}
In this example, the class Utility is placed inside the package com.example, and it is
accessed from another file by importing the package. This is how you can organize and
structure your code into meaningful packages.

28. Write a Java program to demonstrate thread priorities.

In Java, each thread has a priority that determines its importance in relation to other
threads. The thread priority is an integer value, where the default priority is 5, and the
valid range is from Thread.MIN_PRIORITY (1) to Thread.MAX_PRIORITY (10).

Thread priority influences the thread scheduling in a multi-threaded environment, but


note that it doesn’t guarantee that a thread with a higher priority will always be
executed before one with a lower priority.

Here’s a Java program demonstrating thread priorities:

class MyThread extends Thread {


public void run() {
System.out.println(Thread.currentThread().getName() + " is
running");
}
}

public class ThreadPriorityExample {


public static void main(String[] args) {
MyThread t1 = new MyThread();
MyThread t2 = new MyThread();
MyThread t3 = new MyThread();

t1.setPriority(Thread.MIN_PRIORITY); // Setting minimum


priority
t2.setPriority(Thread.NORM_PRIORITY); // Default priority
t3.setPriority(Thread.MAX_PRIORITY); // Setting maximum
priority

t1.start();
t2.start();
t3.start();
}
}
In this program, three threads are created with different priorities. The setPriority()
method is used to assign priorities to each thread. When executed, the thread
scheduler decides the order of thread execution based on their priorities.

29. Develop a simple program to implement KeyEvent class.

In Java, the KeyEvent class is used to handle keyboard events. These events include
key presses, key releases, and key typing. The KeyListener interface provides
methods for detecting key events, such as keyPressed(), keyReleased(), and
keyTyped().

Here’s a simple program that demonstrates how to implement the KeyEvent class:

import java.awt.*;
import java.awt.event.*;

public class KeyEventExample extends Frame implements KeyListener {


TextArea area;

public KeyEventExample() {
area = new TextArea();
area.addKeyListener(this);
add(area);
setSize(400, 400);
setVisible(true);
}

public void keyPressed(KeyEvent e) {


area.append("Key Pressed: " + e.getKeyChar() + "\n");
}

public void keyReleased(KeyEvent e) {


area.append("Key Released: " + e.getKeyChar() + "\n");
}

public void keyTyped(KeyEvent e) {


area.append("Key Typed: " + e.getKeyChar() + "\n");
}

public static void main(String[] args) {


new KeyEventExample();
}
}

In this program, a TextArea is added to the frame, and a KeyListener is implemented


to capture key events. When keys are pressed, released, or typed, the corresponding
method prints the key character to the text area.

30. Write an applet that receives three numeric values as input from
the user and displays the largest.

Java applets are small programs that run in the context of a web browser. To receive
user input, applets can use graphical components like text fields and buttons. The
following applet receives three numbers from the user and displays the largest of the
three.

import java.applet.*;
import java.awt.*;
import java.awt.event.*;

public class LargestNumberApplet extends Applet implements


ActionListener {
TextField num1, num2, num3;
Button button;
Label result;

public void init() {


num1 = new TextField(10);
num2 = new TextField(10);
num3 = new TextField(10);
button = new Button("Find Largest");
result = new Label();

add(new Label("Enter first number:"));


add(num1);
add(new Label("Enter second number:"));
add(num2);
add(new Label("Enter third number:"));
add(num3);
add(button);
add(result);
button.addActionListener(this);
}

public void actionPerformed(ActionEvent e) {


int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
int n3 = Integer.parseInt(num3.getText());
int largest = Math.max(Math.max(n1, n2), n3);

result.setText("Largest number: " + largest);


}
}

In this applet, the user enters three numbers in the text fields, and when the "Find
Largest" button is clicked, the applet calculates and displays the largest number. The
Math.max() method is used to find the largest of the three numbers.

Here are the next 10 answers for the questions, including explanations and examples.

31. What are JDBC statements?

JDBC (Java Database Connectivity) statements are used to interact with databases
from Java applications. The java.sql.Statement interface is used to execute SQL
queries against a database, retrieve data, and update records. There are three types of
JDBC statements:

1. Statement: Used for executing simple SQL queries without parameters.


2. PreparedStatement: Used to execute precompiled SQL statements with or
without parameters, providing better performance and preventing SQL injection.
3. CallableStatement: Used to call stored procedures in the database.

Example using Statement:

import java.sql.*;

public class JDBCStatementExample {


public static void main(String[] args) {
try {
// Establish a connection to the database
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"username", "password");

// Create a Statement object


Statement stmt = conn.createStatement();

// Execute a query
String sql = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(sql);

// Process the result set


while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ",
Name: " + rs.getString("name"));
}

// Close the connection


conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

In this example, a simple SELECT query is executed using a Statement. The


executeQuery() method is used to fetch the data from the database.

32. Explain different types of literals with example.

In Java, literals are fixed values that are directly assigned to variables or used in
expressions. There are several types of literals:

1. Integer Literals: Represent whole numbers and can be written in decimal, octal,
hexadecimal, or binary formats.
Example: int decimal = 100;, int hex = 0x1A;
2. Floating-Point Literals: Represent decimal values with fractional parts and are
written as float or double.
Example: double pi = 3.14;, float price = 5.99f;
3. Character Literals: Represent a single character enclosed in single quotes.
Example: char letter = 'A';
4. String Literals: Represent sequences of characters enclosed in double quotes.
Example: String greeting = "Hello, World!";
5. Boolean Literals: Represent true or false values.
Example: boolean isJavaFun = true;
6. Null Literal: Represents a null reference, which points to no object.
Example: String str = null;

Example code with different literals:

public class LiteralsExample {


public static void main(String[] args) {
int decimal = 100; // integer literal
double price = 99.99; // floating-point literal
char letter = 'A'; // character literal
String message = "Welcome to Java!"; // string literal
boolean isTrue = true; // boolean literal

System.out.println("Decimal: " + decimal);


System.out.println("Price: " + price);
System.out.println("Letter: " + letter);
System.out.println("Message: " + message);
System.out.println("Boolean value: " + isTrue);
}
}

This example demonstrates how various types of literals are used in Java.

33. Explain looping statements with example.

Looping statements in Java are used to repeat a block of code multiple times. There are
three primary types of loops:

1. for loop: Executes a block of code a specific number of times. It is commonly


used when the number of iterations is known beforehand.

Syntax:

for (initialization; condition; increment/decrement) {


// code block
}

Example:

public class ForLoopExample {


public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
System.out.println("Iteration " + i);
}
}
}

2. while loop: Repeats a block of code as long as a condition is true. It is useful


when the number of iterations is not known in advance.

Syntax:

while (condition) {
// code block
}

Example:

public class WhileLoopExample {


public static void main(String[] args) {
int i = 1;
while (i <= 5) {
System.out.println("Iteration " + i);
i++;
}
}
}

3. do-while loop: Similar to the while loop, but it guarantees that the code block
is executed at least once, as the condition is checked after the loop execution.

Syntax:

do {
// code block
} while (condition);

Example:

public class DoWhileLoopExample {


public static void main(String[] args) {
int i = 1;
do {
System.out.println("Iteration " + i);
i++;
} while (i <= 5);
}
}

Each loop has its unique use case, but all serve the purpose of executing repetitive
tasks.

34. Write a note on constructors.

In Java, a constructor is a special type of method that is called when an object is


created. Constructors initialize the state of the object by assigning values to the
instance variables. A constructor has the same name as the class and does not have a
return type.

There are two types of constructors:

1. Default Constructor: A constructor that is provided by Java if no constructors


are explicitly defined. It initializes all instance variables with default values (e.g.,
0 for integers, null for objects).

Example:

public class Car {


int speed;

// Default constructor
public Car() {
speed = 0;
}
}

2. Parameterized Constructor: A constructor that accepts parameters to initialize


the object with specific values.

Example:

public class Car {


int speed;

// Parameterized constructor
public Car(int speed) {
this.speed = speed;
}

public static void main(String[] args) {


Car myCar = new Car(100);
System.out.println("Car speed: " + myCar.speed);
}
}

In this example, the parameterized constructor initializes the speed of the car.

35. Discuss final methods in detail with an example.

In Java, the final keyword is used to define methods that cannot be overridden by
subclasses. Declaring a method as final prevents subclassing from changing its
implementation. This is useful when you want to ensure that the behavior of a method
remains unchanged, regardless of how the class is extended.

Example:

class Parent {
public final void display() {
System.out.println("This is a final method in the parent
class.");
}
}

class Child extends Parent {


// Attempting to override the final method would result in a
compile-time error.
// public void display() { } // Error: Cannot override the
final method from Parent
}

public class FinalMethodExample {


public static void main(String[] args) {
Parent parent = new Parent();
parent.display(); // Output: This is a final method in the
parent class.
}
}

In this example, the display() method is marked as final in the Parent class, so the
Child class cannot override it. The method in the Parent class is always used.

36. What is an array and explain types of arrays with examples?

An array in Java is a data structure that stores a fixed-size sequence of elements of the
same type. Arrays allow you to store multiple values in a single variable, making it
easier to manage data collections. There are two types of arrays in Java: one-
dimensional arrays and multi-dimensional arrays.

1. One-dimensional Array: A simple array where elements are stored in a linear


sequence.

Example:

public class OneDimensionalArray {


public static void main(String[] args) {
int[] numbers = {10, 20, 30, 40, 50};
for (int i = 0; i < numbers.length; i++) {
System.out.println(numbers[i]);
}
}
}
2. Multi-dimensional Array: An array that contains other arrays. The most
common type is a two-dimensional array, which is like a matrix.

Example (2D Array):

public class TwoDimensionalArray {


public static void main(String[] args) {
int[][] matrix = {
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}
};

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


for (int j = 0; j < matrix[i].length; j++) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
}
}

In a 2D array, data is stored in rows and columns, making it suitable for representing
tables or grids.

37. Explain throw, throws & finally with an example.

In Java, exception handling is a mechanism to handle runtime errors, allowing the


program to continue execution. Three important keywords related to exception
handling are throw, throws, and finally.

1. throw: Used to explicitly throw an exception. It is followed by an instance of the


Throwable class (e.g., Exception or Error).

Example:

public class ThrowExample {


public static void main(String[] args) {
throw new ArithmeticException("Division by zero is not
allowed");
}
}

2. throws: Used in method signatures to declare that a method may throw one or
more exceptions. It helps the caller of the method handle the exception.

Example:

public class ThrowsExample {


public static void main(String[] args) throws
ArithmeticException {
divideByZero();
}

public static void divideByZero() throws ArithmeticException {


int result = 10 / 0; // This will throw ArithmeticException
}
}

3. finally: A block that is always executed after the try-catch block, regardless of
whether an exception was thrown or not. It is often used to release resources.

Example:

public class FinallyExample {


public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception: " + e);
} finally {
System.out.println("Finally block is always executed.");
}
}
}

In this example, the finally block is always executed even if an exception occurs.
38. Explain how threads are created using Runnable interface.

In Java, threads can be created by either extending the Thread class or implementing
the Runnable interface. Implementing the Runnable interface is preferred when the
class is already extending another class (since Java supports only single inheritance).
The Runnable interface defines a single method: run().

Steps to create a thread using the Runnable interface:

1. Implement the Runnable interface.


2. Create a Thread object, passing the Runnable object as a parameter.
3. Start the thread using the start() method.

Example:

class MyRunnable implements Runnable {


public void run() {
System.out.println("Thread is running...");
}
}

public class RunnableExample {


public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread(myRunnable);
thread.start();
}
}

In this example, the MyRunnable class implements Runnable, and the run() method
is executed when the thread starts.

39. Define an Event. List some of the Event Classes defined in Java
AWT.

An event in Java represents an action or occurrence in the system that the program can
respond to. Examples include mouse clicks, key presses, or window resizing. The Java
AWT (Abstract Window Toolkit) provides an event-handling mechanism, where an event
listener listens for events and performs the necessary action.
Some of the common event classes in AWT include:

1. ActionEvent: Occurs when a button or menu item is clicked.


2. MouseEvent: Occurs when a mouse action (e.g., click, movement) takes place.
3. KeyEvent: Occurs when a key is pressed, released, or typed.
4. WindowEvent: Occurs when a window is opened, closed, or resized.

Example (ActionEvent handling):

import java.awt.*;
import java.awt.event.*;

public class ActionEventExample extends Frame implements


ActionListener {
Button button;

public ActionEventExample() {
button = new Button("Click Me");
button.addActionListener(this);
add(button);
setSize(200, 200);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


System.out.println("Button clicked!");
}

public static void main(String[] args) {


new ActionEventExample();
}
}
In this example, the program listens for an ActionEvent (button click) and prints a
message when the button is clicked.

40. How to pass parameters to an applet? Explain with Example.

In Java applets, parameters can be passed to an applet through the <param> tag inside
the <applet> tag in the HTML file. These parameters are typically used to customize
the applet's behavior at runtime. The getParameter() method of the Applet class is
used to retrieve these parameters within the applet code.

Steps to pass parameters:


1. Define the parameters in the HTML file using the <param> tag.
2. Retrieve the parameters in the applet using the getParameter() method.

HTML code:

<html>
<head>
<title>Applet Parameter Example</title>
</head>
<body>
<applet code="ParameterApplet.class" width="300" height="200">
<param name="message" value="Hello from the Applet!">
<param name="color" value="blue">
</applet>
</body>
</html>

Applet code:

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class ParameterApplet extends Applet {


public void paint(Graphics g) {
String message = getParameter("message"); // Get parameter
"message"
String color = getParameter("color"); // Get parameter
"color"

if (color != null && color.equals("blue")) {


g.setColor(Color.BLUE); // Set text color to blue
} else {
g.setColor(Color.BLACK); // Default color
}

g.drawString(message, 50, 50); // Display the message


}
}
In this example, two parameters, message and color, are passed to the applet. The
applet displays the message in the specified color.

41. Briefly explain JDBC Architecture.

JDBC (Java Database Connectivity) is an API that enables Java applications to interact
with databases. It allows Java programs to execute SQL queries, update data, and
manage database connections. The JDBC architecture consists of the following
components:

1. JDBC API: A set of Java interfaces that provide methods to interact with the
database. It includes classes like Connection, Statement, ResultSet, and
DriverManager.
2. JDBC Drivers: These are platform-specific implementations that allow Java
applications to communicate with a particular database. There are four types of
JDBC drivers:
a. Type 1 (JDBC-ODBC Bridge Driver): Uses ODBC to connect to the
database.
b. Type 2 (Native-API Driver): Uses native database client libraries.
c. Type 3 (Network Protocol Driver): Uses a middleware server to
communicate with the database.
d. Type 4 (Thin Driver): Directly communicates with the database using a
proprietary protocol.
3. Database: The actual database system (e.g., MySQL, Oracle, SQL Server) where
data is stored.

The basic flow of the JDBC architecture is:

• Driver Manager selects the appropriate driver for connecting to the database.
• Connection is established, and SQL queries are executed via Statement
objects.
• ResultSet stores and retrieves query results.

Example of connecting to a database using JDBC:

import java.sql.*;

public class JDBCExample {


public static void main(String[] args) {
try {
// Establishing a connection
Connection conn =
DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb",
"username", "password");

// Creating a Statement object


Statement stmt = conn.createStatement();

// Executing a query
String query = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(query);

// Processing the result


while (rs.next()) {
System.out.println("ID: " + rs.getInt("id") + ",
Name: " + rs.getString("name"));
}

// Closing the connection


conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}

This code demonstrates the basic JDBC steps of establishing a connection, executing a
query, processing results, and closing the connection.

42. Write a Java program to print prime numbers between two limits.

A prime number is a number greater than 1 that has no divisors other than 1 and itself.
Here's a Java program that prints all prime numbers between two specified limits:

public class PrimeNumber {


public static void main(String[] args) {
int lower = 10, upper = 50;

for (int num = lower; num <= upper; num++) {


boolean isPrime = true;
// Check for factors other than 1 and the number itself
for (int i = 2; i <= num / 2; i++) {
if (num % i == 0) {
isPrime = false;
break;
}
}

if (isPrime && num > 1) {


System.out.println(num);
}
}
}
}

In this program, the for loop checks all numbers between lower and upper for
primality by checking if they have divisors other than 1 and themselves.

43. How will you implement multilevel inheritance in Java?

In Java, multilevel inheritance occurs when a class is derived from another class, which
is also derived from another class. This forms a chain of inheritance.

Example:

class Animal {
void eat() {
System.out.println("Eating...");
}
}

class Mammal extends Animal {


void walk() {
System.out.println("Walking...");
}
}

class Dog extends Mammal {


void bark() {
System.out.println("Barking...");
}
}

public class MultilevelInheritance {


public static void main(String[] args) {
Dog dog = new Dog();
dog.eat(); // Inherited from Animal
dog.walk(); // Inherited from Mammal
dog.bark(); // Defined in Dog
}
}

In this example, the Dog class inherits from Mammal, and Mammal inherits from Animal,
thus forming a chain of inheritance. A Dog object can access methods from both
Mammal and Animal.

44. Write a note on dynamic method dispatch.

Dynamic method dispatch, also known as runtime polymorphism, is the process by


which Java determines which method to call at runtime. It is used to implement method
overriding in Java, where a subclass provides its own implementation of a method that
is already defined in its superclass.

Java uses dynamic method dispatch to call the overridden method of a subclass at
runtime, based on the object type (not the reference type) used to call the method. This
allows for flexibility in method calls and is a key feature of object-oriented
programming.

Example:

class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}

class Dog extends Animal {


@Override
void sound() {
System.out.println("Dog barks");
}
}

class Cat extends Animal {


@Override
void sound() {
System.out.println("Cat meows");
}
}

public class DynamicDispatch {


public static void main(String[] args) {
Animal myAnimal = new Animal();
Animal myDog = new Dog();
Animal myCat = new Cat();

myAnimal.sound(); // Output: Animal makes a sound


myDog.sound(); // Output: Dog barks
myCat.sound(); // Output: Cat meows
}
}

In this example, the method sound() is overridden in the Dog and Cat classes. At
runtime, Java determines the appropriate method to call based on the actual object
type (Dog or Cat), not the reference type (Animal).

45. Difference between String and StringBuffer?

In Java, both String and StringBuffer are used to represent text, but they differ in
terms of mutability and performance.

1. String: A String is immutable, meaning once it is created, its value cannot be


changed. Every modification to a String creates a new object.

Example:

String str1 = "Hello";


str1 = str1 + " World"; // Creates a new String object
System.out.println(str1); // Output: Hello World
2. StringBuffer: A StringBuffer is mutable, meaning its content can be changed
without creating new objects. It is more efficient than String when it comes to
string manipulation in loops or when many modifications are needed.

Example:

StringBuffer sb = new StringBuffer("Hello");


sb.append(" World"); // Modifies the same StringBuffer object
System.out.println(sb); // Output: Hello World

StringBuffer is preferred when you need to modify a string repeatedly, as it is more


efficient in such cases.

46. Explain different types of built-in exceptions.

Java provides several built-in exceptions that represent common error conditions.
Some of the most frequently encountered built-in exceptions are:

1. ArithmeticException: Thrown when an illegal arithmetic operation, such as


division by zero, occurs. Example:

int result = 10 / 0; // Throws ArithmeticException

2. NullPointerException: Thrown when the program attempts to use a null


reference where an object is required. Example:

String str = null;


System.out.println(str.length()); // Throws NullPointerException

3. ArrayIndexOutOfBoundsException: Thrown when trying to access an array


element with an invalid index. Example:

int[] arr = new int[5];


System.out.println(arr[10]); // Throws
ArrayIndexOutOfBoundsException

4. FileNotFoundException: Thrown when an attempt to open a file fails because


the file does not exist. Example:
File file = new File("nonexistent.txt");
FileReader fr = new FileReader(file); // Throws
FileNotFoundException

5. IOException: Thrown when an I/O operation fails, such as reading or writing to a


file. Example:

FileReader fr = new FileReader("file.txt");


int data = fr.read(); // Throws IOException if file is not
accessible

These exceptions are part of Java’s exception hierarchy and are used to handle specific
errors that may occur during program execution.

47. Define Swing and its architecture.

Swing is a part of Java's Java Foundation Classes (JFC) used for creating graphical user
interfaces (GUIs). Swing provides a rich set of GUI components, such as buttons,
labels, text fields, tables, and menus, that can be used to build interactive desktop
applications.

Swing Architecture:

• Lightweight Components: Swing components do not rely on native operating


system controls, making them platform-independent.
• MVC Design: Swing follows the Model-View-Controller (MVC) design pattern.
The model contains data, the view represents the data to the user, and the
controller handles user input and updates the model.
• Event Handling: Swing uses event-driven programming, where components
listen for events like mouse clicks or keyboard presses and respond accordingly.

Swing components are built on top of the Abstract Window Toolkit (AWT) components
but are more flexible and powerful. Some commonly used Swing components include
JButton, JLabel, JTextField, JTable, and JComboBox.

Example of a simple Swing program:

import javax.swing.*;

public class SwingExample {


public static void main(String[] args) {
JFrame frame = new JFrame("Swing Example");
JButton button = new JButton("Click Me");
frame.add(button);
frame.setSize(300, 200);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}

In this example, a basic Swing application creates a window with a button.

48. Write an applet that receives two integer values as input and
displays the sum.

An applet is a Java program that runs inside a web browser or an applet viewer. To
create an applet that receives two integers as input and displays the sum, we will use
the TextField to receive input and a Button to trigger the calculation.

HTML code:

<html>
<head>
<title>Sum Applet</title>
</head>
<body>
<applet code="SumApplet.class" width="300" height="200">
</applet>
</body>
</html>

Applet code:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

public class SumApplet extends Applet {


TextField num1, num2;
Button sumButton;
Label result;

public void init() {


num1 = new TextField(10);
num2 = new TextField(10);
sumButton = new Button("Sum");
result = new Label("Result:");

add(num1);
add(num2);
add(sumButton);
add(result);

sumButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
int n1 = Integer.parseInt(num1.getText());
int n2 = Integer.parseInt(num2.getText());
int sum = n1 + n2;
result.setText("Result: " + sum);
}
});
}
}

In this applet, two text fields (num1 and num2) are used to get user input. When the user
clicks the button (sumButton), the ActionListener triggers the sum calculation, and
the result is displayed on a label.

49. Describe various ways of drawing polygons.

In Java, polygons can be drawn using the Graphics class. The Graphics class provides
the drawPolygon() method, which allows you to draw any polygon by specifying an
array of x and y coordinates for its vertices.

Basic method to draw a polygon:

1. Use the drawPolygon() method of the Graphics class.


2. Pass arrays of x and y coordinates to define the polygon's vertices.
Example to draw a triangle:

import java.awt.*;
import javax.swing.*;

public class PolygonExample extends JPanel {


public void paintComponent(Graphics g) {
super.paintComponent(g);
int[] xPoints = {50, 100, 150};
int[] yPoints = {150, 50, 150};
int nPoints = 3;

g.setColor(Color.BLUE);
g.drawPolygon(xPoints, yPoints, nPoints); // Draws a
triangle
}

public static void main(String[] args) {


JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300, 300);
frame.add(new PolygonExample());
frame.setVisible(true);
}
}

In this example, the drawPolygon() method is used to draw a triangle by providing the
x and y coordinates of the vertices.

50. Explain the data types used in Java.

Java has a rich set of data types to define variables, which are categorized into primitive
data types and reference data types.

1. Primitive Data Types:


a. byte: 1 byte, used for integers in the range of -128 to 127.
b. short: 2 bytes, used for integers in the range of -32,768 to 32,767.
c. int: 4 bytes, used for integers in the range of -2^31 to 2^31-1.
d. long: 8 bytes, used for larger integers.
e. float: 4 bytes, used for floating-point numbers with single precision.
f. double: 8 bytes, used for floating-point numbers with double precision.
g. char: 2 bytes, used to store a single character.
h. boolean: 1 bit, used to represent true or false.
2. Reference Data Types: These are used to store references (addresses) to
objects and arrays. Examples include String, Arrays, and user-defined
classes.

Example:

public class DataTypesExample {


public static void main(String[] args) {
int a = 10; // Integer
float b = 10.5f; // Float
double c = 20.99; // Double
char d = 'A'; // Character
boolean isTrue = true; // Boolean

System.out.println("Integer: " + a);


System.out.println("Float: " + b);
System.out.println("Double: " + c);
System.out.println("Char: " + d);
System.out.println("Boolean: " + isTrue);
}
}

In this example, various primitive data types are used, demonstrating how they are
defined and printed.

51. Explain the character set of Java Program.

In Java, a character set refers to the collection of characters that the language
recognizes. Java uses Unicode, a standard character encoding system, to represent
characters. Unicode supports a wide range of characters, including characters from
various languages, symbols, and even emojis.

Java's default character set is UTF-16, which is capable of representing characters as


16-bit units, and it can handle characters beyond the basic multilingual plane (BMP)
through surrogate pairs.

Example of Unicode usage in Java:


public class UnicodeExample {
public static void main(String[] args) {
char letter = 'A'; // A simple character
char chineseChar = '\u4E2D'; // Unicode for Chinese
character '中'

System.out.println("Letter: " + letter);


System.out.println("Chinese Character: " + chineseChar);
}
}

In this example, the character 'A' is stored normally, while the Chinese character '中'
is represented using its Unicode value \u4E2D.

52. Write a Java program to find the smallest among 3 numbers.

To find the smallest of three numbers in Java, we can use conditional statements like
if or Math.min() method.

Example using if statements:

public class SmallestNumber {


public static void main(String[] args) {
int num1 = 15, num2 = 10, num3 = 25;

int smallest = num1;

if (num2 < smallest) {


smallest = num2;
}

if (num3 < smallest) {


smallest = num3;
}

System.out.println("The smallest number is: " + smallest);


}
}
In this program, we initialize smallest with the first number and then use if conditions
to compare and assign the smallest value from the three numbers.

53. Explain method overloading with example.

Method overloading in Java is the ability to define multiple methods with the same
name but different parameter lists (i.e., different number or types of parameters). It
allows you to perform similar operations with different inputs.

Example of method overloading:

public class MethodOverloadingExample {


// Method to add two integers
public int add(int a, int b) {
return a + b;
}

// Overloaded method to add three integers


public int add(int a, int b, int c) {
return a + b + c;
}

public static void main(String[] args) {


MethodOverloadingExample obj = new
MethodOverloadingExample();
System.out.println("Sum of two integers: " + obj.add(5,
10));
System.out.println("Sum of three integers: " + obj.add(5,
10, 15));
}
}

In this example, the add method is overloaded to handle both two and three integer
inputs. The correct method is called based on the number of arguments passed when
invoking the method.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy