[go: up one dir, main page]

0% found this document useful (0 votes)
2 views16 pages

JAVASSIGN MUB3

The document contains Java programming exercises and implementations by Mohammed Mubasheer, focusing on file handling, data serialization, string manipulation, and word counting. It includes various classes such as StudentFileCreator, SumNumbersFromFile, and PalindromeChecker, demonstrating different functionalities like saving student information, summing numbers from a file, and checking for palindromes. Overall, it serves as a practical guide for learning Java programming concepts and techniques.
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)
2 views16 pages

JAVASSIGN MUB3

The document contains Java programming exercises and implementations by Mohammed Mubasheer, focusing on file handling, data serialization, string manipulation, and word counting. It includes various classes such as StudentFileCreator, SumNumbersFromFile, and PalindromeChecker, demonstrating different functionalities like saving student information, summing numbers from a file, and checking for palindromes. Overall, it serves as a practical guide for learning Java programming concepts and techniques.
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/ 16

Mohammed Mubasheer 22MMI0013

Programming in
Java

Faculty: Dr.DEEPIKA S

NAME : Mohammed Mubasheer


REG NO. : 22MMI0013
Mohammed Mubasheer 22MMI0013

1. import javax.swing.*;

import java.awt.*;

import java.awt.event.*;

import java.io.FileWriter;

import java.io.IOExcep on;

public class StudentFileCreator {

private JTextField rollNumberField, nameField, marksField;

public StudentFileCreator() {

JFrame frame = new JFrame("Student File Creator");

frame.setLayout(new FlowLayout());

JLabel rollNumberLabel = new JLabel("Roll Number:");

JLabel nameLabel = new JLabel("Name:");

JLabel marksLabel = new JLabel("Marks:");

rollNumberField = new JTextField(20);

nameField = new JTextField(20);

marksField = new JTextField(20);

JBu on saveBu on = new JBu on("Save");

saveBu on.addAc onListener(new Ac onListener() {

public void ac onPerformed(Ac onEvent e) {

saveStudentInfo();

});

frame.add(rollNumberLabel);

frame.add(rollNumberField);

frame.add(nameLabel);

frame.add(nameField);

frame.add(marksLabel);

frame.add(marksField);
tt
tt
tt
ti
ti
ti
tt
ti
ti
Mohammed Mubasheer 22MMI0013
frame.add(saveBu on);

frame.setDefaultCloseOpera on(JFrame.EXIT_ON_CLOSE);

frame.setSize(300, 200);

frame.setVisible(true);

private void saveStudentInfo() {

String rollNumber = rollNumberField.getText();

String name = nameField.getText();

String marks = marksField.getText();

if (rollNumber.isEmpty() || name.isEmpty() || marks.isEmpty()) {

JOp onPane.showMessageDialog(null, "Please ll in all elds.");

return;

try (FileWriter leWriter = new FileWriter("student.txt", true)) {

String studentInfo = rollNumber + "," + name + "," + marks + "\n";

leWriter.write(studentInfo);

JOp onPane.showMessageDialog(null, "Student informa on saved successfully!");

rollNumberField.setText("");

nameField.setText("");

marksField.setText("");

} catch (IOExcep on e) {

JOp onPane.showMessageDialog(null, "An error occurred while saving the data.");

} public sta c void main(String[] args) {

SwingU li es.invokeLater(new Runnable() {

public void run() {

new StudentFileCreator();
fi
ti
ti
ti
ti
ti
ti
fi
ti
tt
ti
fi
fi
ti
Mohammed Mubasheer 22MMI0013
}

});

2. import java.io.Bu eredReader;

import java.io.FileReader;

import java.io.IOExcep on;

public class SumNumbersFromFile {

public sta c void main(String[] args) {

String leName = "numbers.txt";

try (Bu eredReader reader = new Bu eredReader(new FileReader( leName)) {

String line;

double sum = 0;

while ((line = reader.readLine()) != null) {

try {

double number = Double.parseDouble(line);

System.out.println("Number: " + number);

sum += number;

} catch (NumberFormatExcep on e) {

System.err.println("Skipping invalid line: " + line);

System.out.println("Sum of numbers: " + sum);

} catch (IOExcep on e) {

System.err.println("An error occurred while reading the le.");

}
ff
fi
ti
ff
ti
ti
ff
ti
fi
fi
Mohammed Mubasheer 22MMI0013
3. import java.io.FileInputStream;

import java.io.IOExcep on;

public class ReadFileBytes {

public sta c void main(String[] args) {

String leName = "sample.txt";

try (FileInputStream s = new FileInputStream( leName)) {

int byteRead;

while ((byteRead = s.read()) != -1) {

System.out.print((char) byteRead);

} } catch (IOExcep on e) {

System.err.println("An error occurred while reading the le.");

4. import java.io.*;

public class UpdateFile {

public sta c void main(String[] args) {

String leName = "java.txt";

try {

DataInputStream dataInputStream = new DataInputStream(new FileInputStream( leName));

RandomAccessFile randomAccessFile = new RandomAccessFile( leName, "rw");

randomAccessFile.seek(10);

randomAccessFile.writeUTF("New Data");

System.out.println("Data from DataInputStream: " + dataInputStream.readUTF());

dataInputStream.close();

randomAccessFile.close();
fi
fi
ti
ti
fi
ti
ti
fi
fi
fi
fi
fi
Mohammed Mubasheer 22MMI0013
} catch (IOExcep on e) {

e.printStackTrace();

5. import java.io.*;

public class DataStreamExample {

public sta c void main(String[] args) {

String leName = "data le.dat";

try (DataOutputStream dataOutputStream = new DataOutputStream(new FileOutputStream( leName))) {

dataOutputStream.writeInt(42);

dataOutputStream.writeDouble(3.14159);

dataOutputStream.writeBoolean(true);

} catch (IOExcep on e) {

e.printStackTrace();

try (DataInputStream dataInputStream = new DataInputStream(new FileInputStream( leName)) {

int intValue = dataInputStream.readInt();

double doubleValue = dataInputStream.readDouble();

boolean booleanValue = dataInputStream.readBoolean();

System.out.println("Read Integer: " + intValue);

System.out.println("Read Double: " + doubleValue);

System.out.println("Read Boolean: " + booleanValue);

} catch (IOExcep on e) {

e.printStackTrace();

6. import java.io.Bu eredReader;


fi
ti
ff
ti
ti
ti
fi
fi
fi
Mohammed Mubasheer 22MMI0013
import java.io.FileReader;

import java.io.IOExcep on;

class Employee {

private int id;

private double salary;

private String name;

private String address;

public Employee(int id, double salary, String name, String address) {

this.id = id;

this.salary = salary;

this.name = name;

this.address = address;

@Override

public String toString() {

return "ID: " + id + ", Salary: " + salary + ", Name: " + name + ", Address: " + address;

}}

public class ReadTextFile {

public sta c void main(String[] args) {

String leName = "ReadTextFile.txt";

try (Bu eredReader reader = new Bu eredReader(new FileReader( leName)) {

String line;

while ((line = reader.readLine()) != null) {

String[] parts = line.split(",");

if (parts.length == 4) {

int id = Integer.parseInt(parts[0].trim());

double salary = Double.parseDouble(parts[1].trim());

String name = parts[2].trim();

String address = parts[3].trim();

Employee employee = new Employee(id, salary, name, address);


fi
ff
ti
ti
ff
fi
Mohammed Mubasheer 22MMI0013
System.out.println(employee);

} else {

System.err.println("Invalid record: " + line);

}}

} catch (IOExcep on e) {

e.printStackTrace(); }}}

7. Serialization and Deserialization:


import java.io.*;

class Student implements Serializable {

private int id;

private String name;

public Student(int id, String name) {

this.id = id;

this.name = name;

} public String toString() {

return "ID: " + id + ", Name: " + name;

public class Serializa onExample {

public sta c void main(String[] args) {

try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("student.ser"))) {

Student student = new Student(1, "Alice");

oos.writeObject(student);

System.out.println("Object has been serialized.");

} catch (IOExcep on e) {

e.printStackTrace();

} try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("student.ser"))) {

Student student = (Student) ois.readObject();

System.out.println("Object has been deserialized.");


ti
ti
ti
ti
Mohammed Mubasheer 22MMI0013
System.out.println("Deserialized Object: " + student);

} catch (IOExcep on | ClassNotFoundExcep on e) {

e.printStackTrace(); } } }

Reversing Words in a String:


public class ReverseWordsInString {

public sta c void main(String[] args) {

String input = "java program is fun to learn";

String[] words = input.split(" ");

StringBuilder reversedString = new StringBuilder();

for (String word : words) {

StringBuilder reversedWord = new StringBuilder(word).reverse();

reversedString.append(reversedWord).append(" ");

String result = reversedString.toString().trim();

System.out.println("Original String: " + input);

System.out.println("Reversed String: " + result);

8)A. Counting Duplicate Words in a String:


import java.u l.HashMap;

import java.u l.Map;

public class DuplicateWordsCounter {

public sta c void main(String[] args) {

String input = "java is a programming language and java is fun to learn";

String[] words = input.split(" ");

Map<String, Integer> wordCount = new HashMap<>();

for (String word : words) {

word = word.toLowerCase();
ti
ti
ti
ti
ti
ti
Mohammed Mubasheer 22MMI0013
if (wordCount.containsKey(word)) {

wordCount.put(word, wordCount.get(word) + 1);

} else {

wordCount.put(word, 1);

} for (Map.Entry<String, Integer> entry : wordCount.entrySet()) {

if (entry.getValue() > 1) {

System.out.println("Duplicate word: " + entry.getKey() + ", Count: " + entry.getValue());

} }}}

B. Counting Occurrences of a Substring in a String:

public class SubstringCounter {

public sta c void main(String[] args) {

String input = "java is a programming language and Java is fun to learn";

String substring = "java";

int count = 0;

int index = input.indexOf(substring);

while (index != -1) {

count++;

index = input.indexOf(substring, index + 1);

System.out.println("Substring '" + substring + "' appears " + count + " mes in the input string.");

}
ti
ti
Mohammed Mubasheer 22MMI0013
C. Checking if a String is a Palindrome:
public class PalindromeChecker {

public sta c void main(String[] args) {

String input = "racecar";

if (isPalindrome(input)) {

System.out.println("The input string is a palindrome.");

} else {

System.out.println("The input string is not a palindrome.");

} public sta c boolean isPalindrome(String str) {

str = str.replaceAll("\\s", "").toLowerCase();

int le = 0;

int right = str.length() - 1;

while (le < right) {

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

return false;

le ++;

right--;

return true;

9. import java.io.*;

import java.u l.HashMap;


ft
ft
ti
ft
ti
ti
ft
Mohammed Mubasheer 22MMI0013
import java.u l.Map;

import java.u l.regex.Pa ern;

public class WordCounter {

public sta c void main(String[] args) {

String inputFileName = "input.txt";

String outputFileName = "word_counts.txt";

Map<String, Integer> wordCountMap = new HashMap<>();

try (Bu eredReader reader = new Bu eredReader(new FileReader(inputFileName)) {

String line;

Pa ern pa ern = Pa ern.compile("[\\s\\p{Punct}]");

while ((line = reader.readLine()) != null) {

String[] words = pa ern.split(line);

for (String word : words) {

word = word.toLowerCase(); // Convert to lowercase for case-insensi ve counts

if (!word.isEmpty()) {

wordCountMap.put(word, wordCountMap.getOrDefault(word, 0) + 1);

} catch (IOExcep on e) {

e.printStackTrace();

try (Bu eredWriter writer = new Bu eredWriter(new FileWriter(outputFileName)) {

for (Map.Entry<String, Integer> entry : wordCountMap.entrySet()) {

writer.write(entry.getKey() + ": " + entry.getValue());

writer.newLine();

} catch (IOExcep on e) {

e.printStackTrace();

}
tt
ff
ff
ti
ti
ti
tt
ti
ti
tt
tt
tt
ff
ff
ti
Mohammed Mubasheer 22MMI0013
System.out.println("Word counts have been wri en to " + outputFileName);

10. import java.io.Bu eredReader;

import java.io.FileReader;

import java.io.IOExcep on;

import java.u l.*;

public class TextFileAnalyzer {

public sta c void main(String[] args) {

String leName = "input.txt";

try (Bu eredReader reader = new Bu eredReader(new FileReader( leName))) {

String line;

StringBuilder textContent = new StringBuilder();

while ((line = reader.readLine()) != null) {

textContent.append(line).append("\n");

String text = textContent.toString();

int totalCharacters = text.length();

String[] words = text.split("\\s+");

int totalWords = words.length;

int totalLines = text.split("\n").length;

Map<String, Integer> wordCounts = new HashMap<>();

for (String word : words) {

wordCounts.put(word, wordCounts.getOrDefault(word, 0) + 1);

String mostCommonWord = null;

int mostCommonWordCount = 0;

for (Map.Entry<String, Integer> entry : wordCounts.entrySet()) {

if (entry.getValue() > mostCommonWordCount) {

mostCommonWord = entry.getKey();
fi
ff
ti
ti
ff
ti
ff
tt
fi
Mohammed Mubasheer 22MMI0013
mostCommonWordCount = entry.getValue();

Set<String> uniqueWords = new HashSet<>(Arrays.asList(words));


System.out.println("Total number of characters: " + totalCharacters);

System.out.println("Total number of words: " + totalWords);

System.out.println("Total number of lines: " + totalLines);

System.out.println("Most common word: " + mostCommonWord);

System.out.println("Number of occurrences of the most common word: " +


mostCommonWordCount);

System.out.println("List of unique words:");

for (String word : uniqueWords) {

System.out.println(word);

} catch (IOExcep on e) {

e.printStackTrace();

11. import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOExcep on;

import java.u l.Scanner;

public class FileCopy {

public sta c void main(String[] args) {

Scanner scanner = new Scanner(System.in);

System.out.print("Enter the source le name: ");

String sourceFileName = scanner.nextLine();

System.out.print("Enter the des na on le name: ");

String des na onFileName = scanner.nextLine();


ti
ti
ti
ti
ti
ti
ti
fi
ti
fi
Mohammed Mubasheer 22MMI0013
try (FileInputStream sourceFile = new FileInputStream(sourceFileName);

FileOutputStream des na onFile = new FileOutputStream(des na onFileName)) {

int bytesRead;

byte[] bu er = new byte[1024];

while ((bytesRead = sourceFile.read(bu er)) != -1) {

des na onFile.write(bu er, 0, bytesRead);

System.out.println("File copied successfully.");

} catch (IOExcep on e) {

e.printStackTrace();

12. import java.io.*; public class ReadTextFile {

public sta c void main(String[] args) {

Bu eredReader reader = new Bu eredReader(new InputStreamReader(System.in));

try {

System.out.print("Enter the name of the text le you want to read (e.g., sample.txt): ");

String leName = reader.readLine();

FileInputStream leInputStream = new FileInputStream( leName);

InputStreamReader inputStreamReader = new InputStreamReader( leInputStream);

Bu eredReader leReader = new Bu eredReader(inputStreamReader);

String line;

System.out.println("Contents of the le " + leName + ":");

while ((line = leReader.readLine()) != null) {

System.out.println(line);

} leReader.close();
ff
ff
ti
ti
fi
fi
ff
ti
fi
ti
fi
fi
ti
ff
ti
ff
ff
fi
ff
fi
fi
fi
ti
ti
fi
Mohammed Mubasheer 22MMI0013
} catch (FileNotFoundExcep on e) {

System.err.println("File not found.");

} catch (IOExcep on e) {

System.err.println("An error occurred while reading the le.");

} nally {

try {

reader.close();

} catch (IOExcep on e) {

e.printStackTrace();

}
fi
ti
ti
ti
fi

You might also like