0% found this document useful (0 votes)
6 views

soljava

The document contains various Java code snippets demonstrating multithreading, GUI applications, and data structures. Key examples include a program that prints letters A-Z with a delay, a friend list that sorts names, and a traffic signal simulation. Other snippets showcase thread lifecycle, priority, and user input handling with collections like TreeSet and LinkedList.

Uploaded by

snehaajadhav8565
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

soljava

The document contains various Java code snippets demonstrating multithreading, GUI applications, and data structures. Key examples include a program that prints letters A-Z with a delay, a friend list that sorts names, and a traffic signal simulation. Other snippets showcase thread lifecycle, priority, and user input handling with collections like TreeSet and LinkedList.

Uploaded by

snehaajadhav8565
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 19

Slip 1

1.
class Slip1 implements Runnable
{
public void run()
{
try
{
for(char c='A';c<='Z';c++)
{
System.out.println(c);
Thread.sleep(3000);
}
}
catch(Exception e)
{
System.out.println("error");
}
}

public static void main(String[] d)


{
Slip1 x=new Slip1();
Thread y=new Thread(x);
y.start();

}
}
_____________________________________________________________________________
Slip 2
1.
import java.util.*;
public class Friend {

public static void main(String[] args)


{
Scanner in =new Scanner(System.in);
System.out.println("Enter the number of friends:");
int n=in.nextInt();
Set<String>friends=new HashSet<>();
for(int i=1;i<=n;i++)
{
System.out.println("Enter name "+i+":");
String name= in.next();
friends.add(name);
}
List<String>sorted=new ArrayList<>(friends);
Collections.sort(sorted);
System.out.println("\nList of friends in ascending order:");
for(String friend:sorted)
{
System.out.println(friend);
}
}

}
_____________________________________________________________________________

___________________________________________________________________________________
_____________________________________________________________
Slip 4
1.
import javax.swing.*;
import java.awt.*;

public class BlinkingText implements Runnable {

private JLabel label;


private boolean isVisible = true;

public BlinkingText(String text) {


label = new JLabel(text);
label.setFont(new Font("Arial", Font.BOLD, 20));
}

public void run() {


while (true) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
isVisible = !isVisible;
label.setVisible(isVisible);
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
JFrame frame = new JFrame("Blinking Text Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

BlinkingText blinker = new BlinkingText(" abhays kr ");


frame.getContentPane().add(blinker.label);

frame.setSize(300, 100);
frame.setLocationRelativeTo(null);
frame.setVisible(true);

Thread blinkThread = new Thread(blinker);


blinkThread.start();
});
}
}

2.
___________________________________________________________________________________
____
Slip 5
1.
import java.util.Enumeration;
import java.util.Hashtable;

public class StudentDirectory {


public static void main(String[] args) {

Hashtable<String, String> studentTable = new Hashtable<>();


studentTable.put("1234567890", "Alice");
studentTable.put("0987654321", "Bob");
studentTable.put("1122334455", "Charlie");
studentTable.put("2233445566", "David");

Enumeration<String> mobileNumbers = studentTable.keys();


Enumeration<String> studentNames = studentTable.elements();

System.out.println("Student Directory:");
System.out.println("------------------");
while (mobileNumbers.hasMoreElements() &&
studentNames.hasMoreElements()) {
String mobileNumber = mobileNumbers.nextElement();
String studentName = studentNames.nextElement();
System.out.println("Mobile Number: " + mobileNumber + ", Student
Name: " + studentName);
}
}
}

2.

___________________________________________________________________________________
___
Slip 6
1.
import java.util.*;

import java.io.*;

class Slip1_2

public static void main(String[] args) throws Exception

int no, element,i;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

TreeSet ts=new TreeSet();

System.out.println("Enter the of elements:");

no=Integer.parseInt(br.readLine());

for(i=0;i<no;i++)

System.out.println("Enter the element: ");

element=Integer.parseInt(br.readLine());

ts.add(element);
}

System.out.println("The elements in sorted order:"+ts);

System.out.println("Enter element to be serach: ");

element = Integer.parseInt(br.readLine());

if(ts.contains(element))

System.out.println("Element is found");
else
System.out.println("Element is NOT found");
}
}

2.File1
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class TrafficSignal extends JPanel {

private int state = 0;


private Timer timer;

public TrafficSignal() {
setBackground(Color.BLACK);
setPreferredSize(new Dimension(200, 600));

timer = new Timer(2000, new ActionListener() {

public void actionPerformed(ActionEvent e) {


changeState();
repaint();
}
});
timer.start();
}

private void changeState() {


state = (state + 1) % 3;
}

public void paintComponent(Graphics g) {


super.paintComponent(g);
g.setColor(Color.BLACK);
g.fillRect(0, 0, getWidth(), getHeight());

if (state == 0) {
g.setColor(Color.RED);
g.fillOval(50, 50, 100, 100);
g.setColor(Color.BLACK);
g.fillOval(50, 250, 100, 100);
g.fillOval(50, 450, 100, 100);
} else if (state == 1) {
g.setColor(Color.BLACK);
g.fillOval(50, 50, 100, 100);
g.setColor(Color.YELLOW);
g.fillOval(50, 250, 100, 100);
g.setColor(Color.BLACK);
g.fillOval(50, 450, 100, 100);
} else {
g.setColor(Color.BLACK);
g.fillOval(50, 50, 100, 100);
g.fillOval(50, 250, 100, 100);
g.setColor(Color.GREEN);
g.fillOval(50, 450, 100, 100);
}
}
}
File2
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TrafficSignalSimulation {


public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {

public void run() {


JFrame frame = new JFrame("Traffic Signal Simulation");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TrafficSignal());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
}
_____________________________________________________________________________
Slip 7
1.
import java.util.Random;
class Sqr extends Thread
{
int x;
Sqr(int n)
{
x=n;
}
public void run()
{
int sqr=x*x;
System.out.println("Square of "+x+" = "+sqr);
}
}
class Cube extends Thread
{
int x;
Cube(int n)
{
x=n;
}
public void run()
{
int c=x*x*x;
System.out.println("Cube of "+x+" = "+c);
}
}
class Rno extends Thread
{
public void run()
{
Random random =new Random();
for(int i=0;i<5;i++)
{
int Dom=random.nextInt(10);
System.out.println("random Integer generated : "+Dom);
Sqr s=new Sqr(Dom);
s.start();
Cube c=new Cube(Dom);
c.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException ex){
System.out.println(ex);
}
}
}
}
public class ThreadP {

public static void main(String[] args)


{
Rno n=new Rno();
n.start();
}

________________________________________________________________________________
Slip 8
1.
class A extends Thread
{
public void run()
{
for(int i=1;i<=10;i++)
{
System.out.println("Covid 19...."+i);
}
}
}
class B extends Thread
{
public void run()
{
for (int i=1;i<=20;i++)
{
System.out.println("LOCKDOWN2020...."+i);
}
}
}
class C extends Thread
{
public void run()
{
for (int i=1;i<=30;i++)
{
System.out.println("VACINATED2021...."+i);
}
}
}
class SetA1
{
public static void main(String args[])
{
A obj=new A();
obj.start();
B obj1=new B();
obj1.start();
C obj2=new C();
obj2.start();
}
}
________________________________________________________________
Slip 9
1.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class ballMover extends JFrame {

private static final long serialVersionUID = 1L;


private BallPanel ballPanel;
private JButton startButton;

public ballMover() {
setTitle("Ball Mover");
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new BorderLayout());

ballPanel = new BallPanel();


startButton = new JButton("Start");

startButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
ballPanel.startMoving();
}
});

add(ballPanel, BorderLayout.CENTER);
add(startButton, BorderLayout.SOUTH);
}

public static void main(String[] args) {


SwingUtilities.invokeLater(() -> {
ballMover frame = new ballMover();
frame.setVisible(true);
});
}
}

class BallPanel extends JPanel {


private int ballY = 0;
private int ballDirection = 1;
private final int ballSize = 30;
private boolean isMoving = false;

public BallPanel() {
setBackground(Color.WHITE);
}

public void startMoving() {


if (!isMoving) {
isMoving = true;
new Thread(() -> {
while (isMoving) {
ballY += ballDirection * 5;
if (ballY + ballSize >= getHeight() || ballY <= 0) {
ballDirection *= -1;
}
repaint();
try {
Thread.sleep(30);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
}
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.RED);
g.fillOval(150, ballY, ballSize, ballSize);
}
}

2.
___________________________________________________________________________________
__
Slip 13
2.
File 1:
import java.util.Random;

class LifecycleThread extends Thread {


private Random random = new Random();

public LifecycleThread(String name) {


super(name);
}
public void run() {
System.out.println(getName() + " is born (created)");
try {
int sleepTime = random.nextInt(5000);
System.out.println(getName() + " is sleeping for " + sleepTime + "
milliseconds");
Thread.sleep(sleepTime);
} catch (InterruptedException e) {
System.out.println(getName() + " is interrupted");
}

System.out.println(getName() + " is dead (completed)");


}
}

File 2:
public class Main1 {
public static void main(String[] args) {
LifecycleThread thread1 = new LifecycleThread("Thread-1");
LifecycleThread thread2 = new LifecycleThread("Thread-2");
LifecycleThread thread3 = new LifecycleThread("Thread-3");

thread1.start();
thread2.start();
thread3.start();
}
}
___________________________________________________________________________________
Slip 15
1.
File 1:
class ThreadPriority extends Thread {
public ThreadPriority(String name) {
super(name);
}

@Override
public void run() {
System.out.println("Thread Name: " + Thread.currentThread().getName());
System.out.println("Thread Priority: " +
Thread.currentThread().getPriority());
}
}

File 2:
public class Main2 {
public static void main(String[] args) {
ThreadPriority thread1 = new ThreadPriority("Thread-1");
ThreadPriority thread2 = new ThreadPriority("Thread-2");

thread1.setPriority(Thread.MAX_PRIORITY);
thread2.setPriority(Thread.NORM_PRIORITY);

thread1.start();
thread2.start();
}
}
___________________________________________________________________________________
__
Slip 17
1.
import java.util.Scanner;
import java.util.TreeSet;

public class Sorted {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers (N): ");


int n = scanner.nextInt();

TreeSet<Integer> uniqueIntegers = new TreeSet<>();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
int integer = scanner.nextInt();
uniqueIntegers.add(integer);
}

System.out.println("Sorted unique integers:");


for (Integer integer : uniqueIntegers) {
System.out.print(integer + " ");
}
}
}

2.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class NumberDisplay extends JFrame {

private JTextField textField;


private JButton button;
private boolean running = false;
private int number = 1;

public NumberDisplay() {
setLayout(new FlowLayout());

textField = new JTextField(10);


add(textField);

button = new JButton("Start");


button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


if (!running) {
running = true;
button.setText("Stop");
Thread thread = new Thread(new NumberRunnable());
thread.start();
} else {
running = false;
button.setText("Start");
}
}
});
add(button);

setSize(300, 100);
setDefaultCloseOperation(EXIT_ON_CLOSE);
setVisible(true);
}

private class NumberRunnable implements Runnable {

public void run() {


while (running) {
SwingUtilities.invokeLater(new Runnable() {

public void run() {


textField.setText(String.valueOf(number));
}
});

try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

number = (number % 100) + 1;


}
}
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {

public void run() {


new NumberDisplay();
}
});
}
}
_______________________________________________________________________________
Slip 18
1.File 1
import java.util.Scanner;

class VowelDisplay implements Runnable {


private String str;

public VowelDisplay(String str) {


this.str = str;
}

public void run() {


for (char c : str.toCharArray()) {
if (isVowel(c)) {
System.out.println(c);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

private boolean isVowel(char c) {


String vowels = "aeiouAEIOU";
return vowels.indexOf(c) != -1;
}
}
File 2
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();

Thread thread = new Thread(new VowelDisplay(str));


thread.start();
}
}
___________________________________________________________________________________
____
Slip 19
1.
import java.util.LinkedList;
import java.util.Scanner;

public class Negativentegers {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of integers (N): ");


int n = scanner.nextInt();

LinkedList<Integer> integers = new LinkedList<>();

System.out.println("Enter " + n + " integers:");


for (int i = 0; i < n; i++) {
integers.add(scanner.nextInt());
}

System.out.println("Negative integers:");
for (Integer integer : integers) {
if (integer < 0) {
System.out.print(integer + " ");
}
}

scanner.close();
}
}

2.
___________________________________________________________________________
Slip 20
2.
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

class TempleDrawer extends JPanel implements Runnable {


private boolean drawing = false;

public TempleDrawer() {
setBackground(Color.WHITE);
setPreferredSize(new Dimension(800, 600));

JButton button = new JButton("Draw Temple");


button.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {


if (!drawing) {
drawing = true;
Thread thread = new Thread(TempleDrawer.this);
thread.start();
}
}
});

JFrame frame = new JFrame("Temple Drawing");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(this, BorderLayout.CENTER);
frame.add(button, BorderLayout.SOUTH);
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

public void run() {


drawTemple();
}

private void drawTemple() {


Graphics2D g2d = (Graphics2D) getGraphics();

g2d.setColor(Color.BLUE);
g2d.fillRect(200, 400, 400, 100);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

g2d.setColor(Color.GRAY);
g2d.fillRect(220, 300, 50, 100);
g2d.fillRect(530, 300, 50, 100);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

g2d.setColor(Color.DARK_GRAY);
g2d.fillOval(300, 200, 200, 200);

try {
Thread.sleep(1000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}

g2d.setColor(Color.BLACK);
g2d.fillRect(350, 450, 100, 50);

drawing = false;
}

public static void main(String[] args) {


SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new TempleDrawer();
}
});
}
}
_______________________________________________________________________
Slip 21
1.
import java.util.LinkedList;
import java.util.Iterator;
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of subjects: ");


int n = scanner.nextInt();
scanner.nextLine();

LinkedList<String> subjects = new LinkedList<>();

System.out.println("Enter " + n + " subject names:");


for (int i = 0; i < n; i++) {
String subject = scanner.nextLine();
subjects.add(subject);
}

System.out.println("\nSubjects:");
Iterator<String> iterator = subjects.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
scanner.close();
}
}

2.
class SharedBuffer {
private int value;
private boolean empty = true;

public synchronized void produce(int value) {


while (!empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
this.value = value;
empty = false;
notify();
}

public synchronized int consume() {


while (empty) {
try {
wait();
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
int value = this.value;
empty = true;
notify();
return value;
}
}

class Producer extends Thread {


private SharedBuffer sharedBuffer;

public Producer(SharedBuffer sharedBuffer) {


this.sharedBuffer = sharedBuffer;
}

public void run() {


for (int i = 1; i <= 10; i++) {
sharedBuffer.produce(i);
System.out.println("Produced: " + i);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}
class Consumer extends Thread {
private SharedBuffer sharedBuffer;

public Consumer(SharedBuffer sharedBuffer) {


this.sharedBuffer = sharedBuffer;
}

public void run() {


for (int i = 1; i <= 10; i++) {
int value = sharedBuffer.consume();
System.out.println("Consumed: " + value);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

public class ProducerConsumer {


public static void main(String[] args) {
SharedBuffer sharedBuffer = new SharedBuffer();
Producer producer = new Producer(sharedBuffer);
Consumer consumer = new Consumer(sharedBuffer);

producer.start();
consumer.start();
}
}
_________________________________________________________________________
Slip 23
1.
1.File 1
import java.util.Scanner;

class VowelDisplay implements Runnable {


private String str;

public VowelDisplay(String str) {


this.str = str;
}

public void run() {


for (char c : str.toCharArray()) {
if (isVowel(c)) {
System.out.println(c);
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
}
}

private boolean isVowel(char c) {


String vowels = "aeiouAEIOU";
return vowels.indexOf(c) != -1;
}
}
File 2
import java.util.Scanner;

public class Main {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter a string: ");
String str = scanner.nextLine();
scanner.close();

Thread thread = new Thread(new VowelDisplay(str));


thread.start();
}
}

2.
import java.util.LinkedList;
import java.util.Iterator;
import java.util.ListIterator;
import java.util.Scanner;

public class StudentNames {


public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter the number of students: ");


int n = scanner.nextInt();
scanner.nextLine();

LinkedList<String> studentNames = new LinkedList<>();

System.out.println("Enter " + n + " student names:");


for (int i = 0; i < n; i++) {
String name = scanner.nextLine();
studentNames.add(name);
}

System.out.println("\nStudent Names (using Iterator):");


Iterator<String> iterator = studentNames.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}

System.out.println("\nStudent Names (using ListIterator):");


ListIterator<String> listIterator = studentNames.listIterator();
while (listIterator.hasNext()) {
System.out.println(listIterator.next());
}

System.out.println("\nStudent Names (using ListIterator in reverse


order):");
while (listIterator.hasPrevious()) {
System.out.println(listIterator.previous());
}
scanner.close();
}
}
___________________________________________________________________________________
__________
Slip 28
2.
class MyThread extends Thread {
public MyThread(String name) {
super(name);
}

public void run() {


System.out.println("Currently executing thread: " +
Thread.currentThread().getName());
}
}

public class Main3 {


public static void main(String[] args) {
MyThread thread1 = new MyThread("Thread-1");
MyThread thread2 = new MyThread("Thread-2");
MyThread thread3 = new MyThread("Thread-3");

thread1.start();
thread2.start();
thread3.start();
}
}
___________________________________________________________________________________
____________________
Slip 29
2.
import java.util.LinkedList;

public class LinkedListExample {


public static void main(String[] args) {

LinkedList<Integer> linkedList = new LinkedList<>();

linkedList.add(10);
linkedList.add(20);
linkedList.add(30);
linkedList.add(40);
linkedList.add(50);

System.out.println("Initial LinkedList: " + linkedList);


linkedList.addFirst(5);
System.out.println("LinkedList after adding element at first position: " +
linkedList);

linkedList.removeLast();
System.out.println("LinkedList after deleting last element: " +
linkedList);
System.out.println("Size of LinkedList: " + linkedList.size());
}
}
___________________________________________________________________________________
_________________
Slip 30

You might also like