Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Strings

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

BIT 2203: Advanced Programming Assignment

1)
Strings

i) Given the following string:

String str= “Baseball park”;

a) The first occurrence of ‘l’ in str

b) Find and replace ‘base ’ with ‘foot’

c) Extract and display ‘park ’ from str

d) Replace park with ‘Stadium’

Code:

public class StringManipulation {

public static void main(String[] args) {

String str = "Baseball park";

System.out.println("Original string: " + str);

// Finding the first occurrence of 'l'

int firstLIndex = str.indexOf('l');

System.out.println("First occurrence of 'l': " + firstLIndex);

// Replacing 'base' with 'foot'

str = str.replace("base", "foot");

System.out.println("String after replacement: " + str);

// Extracting 'park'

String park = str.substring(9);

System.out.println("Extracted park: " + park);

// Replacing 'park' with 'Stadium'

str = str.replace("park", "Stadium");

System.out.println("String after replacement: " + str);

ii) Write a program that inputs from the user a file pathname and extracts: path, filename and extension.

Example: pathname: \programs\java\testProgram.java

Path: \programs\java

Filename: testProgram

Extension: java
Code:

import java.util.Scanner;

public class FilePathExtractor {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a file pathname: ");

String pathname = scanner.nextLine();

int lastSlashIndex = pathname.lastIndexOf('\\');

int lastDotIndex = pathname.lastIndexOf('.');

String path = pathname.substring(0, lastSlashIndex);

String filename = pathname.substring(lastSlashIndex + 1, lastDotIndex);

String extension = pathname.substring(lastDotIndex + 1);

System.out.println("Path: " + path);

System.out.println("Filename: " + filename);

System.out.println("Extension: " + extension);

iii) Write a program to check whether a string is a palindrome

Code:

import java.util.Scanner;

public class PalindromeChecker {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter a string: ");

String str = scanner.nextLine();

if (isPalindrome(str)) {
System.out.println(str + " is a palindrome.");

} else {

System.out.println(str + " is not a palindrome.");

public static boolean isPalindrome(String str) {

str = str.toLowerCase();

int left = 0;

int right = str.length() - 1;

while (left < right) {

if (str.charAt(left) != str.charAt(right)) {

return false;

left++;

right--;

return true;

iv) Write and test a program having a method newString () that takes two string objects as arguments. The string compares (lexicographically) the two string arguments

and returns the concatenation of the arguments with the lesser string coming first.

Code:

import java.util.Scanner;

public class StringConcatenator {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter first string: ");

String str1 = scanner.nextLine();

System.out.print("Enter second string: ");

String str2 = scanner.nextLine();

String newString = newString(str1, str2);

System.out.println("New string: " + newString);


}

public static String newString(String str1, String str2) {

if (str1.compareTo(str2) <= 0) {

return str1.concat(str2);

} else {

return str2.concat(str1);

v) Write a program with a method strInsert() that takes str1 and str2 and an integer pos, as arguments. The method inserts str2 in str1 beginning at position pos

provided that pos < str1.length().Otherwise str2 is inserted at the end of str1.Implement the methods using substring and ‘+’ methods.

Code:

import java.util.Scanner;

public class StringInserter {

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter first string: ");

String str1 = scanner.nextLine();

System.out.print("Enter second string: ");

String str2 = scanner.nextLine();

System.out.print("Enter position to insert: ");

int pos = scanner.nextInt();

String result = strInsert(str1, str2, pos);

System.out.println("Result: " + result);

public static String strInsert(String str1, String str2, int pos) {

if (pos < str1.length()) {

return str1.substring(0, pos) + str2 + str1.substring(pos);

} else {

return str1 + str2;

}
}

vi) A method strReplace takes strings str1, str2 and str3 as arguments. In str1, the method replaces all occurrences of str2 with str3. Implement using appropriate String

class methods. In the main method as ask for input from the keyboard using an input dialog and display the resulting string using a message dialog.

Code:

import javax.swing.JOptionPane;

public class StringReplacer {

public static void main(String[] args) {

String str1 = JOptionPane.showInputDialog(null, "Enter string 1:");

String str2 = JOptionPane.showInputDialog(null, "Enter string 2:");

String str3 = JOptionPane.showInputDialog(null, "Enter string 3:");

String result = strReplace(str1, str2, str3);

JOptionPane.showMessageDialog(null, "Result: " + result);

public static String strReplace(String str1, String str2, String str3) {

return str1.replaceAll(str2, str3);

}
2)
File input and output

th
1. Exercise 15.4, Deitel and Deitel , 10 Edition.

a) Implementation of the TransactionRecord class:

Code:

public class TransactionRecord {

private int accountNumber;

private double amount;

public TransactionRecord(int accountNumber, double amount) {

this.accountNumber = accountNumber;

this.amount = amount;

public int getAccountNumber() {

return accountNumber;

public void setAccountNumber(int accountNumber) {

this.accountNumber = accountNumber;

public double getAmount() {

return amount;
}

public void setAmount(double amount) {

this.amount = amount;

b) Modification of the Account class to include the combine method:

Code:

public class Account {

private int accountNumber;

private String name;

private double balance;

public Account(int accountNumber, String name, double balance) {

this.accountNumber = accountNumber;

this.name = name;

this.balance = balance;

public int getAccountNumber() {

return accountNumber;

public void setAccountNumber(int accountNumber) {

this.accountNumber = accountNumber;

}
public String getName() {

return name;

public void setName(String name) {

this.name = name;

public double getBalance() {

return balance;

public void setBalance(double balance) {

this.balance = balance;

public void combine(TransactionRecord transactionRecord) {

double amount = transactionRecord.getAmount();

if (amount > 0) {

this.balance += amount;

} else {

double absAmount = Math.abs(amount);

if (this.balance >= absAmount) {

this.balance -= absAmount;

} else {

System.out.printf("Account %d: insufficient funds%n", this.accountNumber);

}
}

3)
Generics and Collections

a) Explain with aid of code snippets the use of the keywords super, extends and implements for java Generics.

Extends

The extends keyword is used to specify an upper bound for a type parameter. It restricts the type argument to be a subtype of the specified type. The syntax for using extends is as

follows:

public class MyClass<T extends SomeClass> {

// class implementation

In the example above, T is a type parameter that is bounded by SomeClass. This means that any type argument passed to MyClass must be a subtype of SomeClass.

Super

The super keyword is used to specify a lower bound for a type parameter. It restricts the type argument to be a supertype of the specified type. The syntax for using super is as

follows:

public class MyClass<T super SomeClass> {

// class implementation

In the example above, T is a type parameter that is bounded by SomeClass. This means that any type argument passed to MyClass must be a supertype of SomeClass.

Implements

The implements keyword is used to specify that a class or interface implements one or more interfaces. The syntax for using implements is as follows:

public class MyClass<T extends SomeInterface> implements AnotherInterface {

// class implementation

In the example above, MyClass implements AnotherInterface and has a type parameter T that is bounded by SomeInterface. This means that any type argument passed to MyClass

must implement SomeInterface.


b) Using the List interface (and any of its child classes ) from the Collection framework write a program that features the following:

i) An initial list of 50 students each taking 8 units. A student is an object with a name and registration number.

ii) Add and remove students to the list

iii) Traverse the entire list using ListIterator and display student information in a tabular format

Code:

import java.util.ArrayList;

import java.util.List;

import java.util.ListIterator;

public class StudentList {

public static void main(String[] args) {

// Create initial list of 50 students

List<Student> studentList = new ArrayList<>();

for (int i = 1; i <= 50; i++) {

Student student = new Student("Student " + i, "Reg. No. " + i);

for (int j = 1; j <= 8; j++) {

student.addCourse("Course " + j);

studentList.add(student);

// Add and remove students

studentList.add(new Student("New Student", "Reg. No. 51"));

studentList.remove(0);
// Traverse the entire list using ListIterator and display student information in a tabular format

System.out.println("Name\tRegistration No.\tCourses");

ListIterator<Student> iterator = studentList.listIterator();

while (iterator.hasNext()) {

Student student = iterator.next();

System.out.println(student.getName() + "\t" + student.getRegNo() + "\t\t" + student.getCourses());

class Student {

private String name;

private String regNo;

private List<String> courses;

public Student(String name, String regNo) {

this.name = name;

this.regNo = regNo;

this.courses = new ArrayList<>();

public String getName() {

return name;

}
public String getRegNo() {

return regNo;

public List<String> getCourses() {

return courses;

public void addCourse(String course) {

courses.add(course);

4)
Databases

1. With aid of an example explain the need for a ResultSetMetaData object in JDBC

In JDBC, a ResultSetMetaData object is used to retrieve metadata (information about the data) from a ResultSet object. This metadata includes information such as the number and

types of columns in the result set, the column names, and the column labels.

2. Create a data source, books db, based on the SQL code provided in the following link : http://www2.cs.uregina.ca/~nova/Java_Study/Examples8/books.sql

Use the database created above to create a simple jdbc-GUI-based application that displays the following on the screen :

a) All Authors from the Authors table.

b) All publishers from the Publishers table.

c) A specific author and list all books for that author. Include the title, year and ISBN. Put the information in alphabetical order by the title.

d) A specific publisher and list all books published by the publisher. Include the title, year, and ISBN. Put the information in alphabetical order by title.

e) All books published in the year 2002.

f) All books whose price is 80 dollars and above


5)
Socket Programming

a) With aid of examples explain the following java.net classes:

i) Socket

Socket class represents a client-side endpoint that provides a connection to a server-side endpoint represented by a ServerSocket. It is used to establish a two-way communication

link between a client and a server over a network. Here's an example of how to use Socket to connect to a server:

try (Socket socket = new Socket("localhost", 8080)) {

// do something with the socket

} catch (IOException e) {

// handle exception

ii) ServerSocket

ServerSocket class represents a server-side endpoint that listens for incoming client connections and creates a Socket object for each new connection. Here's an example of how to

use ServerSocket to listen for incoming connections:

try (ServerSocket serverSocket = new ServerSocket(8080)) {

while (true) {

Socket socket = serverSocket.accept();

// handle client connection

} catch (IOException e) {

// handle exception

iii) InetAddress

InetAddress class represents an IP address, either IPv4 or IPv6. It provides methods to resolve host names to IP addresses and vice versa. Here's an example of how to use

InetAddress to get the IP address of a host:


try {

InetAddress address = InetAddress.getByName("www.google.com");

System.out.println(address.getHostAddress());

} catch (UnknownHostException e) {

// handle exception

iv) Inet4Address

Inet4Address class represents an IPv4 address specifically. It is a subclass of InetAddress and provides additional methods to work with IPv4 addresses. Here's an example of how to

use Inet4Address to get the loopback address:

try {

InetAddress address = Inet4Address.getLoopbackAddress();

System.out.println(address.getHostAddress());

} catch (UnknownHostException e) {

// handle exception

v) DatagramSocket

DatagramSocket class represents a socket for sending and receiving datagrams, which are small packets of data. It provides methods for sending and receiving datagrams over a

network. Here's an example of how to use DatagramSocket to send a datagram:

socket = new DatagramSocket()) {

byte[] data = "Hello, world!".getBytes();

DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName("localhost"), 8080);

socket.send(packet);

} catch (IOException e) {

// handle exception

vi) DatagramPacket
It holds message data.

try (DatagramSocket socket = new DatagramSocket()) {

String message = "Hello, world!";

byte[] buffer = message.getBytes();

InetAddress address = InetAddress.getByName("localhost");

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, 8080);

socket.send(packet);

} catch (IOException e) {

// handle exception

b) Write complete programs(client and server side) to demonstrate socket programming using the following socket APIs:

i) TCP

ii) UDP

TCP Socket Programming

import java.io.BufferedReader;
import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.ServerSocket;

import java.net.Socket;

public class TCPServer {

public static void main(String[] args) {

try {

ServerSocket serverSocket = new ServerSocket(1234);

System.out.println("Server started. Listening for client connections...");

while (true) {

Socket clientSocket = serverSocket.accept();

System.out.println("Client connected: " + clientSocket.getInetAddress().getHostAddress());

BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));

PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);

String message = in.readLine();

System.out.println("Received message from client: " + message);

out.println("Hello, client!");

System.out.println("Sent message to client");


clientSocket.close();

} catch (IOException e) {

e.printStackTrace();

Client

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.Socket;

public class TCPClient {

public static void main(String[] args) {

try {

Socket socket = new Socket("localhost", 1234);

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

out.println("Hello, server!");

System.out.println("Sent message to server");


String message = in.readLine();

System.out.println("Received message from server: " + message);

socket.close();

} catch (IOException e) {

e.printStackTrace();

UDP Socket Programming

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;

public class UDPServer {

public static void main(String[] args) {

try {

DatagramSocket socket = new DatagramSocket(1234);

System.out.println("Server started. Listening for client connections...");

byte[] buffer = new byte[1024];

DatagramPacket packet = new DatagramPacket(buffer, buffer.length);

socket.receive(packet);

System.out.println("Client connected: " + packet.getAddress().getHostAddress());


String message = new String(packet.getData(), 0, packet.getLength());

System.out.println("Received message from client: " + message);

message = "Hello, client!";

buffer = message.getBytes();

InetAddress address = packet.getAddress();

int port = packet.getPort();

packet = new DatagramPacket(buffer, buffer.length, address, port);

socket.send(packet);

System.out.println("Sent message to client");

socket.close();

} catch (IOException e) {

e.printStackTrace();

Client

import java.net.DatagramPacket;

import java.net.DatagramSocket;

import java.net.InetAddress;
public class UDPClient {

public static void main(String[] args) {

try {

DatagramSocket socket = new DatagramSocket();

String message = "Hello, server!";

byte[] buffer = message.getBytes();

InetAddress address = InetAddress.getByName("localhost");

int port = 1234;

DatagramPacket packet = new DatagramPacket(buffer, buffer.length, address, port);

socket.send(packet);

System.out.println("Sent message to server");

buffer = new byte[1024];

packet = new DatagramPacket(buffer, buffer.length);

socket.receive(packet);

System.out.println("Received message from server: " + new String(packet.getData(),

You might also like