Monday, June 21, 2010


Palindrome Number Example

This blog post explains you what is palindrome number and a java example to calculate palindrome number.

Palindrome Number
Palindrome Number is the same number after reversing the actual number.

For Example : 545 (After reversing, the output is same)

The example of palindrom number below :

import java.io.*;

public class Palindrome {
public static void main(String [] args){
try{
BufferedReader object = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter a number");
int num= Integer.parseInt(object.readLine());
int n = numb;
int rev=0;
System.out.println("The Number is : ");
System.out.println(" "+ numb);
for (int i=0; i<=num; i++){
int r=numb%10;
numb=numb/10;
rev=rev*10+r;
i=0;
}
System.out.println("Output after reversing: "+ " ");
System.out.println(" "+ rev);
if(n == rev){
System.out.print("This Number is Palindrome!");
}
else{
System.out.println("This Number is not palindrome!");
}
}
catch(Exception e){
System.out.println("Unknown Number!");
}
}
}


Saturday, June 12, 2010


Write To File Example

This post will expain you the two classes - FileWriter and BufferedWriter and how to write java program to write to a file.

Class FileWriter - The FileWriter is a class used for writing character files.

Class BufferedWriter - The BufferWriter class is used to write text to a character-output stream, buffering characters. It will help us to provide for the efficient writing of single characters, arrays, and strings.

Find the code below of java program to write text to a file:

import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt");
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}


Thursday, November 26, 2009


Example to Determine if a File or Directory Exists

This program checks whether the file or directory exist in your computer or not. This can be possible using exists() method and in the example we are using if condition to check whether the given file or directory exists or not. The example is given below :

import java.io.*;
public class filedirexists{
public static void main(String args[])
{
File filedir=new File("File or Directory exists or not!!")
boolean exists = filedir.exists()
if (!exists)
{
System.out.println("The File/Directory you are looking for is not found")
}
else
{
System.out.println("The File/Directory you are looking for available")


Sunday, November 15, 2009


Comparing Two Dates

Here your will find the example to compare two dates in java. We use java.util.Date class and compareTo() method for comparison. The compareTo() method returns integer value when we comparing two dates.

The compareTo() method returns the following integer value if comparing two dates :

The integer value '0' returns if both dates are equal.
The integer value '1' returns when first date is greater than second date.
The integer value '-1' returns when first date is less than second date.

Here is the example of comparing 2 dates and display the final result :

import java.util.Date;
public class Comparedates{

public static void main(String[] args) {
Date Date1 = new Date();
try{
Thread.sleep(1000);
}catch(Exception e){
}
Date Date2 = new Date();
System.out.println("First Date:="+Date1);
System.out.println("Second Date:="+Date2);
if(Date1.compareTo(Date2) > 0)
System.out.println("Date1 is Greater than Date2");
else if(Date1.compareTo(Date2) < 0)
System.out.println("Date1 is less than Date2");
else
System.out.println("Date1 and Date2 are equal!!!");
}
}


Wednesday, March 25, 2009


JDBC and JDBC Driver Connectivity

The JDBC or Java database connectivity is a unique technology that empowers applications to be written once but run anywhere. JDBC enabled devise driver could access corporate data even if the environment is not homogeneous. This unique feature is very much Java specific for Java itself is platform independent and Java API which is actually a short term of JDBC enables the easy execution of SQL statements.

JDBC is an application program to the core used to access database in tubular format encrypted by Java and driven by standard interfaces. RDBMS like SQL and Oracle are quarried and updated by JDBC with its niche in using and allowing heterogeneous implementation with the same application.

Since SQL is supported by all Relational Database Management System any corporate database could be accessed, quarried or updated via this single Java written JDBC program. In order to interact with database Java interface is used by programmers but it is the job of a JDBC driver to implement the interface according to the data base management system. Though Java Database Connectivity Driver categorically implements connection some are better suited for specific applications over the other types.

Four types of JDBC driver connectivity are common with Type 1 driver heading the list. It’s a popular, platform independent driver that uses ODBC to connect to database. Type 2 Native API driver is not coded by Java in its entirety making it more versatile in interpreting client libraries of database into recognizable native calls.

Application server, namely middle tier technology is used by Type 3 drivers and therefore client software is not required and database access could be gained through internet.

A type 4 driver also known as Native Protocol Driver and is a complete Java written program, which displays superior performance over the other two types and is completely platform independent. Communication with client application is speedy and easy as direct conversion of JDBC into vendor database protocol is enabled excluding middleware function; however a separate client side driver is required for a different database which poses the only challenge at times.


Tuesday, March 17, 2009


Changing Mouse Icon Example

In this example, you will learn how to change the cursor icon. In this program, the cursor will change when user moov the mouse to "Yes" button and then "No" button. The source code is available below :

import java.awt.*;
import java.awt.event.*;

public class ChangeCursor{
public static void main(String[] args) {
Frame m = new Frame("Change cursor");
Panel panel = new Panel();
Button b1 = new Button("Yes");
Button b2 = new Button("No");
panel.add(b1);
panel.add(b2);
m.add(panel,BorderLayout.CENTER);
m.setSize(300,300);
m.setVisible(true);
Cursor c1 = b1.getCursor();
Cursor c2 = b2.getCursor();
b1.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
b2.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
m.addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});

}
}


Wednesday, December 31, 2008


Disable Keyboard Editing in JSpinner

A simple example on JSpinner. In the example, the editing mode is disabled using setEditable() method. So it will not be possible to insert numbers with the help of keyboard :


import javax.swing.*;
import java.awt.*;

public class Disablekeyboard{
public static void main(String[] args){
JFrame frm = new JFrame("Disable Keyboard Editing Example");
JSpinner spinner = new JSpinner();
JFormattedTextField tf = ((JSpinner.DefaultEditor)spinner.getEditor())
.getTextField();
tf.setEditable(false);
spinner.setValue(new Integer(100));
JPanel panel = new JPanel();
panel.add(spinner);
frm.add(panel, BorderLayout.NORTH);
frm.setSize(350, 350);
frm.setVisible(true);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Thursday, October 16, 2008


Java sort() Method Example

If you want to sort string characters then this example is the best for you. The sort() method sort words in ascending order. Look a simple example of sort() method given below :

import java.util.*;
import java.io.*;
import java.lang.String;

public class sortstr{
public static void main(String args[]){
String str = "Java String Example";
char[] content = str.toCharArray();
java.util.Arrays.sort(content);
String sorted = new String(content);
System.out.println(content);
}
}

Result : EJSaaegilmnprtvx


Friday, September 26, 2008


Show Icon on The Button

With the help of java swing, you can add images, icons in the application to make your GUI application interface more attractive. With the help of this example, you can learn how to add image on the button or other control. This example expain you add image file. The code is given below :

import javax.swing.*;
import java.awt.*;

public class IconButton{
public static void main(String[] args){
JFrame frame = new JFrame("Swing Icon Example");
JButton button = new JButton("My Button");
Icon imgicon = new ImageIcon("smiley_icon.gif");
JPanel panel = new JPanel();
button.setIcon(imgicon);
panel.add(button);
frame.add(panel, BorderLayout.NORTH);
frame.setSize(380, 380);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}


Saturday, September 13, 2008


Swing Input Dialog Box

Input dialog box in java is the good example of user input example in GUI environment. A user can input value at run time in small window. The input box also contains "OK" and "Cancel" button. The code below is the example to create an input box where user enter either text or numeric value at run time :

import javax.swing.*;
import java.awt.event.*;

public class ShowInputDialog{
public static void main(String[] args){
JFrame frame = new JFrame("Input Dialog Box Example");
JButton button = new JButton("Click for Input Dialog Box");
button.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent ae){
String txt = JOptionPane.showInputDialog(null, "Enter Your Text : ",
"Input Box", 1);
if(txt != null)
JOptionPane.showMessageDialog(null, "The text you have entered : " + txt,
"Input Box", 1);
else
JOptionPane.showMessageDialog(null, "You clicked on cancel button.",
"Input Box", 1);
}
});
JPanel panel = new JPanel();
panel.add(button);
frame.add(panel);
frame.setSize(350, 350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Tuesday, September 2, 2008


Comparing Two Strings Using equals()

The given example show you how to compare two strings with the help of equals() method in java. The equals() method is used to compare the contents of objects. The method returns value in either "true" or "false". The code give below compare two strings whether both are equal or not. If both are same then it returns true else not :

import java.lang.*;
import java.io.*;

public class equalstrings{
public static void main(String[] args) throws IOException{
System.out.println("String Compares Example Using Equals() Method");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter First String:");
String str1 = bf.readLine();
System.out.println("Enter Second String to Compare :");
String str2 = bf.readLine();
if (str1.equals(str2)){
System.out.println("Both the Strings are Equal!");
}
else{
System.out.println("Both the Strings are not Equal!");
}
}
}


Saturday, August 23, 2008


Java String Length Example

If you want to count the lenght of the string in java then use lenght() method that returns integer value of a string entered by the user. Below is the example that calculate the length of the string :

import java.lang.*;
import java.io.*;

public class Strlen{
public static void main(String[] args) throws IOException{
System.out.println("Count the Lenght of String");
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter String:");
String str = bf.readLine();
int len = str.length();
System.out.println("Length of Text : " + len);
}
}


Tuesday, July 1, 2008


Java Prime Number Example

What is Prime Number?

Definition : A prime number is a natural number that has only two divisor. Either it is divisible by 1 or itself and it is greater than 1. So we can say it has only one divisor means it can only divided by itself.

Here is the example of prime number in Java. It display all the prime numbers between 1 and the limit entered by user. Get the source code of prime number example here :

import java.io.*;
class Primenumberexample {
public static void main(String[] args) throws Exception{
BufferedReader bf = new BufferedReader(
new InputStreamReader(System.in));
System.out.println("Enter Limit to Print Prime Number :");
int k = Integer.parseInt(bf.readLine());
System.out.println("Prime Numbers Are : ");
for (int i=1; i < k; i++ ){
for (int j=2; j < i; j++){
int a = i%j;
if (a==0){
break;
}
}
if(i == j){
System.out.print(" "+i);
}
}
}
}


Monday, June 30, 2008


How to Calculate Area of Rectangle?

This example explain you how to calculate area of a rectangle using java code. For calculating area of rectangle, we need three variables. One for length, one for breadth and one variable calculate the area of rectangle. We have already read and know how to calculate area of rectangle using formula a=lXb. Here is the source code to find the area of rectangle :

class Rectangleexample
{
public static void main(String[] args)
{
int len=5, breadth=7, area=1;
area = len*breadth;
System.out.println("Area if Rectangle :" + area);
}
}


Saturday, June 21, 2008


Count Vowels Example in Java

This example show you how to check and calculate how many vowel are in the string entered by user. With the help of for loop, we calculate how many vowels a user entered in the string. Here is the source code :

import java.lang.String;
import java.io.*;
import java.util.*;

public class vowels{

public static void main(String args[])throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter New String to Check :");
String text = bf.readLine();
int cnt = 0;
for (int a = 0; a < text.length(); a++) {
char b = text.charAt(a);
if (b=='a' || b=='e' || b=='i' || b=='o' || b=='u') {
cnt++;
}
}
System.out.println("Total Vowels are" + " : " + cnt);
}
}


Tuesday, June 17, 2008


How to Create Checkbox in Java Swing?

What is Check Box?

A check box or tick box is a graphical user interface element that allow or permits user to make selections from the options. User can select more than one item or element.

The given example will explain you how to create check box in java swing. It is created in java by creating the instance of JCheckBo class. Here is the check box program :


public class CreateCheckBox{
public static void main(String[] args){
JFrame frame = new JFrame("The Check Box Example");
JCheckBox chk = new JCheckBox("Check Box 1");
JCheckBox chk = new JCheckBox("Check Box 2");
JCheckBox chk = new JCheckBox("Check Box 3");
frame.add(chk);
frame.setSize(400, 400);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}


Tuesday, May 27, 2008


Java String Trim Example

The string trim() method remove the blank spaces from the left and right in the given string.

Here is the example how to remove blank spaces :

import java.lang.*;
public class StringTrim{
public static void main(String[] args) {
System.out.println("Source code of String Trim Method");
String str = " blankspaces ";
System.out.println("Entered String :" + str);
System.out.println("Output of the Program :" +str.trim());
}
}


Friday, April 18, 2008


Display Time in JSpinner : Swing Examples

Spinner allow user to select and type the value from a range of values. It has no drop-down list and this reason it is different to combo box. Here is the example to display time in JSpinner and also edit the time :

import javax.swing.*;
import java.awt.*;
import java.util.*;

public class ShowTimeJSpinner{
public static void main(String[] args) {
ShowTimeJSpinner h = new ShowTimeJSpinner();
}

public ShowTimeJSpinner(){
JFrame frame = new JFrame("JSpinner Time Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
JSpinner spinner = new JSpinner(sm);
JSpinner.DateEditor de = new JSpinner.DateEditor(spinner, "hh:mm");
spinner.setEditor(de);
frame.add(spinner,BorderLayout.NORTH);
frame.setSize(100,100);
frame.setVisible(true);
}
}


Saturday, March 29, 2008


How to Create Combo Box : Java Swing Example

You will learn how to insert combo-box using Swing in Java. Combox box is used display item in drop down list. It provides option to select an item from the drop down. The basic difference between combo box and list box is that user cannot select multiple item from combo-box but it can be possible in list box.


import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ComboBox{
JComboBox combo;
JTextField txt;
public static void main(String[] args) {
ComboBox b = new ComboBox();
}

public ComboBox(){
String course[] = {"India","Germany","America","Russia"};
JFrame frame = new JFrame("Creating a JComboBox Component");
JPanel panel = new JPanel();
combo = new JComboBox(course);
combo.setBackground(Color.gray);
combo.setForeground(Color.red);
txt = new JTextField(10);
panel.add(combo);
panel.add(txt);
frame.add(panel);
combo.addItemListener(new ItemListener(){
public void itemStateChanged(ItemEvent ie){
String str = (String)combo.getSelectedItem();
txt.setText(str);
}
});
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400,400);
frame.setVisible(true);
}
}


Thursday, March 20, 2008


Maximize a Frame using Swing

In this program, you will learn how to maximize a frame using setMaximizedBounds() to set the bounds for a maximized frame. Here is the source code :

import java.awt.*;
import javax.swing.*;

public class SwingSetBounds{
public static void main(String[] args){
JFrame frame = new JFrame();
Rectangle bounds = new Rectangle(0, 0, 500, 500);
frame.setMaximizedBounds(bounds);
frame.setSize(400, 400);
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}