Programming Flashcards
Programming
make a dropdown with multiple options in java swing
String[] String = {“Item 1”, “Item 2”, “Item 3”}
JComboBox dropdown = new JComboBox(String);
dropdown.addActionListener(e -> System.out.println(“print-out”);
window.add(dropdown);
setup a window using JAVA swing.
public class main{
//setting up the window public static void main(String[] args){ jFrame window = new jFrame(); window.setVisible(True); window.setsize(420, 420); window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); }
}
Make a text input field that prints something when the user submits
//Add an input field
JTextField inputBox = new JTextField();
inputBox.setBounds(50, 50, 200, 30);
window.add(inputBox);
What does it mean if class attributes are defined as protected in Java?
protected attributes can be accessed by subclasses and other classes within the same package
What is the structure and purpose of Java IO Streams?
Java IO streams provide a sequence of data for reading and writing operations. supporting input and output through input stream and output stream.
What type of sockets does java support and which is recommended for VOIP and file transfer?
Java supports both stream(TCP) and datagram(UDP) sockets. VOIP would use datagram(UDP) as it needs fast data transfer and lost packets being played again would be useless. For file transfer stream sockets are used for the reliability and for safety.
How can threads be safely stopped in java?
.Stop() is Unsafe. So you should manage the thread stopping with a flag checked within the threads run method.
Why is an Array-List often better performing than a Linked-List in java?
An Array-List offers fast access to elements while the pros of the linked list is faster inserts and deletions as it doesn’t have to shift elements after performing these insertions and deletions.
what is the purpose of the Collections.binarysearch idiom in java?
It searchs for an element in a sorted list.
What is the difference between a process and a thread in java?
A process is a self contained execution environment while a thread is a lightweight process that shares the same memory space.
What is the difference between a nested inner class and a static nested class in java?
A nested inner class is tied to an instance of its enclosing class and can access instance members.
A static nested class belongs to the enclosing class and cannot access instance members directly.
What are the characteristics of a Set in java?
A set is an unordered collection that does not allow for duplicate elements and some of the implementations are a Hashset(Unsorted) and a Treeset (Sorted).
What is meant by the transient keyword in java?
transient fields are excluded during serialization meaning their values are not saved or included in the stream.
What is autoboxing and auto-unboxing in java?
Autoboxing converts the primitive types to their wrapper classes EG *( int to Integer). Auto-unboxing does the reverse and converts( Integer -> int)
Primitive types don’t provide any methods
When converted to wrapper classes like Integer and Short Theya re Objectsand provide useful methods like comparison etc.
What is the difference between checked and unchecked exceptions in java?
Checked exceptions must be declared in the method signature or handled with a try-catch block. Unchecked exceptions are runtime exceptions that don’t need to be handled prior.
What is the difference between the Collection interface and the Collections class in java?
the Collections interface defines common data structure operations.Defines the basic methods that all collection types (like List, Set, Queue) must implement.
Examples of methods: add(), remove(), size(), isEmpty().
The Collections class provides utility methods like sorting and searching for Collections. Examples of methods: sort(), binarySearch(), reverseOrder(), synchronizedList().
What is an Iterator in the java Collections Framework?
An Iterator is an object for traversing elements in a collection sequentially without exposing the underlying data structure.
How can Java Streams process collections declaratively?
Java streams process collections by specifying what to do (e.g. filter, sort) instead of how to do it. They use a pipeline of operations that are readable, composable, and can run in parallel for better performace.
In Java swing how would you group a set of buttons together so that only can be selected at a time? Make a difficulty group that has the options fun, impossible and difficult
JRadioButton fun = new JRadioButton(“fun”);
JRadioButton hard = new JRadioButton(“Hard”);
JRadioButton impossible = new JRadioButton(impossible);
ButtonGroup difficultyGroup = new ButtonGroup();
difficultyGroup.add(hard);
same again
//do this for each button so that it prints out when clicked
fun.addActionListener(e -> System.out.println(“Difficulty selected: Fun”));
window.add(difficultyPanel);
How would you create and start a thread using extends Thread?
What are the disadvantages of this approach?
public class HelloWorldThread extends Thread{
@override
public void run(){
System.out.printLn(“hello, world!”);
} public static void main(String[] args){ HelloWorldThread Thread = new HelloWorldThread(); Thread.start } } Disadvantages is that you cant extend more than one thing.
How would you create and start a thread using implements runnable?
What are the advantages of this approach?
class MyTask implements Runnable{
@override public void run(){ system.out.print("welcome to earth"); } }
Public class Main{
public static void main(String args[]){
Thread thread = new thread(new Mytask());
thread.start();
}
}
Advanatages over extends thread is that you can implement many things.
What is a way to stop a thread safely? Using implements runnable show how you would implement this.
Using a volatile flag to stop the thread is safer.
class Task implements Runnable {
private volatile boolean running = true;
@Override public void run() { while (running) { System.out.println("Thread is running..."); try { Thread.sleep(1000); // Simulate work } catch (InterruptedException e) { // Ignore interruption and keep checking the flag } } System.out.println("Thread has stopped."); } public void stop() { running = false; } }
public class Main {
public static void main(String[] args) throws InterruptedException {
Task task = new Task();
Thread thread = new Thread(task);
thread.start()
}
}
What does it mean to be thread safe? Use a bank account accessed by multiple threads to explain.
Thread safety means ensuring that shared data (like a bank account balance) remains consistent and correct.
Imagine two threads accessing a bank account simultaneously:
One thread is depositing money.
Another thread is withdrawing money.
Without proper synchronization, these operations can lead to race conditions, where the final account balance is incorrect because operations interfere with each other.
Write code that shows how a bank account class accessed by more than one thread of execution could be made thread safe.
//How to make a Bank class that can be accessed by many threads changing variables thread safe
class BankAccount {
private int balance;
public BankAccount(int balance){ this.balance = balance; } public synchronised void deposit(int amount){ balance += amount } public synchronised void Withdraw(int amount){ balance -= amount } }
public class Main {
public static void main(String[] args) throws InterruptedException {
BankAccount account = new BankAccount(100);
// Create and start threads with anonymous inner classes Thread t1 = new Thread(new Runnable() { @Override public void run() { account.deposit(50); } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { account.withdraw(30); } }); // Start the threads t1.start(); t2.start(); t3.start(); // Wait for threads to finish t1.join(); t2.join(); } }
What is the Synchronized keyword used for?
Used for thread safety when multiple threads are accessing the same variable.
What is the producer-Consumer problem in java?
Producer Threads: These threads write String values to a shared buffer.
Consumer Threads: These threads read String values from the shared buffer.
Constraints:
The buffer can only hold one String at a time.
A producer cannot write a new value until the previous value has been consumed.
A consumer cannot consume unless a producer has produced a value.
Code a producer-consumer problem in java
// Need a Buffer class with synchronized methods:
// - put(String input): Allows a Producer to add a String to the buffer, but only if it is empty.
// - take(): Allows a Consumer to retrieve a String from the buffer, but only if it is not empty.
//
// These methods check the isEmpty flag to ensure proper coordination between threads.
//
// Producers and Consumers use these methods by instantiating the shared Buffer object.
class Buffer {
private String data = null; // Holds the String
private boolean empty = true; // Tracks if buffer is empty
// Synchronized method for the producer public synchronized void put(String value) { while (!empty) { // Wait if the buffer is not empty try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } data = value; empty = false; // Mark buffer as full System.out.println("Produced: " + value); notifyAll(); // Notify consumers } // Synchronized method for the consumer public synchronized String take() { while (empty) { // Wait if the buffer is empty try { wait(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } empty = true; // Mark buffer as empty System.out.println("Consumed: " + data); notifyAll(); // Notify producers return data; } }
// Producer Thread
class Producer extends Thread {
private final Buffer buffer;
public Producer(Buffer buffer) { this.buffer = buffer; } public void run() { for (int i = 1; i <= 5; i++) { // Produce 5 messages buffer.put("Message " + i); } } }
// Consumer Thread
class Consumer extends Thread {
private final Buffer buffer;
public Consumer(Buffer buffer) { this.buffer = buffer; } public void run() { for (int i = 1; i <= 5; i++) { // Consume 5 messages buffer.take(); } } }
What are the steps to implement custom serialization?
Make the Class Serializable:
Implement the Serializable interface in your class.
This is a marker interface, so no methods need to be implemented.
Define writeObject():
Write the fields you want to save manually to an ObjectOutputStream.
Define readObject():
Read the fields back in the same order from an ObjectInputStream.
Handle Non-Serializable Fields:
For fields that cannot be serialized (e.g., a transient or complex object), save their necessary state manually in writeObject() and reconstruct them in readObject().
Write code that implements simple object serialization and deserialization.
public class SerializeExample {
public static void main(String[] args) {
User user = new User(“Alice”, 25);
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) { oos.writeObject(user); // Serialize the object System.out.println("Object Serialized"); } catch (IOException e) { e.printStackTrace(); } } }
public class DeserializeExample {
public static void main(String[] args) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(“user.ser”))) {
User user = (User) ois.readObject(); // Deserialize the object
System.out.println(“Deserialized Object: “ + user);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Explain the difference between processing streams and data sink streams. Use a
byte stream example involving reading and writing to support your answer.
- Processing Streams enhance and add extra functionality of their underlying stream.
Wrap around another stream (like a data sink). cannot function alone, needs an underlying stream - Data sink streams are responsible for the actual interaction with the data source.
perform raw data transform.
can function independently
EXAMPLE:
DataSinkStream
FileInputStream fileInput = new FileInputStream;
FileOutputStream fileOutput = newFileOutputStream.
Processing Streams:
BufferedInputStream bufferedInputstream = new BufferedInputStream(fileInput);
BufferedInputStream bufferedOutputstream = new BufferedOutputStream(fileOutput);
implement custom serialization for an integer that shouldn’t be handled by the default serialization.
class User implements Serializable {
private String name;
private transient int loginCount; // Won’t be serialized by default
public User(String name, int loginCount) { this.name = name; this.loginCount = loginCount; } // Custom serialization method private void writeObject(ObjectOutputStream oos) throws IOException { oos.defaultWriteObject(); // Serialize default fields (e.g., name) oos.writeInt(loginCount); // Manually serialize transient loginCount } // Custom deserialization method private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException { ois.defaultReadObject(); // Deserialize default fields loginCount = ois.readInt(); // Restore the transient loginCount manually }
list of CODE you need to know
Serialization and Deserialization
Custom serialization
Enum question with custom to-String
Producer and consumer problem
How would you write a list of strings to a file and then read them back in?
public class SimpleSerialization {
public static void main(String[] args) {
String filename = “strings.ser”; // File to store serialized data
// Create a List of strings List<String> strings = new ArrayList<>(); strings.add("Hello"); strings.add("World"); strings.add("Serialization in Java"); // Serialize the List to a file try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filename))) { oos.writeObject(strings); System.out.println("List has been serialized to " + filename); } catch (IOException e) { e.printStackTrace(); } // Deserialize the List from the file try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(filename))) { List<String> deserializedStrings = (List<String>) ois.readObject(); System.out.println("Deserialized List: " + deserializedStrings); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
Write the code to serialize and deserialize a list of strings.
public class SimpleListSerialization {
public static void main(String[] args) {
// Step 1: Create a List of Strings
List<String> stringList = Arrays.asList("Hello", "World", "Java", "Serialization");</String>
// Step 2: Serialize the List to a file try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("strings.ser"))) { oos.writeObject(stringList); System.out.println("List Serialized: " + stringList); } catch (IOException e) { e.printStackTrace(); } // Step 3: Deserialize the List from the file try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("strings.ser"))) { List<String> deserializedList = (List<String>) ois.readObject(); System.out.println("List Deserialized: " + deserializedList); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } }
If i have a class with these 3 variables how would i make a hashcode method including all 3 of these?
private String firstName;
private String lastName;
private int ppsNumber;
Override
public int hashCode() {
return Objects.hash(firstName, lastName, ppsNumber);
}
Describe the Set interface in the Java Collections Framework. What is its
relationship to the Collection interface? What are the main characteristics
of a Set collection? List and briefly describe two classes in the Java
Collections Framework that implement the Set interface, outlining the
difference between them.
The set interface represents a collection of unique elements in the java collections framework.
It ensures no duplicate elements
it extends the collection interface methods like add(), remove() etc.
A set does not allow for duplicates and has efficient operators.
Example of classes that implement the set interface:
Hashset: Does not guarentee orderin, uniquekey value pairs, provides constant time performace O(1) for operations like add and remove.
TreeSet: Maintains elements in order. Provides logarithmic time O(Log N) for operations like add() and remove().
Explain fully the purpose and operation of the following code idiom:
int pos = Collections.binarySearch(list, key);
if (pos < 0)
list.add(-pos-1, key);
it check of a key is in a list and if not it inserts it in the right place to ensure sorting.
(c) Write a Plant class that includes an ID number, a genus name and a
species name as class attributes. The Plant class should implement the Comparable interface to define the natural order for these objects such that
the genus is compared first and then the species.
public class Plant implements Comparable<Plant> {
private String genus;
private String species;</Plant>
public Plant(String genus, String species) { this.genus = genus; this.species = species; } @Override public int compareTo(Plant other) { int genusComparison = this.genus.compareTo(other.genus); if (genusComparison != 0) { return genusComparison; // Compare by genus first } return this.species.compareTo(other.species); // If genus is equal, compare by species } }
Write a Java program that uses an ArrayList to store a collection of Plant
objects and then sort the list based on natural order.
public class PlantSorter {
public static void main(String[] args) {
// Step 1: Create an ArrayList of Plant objects
List<Plant> plants = new ArrayList<>();
plants.add(new Plant("Rosa", "rubiginosa"));
plants.add(new Plant("Quercus", "robur"));
plants.add(new Plant("Acer", "palmatum"));
plants.add(new Plant("Rosa", "canina"));</Plant>
// Step 2: Sort the list based on natural order Collections.sort(plants); // Step 3: Print the sorted list System.out.println("Sorted Plants:"); for (Plant plant : plants) { System.out.println(plant); } } }
Explain comparator and give an example of how it is used.
public class IdComparator implements Comparator<Plant> {
@Override
public int compare(Plant p1, Plant p2) {
return Integer.compare(p1.getId(), p2.getId());
}
}</Plant>
By implementing comparable write code so that the compareTo() method compares by lastName then firstName.
@override
public int compareTo(customer other){
int surnameComparison = this.surname.compareTo(other.surname)
if(surnameComparison != 0){ return surnameComparison; }else{ return this.firstName.compareTo(other.firstName); } }
What are streams in java.util.stream in JAVA?
Streams allow you to work with collections (such as lists). They let you process data by saying what you want it to do as opposed to how you want to do it.
Streams from java.util.stream allow for processing of collections
in a way that is declarative, composable, and parallelizable. Explain
what is meant by this using examples where appropriate.
Declarative: Describing what to do as opposed to how to do it
Example:
//makes a new list that is called fileredList with a filter
List<String> filteredList = cars.Stream()
.filter(car -> cars.getengine() >= 2.0)
.collect(collectors.toList())
//here it declared to filter it but not the logic to actually do it.</String>
composable:
this meant that you can have multiple operations at the same time.
Example
List<String> regNumbers = cars.stream()
.filter(car -> car.getEngineSize() > 2.0) // Step 1: Filter
.map(Car::getRegistrationNumber) // Step 2: Map to registration
.collect(Collectors.toList()); // Step 3: Collect to List
//Here its filtering it and mapping it to a list
Parralelizable:
Streams can run in parrellel to speed up processing (for large datasets)</String>
Example:
long count = cars.parrallelStream()
.filters(car -> car.getEngineSize()>= 2.0)
.count();
//usees the .parrallelStream() method
Using Streams loop through a list called cars and for each of the cars get a list that contains the regrestration numbers. Assume that GetRegestrationNumber() is a method already defined.
List<cars> RegestrationNumbers = cars.stream()
.filter(car::getRegrestrationNumber)
.collect(collectors.toList());</cars>
What are 3 Polymorphic algorithms in the java Collections Framework
- Collection.sort<List></List>
- Collections.BinarySearch<List></List>
- Collections.shuffle<List></List>