5 MARK JAVA
5 MARK JAVA
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.
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.
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.
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:
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.
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.
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.
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.
// 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);
}
}
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:
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:
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:
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.
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:
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:
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).
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.
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
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.
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.
// StringBuffer example
StringBuffer strBuffer = new StringBuffer("Hello");
strBuffer.append(" World"); // Modifies the existing
StringBuffer object
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.
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.
import java.io.*;
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.
import javax.swing.*;
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.*;
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.
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.
import java.applet.*;
import java.awt.*;
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.
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:
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.
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.
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.
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.
import java.util.Scanner;
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:
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.
class Animal {
void eat() {
System.out.println("Animal is eating");
}
}
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.
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.
// File: com/example/Utility.java
package com.example;
// File: Main.java
import com.example.Utility;
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).
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.
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 KeyEventExample() {
area = new TextArea();
area.addKeyListener(this);
add(area);
setSize(400, 400);
setVisible(true);
}
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.*;
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.
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:
import java.sql.*;
// Execute a query
String sql = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(sql);
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;
This example demonstrates how various types of literals are used in Java.
Looping statements in Java are used to repeat a block of code multiple times. There are
three primary types of loops:
Syntax:
Example:
Syntax:
while (condition) {
// code block
}
Example:
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:
Each loop has its unique use case, but all serve the purpose of executing repetitive
tasks.
Example:
// Default constructor
public Car() {
speed = 0;
}
}
Example:
// Parameterized constructor
public Car(int speed) {
this.speed = speed;
}
In this example, the parameterized constructor initializes the speed of the car.
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.");
}
}
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.
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.
Example:
In a 2D array, data is stored in rows and columns, making it suitable for representing
tables or grids.
Example:
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:
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:
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().
Example:
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:
import java.awt.*;
import java.awt.event.*;
public ActionEventExample() {
button = new Button("Click Me");
button.addActionListener(this);
add(button);
setSize(200, 200);
setVisible(true);
}
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.
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;
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.
• 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.
import java.sql.*;
// Executing a query
String query = "SELECT * FROM students";
ResultSet rs = stmt.executeQuery(query);
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:
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.
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...");
}
}
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.
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");
}
}
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).
In Java, both String and StringBuffer are used to represent text, but they differ in
terms of mutability and performance.
Example:
Example:
Java provides several built-in exceptions that represent common error conditions.
Some of the most frequently encountered built-in exceptions are:
These exceptions are part of Java’s exception hierarchy and are used to handle specific
errors that may occur during program execution.
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:
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.
import javax.swing.*;
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.*;
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.
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.
import java.awt.*;
import javax.swing.*;
g.setColor(Color.BLUE);
g.drawPolygon(xPoints, yPoints, nPoints); // Draws a
triangle
}
In this example, the drawPolygon() method is used to draw a triangle by providing the
x and y coordinates of the vertices.
Java has a rich set of data types to define variables, which are categorized into primitive
data types and reference data types.
Example:
In this example, various primitive data types are used, demonstrating how they are
defined and printed.
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.
In this example, the character 'A' is stored normally, while the Chinese character '中'
is represented using its Unicode value \u4E2D.
To find the smallest of three numbers in Java, we can use conditional statements like
if or Math.min() method.
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.
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.