Pages

Showing posts with label java code. Show all posts
Showing posts with label java code. Show all posts

Tuesday, July 3, 2012

program to accept three command line arguments from the user and to display it in sorted order

Write a program to accept three command line arguments from the user and to display it in sorted order.



import java.util.Arrays;



class sorting

{

public static void main(String args[])

{

if (args.length>0)

{

Arrays.sort(args);

System.out.println("");

for(int i=0;i
{

System.out.println(args[i]);

}

}

}

}
Read more

find the Factorial of a number using Recursion

Write a program to find the Factorial of a number using Recursion. Factorial can be defined as Factorial(n) = 1 * 2 * 3 ….* (n-1) * n.

class rfactorial
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
int fact;

recursion r1=new recursion();
fact=r1.rec(num);
System.out.println("The factorial for "+num+" is = "+fact);
}
}

class recursion
{
public int rec(int a)
{
int f;
if(a==1 || a==0)
{
return(1);
}
else
{
f=a*rec(a-1);
return(f);
}
}
}
Read more

a program which accept amount in dollars and convert it to the rupees.

Write a program, which accept amount in dollars, and convert it to the rupees.
class rupeeDollar
{
public static void main(String args[])
{
double rup,dol;
dol=Double.parseDouble(args[0]);
if(dol>0)
{
rup=dol*45.38;
System.out.println("$"+dol+" is equal to "+rup+" INR");
}

}
}
Read more

find Prime numbers program in java

Write a program that prints prime numbers between 1 to n. Number n should be acepted as command line input.



class PrimeNumber {

public static void main (String args[])

{

int num=Integer.parseInt(args[0]);

int i,j;

for(i=1;i
{

for(j=2;j
{

int n=i%j;

if(n==0) {break;}

}

if(i==j)

{

System.out.print(" " + i);

}

}



}

}

Read more

simple interest program in java

Write a Java program that calculates and prints the simple interest using the formula
Simple Interest = PNR / 100
Input values P,N,R should be accepted as command line input as below.
e.g. java SimpleInterest 5 10 15


class one{
public static void main(String args[])
{
double p,n,r,SI;
p=Double.parseDouble(args[0]);
n=Double.parseDouble(args[1]);
r=Double.parseDouble(args[2]);
SI=(p*n*r)/100;
System.out.println("The simple interese is: "+SI);
}
}
Read more

program that detects successive repeated occurrence of a letter in a word in java

Write a program that detects successive repeated occurrence of a letter in a word. For example, in the word “explanation” letter ‘a’ and ‘n’ occurs twice.





class occurance

{

public static void main(String args[])

{

String a;

String[] Arr;

Arr = new String[20];



int f=0,len;

len=args[0].length();



String str=args[0];

System.out.println(str);





for(int i=0;i
{

Arr[i]=str.substring(i,i+1);

System.out.println(Arr[i]);

}





}

}

Read more

Find Odd and Even Numbers in java

Write a program to accept a number from the user. Use condition checking statement and display whether the number is odd or even.
class oddEven
{
public static void main(String args[])
{
int num=Integer.parseInt(args[0]);
if(num%2==0)
{
System.out.println("The number "+num+" is EVEN");
}
else
{
System.out.println("The number "+num+" is ODD");
}
}
}
Read more

Example on inheritance in java

Write a class vehicle .Define suitable attributes and methods. Write subclasses of Vehicle like Car, Bicycle, Scooter. Assume suitable required attributes. Write constructor for each and define a method maxSpeed() in each class which prints the maximum speed of the vehicle. (use of super keyword is expected in the constructor of inherited classes)

class vehicle
{
vehicle(String c)
{
System.out.println(" Color is " +c+" ");
}
}


class bicycle extends vehicle
{
String name;
double speed;
bicycle(String c,String n, double s)
{
super(c);
speed=s;
name=n;
System.out.println(" Bicycle Name is "+name+" ");
}
void maxspeed()
{
System.out.println(" Max Speed is "+ speed);
}
}

class car extends vehicle
{
String name;
double speed;
car(String c,String n, double s)
{
super(c);
speed=s;
name=n;
System.out.println(" Car Name is "+name+" ");
}
void maxspeed()
{
System.out.println(" Max Speed is "+ speed);
}
}

class motors
{
public static void main(String args[])
{
bicycle b1=new bicycle("Black","BMW R1200",175F);
b1.maxspeed();
System.out.println("");
car c1=new car("Red","Lamborghini Galardo",382F);
c1.maxspeed();
}
}
Read more

How to find length of a number

Write a program that calculates the length(i.e. number of characters) in the input string.

class length
{
public static void main(String args[])
{
String val=args[0];
System.out.println("The length of "+val+" is : "+val.length());
}
}
Read more

interChange program in java

Write a program to accept a String and interchange the first character with the last character.

class interChange
{
public static void main(String args[])
{
String val=args[0];
String f,l,newrep;
int len;
len=val.length();
f=val.substring(0,1);
l=val.substring(len-1,len);

System.out.println(val);
newrep=l+val.substring(1,len-1)+f;
System.out.println(newrep);
}
}
Read more

Sum of digit, Length of number, average and reverse of digit program in java

To find Sum of digit, Length of number, average of digit and reverse of digit program in java

class digits
{
public static void main(String args[])
{
int dig=Integer.parseInt(args[0]);
int sum=0,rev=0;
float avg;
int len=args[0].length();

while(dig>0)
{
int r=dig%10;
sum=sum+r;
dig=dig/10;
rev=rev*10;
rev=rev+r;
}
avg=(float)sum/len;
System.out.println("The sum of digits is: "+sum);
System.out.println("The length of number is: "+len);
System.out.println("The average of the digits is: "+avg);
System.out.println("The reverse of digits is: "+rev);
}
}
Read more

fibonacci program in java

The numbers in the following sequence are called the fibonacci numbers .

0 , 1 , 1 , 2, 3 , 5 , 8 , 13 , …………..





class fibonacci{

public static void main(String args[])

{

int n=Integer.parseInt(args[0]);

int f=0,s=1;

int cur;

System.out.print(f+" "+s+" ");

do{

cur=f+s;

f=s;

s=cur;

System.out.print(cur+" ");

}while(cur




}

}
Read more

Monday, July 2, 2012

find if the given number is palindrome number or not.

/*
Java Palindrome Number Example
This Java Palindrome Number Example shows how to find if the given
number is palindrome number or not.
*/


public class JavaPalindromeNumberExample {

public static void main(String[] args) {

//array of numbers to be checked
int numbers[] = new int[]{121,13,34,11,22,54};

//iterate through the numbers
for(int i=0; i < numbers.length; i++){

int number = numbers[i];
int reversedNumber = 0;
int temp=0;

/*
* If the number is equal to it's reversed number, then
* the given number is a palindrome number.
*
* For example, 121 is a palindrome number while 12 is not.
*/

//reverse the number
while(number > 0){
temp = number % 10;
number = number / 10;
reversedNumber = reversedNumber * 10 + temp;
}

if(numbers[i] == reversedNumber)
System.out.println(numbers[i] + " is a palindrome number");
else
System.out.println(numbers[i] + " is not a palindrome number");
}

}
}

/*
Output of Java Palindrome Number Example would be
121 is a palindrome number
13 is not a palindrome number
34 is not a palindrome number
11 is a palindrome number
22 is a palindrome number
54 is not a palindrome number
*/
Read more

Friday, June 29, 2012

JDBC insert using prerpared statement

JDBC Connection code to insert data using prepared statement.

import java.sql.*;

public class jdbc_insert

{

public static void main(String args[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection conn=DriverManager.getConnection("jdbc:odbc:Darshana");

PreparedStatement ps=conn.prepareStatement("insert into Students

values(?,?,?,?,?)");

ps.setString(1,"4");

ps.setString(2,"Priyanka");

ps.setString(3,"Punjab");

ps.setString(4,"9877654321");

ps.setString(5,"Classic");

ps.executeUpdate();

ps.close();

conn.close();

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

}

Read more

JDBC Connection code to retrieve data from database

JDBC Connection code to get Name and roll no. of student from database Students.

import java.sql.*;

public class jdbc_select

{

public static void main(String args[])

{

try

{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

Connection conn=DriverManager.getConnection("jdbc:odbc:Students");

Statement st=conn.createStatement();

String sql1="select * from Student ";

ResultSet rs=st.executeQuery(sql1);

while(rs.next())

{

System.out.println(rs.getString("Roll_no"));

System.out.println(rs.getString("Name"));

}

}

catch(Exception e)

{

System.out.println(e.getMessage());

}

}

}

Read more

Sorting Algorithm in java

This program will sort the given number in array.

import java.util.*;
import java.lang.*;

public class sort{
public static void main(String args[]){

int a[]={2,3,1,5,4};

for(int i=0;i<5;i++)
{
for(int j=i;j<5;j++)
{
if(a[i]>a[j])
{
int temp;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}

}
System.out.print(" " + a[i]);
}

}
}
Read more

Thursday, September 22, 2011

First hibernate program – helloworld

SoftWare Used

1. Eclipse 3.2
2. Razorsql (http://www.razorsql.com/)
3 HsqlDB (http://hsqldb.org/)
4 JDK 1.6
5 ant

The following jar are requied to run the appication

1.hibernate3.jar
2.antlr-2.7.6.jar
3.javassist-3.9.0.GA.jar
4.jta-1.1.jar
5.dom4j-1.6.1.jar
6.commons-collections-3.1.jar
7.slf4j-api-1.5.8.jar
8.slf4j-simple-1.5.2.jar
9.hsqldb.jar

Most of the jars will be available in hibernate binary distribution, remaining can be downloaded from findjar.com

Below are the steps to develop and run the hibernate hsql Application

Create the directory structure and source files as shown below


JAVA SOURCE FILES

User.java

package com.upog.demo;
import java.util.Date;
public class User {
private int id;
private String name;
private Date date;
public User() {}

public int getId() {
return id;
}
private void setId(int id) {
this.id = id;
}

public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}

public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

HibernateUtil.java

package com.upog.demo;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
return new Configuration().configure().buildSessionFactory();
}
catch (Exception e)
{
System.out.println(” SessionFactory creation failed” + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory()
{
return sessionFactory;
}
}

HibernateTest.java

package com.upog.demo;

import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class HibernateTest {

public static void RetrieveUser()
{
System.out.println(“Retrieving User list from USER_INFO ….”);
Session session = HibernateUtil.getSessionFactory().openSession();

List UserList = session.createQuery(“from User”).list();
for (Iterator iterator = UserList.iterator(); iterator.hasNext();)
{
User user = (User) iterator.next();
System.out.println(user.getName() + “\t ” + user.getId() + “\t ” + user.getDate());
}
session.close();

}

public static void saveUser( String title)
{
Session session = HibernateUtil.getSessionFactory().openSession();
User user = new User();
user.setName(title);
user.setDate(new Date());
System.out.println(“\n Saving user ” + user.getName());
session.save(user);
session.flush();
session.close();
}

public static void main (String args[])
{
saveUser(“abc”);
saveUser(“def”);
saveUser(“Hi”);
saveUser(“hello”);
RetrieveUser();

}

}

Hibernate Configuration Files
Hibernate.cfg.xml - Contains the information about the database like URL,diver,ID,Password etc
Note: Change the value of connection.url as per you project home (I have given absolute path)

”-//Hibernate/Hibernate Configuration DTD 3.0//EN”
”http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd“>



org.hsqldb.jdbcDriver
jdbc:hsqldb:file:D:\data\workspace\Hibernate\database\mydb;shutdown=true
sa


2
org.hibernate.dialect.HSQLDialect
true
update
thread




Hibernate.hbm.xml – Defines the mapping between the Java Object and database table


”-//Hibernate/Hibernate Mapping DTD 3.0//EN”
”http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd“>










Create USER_INFO table in hsqldb
1. Connect hsqldb using razor sql with the properties as given below.

Login : sa
Password :
Driver class : org.hsqldb.jdbcDriver
Driver location :${PROJECT_HOME}\lib\hsqldb.jar
JDBC URL :jdbc:hsqldb:file:${PROJECT_HOME}\database\mydb;shutdown=true
2. Execute the following command
CREATE MEMORY TABLE PUBLIC.USER_INFO(ID INTEGER DEFAULT 0 NOT NULL PRIMARY KEY,NAME VARCHAR(25),CREATED_DATE DATE)
3. close the connection
Build.xml

[























































Right click on the build.xml file in eclipse Then Click on Run As – > Ant Buid.
Read more

Java Program--first stepp--hello world.

java – hello world

First Java Program

First to Compile and run a java program you need a Java SE Development Kit . if you don’t have java SE Development Kit download and install from the above link

Below are the steps to compile and run a java Program

Step1.

create a folder JavaProg. I have Created in D:\data\JavaProg

Step2.

Open a text file copy and paste the helloWorld program and save it as “helloWorld.java” in D:\data\JavaProg

public class helloWorld

{

public static void main(String[] args)

{

System.out.println(“Hello World”);

}

}

Step3.

Open a command Promt and type the following commands



Commands are highlighted by a red box and output was highlighted by a green box..
Notify me of follow-up comments via email.
Read more

Saturday, February 5, 2011

User Login in JSP

User Login in JSP



Every website and software in the world is having login facility. Login gives access rights to user and defines their role in website and application. Nobody can access website if they failure in proving their identity on website or application.

Registration is first step by login to website. We will keep focus on only user login in JSP.



User login contain two fields, first one important User ID. This is unique ID provided by site owner or software application itself or most of provide facility to choose user id themselves on their website of web application.



Second is password, it is secret field and user have to keep remember without sharing with anybody. This field gives authentication to user to login on the website. User ID and password keep isolate one user to other users.



We have three forms of JSP pages.



login.jsp take input from user, mainly user id and password then submitted to server for further processing. This process handles with database. Database has a SQL table name usermaster. Usermaster table is having number of fields which are not using in login process. We need user id, password, user type, user level, first name, last name.

User type field in database explain user type as e.g. admin role, power user role, moderator role, end user role. User levels field explain about permission defined to user. Read, write, update, view are permission on user can work accordingly to these permission. This certainly is not using in current login facility. This can be useful after user login successfully and work in application.



SQL usermaster Table



CREATE TABLE `usermaster` (

`sUserID` varchar(45) NOT NULL,

`sEmail` varchar(250) NOT NULL,

`sFirstName` varchar(45) NOT NULL,

`sLastName` varchar(45) NOT NULL,

`iDOB` datetime NOT NULL,

`cGender` varchar(45) NOT NULL,

`iCountryID` int(10) unsigned NOT NULL,

`iCityID` varchar(45) NOT NULL,

`iUserType` varchar(45) DEFAULT NULL,

`iUserLevel` varchar(45) DEFAULT NULL,

`sPassword` varchar(45) NOT NULL,

`sForgetPassword` varchar(45) DEFAULT NULL,

`sContact` bigint(20) unsigned NOT NULL,

`sCreatedBy` varchar(45) DEFAULT NULL,

`dCreatedDate` datetime DEFAULT NULL,

`sModifiedBy` varchar(45) DEFAULT NULL,

`sModifiedDate` datetime DEFAULT NULL,

`sStatus` varchar(45) NOT NULL,

PRIMARY KEY (`sUserID`),

UNIQUE KEY `sEmail` (`sEmail`)

);







login.jsp



<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>

<% String error=request.getParameter("error"); if(error==null || error=="null"){ error=""; } %>





User Login JSP









<%=error%>




User Name



Password

















doLogin.jsp mainly deals with database to check user id and password is matched with user trying to provide to get access from the server.



Our password field is encrypted with mysql password function. To decrypt password we have to use mysql password function again. If you are using Oracle or other database password function come with different name. Only user knows exact password and anybody can find out real password of the user. This increases the security of the system and reduces the hacking.



doLogin.jsp



<%@ page language="java" import="java.sql.*" errorPage="" %>

<% Connection conn = null; Class.forName("com.mysql.jdbc.Driver").newInstance(); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/database","root", ""); ResultSet rsdoLogin = null; PreparedStatement psdoLogin=null; String sUserID=request.getParameter("sUserName"); String sPassword=request.getParameter("sPwd"); String message="User login successfully "; try{ String sqlOption="SELECT * FROM usermaster where" +" sUserID=? and sPassword=password(?) and sStatus='A'"; psdoLogin=conn.prepareStatement(sqlOption); psdoLogin.setString(1,sUserID); psdoLogin.setString(2,sPassword); rsdoLogin=psdoLogin.executeQuery(); if(rsdoLogin.next()) { String sUserName=rsdoLogin.getString("sFirstName")+" "+rsdoLogin.getString("sLastName"); session.setAttribute("sUserID",rsdoLogin.getString("sUserID")); session.setAttribute("iUserType",rsdoLogin.getString("iUserType")); session.setAttribute("iUserLevel",rsdoLogin.getString("iUserLevel")); session.setAttribute("sUserName",sUserName); response.sendRedirect("success.jsp?error="+message); } else { message="No user or password matched" ; response.sendRedirect("login.jsp?error="+message); } } catch(Exception e) { e.printStackTrace(); } /// close object and connection try{ if(psdoLogin!=null){ psdoLogin.close(); } if(rsdoLogin!=null){ rsdoLogin.close(); } if(conn!=null){ conn.close(); } } catch(Exception e) { e.printStackTrace(); } %>



doLogin.jsp match user id and password with database record. If record is matched with user field and password. It will set user id, user type, user level, first name, last name in session. This can access from session in further in application. It will finish processing and return to success.jsp page.



success.jsp



<%@ page contentType="text/html; charset=iso-8859-1" language="java"%>





Successfully Login by JSP







Successfully login by JSP



Session Value



<% out.print("UserName :"+session.getAttribute("sUserID")+"

");

out.print("First & Last Name :"+session.getAttribute("sUserName"));

%>







If user id and password is not matched, it will return back to login.jsp page and print error message to user, user id and password is not matched.



The example of login is given with source code, login.jsp, doLogin.jsp and success.jsp.
Read more

Monday, November 1, 2010

Java Browser

//SAVE AND RUN UR OWN BROWSER

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.IDN;

import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.event.HyperlinkEvent;
import javax.swing.event.HyperlinkListener;

public class WebBrowserBasedOnJEditorPane extends JFrame implements HyperlinkListener {
private JTextField txtURL= new JTextField("");
JEditorPane ep = new JEditorPane();
private JLabel lblStatus= new JLabel(" ");

public WebBrowserBasedOnJEditorPane() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
JPanel pnlURL = new JPanel();
pnlURL.setLayout(new BorderLayout());
pnlURL.add(new JLabel("URL: "), BorderLayout.WEST);
pnlURL.add(txtURL, BorderLayout.CENTER);
getContentPane().add(pnlURL, BorderLayout.NORTH);
getContentPane().add( ep, BorderLayout.CENTER);

getContentPane().add(lblStatus, BorderLayout.SOUTH);

ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try {
String url = ae.getActionCommand().toLowerCase();
if (url.startsWith("http://"))
url = url.substring(7);
ep.setPage("http://" + IDN.toASCII(url));
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(WebBrowserBasedOnJEditorPane.this, "Browser problem: " + e.getMessage());
}
}
};
txtURL.addActionListener(al);

setSize(300, 300);
setVisible(true);
}
public void hyperlinkUpdate(HyperlinkEvent hle) {
HyperlinkEvent.EventType evtype = hle.getEventType();
if (evtype == HyperlinkEvent.EventType.ENTERED)
lblStatus.setText(hle.getURL().toString());
else if (evtype == HyperlinkEvent.EventType.EXITED)
lblStatus.setText(" ");
}

public static void main(String[] args) {
new WebBrowserBasedOnJEditorPane();
}
}
Read more