Java Basic Problems

Java:What is Static Variable?

What is Static Variable:
Static variable is that variable which has single copy in memory and is shared by all objects, so if there is any modifications to that static variable will also modify it’s value in all objects.

 

Important Notes about Static Variable:

** Fields that have the static modifier in their declaration are called static fields or class variables.

** Class variables (Static Variables) are referenced by the class name itself, as in

test1.demo //Code is given below

** Static Variables are associated with the class, rather than with any object. So, every instance of the class shares a class variable /Static Variable, which is in one fixed location in memory. Any object can change the value of a class variable.

static variable java

Code:
public class staticVariable

{

static int demo=0;

staticVariable()

{

demo++;

}

public static void main(String[] args)

{

staticVariable test1=new staticVariable();

System.out.println(“Value of demo in test1:”+test1.demo);

System.out.println(“***********************************” );

staticVariable test2=new staticVariable();

System.out.println(“Value of demo in test1:”+test1.demo);

System.out.println(“Value of demo in test2:”+test2.demo);

System.out.println();

}

}

 

OUTPUT
 
 
 
 

 

static variable java

 

Java Basic Problems

Java: How to connect with Database

Today I will show you how to connect with database server using Java.

Here, I have used PostGre Sql as my database server  and I have uploaded the PGSQL.Jar  (the postgre sql driver) for your convenience.

** I have used the OldVersion of NetBeans (NetBeans IDE 5.0) and JDK 1.4.2.

** Another matter, You have to include the  pgsql.jar  in your classpath while compiling and running this project.

 ** Download pgsql.jar  from http://www.ziddu.com/download/12613415/pgsql.jar.html

package dbconnection;

import java.sql.*;

 public class dbConnection extends javax.swing.JFrame {

     private void myInit()

    {

         /************************DB Connection Started********************/

   Connection result = null;

   String DB_CONN_STRING =”jdbc:postgresql://localhost:5432/replicationdb”;

    String DRIVER_CLASS_NAME = “org.postgresql.Driver”;

    String USER_NAME = “XYZ”;

    String PASSWORD = “pass”;

    try {

       Class.forName(“org.postgresql.Driver”);

    }

    catch (ClassNotFoundException cnfe){

    System.out.println(“Couldn’t find the driver!”);

    System.out.println(“Let’s print a stack trace, and exit.”);

    cnfe.printStackTrace();

    System.exit(1);

            }

    try {

 result = DriverManager.getConnection(“jdbc:postgresql://localhost:5432/Test”, USER_NAME, PASSWORD);

            }

    catch (SQLException se){

    System.out.println(“Couldn’t connect: print out a stack trace and exit.”);

    se.printStackTrace();

    System.exit(1);

         }

   /*******************DB Connection finished***************************/

    }

    public dbConnection() {

        initComponents();

        myInit();

    }

/***************Auto Generated Code by NetBeans—-Started from here *****************    

    private void initComponents() {

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        setCursor(new java.awt.Cursor(java.awt.Cursor.DEFAULT_CURSOR));

        setForeground(java.awt.Color.white);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());

        getContentPane().setLayout(layout);

        layout.setHorizontalGroup(

                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

                .add(0, 446, Short.MAX_VALUE)

                );

        layout.setVerticalGroup(

                layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)

                .add(0, 350, Short.MAX_VALUE)

                );

        pack();

    }                      

/******************** Auto Generated Code by NetBeans—-Ended*******************/

    public static void main(String args[]) {

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {

                new dbConnection().setVisible(true);

            }

        });

    }

}

Java Basic Problems

Java: Show image in a table of PDF from database

The following program will show you how to show image in  the table of a pdf  using java and iText. It is too much easy.  If you face any problem to understand please leave a reply.

** I have used NetBeans IDE 5.0  and JDK 1.4.2 –Old Version :(

 ** To run this Code, you have to add pgsql.jar (postgre sql driver),iText-2.1.7.jar( To Create PDF) in your classpath

The OutPut will be like this:

show image in pdf from database using java and iText

/*****************************************************/

package db2pdf;

import java.io.*;

import com.lowagie.text.*;

import com.lowagie.text.pdf.*;

import java.sql.*;

import java.util.*;

import java.io.*;

/**

*

 To run this Code, you have to add pgsql.jar (postgre sql driver),iText-2.1.7.jar( To Create PDF) in your classpath

*/

public class Main {

public Main() {

}

public static void main(String[] args) {

Document doc=null;

PdfPTable table=null;

Image image=null;

try{

System.out.println(“entered”);

doc=new Document();

PdfWriter.getInstance(doc,new FileOutputStream(“C:\\Table.pdf”));

doc.open();

 table=new PdfPTable(9);

table.setWidthPercentage(100);

table.setWidths(new float[] {1f, 1f, 1f, 1f,1f, 1f,3f,1f,2f});

table.addCell(“ID No”);

table.addCell(“Name”);

table.addCell(“Father’s Name”);

table.addCell(“Mother’s Name”);

table.addCell(“Thana”);

table.addCell(“District”);

table.addCell(“Present Address”);

table.addCell(“NID”);

table.addCell(“Picture”);

//doc.add(table);

// doc.close();

}

catch(Exception e){}

/*******************DB Connection Started*************************/

Connection result = null;

String DB_CONN_STRING =”jdbc:postgresql://localhost:5432/replicationdb”;

String DRIVER_CLASS_NAME = “org.postgresql.Driver”;

String USER_NAME = “XYZ”;

String PASSWORD = “line”;

try {

Class.forName(“org.postgresql.Driver”);

}

catch (ClassNotFoundException cnfe){

// log(“Check classpath. Cannot load db driver: ” + DRIVER_CLASS_NAME);

System.out.println(“Couldn’t find the driver!”);

System.out.println(“Let’s print a stack trace, and exit.”);

cnfe.printStackTrace();

System.exit(1);

}

try {

result = DriverManager.getConnection(“jdbc:postgresql://localhost/Test”, USER_NAME, PASSWORD); 

}

catch (SQLException se){

//log( “Driver loaded, but cannot connect to db: ” + DB_CONN_STRING);

System.out.println(“Couldn’t connect: print out a stack trace and exit.”);

se.printStackTrace();

System.exit(1);

 

}

// return result;

/*******************DB Connection finished***************************/

/**************************** Query Initialization ***************/

try{

PreparedStatement ps = result.prepareStatement(“select id,name,fathername,mothername,thana,district,presentaddress,nidno,picture from worker2 “);

ResultSet rs = ps.executeQuery();

if (rs != null) {

while(rs.next()) {

table.addCell(new String(rs.getBytes(1)));

table.addCell(new String(rs.getBytes(2)));

table.addCell(new String(rs.getBytes(3)));

table.addCell(new String(rs.getBytes(4)));

table.addCell(new String(rs.getBytes(5)));

table.addCell(new String(rs.getBytes(6)));

table.addCell(new String(rs.getBytes(7)));

table.addCell(new String(rs.getBytes(8)));

image = Image.getInstance (rs.getBytes(9));

System.out.println(“Image:”+rs.getBytes(9));

table.addCell(image);

}}

doc.add(table);

//doc.add(image);

doc.close();

String file=”C:\\Table.pdf”;

Runtime.getRuntime().exec(“rundll32 url.dll,FileProtocolHandler “+file);

}

catch(Exception e){}

/**************************** Query Initialization ***************/

}

}