Problems Flashcards
Text I/O Read and Write File a File Example
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
public class TextFileIOExample {
public static void main(String[] args) { String fileName = "textfile.txt"; try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) { writer.write("Hello, this is a text file example.\n"); writer.write("Writing some text to demonstrate text file I/O.\n"); } catch (IOException e) { e.printStackTrace(); } try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { e.printStackTrace(); } }
}
Binary I/O Read and Write a File Example
import java.io.*;
public class BinaryFileIOExample {
public static void main(String[] args) { String fileName = "binaryfile.dat"; try (DataOutputStream dos = new DataOutputStream(new FileOutputStream(fileName))) { dos.writeInt(42); dos.writeDouble(3.14); dos.writeUTF("Binary file example."); } catch (IOException e) { e.printStackTrace(); } try (DataInputStream dis = new DataInputStream(new FileInputStream(fileName))) { int intValue = dis.readInt(); double doubleValue = dis.readDouble(); String stringValue = dis.readUTF(); System.out.println("Int value: " + intValue); System.out.println("Double value: " + doubleValue); System.out.println("String value: " + stringValue); } catch (IOException e) { e.printStackTrace(); } }
}
Read input from the console and write it to a file using Scanner and FileWriter
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class ConsoleInputFileOutput {
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); FileWriter fileWriter = null; try { System.out.print("Enter the file name: "); String fileName = scanner.nextLine(); fileWriter = new FileWriter(fileName); System.out.println("Enter text (type 'exit' to stop):"); String line; while (!(line = scanner.nextLine()).equalsIgnoreCase("exit")) { fileWriter.write(line + "\n"); } System.out.println("Data has been written to the file."); } catch (IOException e) { e.printStackTrace(); } finally { try { if (fileWriter != null) { fileWriter.close(); } } catch (IOException e) { e.printStackTrace(); } // Close the scanner scanner.close(); } }
}
Fully Loaded Constructor
public class Person {
private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; }
}
Mutator Method
public void setAge(int age) {
this.age = age;
}
Copy Constructor
public class Person {
private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public Person(Person other) { this.name = other.name; this.age = other.age; }
}
toString Method
@Override
public String toString() {
return "Person[name=" + name + ", age=" + age + "]";
}
Accessor
public int getAge() {
return age;
}
Main Method
public class Main {
public static void main(String[] args) { // Your main code here }
}
Derived Class
public class Student extends Person {
private int studentId; public Student(String name, int age, int studentId) { super(name, age); this.studentId = studentId; }
}
Instance Variables
public class Example {
private int variable1; private String variable2;
}
Accessors and Mutators
public int getVariable1() {
return variable1;
}
public void setVariable1(int variable1) {
this.variable1 = variable1;
}
public String getVariable2() {
return variable2;
}
public void setVariable2(String variable2) {
this.variable2 = variable2;
}
Override toString
@Override
public String toString() {
return "Example[variable1=" + variable1 + ", variable2=" + variable2 + "]";
}
Hierarchy and Polymorphism
public abstract class Shape {
public abstract double calculateArea();
}
public class Circle extends Shape {
private double radius; public Circle(double radius) { this.radius = radius; } @Override public double calculateArea() { return Math.PI * radius * radius; }
}
Define and Use Recursive Method
public class RecursiveExample {
public int factorial(int n) { if (n == 0 || n == 1) { return 1; } else { return n * factorial(n - 1); } }
}
Class and Object Example
class Car {
}
Car myCar = new Car();
Composition Example
class Component {}
class Composition {
private Component component;
}
Inheritance Example
class Parent {}
class Child extends Parent {}
Abstract Class and Interface Example
abstract class AbstractClass {
abstract void performAction();
}
class ConcreteClass extends AbstractClass {
void performAction() { System.out.println("Performing concrete action"); }
}
Exception Handling Example
try {
throw new IOException("Input/Output Exception");
} catch (IOException e) {
System.out.println("Caught IOException: " + e.getMessage());
}
GUI Basics Example
import javax.swing.*;
import java.awt.*;
JFrame frame = new JFrame(“GUI Example”);
JButton button = new JButton(“Click Me”);
frame.add(button);
Recursion Example
static int calculateFactorial(int n) {
return n == 0 || n == 1 ? 1 : n * calculateFactorial(n - 1);
}
File I/O Example
try (PrintWriter writer = new PrintWriter(“output.txt”)) {
writer.println("Hello, World!");
} catch (IOException e) {
System.out.println("Error writing to file: " + e.getMessage());
}
Generics Example
class Box<T> {</T>
private T content; public void put(T item) { this.content = item; } public T get() { return content; }
}
Box<String> stringBox = new Box<>();</String>
stringBox.put(“Hello”);
String greeting = stringBox.get();
Case Convertor
import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class CaseConverter extends JFrame {
private JTextField inputField; private JTextField outputField; public CaseConverter() { super("Case Converter"); inputField = new JTextField(20); outputField = new JTextField(20); outputField.setEditable(false); JButton convertButton = new JButton("Convert"); convertButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { convertText(); } }); setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS)); add(new JLabel("Input Text:")); add(inputField); add(new JLabel("Converted Text:")); add(outputField); add(convertButton); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack(); setLocationRelativeTo(null); } private void convertText() { String inputText = inputField.getText(); String convertedText = ""; convertedText = inputText.toUpperCase(); outputField.setText(convertedText); } public static void main(String[] args) { SwingUtilities.invokeLater(new Runnable() { @Override public void run() { new CaseConverter().setVisible(true); } }); } }