http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/
Saturday, 9 August 2014
Thursday, 3 October 2013
https://www.digitalocean.com/community/articles/how-to-install-apache-tomcat-on-ubuntu-12-04
https://www.digitalocean.com/community/articles/how-to-install-apache-tomcat-on-ubuntu-12-04
https://www.digitalocean.com/community/articles/how-to-install-apache-tomcat-on-ubuntu-12-04
https://www.digitalocean.com/community/articles/how-to-install-apache-tomcat-on-ubuntu-12-04
Monday, 18 March 2013
configuring pache tomcat and eclipse in ubuntu
sudo apt-get install tomcat7 tomcat7-docs tomcat7-examples tomcat7-admin -y
- select Windows -> Preferences -> Server -> Runtime Environments;
- press Add…;
- select “Apache Tomcat v7.0″;
- enter “/usr/share/tomcat7″ into the “Tomcat installation directory” field;
- press Ok;
- as Target Runtime select “Apache Tomcat v7.0″;
- press twice Next;
- select the “Generate the web.xml deployment descriptor” option at the final dialog;
- press Finish;
cd ~/workspace/.metadata/.plugins/org.eclipse.core.runtime/.settings/ rm org.eclipse.jst.server.tomcat.core.prefs rm org.eclipse.wst.server.core.prefs
cd /usr/share/tomcat7 sudo ln -s /var/lib/tomcat7/conf conf sudo ln -s /etc/tomcat7/policy.d/03catalina.policy conf/catalina.policy sudo ln -s /var/log/tomcat7 log sudo chmod -R 777 /usr/share/tomcat7/conf
cp /etc/tomcat7/* workspace/Servers/Tomcat\ v7.0\ Server\ at\ localhost-config/
- go to Window->Show View->Other…;
- choose the Servers under the Server category;
- choose Apache / Tomcat v7.0 Server and press Next;
- enter “/usr/share/tomcat7″ into the “Tomcat installation directory” field;
- press Next;
- select your project on the left pane under “Available” and press Add> to move it to the right pane under “Configured”;
- press Finish”;
sudo service tomcat7 stop
and to disable Tomcat to automatically start at boot run:
sudo update-rc.d tomcat7 disable
Your web services will be automatically deployed in the following folder:
~/workspace/.metadata/.plugins/org.eclipse.wst.server.core/tmp0/wtpwebapps/
Your web service will be accessible through the following URI:
http://localhost:8080/EclipseProjectName/x/y/z
Where:
- x = the root of your service set inside the tag url-pattern in web.xml;
- y = the path set for your class
- z = the path set for your method
Tuesday, 8 January 2013
Java Sorting: Comparator vs Comparable Tutorial
Article By Kamal Mettananda on July 10, 2008
Java Comparators and Comparables? What are they? How do we use them? This is a question we received from one of our readers. This article will discuss the java.util.Comparator and java.lang.Comparable in details with a set of sample codes for further clarifications.
Prerequisites
Basic Java knowledge
System Requirements
JDK installed
What are Java Comparators and Comparables?
As both names suggest (and you may have guessed), these are used for comparing objects in Java. Using these concepts; Java objects can be
sorted according to a predefined order.
Two of these concepts can be explained as follows.
Comparable
A comparable object is capable of comparing itself with another object. The class itself must implements the java.lang.Comparable interface in order to be able to compare its instances.
Comparator
A comparator object is capable of comparing two different objects. The class is not comparing its instances, but some other class’s instances. This comparator class must implement the java.util.Comparator interface.
Do we need to compare objects?
The simplest answer is yes. When there is a list of objects, ordering these objects into different orders becomes a must in some situations. For example; think of displaying a list of employee objects in a web page. Generally employees may be displayed by sorting them using the employee id. Also there will be requirements to sort them according to the name or age as well. In these situations both these (above defined) concepts will become handy.
How to use these?
There are two interfaces in Java to support these concepts, and each of these has one method to be implemented by user.
Those are;
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
positive – this object is greater than o1
zero – this object equals to o1
negative – this object is less than o1
java.util.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
positive – o1 is greater than o2
zero – o1 equals to o2
negative – o1 is less than o2
java.util.Collections.sort(List) and java.util.Arrays.sort(Object[]) methods can be used to sort using natural ordering of objects.
java.util.Collections.sort(List, Comparator) and java.util.Arrays.sort(Object[], Comparator) methods can be used if a Comparator is available for comparison.
The above explained Employee example is a good candidate for explaining these two concepts. First we’ll write a simple Java bean to represent the Employee.
public class Employee {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
// set values on attributes
}
// getters & setters
}
Next we’ll create a list of Employees for using in different sorting requirements. Employees are added to a List without any specific order in the following class.
import java.util.*;
public class Util {
public static List
List
col.add(new Employee(5, "Frank", 28));
col.add(new Employee(1, "Jorge", 19));
col.add(new Employee(6, "Bill", 34));
col.add(new Employee(3, "Michel", 10));
col.add(new Employee(7, "Simpson", 8));
col.add(new Employee(4, "Clerk",16 ));
col.add(new Employee(8, "Lee", 40));
col.add(new Employee(2, "Mark", 30));
return col;
}
}
Sorting in natural ordering
Employee’s natural ordering would be done according to the employee id. For that, above Employee class must be altered to add the comparing ability as follows.
public class Employee implements Comparable
private int empId;
private String name;
private int age;
/**
* Compare a given Employee with this object.
* If employee id of this object is
* greater than the received object,
* then this object is greater than the other.
*/
public int compareTo(Employee o) {
return this.empId - o.empId ;
}
….
}
The new compareTo() method does the trick of implementing the natural ordering of the instances. So if a collection of Employee objects is sorted using Collections.sort(List) method; sorting happens according to the ordering done inside this method.
We’ll write a class to test this natural ordering mechanism. Following class use the Collections.sort(List) method to sort the given list in natural order.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
Collections.sort(coll); // sort method
printList(coll);
}
private static void printList(List
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Run the above class and examine the output. It will be as follows. As you can see, the list is sorted correctly using the employee id. As empId is an int value, the employee instances are ordered so that the int values ordered from 1 to 8.
EmpId Name Age
1 Jorge 19
2 Mark 30
3 Michel 10
4 Clerk 16
5 Frank 28
6 Bill 34
7 Simp 8
8 Lee 40
Sorting by other fields
If we need to sort using other fields of the employee, we’ll have to change the Employee class’s compareTo() method to use those fields. But then we’ll loose this empId based sorting mechanism. This is not a good alternative if we need to sort using different fields at different occasions. But no need to worry; Comparator is there to save us.
By writing a class that implements the java.util.Comparator interface, you can sort Employees using any field as you wish even without touching the Employee class itself; Employee class does not need to implement java.lang.Comparable or java.util.Comparator interface.
Sorting by name field
Following EmpSortByName class is used to sort Employee instances according to the name field. In this class, inside the compare() method sorting mechanism is implemented. In compare() method we get two Employee instances and we have to return which object is greater.
public class EmpSortByName implements Comparator
public int compare(Employee o1, Employee o2) {
return o1.getName().compareTo(o2.getName());
}
}
Watch out: Here, String class’s compareTo() method is used in comparing the name fields (which are Strings).
Now to test this sorting mechanism, you must use the Collections.sort(List, Comparator) method instead of Collections.sort(List) method. Now change the TestEmployeeSort class as follows. See how the EmpSortByName comparator is used inside sort method.
import java.util.*;
public class TestEmployeeSort {
public static void main(String[] args) {
List coll = Util.getEmployees();
//Collections.sort(coll);
//use Comparator implementation
Collections.sort(coll, new EmpSortByName());
printList(coll);
}
private static void printList(List
System.out.println("EmpId\tName\tAge");
for (Employee e: list) {
System.out.println(e.getEmpId() + "\t" + e.getName() + "\t" + e.getAge());
}
}
}
Now the result would be as follows. Check whether the employees are sorted correctly by the name String field. You’ll see that these are sorted alphabetically.
EmpId Name Age
6 Bill 34
4 Clerk 16
5 Frank 28
1 Jorge 19
8 Lee 40
2 Mark 30
3 Michel 10
7 Simp 8
Sorting by empId field
Even the ordering by empId (previously done using Comparable) can be implemented using Comparator; following class
does that.
public class EmpSortByEmpId implements Comparator
public int compare(Employee o1, Employee o2) {
return o1.getEmpId() - o2.getEmpId();
}
}
Explore further
Do not stop here. Work on the followings by yourselves and sharpen knowledge on these concepts.
Sort employees using name, age, empId in this order (ie: when names are equal, try age and then next empId)
Explore how & why equals() method and compare()/compareTo() methods must be consistence.
If you have any issues on these concepts; please add those in the comments section and we’ll get back to you.
Labels: Java, Tech, Tutorial
Visitors Who Read This Article Also Read
Friday, 21 December 2012
Java MYSQL connection
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
In order to access to
*/
package helloworld;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
import java.sql.*;
/**
*// In order to get database mysql connection you need add mysql-connector-java-5.0.8.tar jar file to the libraries in netbeans or eclipse
for doubts contact jayachandra1805@gmail.com
* @author jayachandra
*/
public class Helloworld {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO code application logic here
char c;
Hashtable ht=new Hashtable();
for(int i=0;i<10;i++) { ht.put(i,"a"); } // public final native Class getClass();
System.out.println(!ht.contains("ad"));
Enumeration e=ht.keys();
while(e.hasMoreElements())
{
System.out.println(ht.get(e.nextElement()));
}
Scanner sc=new Scanner(System.in);
sqlConnection();
}
public static void sqlConnection() throws ClassNotFoundException, SQLException{
Connection con;
Statement st;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/practice","root", "root");
System.out.println(con);
String s="Select * from orders"; // write any query here
st=con.createStatement();
rs=st.executeQuery(s); // query is performing on database
if (rs.next()) {
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+ " ");
}
con.close();
}
}
* To change this template, choose Tools | Templates
* and open the template in the editor.
In order to access to
*/
package helloworld;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Scanner;
import java.sql.*;
/**
*// In order to get database mysql connection you need add mysql-connector-java-5.0.8.tar jar file to the libraries in netbeans or eclipse
for doubts contact jayachandra1805@gmail.com
* @author jayachandra
*/
public class Helloworld {
/**
* @param args the command line arguments
*/
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// TODO code application logic here
char c;
Hashtable ht=new Hashtable();
for(int i=0;i<10;i++) { ht.put(i,"a"); } // public final native Class getClass();
System.out.println(!ht.contains("ad"));
Enumeration e=ht.keys();
while(e.hasMoreElements())
{
System.out.println(ht.get(e.nextElement()));
}
Scanner sc=new Scanner(System.in);
sqlConnection();
}
public static void sqlConnection() throws ClassNotFoundException, SQLException{
Connection con;
Statement st;
ResultSet rs;
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/practice","root", "root");
System.out.println(con);
String s="Select * from orders"; // write any query here
st=con.createStatement();
rs=st.executeQuery(s); // query is performing on database
if (rs.next()) {
System.out.print(rs.getString(1)+" ");
System.out.print(rs.getString(2)+" ");
System.out.print(rs.getString(3)+ " ");
}
con.close();
}
}
Tuesday, 27 November 2012
Friday, 14 September 2012
Different ways to create objects in Java
This is a trivia. Yeah, it’s a bit tricky question and people often get confused. I had searched a lot to get all my doubts cleared.
There are four different ways (I really don’t know is there a fifth way to do this) to create objects in java:
1. Using new keyword
This is the most common way to create an object in java. I read somewhere that almost 99% of objects are created in this way.
MyObject object = new MyObject();
2. Using Class.forName()
If we know the name of the class & if it has a public default constructor we can create an object in this way.
MyObject object = (MyObject) Class.forName("subin.rnd.MyObject").newInstance();
3. Using clone()
The clone() can be used to create a copy of an existing object.
MyObject anotherObject = new MyObject();
MyObject object = anotherObject.clone();
4. Using object deserialization
Object deserialization is nothing but creating an object from its serialized form.
ObjectInputStream inStream = new ObjectInputStream(anInputStream );
MyObject object = (MyObject) inStream.readObject();
Now you know how to create an object. But its advised to create objects only when it is necessary to do so.
Friday, 11 May 2012
Nested Interfaces in Java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author bjr
*/
public class Main implements nested
{
public static void main(String args[])
{
ImplTopIfImplTopIf m=new ImplTopIfImplTopIf ();
System.out.println("Hello world");
System.out.println(m.fNestedIf1());
}
public static class ImplTopIfImplTopIf implements NestedIf1
{
@Override
public String fNestedIf1()
{
return "NestedIf1 implementation";
}
}
public static class NestedImplNestedIf2 implements NestedIf1.NestedIf2
{
@Override
public String fNestedIf2()
{
return "NestedIf2 implementation";
}
}
public interface NestedIf3
{
String fNestedIf3();
}
public static class NestedImplNestedIf3 implements NestedIf3
{
@Override
public String fNestedIf3()
{
return "NestedIf3 implementation";
}
}
@Override
public String fTopIf()
{
return "fTopIf implementation";
}
}
class ImplNestedIf3 implements Main.NestedIf3
{
@Override
public String fNestedIf3()
{
return "NestedIf3 implementation";
}
}
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author bjr
*/
public class Main implements nested
{
public static void main(String args[])
{
ImplTopIfImplTopIf m=new ImplTopIfImplTopIf ();
System.out.println("Hello world");
System.out.println(m.fNestedIf1());
}
public static class ImplTopIfImplTopIf implements NestedIf1
{
@Override
public String fNestedIf1()
{
return "NestedIf1 implementation";
}
}
public static class NestedImplNestedIf2 implements NestedIf1.NestedIf2
{
@Override
public String fNestedIf2()
{
return "NestedIf2 implementation";
}
}
public interface NestedIf3
{
String fNestedIf3();
}
public static class NestedImplNestedIf3 implements NestedIf3
{
@Override
public String fNestedIf3()
{
return "NestedIf3 implementation";
}
}
@Override
public String fTopIf()
{
return "fTopIf implementation";
}
}
class ImplNestedIf3 implements Main.NestedIf3
{
@Override
public String fNestedIf3()
{
return "NestedIf3 implementation";
}
}
Thursday, 10 May 2012
JDBC connection in net beans
The following statements in the java net beans in try catch block will connects to mysql jdbc connection
Before that you have to add jdbc connector jar file into you netbeans java project libraries
You also need to import the following packages
import com.mysql.jdbc.Statement; // for executing sql queries
import java.sql.DriverManager; // for jdbc connection
import java.sql.SQLException; // fir raising exception
Class.forName("java.sql.Driver");
Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/snakes_ladders","root","root");
Statement stmt=(Statement) conn.createStatement();
if(conn!=null)
{
System.out.println("connection success");
}
else
{
System.out.println("connection failed");
}
Before that you have to add jdbc connector jar file into you netbeans java project libraries
You also need to import the following packages
import com.mysql.jdbc.Statement; // for executing sql queries
import java.sql.DriverManager; // for jdbc connection
import java.sql.SQLException; // fir raising exception
Class.forName("java.sql.Driver");
Connection conn=(Connection) DriverManager.getConnection("jdbc:mysql://localhost/snakes_ladders","root","root");
Statement stmt=(Statement) conn.createStatement();
if(conn!=null)
{
System.out.println("connection success");
}
else
{
System.out.println("connection failed");
}
Wednesday, 2 May 2012
Reading pdf file in java
import com.itextpdf.awt.geom.Rectangle;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.FileOutputStream;
/**
*
* @author bjr
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
PdfReader reader = new PdfReader("D:\\MSIT_2012\\SSD\\Week3\\Applying_UML_And_Patterns_2001_Craig_Larman.pdf");
int n = reader.getNumberOfPages();
com.itextpdf.text.Rectangle psize = reader.getPageSize(1);
Document document = new Document(psize);
// creating new pdf file and writing the contentof the other pdf file to it
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\BookShelf\\new.pdf"));
document.open();
PdfContentByte pdf = writer.getDirectContent();
document.newPage();
int i=1;
while (i<=n)
{
String str=PdfTextExtractor.getTextFromPage(reader,i); // priting content of the pdf file to console
System.out.println(str);
i++;
}
PdfImportedPage page = writer.getImportedPage(reader, 1);
pdf.addTemplate(page, .5f, 0, 0, .5f, 60, 120);
document.close();
} catch (Exception de) {}
}
}
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.*;
import com.itextpdf.text.pdf.parser.PdfTextExtractor;
import java.io.FileOutputStream;
/**
*
* @author bjr
*/
public class Main {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
try {
PdfReader reader = new PdfReader("D:\\MSIT_2012\\SSD\\Week3\\Applying_UML_And_Patterns_2001_Craig_Larman.pdf");
int n = reader.getNumberOfPages();
com.itextpdf.text.Rectangle psize = reader.getPageSize(1);
Document document = new Document(psize);
// creating new pdf file and writing the contentof the other pdf file to it
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("D:\\BookShelf\\new.pdf"));
document.open();
PdfContentByte pdf = writer.getDirectContent();
document.newPage();
int i=1;
while (i<=n)
{
String str=PdfTextExtractor.getTextFromPage(reader,i); // priting content of the pdf file to console
System.out.println(str);
i++;
}
PdfImportedPage page = writer.getImportedPage(reader, 1);
pdf.addTemplate(page, .5f, 0, 0, .5f, 60, 120);
document.close();
} catch (Exception de) {}
}
}
Tuesday, 21 February 2012
Appending Serialized Objects to a file in java
// This program demonstrate how to write multiple bojects to a file and reading multiple objects from
// a file using Object Serilization
import java.io.Serializable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.IOException;
import java.io.File;
import java.util.ArrayList;
import java.io.OutputStream;
//import java.io.BinaryWriteHelper;
import java.util.Scanner;
// class Student
class Student implements Serializable
{
String name;
int age;
String clas;
String dob;
float cgp;
}
public class PS_Task3
{
static ArrayList al=new ArrayList();
public static void main(String[] args)
{
int n;
Scanner sc=new Scanner(System.in);
//storeArrayList();
// This try block will write multiple objects to a file
ObjectOutputStream oo=null;
try
{
File file1 = new File ("student.bin");
if (!file1.exists())
{
FileOutputStream fo=new FileOutputStream("student.bin");
oo=new ObjectOutputStream(fo);
}
else
{
oo = new AppendableObjectOutputStream (new FileOutputStream ("student.bin", true));
//FileOutputStream fo=new FileOutputStream("student.bin",true);
//oo=new ObjectOutputStream(fo);
}
System.out.println("Please enter n how many student details you want to enter");
n=sc.nextInt();
Student s;
for (int i=0;i
Saturday, 11 February 2012
Task 1 Description:Create a class LIST which represents a generalized list (By a sequential implementation) where insertions and deletions can be done arbitrarily at any point in the list. Implement all basic operations on it. (Insert, Delete, Isempty, Display etc). Specialize this class to represent STACK data structure (By inheriting the List class) and implement all basic operations (push, pop, Isempty, Display), on it
import java.util.ArrayList;
import java.util.Scanner;
class LIST // class List
{
ArrayList Al;
LIST()
{
Al=new ArrayList();
}
public boolean push(Object ele) // Stack push function
{
Al.add(ele);
System.out.println("The added element is "+ele);
return true;
}
public boolean isEmpty() // Stack is empty function
{
if(size()==-1)
return true;
else
return false;
}
public Object pop() // Stack pop function
{
String s="Sorry Stack is empty";
if(size()==-1)
return s;
else
return Al.remove(Al.size()-1);
}
public int size() // Stack size function
{
int n=Al.size();
if(n==0)
return -1;
else
return n;
}
public void display() // Stack display function
{
int n=Al.size();
if(Al.size()!=-1)
{
for(int i=0;i
{
System.out.println(Al.get(n-1));
n=n-1;
}
}
else
System.out.println("Stack is empty");
}
}
class PS_Stack extends LIST // class Main
{
public static void main(String[] args)
{
LIST l=new LIST();
int n;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("\t*************************************************\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \tPlease choose your Option: \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t1 to push element in to Stack\t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t2 to check Stack is empty \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t3 to Pop element from stack\t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t4 to get size of the stack \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t5 to dipslay stack elements \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t6 to exit\t\t\t\t*\n\t*\t\t\t\t\t\t*");
System.out.println("\t*************************************************");
n=sc.nextInt();
switch (n)
{
case 1:
Object ole;
System.out.println("Enter an element to push in to stack :");
ole=sc.nextInt();
l.push(ole);
break;
case 2:
System.out.println(l.isEmpty());
break;
case 3:
System.out.println(l.pop());
break;
case 4:
System.out.println(l.size());
break;
case 5:
l.display();
break;
case 6:
System.exit(0);
break;
default:
System.out.println("Choose correct option");
}
}
}// End of main
}
import java.util.Scanner;
class LIST // class List
{
ArrayList Al;
LIST()
{
Al=new ArrayList();
}
public boolean push(Object ele) // Stack push function
{
Al.add(ele);
System.out.println("The added element is "+ele);
return true;
}
public boolean isEmpty() // Stack is empty function
{
if(size()==-1)
return true;
else
return false;
}
public Object pop() // Stack pop function
{
String s="Sorry Stack is empty";
if(size()==-1)
return s;
else
return Al.remove(Al.size()-1);
}
public int size() // Stack size function
{
int n=Al.size();
if(n==0)
return -1;
else
return n;
}
public void display() // Stack display function
{
int n=Al.size();
if(Al.size()!=-1)
{
for(int i=0;i
System.out.println(Al.get(n-1));
n=n-1;
}
}
else
System.out.println("Stack is empty");
}
}
class PS_Stack extends LIST // class Main
{
public static void main(String[] args)
{
LIST l=new LIST();
int n;
Scanner sc=new Scanner(System.in);
while(true)
{
System.out.println("\t*************************************************\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \tPlease choose your Option: \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t1 to push element in to Stack\t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t2 to check Stack is empty \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t3 to Pop element from stack\t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t4 to get size of the stack \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t5 to dipslay stack elements \t\t*\n\t* \t\t\t\t\t\t*");
System.out.println("\t* \t6 to exit\t\t\t\t*\n\t*\t\t\t\t\t\t*");
System.out.println("\t*************************************************");
n=sc.nextInt();
switch (n)
{
case 1:
Object ole;
System.out.println("Enter an element to push in to stack :");
ole=sc.nextInt();
l.push(ole);
break;
case 2:
System.out.println(l.isEmpty());
break;
case 3:
System.out.println(l.pop());
break;
case 4:
System.out.println(l.size());
break;
case 5:
l.display();
break;
case 6:
System.exit(0);
break;
default:
System.out.println("Choose correct option");
}
}
}// End of main
}
Saturday, 4 February 2012
1. Write a C++ program to implement a complex class that contains two data members to store the real and imaginary parts of a complex number. Include member functions to initialize the data members to display the complex objects in the form ‘a+ib’. Use constructor and destructor for data members. Create a menu for the operations. Perform the following operations 1. Addition (use operator overloading) 2. Subtraction(use operator overloading) 3. Multiplication (use operator overloading) 4. Division Store the result in third object in the form of complex number. 2.
// Jayachandra
// addition,substraction,division and multiplication of two complex numbers
#include
using namespace std;
class Complex
{
public:
double getVolume()
{
cout<real + b.real;
com.imag = this->imag + b.imag;
return com;
}
// substraction
Complex operator-(const Complex& b)
{
Complex com;
com.real = this->real - b.real;
com.imag = this->imag - b.imag;
return com;
}
// multiplication
Complex operator*(const Complex& b)
{
Complex com;
com.real = this->real * b.real;
com.imag = this->imag * b.imag;
return com;
}
// division
Complex operator/(const Complex& b)
{
Complex com;
com.real = this->real / b.real;
com.imag = this->imag / b.imag;
return com;
}
private:
double real;
double imag;
};
// Main function for the program
int main( )
{
int n;
double i,r;
Complex Complex1;
Complex Complex2;
Complex Complex3;
cout<<"Plase enter real number for Complex1"<>r;
cout<<"Plase enter imaginary number Complex1"<>i;
Complex1.real_image(r,i);
cout<<"Plase enter real number for Complex2"<>r;
cout<<"Plase enter imaginary number Complex2"<>i;
Complex2.real_image(r,i);
Complex3 = Complex1 + Complex2;
for(;;)
{
cout<<"*****************************************\n*\t\t\t\t\t*"<>n;
switch(n)
{
case 1:
Complex3 = Complex1 + Complex2;
Complex3.getVolume();
break;
case 2:
Complex3 = Complex1 - Complex2;
Complex3.getVolume();
break;
case 3:
Complex3 = Complex1 * Complex2;
Complex3.getVolume();
break;
case 4:
Complex3 = Complex1 / Complex2;
Complex3.getVolume();
break;
case 5:
exit(0);
default:
cout<<"please choose correct option"<
// addition,substraction,division and multiplication of two complex numbers
#include
using namespace std;
class Complex
{
public:
double getVolume()
{
cout<
com.imag = this->imag + b.imag;
return com;
}
// substraction
Complex operator-(const Complex& b)
{
Complex com;
com.real = this->real - b.real;
com.imag = this->imag - b.imag;
return com;
}
// multiplication
Complex operator*(const Complex& b)
{
Complex com;
com.real = this->real * b.real;
com.imag = this->imag * b.imag;
return com;
}
// division
Complex operator/(const Complex& b)
{
Complex com;
com.real = this->real / b.real;
com.imag = this->imag / b.imag;
return com;
}
private:
double real;
double imag;
};
// Main function for the program
int main( )
{
int n;
double i,r;
Complex Complex1;
Complex Complex2;
Complex Complex3;
cout<<"Plase enter real number for Complex1"<
cout<<"Plase enter imaginary number Complex1"<
Complex1.real_image(r,i);
cout<<"Plase enter real number for Complex2"<
cout<<"Plase enter imaginary number Complex2"<
Complex2.real_image(r,i);
Complex3 = Complex1 + Complex2;
for(;;)
{
cout<<"*****************************************\n*\t\t\t\t\t*"<
switch(n)
{
case 1:
Complex3 = Complex1 + Complex2;
Complex3.getVolume();
break;
case 2:
Complex3 = Complex1 - Complex2;
Complex3.getVolume();
break;
case 3:
Complex3 = Complex1 * Complex2;
Complex3.getVolume();
break;
case 4:
Complex3 = Complex1 / Complex2;
Complex3.getVolume();
break;
case 5:
exit(0);
default:
cout<<"please choose correct option"<
Friday, 5 August 2011
Java Interview Questions
Java Threads Interview Questions - 1
1)What is threaded programming and when is it used?
Threaded programming is normally used when a program is required to do more than one task at the same time. Threading is often used in applications with graphical user interfaces; a new thread may be created to do some processor-intensive work while the main thread keeps the interface responsive to human interaction.The Java programming language has threaded programming facilities built in, so it is relatively easy to create threaded programs. However, multi-threaded programs introduce a degree of complexity that is not justified for most simple command line applications.
2)Why are wait(), notify() and notifyall() methods defined in the Object class?
A: These methods are detailed on the Java Software Development Kit JavaDoc page for the Object class, they are to implement threaded programming for all subclasses of Object. 3)Why are there separate wait and sleep methods?
A: The static Thread.sleep(long) method maintains control of thread execution but delays the next action until the sleep time expires. The wait method gives up control over thread execution indefinitely so that other threads can run. 4)What's the difference between Thread and Runnable types?
A: A Java Thread controls the main path of execution in an application. When you invoke the Java Virtual Machine with the java command, it creates an implicit thread in which to execute the main method. The Thread class provides a mechanism for the first thread to start-up other threads to run in parallel with it. The
Runnable interface defines a type of class that can be run by a thread. The only method it requires is run, which makes the interface very easy to to fulfil by extending existing classes. A runnable class may have custom constructors and any number of other methods for configuration and manipulation. 5)How does the run() method in Runnable work?
A: It may help to think of the run method like the main method in standard single threaded applications. The run method is a standard entry point to run or execute a class. The run method is normally only executed in the context of an independent Thread, but is a normal method in all other respects. 6)A Thread is runnable, how does that work?
A: The Thread class' run method normally invokes the run method of the Runnable type it is passed in its constructor. However, it is possible to override the thread's run method with your own. 7)Why not override Thread to make a Runnable?
A: There is little difference in the work required to override the Thread class compared with implementing the Runnable interface, both require the body of the run() method. However, it is much simpler to make an existing class hierarchy runnable because any class can be adapted to implement the run() method. A subclass of Thread cannot extend any other type, so application-specific code would have to be added to it rather than inherited. Separating the
Thread class from the Runnable implementation also avoids potential synchronization problems between the thread and the run() method. A separate Runnable generally gives greater flexibility in the way that runnable code is referenced and executed. 8)What's the difference between a thread's start() and run() methods?
A: The separate start() and run() methods in the Thread class provide two ways to create threaded programs. The start() method starts the execution of the new thread and calls the run() method. The start() method returns immediately and the new thread normally continues until the run() method returns. The
Thread class' run() method does nothing, so sub-classes should override the method with code to execute in the second thread. If a Thread is instantiated with a Runnable argument, the thread's run() method executes the run() method of the Runnable object in the new thread instead. Depending on the nature of your threaded program, calling the
Thread run() method directly can give the same output as calling via the start() method, but in the latter case the code is actually executed in a new thread. 9)Can I implement my own start() method?
A: The Thread start() method is not marked final, but should not be overridden. This method contains the code that creates a new executable thread and is very specialised. Your threaded application should either pass a Runnable type to a new Thread, or extend Thread and override the run() method. 10)Do I need to use synchronized on setValue(int)?
A: It depends whether the method affects method local variables, class static or instance variables. If only method local variables are changed, the value is said to be confined by the method and is not prone to threading issues. Monday, 11 July 2011
To find given string is palindrom or not using stack in java
Write a function to test if a string is a palindrome using a stack. You can push characters in the stack one by one. When you reach the end of the string, you can pop the characters and form a new string. If the two strings are exactly the same, the string is a palindrome. Note: Palindrome ignores spacing, punctuation, and capitalization. Test your program with the following test cases.
Here I am creating 3 files 1. StackADT.java 2. JCStack.java 3. Palindrome.java
// 1. StackADT.java
package Stack;
public interface StackADT
{
public int size();
public void push(char element);
public String pop();
}
// 2. 2. JCStack.java
import Stack.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=-1;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public void push(char element)
{
Character c=element;
try
{
st.push(new Character(element));
top++;
}
catch (Exception e)
{
}
}
public String pop()
{
String str="";
if(st.size()==0)
{
System.out.println("\nSorry stack is empty");
System.exit(0);
}
else
{
int i=st.size();
for (int j=0;j<i;j++ )
{
Character ob=ob=(Character)st.pop();
str=str+ob.charValue();
}
}
return str;
}
public void exit()
{
System.exit(0);
}
}
3. 3. Palindrome.java
import java.util.Scanner;
import java.lang.Character;
class Palindrome
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice;
String el,el1;
String st="";
System.out.println("Please enter Enter you new string line");
el1=sc.nextLine();
el1=el1.replaceAll(" ", ""); // removning places in string
el1=el1.replaceAll(",","");
el1=el1.replaceAll("'", "");
el=el1.toLowerCase(); // converting all the characters to lower case
while (true)
{
System.out.println("\nPlease enter you choice\n");
System.out.println(" 1 to insert or push \n 2 to check given string is palindrom");
System.out.println(" 3 to exit \n");
choice=sc.nextInt();
switch (choice)
{
case 1:
int k=el.length();
for(int i=0;i<k;i++)
{
char ch=el.charAt(i);
ST.push(ch);
}
break;
case 2:
if(ST.size()!=0)
{
String str=ST.pop();
if(el.equals(str))
{
System.out.println("\nString is palindrom\n");
}
else
{
System.out.println("\nString is not palindrom\n");
}
}
break;
case 3:
ST.exit();
default:
System.out.println("Plese choose correct choice");
}
}
}
}
- Go Dog
- Madam, I'm Adam
- Madam, I'm not a palindrome
Here I am creating 3 files 1. StackADT.java 2. JCStack.java 3. Palindrome.java
// 1. StackADT.java
package Stack;
public interface StackADT
{
public int size();
public void push(char element);
public String pop();
}
// 2. 2. JCStack.java
import Stack.*;
import java.io.*;
import java.util.*;
import java.lang.*;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=-1;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public void push(char element)
{
Character c=element;
try
{
st.push(new Character(element));
top++;
}
catch (Exception e)
{
}
}
public String pop()
{
String str="";
if(st.size()==0)
{
System.out.println("\nSorry stack is empty");
System.exit(0);
}
else
{
int i=st.size();
for (int j=0;j<i;j++ )
{
Character ob=ob=(Character)st.pop();
str=str+ob.charValue();
}
}
return str;
}
public void exit()
{
System.exit(0);
}
}
3. 3. Palindrome.java
import java.util.Scanner;
import java.lang.Character;
class Palindrome
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice;
String el,el1;
String st="";
System.out.println("Please enter Enter you new string line");
el1=sc.nextLine();
el1=el1.replaceAll(" ", ""); // removning places in string
el1=el1.replaceAll(",","");
el1=el1.replaceAll("'", "");
el=el1.toLowerCase(); // converting all the characters to lower case
while (true)
{
System.out.println("\nPlease enter you choice\n");
System.out.println(" 1 to insert or push \n 2 to check given string is palindrom");
System.out.println(" 3 to exit \n");
choice=sc.nextInt();
switch (choice)
{
case 1:
int k=el.length();
for(int i=0;i<k;i++)
{
char ch=el.charAt(i);
ST.push(ch);
}
break;
case 2:
if(ST.size()!=0)
{
String str=ST.pop();
if(el.equals(str))
{
System.out.println("\nString is palindrom\n");
}
else
{
System.out.println("\nString is not palindrom\n");
}
}
break;
case 3:
ST.exit();
default:
System.out.println("Plese choose correct choice");
}
}
}
}
Saturday, 9 July 2011
Queue Implementation using Linked List in java
Here I am creating 3 files in order to implement the Queue using Linked list in java
1.QueueADT.java 2. LLQueue.java 3. LLQueue_Test.java
// QueueADT.java
package Queue;
public interface QueueADT<E>
{
public Object getFront();
public void enqueue(Object a);
public Object dequeue();
public boolean isEmpty();
}
// 2. LLQueu.java
import java.util.Scanner;
import Queue.*;
import java.util.*;
public class LLQueue<E> implements QueueADT<E>
{
public ListNode front;
public ListNode back;
/*public LLQueue()
{
front=back=null;
}*/
// Test if the queue is logically empty, return true if empty else false
public boolean isEmpty()
{
return front==null;
}
// Insert a new item in to queue;
public void enqueue(Object x)
{
ListNode n=new ListNode(x);
if(isEmpty())
back=front=n;
else
back=back.next=n;
}
//Retun and remove the lest recently inserted item from the queue
public Object dequeue()
{
if(isEmpty())
throw new UnderflowException("Queue is empty");
Object val=front.element;
front=front.next;
return val;
}
// get the least recently inserted element from the queue;
public Object getFront()
{
if(isEmpty())
throw new UnderflowException("Queue is empty");
else
return front.element;
}
// Make queue empty
public void makeEmpty()
{
back=front=null;
}
// exit program
public void exit()
{
System.exit(0);
}
// display all the itmes in the queue
public void display()
{
if(!isEmpty())
{
ListNode current=front;
while (current!=null)
{
System.out.println(current.element);
current=current.next;
}
}
System.out.println("\nQueue is empty\n");
}
};
//Exception class for access in empty containers
//* such as stacks, queues, and priority queues.
class UnderflowException extends RuntimeException
{
// Construct this exception object
// Messages the error message
public UnderflowException( String message )
{
super( message );
}
}
// class List Node
class ListNode
{
public Object element;
public ListNode next;
// constructors
public ListNode(Object Elem)
{
element=Elem;
}
public ListNode(ListNode n, Object Ele)
{
element=Ele;
next=n;
}
};
// LLQueue_Test.java
import java.util.*;
class Queue_Test
{
public static void main(String[] args)
{
int choice,el;
Scanner sc=new Scanner(System.in);
LLQueue LLQ=new LLQueue();
//size=sc.nextInt();
while (true)
{
System.out.println("Please enter you choice\n");
System.out.println(" 1 for insert or enqueue \n 2 for is Queue empty \n 3 to get front element \n 4 to dequeue the element");
System.out.println(" 5 to display \n 6 to make Queue empty\n 7 to exit ");
System.out.print("\n Choice --> ");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Please enter Enter your element --> ");
el=sc.nextInt();
LLQ.enqueue(el);
System.out.println();
break;
case 2:
System.out.println(LLQ.isEmpty());
break;
case 3:
if(!LLQ.isEmpty())
{
System.out.println("Front element is ");
System.out.println(LLQ.getFront());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is ");
System.out.print(LLQ.dequeue());
System.out.println();
break;
case 5:
LLQ.display();
break;
case 6:
LLQ.makeEmpty();
break;
case 7:
LLQ.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
1.QueueADT.java 2. LLQueue.java 3. LLQueue_Test.java
// QueueADT.java
package Queue;
public interface QueueADT<E>
{
public Object getFront();
public void enqueue(Object a);
public Object dequeue();
public boolean isEmpty();
}
// 2. LLQueu.java
import java.util.Scanner;
import Queue.*;
import java.util.*;
public class LLQueue<E> implements QueueADT<E>
{
public ListNode front;
public ListNode back;
/*public LLQueue()
{
front=back=null;
}*/
// Test if the queue is logically empty, return true if empty else false
public boolean isEmpty()
{
return front==null;
}
// Insert a new item in to queue;
public void enqueue(Object x)
{
ListNode n=new ListNode(x);
if(isEmpty())
back=front=n;
else
back=back.next=n;
}
//Retun and remove the lest recently inserted item from the queue
public Object dequeue()
{
if(isEmpty())
throw new UnderflowException("Queue is empty");
Object val=front.element;
front=front.next;
return val;
}
// get the least recently inserted element from the queue;
public Object getFront()
{
if(isEmpty())
throw new UnderflowException("Queue is empty");
else
return front.element;
}
// Make queue empty
public void makeEmpty()
{
back=front=null;
}
// exit program
public void exit()
{
System.exit(0);
}
// display all the itmes in the queue
public void display()
{
if(!isEmpty())
{
ListNode current=front;
while (current!=null)
{
System.out.println(current.element);
current=current.next;
}
}
System.out.println("\nQueue is empty\n");
}
};
//Exception class for access in empty containers
//* such as stacks, queues, and priority queues.
class UnderflowException extends RuntimeException
{
// Construct this exception object
// Messages the error message
public UnderflowException( String message )
{
super( message );
}
}
// class List Node
class ListNode
{
public Object element;
public ListNode next;
// constructors
public ListNode(Object Elem)
{
element=Elem;
}
public ListNode(ListNode n, Object Ele)
{
element=Ele;
next=n;
}
};
// LLQueue_Test.java
import java.util.*;
class Queue_Test
{
public static void main(String[] args)
{
int choice,el;
Scanner sc=new Scanner(System.in);
LLQueue LLQ=new LLQueue();
//size=sc.nextInt();
while (true)
{
System.out.println("Please enter you choice\n");
System.out.println(" 1 for insert or enqueue \n 2 for is Queue empty \n 3 to get front element \n 4 to dequeue the element");
System.out.println(" 5 to display \n 6 to make Queue empty\n 7 to exit ");
System.out.print("\n Choice --> ");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Please enter Enter your element --> ");
el=sc.nextInt();
LLQ.enqueue(el);
System.out.println();
break;
case 2:
System.out.println(LLQ.isEmpty());
break;
case 3:
if(!LLQ.isEmpty())
{
System.out.println("Front element is ");
System.out.println(LLQ.getFront());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is ");
System.out.print(LLQ.dequeue());
System.out.println();
break;
case 5:
LLQ.display();
break;
case 6:
LLQ.makeEmpty();
break;
case 7:
LLQ.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
Stack implementation using Singly linked list
Here I am creating 3 files 1. StackADT.java 2. SLStack.java 3. SLStack_Test.java
// Save the following StackADT inter face code with the above mentioned name
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. SLStack.java
import java.util.*;
class Node
{
public Object element;
public Node next;
public Node()
{
this(null,null);
}
public Node(Object element, Node next)
{
this.element=element;
this.next=next;
}
public Object getElement()
{
return element;
}
public Node getNode()
{
return next;
}
public void seElement(Object obj)
{
this.element=obj;
}
public void setNode(Node node)
{
this.next=node;
}
}
public class SLStack implements StackADT
{
private Node top;
private int size;
public boolean isEmpty()
{
return (size==0);
}
public void makeEmpty()
{
top=null;
size=0;
}
public Object pop()
{
if (top==null)
{
return null;
}
Object val=top.getElement();
top=top.getNode();
size--;
return val;
}
public void push(Object obj)
{
Node v=new Node(obj,top);
size++;
top=v;
}
public int size()
{
return size;
}
public Object top()
{
Node temp=top;
if(!isEmpty())
try
{
return temp.getElement();
}
catch (Exception e)
{
return e.getMessage();
}
else
return null;
//return null;
}
public void display()
{
Node current=top;
while (current!=null)
{
System.out.println(current.getElement());
current=current.next;
}
}
public void exit()
{
System.exit(0);
}
};
// 3. SLStack_Test.java
import java.util.*;
public class SLStack_Test
{
public static void main(String[] args)
{
int choice,el;
Scanner sc=new Scanner(System.in);
SLStack SLS=new SLStack();
//size=sc.nextInt();
while (true)
{
System.out.println("Please enter you choice\n");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to display \n 6 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Please enter Enter your element --> ");
el=sc.nextInt();
SLS.push(el);
System.out.println();
break;
case 2:
System.out.println(SLS.isEmpty());
break;
case 3:
if(!SLS.isEmpty())
{
System.out.println("top element is ");
System.out.println(SLS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is ");
System.out.print(SLS.pop());
System.out.println();
break;
case 5:
SLS.display();
break;
case 6:
SLS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
// Save the following StackADT inter face code with the above mentioned name
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. SLStack.java
import java.util.*;
class Node
{
public Object element;
public Node next;
public Node()
{
this(null,null);
}
public Node(Object element, Node next)
{
this.element=element;
this.next=next;
}
public Object getElement()
{
return element;
}
public Node getNode()
{
return next;
}
public void seElement(Object obj)
{
this.element=obj;
}
public void setNode(Node node)
{
this.next=node;
}
}
public class SLStack implements StackADT
{
private Node top;
private int size;
public boolean isEmpty()
{
return (size==0);
}
public void makeEmpty()
{
top=null;
size=0;
}
public Object pop()
{
if (top==null)
{
return null;
}
Object val=top.getElement();
top=top.getNode();
size--;
return val;
}
public void push(Object obj)
{
Node v=new Node(obj,top);
size++;
top=v;
}
public int size()
{
return size;
}
public Object top()
{
Node temp=top;
if(!isEmpty())
try
{
return temp.getElement();
}
catch (Exception e)
{
return e.getMessage();
}
else
return null;
//return null;
}
public void display()
{
Node current=top;
while (current!=null)
{
System.out.println(current.getElement());
current=current.next;
}
}
public void exit()
{
System.exit(0);
}
};
// 3. SLStack_Test.java
import java.util.*;
public class SLStack_Test
{
public static void main(String[] args)
{
int choice,el;
Scanner sc=new Scanner(System.in);
SLStack SLS=new SLStack();
//size=sc.nextInt();
while (true)
{
System.out.println("Please enter you choice\n");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to display \n 6 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.print("Please enter Enter your element --> ");
el=sc.nextInt();
SLS.push(el);
System.out.println();
break;
case 2:
System.out.println(SLS.isEmpty());
break;
case 3:
if(!SLS.isEmpty())
{
System.out.println("top element is ");
System.out.println(SLS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is ");
System.out.print(SLS.pop());
System.out.println();
break;
case 5:
SLS.display();
break;
case 6:
SLS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
Stack Array in java
Here I am implementing Stack Array in java with StackADT, I have created 3 files
1. StackADT.java 2. AStack.java 3. AStack_Test.java
// StackADT.java
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. AStack.java
public class AStack implements StackADT
{
Object Array[];
int top=-1;
AStack(int size)
{
Array=new Object[size];
}
public int size()
{
return top;
}
public boolean isEmpty()
{
if (top<0)
{
return true;
}
else
return false;
}
public Object top()
{
return Array[top];
}
public void push(Object element)
{
try
{
Array[++top]=element;
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public Object pop()
{
try
{
Object result=Array[top];
top=top-1;
return result;
}
catch (ArrayIndexOutOfBoundsException e)
{
return e.getMessage();
}
}
public void exit()
{
System.exit(0);
}
}
// 3. AStack_Test.java
import java.util.Scanner;
class AStack_Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int choice,size,el;
System.out.println("Please enter size of the Array stack");
size=sc.nextInt();
AStack AS=new AStack(size);
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
AS.push(el);
break;
case 2:
System.out.println(AS.isEmpty());
break;
case 3:
if(!AS.isEmpty())
{
System.out.println("top element is ");
System.out.println(AS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is\n ");
System.out.println(AS.pop());
break;
case 5:
AS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
1. StackADT.java 2. AStack.java 3. AStack_Test.java
// StackADT.java
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// 2. AStack.java
public class AStack implements StackADT
{
Object Array[];
int top=-1;
AStack(int size)
{
Array=new Object[size];
}
public int size()
{
return top;
}
public boolean isEmpty()
{
if (top<0)
{
return true;
}
else
return false;
}
public Object top()
{
return Array[top];
}
public void push(Object element)
{
try
{
Array[++top]=element;
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
public Object pop()
{
try
{
Object result=Array[top];
top=top-1;
return result;
}
catch (ArrayIndexOutOfBoundsException e)
{
return e.getMessage();
}
}
public void exit()
{
System.exit(0);
}
}
// 3. AStack_Test.java
import java.util.Scanner;
class AStack_Test
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int choice,size,el;
System.out.println("Please enter size of the Array stack");
size=sc.nextInt();
AStack AS=new AStack(size);
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
AS.push(el);
break;
case 2:
System.out.println(AS.isEmpty());
break;
case 3:
if(!AS.isEmpty())
{
System.out.println("top element is ");
System.out.println(AS.top());
}
else
System.out.println("\nArray stack is empty\n");
break;
case 4:
System.out.println("\nPoped element is\n ");
System.out.println(AS.pop());
break;
case 5:
AS.exit();
default:
System.out.println("Please choose correct choice");
}
}
}
}
Java Collection Stack implementation
Here I am implementing Java collection stack, here I am creating three files
1 is StackADT.java. 2 JCStack.java. 3 JCStack_Test.java
// save it as StackADT
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// save it as JCStack.java
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=0;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public Object top()
{
return st.peek();
}
public void push(Object element)
{
st.push(element);
top++;
}
public Object pop()
{
try
{
return st.pop();
}
catch (EmptyStackException e )
{
return e.getMessage();
}
}
public void exit()
{
System.exit(0);
}
}
// Save it as JCStack_Test.java
import java.util.Scanner;
class JCStack_Test
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice,el;
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
ST.push(el);
break;
case 2:
System.out.println(ST.isEmpty());
break;
case 3:
System.out.println("top element is ");
System.out.println(ST.top());
break;
case 4:
System.out.println("Poped element is ");
System.out.println(ST.pop());
break;
case 5:
ST.exit();
default:
System.out.println("Plese choose correct choice");
}
}
}
}
1 is StackADT.java. 2 JCStack.java. 3 JCStack_Test.java
// save it as StackADT
public interface StackADT
{
public int size();
public boolean isEmpty();
public Object top();
public void push(Object element);
public Object pop();
}
// save it as JCStack.java
import java.util.Scanner;
import java.util.Stack;
import java.util.EmptyStackException;
public class JCStack implements StackADT
{
Stack st=new Stack();
int top=0;
public int size()
{
return st.size();
}
public boolean isEmpty()
{
return st.isEmpty();
}
public Object top()
{
return st.peek();
}
public void push(Object element)
{
st.push(element);
top++;
}
public Object pop()
{
try
{
return st.pop();
}
catch (EmptyStackException e )
{
return e.getMessage();
}
}
public void exit()
{
System.exit(0);
}
}
// Save it as JCStack_Test.java
import java.util.Scanner;
class JCStack_Test
{
public static void main(String[] args)
{
JCStack ST=new JCStack();
Scanner sc=new Scanner(System.in);
int choice,el;
while (true)
{
System.out.println("Please enter you choice");
System.out.println(" 1 for insert or push \n 2 for is Stack empty \n 3 to get top element \n 4 to pop the lement");
System.out.println(" 5 to exit");
choice=sc.nextInt();
switch (choice)
{
case 1:
System.out.println("Please enter Enter your element");
el=sc.nextInt();
ST.push(el);
break;
case 2:
System.out.println(ST.isEmpty());
break;
case 3:
System.out.println("top element is ");
System.out.println(ST.top());
break;
case 4:
System.out.println("Poped element is ");
System.out.println(ST.pop());
break;
case 5:
ST.exit();
default:
System.out.println("Plese choose correct choice");
}
}
}
}
Subscribe to:
Posts (Atom)