[Go to site: main page, start]

0% found this document useful (0 votes)
3 views41 pages

Java Program Lab Manual

The document contains multiple Java programs demonstrating various concepts such as inheritance, dynamic binding, interface implementation, applets, exception handling, unique number input, threading, file splitting, area calculation, GUI for exams, save dialog, and URL connection examination. Each section includes a program followed by its output. The programs serve as practical examples for learning Java programming techniques.

Uploaded by

saifizaid909
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)
3 views41 pages

Java Program Lab Manual

The document contains multiple Java programs demonstrating various concepts such as inheritance, dynamic binding, interface implementation, applets, exception handling, unique number input, threading, file splitting, area calculation, GUI for exams, save dialog, and URL connection examination. Each section includes a program followed by its output. The programs serve as practical examples for learning Java programming techniques.

Uploaded by

saifizaid909
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

1.

Write Java program(s) on use of inheritance, preventing inheritance using


final, abstract classes.

PROGRAM:

class Animal { void sound(){ [Link]("Animal makes


sound");}} class Dog extends Animal { void sound(){
[Link]("Dog barks");}} final class FinalClass { void
show(){ [Link]("Final class");}} abstract class Shape
{ abstract void draw(); }
class Circle extends Shape { void draw(){
[Link]("Circle");}} public class
InheritanceDemo { public static void main(String[] args){
Dog d=new Dog(); [Link]();
Circle c=new Circle(); [Link]();
}
}

OUTPUT:

Page 1 of 40
[Link] Java program(s) overriding. on dynamic binding, differentiating
method overloading

PROGRAM:

class Parent {
void show(){ [Link]("Parent
show"); } void display(int a){
[Link]("Int: "+a); } void
display(String s){ [Link]("String:
"+s); }
}
class Child extends Parent { void
show(){ [Link]("Child
show"); }
}
public class
DynamicBindingDemo { public
static void main(String[] args){
Parent p=new Child();
[Link]();
[Link](10);
[Link]("Hello");
}
}

OUTPUT:

Page 2 of 40
[Link] Java program(s) on ways of implementing interface.

Program:

interface Printable {
void print();
}

// 1) Class implements interface


class Printer implements Printable {
public void print(){ [Link]("Printer printing..."); }
}
// 2) Anonymous class
class Demo {
void anonymousPrintable(){
Printable anon = new Printable(){
public void print(){ [Link]("Anonymous printing..."); }
};
[Link]();
}
}

// 3) Lambda (functional interface)


@FunctionalInterface
interface Adder {
intadd(int a, int b);

}
publicclass InterfaceDemo
public static {
void main(String[] args){
Printable p = new Printer();
[Link]();

new Demo().anonymousPrintable();

Adder lambda = (x,y) -> x + y;


[Link]("Lambda add result: " + [Link](3,4));
}
}

Page 3 of 40
OUTPUT:

Page 4 of 40
4. Write a program for the following
a. Develop an applet that displays a simple message

PROGRAM: import
[Link]; import
[Link];

publicclass SimpleApplet extends Applet {


public void paint(Graphics g){
[Link]("Hello from SimpleApplet!", 20, 20);
}
}
OUTPUT:

Page 5 of 40
b. Develop an applet for waving a Flag using Applets and Threads.
PROGRAM:
// File: [Link]
import [Link];
import [Link].*;
public class FlagApplet extends Applet implements Runnable {

private Thread animator;


private int offset = 0;
public void init(){ setBackground([Link]); }
public void start(){

animator = new Thread(this);


[Link]();
}
public void stop(){
animator = null; // thread stops
}
public void run(){
Thread me = [Link]();
while(animator == me){
offset = (offset + 5) % getWidth();
repaint();
try { [Link](100); } catch (InterruptedException e) { break; }
}
}
public void paint(Graphics g){
int w = getWidth(), h = getHeight();
// draw flag pole

Page 6 of 40
[Link]([Link]);
[Link](10, 10, 10, h - 20);
//draw waving rectangle (simple)
intflagWidth = 120, flagHeight = 60;
intx = 30 + (int)(10 * [Link](offset * [Link] / 180.0));
[Link]([Link]);
[Link](x, 30, flagWidth, flagHeight);
//add stripes to give wave impression
[Link]([Link]);
for(int i=1;i<4;i++){

[Link](x, 30 + i*(flagHeight/4), x+flagWidth, 30 + i*(flagHeight/4));


}
}
}
OUTPUT:

Page 7 of 40
[Link] Java program(s) which uses the exception handling features of the
language, creates exceptions and handles them properly, uses the predefined
ownexceptions.

PROGRAM:

//File: [Link]
class MyCustomException extends Exception {
public MyCustomException(String msg){ super(msg); }
}
public class ExceptionDemo {
static void test(int a) throws MyCustomException {
if(a < 0) throw new MyCustomException("Negative not allowed: " + a);
if(a == 0) throw new ArithmeticException("Divide by zero example
(predefined)");
[Link]("Value OK: " + a);
}
public static void main(String[] args){
int[] tests = {5, 0, -3};
for(int val : tests){
try {
test(val);
} catch (MyCustomException e){
[Link]("Caught custom: " + [Link]());
} catch (RuntimeException e){
[Link]("Caught runtime: " + [Link]());
} finally {
[Link]("Finally block executed for " + val);
}

Page 8 of 40
}
}
}

OUTPUT:

Page 9 of 40
6. Write java program that inputs 5 numbers, each between 10 and 100
inclusive. As each number is read display it only if it’s not a duplicate of any
number already read. Display the complete set of unique values input after the
user enters each new value. UNIQUE NUMBERS (10–100).

PROGRAM:

//File:[Link]
[Link].*;

publicclassUniqueNumbers {
publicstaticvoidmain(String[] args){
Scannersc=new Scanner([Link]);
Set<Integer>unique = new LinkedHashSet<>();
[Link]("Enter 5 numbers between 10 and 100 inclusive:");
int count=0;
while(count<5){
[Link]("Number " + (count+1) + ": ");
if(![Link]()){
[Link]("Please enter an integer.");
[Link]();
continue;
}
intn=[Link]();
if(n<10||n>100){
[Link]("Out of range. Try again.");
continue;
}
if([Link](n)){
[Link](n + " is duplicate; not added.");
}else {
[Link](n);
[Link](n + " added.");
}

Page 10 of 40
[Link]("Current unique set: " + unique);
count++;
}
[Link]();
}
}

OUTPUT:

Page 11 of 40
7. Write Java program(s) on creating multiple threads, assigning priority to
threads, synchronizing threads, suspend and resume threads.

PROGRAM:

//File:[Link]
classMyWorker implements Runnable {
privatefinalString name;
privatevolatile boolean suspended = false;
publicMyWorker(String name){ [Link] = name; }

publicvoidrun(){
try{
for(inti=1;i<=5;i++){
synchronized(this){
while(suspended) wait(); // custom suspend
}
[Link](name + " working: step " + i);
[Link](200);
}
}catch(InterruptedException e){
[Link](name + " interrupted");
}
}
publicvoidsuspendThread(){
suspended = true;
}
publicsynchronized void resumeThread(){
suspended = false;
notify();
}
}
publicclassThreadDemo {
publicstaticvoid main(String[] args) throws Exception {

Page 12 of 40
MyWorker w1 = new MyWorker("Worker-1");
MyWorker w2 = new MyWorker("Worker-2"); Thread t1
= new Thread(w1); Thread t2 = new Thread(w2);
[Link](Thread.MAX_PRIORITY); // high priority
[Link](Thread.MIN_PRIORITY); // low priority
[Link](); [Link]();

[Link](500);
[Link]("Suspending Worker-1");
[Link]();

[Link](700);
[Link]("Resuming Worker-1");
[Link]();

[Link]();
[Link]();
[Link]("All threads finished.");
}
}

Page 13 of 40
OUTPUT:

Page 14 of 40
8. Write a java program to split a given text file into n parts. Name each part as
the name of the original file followed by. part where n is the sequence number
of the part file.
PROGRAM:
// File: [Link]
import [Link].*;
import [Link].*;

publicclassFileSplitter {
publicstaticvoidsplitFile(File inputFile, int parts) throws IOException {
longtotal=[Link]();
longpartSize=total / parts;
try(BufferedInputStream bis = new BufferedInputStream(new
FileInputStream(inputFile))) {
Stringbase=[Link]();
for(inti=1;i<= parts; i++) {
StringpartName = base + ".part" + i;
try(BufferedOutputStream bos = new BufferedOutputStream(new
FileOutputStream(partName))) {
longbytesToWrite = (i == parts) ? Long.MAX_VALUE : partSize;
byte[]buffer = new byte[4096];
longwritten = 0;
int read;
while((read = [Link](buffer)) != -1) {
if(i!=parts && written + read > bytesToWrite) {
inttoWrite = (int)(bytesToWrite - written);
[Link](buffer, 0, toWrite);

written += toWrite;

Page 15 of 40
break;
}else {
[Link](buffer, 0, read);
written += read;
}
}
}
}
}
}

publicstaticvoid main(String[] args) {


if([Link] < 2) {
[Link]("Usage: java FileSplitter <inputfile> <parts>");
return;
}
Fileinput=new File(args[0]);
intparts=[Link](args[1]);
try{

splitFile(input, parts);
[Link]("File split into " + parts + " parts.");
}catch(IOException e) {
[Link]();
}
}
}

Page 16 of 40
OUTPUT:

Page 17 of 40
9. Write a java program to create a super class called Figure that receives the
dimensions of two dimensional objects. It also defines a method called area
that computes the area of an object. The program derives two subclasses from
Figure. The first is Rectangle and second is Triangle. Each of the sub classes
override area () so that it returns the area of a rectangle and triangle
respectively.
PROGRAM:
// File: [Link]
class Figure {

double dim1, dim2;


Figure(double d1, double d2){ dim1 = d1; dim2 = d2; }
double area(){ return 0; }
}

class Rectangle extends Figure {


Rectangle(double l, double b){ super(l, b); }
@Override
double area(){ return dim1 * dim2; }
}

class Triangle extends Figure {


Triangle(double base, double height){ super(base, height); }
@Override
double area(){ return 0.5 * dim1 * dim2; }
}

public class FigureDemo {


public static void main(String[] args){
Figure r = new Rectangle(5, 4);

Page 18 of 40
Figure t = new Triangle(6, 3);
[Link]("Rectangle area: " + [Link]());
[Link]("Triangle area: " + [Link]());
}
}
OUTPUT:

Page 19 of 40
10. Write a java program that allows conduction of object type examination
containing multiple choice questions, and true/false questions. At the end of
the examination when the user clicks a button the total marks have to be
displayed in the form of the message.
PROGRAM:
// File: [Link]
import [Link].*;
import [Link].*;
import [Link].*;

public class ExamGUI extends JFrame {


private JRadioButton q1a, q1b, q1c;
private JCheckBox q2a, q2b, q2c;
private JRadioButton tfTrue, tfFalse;
public ExamGUI(){

setTitle("Simple Exam");
setDefaultCloseOperation(EXIT_ON_CLOSE);
setLayout(new GridLayout(0,1));
// Q1 - single choice
add(new JLabel("Q1. Which is a JVM language?"));
ButtonGroup g1 = new ButtonGroup();
q1a = new JRadioButton("Python");
q1b = new JRadioButton("Java");
q1c = new JRadioButton("C++");
[Link](q1a); [Link](q1b); [Link](q1c);
add(q1a); add(q1b); add(q1c);
// Q2 - multi choice (example)
add(new JLabel("Q2. Select OOP languages (multiple):"));

Page 20 of 40
q2a = new JCheckBox("Java");
q2b = new JCheckBox("C");
q2c = new JCheckBox("C++");
add(q2a); add(q2b); add(q2c);
// Q3 - True/False
add(new JLabel("Q3. 'int' is a class in Java. True/False?"));
ButtonGroup g3 = new ButtonGroup();
tfTrue = new JRadioButton("True");
tfFalse = new JRadioButton("False");
[Link](tfTrue); [Link](tfFalse);
add(tfTrue); add(tfFalse);
JButton submit = new JButton("Submit");
[Link](e -> calculate());
add(submit);
pack();
setVisible(true);

}
private void calculate(){
int score = 0; if ([Link]()) score += 5; // correct if
([Link]()) score += 2; if ([Link]()) score += 2; if
(![Link]()) score += 0; // C is not OOP in the classic sense if
([Link]()) score += 3;
[Link](this, "Total Marks: " + score);

}
public static void main(String[] args){ [Link](ExamGUI::new); }

Page 21 of 40
}
OUTPUT:

Page 22 of 40
11. Write a java program that creates dialog box which is similar to the save
dialog box of the Microsoft windows or any word processor of your choice.
PROGRAM:
[Link].*;
[Link].*;
[Link];
publicclassSaveDialogDemo {

publicstatic void main(String[] args){


[Link](() -> {
JFrame f = new JFrame("Save Dialog Demo");
[Link](JFrame.EXIT_ON_CLOSE);
JButton btn = new JButton("Save As...");
[Link](e -> {

JFileChooser chooser = new JFileChooser();


[Link]("Save File As");
intchoice = [Link](f);
if(choice == JFileChooser.APPROVE_OPTION){

File selected = [Link]();


[Link](f, "Would save to: " +
[Link]());
}
});
[Link]().add(btn);
[Link]();
[Link](true);
});
}
}

Page 23 of 40
OUTPUT:

Page 24 of 40
12. Write a Java program to create aURLConnection and use it to examine the
documents properties and content.
PROGRAM:
// File: [Link]
import [Link].*;
import [Link].*;

public class URLConnectionDemo {


public static void main(String[] args) {
if ([Link] == 0) {
[Link]("Usage: java URLConnectionDemo <url>");
return;
}
try {
URL url = new URL(args[0]);
URLConnection conn = [Link]();
[Link]();
[Link]("Content-Type: " + [Link]());
[Link]("Content-Length: " + [Link]());
[Link]("Last-Modified: " + [Link]());
[Link]("Header Fields:");
[Link]().forEach((k,v) -> [Link](k + ": " + v));
// Read a bit of content
try (BufferedReader br = new BufferedReader(new
InputStreamReader([Link]()))) {
[Link]("\n---- Content (first 10 lines) ----");
for (int i=0;i<10;i++){
String line = [Link]();

Page 25 of 40
if (line == null) break;
[Link](line);
}
}
}catch(Exception e) {
[Link]();
}
}
}

OUTPUT:

Page 26 of 40
13. Write a Java program that correctly implements producer consumer
problem using the concept of inter thread communication.
PROGRAM:
// File: [Link]
import [Link].*;

classDrop {
private final LinkedList<Integer> buffer = new LinkedList<>();
private final int capacity;
public Drop(int capacity){ [Link] = capacity; }

public synchronized void put(int value) throws InterruptedException {


while([Link]() == capacity) wait();
[Link](value);
notifyAll();
}
public synchronized int take() throws InterruptedException {
while([Link]()) wait();
int val = [Link]();
notifyAll(); return val;

}
}

classProducer implements Runnable {


private final Drop drop;
public Producer(Drop d){ drop = d; }
public void run(){

Page 27 of 40
try{
for(int i=1;i<=10;i++){
[Link](i);
[Link]("Produced: " + i);
[Link](100);
}
}catch (InterruptedException e) {}
}
}

classConsumer implements Runnable {


privatefinal Drop drop;
publicConsumer(Drop d){ drop = d; }
publicvoid run(){
try{
for(int i=1;i<=10;i++){
int val = [Link]();
[Link]("Consumed: " + val);
[Link](150);
}
}catch (InterruptedException e) {}
}
}

publicclass ProducerConsumer {
publicstatic void main(String[] args){
Dropdrop = new Drop(3);

Page 28 of 40
new Thread(new Producer(drop)).start();
new Thread(new Consumer(drop)).start();
}
}

OUTPUT:

Page 29 of 40
14. Write a Java program that checks whether a given string is a palindrome or
not. Ex: MADAM is a palindrome?
PROGRAM: public class Palindrome {
public static void
main(String[] a){
String s="MADAM";
[Link]([Link](new
StringBuilder(s).reverse().toString())?"Palindrome":"Not");
}
}

OUTPUT:

Page 30 of 40
15. Write Java program to find prime numbers between 1 to n.
PROGRAM:
// File:[Link]
[Link].*;
publicclassPrimesToN {
publicstaticboolean isPrime(int n){
if(n<=1)returnfalse;
if(n<=3)returntrue;
if(n%2==0)return false;
for(inti=3;i*i<=n;i+=2) if(n % i == 0) return false;
returntrue;

}
publicstaticvoidmain(String[] args){
Scannersc=new Scanner([Link]);
[Link]("Enter n: ");
intn=[Link]();
[Link]("Primes between 1 and " + n + ":");
for(inti=2;i<=n;i++) if(isPrime(i)) [Link](i + " ");
[Link]();
[Link]();

}
}
OUTPUT:

Page 31 of 40
16. Write a java program that prints all real and imaginary solutions to the
quadratic equation ax2+bx+c=0. Read in a, b, c and use the quadratic formula.
PROGRAM:
// File: [Link]
import [Link].*;

public class QuadraticSolver {


public static void main(String[] args){
Scanner sc = new Scanner([Link]);
[Link]("Enter a b c: "); double
a = [Link](); double b =
[Link](); double c =
[Link](); if(a == 0){

[Link]("Not a quadratic equation.");


} else {
double disc = b*b - 4*a*c;
if(disc > 0){
double r1 = (-b + [Link](disc)) / (2*a);
double r2 = (-b - [Link](disc)) / (2*a);
[Link]("Real roots: " + r1 + ", " + r2);
} else if(disc == 0){
double r = -b / (2*a);
[Link]("One real root: " + r);
} else {
double real = -b / (2*a);
double imag = [Link](-disc) / (2*a);

Page 32 of 40
[Link]("Complex roots: " + real + " + " + imag + "i and " + real +
"-"+imag + "i");
}
}
[Link]();
}
}

OUTPUT:

Page 33 of 40
17. Write a Java program for sorting a given list of names in ascending order.
PROGRAM:
// File:[Link]
[Link].*;
publicclassSortNames {
publicstaticvoidmain(String[] args){
Scannersc=new Scanner([Link]);
[Link]("How many names? ");
intn=[Link](); [Link]();
List<String>names = new ArrayList<>();
for(inti=0;i<n;i++){

[Link]("Name " + (i+1) + ": ");


[Link]([Link]());
}
[Link](names, String.CASE_INSENSITIVE_ORDER);
[Link]("Sorted names:");
[Link]([Link]::println);
[Link]();

}
}

OUTPUT:

Page 34 of 40
18. Write a java program to accept a string from user and display number of
vowels, consonants, digits and special characters present in each of the
words of the given text.
PROGRAM:
[Link].*;
publicclassCharCountPerWord {
publicstaticvoidmain(String[] args){
Scannersc=new Scanner([Link]);
[Link]("Enter a line of text:");
Stringline=[Link]();
String[]words=[Link]("\\s+");
for(Stringw:words){

intvowels=0,cons=0, digits=0, special=0;


for(charch:[Link]()){
if([Link](ch)) digits++;
elseif([Link](ch)){
charc=[Link](ch);
if("aeiou".indexOf(c) >= 0) vowels++;
elsecons++;
}elsespecial++;
}
[Link]("Word: '%s' -> vowels:%d, consonants:%d, digits:%d,
special:%d%n",
w,vowels, cons, digits, special);
}
[Link]();
}

Page 35 of 40
OUTPUT:

Page 36 of 40
19. Write a java program to read the time intervals (HH:MM) and to compare
system time if the system time between your time intervals print correct time
and exit else try again to repute the same thing. By using StringToknizer class.
PROGRAM:
// File: [Link]
import [Link].*;
import [Link].*;

publicclass TimeIntervalChecker {
publicstatic int minutesOfDay(int hh, int mm){ return hh*60 + mm; }

publicstatic void main(String[] args) throws Exception {


Scanner sc = new Scanner([Link]);
[Link]("Enter start time (HH:MM): ");
String s1 = [Link]();
[Link]("Enter end time (HH:MM): ");
String s2 = [Link]();

StringTokenizer t1 = new StringTokenizer(s1, ":");


StringTokenizer t2 = new StringTokenizer(s2, ":");
intsh = [Link]([Link]());
intsm = [Link]([Link]());
inteh = [Link]([Link]());
intem = [Link]([Link]());
intstartMin = minutesOfDay(sh, sm);
intendMin = minutesOfDay(eh, em);

Calendar cal = [Link]([Link]());

Page 37 of 40
intnowMin = [Link](Calendar.HOUR_OF_DAY) * 60 +
[Link]([Link]);
[Link]("System time: " + [Link]("%02d:%02d",
[Link](Calendar.HOUR_OF_DAY), [Link]([Link])));

boolean inside;
if(startMin <= endMin) {
inside = (nowMin >= startMin && nowMin <= endMin);
}else { // interval spans midnight
inside = (nowMin >= startMin || nowMin <= endMin);
}

if(inside) {
[Link]("System time is between the intervals. Exiting.");
}else {
[Link]("System time NOT in interval. Try again.");
}
[Link]();
}
}

OUTPUT:

Page 38 of 40
20. Write a java program to find factorials of numbers in a given range.
PROGRAM:
// File:[Link]
[Link];
[Link].*;
publicclassFactorialRange {

publicstaticBigInteger factorial(int n){


BigIntegerres= [Link];
for(inti=2;i<=n;i++) res = [Link]([Link](i));
returnres;

}
publicstaticvoidmain(String[] args){
Scannersc=new Scanner([Link]);
[Link]("Enter start and end (e.g., 1 10): ");
inta=[Link](); intb=[Link](); if(a>b){intt=a; a=b;
b=t; } for(inti=a;i<=b;i++){

[Link](i + "! = " + factorial(i));


}
[Link]();
}
}

Page 39 of 40
OUTPUT:

Page 40 of 40

You might also like