0% found this document useful (0 votes)
14 views11 pages

Java Programs (5,6,7)

Uploaded by

Shiva Prasad
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)
14 views11 pages

Java Programs (5,6,7)

Uploaded by

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

5.

Implement a java program to illustrate the use of different types of character extraction, string
comparison, string search and string modification methods.

public class ArrayListDemo {

public static void main(String[] args) {


System.out.println("Implementing Java program to illustrate different
types of string operations.\n");

// Section 1: Character Extraction Methods


System.out.println("1. Implementation of character extraction methods:");
charAtExample();
substringExample();
toCharArrayExample();
System.out.println();

// Section 2: String Comparison Methods


System.out.println("2. Implementation of String comparison methods:");
equalsExample();
regionMatchesExample();
startsWithEndsWithExample();
equalsVsEqualsOperator();
compareToExample();
System.out.println();

// Section 3: Searching a String


System.out.println("3. Implementation of searching a string:");
indexOfExample();
System.out.println();

// Section 4: Modifying a String


System.out.println("4. Implementation of modifying a string:");
substringExample();
concatExample();
replaceExample();
trimExample();
}

// Section 1: Character Extraction Methods


public static void charAtExample() {
// Example of charAt()
String str = "Hello, World!";
char charAtIndex4 = str.charAt(4);
String substringFrom10To12 = str.substring(10, 13); // Note: endIndex is
exclusive

System.out.println("Character at index 4 in \"" + str + "\": " +


charAtIndex4);
System.out.println("Characters extracted from index 10 to 12: " +
substringFrom10To12);
}

public static void substringExample() {


// Example of substring()
String str = "This is a test. This is, too.";
String search = "is";
String replace = "was";
String result = "";
int index;

System.out.println("Example of substring():");
do {
System.out.println(str);
index = str.indexOf(search);
if (index != -1) {
result = str.substring(0, index);
result = result + replace;
result = result + str.substring(index + search.length());
str = result;
}
} while (index != -1);
System.out.println();
}

public static void toCharArrayExample() {


// Example of toCharArray()
String str = "Hello";
char[] charArray = str.toCharArray();

System.out.print("Character array for \"" + str + "\": ");


for (char ch : charArray) {
System.out.print(ch + " ");
}
System.out.println();
}

// Section 2: String Comparison Methods


public static void equalsExample() {
// Example of equals() and equalsIgnoreCase()
String s1 = "Hello";
String s2 = "Hello";
String s3 = "Good-bye";
String s4 = "HELLO";

System.out.println("a) Example of equals() and equalsIgnoreCase()");


System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " equals " + s3 + " -> " + s1.equals(s3));
System.out.println(s1 + " equals " + s4 + " -> " + s1.equals(s4));
System.out.println(s1 + " equalsIgnoreCase " + s4 + " -> " +
s1.equalsIgnoreCase(s4));
System.out.println();
}

public static void regionMatchesExample() {


// Example of regionMatches()
String str1 = "Hello, World!";
String str2 = "World";
boolean regionMatches = str1.regionMatches(true, 7, str2, 0, 5); // Ignore
case, from index 7, compare with str2 from index 0 for 5 characters

System.out.println("b) Example of regionMatches()");


System.out.println("Region matches from index 7: " + regionMatches);
System.out.println();
}

public static void startsWithEndsWithExample() {


// Example of startsWith() and endsWith()
String str = "Hello, World!";

System.out.println("c) Example of startsWith() and endsWith()");


System.out.println("Starts with \"Hello\": " + str.startsWith("Hello"));
System.out.println("Ends with \"World!\": " + str.endsWith("World!"));
System.out.println();
}

public static void equalsVsEqualsOperator() {


// Example of equals() vs ==
String s1 = "Hello";
String s2 = new String(s1);

System.out.println("d) Example of equals() vs ==");


System.out.println(s1 + " equals " + s2 + " -> " + s1.equals(s2));
System.out.println(s1 + " == " + s2 + " -> " + (s1 == s2));
System.out.println();
}

public static void compareToExample() {


// Example of compareTo()
String[] arr = { "Now", "is", "the", "time", "for", "all", "good", "men",
"to", "come", "to", "the", "aid", "of", "their", "country" };
bubbleSort(arr);

System.out.println("e) Example of compareTo()");


System.out.println("Sorted array:");
for (String str : arr) {
System.out.print(str + " ");
}
System.out.println();
System.out.println();
}

// Bubble sort for compareTo() demonstration


public static void bubbleSort(String[] arr) {
int n = arr.length;
String temp;

for (int i = 0; i < n; i++) {


for (int j = 1; j < (n - i); j++) {
if (arr[j - 1].compareTo(arr[j]) > 0) {
temp = arr[j - 1];
arr[j - 1] = arr[j];
arr[j] = temp;
}
}
}
}

// Section 3: Searching a String


public static void indexOfExample() {
// Example of indexOf() and lastIndexOf()
String s = "Now is the time for all good men to come to the aid of their
country.";

System.out.println("Example of indexOf() and lastIndexOf():");


System.out.println("First index of \"Java\": " + s.indexOf("Java"));
System.out.println("Last index of \"Java\": " + s.lastIndexOf("Java"));
System.out.println();
}

// Section 4: Modifying a String


public static void concatExample() {
// Example of concat()
String s1 = "Hello";
String s2 = s1.concat(" World");

System.out.println("a) Example of concat()");


System.out.println("Concatenated string: " + s2);
System.out.println();
}

public static void replaceExample() {


// Example of replace()
String s = "Hello".replace('l', 'w');

System.out.println("b) Example of replace()");


System.out.println("Replaced string: " + s);
System.out.println();
}

public static void trimExample() {


// Example of trim()
String s = " Hello World ".trim();

System.out.println("c) Example of trim()");


System.out.println("Trimmed string: \"" + s + "\"");
System.out.println();
}
}

Output:

Implementing Java program to illustrate different types of string operations.

1. Implementation of character extraction methods:


Character at index 4 in "Hello, World!": o
Characters extracted from index 10 to 12: ld!
Example of substring():
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

Character array for "Hello": H e l l o

2. Implementation of String comparison methods:


a) Example of equals() and equalsIgnoreCase()
Hello equals Hello -> true
Hello equals Good-bye -> false
Hello equals HELLO -> false
Hello equalsIgnoreCase HELLO -> true
b) Example of regionMatches()
Region matches from index 7: true

c) Example of startsWith() and endsWith()


Starts with "Hello": true
Ends with "World!": true

d) Example of equals() vs ==
Hello equals Hello -> true
Hello == Hello -> false

e) Example of compareTo()
Sorted array:
Now aid all come country for good is men of the the their time to to

3. Implementation of searching a string:


Example of indexOf() and lastIndexOf():
First index of "Java": -1
Last index of "Java": -1

4. Implementation of modifying a string:


Example of substring():
This is a test. This is, too.
Thwas is a test. This is, too.
Thwas was a test. This is, too.
Thwas was a test. Thwas is, too.
Thwas was a test. Thwas was, too.

a) Example of concat()
Concatenated string: Hello World

b) Example of replace()
Replaced string: Hewwo

c) Example of trim()
Trimmed string: "Hello World"

6. Implement a java program to illustrate the use of different types of StringBuffer methods
public class StrinBufferDemo {

public static void main(String[] args) {


// A. length() and capacity()
StringBuffer sb = new StringBuffer("Hello");
System.out.println("A. length() and capacity()");
System.out.println("Initial buffer: " + sb);
System.out.println("Length: " + sb.length());
System.out.println("Capacity: " + sb.capacity());
System.out.println();

// B. ensureCapacity()
sb.ensureCapacity(30);
System.out.println("B. ensureCapacity()");
System.out.println("Updated capacity after ensureCapacity(30): " +
sb.capacity());
System.out.println();

// C. setLength()
sb.setLength(2);
System.out.println("C. setLength()");
System.out.println("Buffer after setLength(2): " + sb);
System.out.println();

// D. charAt() and setCharAt()


System.out.println("D. charAt() and setCharAt()");
System.out.println("Character at index 1: " + sb.charAt(1));
sb.setCharAt(1, 'i');
System.out.println("Buffer after setting charAt(1) to 'i': " + sb);
System.out.println();

// E. getChars()
char[] target = new char[5];
sb.getChars(0, 2, target, 0);
System.out.println("E. getChars()");
System.out.print("Characters copied into target array: ");
System.out.println(target);
System.out.println();

// F. append()
sb.append(" World!");
System.out.println("F. append()");
System.out.println("Buffer after append: " + sb);
System.out.println();

// G. insert()
sb.insert(6, "Beautiful ");
System.out.println("G. insert()");
System.out.println("Buffer after insert: " + sb);
System.out.println();

// H. reverse()
sb.reverse();
System.out.println("H. reverse()");
System.out.println("Reversed buffer: " + sb);
System.out.println();

// I. delete() and deleteCharAt()


sb.delete(8, 17);
System.out.println("I. delete() and deleteCharAt()");
System.out.println("Buffer after delete(8, 17): " + sb);
sb.deleteCharAt(0);
System.out.println("Buffer after deleteCharAt(0): " + sb);
System.out.println();

// J. replace()
sb.replace(5, 9, "was");
System.out.println("J. replace()");
System.out.println("Buffer after replace(5, 9, \"was\"): " + sb);
System.out.println();

// K. substring()
String substring = sb.substring(5);
System.out.println("K. substring()");
System.out.println("Substring from index 5: " + substring);
}
}

Output:

A. length() and capacity()

Initial buffer: Hello

Length: 5

Capacity: 21

B. ensureCapacity()

Updated capacity after ensureCapacity(30): 30

C. setLength()

Buffer after setLength(2): He

D. charAt() and setCharAt()

Character at index 1: e

Buffer after setting charAt(1) to 'i': Hi

E. getChars()

Characters copied into target array: Hi

F. append()

Buffer after append: Hi World!

G. insert()

Buffer after insert: Hi Beautiful World!

H. reverse()

Reversed buffer: !dlroW lufituaeB iH


I. delete() and deleteCharAt()

Buffer after delete(8, 17): lufituaeB iH

Buffer after deleteCharAt(0): ufituaeB iH

J. replace()

Buffer after replace(5, 9, "was"): ufitwasB iH

K. substring()

Substring from index 5: asB Ih

7 Demonstrate a swing event handling application that creates 2 buttons Alpha and Beta and
displays the text “Alpha pressed” when alpha button is clicked and “Beta pressed” when beta
button is clicked.

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

public class EventDemo {

JLabel jlab;

public EventDemo() {

// Create a new JFrame container.

JFrame jfrm = new JFrame("An Event Example");

// Specify FlowLayout for the layout manager.

jfrm.setLayout(new FlowLayout());

// Give the frame an initial size.

jfrm.setSize(220, 90);

// Terminate the program when the user closes the application.

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Make two buttons.

JButton jbtnAlpha = new JButton("Alpha");

JButton jbtnBeta = new JButton("Beta");

// Add action listener for Alpha.

jbtnAlpha.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

jlab.setText("Alpha was pressed.");

});

// Add action listener for Beta.

jbtnBeta.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent ae) {

jlab.setText("Beta was pressed.");

});

// Add the buttons to the content pane.

jfrm.add(jbtnAlpha);

jfrm.add(jbtnBeta);

// Create a text-based label.

jlab = new JLabel("Press a button.");

// Add the label to the content pane.

jfrm.add(jlab);

// Display the frame.

jfrm.setVisible(true);
}

public static void main(String[] args) {

// Create the frame on the event dispatching thread.

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new EventDemo();

});

Output:
8. A program to display greeting message on the browser “Hello UserName”, “How Are You?”,
accept username from the client using servlet.

You might also like