0% found this document useful (0 votes)
4 views12 pages

Java Programs for String Manipulation and Geometry

The document contains multiple Java programming examples, including displaying alternate characters from a string, calculating areas of different shapes using method overloading, searching for a name in an array, and displaying ASCII values from a file. It also covers GUI applications using AWT and Swing, user-defined exceptions, recursion for factorial calculation, and file handling operations. Additionally, it includes examples of abstract classes, applets, and working with ArrayLists.

Uploaded by

truptiraut6555
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)
4 views12 pages

Java Programs for String Manipulation and Geometry

The document contains multiple Java programming examples, including displaying alternate characters from a string, calculating areas of different shapes using method overloading, searching for a name in an array, and displaying ASCII values from a file. It also covers GUI applications using AWT and Swing, user-defined exceptions, recursion for factorial calculation, and file handling operations. Additionally, it includes examples of abstract classes, applets, and working with ArrayLists.

Uploaded by

truptiraut6555
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

(a) Display alternate characters from a string

public class AlternateCharacters {


public static void main(String[] args) {
String str = "HELLO WORLD";
[Link]("Alternate characters: ");
for (int i = 0; i < [Link](); i += 2) {
[Link]([Link](i));
}
}
}
✔ Output:
Alternate characters: HLOWRD

(b) Calculate area of Circle, Triangle & Rectangle (Method Overloading)

class Area {

double area(double r) { // Circle


return 3.14 * r * r;
}

double area(double l, double b) { // Rectangle


return l * b;
}

double area(double b, double h, boolean isTriangle) { // Triangle


return 0.5 * b * h;
}
}
public class TestArea {
public static void main(String[] args) {
Area obj = new Area();
[Link]("Circle Area: " + [Link](5));
[Link]("Rectangle Area: " + [Link](5, 10));
[Link]("Triangle Area: " + [Link](10, 6, true));
}
}
✔ Output:
Circle Area: 78.5Rectangle Area: 50.0Triangle Area: 30.0

✅ (c) Search name in array & display index

import [Link];

public class SearchName {

public static void main(String[] args) {


String[] names = {"Rehan", "Amit", "Sajid", "Rahul"};
Scanner sc = new Scanner([Link]);
[Link]("Enter name to search: ");
String name = [Link]();
boolean found = false;
for (int i = 0; i < [Link]; i++) {
if (names[i].equalsIgnoreCase(name)) {
[Link]("Found at index: " + i);
found = true;
break;
}
}
if (!found) {
[Link]("Name not found!");
}
}
}
✔ Output:
Enter name to search: SajidFound at index: 2

(If not found:)

Name not found!

✅ (d) Display ASCII values of characters from a file

Suppose file name = [Link]


content = ABC

import [Link].*;

public class ASCIIFile {


public static void main(String[] args) throws Exception {
FileReader fr = new FileReader("[Link]");
int ch;
while ((ch = [Link]()) != -1) {
[Link]((char) ch + " = " + ch);
}
[Link]();
}
}
✔ Output:
A = 65B = 66C = 67

✅ (e) Multiplication table in Listbox (Swing)

import [Link].*;import [Link].*;

public class TableGUI {

public static void main(String[] args) {

JFrame f = new JFrame("Multiplication Table");

JTextField tf = new JTextField();


JButton btn = new JButton("Show");
JList<String> list = new JList<>();
DefaultListModel<String> model = new DefaultListModel<>();

[Link](40, 40, 100, 30);


[Link](40, 80, 100, 30);
[Link](40, 130, 150, 200);

[Link](new ActionListener() {
public void actionPerformed(ActionEvent e) {
[Link]();
int n = [Link]([Link]());
for (int i = 1; i <= 10; i++) {
[Link](n + " x " + i + " = " + (n * i));
}
[Link](model);
}
});

[Link](tf);
[Link](btn);
[Link](list);
[Link](300,400);
[Link](null);
[Link](true);
}
}
✔ Output (When number = 5)
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

Set 2

(a) Java AWT program to accept student details and display on next Frame

import [Link].*;import [Link].*;


class StudentForm extends Frame implements ActionListener {
TextField t1, t2, t3;
Button b;
StudentForm() {
setLayout(new FlowLayout());
add(new Label("Enter Student Id:"));
t1 = new TextField(15);
add(t1);
add(new Label("Enter Name:"));
t2 = new TextField(15);
add(t2);
add(new Label("Enter Address:"));
t3 = new TextField(15);
add(t3);
b = new Button("Submit");
add(b);

[Link](this);

setSize(300,300);
setVisible(true);
}

public void actionPerformed(ActionEvent e) {


new Display([Link](), [Link](), [Link]());
}

public static void main(String args[]) {


new StudentForm();
}
}
class Display extends Frame {
Display(String id, String name, String addr) {
setLayout(new FlowLayout());
add(new Label("Student Details"));
add(new Label("ID: " + id));
add(new Label("Name: " + name));
add(new Label("Address: " + addr));

setSize(300,300);
setVisible(true);
}
}

✔ Output (GUI)

ID: 101Name: RehanAddress: Pune

✅ (b) Create MCA package and calculate percentage

✔ Package file: MCA/[Link]

package MCA;
public class Student {
int marks1, marks2, marks3;
String name;

public Student(String name, int m1, int m2, int m3) {


[Link] = name;
marks1 = m1;
marks2 = m2;
marks3 = m3;
}

public void display() {


[Link]("Name: " + name);
[Link]("Marks: " + marks1 + ", " + marks2 + ", " + marks3);
}
}

✔ Main class

import [Link];
public class Test {
public static void main(String[] args) {
Student s = new Student("Amit", 80, 90, 70);
[Link]();

int total = s.marks1 + s.marks2 + s.marks3;


double per = total / 3.0;
[Link]("Total: " + total);
[Link]("Percentage: " + per);
}
}

✔ Output:

Name: AmitMarks: 80, 90, 70Total: 240Percentage: 80.0

✅ (c) Throw user defined exception if string length < 5

✔ Program

import [Link].*;
class InvalidString extends Exception {
InvalidString(String s) {
super(s);
}
}
public class TestString {
public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

[Link]("Enter String: ");


String st = [Link]();

try {
if ([Link]() < 5)
throw new InvalidString("Invalid String");
else
[Link]([Link]());
}
catch (InvalidString e) {
[Link](e);
}
}
}

✔ Output:

Case-1:

Enter String: [Link]: Invalid String

Case-2:

Enter String: helloHELLO

✅ (d) Java program using Applet (Login Form)

import [Link].*;import [Link].*;


public class LoginApplet extends Applet {
Label l1 = new Label("Username:");
Label l2 = new Label("Password:");

TextField t1 = new TextField(15);


TextField t2 = new TextField(15);

Button b = new Button("Login");

public void init() {


add(l1); add(t1);
add(l2); add(t2);
add(b);
}
}

✔ HTML File

<applet code="[Link]" width="300" height="200"></applet>

✔ Output (Applet window)

Username: [ ]Password: [ ]
[ Login ]

✅ (e) Recursion + factorial program

✔ Program

public class Fact {

static int fact(int n) {


if (n == 1) return 1;
return n * fact(n - 1);
}

public static void main(String[] args) {


int num = 5;
[Link]("Factorial = " + fact(num));
}
}

✔ Output:

Factorial = 120

✅ (ii) Reverse elements of array

✔ Program

public class ReverseArray {


public static void main(String[] args) {

int arr[]={10,20,30,40,50};
[Link]("Reversed array: ");
for(int i=[Link]-1;i>=0;i--){
[Link](arr[i]+" ");
}
}
}

✔ Output:

Reversed array: 50 40 30 20 10

✅ (iii) Static method to maintain bank account info

✔ Program

class Bank {
static void display(String name, int accno, double bal){
[Link](name+" "+accno+" "+bal);
}
}
public class CustomerBank {
public static void main(String[] args) {
[Link]("Name AccNo Balance");

[Link]("Amit",101,5000);
[Link]("Rehan",102,7500);
[Link]("Sajid",103,6000);
}
}

✔ Output:

Name AccNo BalanceAmit 101 5000.0Rehan 102 7500.0Sajid 103 6000.0

✅ (iv) Abstract class Shape + Cone & Cylinder

✔ Program

abstract class Shape {


abstract double area();
abstract double volume();
}
class Cone extends Shape {
double r,h;

Cone(double r,double h){ this.r=r; this.h=h; }

double area(){
return 3.14*r*(r + [Link](r*r + h*h));
}
double volume(){
return (3.14*r*r*h)/3;
}
}
class Cylinder extends Shape {
double r,h;

Cylinder(double r,double h){ this.r=r; this.h=h; }

double area(){
return 2*3.14*r*(r+h);
}
double volume(){
return 3.14*r*r*h;
}
}
public class TestShape {
public static void main(String[] args) {

Shape c1=new Cone(5,10);


Shape c2=new Cylinder(4,7);

[Link]("Cone Area: "+[Link]());


[Link]("Cone Volume: "+[Link]());

[Link]("Cylinder Area: "+[Link]());


[Link]("Cylinder Volume: "+[Link]());
}
}

✔ Output:

Cone Area: 282.6Cone Volume: 261.6666666666667Cylinder Area: 275.52Cylinder Volume:


351.68

✅ (v) Smiley Face using Applet

✔ Program

import [Link].*;import [Link].*;


public class Smiley extends Applet {
public void paint(Graphics g){

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

[Link](90,110,30,30); // eyes
[Link](170,110,30,30);

[Link](90,130,110,70,0,-180); // smile
}
}

✔ HTML File

<applet code="[Link]" width="300" height="300"></applet>

✔ Output:
(A proper smiley face drawn)

(d) Java program to check Armstrong number using static keyword

✔ Program

import [Link];
public class Armstrong {

static boolean isArmstrong(int num) {


int temp = num, sum = 0;

while (temp != 0) {
int r = temp % 10;
sum += r * r * r;
temp /= 10;
}

return sum == num;


}

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);


[Link]("Enter number: ");
int n = [Link]();

if (isArmstrong(n))
[Link](n + " is Armstrong number");
else
[Link](n + " is NOT Armstrong number");
}
}

✔ OUTPUT

Case-1

Enter number: 153153 is Armstrong number

Case-2

Enter number: 100100 is NOT Armstrong number

✅ (e) Copy only non-numeric data from one file to another

Example: File1 contains:

abc123xyz45pq

Output file should have:


abcxyzpq

✔ Program

import [Link].*;
public class CopyNonNumeric {
public static void main(String[] args) throws Exception {

FileReader fr = new FileReader("[Link]");


FileWriter fw = new FileWriter("[Link]");

int ch;
while ((ch = [Link]()) != -1) {
if (![Link]((char) ch)) {
[Link](ch);
}
}

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

[Link]("Non numeric data copied successfully!");


}
}

✔ OUTPUT (console)

Non numeric data copied successfully!

✔ Content of [Link]

abcxyzpq

(d) Write a Java program to copy the data from one file into another file

✔ Program (File Copy Example)

import [Link].*;
public class CopyFile {
public static void main(String[] args) {
try {
FileInputStream fin = new FileInputStream("[Link]");
FileOutputStream fout = new FileOutputStream("[Link]");

int ch;
while ((ch = [Link]()) != -1) {
[Link](ch);
}

[Link]();
[Link]();
[Link]("File copied successfully!");
} catch (Exception e) {
[Link]("Error: " + e);
}
}
}

Before running

Create a file named [Link] with some text:

Hello Java File Handling!

▶ Expected Output

File copied successfully!

After program runs:

[Link] will contain:

Hello Java File Handling!

✅ (e) Java program to accept ‘n’ integers, store into ArrayList and display in reverse
order

✔ Program

import [Link].*;
public class ArrayListReverse {
public static void main(String[] args) {
Scanner sc = new Scanner([Link]);

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

[Link]("Enter number of elements: ");


int n = [Link]();

[Link]("Enter " + n + " integers:");


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

[Link]("ArrayList: " + list);

[Link]("Reverse order:");
for (int i = [Link]() - 1; i >= 0; i--) {
[Link]([Link](i) + " ");
}
}
}

▶ Sample Input

Enter number of elements: 5Enter 5 integers:1020304050

▶ Output

ArrayList: [10, 20, 30, 40, 50]


Reverse order:50 40 30 20 10

Common questions

Powered by AI

Capturing and using ASCII values of characters from text files in Java enables detailed data processing and manipulation by converting the characters into their numerical representations. This process allows developers to perform various operations like encryption, sorting based on character values, and formatting validation. ASCII values provide a foundation for character encoding standards and help in the transformation of text data for both analysis and processing contexts, offering consistent means to handle textual data across diverse scenarios .

Filtering non-numeric characters from a file involves reading and processing each character, which can be challenging due to file size constraints and encoding variations. The solution involves using character streams like FileReader to read text data and identity checks, such as Character.isDigit(), to differentiate numeric from non-numeric characters. After identifying non-numeric values, they can be selectively written to a new file using FileWriter, ensuring data specificity. This stream-based approach efficiently handles character filtering while maintaining data integrity .

Input and Output stream classes in Java play a pivotal role in handling file operations by providing interfaces to read from and write to files. Classes like FileInputStream and FileOutputStream enable efficient byte-level data transfer, which is crucial for file copying tasks. The input stream reads the content byte by byte, and the output stream writes it to the target file. This mechanism facilitates clear and direct handling of file I/O operations, ensuring data integrity during transfers .

Using static methods for managing bank account information allows these methods to be called without creating an instance of the class, simplifying the access and reducing the overhead of object instantiation. This is beneficial for operations that don't require object state changes, like displaying customer details where shared functionality can be centralized. However, it might limit flexibility in terms of object-oriented principles like encapsulation, as specific operations that alter state would need to manage state through other means .

Recursive methods, like using a function that calls itself to compute the factorial of a number, provide elegant and concise solutions that map directly to mathematical definitions. The benefits include simplicity and easy readability for recursion-friendly problems. However, recursive methods can have drawbacks such as potential stack overflow errors if the recursion depth is too high, as each method call consumes a stack frame, and inefficiency compared to iterative solutions due to repeated method call overhead .

Action listeners in Java Swing are crucial for adding interactivity to a graphical user interface (GUI). They allow the program to handle events, such as button clicks, enabling the application to respond to user inputs in real-time. This enhances the functionality by allowing dynamic changes to the GUI, such as updating a list or displaying calculated results based on user input. For example, an action listener attached to a button can trigger an event to display a multiplication table when clicked .

Inheritance allows concrete classes like Cone and Cylinder to extend an abstract class Shape that declares methods for area and volume without implementation. These subclasses provide specific implementations for calculating the areas and volumes based on their geometric formulas, thus demonstrating polymorphism. Each subclass overrides the abstract methods to perform specific computations pertinent to its dimensions while maintaining a consistent interface for the client code to interact with different shapes polymorphically, improving code modularity and reusability .

Java AWT provides a platform-independent way of creating GUI applications and is effective for simple interfaces, offering direct access to native system resources. However, compared to more advanced frameworks like Java Swing and JavaFX, AWT has limitations in terms of rich graphical capabilities and cross-platform consistency. Modern frameworks provide more sophisticated components, better performance, and are more suited for developing complex GUI applications, whereas AWT might suffice for basic applications requiring less overhead and complexity .

User-defined exceptions in Java enhance error handling by enabling developers to implement specific exceptions that are meaningful to the application, facilitating precise error detection and debugging. For instance, creating an exception for input validation, such as string length checks, helps to manage edge cases where the input does not meet the required criteria. Throwing a specific exception allows the program to provide clear feedback on why an input is invalid, leading to more robust and maintainable code that communicates clear error semantics to developers and users .

Method overloading allows multiple methods in the same class to have the same name but different parameters. This way, different methods can calculate the area of various shapes like a circle, rectangle, or triangle using appropriate formulas. The advantage of method overloading is that it improves code readability and reusability by providing a clean and understandable way to handle different actions that are logically similar but vary slightly in implementation .

You might also like