0% found this document useful (0 votes)
68 views3 pages

Java Code Examples for Beginners

The document contains several Java code examples demonstrating various programming concepts, including a synchronized bank withdrawal and deposit system, file reading and writing, custom exception handling, and a simple Java Swing application for concatenating names. Each example is structured with classes and methods to illustrate functionality. The code is intended for educational purposes, showcasing practical implementations of Java features.

Uploaded by

golurwt9720
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)
68 views3 pages

Java Code Examples for Beginners

The document contains several Java code examples demonstrating various programming concepts, including a synchronized bank withdrawal and deposit system, file reading and writing, custom exception handling, and a simple Java Swing application for concatenating names. Each example is structured with classes and methods to illustrate functionality. The code is intended for educational purposes, showcasing practical implementations of Java features.

Uploaded by

golurwt9720
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

Java Code Examples

Deposit and Withdraw Problem in Java


class Bank {
int balance = 1000;

synchronized void withdraw(int amount) {


[Link]("Trying to withdraw: " + amount);
if (balance < amount) {
[Link]("Insufficient balance, waiting for deposit...");
try {
wait();
} catch (Exception e) {
[Link](e);
}
}
balance -= amount;
[Link]("Withdraw successful. Remaining balance: " + balance);
}

synchronized void deposit(int amount) {


[Link]("Depositing: " + amount);
balance += amount;
[Link]("Deposit successful. New balance: " + balance);
notify();
}
}

class WithdrawThread extends Thread {


Bank b;
WithdrawThread(Bank b) {
this.b = b;
}

public void run() {


[Link](1500);
}
}

class DepositThread extends Thread {


Bank b;
DepositThread(Bank b) {
this.b = b;
}

public void run() {


[Link](1000);
}
}

class main {
public static void main(String args[]) {
Bank obj = new Bank();
WithdrawThread t1 = new WithdrawThread(obj);
DepositThread t2 = new DepositThread(obj);

[Link]();
[Link]();
}
Java Code Examples

File Printing using Scanner


import [Link].*;
import [Link].*;

class test {
public static void main(String arg[]) throws IOException {
File f = new File("[Link]");
Scanner sc = new Scanner(f);
while ([Link]()) {
String s = [Link]();
[Link](s);
}
[Link]();
}
}

File Writing using FileWriter


import [Link].*;
import [Link].*;

class test {
public static void main(String arg[]) throws IOException {
Scanner sc = new Scanner([Link]);
FileWriter f = new FileWriter("[Link]");

while (true) {
String s = [Link]();
if ([Link]("exit")) {
break;
}
[Link](s + "\n");
}

[Link]();
}
}

Custom Exception Handling


import [Link].*;

class myexception extends Exception {


public myexception(String e) {
super(e);
}
}

public class test {


public static void main(String arg[]) {
Scanner sc = new Scanner([Link]);
try {
int a = [Link]();
int b = [Link]();
Java Code Examples

if (b == 0) {
throw new myexception("Are bhai ye kya kar raha hai, 0 se koi chiz kaise divide
hogi?");
}

[Link](a / b);
} catch (myexception e) {
[Link]([Link]());
}
}
}

Java Swing - Concatenate Names


import [Link].*;
import [Link].*;
import [Link].*;

class demo extends JFrame {


JButton jb1;
JLabel jl1, jl2, jl3;
JTextField jf1, jf2, jf3;

demo() {
jb1 = new JButton("Concatenate");
jl1 = new JLabel("Enter first name");
jl2 = new JLabel("Enter second name");
jl3 = new JLabel("Result");
jf1 = new JTextField(20);
jf2 = new JTextField(20);
jf3 = new JTextField(20);

setLayout(new FlowLayout());
add(jl1);
add(jf1);
add(jl2);
add(jf2);
add(jl3);
add(jf3);
add(jb1);

[Link](new xy());
}

class xy implements ActionListener {


public void actionPerformed(ActionEvent e) {
[Link]([Link]() + " " + [Link]());
}
}

public static void main(String arg[]) {


demo d = new demo();
[Link](300, 200);
[Link](true);
[Link](JFrame.EXIT_ON_CLOSE);
}
}

Common questions

Powered by AI

The Bank example utilizes two separate threads: WithdrawThread and DepositThread. Each thread encapsulates a specific operation that can be run concurrently. WithdrawThread attempts to withdraw funds, potentially causing it to wait if insufficient funds exist, while DepositThread handles depositing money, which may notify any waiting threads once sufficient funds are deposited. This separation allows for concurrent operations on the shared Bank resource, potentially improving responsiveness and performance by handling deposits and withdrawals simultaneously when safe .

One potential issue is the risk of deadlock, where the withdraw method waits indefinitely if no other thread makes a deposit. This can occur if notify is never called. Additionally, spurious wake-ups might occur. These issues can be addressed by using a loop to continually check the condition being waited on (i.e., the balance) after a thread is notified, rather than assuming it is ready to proceed. This ensures that the balance is checked again before proceeding with withdrawal .

FlowLayout provides a simple layout that arranges components in a left-to-right flow, wrapping to the next row if necessary. It is easy to use, making it effective for simple UI designs. However, it lacks flexibility for complex interfaces where component alignment and spacing control are crucial. It might not effectively handle resizing of windows or dynamic content, potentially leading to inefficient use of screen space depending on component sizes and screen resolution .

Using Scanner for reading files, as in the example, is straightforward and convenient for text input and parsing simple lines. However, it may not be highly performant for large files due to its internal buffering and tokenization processes. It is generally more suited for smaller data and less optimal when parsing large files, where more controlled and efficient buffer management using classes like BufferedReader might offer better performance due to reduced overhead and large buffer sizes .

The 'synchronized' keyword ensures that only one thread can execute the withdraw or deposit method at a time, preventing race conditions. When a thread enters a synchronized method, it locks the object for any other synchronized method, ensuring that the balance updates are atomic. This prevents inconsistent states caused by concurrent modifications by multiple threads .

Inheritance allows WithdrawThread and DepositThread to extend the Thread class, inheriting its properties and methods. This allows them to be managed by the JVM as separate threads of execution. Polymorphism is used in how the start() method is called on instances of these classes, leveraging the overridden run() method defined in each specific thread class. This showcases Java's polymorphic runtime handling of threads, enabling custom execution paths per thread type .

The custom exception 'myexception' is used to handle a division by zero error case in the code. When 'b' is zero, the code throws an instance of 'myexception', displaying a custom error message. The benefit of custom exceptions is that they provide specific, readable contexts for error handling tailored to particular needs in applications, allowing for more informative and purposeful error messages and handling logic .

Not closing resources like FileWriter and Scanner can lead to resource leaks, such as file handles remaining open. This can exhaust file descriptors, leading to errors in resource-constrained environments. It can be rectified by using try-with-resources in Java, which automatically closes resources when the try block is exited, even if an exception occurs. This ensures all resources are managed correctly and no leaks occur .

The ActionListener interface in the 'demo' class is implemented in the inner class 'xy', which provides the actionPerformed method. This method is triggered when the 'Concatenate' button is pressed. It concatenates the text from two JTextFields (jf1 and jf2) and sets the result in a third JTextField (jf3). The ActionListener thus facilitates interaction with the GUI by defining the action that should be taken in response to user inputs .

FileWriter is used for writing data to a file named 'this.txt'. It continuously reads user input until the keyword 'exit' is entered. For each input string (not 'exit'), it writes the string followed by a newline to the file. This is facilitated through user input captured by a Scanner object and written line-by-line using the FileWriter object before it is closed .

You might also like