Ticker

6/recent/ticker-posts

Java

 1. Use Eclipse or Net bean platform and acquaint with the various menus. Create a test project, add a test class, and run it. See how you can use auto suggestions, auto fill. Try code formatter and code refactoring like renaming variables, methods, and classes. Try debug step by step with a small program of about 10 to 15 lines which contains at least one if else condition and a for loop.

Source code

import java.lang.System; 

import java.util.Scanner; 

class Sample_Program {

public static void main(String args[]) {

int i, count = 0, n;

// creating scanner object

Scanner sc = new Scanner(System.in);

// get input number from user System.out.print("Enter Any Number : "); n = sc.nextInt();

// logic to check prime or not

for (i = 1; i <= n; i++) {

if (n % i == 0) {

count++;

}

}

if (count == 2)

System.out.println(n + " is prime");

else

System.out.println(n + " is not prime");

}

}

2. Write a Java program that works as a simple calculator. Use a grid layout to arrange buttons for the digits and for the +, -,*, % operations. Add a text field to display the result. Handle any possible exceptions like divided by zero.

Source code

/*<applet code="Calculator.class" height=150 width=700> </applet>*/

import java.applet.*;

 import java.awt.*;

 import java.awt.event.*;

 import javax.swing.*;

public class Calculator extends Applet implements ActionListener

{ JTextField t1, t2, t3; JLabel l1, l2, l3; JButton b1, b2, b3, b4; JPanel p1, p2; public void init() {

p1 = new JPanel();

p2 = new JPanel();

p1.setBackground(Color.gray);

p2.setBackground(Color.gray); setBackground(Color.lightGray);

l1 = new JLabel("enter the first number");

p1.add(l1);

t1 = new JTextField(10);

p1.add(t1);

l2 = new JLabel("enter the second number");

p1.add(l2);

t2 = new JTextField(10);

p1.add(t2);

l3 = new JLabel("result");

p1.add(l3);

t3 = new JTextField(10);

p1.add(t3);

b1 = new JButton("add");

p2.add(b1);

b1.addActionListener(this);

b2 = new JButton("sub");

p2.add(b2);

b2.addActionListener(this);

b3 = new JButton("mul");

p2.add(b3);

b3.addActionListener(this);

b4 = new JButton("division");

p2.add(b4);

b4.addActionListener(this);

add(p1, BorderLayout.NORTH);

add(p2, BorderLayout.CENTER);

t1.setBackground(Color.yellow);

t2.setBackground(Color.yellow);

t3.setBackground(Color.yellow);

}

public void actionPerformed(ActionEvent ae) {

try {

if (ae.getSource() == b1) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int sum = x + y;

t3.setText(" " + sum);

}

if (ae.getSource() == b2) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int sub = x - y;

t3.setText(" " + sub);

}

if (ae.getSource() == b3) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int sub = x - y;

t3.setText(" " + sub);

}

if (ae.getSource() == b3) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int mul = x * y;

t3.setText(" " + mul);

}

if (ae.getSource() == b4) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int div = x / y;

t3.setText(" " + div);

}

} catch (Exception e) {

JOptionPane.showMessageDialog(null, e);

}

}

}

3. I) Develop an applet in Java that displays a simple message.

Source code

 import java.awt.*;

 import java.applet.*;

public class SimpleApplet extends Applet

{ public void paint(Graphics g) {

g.drawString("welcome to applets", 50, 50);

}

}

//<applet code="SimpleApplet.class" height=200 width=400></applet>

II) Develop an applet in Java that receives an integer in one text field, and computes its factorial Value and returns it in another text field, when the button named “Compute” is clicked.

Source code

import java.applet.*;

import java.awt.*;

import java.awt.event.*;

public class Factj extends Applet implements ActionListener

{ Label l1, l2; TextField t1, t2; Button b1, b2; public void init() {

l1 = new Label("Enter a value: ");

l2 = new Label("Result:");

t1 = new TextField(10);

t2 = new TextField(10);

b1 = new Button("Calculate");

b2 = new Button("Clear"); add(l1);

add(t1);

add(b1);

add(b2);

add(l2);

add(t2);

b1.addActionListener(this);

b2.addActionListener(this);


}

public void actionPerformed(ActionEvent ae) {

int n = Integer.parseInt(t1.getText());

int fact = 1;

if (ae.getSource() == b1) {

if (n == 0 || n == 1) {

fact = 1;

t1.setText(String.valueOf(fact));

} else {

for (int i = 1; i <= n; i++)

fact = fact * i;

}

t2.setText(String.valueOf(fact));

} else if (ae.getSource() == b2) { t1.setText("");

t2.setText("");

}

}

}

//<applet code="Factj.class" height=300 width=300></applet>

4. Write a Java program that creates a user interface to perform integer divisions. The user enters two numbers in the text fields, Num1 and Num2. The division of Num1 and Num 2 is displayed in the Result field when the Divide button is clicked. If Num1 or Num2 were not an integer, the program would throw a Number Format Exception. If Num2 were Zero, the program would throw an Arithmetic Exception. Display the exception in a message dialog box.

Source code

/*<applet code="Div.class" height=150 width=700> </applet>*/

import java.applet.*;

 import java.awt.*; 

import java.awt.event.*; 

import javax.swing.*;

public class Div extends Applet implements ActionListener

{ JTextField t1, t2, t3; JLabel l1, l2, l3; JButton b1; JPanel p1, p2; public void init() {

p1 = new JPanel();

p2 = new JPanel();

p1.setBackground(Color.gray);

p2.setBackground(Color.gray); setBackground(Color.lightGray);

l1 = new JLabel("enter the first number");

p1.add(l1);

t1 = new JTextField(10);

p1.add(t1);

l2 = new JLabel("enter the second number");

p1.add(l2);

t2 = new JTextField(10);

p1.add(t2);

l3 = new JLabel("result");

p1.add(l3);

t3 = new JTextField(10);

p1.add(t3);

b1 = new JButton("div");

p2.add(b1);

b1.addActionListener(this);

add(p1, BorderLayout.NORTH);

add(p2, BorderLayout.CENTER);

t1.setBackground(Color.yellow);

t2.setBackground(Color.yellow);

t3.setBackground(Color.yellow);

}

public void actionPerformed(ActionEvent ae) {

try {

if (ae.getSource() == b1) {

int x = Integer.parseInt(t1.getText());

int y = Integer.parseInt(t2.getText());

int div = x / y;

t3.setText(" " + div);

}

} catch (Exception e) {

JOptionPane.showMessageDialog(null, e);

}

}

}

5. Write a Java program that implements a multi-thread application that has three threads. First thread generates random integer every 1 second and if the value is even, second thread computes the square of the number and prints. If the value is odd, the third thread will print the value of cube of the number.

Source code

 import java.util.*;

class Even implements Runnable { public int x;

public Even(int x)

{ this.x = x;

}

public void run() {

System.out.println("new thread " + x + " is EVEN and square of " + x + " is :" + x * x);

}

}

class Odd implements Runnable {

public int x;

public Odd(int x)

{ this.x = x;

}

public void run() {

System.out.println("new thread " + x + " is ODD and cube of " + x + " is:" + x * x * x);

}

}

class A extends Thread

{ public void run() {

int num = 0;

Random r = new

Random(); try {

for (int i = 0; i < 5; i++) {

num = r.nextInt(100);

System.out.println("main thread and generated number is" + num); if (num % 2 == 0) {

Thread t1 = new Thread(new

Even(num)); t1.start();

} else {

Thread t2 = new Thread(new Odd(num));

t2.start();

}

Thread.sleep(1000);

System.out.println("............................");

}

} catch (Exception ex) { System.out.println(ex.getMessage());

}

}

}

public class Random1 {

public static void main(String args[]) {

A a = new A();

a.start();

}

}

6. Write a Java program for the following: Create a doubly linked list of elements. Delete a given element from the above list. Display the contents of the list after deletion.

Source code

 import java.io.*; 

import java.util.Scanner;

class linkedlist { int data; linkedlist prev; linkedlist next;

linkedlist(int value) {

this.data = value;

}

void display() {

System.out.println(data);

}

}

class linked {

public linkedlist fstnode, lastnode;

linked() {

fstnode = null;

lastnode = null;

}

/* Insert node at the beginning or create linked list */ void insert_front(int value) {

linkedlist node = new linkedlist(value);

if(fstnode == null) {

node.prev = node.next = null;

fstnode = lastnode = node;

System.out.println("Lined list created successfully!");

}

else {

node.prev = null;

node.next = fstnode;

fstnode.prev = node;

fstnode = node;

System.out.println("Node Inserted at the front of the Linked list!");

}

}

/* Insert node at the end or create linked list */

void insert_end(int value) {

linkedlist node = new linkedlist(value);

if(fstnode == null) {

node.prev = node.next = null;

fstnode = lastnode = node;

System.out.println("Lined list created successfully!");

}

else {

node.next = null;

node.prev = lastnode;

lastnode.next = node;

lastnode = node;

System.out.println("Node Inserted at the end of the Linked list!");

}

}

/* Delete node from linked list */

void delete() {

int count = 0, number, i;

linkedlist node, node1, node2;

Scanner input = new Scanner(System.in);

for(node = fstnode; node != null; node = node.next)

count++;

display();

node = node1 = node2 = fstnode;

System.out.println(count+" nodes available here!");

System.out.println("Enter the node number which you want to delete from

ascending order list:");

number = Integer.parseInt(input.nextLine());

if(number != 1) {

if(number < count && number > 0) {

for(i = 2; i <= number; i++)

node = node.next;

for(i = 2; i <= number-1; i++)

node1 = node1.next;

for(i = 2; i <= number+1; i++)

node2 = node2.next;

node2.prev = node1;

node1.next = node2;

node.prev = null;

node.next = null;

node = null;

}

else if(number == count) {

node = lastnode;

lastnode = node.prev;

lastnode.next = null;

node = null;

}

else

System.out.println("Invalid node number!\n");

}

else {

node = fstnode;

fstnode = node.next;

fstnode.prev = null;

node = null;

}

System.out.println("Node has been deleted successfully!\n");

}

/* Display linked list */

void display() {

linkedlist node = fstnode;

System.out.println("List of node in Ascending order!"); while(node != null) {

node.display();

node = node.next;

}

node = lastnode;

System.out.println("List of node in Descending

order!"); while(node != null) {

node.display();

node = node.prev;

}

}

}

class doublylinkedlist {

public static void main(String args[ ]) {

linked list = new linked();

Scanner input = new Scanner(System.in);

int op = 0;

while(op != 5) {

System.out.println("1. Insert at front 2. Insert at back 3. Delete 4. Display

5. Exit");

System.out.println("Enter your choice:");

op = Integer.parseInt(input.nextLine());

switch(op) {

case 1:

System.out.println("Enter the positive value for Linked

list:");

list.insert_front(Integer.parseInt(input.nextLine())); break;

case 2:

System.out.println("Enter the positive value for Linked

list:");

list.insert_end(Integer.parseInt(input.nextLine())); break;

case 3:

list.delete();

break;

case 4:

list.display();

break;

case 5:

System.out.println("Bye Bye!");

System.exit(0);

break;

default:

System.out.println("Invalid choice!");

}

}

}

}

7. Write a Java program that simulates a traffic light. The program lets the user select one of three lights: red, yellow, or green with radio buttons. On selecting a button, an appropriate message with “Stop” or “Ready” or “Go” should appear above the buttons in selected color. Initially, there is no message shown.

Source code

 import java.applet.*;

 import java.awt.*;

 import java.awt.event.*;

/*<applet code="Signals.class" width=400 height=250></applet>*/ public class Signals extends Applet implements ItemListener

{

String msg=""; Checkbox stop,ready,go; CheckboxGroup cbg; public void init()

{

cbg = new CheckboxGroup();

stop = new Checkbox("Stop", cbg, false); ready = new Checkbox("Ready", cbg, false); go= new Checkbox("Go", cbg, false); add(stop);

add(ready);

add(go);

stop.addItemListener(this);

ready.addItemListener(this);

go.addItemListener(this);

}

public void itemStateChanged(ItemEvent ie)

{

repaint();

}

public void paint(Graphics g)

{

msg=cbg.getSelectedCheckbox().getLabel();

g.drawOval(165,40,50,50);

g.drawOval(165,100,50,50);

g.drawOval(165,160,50,50);

if(msg.equals("Stop"))

{

g.setColor(Color.red);

g.fillOval(165,40,50,50);

}

else if(msg.equals("Ready"))

{

g.setColor(Color.yellow);

g.fillOval(165,100,50,50);

}

else

{

g.setColor(Color.green);

g.fillOval(165,160,50,50);

}

}

}

8. Write a Java program to create an abstract class named Shape that contains two integers and an empty method named print Area (). Provide three classes named Rectangle, Triangle, and Circle such that each one of the classes extends the class Shape. Each one of the classes contains only the method print Area () that prints the area of the given shape.

Source code

import java.util.*; 

abstract class Shape {

public int x, y;

public abstract void printArea();

}

class Rectangle1 extends Shape

{ public void printArea() {

float area;

area = x * y;

System.out.println("area of rectangle is:" + area);

}

}

class Triangle extends Shape {

public void printArea() {

float area;

area = (x * y) / 2;

System.out.println("Area of Triangle is:" + area);

}

}

class Circle extends Shape {

public void printArea() {

float area;

area = (22 * x * x) / 7; System.out.println("area

of circle is:" + area);

}

}

public class Shapes {

public static void main(String args[]) {

Scanner sc = new Scanner(System.in);

System.out.println("enter values :"); int

x1 = sc.nextInt();

int y1 = sc.nextInt();

Rectangle1 r = new

Rectangle1(); r.x = x1;

r.y = y1;

r.printArea();

Triangle t = new Triangle();

t.x = x1;

t.y = y1;

t.printArea();

Circle c = new Circle();

c.x = x1;

c.y = y1;

c.printArea();

}

}

9. Suppose that a table named Table.txt is stored in a text file. The first line in the file is the header, and the remaining lines correspond to rows in the table. The elements are separated by commas. Write a java program to display the table using Labels in Grid Layout.

Source code 

import java.io.*; 

import java.util.*; 

import java.awt.*; 

import java.awt.event.*; 

import javax.swing.*;

import javax.swing.event.*;

class A extends JFrame { public A() {

setSize(600, 600);

GridLayout g = new GridLayout(0, 4); setLayout(g);

try {

FileInputStream fin = new FileInputStream("F:\\Student.txt"); Scanner sc = new Scanner(fin).useDelimiter(",");

String[] arrayList; String a;

while (sc.hasNextLine()) { a = sc.nextLine(); arrayList = a.split(","); for (String i: arrayList) {

add(new Label(i));

}

}

} catch (Exception ex) {} this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); pack();

setVisible(true);

}

}

public class TableData {

public static void main(String[] args) {

A a = new A();

}

}

Explanation:

Create one text document

Save as “Student.txt”

Copy the path of “Student.txt” file

In program replace the line ("F:\\Student.txt"); with copied path

Example: C:\\Users\\MRCE-16\\Desktop\\ Student.txt (convert all single backslash to double back slash)

Student.txt contents

10. Write a Java program that handles all mouse events and shows the event name at the center of the window when a mouse event is fired (Use Adapter classes).

Source code

import javax.swing.*; 

import java.awt.*;

import javax.swing.event.*; 

import java.awt.event.*;

class A extends JFrame implements MouseListener { JLabel l1;

public A() { setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setSize(400, 400);

setLayout(new FlowLayout()); l1 = new JLabel();

Font f = new Font("verdana", Font.BOLD, 20); l1.setFont(f);

l1.setForeground(Color.blue);

l1.setAlignmentX(Component.CENTER_ALIGNMENT);

l1.setAlignmentY(Component.CENTER_ALIGNMENT); add(l1);

addMouseListener(this);

setVisible(true);

}

public void mouseExited(MouseEvent m) { l1.setText("Mouse Exited");

}

public void mouseEntered(MouseEvent m) { l1.setText("Mouse Entered");

}

public void mouseReleased(MouseEvent m) { l1.setText("Mouse Released");

}

public void mousePressed(MouseEvent m)

{ l1.setText("Mouse Pressed");

}

public void mouseClicked(MouseEvent m) {

l1.setText("Mouse Clicked");

}

}

public class MEvent {

public static void main(String args[]) {

A a = new A();

}

}

11. Write a Java program that loads names and phone numbers from a text file where the data is organized as one line per record and each field in a record are separated by a tab (\t). It takes a name or phone number as input and prints the corresponding other value from the hash table (hint: use hash tables).

Source code 

import java.util.*; 

import java.io.*;

public class PhoneDictionary {

public static void main(String[] args) { try {

FileInputStream fs = new FileInputStream("F:\\emp.txt"); Scanner sc = new Scanner(fs).useDelimiter("\\s+");

Hashtable < String, String > ht = new Hashtable < String, String > (); String[] arrayList;

String a;

System.out.println("Welcome To PhoneDirectory"); System.out.println("Phone numbers are");

while (sc.hasNext()) { a = sc.nextLine(); arrayList = a.split("\\s+"); ht.put(arrayList[0], arrayList[1]); System.out.println(arrayList[0] + ":" + arrayList[1]);

}

System.out.println("Welcome To

PhoneDirectory"); System.out.println("MENU");

System.out.println("1.Search by Name");

System.out.println("2.Search by Mobile");

System.out.println("3.Exit");

String opt = "";

String name, mobile;

Scanner s = new Scanner(System.in);

while (opt != "3") {

System.out.println("Enter Your Option (1,2,3):

"); opt = s.next();

switch (opt) {

case "1":

System.out.println("Enter

Name"); name = s.next();

if (ht.containsKey(name)) {

System.out.println("Mobile is " +

ht.get(name)); } else {

System.out.println("Not Found");

}

break;

case "2":

System.out.println("Enter mobile");

mobile = s.next();

if (ht.containsValue(mobile)) {

for (Map.Entry e: ht.entrySet()) {

if (mobile.equals(e.getValue())) {

System.out.println("Name is " + e.getKey());

}

}

} else {

System.out.println("Not Found");

}

break;

case "3":

opt = "3";

System.out.println("Menu Successfully Exited"); break;

default:

System.out.println("Choose Option betwen 1 and Three"); break;

}

}

} catch (Exception ex) {

System.out.println(ex.getMessage());

}

}

}

Explanation

Create one text document

Save as “emp.txt”

Copy the path of “emp.txt” file by right clicking on file -> properties In program replace the line ("F:\\emp.txt"); with copied path

Example: C:\\Users\\MRCE-16\\Desktop\\ emp.txt (convert all single backslash to double back slash)

12. Write a Java program that correctly implements the producer – consumer problem using the concept of interthread communication.

Source code

public class ProducerConsumerTest { public static void main(String[] args) {

CubbyHole c = new CubbyHole(); 

Producer p1 = new Producer(c, 1); 

Consumer c1 = new Consumer(c, 1); 

p1.start();

c1.start();

}

}

class CubbyHole { private int contents;

private boolean available = false;

public synchronized int get() {

while (available == false) {

try {

wait();

} catch (InterruptedException e) {}

}

available = false;

notifyAll();

return contents;

}

public synchronized void put(int value) {

while (available == true) {

try {

wait();

} catch (InterruptedException e) { }

}

contents = value;

available = true;

notifyAll();

}

}

class Consumer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Consumer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

int value = 0;

for (int i = 0; i < 10; i++) {

value = cubbyhole.get();

System.out.println("Consumer #" + this.number + " got: " + value);

}

}

}

class Producer extends Thread {

private CubbyHole cubbyhole;

private int number;

public Producer(CubbyHole c, int number) {

cubbyhole = c;

this.number = number;

}

public void run() {

for (int i = 0; i < 10; i++) {

cubbyhole.put(i);

System.out.println("Producer #" + this.number + " put: " + i); try {

sleep((int)(Math.random() * 100));

} catch (InterruptedException e) { }

}

}

}

13. Write a Java program to list all the files in a directory including the files present in all its subdirectories.

Source code

import java.io.File;

public class Fdir

{

static void RecursivePrint(File[] arr,int index,int level)

{

// terminate condition if(index == arr.length)

return;

// tabs for internal levels for (int i = 0; i < level; i++)

System.out.print("\t");

// for files if(arr[index].isFile())

System.out.println(arr[index].getName());

// for sub-directories

else if(arr[index].isDirectory())

{

System.out.println("[" + arr[index].getName() + "]");

// recursion for sub-directories RecursivePrint(arr[index].listFiles(), 0, level + 1);

}

// recursion for main directory RecursivePrint(arr,++index, level);

}

// Driver Method

public static void main(String[] args)

{

// Provide full path for directory(change accordingly)

String maindirpath = "C:\\kau";

// File object

File maindir = new File(maindirpath);

if(maindir.exists() && maindir.isDirectory())

{

// array for files and sub-directories

// of directory pointed by maindir File arr[] = maindir.listFiles();

System.out.println("**********************************************"); System.out.println("Files from main directory : " + maindir); System.out.println("**********************************************");

// Calling recursive method RecursivePrint(arr,0,0);

}

}

}



14. Write a Java program that implements Quick sort algorithm for sorting a list of names in ascending order

Source code

import java.util.Scanner;

class QuickSort1

{

public static void main(String args[])

{

String temp;

Scanner SC = new Scanner(System.in);

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

int N= SC.nextInt();

SC.nextLine(); //ignore next line character

String names[] = new String[N];

System.out.println("Enter names: ");

for(int i=0; i<N; i++)

{

System.out.print("Enter name [ " + (i+1) +" ]: ");

names[i] = SC.nextLine();

}

//sorting strings

for(int i=0; i<5; i++)

{

for(int j=1; j<5; j++)

{

if(names[j-1].compareTo(names[j])>0)

{

temp=names[j-1];

names[j-1]=names[j];

names[j]=temp;

}

}

}

System.out.println("\nSorted names are in Ascending Order: ");

for(int i=0;i<N;i++)

{

System.out.println(names[i]);

}

}

}

15. Write a Java program that implements Bubble sort algorithm for sorting in descending order and also shows the number of interchanges occurred for the given set of integers.

Source code

import java.io.*; 

import java.util.*; 

class BubbleSort {

public static void main(String[] args) throws IOException, ArrayIndexOutOfBoundsException {

int num;

System.out.println("BUBBLE SORTING");

 System.out.println("\n enter the number of elements"); 

Scanner input = new Scanner(System.in); num = input.nextInt();

BubbleImp imp = new BubbleImp(num); 

System.out.println("\n enter the elements to sort"); for (int i = 0; i < num; i++)

imp.A[i] = input.nextInt(); imp.bubblesort(num); imp.display(num);

}

}

class BubbleImp

{ public int n; public int[] A;

public BubbleImp(int MAX) { A = new int[MAX];

}

public void bubblesort(int n)

{ int temp; int swap = 0;

for (int i = 0; i <= n - 1; i++) { for (int j = 0; j < n - 1 - i; j++) {

if (A[j] < A[j + 1]); { temp = A[j]; A[j]

= A[j + 1]; A[j +

1] = temp;

System.out.println("Array element at" + j + "position" + A[j]); 

System.out.println("Array element at" + (j + 1) + "position" + A[j + 1]); 

swap++;

}

}

}

System.out.println("number of interchanges are:" + (swap));

}

public void display(int n) {

System.out.println("\n the sorted list is...\n");

for (int i = 0; i > n; i++)

System.out.println(" " + A[i]);

}

}

Post a Comment

0 Comments