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

Java Lab Manual

The document outlines a Java lab course for B.Tech students focusing on Object-Oriented Programming. It includes objectives such as writing programs using abstract classes, multithreading, and GUI development, along with a list of experiments to complete. Each experiment provides specific programming tasks, such as creating a calculator, implementing a traffic light simulation, and handling exceptions.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Java Lab Manual

The document outlines a Java lab course for B.Tech students focusing on Object-Oriented Programming. It includes objectives such as writing programs using abstract classes, multithreading, and GUI development, along with a list of experiments to complete. Each experiment provides specific programming tasks, such as creating a calculator, implementing a traffic light simulation, and handling exceptions.

Uploaded by

jayart.9949
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 49

OBJECT ORIENTED PROGRAMMING THROUGH JAVA LAB

B.Tech. II Year I Sem. LTPC00


3 1.5

Course Objectives:

● To write programs using abstract classes.

● To write programs for solving real world problems using the java collection
framework.

● To write multithreaded programs.

● To write GUI programs using swing controls in Java.

● To introduce java compiler and eclipse platform.

● To impart hands-on experience with java programming.

Course Outcomes:

● Able to write programs for solving real world problems using the java collection
framework.

● Able to write programs using abstract classes.

● Able to write multithreaded programs.

● Able to write GUI programs using swing controls in Java.

Note:

1. Use LINUX and MySQL for the Lab Experiments. Though not mandatory,
encourage the use

of the Eclipse platform.

2. The list suggests the minimum program set. Hence, the concerned staff is
requested to add

more problems to the list as needed.


List of Experiments:

1. Use Eclipse or Net bean platform and acquaint yourself 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.

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.

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

B) 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.

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.

5. Write a Java program that implements a multi-thread application that has three
threads. First thread

generates a random integer every 1 second and if the value is even, the second
thread computes the

square of the number and prints. If the value is odd, the third thread will print the
value of the cube of

the number.

6. Write a Java program for the following:

Create a doubly linked list of elements.

R22 B.Tech. CSE (Data Science) Syllabus JNTU Hyderabad

Delete a given element from the above list.

Display the contents of the list after deletion.

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 the selected color.
Initially, there is no

message shown.

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.


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.

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).

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).

12. Write a Java program that correctly implements the producer – consumer
problem using the

concept of inter thread communication.

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

subdirectories.

REFERENCE BOOKS:

1. Java for Programmers, P. J. Deitel and H. M. Deitel, 10th Edition Pearson


education.

2. Thinking in Java, Bruce Eckel, Pearson Education.

3. Java Programming, D. S. Malik and P. S. Nair, Cengage Learning.


4. Core Java, Volume 1, 9th edition, Cay S. Horstmann and G Cornell, Pearson.

1. Use Eclipse or Net bean platform and acquaint yourself 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.

JAVA Lab Program-2


AIM:

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.

PROGRAM:

import java.awt.*;
import java.awt.event.*;
import java.applet.*;
import javax.swing.*;
/*
<applet code="Calculator" width=300 height=300>
</applet>
*/
public class Calculator extends Applet implements ActionListener
{
int num1,num2,result;
TextField T1;
Button NumButtons[]=new Button[10];
Button Add,Sub,Mul,Div,clear,EQ;
char Operation;
Panel nPanel,CPanel,SPanel;
public void init( )
{
nPanel=new Panel();
T1=new TextField(30);
nPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
nPanel.add(T1);
CPanel=new Panel();
CPanel.setBackground(Color.white);
CPanel.setLayout(new GridLayout(5,5,3,3));
for(int i=0;i<10;i++)
{
NumButtons[i]=new Button(""+i);
}
Add=new Button("+");
Sub=new Button("-");
Mul=new Button("*");
Div=new Button("/");
clear=new Button("clear");
EQ=new Button("=");
T1.addActionListener(this);
for(int i=0;i<10;i++)
{
CPanel.add(NumButtons[i]);
}
CPanel.add(Add);
CPanel.add(Sub);
CPanel.add(Mul);
CPanel.add(Div);
CPanel.add(EQ);
SPanel=new Panel();
SPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
SPanel.setBackground(Color.yellow);
SPanel.add(clear);
for(int i=0;i<10;i++)
{
NumButtons[i].addActionListener(this);
}
Add.addActionListener(this);
Sub.addActionListener(this);
Mul.addActionListener(this);
Div.addActionListener(this);
clear.addActionListener(this);
EQ.addActionListener(this);
this.setLayout(new BorderLayout());
add(nPanel,BorderLayout.NORTH);
add(CPanel,BorderLayout.CENTER);
add(SPanel,BorderLayout.SOUTH);
}
public void actionPerformed(ActionEvent ae)
{
String str=ae.getActionCommand ();
char ch=str.charAt(0);
if(Character.isDigit(ch))
T1.setText(T1.getText()+str);
else
if(str.equals("+"))
{
num1=Integer.parseInt (T1.getText());
Operation='+';
T1.setText ("");
}
if(str.equals("-"))
{
num1=Integer.parseInt(T1.getText());
Operation='-';
T1.setText("");
}
if(str.equals("*"))
{
num1=Integer.parseInt(T1.getText());
Operation='*';
T1.setText("");
}
if(str.equals("/"))
{
num1=Integer.parseInt(T1.getText());
Operation='/';
T1.setText("");
}
if(str.equals("%"))
{
num1=Integer.parseInt(T1.getText());
Operation='%';
T1.setText("");
}
if(str.equals("="))
{
num2=Integer.parseInt(T1.getText());
switch(Operation)
{
case '+':result=num1+num2;
break;
case '-':result=num1-num2;
break;
case '*':result=num1*num2;
break;
case '/':try {
result=num1/num2;
}
catch(ArithmeticException e)
{
result=num2;
JOptionPane.showMessageDialog(this,"Divided by
zero");
}
break;
}
T1.setText(""+result);
}
if(str.equals("clear"))
{
T1.setText("");
}
}
}

OUTPUT:
JAVA Lab Program-3(a)
AIM:

Develop an applet in Java that displays a simple message.

PROGRAM:

import java.applet.Applet;
import java.awt.Graphics;
/*<applet code = "Hello" width = 400 height = 300>
</applet>*/
public class Hello extends Applet
{
public void paint(Graphics g)
{
g.drawString("Hello world",50,30);
}
}

OUTPUT:
JAVA Lab Program-3(b)
AIM:

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.

PROGRAM:

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<applet code="Factorial" width=500 height=250>
</applet>*/
public class Factorial extends Applet implements ActionListener
{
Label L1,L2;
TextField T1,T2;
Button B1;
public void init()
{
L1=new Label("Enter any Number : ");
add(L1);
T1=new TextField(10);
add(T1);
L2=new Label("Factorial of Num : ");
add(L2);
T2=new TextField(10);
add(T2);
B1=new Button("Compute");
add(B1);
B1.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if(e.getSource()==B1)
{
int value=Integer.parseInt(T1.getText());
int fact=factorial(value);
T2.setText(String.valueOf(fact));
}
}
int factorial(int n)
{
if(n==0)
return 1;
else
return n*factorial(n-1);
}
}
OUTPUT:

JAVA Lab Program-4


AIM:

To 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.

PROGRAM:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
class A extends JFrame implements ActionListener
{
JLabel l1, l2, l3;
JTextField tf1, tf2, tf3; JButton b1;
A()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
l1 = new JLabel("Enter Number1");
add(l1);
tf1 = new JTextField(10);
add(tf1);
l2 = new JLabel("Enter Number2");
add(l2);
tf2 = new JTextField(10);
add(tf2);
l3 = new JLabel("Result");
add(l3);
tf3 = new JTextField(10);
add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
}
public void actionPerformed(ActionEvent ae)
{
try
{
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
throw new ArithmeticException(" Divide by Zero Error"); float c = (float) a / b;
tf3.setText(String.valueOf(c));
}
catch (NumberFormatException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
catch (ArithmeticException ex)
{
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
}
public class IntegerDivision
{
public static void main(String[] args)
{
A a = new A();
}
}
OUTPUT:
JAVA Lab Program-5
AIM:

Write a Java program that implements a multi-thread application that has


three threads. First thread generates a 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

PROGRAM:
import java.util.*;
class EvenNum implements Runnable
{
public int a;
public EvenNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is EVEN and Square of " + a + " is : " +
a * a);
}
}
class OddNum implements Runnable
{
public int a;
public OddNum(int a)
{
this.a = a;
}
public void run()
{
System.out.println("The Thread "+ a +" is ODD and Cube of " + a + " is: " + a *
a * a);
}
}
class RandomNumGenerator extends Thread
{
public void run()
{
int n = 0;
Random rand = new Random();
try
{
for(int i = 0; i < 10; i++)
{
n = rand.nextInt(20);
System.out.println("Generated Number is " + n);
// check if random number is even or odd
if (n % 2 == 0)
{
Thread thread1 = new Thread(new EvenNum(n));
thread1.start();
}
else
{
Thread thread2 = new Thread(new OddNum(n));
thread2.start();
}
Thread.sleep(1000);
System.out.println("------------------------------------");
}
}
catch (Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
public class MultiThreadOddEven
{
public static void main(String[ ] args)
{
RandomNumGenerator rand_num = new RandomNumGenerator();
rand_num.start();
}
}
OUTPUT:
Java Lab Program-6
AIM:
Write a Java program for the following:
a)Create a doubly linked list of elements.
b)Delete a given element from the above list.
c)Display the contents of the list after deletion.
PROGRAM:
import java.util.*;
public class DoubleLinkedListDemo
{
public static void main(String[ ] args)
{
int i,ch,element,position;
LinkedList<Integer> dblList = new LinkedList<Integer>();
System.out.println("1.Insert element at begining");
System.out.println("2.Insert element at end");
System.out.println("3.Insert element at position");
System.out.println("4.Delete a given element");
System.out.println("5.Display elements in the list");
System.out.println("6.Exit");
Scanner sc=new Scanner(System.in);
do
{
System.out.print("Choose your choice(1 - 6) :");
ch=sc.nextInt();
switch(ch)
{
case 1: System.out.print("Enter an element to insert
at begining : ");
element=sc.nextInt();
// to add element to doubly linked list at
begining
dblList.addFirst(element);
System.out.println("Successfully
Inserted");
break;
case 2: System.out.print("Enter an element to insert
at end : ");
element=sc.nextInt();
// to add element to doubly linked list at
end
dblList.addLast(element);
System.out.println("Successfully
Inserted");
break;
case 3: System.out.print("Enter position to insert
element : ");
position=sc.nextInt();
// checks if the position is lessthan or
equal to list size.
if(position<=dblList.size())
{
// To read element
System.out.print("Enter element : ");
element=sc.nextInt();
// to add element to doubly linked list at given
position
dblList.add(position,element);
System.out.println("Successfully
Inserted");
}
else
{
System.out.println("Enter the size between 0
to"+dblList.size());
}
break;
case 4: System.out.print("Enter element to remove :
");
Integer ele_rm;
ele_rm=sc.nextInt();
if (dblList.contains(ele_rm))
{
dblList.remove(ele_rm);
System.out.println("Successfully
Deleted");
Iterator itr=dblList.iterator();
System.out.println("Elements after
deleting :"+ele_rm);
while(itr.hasNext())
{
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
}
else
{
System.out.println("Element not found");
}
break;

case 5: Iterator itr=dblList.iterator();


System.out.println("Elements in the list :");
while(itr.hasNext())
{
System.out.print(itr.next()+"<->");
}
System.out.println("NULL");
break;
case 6: System.out.println("Program terminated");
break;
default: System.out.println("Invalid choice");
}
}while(ch!=6);
}
}
OUTPUT:

JAVA Lab Program-7


AIM:

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.

PROGRAM:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class TrafficLightSimulator extends JFrame implements ItemListener
{
JLabel lbl1, lbl2;
JPanel nPanel, cPanel;
CheckboxGroup cbg;
public TrafficLightSimulator()
{
setTitle("Traffic Light Simulator");
setSize(600,400);
setLayout(new GridLayout(2, 1));
nPanel = new JPanel(new FlowLayout());
cPanel = new JPanel(new FlowLayout());

lbl1 = new JLabel();


Font font = new Font("Verdana", Font.BOLD, 70);
lbl1.setFont(font);
nPanel.add(lbl1);
add(nPanel);

Font fontR = new Font("Verdana", Font.BOLD, 20);


lbl2 = new JLabel("Select Lights");
lbl2.setFont(fontR);
cPanel.add(lbl2);
cbg = new CheckboxGroup();
Checkbox rbn1 = new Checkbox("Red Light", cbg, false);
rbn1.setBackground(Color.RED);
rbn1.setFont(fontR);
cPanel.add(rbn1);
rbn1.addItemListener(this);

Checkbox rbn2 = new Checkbox("Yellow Light", cbg, false);


rbn2.setBackground(Color.YELLOW);
rbn2.setFont(fontR);
cPanel.add(rbn2);
rbn2.addItemListener(this);

Checkbox rbn3 = new Checkbox("Green Light", cbg, false);


rbn3.setBackground(Color.GREEN);
rbn3.setFont(fontR);
cPanel.add(rbn3);
rbn3.addItemListener(this);
add(cPanel);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void itemStateChanged(ItemEvent i)
{
Checkbox chk = cbg.getSelectedCheckbox();
String str=chk.getLabel();
char choice=str.charAt(0);
switch (choice)
{
case 'R': lbl1.setText("STOP");
lbl1.setForeground(Color.RED);
break;
case 'Y': lbl1.setText("READY");
lbl1.setForeground(Color.YELLOW);
break;
case 'G': lbl1.setText("GO");
lbl1.setForeground(Color.GREEN);
break;
}
}
public static void main(String[ ] args)
{
new TrafficLightSimulator();
}
}
OUTPUT:
JAVA Lab Program-8
AIM:
Java program tocreate an abstract class named Shape that contains two
integers and an empty method named printArea (). 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
printArea() that prints the area of the given shape.
PROGRAM:
import java.util.*;
abstract class Shape
{
int x,y;
abstract void area(double x,double y);
}
class Rectangle extends Shape
{
void area(double x,double y)
{
System.out.println("Area of rectangle:" +(x*y));
}
}
class Circle extends Shape
{
void area(double x,double y)
{
System.out.println("Area of circle:" +(3.14*x*x));
}
}
class Triangle extends Shape
{
void area(double x,double y)
{
System.out.println("Area of triangle:"+(0.5*x*y));
}
}
public class AbstractDemo
{
public static void main(String[] args)
{
Rectangle r=new Rectangle();
r.area(2,5);
Circle c=new Circle();
c.area(5,5);
Triangle t=new Triangle();
t.area(7,3);
}
}
OUTPUT:

JAVA Lab Program-9


AIM:
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
PROGRAM:
import java.io.*;
import java.util.*;
import java.awt.*;
import javax.swing.*;
class A extends JFrame {
public A() {
setSize(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(3,3,20,30);
setLayout(g);
try {
FileInputStream fin = new FileInputStream("table.txt");
Scanner sc = new Scanner(fin).useDelimiter("\n");
String[] arrayList;
String a;
while (sc.hasNextLine())
{
a = sc.nextLine();
arrayList =a.split(" ");
for (String i : arrayList)
{
add(new JLabel(i));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
pack();
setVisible(true);
}
}
public class GridTable {
public static void main(String[] args) {
A a = new A();
}
}
OUTPUT:
JAVA Lab Program-10
AIM:
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).

PROGRAM:
// Demonstrate an adapter.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init()
{
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new MyMouseMotionAdapter(this));
}
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
this.adapterDemo = adapterDemo;
}
public void mouseEntered(MouseEvent m)
{
adapterDemo.showStatus("Mouse Entered");
}
public void mouseExited(MouseEvent m)
{
adapterDemo.showStatus("Mouse Exited");
}
public void mouseClicked(MouseEvent m)
{
adapterDemo.showStatus("Mouse clicked");
}
public void mouseDragged(MouseEvent m)
{
adapterDemo.showStatus("Mouse dragged");
}
}

OUTPUT:
JAVA Lab Program-11
AIM:
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).

PROGRAM:
import java.io.*;
import java.util.*;
public class NamesAndPhoneNumbers
{
public static void main(String args[ ])
{
try
{
FileInputStream fis=new FileInputStream("phonefile.txt");
Scanner sc=new Scanner(fis).useDelimiter("\t");
Hashtable<String,String> ht=new Hashtable<String,String> ();
String[ ] strarray;
String a,str;
while(sc.hasNext())
{
a=sc.nextLine();
strarray=a.split("\t");
ht.put(strarray[0],strarray[1]);
System.out.println("hash table values are:\t"+strarray[0]+":---
>"+strarray[1]);
}
Scanner s=new Scanner(System.in);
System.out.println("Enter the name as given in the phone book");
str=s.next();
if(ht.containsKey(str))
{
System.out.println("phone no is"+ht.get(str));
}
else
{
System.out.println("Name is not matched");
}
}
catch(Exception e)
{
System.out.println(e);
}
}
}
OUTPUT:
JAVA Lab Program-12
AIM:
Write a Java program that correctly implements the producer – consumer
problem using the concept of interthread communication.

PROGRAM:
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
System.out.println("Got:"+n);
valueSet=false;
notify();
return n;
}
synchronized void put(int n)
{
if(valueSet)
try
{
wait();
}
catch(InterruptedException e)
{
System.out.println("Interrupted Exception caught");
}
this.n=n;
valueSet=true;
System.out.println("Put:"+n);
notify();
}
}
class Producer implements Runnable
{
Q q;
Producer(Q q)
{
this.q=q;
new Thread(this,"Producer").start();
}
public void run()
{
int i=0;
while(true)
{
q.put(i++);
try{
Thread.sleep(1000);
}
catch(Exception e){}
}
}
}
class Consumer implements Runnable
{
Q q;
Consumer(Q q)
{
this.q=q;
new Thread(this,"Consumer").start();
}
public void run()
{
while(true)
{
q.get();
try{Thread.sleep(5000);}
catch(Exception e){}
}
}
}
class ProdCons
{
public static void main(String[] args)
{
Q q=new Q();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-c to stop");
}
}
OUTPUT:

JAVA Lab Program-13


AIM:

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

PROGRAM:

// Using directories.
import java.io.File;
class DirList
{
public static void main(String args[ ])
{
String dirname = "D:/gee-java/gee-JavaProgs";
File f1 = new File(dirname);
if (f1.isDirectory())
{
System.out.println("Directory of " + dirname);
String s[] = f1.list();
for (int i=0; i < s.length; i++)
{
File f = new File(dirname + "/" + s[i]);
if (f.isDirectory())
{
System.out.println(s[i] + " is a directory");
}
else
{
System.out.println(s[i] + " is a file");
}
}
}
else
{
System.out.println(dirname + " is not a directory");
}
}
}

OUTPUT:

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy