0% found this document useful (0 votes)
25 views10 pages

Wta Module 3

The document provides 10 programming questions related to Java string operations, file handling, and client-server applications. It includes sample code to demonstrate string functions like length(), substring(), replace(), etc. It also includes code to count the number of characters, words, and lines in a file, check file properties, read a file and display its contents with line numbers, sort a list of names, check for palindromes, read from keyboard and write to a file, and implement a basic client-server application where the client sends data to the server which processes it and returns the result.
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)
25 views10 pages

Wta Module 3

The document provides 10 programming questions related to Java string operations, file handling, and client-server applications. It includes sample code to demonstrate string functions like length(), substring(), replace(), etc. It also includes code to count the number of characters, words, and lines in a file, check file properties, read a file and display its contents with line numbers, sort a list of names, check for palindromes, read from keyboard and write to a file, and implement a basic client-server application where the client sends data to the server which processes it and returns the result.
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/ 10

MODULE 3

1.Write java program to demonstrate the following String functions


a. length()
b. isEmpty(), isBlank()
c. charAt()
d. equals(),equalsIgnoreCase()
e. compareTo() and compareToIgnoreCase()
f. startsWith() and endsWith()
g. substring()
h. concat()
i. replace(), replaceFirst(), and replaceAll()
j. contains()
k. reverse();
l. split()
m. join()
n. toLowerCase() and toUpperCase()
o. trim( )

public class StringOperations {


public static void main(String args[]) {
String f="Hello ";
String s="World";
System.out.println("Length of first string is "+f.length());
System.out.println("Length of second string is "+s.length());
System.out.println("Is first string empty? "+s.isEmpty());
System.out.println("Character at position 4 of first string "+s.charAt(4));
System.out.println("Is first and second string equal? "+s.equals(f));
String t="world";
System.out.println("Is second and third string equal(ignore case)?
"+s.equalsIgnoreCase(t));
System.out.println("Compare first and second string? "+s.compareTo(f));
System.out.println("Compare second and third string(ignore case)?
"+s.compareToIgnoreCase(t));
System.out.println("Second string starts with H? "+s.startsWith("H"));
System.out.println("First string ends with space? "+f.endsWith(" "));
String res=f.concat(s);
System.out.println("Concatenated string first and second is "+res);
System.out.println("Substring of res "+res.substring(6));
System.out.println("Replace of l with z "+res.replace("l","z"));
System.out.println("Replace of z with l "+res.replaceAll("z","L"));
System.out.println("Replace of z with l "+res.replaceFirst("l","z"));
System.out.println("HEl is in res "+res.contains("HEl"));
StringBuilder input1 = new StringBuilder();
input1.append(res);
System.out.println(input1);
System.out.println("Reverse of res is "+input1.reverse());
System.out.println("Lowercase of res is "+res.toLowerCase());
System.out.println("Uppercase of res is "+res.toUpperCase());
String str=" Java Programming ";
System.out.println("String is "+str);
System.out.println("Trimmed string is "+str.trim());
}
}

OUTPUT:
java -cp /tmp/44XeJS1nAj StringOperations
Length of first string is 6
Length of second string is 5
Is first string empty? false
Character at position 4 of first string d
Is first and second string equal? false
Is second and third string equal(ignore case)? True
Compare first and second string? 15
Compare second and third string(ignore case)? 0
Second string starts with H? False
First string ends with space? True
Concatenated string first and second is Hello World
Substring of res World
Replace of l with z Hezzo Worzd
Replace of z with l Hello World
Replace of z with l Hezlo World
HEl is in res false
Hello World
Reverse of res is dlroW olleH
Lowercase of res is hello world
Uppercase of res is HELLO WORLD
String is Java Programming
Trimmed string is Java Programming
2. Write a java program that displays the number of characters, lines and words in
a given file
import java.util.*;
import java.io.*;

public class CountWlc


{
public static void main(String[] args) throws IOException {
String line;
long nl=0,nw=0,nc=0;
BufferedReader br = new BufferedReader(new FileReader(args[0]));
while((line = br.readLine()) != null)
{
nl++;
nc= nc+line.length();
StringTokenizer st = new StringTokenizer(line);
nw=nw+st.countTokens();
}
System.out.println("Number of Characters: " +nc);
System.out.println("Number of Words: " +nw);
System.out.println("Number of Lines: " +nl);

}
}

OUTPUT:
[viics134@localhost ~]$ vi count.txt
[viics134@localhost ~]$ java CountWlc count.txt
Number of Characters: 35
Number of Words: 9
Number of Lines: 4

3. Write a Java program that reads on file name from the user, then displays
information about whether the file exists, whether the file is readable, whether the
file is writable, Absolute path of file and the length of the file in bytes?
import java.io.File;
class FileDemo {
public static void main(String args[ ]) {
File f1 = new File("count.txt");
if(f1.exists())
{
System.out.println("File Name: " + f1.getName());
System.out.println("Path: " + f1.getPath());
System.out.println("Abs Path: " + f1.getAbsolutePath());
System.out.println("writeable" +f1.canWrite());
System.out.println("readable" +f1.canRead());
System.out.println("File size: " + f1.length() + " Bytes");
}
else{
System.out.println("The file does not exist.");
}
}
}

OUTPUT:
[viics134@localhost ~]$ java FileDemo
File Name: count.txt
Path: count.txt
Abs Path: /home/viics134/count.txt
Writeable true
readabletrue
File size: 39 Bytes

4. Write a Java program that reads a file and displays the file on the screen, with a
line number before each line?
import java.io.*;
class LineNum{
public static void main(String[] args){
String line;
for(int i=0;i<args.length;i++){
try {
LineNumberReader br= new LineNumberReader
(newFileReader(args[i]));
while((line=br.readLine())!=null) {
System.out.println(br.getLineNumber()+". "+line);
}
}catch(IOException e) {
System.out.println("Error "+e);
}
}
}
}
OUTPUT:

5. Write a Java program that displays the number of characters, lines and words
in a text file.
Same as 2ques.

6. Write a Java program for sorting a given list of names in ascending order.
import java.util.Scanner;
public class SortStrings {
public static void main(String[] args) {
int n;
String temp;
Scanner s = new Scanner(System.in);
System.out.print("Enter number of names you want to sort:");
n = s.nextInt();
String names[] = new String[n];
Scanner s1 = new Scanner(System.in);
System.out.println("Enter all the names:");
for(int i=0;i<n;i++)
names[i] = s1.nextLine();
for (int i=0;i<n;i++) {
for (int j=i+1;j<n;j++) {
if (names[i].compareTo(names[j])>0) {
temp = names[i];
names[i] = names[j];
names[j] = temp;
}
}
}
System.out.print("Names in Sorted Order:");
for (int i=0;i<n-1;i++)
System.out.print(names[i] + ",");
System.out.println(names[n - 1]);
s.close();
s1.close();
}
}

OUTPUT:
Enter number of names you want to sort:3
Enter all the names:
sanjana
isha
xerox
Names in Sorted Order:isha,sanjana,xerox

7. Write a Java program that checks whether a given string is a palindrome or not.
Ex: MADAM is a palindrome.
import java.util.*;
class PalindromeExample
{
public static void main(String args[])
{
String original, reverse = "";
Scanner in = new Scanner(System.in);
System.out.println("Enter a string ");
original = in.nextLine();
int length = original.length();
for ( int i = length - 1; i >= 0; i-- )
reverse = reverse + original.charAt(i);
if (original.equals(reverse))
System.out.println("String is a palindrome.");
else
System.out.println("String isn't a palindrome.");
}
}

OUTPUT:
java -cp /tmp/44XeJS1nAj PalindromeExample
Enter a string madam
String is a palindrome.

8. Write a program in java to efficiently read data from the keyboard and write the
same data into the file.
import java.util.*;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

public class KeyboardToFile {


public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a line of text: ");
String line = sc.nextLine();
BufferedWriter writer = new BufferedWriter(new FileWriter(args[0], true));
writer.append(line+ "\n");
writer.close();
BufferedReader br=new BufferedReader(new FileReader(args[0]));
while((line=br.readLine())!=null) {
System.out.println(line);
}

}
}
OUTPUT:

9. Write a program in java to read filename from user, read data from file using
File Reader and improve its efficiency and display the contents of the file.
import java.util.*;
import java.io.*;
public class readFile{
public static void main(String[]a){
try{
Scanner s = new Scanner(System.in);
System.out.println("Enter the filename: ");
String x = s.nextLine();
BufferedReader br = new BufferedReader(new FileReader(x));
Scanner sr = new Scanner(br);
System.out.println("File contents....");
while(sr.hasNextLine()){
String data = sr.nextLine();
System.out.println(data);
}
}catch(Exception e){
System.out.println(e);}
}
}

OUTPUT:
Enter the filename:
sanjana.txt
File contents....
Hi Sanjana Urs, Welcome to Engineering

10. Write a program that implements the client/server application. The client
sends the data to the server; the server receives the data, uses it to produce a
result and then sends the result back to the client. The client displays the result
on the console.

File: MyServer.java

import java.net.*;

import java.io.*;

class MyServer{

public static void main(String args[])throws Exception{

ServerSocket ss=new ServerSocket(3333);

Socket s=ss.accept();

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){
str=din.readUTF();

System.out.println("client says: "+str);

str2=br.readLine();

dout.writeUTF(str2);

dout.flush();

din.close();

s.close();

ss.close();

}}

File: MyClient.java

import java.net.*;

import java.io.*;

class MyClient{

public static void main(String args[])throws Exception{

Socket s=new Socket("localhost",3333);

DataInputStream din=new DataInputStream(s.getInputStream());

DataOutputStream dout=new DataOutputStream(s.getOutputStream());

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";

while(!str.equals("stop")){
str=br.readLine();

dout.writeUTF(str);

dout.flush();

str2=din.readUTF();

System.out.println("Server says: "+str2);

dout.close();

s.close();

}}

You might also like