INDEX
(Write index with Date)
1. Overview of Java.
2. Write a program to print “Hello world”.
3. To find the sum of any number of integers entered as command line arguments.
4. To find the factorial of a given number.
5. To convert a decimal to binary number.
6. To check if a number is prime or not, by taking the number as input from the keyboard.
7. To find the sum of any number of integers interactively, i.e., entering every number from the keyboard,
whereas the total number of integers is given as a command line argument
8. Write a program that show working of different functions of String and String Buffer classs like set
Char At( ), set Length( ), append( ), insert( ), concat( )and equals( ).
9. Write a program to create a – “distance” class with methods where distance is computed in terms of
feet and inches, how to create objects of a class and to see the use of this pointer.
10. Modify the – “distance” class by creating constructor for assigning values (feet and inches) to the
distance object. Create another object and assign second object as reference variable to another
object reference variable. Further create a third object which is a clone of the first object.
11. Write a program to show that during function overloading, if no matching argument is found, then Java
will apply automatic type conversions (from lower to higher data type).
12. Write a program to show the difference between public and private access specifiers. The program
should also show that primitive data types are passed by value and objects are passed by reference
and to learn use of final keyword.
13. Write a program to show the use of static functions and to pass variable length arguments in a
function.
14. Write a program to demonstrate the concept of boxing and unboxing.
15. Create a multi-file program where in one file a string message is taken as input from the user and the
function to display the message on the screen is given in another file (make use of Scanner package
in this program).
16. Write a program to create a multilevel package and also creates a reusable class to generate
Fibonacci series, where the function to generate Fibonacci series is given in a different file belonging
to the same package.
17. Write a program that creates illustrates different levels of protection in classes/subclasses belonging
to same package or different packages
18. Write a program – “Divide By Zero” that takes two numbers a and b as input, computes a/b, and
invokes Arithmetic Exception to generate a message when the denominator is zero.
19. Write a program to show the use of nested try statements that emphasizes the sequence of checking
for catch handler statements.
20. Write a program to create your own exception types to handle situation specific to your application
(Hint: Define a subclass of Exception which itself is a subclass of Throwable).
21. Write a program to demonstrate priorities among multiple threads.
22. Write a program to demonstrate different mouse handling events like mouse Clicked( ), mouse
Entered ( ), mouse Exited ( ), mouse Pressed( ), mouse Released( ) & mouse Dragged( ).
23. Write a program to demonstrate different keyboard handling events.
Answers
(Write Questions before each answer)
1. Java is a class-based, object-oriented programming language that is designed to have as few
implementation dependencies as possible. It is intended to let application developers write once,
and run anywhere (WORA), meaning that compiled Java code can run on all platforms that
support Java without the need for recompilation. Java was first released in 1995 and is widely used
for developing applications for desktop, web, and mobile devices. Java is known for its simplicity,
robustness, and security features, making it a popular choice for enterprise-level applications.
Java was developed by James Gosling at Sun Microsystems Inc in May 1995 and later acquired
by Oracle Corporation. It is a simple programming language. Java makes writing, compiling, and
debugging programming easy. It helps to create reusable code and modular programs. Java is a class-
based, object-oriented programming language and is designed to have as few implementation
dependencies as possible. A general-purpose programming language made for developers to write
once run anywhere that is compiled Java code can run on all platforms that support Java. Java
applications are compiled to byte code that can run on any Java Virtual Machine. The syntax of Java is
similar to C/C++.
History of Java
Java’s history is as interesting as it is impactful. The journey of this powerful programming
language began in 1991 when James Gosling, Mike Sheridan, and Patrick Naughton, a team of
engineers at Sun Microsystems known as the “Green Team,” set out to create a new language initially
called “Oak.” Oak was later renamed Java, inspired by Java coffee, and was first publicly released in 1996
as Java 1.0. This initial version provided a no-cost runtime environment across popular platforms, making
it accessible to a broad audience. Arthur Van Hoff rewrote the Java 1.0 compiler to strictly comply with
its specifications, ensuring its reliability and cross-platform capabilities.
Java evolved over time, with Java 2 introducing multiple configurations tailored for different platforms,
showcasing its versatility.
In 1997, Sun Microsystems aimed to formalize Java through the ISO standards body but eventually
withdrew from the process.
Despite not formalizing through ISO, Sun Microsystems offered most Java implementations at no
cost, earning revenue by licensing specialized products such as the Java Enterprise System.
A significant milestone in Java’s history occurred on November 13, 2006, when Sun
Microsystems released a large portion of the Java Virtual Machine (JVM) as free, open-source
software.
By May 8, 2007, the core JVM code was fully available under open-source distribution terms.
Java was designed with core principles: simplicity, robustness, security, high performance,
portability, multi-threading, and dynamic interpretation. These principles have made Java a
preferred language for various applications, including mobile devices, internet programming, gaming,
and e-business.
Today, Java continues to be a cornerstone of modern software development, widely used across
industries and platforms.
Key Features of Java
1. Platform Independent
Compiler converts source code to byte code and then the JVM executes the bytecode generated by the
compiler. This byte code can run on any platform be it Windows, Linux, or macOS which means if we
compile a program on Windows, then we can run it on Linux and vice versa. Each operating system has
a different JVM, but the output produced by all the OS is the same after the execution of the byte code.
That is why we call java a platform-independent language.
2. Object-Oriented Programming
Java is an object-oriented language, promoting the use of objects and classes. Organizing the program
in the terms of a collection of objects is a way of object-oriented programming, each of which represents
an instance of the class.
The four main concepts of Object-Oriented programming are:
Abstraction
Encapsulation
Inheritance
Polymorphism
3. Simplicity
Java’s syntax is simple and easy to learn, especially for those familiar with C or C++. It eliminates complex
features like pointers and multiple inheritances, making it easier to write, debug, and maintain code.
4. Robustness
Java language is robust which means reliable. It is developed in such a way that it puts a lot of effort
into checking errors as early as possible, that is why the java compiler is able to detect even those errors
that are not easy to detect by another programming language. The main features of java that make it robust
are garbage collection, exception handling, and memory allocation.
5. Security
In java, we don’t have pointers, so we cannot access out-of-bound arrays i.e it
shows ArrayIndexOutOfBound Exception if we try to do so. That’s why several security flaws like stack
corruption or buffer overflow are impossible to exploit in Java. Also, java programs run in an environment
that is independent of the os(operating system) environment which makes java programs more secure.
6. Distributed
We can create distributed applications using the java programming language. Remote Method
Invocation and Enterprise Java Beans are used for creating distributed applications in java. The java
programs can be easily distributed on one or more systems that are connected to each other through an
internet connection.
7. Multithreading
Java supports multithreading, enabling the concurrent execution of multiple parts of a program. This
feature is particularly useful for applications that require high performance, such as games and real-time
simulations.
8. Portability
As we know, java code written on one machine can be run on another machine. The platform-independent
feature of java in which its platform-independent bytecode can be taken to any platform for execution makes
java portable. WORA(Write Once Run Anywhere) makes java application to generates a ‘.class’ file that
corresponds to our applications(program) but contains code in binary format. It provides ease t architecture-
neutral ease as bytecode is not dependent on any machine architecture. It is the primary reason java is
used in the enterprising IT industry globally worldwide.
9. High Performance
Java architecture is defined in such a way that it reduces overhead during the runtime and at some times
java uses Just In Time (JIT) compiler where the compiler compiles code on-demand basis where it only
compiles those methods that are called making applications to execute faster.
2.
public class HelloWorld {
public static void main(String[] args)
{
[Link]("Hello, World!");
}
}
Output: Hello, World!
3.
public class SumOfIntegers {
public static void main(String[] args) {
// Check if arguments are provided
if ([Link] == 0) {
[Link]("Please provide integers as command line arguments.");
return;
}
int sum = 0; // Variable to store the sum
// Iterate over each argument
for (String arg : args) {
try {
// Parse the argument to an integer and add to sum
int number = [Link](arg);
sum += number;
} catch (NumberFormatException e) {
// Handle invalid input
[Link]("'" + arg + "' is not a valid integer. Ignoring it.");
}
}
// Print the result
[Link]("The sum of the integers is: " + sum);
}
}
Output:
java SumOfIntegers 10 20 30
The sum of the integers is: 60
4.
import [Link];
public class Factorial {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a number
[Link]("Enter a number to find its factorial: ");
int number = [Link]();
// Check for negative input
if (number < 0) {
[Link]("Factorial is not defined for negative numbers.");
} else {
long factorial = 1;
// Calculate factorial
for (int i = 1; i <= number; i++) {
factorial *= i;
}
// Print the result
[Link]("The factorial of " + number + " is: " + factorial);
}
[Link]();
}
}
Output:
Enter a number to find its factorial: 5
The factorial of 5 is: 120
5.
import [Link];
public class DecimalToBinary {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a decimal number
[Link]("Enter a decimal number: ");
int decimal = [Link]();
// Convert decimal to binary
String binary = [Link](decimal);
// Display the binary equivalent
[Link]("The binary representation of " + decimal + " is: " + binary);
[Link]();
}
}
Output:
Enter a decimal number: 10
The binary representation of 10 is: 1010
6.
import [Link];
public class PrimeNumberCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a number
[Link]("Enter a number to check if it is prime: ");
int number = [Link]();
// Check if the number is prime
if (isPrime(number)) {
[Link](number + " is a prime number.");
} else {
[Link](number + " is not a prime number.");
}
[Link]();
}
// Method to check if a number is prime
public static boolean isPrime(int num) {
// Prime numbers are greater than 1
if (num <= 1) {
return false;
}
// Check divisors from 2 to √num
for (int i = 2; i <= [Link](num); i++) {
if (num % i == 0) {
return false; // Found a divisor, so not prime
}
}
return true; // No divisors found, so prime
}
}
Output:
Enter a number to check if it is prime: 7
7 is a prime number.
Enter a number to check if it is prime: 10
10 is not a prime number.
7.
import [Link];
public class InteractiveSum {
public static void main(String[] args) {
// Check if the total number of integers is provided as a command-line argument
if ([Link] != 1) {
[Link]("Usage: java InteractiveSum <total_numbers>");
return;
}
int totalNumbers;
try {
// Parse the command-line argument to get the total number of integers
totalNumbers = [Link](args[0]);
} catch (NumberFormatException e) {
[Link]("Please provide a valid integer as the total number of integers.");
return;
}
// Ensure the number of integers is positive
if (totalNumbers <= 0) {
[Link]("The total number of integers must be greater than 0.");
return;
}
Scanner scanner = new Scanner([Link]);
int sum = 0;
// Prompt the user to enter each integer
[Link]("Please enter " + totalNumbers + " integers:");
for (int i = 1; i <= totalNumbers; i++) {
[Link]("Enter integer " + i + ": ");
try {
int number = [Link]();
sum += number; // Add the number to the sum
} catch (Exception e) {
[Link]("Invalid input. Please enter a valid integer.");
[Link](); // Clear invalid input
i--; // Repeat the current iteration
}
}
// Display the result
[Link]("The sum of the entered integers is: " + sum);
[Link]();
}
}
Output:
Please enter 3 integers:
Enter integer 1: 10
Enter integer 2: 20
Enter integer 3: 30
The sum of the entered integers is: 60
8.
public class StringAndStringBufferDemo {
public static void main(String[] args) {
// Demonstrating String methods
[Link]("** String Methods **");
// Example with String
String str1 = "Hello";
String str2 = "World";
// concat()
String concatenated = [Link](" ").concat(str2);
[Link]("Concatenated String: " + concatenated);
// equals()
boolean isEqual = [Link](str2);
[Link]("Are \"" + str1 + "\" and \"" + str2 + "\" equal? " + isEqual);
[Link]("\n** StringBuffer Methods **");
// Demonstrating StringBuffer methods
StringBuffer sb = new StringBuffer("Programming");
// append()
[Link](" in Java");
[Link]("After append: " + sb);
// insert()
[Link](0, "Learn ");
[Link]("After insert: " + sb);
// setCharAt()
[Link](6, 'P'); // Changing 'L' to 'P'
[Link]("After setCharAt: " + sb);
// setLength()
[Link](10); // Truncate to 10 characters
[Link]("After setLength: " + sb);
}
}
Output:
** String Methods **
Concatenated String: Hello World
Are "Hello" and "World" equal? false
** StringBuffer Methods **
After append: Programming in Java
After insert: Learn Programming in Java
After setCharAt: Pean Programming in Java
After setLength: Learn Prog
9.
class Distance {
private int feet;
private int inches;
// Constructor to initialize distance
public Distance(int feet, int inches) {
[Link] = feet;
[Link] = inches;
normalize(); // Ensure inches is less than 12
}
// Method to add another distance to the current distance
public void add(Distance other) {
[Link] += [Link];
[Link] += [Link];
normalize();
}
// Normalize inches to keep it less than 12
private void normalize() {
if ([Link] >= 12) {
[Link] += [Link] / 12;
[Link] = [Link] % 12;
}
}
// Method to display the distance
public void display() {
[Link]("Distance: " + [Link] + " feet, " + [Link] + " inches");
}
// Method to set the distance using this pointer
public void setDistance(int feet, int inches) {
[Link] = feet;
[Link] = inches;
normalize();
}
}
public class DistanceDemo {
public static void main(String[] args) {
// Create objects of the Distance class
Distance d1 = new Distance(5, 8); // 5 feet, 8 inches
Distance d2 = new Distance(3, 10); // 3 feet, 10 inches
// Display the initial distances
[Link]("Initial Distances:");
[Link]();
[Link]();
// Add the second distance to the first using add method
[Link](d2);
// Display the updated distance of d1
[Link]("\nAfter Adding d2 to d1:");
[Link]();
// Update the distance of d2 using setDistance method
[Link](2, 15);
// Display the updated distance of d2
[Link]("\nAfter Updating d2:");
[Link]();
}
}
Output:
Initial Distances:
Distance: 5 feet, 8 inches
Distance: 3 feet, 10 inches
After Adding d2 to d1:
Distance: 9 feet, 6 inches
After Updating d2:
Distance: 3 feet, 3 inches
10.
class Distance implements Cloneable {
private int feet;
private int inches;
// Constructor to initialize distance
public Distance(int feet, int inches) {
[Link] = feet;
[Link] = inches;
normalize(); // Ensure inches is less than 12
}
// Method to normalize inches to less than 12
private void normalize() {
if ([Link] >= 12) {
[Link] += [Link] / 12;
[Link] = [Link] % 12;
}
}
// Method to display the distance
public void display() {
[Link]("Distance: " + [Link] + " feet, " + [Link] + " inches");
}
// Overriding clone() method to create a clone of the object
@Override
protected Object clone() throws CloneNotSupportedException {
return [Link]();
}
}
public class DistanceDemo {
public static void main(String[] args) {
// Creating the first object using the constructor
Distance d1 = new Distance(5, 8);
[Link]("First Object (d1):");
[Link]();
// Assigning the first object to another reference variable (d2)
Distance d2 = d1;
[Link]("\nSecond Object (d2) assigned as reference of d1:");
[Link]();
// Creating a third object as a clone of the first object (d1)
try {
Distance d3 = (Distance) [Link]();
[Link]("\nThird Object (d3), clone of d1:");
[Link]();
} catch (CloneNotSupportedException e) {
[Link]("Cloning not supported for Distance object.");
}
}
}
Output:
First Object (d1):
Distance: 5 feet, 8 inches
Second Object (d2) assigned as reference of d1:
Distance: 5 feet, 8 inches
Third Object (d3), clone of d1:
Distance: 5 feet, 8 inches
11.
class OverloadingDemo {
// Method with int parameter
void display(int num) {
[Link]("Method with int parameter called: " + num);
}
// Method with double parameter
void display(double num) {
[Link]("Method with double parameter called: " + num);
}
// Method with long parameter
void display(long num) {
[Link]("Method with long parameter called: " + num);
}
}
public class TypeConversionExample {
public static void main(String[] args) {
OverloadingDemo obj = new OverloadingDemo();
// Exact match
[Link](10); // Matches the int parameter
// Automatic type conversion from int to long
[Link](10000000000L); // Matches the long parameter
// Automatic type conversion from float to double
[Link](12.34f); // Matches the double parameter
}
}
Output:
Method with int parameter called: 10
Method with long parameter called: 10000000000
Method with double parameter called: 12.34
12.
class AccessSpecifiers {
public int publicVariable = 10; // Public: Accessible anywhere
private int privateVariable = 20; // Private: Accessible only within this class
// Public method to access private variable
public int getPrivateVariable() {
return privateVariable;
}
// Public method to modify private variable
public void setPrivateVariable(int value) {
[Link] = value;
}
}
class PassByValueAndReference {
void modifyPrimitive(int value) {
value = 50; // Change local copy
}
void modifyObject(MyObject obj) {
[Link] = 50; // Modify the original object's field
}
}
class MyObject {
int data;
MyObject(int data) {
[Link] = data;
}
}
public class AccessSpecifierDemo {
public static void main(String[] args) {
// Demonstrate public and private access specifiers
AccessSpecifiers obj = new AccessSpecifiers();
// Access public variable directly
[Link]("Public Variable: " + [Link]);
// Access private variable using public getter
[Link]("Private Variable (via getter): " + [Link]());
// Modify private variable using public setter
[Link](30);
[Link]("Private Variable after modification (via getter): " + [Link]());
// Demonstrate pass-by-value for primitive data types
PassByValueAndReference demo = new PassByValueAndReference();
int primitive = 10;
[Link]("\nBefore modifying primitive: " + primitive);
[Link](primitive);
[Link]("After modifying primitive: " + primitive); // Unchanged
// Demonstrate pass-by-reference for objects
MyObject myObject = new MyObject(10);
[Link]("\nBefore modifying object: " + [Link]);
[Link](myObject);
[Link]("After modifying object: " + [Link]); // Changed
// Demonstrate use of final keyword
final int finalVariable = 100; // Final variable (constant)
[Link]("\nFinal Variable: " + finalVariable);
// finalVariable = 200; // Uncommenting this line will cause a compilation error
final MyObject finalObject = new MyObject(20); // Final reference
[Link]("Final Object data before modification: " + [Link]);
[Link] = 30; // Allowed: We can modify the object's fields
[Link]("Final Object data after modification: " + [Link]);
// finalObject = new MyObject(40); // Uncommenting this line will cause a compilation error
}
}
Output:
Public Variable: 10
Private Variable (via getter): 20
Private Variable after modification (via getter): 30
Before modifying primitive: 10
After modifying primitive: 10
Before modifying object: 10
After modifying object: 50
Final Variable: 100
Final Object data before modification: 20
Final Object data after modification: 30
13.
class StaticDemo {
// Static method to show use of static functions
public static void displayMessage() {
[Link]("This is a static function.");
}
// Static method to calculate the sum of any number of integers (varargs)
public static int sum(int... numbers) {
int total = 0;
for (int num : numbers) {
total += num;
}
return total;
}
// Static method to show variable-length arguments
public static void printNames(String... names) {
[Link]("List of Names:");
for (String name : names) {
[Link](name);
}
}
}
public class VarargsStaticDemo {
public static void main(String[] args) {
// Calling static method without creating an object
[Link]();
// Calling static method with variable-length arguments (sum)
int result = [Link](10, 20, 30, 40, 50);
[Link]("Sum of numbers: " + result);
// Calling static method with variable-length arguments (names)
[Link]("Alice", "Bob", "Charlie", "David");
}
}
Output:
This is a static function.
Sum of numbers: 150
List of Names:
Alice
Bob
Charlie
David
14.
public class BoxingUnboxingDemo {
public static void main(String[] args) {
// Demonstrating Boxing (Primitive to Wrapper Class)
int primitiveInt = 10;
// Autoboxing: Converting primitive int to Integer object
Integer boxedInt = primitiveInt; // Java automatically converts primitive to wrapper
[Link]("Boxed Integer: " + boxedInt);
double primitiveDouble = 20.5;
// Autoboxing: Converting primitive double to Double object
Double boxedDouble = primitiveDouble; // Java automatically converts primitive to wrapper
[Link]("Boxed Double: " + boxedDouble);
// Demonstrating Unboxing (Wrapper Class to Primitive)
Integer unboxedInt = boxedInt; // Unboxing: Java automatically converts Integer to int
[Link]("Unboxed Integer: " + unboxedInt);
Double unboxedDouble = boxedDouble; // Unboxing: Java automatically converts Double to
double
[Link]("Unboxed Double: " + unboxedDouble);
// Manual Boxing and Unboxing for clarity
Integer manualBoxedInt = [Link](primitiveInt); // Boxing
int manualUnboxedInt = [Link](); // Unboxing
[Link]("Manually Boxed Integer: " + manualBoxedInt);
[Link]("Manually Unboxed Integer: " + manualUnboxedInt);
}
}
Output:
Boxed Integer: 10
Boxed Double: 20.5
Unboxed Integer: 10
Unboxed Double: 20.5
Manually Boxed Integer: 10
Manually Unboxed Integer: 10
15.
This file contains a method to display the message.
// [Link]
public class MessageDisplay {
// Method to display the message
public void displayMessage(String message) {
[Link]("Your message is: " + message);
}
}
This file takes input from the user and calls the method from [Link] to display the
message.
// [Link]
import [Link]; // Import Scanner class
public class MessageInput {
public static void main(String[] args) {
// Create a Scanner object to take input
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter a message
[Link]("Enter a message: ");
String message = [Link](); // Read user input
// Create an object of MessageDisplay class to display the message
MessageDisplay messageDisplay = new MessageDisplay();
// Call the displayMessage method to show the message
[Link](message);
// Close the scanner
[Link]();
}
}
Output:
Enter a message: Hello, this is a multi-file program!
Your message is: Hello, this is a multi-file program!
16.
Create the Fibonacci Generator Class ([Link]):
// File: com/myapp/fibonacci/[Link]
package [Link]; // Package declaration
public class FibonacciGenerator {
// Method to generate Fibonacci series up to 'n' terms
public void generateFibonacci(int n) {
int a = 0, b = 1, nextTerm;
[Link]("Fibonacci Series up to " + n + " terms:");
// Print the Fibonacci series
for (int i = 1; i <= n; i++) {
[Link](a + " ");
nextTerm = a + b;
a = b;
b = nextTerm;
}
[Link](); // Move to the next line after printing the series
}
}
Create the Main Class to Test Fibonacci Generator ([Link]):
// File: com/myapp/fibonacci/[Link]
package [Link]; // Package declaration
import [Link]; // Import Scanner for user input
public class FibonacciTest {
public static void main(String[] args) {
// Create a Scanner object to take input from the user
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter the number of terms
[Link]("Enter the number of terms for Fibonacci series: ");
int n = [Link]();
// Create an object of FibonacciGenerator to call the generateFibonacci method
FibonacciGenerator fibonacciGenerator = new FibonacciGenerator();
// Call the method to generate Fibonacci series
[Link](n);
// Close the scanner object
[Link]();
}
}
Output:
Enter the number of terms for Fibonacci series: 10
Fibonacci Series up to 10 terms:
0 1 1 2 3 5 8 13 21 34
17.
[Link] (Same Package)
// File: [Link] (in the same package)
public class BaseClass {
public String publicField = "Public Field";
protected String protectedField = "Protected Field";
String defaultField = "Default Field";
private String privateField = "Private Field";
// Public method
public void publicMethod() {
[Link]("Public Method");
}
// Protected method
protected void protectedMethod() {
[Link]("Protected Method");
}
// Default method (Package-private)
void defaultMethod() {
[Link]("Default Method");
}
// Private method
private void privateMethod() {
[Link]("Private Method");
}
}
[Link] (Same Package)
// File: [Link] (in the same package)
public class SubClass extends BaseClass {
public void testAccess() {
[Link]("Accessing members in SubClass (same package):");
// Accessing public member
[Link]("Public field: " + publicField);
publicMethod();
// Accessing protected member
[Link]("Protected field: " + protectedField);
protectedMethod();
// Accessing default member (package-private)
[Link]("Default field: " + defaultField);
defaultMethod();
// Cannot access private members
// [Link]("Private field: " + privateField); // Error
// privateMethod(); // Error
}
}
[Link] (Different Package)
// File: [Link] (in a different package)
package differentpackage;
import BaseClass; // Import the BaseClass from the original package
public class DifferentPackageSubClass extends BaseClass {
public void testAccess() {
[Link]("Accessing members in SubClass (different package):");
// Accessing public member (can access public members)
[Link]("Public field: " + publicField);
publicMethod();
// Accessing protected member (can access protected members in subclass, even in a different
package)
[Link]("Protected field: " + protectedField);
protectedMethod();
// Cannot access default members (package-private)
// [Link]("Default field: " + defaultField); // Error
// defaultMethod(); // Error
// Cannot access private members (private is not accessible from subclass)
// [Link]("Private field: " + privateField); // Error
// privateMethod(); // Error
}
}
[Link] (Main Class to Test)
// File: [Link] (in the same package)
public class TestAccess {
public static void main(String[] args) {
// Testing access in the same package
SubClass subClass = new SubClass();
[Link](); // Same package access
// Testing access in a different package
[Link] diffSubClass = new
[Link]();
[Link](); // Different package access
}
}
Output:
Accessing members in SubClass (same package):
Public field: Public Field
Public Method
Protected field: Protected Field
Protected Method
Default field: Default Field
Default Method
Accessing members in SubClass (different package):
Public field: Public Field
Public Method
Protected field: Protected Field
Protected Method
18.
import [Link];
public class DivideByZero {
public static void main(String[] args) {
// Create a Scanner object for taking input
Scanner scanner = new Scanner([Link]);
// Prompt the user to enter two numbers
[Link]("Enter the numerator (a): ");
int a = [Link]();
[Link]("Enter the denominator (b): ");
int b = [Link]();
try {
// Attempt to divide a by b
int result = a / b;
[Link]("Result: " + result);
} catch (ArithmeticException e) {
// Catch the exception if division by zero occurs
[Link]("Error: Cannot divide by zero. " + [Link]());
} finally {
// This block will always execute, regardless of exception occurrence
[Link]("Execution completed.");
}
// Close the scanner
[Link]();
}
}
Output:
Division by Non-Zero Number
Enter the numerator (a): 10
Enter the denominator (b): 2
Result: 5
Execution completed.
Division by Zero
Enter the numerator (a): 10
Enter the denominator (b): 0
Error: Cannot divide by zero. / by zero
Execution completed.
19.
public class NestedTryExample {
public static void main(String[] args) {
try {
// Outer try block
[Link]("Outer try block started.");
try {
// Inner try block
[Link]("Inner try block started.");
int result = 10 / 0; // This will throw ArithmeticException
} catch (ArithmeticException e) {
// This catch block handles exceptions from the inner try block
[Link]("Caught ArithmeticException in the inner catch block: " + e);
}
// Continuing with outer try block
String str = null;
[Link]([Link]()); // This will throw NullPointerException
} catch (NullPointerException e) {
// This catch block handles exceptions from the outer try block
[Link]("Caught NullPointerException in the outer catch block: " + e);
} catch (Exception e) {
// This catch block handles all other exceptions
[Link]("Caught Exception in the outer catch block: " + e);
} finally {
// Finally block executes no matter what
[Link]("Finally block executed.");
}
}
}
Output:
Outer try block started.
Inner try block started.
Caught ArithmeticException in the inner catch block: / by zero
Caught NullPointerException in the outer catch block: [Link]: Cannot invoke
"[Link]()" because "str" is null
Finally block executed.
20.
// Custom exception class
class InvalidAgeException extends Exception {
// Constructor
public InvalidAgeException(String message) {
super(message); // Pass the error message to the superclass (Exception)
}
}
// Main class to test custom exception
public class AgeValidator {
// Method to validate age
public void validateAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
// If age is out of valid range, throw the custom exception
throw new InvalidAgeException("Invalid age: " + age + ". Age must be between 0 and 150.");
} else {
[Link]("Age is valid: " + age);
}
}
public static void main(String[] args) {
AgeValidator validator = new AgeValidator();
// Test with valid and invalid age values
try {
// Valid age
[Link](25);
// Invalid age
[Link](-5); // This will throw InvalidAgeException
} catch (InvalidAgeException e) {
// Catch the custom exception and handle it
[Link]("Caught exception: " + [Link]());
}
}
}
Output:
Age is valid: 25
Caught exception: Invalid age: -5. Age must be between 0 and 150.
21.
class MyThread extends Thread {
// Override the run method to define thread's task
public void run() {
try {
// Print the thread's name and priority
[Link]([Link]().getName() + " with priority " +
[Link]().getPriority() + " is running.");
} catch (Exception e) {
[Link](e);
}
}
}
public class ThreadPriorityExample {
public static void main(String[] args) {
// Creating threads with different priorities
MyThread thread1 = new MyThread();
MyThread thread2 = new MyThread();
MyThread thread3 = new MyThread();
// Set priorities
[Link](Thread.MIN_PRIORITY); // Priority 1 (lowest)
[Link](Thread.NORM_PRIORITY); // Priority 5 (default)
[Link](Thread.MAX_PRIORITY); // Priority 10 (highest)
// Start the threads
[Link]();
[Link]();
[Link]();
}
}
Output:
Thread-1 with priority 1 is running.
Thread-2 with priority 5 is running.
Thread-0 with priority 10 is running.
22.
import [Link].*;
import [Link].*;
import [Link].*;
public class MouseEventDemo extends JFrame implements MouseListener, MouseMotionListener {
// Constructor to setup the GUI
public MouseEventDemo() {
// Set the title for the frame
setTitle("Mouse Events Demo");
// Set the size of the window
setSize(400, 400);
// Close the application when the window is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add MouseListener and MouseMotionListener to this frame
addMouseListener(this);
addMouseMotionListener(this);
// Set the layout manager
setLayout(new FlowLayout());
}
// MouseListener methods
@Override
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked at (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered the window.");
}
@Override
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited the window.");
}
@Override
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed at (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released at (" + [Link]() + ", " + [Link]() + ")");
}
// MouseMotionListener methods
@Override
public void mouseDragged(MouseEvent e) {
[Link]("Mouse Dragged to (" + [Link]() + ", " + [Link]() + ")");
}
@Override
public void mouseMoved(MouseEvent e) {
// Optional: You can handle mouseMoved here if needed
}
// Main method to run the program
public static void main(String[] args) {
// Create an instance of the MouseEventDemo class
MouseEventDemo demo = new MouseEventDemo();
// Make the window visible
[Link](true);
}
}
Output:
When you click the mouse:
Mouse Pressed at (X, Y)
Mouse Released at (X, Y)
Mouse Clicked at (X, Y)
When the mouse enters or exits the window:
Mouse Entered the window.
Mouse Exited the window.
When you drag the mouse:
Mouse Dragged to (X, Y)
23.
import [Link].*;
import [Link].*;
public class KeyboardEventDemo extends JFrame implements KeyListener {
// Constructor to setup the GUI
public KeyboardEventDemo() {
// Set the title for the frame
setTitle("Keyboard Events Demo");
// Set the size of the window
setSize(400, 200);
// Close the application when the window is closed
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Add the KeyListener to the JFrame
addKeyListener(this);
// Make sure the frame is focusable to capture keyboard events
setFocusable(true);
}
// KeyListener methods
@Override
public void keyPressed(KeyEvent e) {
[Link]("Key Pressed: " + [Link]() + " (Code: " + [Link]() + ")");
}
@Override
public void keyReleased(KeyEvent e) {
[Link]("Key Released: " + [Link]() + " (Code: " + [Link]() + ")");
}
@Override
public void keyTyped(KeyEvent e) {
[Link]("Key Typed: " + [Link]());
}
// Main method to run the program
public static void main(String[] args) {
// Create an instance of the KeyboardEventDemo class
KeyboardEventDemo demo = new KeyboardEventDemo();
// Make the window visible
[Link](true);
}
}
Output:
Key Pressed: A (Code: 65)
Key Released: A (Code: 65)
Key Typed: A
Key Pressed: B (Code: 66)
Key Released: B (Code: 66)
Key Typed: B
Key Pressed: 1 (Code: 49)
Key Released: 1 (Code: 49)
Key Typed: 1