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");
}

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) {}
}

}

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
}

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"<

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.
  1. Go Dog
  2. Madam, I'm Adam
  3. 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");
                               
                           
                            }
                                   

                        }
       
    }
}