0% found this document useful (0 votes)
835 views17 pages

Core Java Practical Exercises

Uploaded by

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

Core Java Practical Exercises

Uploaded by

omyaa122
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

1) Write a java program to display alternate character from a given

string.

public class AlternateCharacters {

public static void main(String[] args) {

String input = “ExampleString”;

For (int I = 0; I < [Link](); I += 2) {

[Link]([Link](i));

2) Write a Java program to calculate area of Circle, Triangle &


Rectangle.(Use Method Overloading).

public class AreaCalculator {

public double area(double radius) {

return [Link] * radius * radius;

public double area(double base, double height) {

return 0.5 * base * height;

public double area(double length, double width) {

return length * width;

public static void main(String[] args) {

AreaCalculator calc = new AreaCalculator();

[Link]("Circle Area: " + [Link](5));

[Link]("Triangle Area: " + [Link](4, 6));

[Link]("Rectangle Area: " + [Link](7, 3));


}

3) Write a java program to search given name into the array, if it is


found then display its index otherwise display appropriate message.

public class NameSearch {

public static void main(String[] args) {

String[] names = {"Alice", "Bob", "Charlie"};

String target = "Bob";

int index = -1;

for (int i = 0; i < [Link]; i++) {

if (names[i].equals(target)) {

index = i;

break;

if (index != -1) {

[Link]("Index: " + index);

} else {

[Link]("Name not found");

4) Write a java program to display ASCII values of the characters


from a file.

import [Link];

import [Link];

import [Link];
public class AsciiValuesFromFile {

public static void main(String[] args) {

try (BufferedReader reader = new BufferedReader(new


FileReader("[Link]"))) {

int c;

while ((c = [Link]()) != -1) {

[Link]((char) c + " : " + (int) c);

} catch (IOException e) {

[Link]();

5) Write a java program to display multiplication table of a given


number into the List box by clicking on button.

Import [Link].*;

Import [Link];

Import [Link];

Public class MultiplicationTableGUI {

Public static void main(String[] args) {

JFrame frame = new JFrame(“Multiplication Table”);

JButton button = new JButton(“Generate Table”);

JList<String> list = new JList<>();

[Link](new ActionListener() {

Public void actionPerformed(ActionEvent e) {

Int number = 5; // Example number

DefaultListModel<String> model = new DefaultListModel<>();


For (int I = 1; I <= 10; i++) {

[Link](number + “ x “ + I + “ = “ + (number * i));

[Link](model);

});

[Link](new [Link]());

[Link](button, [Link]);

[Link](new JScrollPane(list), [Link]);

[Link](300, 200);
[Link](JFrame.EXIT_ON_CLOSE);

[Link](true);

6) Create a package named Series having three different classes to


print

series:

i) Fibonacci series

ii) Cube of numbers

iii) Square of numbers

Write a java program to generate ‘n’ terms of the above series

[Link]

Package Series;

Public class Fibonacci {

Public static void generate FibonacciSeries(int n) {

Int a = 0, b = 1;

[Link](“Fibonacci Series (“ + n + “ terms): “);


For (int I = 1; I <= n; i++) {

[Link](a + “ “);

Int sum a + b;

A = b;

B = sum;

[Link]

Package Series;

Public class CubeOfNumbers {

Public static void generateCubeSeries(int n) {

[Link](“Cube of Numbers (“ + n + “ terms): “);

For (int I = 1; I <= n; i++) {

Int cube = I * I * I;

[Link](cube + “ “);

[Link]

Package Series;

Public class SquareOfNumbers {

Public static void generateSquareSeries(int n) {

[Link](“Square of Numbers (“ + n +

“ terms): “);

For (int I = 1; I <= n; i++) {

Int square = I * I;
[Link](square + “ “);

[Link]

Import Series.*;

Public class Series Main {

Public static void main(String[] args) {

Int n = 10;

[Link](n); [Link]();

[Link](n);

[Link]();

[Link](n);

[Link]();

8) Write a ‘java’ program to check whether given number is


Armstrong or not. (Use static keyword)

Public class ArmstrongNumber {

Public static boolean isArmstrong(int number) {

Int original = number, sum = 0, digits =


[Link](number).length();

While (number > 0) {

Int digit = number % 10;

Sum += [Link](digit, digits);

Number /= 10;

}
Return sum == original;

Public static void main(String[] args) {

Int num = 153; // Example number

If (isArmstrong(num)) {

[Link](num + “ is an Armstrong number.”);

} else {

[Link](num + “ is not an Armstrong number.”);

9) Write a ‘java’ program to copy only non-numeric data from one


file to another file.

Import [Link];

Import [Link];

Import [Link];

Import [Link];

Import [Link];

Public class NonNumericFileCopy {

Public static void main(String[] args) {

String sourceFile = “[Link]”;

String destinationFile = “[Link]”;

Try (BufferedReader reader = new BufferedReader(new


FileReader(sourceFile));

BufferedWriter writer = new BufferedWriter(new


FileWriter(destinationFile))) {

String line;

While ((line = [Link]()) != null) {


If (!containsNumeric(line)) {

[Link](line);

[Link]();

} catch (IOException e) {

[Link]();

Private static boolean containsNumeric(String line) {

For (char c : [Link]()) {

If ([Link]©) {

Return true;

Return false;

10)Write a java program which accepts student details (Sid, Sname,


Saddr) from user and display it on next frame. (Use AWT).

Import [Link].*;

Import [Link].*;

Class StudentDetailsAWT extends Frame implements ActionListener {

Label l1, l2, l3;

TextField tf1, tf2, tf3;

Button b1;

String sid, sname, saddr;


Public StudentDetailsAWT() {

setLayout(new FlowLayout());

l1 = new Label(“Student ID:”);

l2 = new Label(“Student Name:”);

l3 = new Label(“Student Address:”);

tf1 = new TextField(20);

tf2 = new TextField(20);

tf3 = new TextField(20);

b1 = new Button(“Submit”);

add(l1);

add(tf1);

add(l2);

add(tf2);

add(l3);

add(tf3);

add(b1);

[Link](this);

setTitle(“Enter Student Details”);

setSize(300, 200);

setVisible(true);

Public void actionPerformed(ActionEvent e) {

Sid = [Link]();

Sname = [Link]();

Saddr = [Link]();

[Link](false);

Frame displayFrame = new Frame(“Student Details”);


[Link](new FlowLayout());

Label sidLabel = new Label(“Student ID: “ + sid);

Label snameLabel = new Label(“Student Name: “ + sname);

Label saddrLabel = new Label(“Student Address: “ + saddr);

[Link](sidLabel);

[Link](snameLabel);

[Link](saddrLabel);

[Link](300, 200);

[Link](true);

[Link](new WindowAdapter() {

public void windowClosing(WindowEvent we) {

[Link](0);

});

Public static void main(String[] args) {

New StudentDetailsAWT();

11)Write a package MCA which has one class student. Accept


student Details through parameterized constructor. Write display()
method to display details. Create a main class which will use
package and calculate total marks and percentage.

Package MCA;

Import MCA Student

Public class Student {

String sid;

String sname;
Int marks1, marks2, marks3;

Public Student(String sid, String sname, int marks1, int marks2, int
marks3) {

[Link] = sid;

[Link] = sname;

This.marks1 = marks1;

This.marks2 = marks2;

This.marks3 = marks3;

Public void display() {

[Link](“Student ID: “ + sid);

[Link](“Student Name: “ + sname);

[Link](“Marks 1: “ + marks1);

[Link](“Marks 2: “ + marks2);

[Link](“Marks 3: “ + marks3);

Public class MainClass {

Public static void main(String[] args) {

Student student = new Student(“S101”, “John Doe”, 85, 90, 88);

[Link]();

Int totalMarks = student.marks1 + student.marks2 + student.marks3;

Float percentage = (totalMarks / 3.0f);

[Link](“Total Marks: “ + totalMarks);

[Link](“Percentage: “ + percentage + “%”);

}
12)Write Java program which accepts string from user, if its length
is less than five, then throw user defined exception “Invalid String”
otherwise display string in uppercase.

import [Link];

class InvalidStringException extends Exception {

public InvalidStringException(String message) {

super(message);

public class StringValidation {

public static void validateString(String str) throws


InvalidStringException {

if ([Link]() < 5) {

throw new InvalidStringException("Invalid String: The length of the


string is less than five.");

} else {

[Link]("Valid String in Uppercase: " +


[Link]());

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

[Link]("Enter a string: ");

String input = [Link]();

try {

validateString(input);

} catch (InvalidStringException e) {

[Link]([Link]());
} finally {

[Link]();

13)Write a Java Program using Applet to create login form.

Import [Link].*;
Import [Link].*;
Import [Link].*;
Public class LoginFormApplet extends Applet implements
ActionListener {
Label userLabel, passLabel, messageLabel;
TextField userField, passField;
Button loginButton;
Public void init() {
setLayout(new GridLayout(4, 2));
userLabel = new Label(“Username:”);
passLabel = new Label(“Password:”);
userField = new TextField(20);
passField = new TextField(20);
[Link](‘*’);
loginButton = new Button(“Login”);
messageLabel = new Label();
add(userLabel);
add(userField);
add(passLabel);
add(passField);
add(new Label());
add(loginButton);
add(messageLabel); [Link](this);
}
Public void actionPerformed(ActionEvent ae) {
String username = [Link]();
String password = [Link]();

If ([Link](“admin”) && [Link](“password123”)) {

[Link](“Login Successful”);
} else {
[Link](“Invalid Username or Password”);
}
}
}

14)What is recursion is Java? Write a Java Program to final factorial


of a Given number using recursion.

Import [Link];
Public class Factorial {
Public static int factorial(int n) {
If (n == 0) { // Base case: factorial of 0 is 1
Return 1;
} else {
Return n * factorial(n – 1); // Recursive case
}
}
Public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);
[Link](“Enter a number: “);
Int number = [Link]();
[Link]();
If (number < 0) {
[Link](“Factorial is not defined for negative
numbers.”);
} else {
Int result = factorial(number);
[Link](“Factorial of “ + number + “ is “ + result);
}
}
}

15)Write a applet application in java for designing smiley.

Import [Link];

Import [Link];

Import [Link];

Public class SmileyApplet extends Applet {

Public void paint(Graphics g) {


[Link]([Link]);

[Link](50, 50, 200, 200); // Draw face

[Link]([Link]);

[Link](100, 100, 30, 30); // Left eye

[Link](170, 100, 30, 30); // Right eye

[Link]([Link]);

[Link](100, 150, 100, 50, 0, -180);

<!DOCTYPE html>

<html>

<head>

<title>Smiley Applet</title>

</head>

<body>

<applet code=”[Link]” width=”300” height=”300”>

Your browser does not support Java Applets.

</applet>

</body>

</html>

16)Write a java program to copy the dates from one file into another
file.

Import [Link];

Import [Link];

Import [Link];

Public class FileCopy {

Public static void main(String[] args) {


If ([Link] != 2) {

[Link](“Usage: java FileCopy <source file> <destination


file>”);

Return;

String sourceFile = args[0];

String destinationFile = args[1];

Try (FileReader fr = new FileReader(sourceFile);

FileWriter fw = new FileWriter(destinationFile)) {

Int ch;

While ((ch = [Link]()) != -1) {

[Link](ch);

[Link](“File copied successfully!”);

} catch (IOException e) {

[Link](“An error occurred during file operations.”);

[Link]();

17)Write a java program to accept’ ‘n’ integers from the user &
store them

In an ArrayList Collection. Display the elements of ArrayList collection in


reverse order.

Import [Link];

Import [Link];

Import [Link];

Public class ReverseArrayList {


Public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

ArrayList<Integer> numbers = new ArrayList<>();

[Link](“Enter the number of integers you want to input: “);

Int n = [Link]();

[Link](“Enter “ + n + “ integers:”);

For (int I = 0; I < n; i++) {

Int number = [Link]();

[Link](number);

[Link](numbers);

[Link](“Elements in reverse order:”);

For (int num : numbers) {

[Link](num);

[Link]();

Common questions

Powered by AI

Method overloading and overriding are distinct concepts in Java which play pivotal roles in object-oriented design. Method overloading involves defining multiple methods with the same name in the same class, but with different parameters (i.e., different type, number, or both), as seen in the 'AreaCalculator' class where the 'area' method is overloaded to calculate areas of a circle, triangle, and rectangle . Overloading is a compile-time polymorphism feature that allows for more flexible implementations by relying on different signatures. In contrast, method overriding occurs when a subclass provides a specific implementation for a method that is already defined in its superclass. This allows for runtime polymorphism, enabling objects of the subclass to invoke the overridden method defined by the subclass rather than the one in the superclass. This is fundamental to implementing dynamic method dispatch in Java, leading to more dynamic and flexible code behavior. The implications for object-oriented design are significant, as overriding promotes abstraction and code reuse, allowing subclasses to tailor inherited behavior to meet specific needs .

Organizing classes into a package, such as the 'Series' package for generating mathematical sequences like Fibonacci and squares and cubes of numbers, benefits Java development through improved code manageability, reusability, and encapsulation . Inheritance within this context allows shared code and behaviors across classes, reducing redundancy and fostering code cohesion. If a common series-generation method were required, it could be abstracted in a superclass, and then specialized behaviors could be added by subclass implementations. However, the limitations include potential misuses of inheritance where inappropriate class hierarchies are created, leading to maintenance difficulties. In cases of improper design, changes in a superclass can cascade risks across subclasses, creating dependencies that complicate future enhancements or bug fixes. Without careful design and clear class responsibilities, inheritance can introduce rigidity contrary to desired extensibility .

A user-defined exception in Java allows developers to create custom exception conditions tailored to their application's specific needs, providing a mechanism for handling errors in a controlled manner. The 'InvalidStringException', for instance, is a user-defined exception that handles cases where a string length is less than a specified limit . By extending the Exception class, developers can define exception constructors and methods to get additional error information relevant to their domain logic. Unlike built-in exceptions, which are part of the Java API and handle common error conditions (such as NullPointerException or ArithmeticException), user-defined exceptions empower developers to create more meaningful and contextually relevant error handling that aligns with application-specific requirements. This can enhance debugging, as errors are clearly associated with the logical processes of the application, allowing for more precise diagnostics and recovery mechanisms .

In Java, file reading and writing are typically done using classes from the java.io package, such as BufferedReader and BufferedWriter, which are used for efficient reading and writing of characters, arrays, and lines. For instance, in the 'NonNumericFileCopy' program, a BufferedReader is used to read data line-by-line from the source file, while a BufferedWriter writes those lines to the destination file after filtering out numeric characters . The process involves opening the source file in a try-with-resources statement which ensures automatic resource management, reading each line using readLine(), and writing non-numeric lines (determined by a helper method 'containsNumeric') to the destination file. This file I/O approach is robust against exceptions like IOExceptions, by leveraging try-catch blocks for error handling and ensuring resources are closed properly after operations complete .

Using Applets for creating user interfaces in Java poses several design considerations and challenges. Applets are Java programs embedded in web pages, run inside a web browser or applet viewer, and are restricted in access due to security concerns. Designing applets involves dealing with limitations like restricted network access and sandbox security model, impacting how they interact with local resources . One of the primary challenges is the declining support in modern browsers, as many have dropped support for applet execution due to security vulnerabilities associated with running untrusted code. This has prompted a shift toward alternative technologies like JavaFX or web-based frameworks that offer better security and richer interactivity. For robustness, developers must consider compatibility across different browsers and platforms, as well as manage the applet's lifecycle effectively (init, start, stop, destroy methods). Moreover, user experience can be compromised by variations in applet handling between environments, impacting performance and functionality .

Java programs can utilize event-driven programming to handle dynamic content by reacting to user actions or other events at runtime. Typically, this involves UI components like buttons, lists, and forms being manipulated through event listeners that perform certain actions when triggered. In the 'MultiplicationTableGUI' program, an ActionListener is attached to a JButton which updates a JList with a multiplication table when clicked . This structure provides responsive user interactions and a seamless experience, crucial for modern UIs. However, potential performance implications arise from the need to maintain the event queue and processing overhead that can slow down large applications, especially if event handling is not efficiently organized or if background tasks are inadvertently executed on the UI thread. Careful structuring using, for instance, the SwingWorker or threading models to process heavyweight tasks can mitigate these impacts, ensuring the UI remains responsive .

The Strategy pattern is well-suited for improving the architecture of a Java application that calculates areas for different shapes, such as circles, triangles, and rectangles. By encapsulating the algorithm of area calculation into separate, interchangeable objects or strategy classes, the Strategy pattern promotes flexibility and adherence to the open-closed principle, where new shapes can be introduced without modifying existing code . Implementing the Strategy pattern involves creating an interface that declares the area calculation method, and concrete strategy classes for each shape that implements this method. A context class then uses a strategy instance to perform the calculation, allowing algorithms to be selected and swapped at runtime. This design pattern not only simplifies the addition of new shapes by avoiding code duplication but also enhances the maintainability and scalability of the application by decoupling the specific shape implementations from their usage context .

Method overloading enhances flexibility and readability in Java by allowing a single class to handle different types of inputs for similar operations, such as calculating areas. By defining multiple versions of the 'area' method—each tailored to specific parameters like 'radius', 'base' and 'height', or 'length' and 'width'—a programmer can intuitively manage operations on different geometric shapes without having to remember multiple method names. This reduces complexity, as the same method name is used with clear semantic variation, based on the number and types of arguments. This approach not only simplifies the task for developers, making the code easier to read and maintain, but also leverages the same logical operation across different shapes .

Recursion simplifies algorithm design by breaking down complex problems into simpler subproblems of the same kind, leveraging the mathematical logic of self-similarity. In computing the factorial of a number, recursion provides a straightforward implementation approach where the factorial function repeatedly reduces the problem size at each step, invoking itself with decremented values until reaching the base case, usually factorial of 0 (=1). This not only makes the code succinct and easier to comprehend but also aligns naturally with the mathematical definition of factorial, reinforcing theoretical understanding alongside practical implementation. However, recursion in Java involves function call overheads and has inherent memory limitations due to stack size. These limitations necessitate careful design consideration, particularly in assessing the maximum problem size for which the recursive approach remains feasible without risking stack overflow errors .

Using a graphical user interface (GUI) to display data offers several advantages over a text-based interface. GUIs provide a more intuitive and user-friendly way to interact with applications, enhancing accessibility for users with varying levels of technical proficiency. For instance, in the 'MultiplicationTableGUI', a JButton triggers the event to generate a multiplication table displayed in a JList, which is visually more appealing and easier to use compared to textual output . However, GUIs can introduce complexity in both development and maintenance, requiring a deeper understanding of GUI frameworks and event-driven programming concepts. They also typically demand more resources, which can affect performance, especially on lower-end devices or applications running on limited memory resources. Moreover, designing a GUI involves ensuring compatibility across different operating systems, which adds to the development overhead. Thus, while GUIs enhance user experience, they come with trade-offs in terms of complexity and resource utilization .

You might also like