Programming Flashcards
Programming (45 cards)
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(); } }
-
2. Collections.BinarySearch
-
3. Collections.shuffle