Java Basic Problems

Java: RunTime Input from User Example

I have discussed about how to take input from user in runtime from command line here.

Here I will try to give a simple example regarding this.

In this example, our program will take total student number and total subject as input, then it will take input of each subject number. After calculating the average number of total subject, if any student gets less than 40 it will show that student is failed and if any student gets more than 40 that student is passed.

Here is the given Code:

import java.io.*;

class student

{

public static void main(String args[])

{

String inputa;

int num_std;        // Total Number of Student

int sub_std;        // Total Subject of Student

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

System.out.println(“\n”);

System.out.println(“Enter the Total Number of Students:”);

System.out.println(“\n”);

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{

inputa=br.readLine();

num_std=Integer.parseInt(inputa);

System.out.println(“Enter the Total Subject of Student:”);

System.out.println(“\n”);

inputa=br.readLine();

sub_std= Integer.parseInt(inputa);

int i=0;

int j=0;

int z=0;

System.out.println(“\n”);

for (i=1;i<=num_std;i++)

{

System.out.println(“Enter Student  :” +i+” :Subject Number:”);

System.out.println(“\n”);

for (j=1;j<=sub_std;j++)

{

inputa= br.readLine();

z= z+Integer.parseInt(inputa);

if(j==sub_std)

{

System.out.println(“Student:”+i+”Total Number:”+z);

int om=(z)/sub_std;

if(om<40)

{

System.out.println(“Student:”+i+”fails”);

System.out.println(“Student  :”+i+” :  Average Number:”+om);

om=0;

z=0;

}

else

{

System.out.println(“Student  :”+i+” :  passed”);

System.out.println(“Student  :”+i+” :  Average Number:”+om);

om=0;

z=0;

}

}

} //End of student  subject loop

} //End of student num loop

System.out.println(“\n”);

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

}

catch(IOException e)

{}

}

}

OUTPUT:

Java Basic Problems

Java: How to take Run time input from user

Suppose you are doing your coding in java (let you are running your program from command prompt of your desktop) and you need to take input from user in command line or command prompt while  user  run (actually runtime input) your program.

Now I will show you how to take user input from command prompt or command line in java.

Here I have used BufferedReader  and readLine()  to take input from user in command line/ command prompt while the program was running or  simply in run time.

In the example below  br.readLine() takes  input as String, in the next line we have parsed or convert that String into integer.

Code:

import java.io.*;

public class CmdLineInput

{

CmdLineInput()

{

String inputa;

int num_std;

BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

try{

System.out.println(“Enter the number of Students:”);

inputa=br.readLine();

num_std=Integer.parseInt(inputa);

System.out.println(“Number of Students:”+num_std);

   }

 catch(Exception e){}

   }

public static void main(String args[])

{

CmdLineInput takeinput=new CmdLineInput();

}

}

OUTPUT:

Java Basic Problems

Java: About Static Method/Class Method.

Static Method:

I have discussed  Static Variable before,  you can check it from here.

Now I am going to discuss about Static MethodIt is also called Class Method.

In general we can say that methods declared with the keyword Static as modifier are called Static Methods or Class Methods.

Static Method in Java is that type of method which belongs to a class rather than an object of a class. Static Methods are invoked without reference to a particular instance (object) of a class.

So, anyone can invoke a Static Method without having to instantiate an object.

Important Notes / Features:

1. In Static Method, you can only manipulate variables that are declared as static, not other variables. It is because, something that is common to a class cannot refer to things that are  specific to an object.

 2. Static Method can call only other Static Methods.

3. Static Method cannot reference to the current object using super or this keyword.

 *** static means that it cannot be changed

Code:

public class StaticMethod

{

static int value=10;

StaticMethod()

{

test2 test =new test2();

}

              public static int getValue()

                        {

                        return value;

                        }

                        public int againgetValue()

                        {

                        return value;

                        }

public class test2

{

test2()

{

int getvalue= StaticMethod.getValue();

System.out.println(“Test2  calling the value StaticMethod.getValue(): “+getvalue); //Correct

//int setvalue= StaticMethod.againgetValue();  ****

//System.out.println(“test2  calling the value  StaticMethod.againgetValue() “+setvalue); **

}

}

public static void main(String args[])

{

StaticMethod test=new StaticMethod();

}

}

 

*** These 2 lines  will give error message as Instant Method cant be call in this way.

OUTPUT:

Test2  calling the value StaticMethod.getValue(): 10

Java Basic Problems

Java:Open Your Software in the Middle of the Desktop

By default Java Programs(GUI based)actually starts/Open  in the side of the desktop.  IF you want your java program/software (where GUI such as JFrame or JPanel is used) to open by default in the middle of the desktop then it’s for you.

Here I have given the code which will help you to open your java (JFrame window) in the middle of the desktop.

Whatever the resolution of your desktop monitor has, this code will help you to open your desire java written software exactly in the middle of the monitor.

Code:

import java.awt.*;

import javax.swing.*;

public class middlePosition extends JFrame

{

private Toolkit  toolkit;

                                                public middlePosition()

                                                {

                                                JPanel panel=new JPanel();

                                                getContentPane().add(panel);

                                                panel.setLayout(null);

                                                setSize(500,500);

                                                setTitle(“Set JFrame Window in the middle of the Desktop”);

                                                setDefaultCloseOperation(EXIT_ON_CLOSE);

                                                toolkit=getToolkit();

                                                Dimension size=toolkit.getScreenSize();

                                                setLocation(size.width/2-getWidth()/2, size.height/2-getHeight()/2);

                                                }

                        public static void main(String args[])

                        {

                        middlePosition x=new middlePosition();

                        x.setVisible(true);

                        }

}

OUTPUT:

Java program in the middle of the desktop

Java Basic Problems

Java: How to show image in JLabel

How to show image on JLabel:

If we need to show image as a background of a JLabel, then we can easily show it by using ImageIcon and then by setting that  ImageIcon to the JLabel.

Download this project from:

http://www.ziddu.com/download/12618536/jLabelImgIcon.zip.html

I have uploaded the project  and I used  NetBeans IDE 5.0 (You can use latest version) and JDK 1.4.2

I am not giving the whole code here, just I am mentioning the Core Portion of the code. Better you download the project and Run it in your computer.

Code:

import javax.swing.*;

import java.awt.image.BufferedImage;

public class jLabelImgIcon extends javax.swing.JFrame {

private void myInit()

{

 ImageIcon icon = new ImageIcon(“C:\\myworkspace\\sample.png”);

 icon = new ImageIcon(icon.getImage().getScaledInstance(100, 100, BufferedImage.SCALE_SMOOTH));

 jLabel1.setIcon(icon);     

    }

——————

—————

}

 OutPut:

In the output Image is viewing on JLabel  using ImageIcon and jLabel1.setIcon.

JLabel Image Icon

Java Basic Problems

Java: Static Class

About  Static Class:

Static Class is that class in Java for which we don’t need to create any Object.

Though we can create an object of a static class  but it is meaningless, we can use the members and methods of Static Class without creating an Object . The variables and methods can be used by calling them using class name only

Some Important Notes:

** A static nested class uses the instance variables (not static variables) / methods declared or defined in its enclosing class only by using an object reference.  

Code:

public class StaticVariable1

{

static int demo=0;

 StaticVariable1()

{

NonStaticClass demo1=new NonStaticClass();

System.out.println(“Before Value Change in NonStaticClass i=”+demo1.getValue());

demo1.i=10;

System.out.println(“After Value Change in NonStaticClass i=”+demo1.getValue());

}

static class StaticClass

{

static int i=0;

static int j;

}

public class NonStaticClass

{

int i;

int j;

public int getValue()

{

return i;

}

}

public static void main(String[] args)

{

System.out.println(“Before Value Change in StaticClass i=”+StaticClass.i);

StaticClass.i=10;  // No need to Create Object to initialize value of variable i in StaticClass

System.out.println(“After Value Change in StaticClass i=”+StaticClass.i);

//NonStaticClass.i=10; *** check below

StaticVariable1 demo=new StaticVariable1(); 

}

}

** It will create error   non-static variable i cannot be referenced from a static Context NonStaticClass.i=10;

                          ^

OUTPUT:

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 ***************/

}

}