Java Lab
Java Lab
LAB MANUAL
Prepared by
Vision
To achieve the autonomous & university status and spread universal education by
inculcating discipline, character and knowledge into the young minds and mould them into
enlightened citizens.
Mission
Our mission is to impart education, in a conducive ambience, as comprehensive as
possible, with the support of all the modern technologies and make the students acquire
the ability and passion to work wisely, creatively and effectively for the betterment of
our society.
Vision
Serving the high quality educational needs of local and rural students within the core areas
of Computer Science and Engineering and Information Technology through a rigorous
curriculum of theory, research and collaboration with other disciplines that is distinguished
by its impact on academia, industry and society.
Mission
The Mission of the department of Computer Science and Engineering is
To work closely with industry and research organizations to provide high quality
computer education in both the theoretical and applications of Computer Science
and Engineering.
The department encourages original thinking, fosters research and development,
evolve innovative applications of technology.
BHARAT INSTITUTE OF ENGINEERING AND TECHNOLOGY
Ibrahimpatnam - 501 510, Hyderabad
COMPUTER SCIENCE AND ENGINEERING
Program Educational Objectives (PEOs):
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences, and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and
design system components or processes that meet the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of the
information to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with
an understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess
Societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for
sustainable development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of the engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in
diverse teams, and in multidisciplinary settings.
PO11 Project management and finance: Demonstrate knowledge and understanding of the
engineering and management principles and apply these to one's own work, as a member and leader
in a team, to manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
PSO1 Software Development and Research Ability: Ability to understand the structure and
development methodologies of software systems. Possess professional skills and knowledge of
software design process. Familiarity and practical competence with a broad range of
programming language and open source platforms. Use knowledge in various domains to
identify research gaps and hence to provide solution to new ideas and innovations.
PSO2 Foundation of mathematical concepts: Ability to apply the acquired knowledge of basic
skills, principles of computing, mathematical foundations, algorithmic principles, modeling and
design of computer- based systems in solving real world engineering Problems.
PSO3 Successful Career: Ability to update knowledge continuously in the tools like Rational
Rose, MATLAB, Argo UML, R Language and technologies like Storage, Computing,
Communication to meet the industry requirements in creating innovative career paths for
immediate employment and for higher studies.
Course Objectives:
To write programs using abstract classes.
To write programs for solving real world problems using java collection frame work.
To write multithreaded programs.
To write GUI programs using swing controls in Java.
To introduce java compiler and eclipse platform.
Course Outcomes:
Able to write programs for solving real world problems using java collection frame work.
Able to write programs using abstract classes.
Able to write multithreaded programs.
Able to write GUI programs using swing controls in Java
30
INDEX
S. No. List of Experiments
1 Use Eclipse or Netbean platform and acquaint with the various menus. Create a test
project, and 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.
4 Write a 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 Num2 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
NumberFormatException. If Num2 were Zero, the program would throw an
ArithmeticException. 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 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
7 Write a Java Program that simulates a Traffic Light. The program lets the use select
one of three lights :red, yellow
8 Write a java program to create 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
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)
13 Write a java program to list all the files in a directory including files
14 Write a Java program that implements Quick sort algorithm for sorting a list of
names in ascending order
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.
Steps:
Environment Variables
PATH:
CLASSPATH:
This environment variable will help the jvm to find the runtime environment of java i.e. all
predefined classes and interfaces can be located using this variable. The location for
runtime environment is JRE folder.
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.
Aim: To create and test java projects in Eclipse and Netbean platform
Initializing Eclipse : When you develop Java applications in Eclipse, it stores all the created
files in a directory called "workspace". When Eclipse is run for the first time, it will ask you
where you want the workspace to be placed:
You can just use the default location or specify your preferred location. To avoid getting
asked this question every time you start Eclipse, check "Use this as the default and do not ask
again" option and press "OK" button. Once Eclipse finishes its startup process, you
Will see the following welcome window:
Now that you've got Eclipse up and running, it's time to create your first Java project. To
do this, you'll want to go File -> New -> Java Project. After doing so, you'll see a window
like the following:
As you create more projects in Eclipse, other project names will appear in the Package
explorer pane and you will be able to switch between your projects by clicking the name of
a project.
Adding a New File to a Project : Now that you've created your first project, you now
want to create a new Java file (with .java extension) and add it into your project. To
create a new Java file, right click on the name of your project (cs144project1) in the
Package explorer pane and select New -> Class as follows:
In the "Name: " section provide the name of the file (or the class) you want to create,
HelloWorld, and click "Finish" button.
Now let us learn how to code, compile and run a Java program in Eclipse. First copy
and paste the following method into the HelloWorld class definition:
Now that your code has been saved and compiled, you can run your program by
selecting Run -> Run, or by pressing Ctrl-F11 (Option-F11 on Mac) or by
clicking on the "Run" button near the top of the window. Once your
program finishes running, you will be able to see the output of your program by
selecting the "Console tab" at the bottom of the window.
Now you have learned the very basic functionality of Eclipse. Eclipse supports
many more functionalities than what you just learned, including integrated
debugging and automatic code completion and method lookup, etc. Please read
online Eclipse manual to learn more about Eclipse.
1. NetBeans IDE with the File | New Project menu item selected.
2. In the New Project wizard, expand the Java category and select Java
Application as shown in the following figure:
The Projects window, which contains a tree view of the components of the project,
including source files, libraries that your code depends on, and so on.
The Source Editor window with a file called HelloWorldApp.java open.
The Navigator window, which you can use to quickly navigate between elements
within the selected class.
It may be necessary to add JDK 8 to the IDE's list of available platforms. To do this, choose
Tools | Java Platforms as shown in the following figure:
If you don't see JDK 8 (which might appear as 1.8 or 1.8.0) in the list of installed
platforms, click Add Platform, navigate to your JDK 8 install directory, and click
Finish. You should now see this newly added platform:
To set this JDK as the default for all projects, you can run the IDE with the -- jdkhome
switch on the command line, or by entering the path to the JDK in
To specify this JDK for the current project only, select Hello World App in the
Projects pane, choose File | Project Properties (Hello World App), click Libraries, then
select JDK 1.8 in the Java Platform pulldown menu. You should see a screen similar to
the following:
When you created this project, you left the Create Main Class checkbox selected in the
New Project wizard. The IDE has therefore created a skeleton class for you. You can add
the "Hello World!" message to the skeleton code by replacing the line:
the line:
/**
* The HelloWorldApp class implements an applicationthat
* simply prints "Hello World!" to standard output.
*/
These four lines are a code comment and do not affect how the program runs. Later sections
of this tutorial explain the use and format of code comments.
Note: Type all code, commands, and file names exactly as shown. Both the compiler (javac)
and launcher (java) arecase-sensitive, so you must capitalize consistently.
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package helloworldapp;
/**
* The HelloWorldApp class implements an applicationthat
* simply prints "Hello World!" to standard output.
*/
public class HelloWorldApp {
/**
* @param args the command line arguments
*/
}
Compile the Source File into a .class File
To compile your source file, choose Run | Build Project (Hello World App) from the
IDE's main menu.
The Output window opens and displays output similar to what you see in the following
figure:
If the build output concludes with the statement BUILD SUCCESSFUL, congratulations!
You have successfully compiled your program!
If the build output concludes with the statement BUILD FAILED, you probably have a
syntax error in your code. Errors are reported in the Output window as hyperlinked text.
You double-click such a hyperlink to navigate to the source of an error. You can then fix
the error and once again choose Run | Build Project.
When you build the project, the bytecode file HelloWorldApp.class is generated. You can
see where the new file is generated by opening the Files window and expanding
Now that you have built the project, you can run your program.
From the IDE's menu bar, choose Run | Run Main Project. The
The program prints "Hello World!" to the Output window (along with other output from
the build script).
The next few pages of the tutorial will explain the code in this simple application. After
that, the lessons go deeper into core language features and provide many more examples.
Once you have created a project in the IDE, you can add files to the project using
the New File wizard. Choose File | New File, and then select a template in the
wizard, such as the Empty Java File template.
You can compile and run an individual file (as opposed to a whole project) using the
IDE's Compile File (F9) and Run File(Shift-F6) commands. If you use the
Run Main Project command, the IDE will run the file that the IDE associates as
the main class of the main project. Therefore, if you create an additional class in
your HelloWorldApp project and then try to run that file with the Run Main
Project command, the IDE will run the HelloWorldApp file instead.
You might want to create separate IDE projects for sample applications that include
more than one source file.
As you are typing in the IDE, a code completion box might periodically appear.
You can either ignore the code completion box and keep typing, or you can select
one of the suggested expressions. If you would prefer not to have the code
completion box automatically appear, you can turn off the feature. Choose
Tools | Options | Editor, click the Code Completion tab and clear the Auto
Popup Completion Window checkbox.
If you want to rename the node for a source file in the Projects window, choose
Refactor from IDE's main menu. The IDE prompts you with the
Rename dialog box to lead you through the options of renaming the class and the
updating of code that refers to that class. Make the changes and click
Refactor to apply the changes. This sequence of clicks might seem unnecessary if
you have just a single class in your project, but it is very useful when your changes
affect other parts of your code in larger projects.
Program:
import java.util.*;
public class Testp {
public static void main(String[] args) {
System.out.println("Welcome to KG REDDY Engineering College");
System.out.println("--------Prime Number ------ ");
Scanner sc = new Scanner(System.in);
System.out.println("Enter valid Number");
int n = sc.nextInt();
int c = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
c++;
}
}
if (c == 2) {
System.out.println(n + "is Prime Number");
} else {
System.out.println(n + "is not Prime Number");
}
}
}
Output:
AIM : 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.
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ActionListener {
public JButton b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16;
public JTextField tf1;
public JPanel p;
public String v = "";
public String v1 = "0";
public String op = "";
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
p = new JPanel(new FlowLayout());
tf1 = new JTextField(10);
p.add(tf1);
add(p);
setLayout(new GridLayout(0, 3));
b1 = new JButton("1");
b1.addActionListener(this);
add(b1);
b2 = new JButton("2");
b2.addActionListener(this);
add(b2);
b3 = new JButton("3");
b3.addActionListener(this);
add(b3);
b4 = new JButton("4");
b4.addActionListener(this);
add(b4);
b5 = new JButton("5");
b5.addActionListener(this);
add(b5);
b6 = new JButton("6");
b6.addActionListener(this);
add(b6);
Theory: Applets are designed to bring the web alive.they function to add animation sound
and eventually complete multi media into HTML documents.java is also part of the future
of interfacing with virtual-reality environments implemented via VRML.At present ,java is
limited only by the capabilities of the internet itself.applets are java programs that are
specialized for use over the Web.
Program:
import java.applet.Applet;
import java.awt.*;
public class Sms extends Applet {
public void init() {
}
public void paint(Graphics g) {
g.setColor(Color.blue);
Font font = new Font("verdana", Font.BOLD, 15);
g.setFont(font);
g.drawString("Welcome To KG REDDY Eng College", 50, 50);
}
}
Applet code:
<html>
<body>
</applet>
</body>
</html>
Output:
Aim : Develop an applet which receives an integer in one text field, and computes its
factorial Value and returns it in another text field.
Theory: Applets are designed to bring the web alive.they function to add animation sound and
eventually complete multi media into HTML documents.java is also part of the future of
interfacing with virtual-reality environments implemented via VRML.At present ,java is
limited only by the capabilities of the internet itself.applets are java programs that are
specialized for use over the Web. The Applet life cycle
The init()Method: The init()method is where your applet does much of its setup,such as
defined its layout,parsing parameters,or setting the background colors.
The starts() Method: The start()method is used mainly when implementing threads in java.
The stop() Mehtod: The stop() method is used to do what its name suggests: stop what is
going on.
The destroy() method: when it is called,the applet is told to free up system resources.
Program:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
Button b1;
setSize(400, 200);
setLayout(g);
l1.setForeground(Color.BLUE);
add(l1);
tf1.setText("0");
b1 = new Button("Compute");
b1.addActionListener(this);
add(b1);
l3 = new Label();
add(l3);
l2.setForeground(Color.BLUE);
add(l2);
add(tf2);
long n = Integer.parseInt(tf1.getText());
long f = 1;
while (n != 0) {
f = f * n;
n--;
tf2.setText(String.valueOf(f));
Applet code:
<html>
<body>
</applet>
</body>
</html>
Aim : Program to create a user interface to perform integer divisions. The user enters two
numbers in the textfields, Num1 and Num2. The division of Num1 and Num2 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 NumberFormatException. If Num2 were Zero, the program
would throw an ArithmeticException. Display the exception in a message dialog box.
Theory: The AWT supports a rich assortment of graphics methods.All graphics are drawn
relative to a window.this can the main windowof an applet, a child window of an applet,or a
stand alone application window. The origin of each window is at the top-left corner and is 0,0
cordinates are specified in pixels.All output to a window takes place through a graphics
context.
Program:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
JButton b1;
A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
l1 = new JLabel("Welcome");
setSize(800, 400);
add(tf1);
add(l2);
add(tf2);
l3 = new JLabel("Result");
add(l3);
add(tf3);
b1 = new JButton("Divide");
add(b1);
b1.addActionListener(this);
setVisible(true);
try {
int a = Integer.parseInt(tf1.getText());
int b = Integer.parseInt(tf2.getText());
if(b==0)
float c = (float) a / b;
tf3.setText(String.valueOf(c));
JOptionPane.showMessageDialog(this, ex.getMessage());
JOptionPane.showMessageDialog(this, ex.getMessage());
}
}
A a = new A();
Output:
Aim : Creating 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
Theory: The java run-time system depends on the threads for many things, and all the class
libraries are designed with multithreading in mind. In fact,java uses threads to enable the
entire environment to be asynchronous.This helps reduce inefficiency by preventing the
waste of CPU cycles. The benefits of java’s multithreading is that the main loop/polling
mechanism is eliminated.one thread can pause without stopping other parts of your
program.when a thread blocks in ajava program,only the single thread that is blocked
pauses.All other threads continue to run.
Program:
import java.util.*;
class even implements Runnable {
public int x;
public even(int x) {
this.x = x;
}
public void run() {
System.out.println("Thread Name:Even Thread and " + x + "is even Number 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("Thread Name:ODD Thread and " + x + " is odd number and Cube of " +
x + " is: " + x * x * x);
}
}
class A extends Thread {
public String tname;
public Random r;
public Thread t1, t2;
public A(String s) {
tname = s;
}
Output:
Aim : create a program in which doubly linked list operations can be shown in detail.
Theory : A doubly linked list is a linked data structure that consists of a set of sequentially
linked records called nodes. Each node contains two fields, called links, that are references to
the previous and to the next node in the sequence of nodes.
Program:
import java.io.*;
class node
public int x;
class DoubleLinkedList
DoubleLinkedList()
first=new node();
first.next=null;
first.prev=null;
last=first;
temp.x=v;
temp.next=null;
last.next=temp;
temp.prev=last;
last=temp;
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next==null)
add(v);
else
temp=new node();
temp.x=v;
temp.next=ptr.next;
ptr.next.prev=temp;
ptr.next=temp;
temp.prev=ptr;
void del(int p)
node ptr=first,temp;
for(int i=1;i<=p-1;i++)
ptr=ptr.next;
if(ptr.next.next==null)
temp=last;
last=last.prev;
last.next=null;
else
temp=ptr.next;
ptr.next=ptr.next.next;
ptr.next.prev=ptr;
temp=null;
void show()
for(node ptr=first.next;ptr!=null;ptr=ptr.next)
System.out.print("\t"+ptr.x);
for(node ptr=last;ptr.prev!=null;ptr=ptr.prev)
System.out.print("\t"+ptr.x);
Class DListTest
String con="";
int x,op,p,v;
do
x=Integer.parseInt(br.readLine());
l1.add(x);
System.out.print("Add more?(y,n):");
con=br.readLine();
}while(con.equals("y"))
l1.show();
do
System.out.println("\nSelect an option:");
op=Integer.parseInt(br.readLine());
if(op==1)
p= Integer.parseInt(br.readLine());
v= Integer.parseInt(br.readLine());
l1.insert(p,v);
if(op==2)
p= Integer.parseInt(br.readLine());
l1.del(p);
l1.show();
}while(op<4)
}
Output:
Aim: write a java program that simulates trafficlight the program let user select one of three
lights ,thread yellowor green .when a radio button is select the light is turn ed one light can
be on at atime. No lights is on when the program starts.
Theory: The AWT supports a rich assortment of graphics methods.All graphics are drawn
relative to a window.this can the main windowof an applet, a child window of an applet,or a
stand alone application window. The origin of each window is at the top-left corner and is 0,0
cordinates are specified in pixels.All output to a window takes place through a graphics
context.
Program:
import javax.swing.*;
import javax.swing.event.*;
import java.awt.*;
import java.awt.event.*;
class A extends JFrame implements ItemListener {
public JLabel l1, l2;
public JRadioButton r1, r2, r3;
public ButtonGroup bg;
public JPanel p, p1;
public A() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new GridLayout(2, 1));
setSize(800, 400);
p = new JPanel(new FlowLayout());
p1 = new JPanel(new FlowLayout());
l1 = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 60);
l1.setFont(f);
add(l1);
p.add(l1);
add(p);
l2 = new JLabel("Select Lights");
p1.add(l2);
JRadioButton r1 = new JRadioButton("Red Light");
r1.setBackground(Color.red);
p1.add(r1);
r1.addItemListener(this);
JRadioButton r2 = new JRadioButton("Yellow Light");
r2.setBackground(Color.YELLOW);
p1.add(r2);
r2.addItemListener(this);
JRadioButton r3 = new JRadioButton("Green Light");
r3.setBackground(Color.GREEN);
p1.add(r3);
Aim: Write a java program to create an abstract class that illustrates different geometrical
figures.
Theory: To create an abstract class that shows the hiding of elements in a class. At the same
time inheritance property is used to extend the class shape into different geometrical figures.
This represents the reusability of code for a programmer.
Program:
Output:
Aim: Write a java program to display the table using Grid Layout component
Program:
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(400, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
GridLayout g = new GridLayout(0, 3);
setLayout(g);
try {
FileInputStream fin = new FileInputStream("D:\\emp.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 JLabel(i));
}
}
} catch (Exception ex) {
}
setDefaultLookAndFeelDecorated(true);
pack();
setVisible(true);
}
}
public class Tbl {
public static void main(String[] args) {
A a = new A();
}
Output:
Theory : To handle mouse events you must implement the MouseListener and the
MouseMotionListener interfaces.These two interfaces contain methods that receive and
process the various types of mouse events.
Program:
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 GridBagLayout());
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 Mevents {
public static void main(String[] args) {
A a = new A();
Output:
Aim: Write a java program which can read text file into hash table and print the hash values
based on the hash key input.
THEORY: Text file will contain names and phone numbers which are separated by a tab.
This information has to be recorded in to hash table.
Program:
import java.util.*;
import java.io.*;
public class Hashtbl {
public static void main(String[] args) {
try {
FileInputStream fs = new FileInputStream("D:\\ph.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 KG REDDY Eng College");
System.out.println("HASH TABLE IS");
System.out.println(" ------------------------- ");
System.out.println("KEY : VALUE");
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 KG REDDY Eng College");
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 {
Program:
class Q
{
int n;
boolean valueSet=false;
synchronized int get()
{
if(!valueSet)
try
{
wait();
}
catch(InterruptedException 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:
Theory : Java provides a standard way of reading from and writing to files. Traditionally
thejava.io package was used, but in modern Java applications you use
the java.nio.fileAPI. Java will read all input as a stream of bytes. The InputStream class is the
superclass of all classes representing an input stream of bytes.
Program:
import java.io.*;
import java.lang.*;
import java.io.File;
System.out.println(file.getName());
if (file.isFile()){
System.out.println(file.getName());
if (file.isDirectory()){
System.out.println(file.getName());
if (file.isFile()){
System.out.println(file.getAbsolutePath());
} else if (file.isDirectory()){
listFilesAndFilesSubDirectories(file.getAbsolutePath());
listFilesUtil.listFiles(directoryLinuxMac);
Output:
Theory : QuickSort is a Divide and Conquer algorithm. It picks an element as pivot and
partitions the given array around the picked pivot. There are many different versions of
quickSort that pick pivot in different ways.
1. Always pick first element as pivot.
2. Always pick last element as pivot (implemented below)
3. Pick a random element as pivot.
4. Pick median as pivot.
Program :
return;
this.array = inputArr;
length = inputArr.length;
int i = lowerIndex;
int j = higherIndex;
while (i <= j) {
i++;
j--;
if (i <= j) {
exchangeNumbers(i, j);
i++;
j--;
if (lowerIndex < j)
quickSort(lowerIndex, j);
if (i < higherIndex)
quickSort(i, higherIndex);
array[i] = array[j];
array[j] = temp;
sorter.sort(input);
for(int i:input){
System.out.print(" ");
Output:
Theory : Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the
adjacent elements if they are in wrong order.
Program:
import java.util.Scanner;
class BubbleSort {
public static void main(String []args) {
int num, i, j, temp;
Scanner input = new Scanner(System.in);
System.out.println("Enter the number of integers to sort:");
num = input.nextInt();
int array[] = new int[num];
System.out.println("Enter " + num + " integers: ");
for (i = 0; i < num; i++)
array[i] = input.nextInt();
for (i = 0; i < ( num - 1 ); i++) {
for (j = 0; j < num - i - 1; j++) {
if (array[j] < array[j+1])
{
temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
System.out.println("Sorted list of integers:");
for (i = 0; i < num; i++)
System.out.println(array[i]);
}
}
Output: