Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Department of Computer Science & Engineering
OOP Lab Manual
Introduction to JAVA
Java Programming Language:
Java is a very popular and widely used programming language and it was not be an
exaggeration to say it is the most widely used programming language in industry
now. The reason for its wide popularity was probably the well thought of goals of
the programming language. Among other attractive features, the following stand
out in ensuring it gets wide acceptability.
1.
2.
3.
4.
5.
6.
7.
Ease of use
Object Oriented
Very strong API
Focus on removing hard to use and error-prone constructs
Platform Independence
Open Source encouraging collaborative development.
Security (Sandbox)
When people refer to the term JAVA, they are actually referring to any one or all
three of the following.
The JAVA Programming Language
The Java Virtual Machine
The JAVA Application Programming Interface
All three together along with the numerous tools that provide for a strong
programming environment, making programming easy and encouraging rapid
application development has made Java one of the most popular programming
languages.
The JAVA Virtual Machine:
Contrary to other popular languages, JAVA follows a half-compiled, halfinterpreted approach to achieve the famed platform independence. Java inventors
also defined a platform independent java machine language called Byte-Code into
which java Compiler compiles all Java Programs. This byte code is the machine
language of the Java Virtual Machine and is platform independent. Java Virtual
Machine is a software interpreter which interprets byte code (.class files) and
executes them on the target machine on which the byte code in running. Java
inventors provided reference implementations of Java Virtual machine on some of
the most popular machine architectures and encouraged vendors in developing the
same for almost all machine architectures by providing the reference
implementation.
Since the byte code is machine independent, JAVA programs can be compiled once
(into byte code) and executed on any machine architecture provided there is a JVM
implementation on that architecture.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
Java Application Programming Interface:
Java comes with a pretty exhaustive application programming interface which
covers a wide ranging set of tasks which programmers need. By providing a easy to
use application programming interface, JAVA makes the task of the programmer
somewhat easy, allowing him to focus on the solution to his problem not having to
worry about implementing simple data structures, working on lower level file
interaction, etc. Java API has classes that provide support for large number of GUI
widgets, Input & Output Streams, Database interaction, Socket communication
libraries, utility data structures, simple data types, reflection API among other
things. The API also is designed with extensibility and provides scope for alternate
implementations by a thoughtful separation of Interfaces and implementations.
Installation:
The latest version of JAVA (1.6.0_10 at the time of writing this revision of manual)
is freely downloadable from www.java.sun.com. All machines in our Java lab have
JAVA 1.6.0_10 installed at C:\Program Files\Java.
On the Linux/Solaris side, the students should run the command “which javac” on
their shell to figure out the path of Java installation.
Java Compiler:
Java Compiler is the utility that compiles Java programs to their corresponding
Byte Code (.class files). Javac is platform independent, for the simple reason that
both source (input) and output of the javac program are platform independent.
Java Compiler or “javac” as it is commonly called would be available in
C:\Program Files\Java\jdk1.6.0_10\bin.
Java Interpreter:
Java interpreter or the Java Virtual Machine (It is called so because interpreter is a
machine emulator executing each instruction in byte-code, line by line) is the
software which executes Byte-Code. The interpreter is machine dependent
because it interprets machine independent byte-code on a given machine
architecture. The Java interpreter or “java” as it is commonly called would be
available in C:\Program Files\Java\jdk1.6.0_10 \bin
Environment Variables:
PATH: This should have the path of “javac” and other utilities, so they can be
invoked directly without having to give the full absolute path.
CLASS PATH:
This environment variable is used to hold all paths in which Java Byte code of all
classes which one hopes to use in his or her program. For example, classpath
environment variable should have the path till lib directly in Java installation if we
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
plan to use the Java API classes which we most certainly will. CLASSPATH should
also have path of all user defined packages that would be used.
Packages:
Packages are actually groups of related classes and also serve the purpose of
avoiding namespace cluttering. You can define your own packages and put your
classes in that package.
Example:
Let us say I want to create 2 classes called Stack and Queue. I would create a
package called com.jbrec.vjmr and put these classes in that package. To do so, I
have to do the following:
1. Create a directory structure com/jbrec/vjmr is some folder x.
2. Put my Stack and Queue classes in that directory with the first line of
these .java files indicating that they belong to package com.jbrec.vjmr.
3. Compile all files in the package by going into the generic directory and
saying “javac *.java”
4. If I want to use these classes, I put the path “x” in CLASSPATH environment
variable.
5. In the java file where I want to use the classes in this package, I would put
an import com.jbrec.vjmr.* statement before going ahead and using the
class.
JAVA API Packages:
JAVA API groups all interfaces and classes into a set of packages depending on the
functionality they are addressing and supporting.
Java.lang package offers the basic data types and basic classes and is
automatically imported without any explicit import from programmers. All other
packages have to be explicitly imported by the programmers depending on the
need. Importing classes means that the classes would be loaded by the Java Loader
into JVM and takes time. So, it is advisable to only import those packages and
classes which would be used.
Other commonly used packages in JAVA API are java.io, java.util, java.sql,
java.awt, javax.swing, java.net, etc.
JAVA API Documentation:
What does it contain?
API documentation contains the list of all packages, classes, interfaces and a
description of all methods and their signatures among other things. The
documentation is the most definitive source of API available and how to use for the
programmers and is actually generated directly from source code using the JAVA
doc utility. In fact, it is recommended that we use JAVA Doc to generate similar
documentation for all JAVA classes we write as a matter of practice.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
Where is it available?
JAVA API documentation is a must for all JAVA programmers and can be
downloaded from Java.sun.com. Without documentation handy, it is highly unlikely
you would be using the API support in JAVA to a good extent. Java API is available
on all our machines in C:\Program Files\Java\jdk1.6.0_10 \docs.
How to use?
Clicking on C:\program files\Java\jdk1.6.0_10 \docs\index.html will lead you to a
page where there will be a link to API specification. Click on the framed version.
From the resultant page, you can navigate to any package, class, interface and
look at its documentation and go to any related classes following the necessary
navigation links.
Starting with a Simple program:
Program:
Public class HelloWorld
{
Public static void main(String[] args)
{
System.out.println(“Hello World”);
}
}
Notes: JAVA is a complete object-based language. Everything in JAVA is
encapsulated in classes. Main in the class which you give to the interpreter is the
entry point to a Java program. The JAVA interpreter will call the static main
directly with command line options without creating an object.
Steps to run a Java Program:
1. Compile
Command: To compile, “javac HelloWorld.java”
2. Run Interpreter
Command: To interpret, “java HelloWorld”
Note: Compiler will generate HelloWorld.class which is the byte code. The
Interpret will interpret HelloWorld.class by invoking HelloWorld.main().
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that prints all real solutions to the quadratic equation ax2 + bx +
c = 0. Read in a, b, c and use the quadratic formula. If the discriminant b2 -4ac is
negative, display a message stating that there are no real solutions.
2) The Fibonacci sequence is defined by the following rule:
The first two values in the sequence are 1 and 1. Every subsequent value is the
sum of the two values preceding it. Write a Java program that uses both
recursive and non recursive functions to print the nth value in the Fibonacci
sequence.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 1:
package com.jbrec.vjmr;
import java.util.Scanner;
/**
* @author JMR
*/
class QuadraticEquation
{
public static void main(String[] jbrec)
{
try
{
System.out.println("**** QuadraticEquation : ax^2+bx+c=0 ****\n");
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter Value for a:");
long a = objScanner.nextLong();
System.out.print("Enter Value for b:");
long b = objScanner.nextLong();
System.out.print("Enter Value for c:");
long c = objScanner.nextLong();
long discriminant = (b * b) - (4 * a * c);
if (discriminant < 0)
{
System.out.println("\nNo Real Solutions for given
QuadraticEquation");
}
else if (discriminant == 0)
{
double root = (-b) / (2 * a);
System.out.println("\nReal Solution: " + root);
}
else
{
double root1 = (-b + Math.sqrt(discriminant)) / (2 * a);
double root2 = (-b - Math.sqrt(discriminant)) / (2 * a);
System.out.println("\nReal Solution1: " + root1);
System.out.println("\nReal Solution2: " + root2);
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 2:
package com.jbrec.vjmr;
import java.util.Scanner;
/**
*@author JMR
*/
class Fibonacci
{
public static void main(String[] jbrec) throws Exception
{
Scanner objScanner = new Scanner(System.in);
while (true)
{
System.out.print("\nEnter n Value:");
long n = objScanner.nextLong();
System.out.println("1-Use Non Recursive Function");
System.out.println("2-Use Recursive Function");
System.out.println("3-Exit");
System.out.print("Enter your Choice [1 or 2]:");
int choice = objScanner.nextInt();
switch (choice)
{
case 1:
long result = nonRecursiveFibonacci(n);
System.out.println(n + " th Fibonacci No: " + result);
break;
case 2:
result = recursiveFibonacci(n);
System.out.println(n + " th Fibonacci No: " + result);
break;
case 3:
System.exit(0);
break;
default:
System.out.println("Invaild Choice");
}
}
}
public static long nonRecursiveFibonacci(long n)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
{
long previous = 1, result = 1;
if (n == 1 || n == 2)
{
return 1;
}
else
{
for (long i = 0; i < n - 2; i++)
{
long sum = result + previous;
previous = result;
result = sum;
}
return (result);
}
}
public static long recursiveFibonacci(long n)
{
if (n == 1 || n == 2)
{
return 1;
}
else
{
return recursiveFibonacci(n - 1) + recursiveFibonacci(n - 2);
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that prompts the user for an integer and then prints out all prime
numbers up to that integer.
2) Write a Java program to multiply two given matrices.
3) Write a Java Program that reads a line of integers, and then displays each integer, and
the sum of all the integers (Use StringTokenizer class of java.util).
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 3:
package com.jbrec.vjmr;
import java.util.Scanner;
/**
* @author JMR
*/
class PrimeNumbers
{
public static void main(String[] jbrec)
{
try
{
System.out.println("***** PRIME NUMBERS *****");
Scanner objScanner = new Scanner(System.in);
System.out.print("\nEnter n Value:");
long n = objScanner.nextInt();
for (long i = 2; i <= n; i++)
{
boolean isprime = isNumPrime(i);
if (isprime)
{
System.out.print(i + " ");
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
public static boolean isNumPrime(long number)
{
boolean result = true;
for (long i = 2; i <= number / 2; i++)
{
if ((number % i) != 0)
{
result = true;
}
else
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
{
result = false;
break;
}
}
return result;
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 4:
package com.jbrec.vjmr;
import java.util.Iterator;
import java.util.Scanner;
/**
* @author JMR
*/
class MatrixMultiply
{
public static void main(String[] args)
{
Scanner objScanner = new Scanner(System.in);
System.out.println("Matrix The Rows of Matrix A: ");
int rowsA = objScanner.nextInt();
System.out.println("Matrix The Columns of Matrix A: ");
int colsA = objScanner.nextInt();
System.out.println("Matrix The Rows of Matrix B: ");
int rowsB = objScanner.nextInt();
System.out.println("Matrix The Columns of Matrix B: ");
int colsB = objScanner.nextInt();
if (colsA == rowsA)
{
long a[][] = new long[rowsA][colsA];
long b[][] = new long[rowsB][colsB];
long c[][] = new long[rowsA][colsB];
System.out.print("Enter The Values into Matrix A(" + rowsA + "*" +
colsA + "):");
for (int i = 0; i < rowsA; i++)
{
for (int j = 0; j < colsA; j++)
{
a[i][j] = objScanner.nextLong();
}
}
System.out.print("Enter The Values into Matrix B(" + rowsB + "*" +
colsB + "):");
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
for (int i = 0; i < rowsB; i++)
{
for (int j = 0; j < colsB; j++)
{
b[i][j] = objScanner.nextLong();
}
}
System.out.print("The Resultent Matrix:");
for (int i = 0; i < rowsA; i++)
{
System.out.println();
for (int j = 0; j < colsB; j++)
{
c[i][j] = 0;
for (int k = 0; k < colsB; k++)
{
c[i][j] = c[i][j] + a[i][k] * b[k][j];
}
System.out.print(c[i][j] + " ");
}
}
}
else
{
System.out.println("Multiplication Is Not Possible.");
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 5:
package com.jbrec.vjmr;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* @author JMR
*/
class StringTokenizerEx
{
public static void main(String[] args)
{
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter A Line Of Integers:");
String line = objScanner.nextLine();
StringTokenizer st = new StringTokenizer(line);
long sum = 0;
while (st.hasMoreTokens())
{
long i = Long.parseLong(st.nextToken());
System.out.print(i + " ");
sum += i;
}
System.out.print("\n The Sum Is:" + sum);
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that checks whether a given string is a palindrome or not. Ex:
MADAM is a palindrome.
2) Write a Java program for sorting a given list of names in ascending order.
3) Write a Java program to make frequency count of words in a given text.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 6:
package com.jbrec.vjmr;
import java.util.Scanner;
/**
* @author JMR
*/
public class StringPalindrome
{
public static void main(String[] jbrec)
{
String s1, s2 = "";
System.out.print("Enter A String:");
Scanner objScanner = new Scanner(System.in);
s1 = objScanner.next();
int length = s1.length();
for (int i = length - 1; i >= 0; i--)
{
s2 += s1.charAt(i);
}
if (s1.equals(s2))
{
System.out.print("\nThe given string \"" + s1 + "\" is a palindrome");
}
else
{
System.out.print("\nThe given string \"" + s1 + "\" is not a
palindrome");
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 7:
package com.jbrec.vjmr;
import java.util.Scanner;
/**
* @author JMR
*/
class SortingNames
{
public static void main(String[] jbrec)
{
System.out.print("Enter The number of Names you want to enter:");
Scanner objScanner = new Scanner(System.in);
int n = objScanner.nextInt();
String names[] = new String[n];
for (int i = 1; i <= n; i++)
{
System.out.print("Enter Name " + i + ":");
names[i - 1] = objScanner.next();
}
System.out.println("\nNames in Ascending Order");
for (int j = 0; j < names.length; j++)
{
for (int i = j + 1; i < names.length; i++)
{
if (names[i].compareToIgnoreCase(names[j]) < 0)
{
String temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
System.out.println(names[j]);
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 8:
package com.jbrec.vjmr;
import java.util.Scanner;
import java.util.StringTokenizer;
/**
* @author JMR
*/
public class FrequencyOfWords
{
public static void main(String[] jbrec)
{
System.out.print("Enter Some Text:");
Scanner objScanner = new Scanner(System.in);
String text = objScanner.nextLine();
String ans = "";
do
{
System.out.print("Enter A Word You Want To Verify The
Frequency:");
String word = objScanner.next();
int count = 0;
StringTokenizer st = new StringTokenizer(text);
while (st.hasMoreTokens())
{
if (st.nextToken().equals(word))
{
count++;
}
}
System.out.println("Frequency of \"" + word + "\" is " + count + "
times");
System.out.print("Do You Want Verify The Frequency Of One More
Word[Y/N]:");
ans = objScanner.next();
} while (ans.equals("Y") || ans.equals("y"));
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that reads a file from the user then display the information
about whether that file exists, whether the file is readable, whether that file is
writable, the type of file and the length of the file in bytes.
2) Write a Java program that reads a file and displays the file on the screen, with a line
no before each line.
3) Write a Java program that displays the number of characters, lines and words in a text
file.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 9:
package com.jbrec.vjmr;
import java.io.File;
import java.util.Scanner;
/**
* @author JMR
*/
public class FileInfo
{
public static void main(String[] jbrec)
{
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter A File Name:");
String fileName = objScanner.next();
File f = new File(fileName);
String result = f.exists() ? "EXISTS." : "NOT EXISTS.";
System.out.println("THE GIVEN FILE : " + result);
if (f.exists())
{
result = f.canRead() ? "READABLE." : "NOT READABLE.";
System.out.println("THE GIVEN FILE : " + result);
result = f.canWrite() ? "WRITEABLE." : "NOT WRITEABLE.";
System.out.println("THE GIVEN FILE : " + result);
System.out.println("THE GIVEN FILE LENGTH " + f.length() + " IN
BYTES.");
if (fileName.endsWith(".jpg") || fileName.endsWith(".gif") ||
fileName.endsWith(".png"))
{
System.out.println("THE GIVEN FILE IS A IMAGE FILE.");
}
else if (fileName.endsWith(".exe"))
{
System.out.println("THE GIVEN FILE IS A EXECUTABLE
FILE.");
}
else if (fileName.endsWith(".txt"))
{
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
System.out.println("THE GIVEN FILE IS A TEXT FILE.");
}
else
{
System.out.println("THE GIVEN FILE TYPE IS
UNKNOEN.");
}
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 10:
package com.jbrec.vjmr;
import java.io.*;
import java.util.Scanner;
/**
* @author JMR
*/
public class FileContent
{
public static void main(String[] jbrec)
{
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter A File Name:");
String fileName = objScanner.next();
File file = new File(fileName);
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
long lineno=0;
try
{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0)
{
System.out.println(++lineno + ":" +dis.readLine());
}
fis.close();
bis.close();
dis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 11:
package com.jbrec.vjmr;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class FileWordCount
{
public static void main(String[] jbrec) throws IOException
{
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter A Text File Name:");
String fileName = objScanner.next();
int words = 0, lines = 0, chars = 0, c = 0;
boolean lastWhite = true;
String whiteSpace = " \t\n\r";
FileReader fr = new FileReader(fileName);
while ((c = fr.read()) != -1)
{
chars++;
if (c == '\n')
{
lines++;
}
int index = whiteSpace.indexOf(c);
if (index == -1)
{
if (lastWhite == true)
{
++words;
}
lastWhite = false;
}
else
{
lastWhite = true;
}
}
if (chars != 0)
{
++lines;
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
System.out.print("NO OF LINES:" + lines + "\n" + "NO OF WORDS :" +
words + "\n" + "NO OF CHARS:" + chars);
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
Write a Java program that:
I.
Implements stack ADT.
II.
Converts infix expression Into Postfix form
III.
Evaluates the postfix expression
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 12:
package com.jbrec.vjmr;
import java.util.Scanner;
abstract class StackADT
{
int stack[] = new int[5];
int count;
StackADT()
{
count = -1;
}
abstract void push(int a);
abstract int pop();
abstract void display();
}
class Stack extends StackADT
{
@Override
void push( int a)
{
if (count == 4)
{
System.out.println("STACK IS FULL");
}
else
{
stack[++count] = a;
}
}
@Override
int pop()
{
if (count == -1)
{
System.out.println("STACK IS EMPTY");
return 0;
}
else
{
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
return stack[count--];
}
}
@Override
void display()
{
System.out.println("ELEMENTS IN STACK");
for ( int i : stack)
{
System.out.print(" " + i);
}
System.out.println();
}
}
public class StackADTEx
{
public static void main(String[] jbrec)
{
Scanner objScanner = new Scanner(System.in);
Stack objStack = new Stack();
while (true)
{
System.out.println("MENU");
System.out.println("1.PUSH ELEMENT");
System.out.println("2.POP ELEMENT");
System.out.println("3.DISPLAY ELEMENT");
System.out.println("4.EXIT");
System.out.print("ENTER YOUR CHOICE[1/2/3/4]:");
byte choice = objScanner.nextByte();
switch (choice)
{
case 1:
System.out.print("ENTER A NO:");
int value = objScanner.nextInt();
objStack.push(value);
break;
case 2:
if ((value = objStack.pop()) != 0)
{
System.out.print("THE DELETED ELEMENT IS :" +
value);
}
break;
case 3:
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
objStack.display();
break;
case 4:
System.exit(0);
break;
default:
System.out.print("INVALID CHOICE.");
}
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 13:
package com.jbrec.vjmr;
import java.util.EmptyStackException;
import java.util.Scanner;
public class InfixToPostfix
{
public static void main(String[] jbrec)
{
Scanner objScanner=new Scanner(System.in);
System.out.print("Enter A Infix Expression:");
String infixExp=objScanner.nextLine();
System.out.println("Postfix Expresson of \"" +infixExp +"\" is " +
convertInfixToPostfix(infixExp));
/*String a = "3+ 4*9 -2/3";
System.out.println(a + " > " + convertInfixToPostfix(a));
a = "(3+4) * (9 - 3) / 8";
System.out.println(a + " > " + convertInfixToPostfix(a));
a = "(3+45) * (98 - 3) / 8";
System.out.println(a + " > " + convertInfixToPostfix(a));*/
}
public static String convertInfixToPostfix(String infixExpr)
{
StringBuffer infix = new StringBuffer(infixExpr);
StringBuffer postfix = new StringBuffer();
MyStack stack = new MyStack();
try
{
while (infix.length() > 0)
{
//until all has been processed
//operand -- move to postfix
if (Character.isDigit(infix.charAt(0)))
{
if (postfix.length() > 0 &&
Character.isDigit(postfix.charAt(postfix.length() - 1)))
{
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
//last postfix char is a digit, so append a space first
postfix.append(' ');
}
//in the case of a single/first digit, just append
postfix.append(infix.charAt(0)); //charAt(0) deleted below
while (infix.length() > 1 && Character.isDigit(infix.charAt(1)))
{
//there are additional digits to this number, so append all
postfix.append(infix.charAt(1));
infix.deleteCharAt(1);
}
//operators -- remove any operators of >= precedence, then
push
}
else if (infix.charAt(0) == '+' || infix.charAt(0) == '-')
{
//pop any other operators
while (!stack.empty() && isOperator(((Character)
stack.peek()).charValue()))
{
postfix.append(stack.pop());
}
stack.push(new Character(infix.charAt(0)));
}
else if (infix.charAt(0) == '*' || infix.charAt(0) == '/')
{
//pop only other '*' or '/'
while (!stack.empty() && (((Character)
stack.peek()).charValue() == '*' ||((Character)
stack.peek()).charValue() == '/'))
{
postfix.append(stack.pop());
}
stack.push(new Character(infix.charAt(0)));
// '(' -- stack it
}
else if (infix.charAt(0) == '(')
{
stack.push(new Character(infix.charAt(0)));
// ')' -- unstack until hit corresponding '('
}
else if (infix.charAt(0) == ')')
{
char popped = ((Character) stack.pop()).charValue();
while (popped != '(')
{
postfix.append(popped);
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
popped = ((Character) stack.pop()).charValue();
}
//spaces
}
else if (infix.charAt(0) == ' ')
{
// just ignore and move on
//hit something we don't know how to process
}
else
{
throw new IllegalArgumentException();
}
//now remove the char just processed
infix.deleteCharAt(0);
}
//done with infix, but not with stack
while (!stack.empty())
{
postfix.append(stack.pop());
}
}
catch (EmptyStackException ese)
{
//popped something when we shouldn't have, so bad input
throw new IllegalArgumentException();
}
return postfix.toString();
}
/**
* Returns true if c is a legitimate operator for this calculator
*/
protected static boolean isOperator(char c)
{
switch (c)
{
case '+':
case '-':
case '*':
case '/':
return true;
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
default:
return false;
}
}
}
package com.jbrec.vjmr;
public class DLLNode
{
private Object contents;
private DLLNode next;
private DLLNode prev;
/**
* Creates a new Node with no links
*/
public DLLNode(Object contents)
{
this(contents, null, null);
}
/**
* Create a new node with the given contents, and links
*/
public DLLNode(Object contents, DLLNode prev, DLLNode next)
{
this.setValue(contents);
this.setNext(next);
this.setPrev(prev);
}
/**
* Sets this node to contain the given value
*
* @param value The new contents of this node.
*/
public void setValue(Object value)
{
this.contents = value;
}
/**
* Returns this node's contents.
*/
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
public Object getValue()
{
return this.contents;
}
/**
* Set this node's next reference to the given node.
*
* @param next The node this node should point to as next in a list.
*/
public void setNext(DLLNode next)
{
this.next = next;
}
/**
* Returns the next node in a list after this node.
*/
public DLLNode getNext()
{
return this.next;
}
/**
* Set this node's previous reference to the given node.
*
* @param prev The node this node should point to as coming before
*
it in a list.
*/
public void setPrev(DLLNode prev)
{
this.prev = prev;
}
/**
* Returns the node before this node in a list.
*/
public DLLNode getPrev()
{
return this.prev;
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
package com.jbrec.vjmr;
import java.util.EmptyStackException;
public class MyStack
{
/*
* IMPL NOTE: uses DLLNodes, even though singly-linked nodes are all
* that are actually required.
* Doesn't currently bother to set the prev links.
*/
protected DLLNode top;
/** Returns whether this stack is empty */
public boolean empty()
{
return (top == null);
}
/** Pushes the given Object onto the top of this stack. */
public void push(Object x)
{
top = new DLLNode(x, null, top);
}
/**
* Returns the Object at the top of this stack.
* The returned object is not removed or otherwise affected.
*/
public Object peek()
{
if (top == null)
{
throw new EmptyStackException();
}
else
{
return top.getValue();
}
}
/** Removes and returns the Object at the top of the stack. */
public Object pop()
{
if (top == null)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
{
throw new EmptyStackException();
}
else
{
DLLNode removed = top;
top = top.getNext();
return removed.getValue();
}
}
/** Removes all objects from this stack, leaving this stack empty. */
public void popAll()
{
top = null;
}
/* overrides Object.toString */
@Override
public String toString()
{
String s = "[(top)>";
DLLNode curr = top;
while (curr != null)
{
s += " " + curr.getValue().toString();
curr = curr.getNext();
}
s += "]";
return s;
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 14:
package com.jbrec.vjmr;
import java.util.Scanner;
public class EvaluatePostfix
{
public static void main(String[] jbrec)
{
Scanner objScanner = new Scanner(System.in);
System.out.print("Enter A Postfix Expression:");
String postExp = objScanner.nextLine();
System.out.println("Result :" + evaluate(postExp));
}
public static float evaluate(String postfixExpr)
{
MyStack stack = new MyStack();
StringBuffer postfix = new StringBuffer(postfixExpr);
try
{
while (postfix.length() > 0)
{
if (Character.isDigit(postfix.charAt(0)))
{
//operands
//get all digits of this number
StringBuffer num = new StringBuffer();
while (postfix.length() > 0 &&
Character.isDigit(postfix.charAt(0)))
{
num.append(postfix.charAt(0));
postfix.deleteCharAt(0);
}
stack.push(new Float(num.toString()));
}
else
{
//operators
Float rhs, lhs;
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
switch (postfix.charAt(0))
{
case '+':
rhs = new Float(stack.pop().toString());
lhs = new Float(stack.pop().toString());
stack.push(new Float(lhs.floatValue() +
rhs.floatValue()));
break;
case '-':
rhs = new Float(stack.pop().toString());
lhs = new Float(stack.pop().toString());
stack.push(new Float(lhs.floatValue() rhs.floatValue()));
break;
case '*':
rhs = new Float(stack.pop().toString());
lhs = new Float(stack.pop().toString());
stack.push(new Float(lhs.floatValue() *
rhs.floatValue()));
break;
case '/':
rhs = new Float(stack.pop().toString());
lhs = new Float(stack.pop().toString());
stack.push(new Float(lhs.floatValue() /
rhs.floatValue()));
break;
case ' ':
//do nothing with it
break;
default:
//um... not supported
throw new IllegalArgumentException();
}
postfix.deleteCharAt(0);
}
}
//now postfix fully parsed
float result = ((Float) stack.pop()).floatValue();
if (!stack.empty())
{
//then result not really the correct result
throw new IllegalArgumentException();
}
else
{
return result;
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
}
catch (java.util.EmptyStackException ese)
{
throw new IllegalArgumentException();
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Develop an applet that displays a simple message.
2) Develop an applet 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.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 15:
package com.jbrec.vjmr;
import java.applet.Applet;
import java.awt.Graphics;
/*
<applet code="com.jbrec.vjmr.SimpleMessageApplet" width="500" height="300">
</applet>
*/
public class SimpleMessageApplet extends Applet
{
String message;
@Override
public void init()
{
message = "THIS IS SIMPLE MESSAGE FROM APPLETE";
}
@Override
public void paint(Graphics g)
{
g.drawString(message, 10, 10);
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 16:
package com.jbrec.vjmr;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
/*
<applet code="com.jbrec.vjmr.FactorialApplet" width="500" height="300">
</applet>
*/
public class FactorialApplet extends JApplet implements ActionListener
{
JTextField field1, field2;
JButton compute;
@Override
public void init()
{
setLayout(new FlowLayout(FlowLayout.RIGHT));
JLabel label1 = new JLabel("Enter A No:");
field1 = new JTextField(20);
JLabel label2 = new JLabel("Factorial:");
field2 = new JTextField(20);
compute = new JButton("Compute");
compute.addActionListener(this);
add(label1);
add(field1);
add(label2);
add(field2);
add(compute);
}
public void actionPerformed(ActionEvent e)
{
try
{
long no = Long.parseLong(field1.getText());
long fact = 1;
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
for (long j = no; j > 0; j--)
{
fact = fact * j;
}
field2.setText("" + fact);
}
catch(Exception e1)
{
JOptionPane.showMessageDialog(null,
e1,"Error",JOptionPane.ERROR_MESSAGE);
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) 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.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 17:
package com.jbrec.vjmr;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Calculator extends JFrame
{
Calculator()
{
CalculatorPanel calc = new CalculatorPanel();
getContentPane().add(calc);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Calculator Demo");
setResizable(false);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new Calculator();
}
});
}
}
package com.jbrec.vjmr;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CalculatorPanel extends JPanel implements ActionListener
{
JButton n1, n2, n3, n4, n5, n6, n7, n8, n9, n0, plus, minus, mul, div, dot, equal;
static JTextField result = new JTextField("0", 45);
static String lastCommand ="";
JOptionPane p = new JOptionPane();
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
double preRes = 0, secVal = 0, res;
private static void assign(String no)
{
if ((result.getText()).equals("0"))
{
result.setText(no);
}
else if (lastCommand.equals("="))
{
result.setText(no);
lastCommand ="";
}
else
{
result.setText(result.getText() + no);
}
}
public CalculatorPanel()
{
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300, 200);
add(result, BorderLayout.NORTH);
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(4, 4));
n7 = new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8 = new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9 = new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div = new JButton("/");
panel.add(div);
div.addActionListener(this);
n4 = new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5 = new JButton("5");
panel.add(n5);
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
n5.addActionListener(this);
n6 = new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul = new JButton("*");
panel.add(mul);
mul.addActionListener(this);
n1 = new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2 = new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3 = new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus = new JButton("-");
panel.add(minus);
minus.addActionListener(this);
dot = new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0 = new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal = new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus = new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel, BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if (ae.getSource() == n1)
{
assign("1");
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
}
else if (ae.getSource() == n2)
{
assign("2");
}
else if (ae.getSource() == n3)
{
assign("3");
}
else if (ae.getSource() == n4)
{
assign("4");
}
else if (ae.getSource() == n5)
{
assign("5");
}
else if (ae.getSource() == n6)
{
assign("6");
}
else if (ae.getSource() == n7)
{
assign("7");
}
else if (ae.getSource() == n8)
{
assign("8");
}
else if (ae.getSource() == n9)
{
assign("9");
}
else if (ae.getSource() == n0)
{
assign("0");
}
else if (ae.getSource() == dot)
{
if (((result.getText()).indexOf(".")) == -1)
{
result.setText(result.getText() + ".");
}
}
else if (ae.getSource() == minus)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "-";
result.setText("0");
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
else if (ae.getSource() == div)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "/";
result.setText("0");
}
else if (ae.getSource() == equal)
{
secVal = Double.parseDouble(result.getText());
if (lastCommand.equals("/"))
{
res = preRes / secVal;
}
else if (lastCommand.equals("*"))
{
res = preRes * secVal;
}
else if (lastCommand.equals("-"))
{
res = preRes - secVal;
}
else if (lastCommand.equals("+"))
{
res = preRes + secVal;
}
result.setText(" " + res);
lastCommand = "=";
}
else if (ae.getSource() == mul)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "*";
result.setText("0");
}
else if (ae.getSource() == plus)
{
preRes = Double.parseDouble(result.getText());
lastCommand = "+";
result.setText("0");
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program for handling mouse events.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 18:
package com.jbrec.vjmr;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JLabel;
public class MouseEvents extends JFrame implements MouseListener, MouseMotionListener
{
JLabel mouseStatus;
public MouseEvents()
{
mouseStatus = new JLabel();
getContentPane().add(mouseStatus);
addMouseListener(this);
addMouseMotionListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Mouse Events Example");
setSize(500, 500);
setVisible(true);
}
public void mouseClicked(MouseEvent e)
{
mouseStatus.setText("Mouse Clicked");
}
public void mousePressed(MouseEvent e)
{
mouseStatus.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e)
{
mouseStatus.setText("Mouse Released");
}
public void mouseEntered(MouseEvent e)
{
mouseStatus.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
{
mouseStatus.setText("Mouse Exited");
}
public void mouseDragged(MouseEvent e)
{
mouseStatus.setText("Mouse Dragged");
}
public void mouseMoved(MouseEvent e)
{
mouseStatus.setText("Mouse Moved");
}
public static void main(String[] jbrec)
{
MouseEvents objME=new MouseEvents();
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that creates three threads. First thread displays “Good Morning”
every one second, the second thread displays “Hello” every two seconds and the third
thread displays “Welcome” every three seconds.
2) Write a Java program that correctly implements producer consumer problem using the
concept of inter thread communication.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 19:
package com.jbrec.vjmr;
public class ThreadsDemo
{
public static void main(String[] jbrec)
{
new ThreadsMessages("Good Morning",1000);
new ThreadsMessages("Hello",2000);
new ThreadsMessages("Welcome",3000);
try
{
Thread.sleep(10000);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
package com.jbrec.vjmr;
public class ThreadsMessages implements Runnable
{
Thread t;
String message;
int delay;
public ThreadsMessages(String message, int time)
{
this.message = message;
delay = time;
t = new Thread(this, message);
t.start();
}
public void run()
{
try
{
for (int i = 5; i > 0; i--)
{
System.out.println(message);
Thread.sleep(delay);
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 20:
package com.jbrec.vjmr;
public class Producer implements Runnable
{
Queue q;
Producer(Queue q)
{
this.q = q;
new Thread(this, "Producer").start();
}
public void run()
{
int i = 0;
while (true)
{
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
e.printStackTrace();
}
q.put(i++);
}
}
}
package com.jbrec.vjmr;
public class Consumer implements Runnable
{
Queue q;
Consumer(Queue q)
{
this.q = q;
new Thread(this, "Consumer").start();
}
public void run()
{
while (true)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
{
try
{
Thread.sleep(1000);
}
catch (Exception e)
{
e.printStackTrace();
}
q.get();
}
}
}
package com.jbrec.vjmr;
public class Queue
{
int n;
boolean valueSet = false;
synchronized int get()
{
if (!valueSet)
{
try
{
wait();
}
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}
synchronized void put(int n)
{
if (valueSet)
{
try
{
wait();
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
catch (InterruptedException e)
{
System.out.println("InterruptedException caught");
}
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}
package com.jbrec.vjmr;
public class Producer_Consumer_Impl
{
public static void main(String[] jbrec)
{
Queue q = new Queue();
new Producer(q);
new Consumer(q);
System.out.println("Press Control-C to stop.");
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a program that creates 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.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 21:
package com.jbrec.vjmr;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DivisionFrame extends JFrame implements ActionListener
{
JLabel label1, label2, label3;
JTextField number1, number2, result;
public DivisionFrame()
{
Container c = getContentPane();
label1 = new JLabel("Number1:");
label2 = new JLabel("Number2:");
label3 = new JLabel("Result:");
number1 = new JTextField(10);
number2 = new JTextField(10);
result = new JTextField(10);
JButton clear = new JButton("Clear");
clear.addActionListener(this);
JButton division = new JButton("Divide");
division.addActionListener(this);
c.add(label1);
c.add(number1);
c.add(label2);
c.add(number2);
c.add(label3);
c.add(result);
c.add(division);
c.add(clear);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("DivisionFrame Example");
setLayout(new FlowLayout(FlowLayout.RIGHT));
setResizable(false);
setSize(190, 150);
setVisible(true);
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("Clear"))
{
number1.setText("");
number2.setText("");
result.setText("");
}
else
{
try
{
result.setText("" +(Integer.parseInt(number1.getText()) /
Integer.parseInt(number2.getText())));
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex, "Error",
JOptionPane.ERROR_MESSAGE);
}
}
}
public static void main(String[] jbrec)
{
DivisionFrame objDF = new DivisionFrame();
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a Java program that implements a simple client/server application. The client
sends data to a server. The server receives the data, uses it to produce a result, and
then sends the result back to the client. The client displays the result on the console.
For ex: The data sent from the client is the radius of a circle, and the result produced
by the server is the area of the circle. (Use java.net)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 22:
package com.jbrec.vjmr;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ServerApp
{
public static void main(String[] jbrec) throws IOException
{
int serverPort = 3333, clientPort = 3334, pos = 0;
byte buffer[] = new byte[1024];
DatagramSocket objDS = new DatagramSocket(serverPort);
DatagramPacket objDP = new DatagramPacket(buffer, buffer.length);
objDS.receive(objDP);
String c = new String(objDP.getData(), 0, objDP.getLength());
int r = Integer.parseInt(c.trim());
float area = r * r * (22 / 7);
System.out.print("The Calculated Area Sent");
c = (String.valueOf(area));
for (int i = 0; i < c.length(); i++)
{
buffer[i] = (byte) c.charAt(i);
}
objDS.send(new DatagramPacket(buffer, c.length(),
InetAddress.getLocalHost(), clientPort));
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
package com.jbrec.vjmr;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
public class ClientApp
{
public static void main(String[] jbrec) throws IOException
{
int serverPort = 3333, clientPort = 3334, pos = 0;
byte buffer[] = new byte[1024];
DatagramSocket objDS = new DatagramSocket(clientPort);
System.out.print("Enter The Radius Of The Cricle:");
buffer[pos++] = (byte) System.in.read();
objDS.send(new DatagramPacket(buffer, pos, InetAddress.getLocalHost(),
serverPort));
DatagramPacket objDP = new DatagramPacket(buffer, buffer.length);
objDS.receive(objDP);
System.out.print("The Area is: " + new String(objDP.getData(), 0,
objDP.getLength()));
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a java program that simulates a traffic light. The program lets the user select
one of three lights: red, yellow, or green. When a radio button is selected, the light is
turned on, and only one light can be on at a time No light is on when the program
starts.
2) Write a Java program that allows the user to draw lines, rectangles and ovals.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 23:
package com.jbrec.vjmr;
public class TrafficLightsSimulation extends javax.swing.JFrame
{
/** Creates new form TrafficLightsSimulation */
public TrafficLightsSimulation()
{
initComponents();
red.setVisible(false);
green.setVisible(false);
yellow.setVisible(false);
}
private void initComponents()
{
buttonGroup1 = new javax.swing.ButtonGroup();
greenButton = new javax.swing.JRadioButton();
yellowButton = new javax.swing.JRadioButton();
redButton = new javax.swing.JRadioButton();
jPanel1 = new javax.swing.JPanel();
red = new javax.swing.JLabel();
green = new javax.swing.JLabel();
yellow = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE
);
setTitle("TrafficLightsSimulation");
setResizable(false);
buttonGroup1.add(greenButton);
greenButton.setFont(new java.awt.Font("Tahoma", 1, 14));
greenButton.setText("Green");
greenButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
greenButtonActionPerformed(evt);
}
});
buttonGroup1.add(yellowButton);
yellowButton.setFont(new java.awt.Font("Tahoma", 1, 14));
yellowButton.setText("Yellow");
yellowButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
yellowButtonActionPerformed(evt);
}
});
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
buttonGroup1.add(redButton);
redButton.setFont(new java.awt.Font("Tahoma", 1, 14));
redButton.setText("Red");
redButton.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
redButtonActionPerformed(evt);
}
});
jPanel1.setBackground(new java.awt.Color(8, 8, 7));
red.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/com/jbrec/vjmr/red.JPG
green.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/com/jbrec/vjmr/green.JPG"))
);
yellow.setIcon(new
javax.swing.ImageIcon(getClass().getResource("/com/jbrec/vjmr/yellow.JPG"
)));
javax.swing.GroupLayout jPanel1Layout = new
javax.swing.GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addGap(0, 100, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig
nment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(19, 19, 19)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig
nment.LEADING)
.addComponent(red, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(green, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addComponent(yellow, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGap(19, 19, 19)))
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEA
DING)
.addGap(0, 221, Short.MAX_VALUE)
.addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alig
nment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addGap(6, 6, 6)
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
.addComponent(red, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(green, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(yellow, javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGap(19, 19, 19)))
);
javax.swing.GroupLayout layout = new
javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE,
javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(37, 37, 37)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.L
EADING)
.addComponent(redButton)
.addComponent(greenButton)
.addComponent(yellowButton))
.addGap(28, 28, 28))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.L
EADING)
.addGroup(layout.createSequentialGroup()
.addGap(59, 59, 59)
.addComponent(redButton)
.addGap(20, 20, 20)
.addComponent(greenButton)
.addGap(18, 18, 18)
.addComponent(yellowButton))
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, 221,
javax.swing.GroupLayout.PREFERRED_SIZE)))
.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE,
Short.MAX_VALUE))
);
pack();
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
}
private void redButtonActionPerformed(java.awt.event.ActionEvent evt)
{
red.setVisible(true);
green.setVisible(false);
yellow.setVisible(false);
}
private void greenButtonActionPerformed(java.awt.event.ActionEvent evt)
{
red.setVisible(false);
green.setVisible(true);
yellow.setVisible(false);
}
private void yellowButtonActionPerformed(java.awt.event.ActionEvent evt)
{
red.setVisible(false);
green.setVisible(false);
yellow.setVisible(true);
}
public static void main(String args[])
{
java.awt.EventQueue.invokeLater(new Runnable()
{
public void run()
{
new TrafficLightsSimulation().setVisible(true);
}
});
}
private javax.swing.ButtonGroup buttonGroup1;
private javax.swing.JLabel green;
private javax.swing.JRadioButton greenButton;
private javax.swing.JPanel jPanel1;
private javax.swing.JLabel red;
private javax.swing.JRadioButton redButton;
private javax.swing.JLabel yellow;
private javax.swing.JRadioButton yellowButton;
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 24:
package com.jbrec.vjmr;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class DrawFigures extends JFrame implements ActionListener, MouseListener
{
JButton line, rect, oval;
int startX, startY, endX, endY, drawCode = 1;
public DrawFigures()
{
line = new JButton("DRAW LINE");
line.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
line.addActionListener(this);
getContentPane().add(line);
rect = new JButton("DRAW RECTANGLE");
rect.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
rect.addActionListener(this);
getContentPane().add(rect);
oval = new JButton("DRAW OVAL");
oval.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
oval.addActionListener(this);
getContentPane().add(oval);
addMouseListener(this);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("Draw Lines, Rectangles and Ovals");
setCursor(Cursor.getPredefinedCursor(Cursor.CROSSHAIR_CURSOR));
setLayout(new FlowLayout());
setSize(500, 500);
setVisible(true);
}
public static void main(String[] args)
{
SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
new DrawFigures();
}
});
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
public void mouseClicked(MouseEvent e)
{
}
public void mousePressed(MouseEvent e)
{
startX = e.getX();
startY = e.getY();
}
public void mouseReleased(MouseEvent e)
{
endX = e.getX();
endY = e.getY();
Graphics g = getGraphics();
if (drawCode == 1)
{
drawLine(g);
}
else if (drawCode == 2)
{
drawRect(g);
}
else
{
drawOval(g);
}
}
private void drawLine(Graphics g)
{
g.drawLine(startX, startY, endX, endY);
}
private void drawRect(Graphics g)
{
if (startX > endX)
{
g.drawRect(endX, endY, -(endX - startX), -(endY - startY));
}
else
{
g.drawRect(startX, startY, endX - startX, endY - startY);
}
}
private void drawOval(Graphics g)
{
if (startX > endX)
{
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
g.drawOval(endX, endY, -(endX - startX), -(endY - startY));
}
else
{
g.drawOval(startX, startY, endX - startX, endY - startY);
}
}
public void mouseEntered(MouseEvent e)
{
}
public void mouseExited(MouseEvent e)
{
}
public void actionPerformed(ActionEvent e)
{
if (e.getActionCommand().equals("DRAW LINE"))
{
drawCode = 1;
}
else if (e.getActionCommand().equals("DRAW RECTANGLE"))
{
drawCode = 2;
}
else
{
drawCode = 3;
}
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
1) Write a java program to create an abstract class named Shape that contains an empty
method named numberOfSides( ).Provide three classes named Trapezoid, Triangle
and Hexagon such that each one of the classes extends the class Shape. Each one of
the classes contains only the method numberOfSides ( ) that shows the number of
sides in the given geometrical figures.
2) 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 JTable
component.
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 25:
package com.jbrec.vjmr;
abstract class Shape
{
abstract void numberOfSides();
}
package com.jbrec.vjmr;
class Triangle extends Shape
{
@Override
void numberOfSides()
{
System.out.println("NO OF SIDES IN TRIANGLE : 3");
}
}
package com.jbrec.vjmr;
class Trapezoid extends Shape
{
@Override
void numberOfSides()
{
System.out.println("NO OF SIDES IN TRAPEZOID : 4");
}
}
package com.jbrec.vjmr;
class Hexagon extends Shape
{
@Override
void numberOfSides()
{
System.out.println("NO OF SIDES IN HEXAGON : 5");
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
package com.jbrec.vjmr;
public class NumbeOfSides
{
public static void main(String[] jbrec)
{
Triangle objTriangle = new Triangle();
objTriangle.numberOfSides();
Trapezoid objTrapezoid = new Trapezoid();
objTrapezoid.numberOfSides();
Hexagon objHexagon = new Hexagon();
objHexagon.numberOfSides();
}
}
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
PROGRAM 26:
package com.jbrec.vjmr;
import javax.swing.*;
import java.awt.*;
import java.io.*;
import java.util.*;
public class JTableEx extends JPanel
{
public JTableEx()
{
super(new GridLayout(1, 0));
File file = new File("D:\\Table.txt");
FileInputStream fis = null;
BufferedInputStream bis = null;
DataInputStream dis = null;
String initData[] = new String[100];
String[] columnNames = null;
Object[][] data = null;
int rows = 0;
try
{
fis = new FileInputStream(file);
bis = new BufferedInputStream(fis);
dis = new DataInputStream(bis);
while (dis.available() != 0)
{
initData[rows++] = dis.readLine();
}
StringTokenizer st = new StringTokenizer(initData[0]);
columnNames = new String[st.countTokens()];
data = new Object[rows - 1][st.countTokens()];
for (int i = 0; i < rows; i++)
{
if (i != 0)
{
int k = 0;
StringTokenizer st1 = new StringTokenizer(initData[i]);
while (st1.hasMoreTokens())
{
data[i - 1][k++] = st1.nextToken();
}
}
else
{
http://vjmr.wordpress.com
Department of Computer Science & Engineering
OOP Lab Manual
int j = 0;
while (st.hasMoreTokens())
{
columnNames[j++] = st.nextToken();
}
}
}
fis.close();
bis.close();
dis.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
final JTable table = new JTable(data, columnNames);
table.setPreferredScrollableViewportSize(new Dimension(500, 100));
table.setFillsViewportHeight(true);
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
private static void createAndShowGUI()
{
JFrame frame = new JFrame("SimpleTableDemo");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JTableEx newContentPane = new JTableEx();
newContentPane.setOpaque(true);
frame.setContentPane(newContentPane);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args)
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
public void run()
{
createAndShowGUI();
}
});
}
}
http://vjmr.wordpress.com