Monday, February 13, 2017

Jdbc Program to retrieve all data from 'emp' table of oracle database type-4 driver.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc10
{
public static void main(String[] args)
{
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
ResultSet rs=st.executeQuery("select * from emp");
System.out.println("ID\tName\tSalary\tJob");
System.out.println("-----------------------------------------");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getFloat(3)+"\t"+rs.getString(4));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to update column data of 'emp' table .

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc9
{
public static void main(String[] args)
{
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
int rc=st.executeUpdate("update emp set sal=sal+500");
System.out.println(rc+" row updated");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to insert data in 'emp' table in Oracle database using type-4 driver.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Jdbc8
{
public static void main(String[] args)
{
try
{
// Loading & Register the Type-4 Driver Class(OracleDriver). But this line is optional
Class.forName("oracle.jdbc.OracleDriver");
}
catch(ClassNotFoundException cn)
{
cn.printStackTrace();
}
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String check=null; // to check user want to enter more data or not
do
{
System.out.print("Enter id : ");
int id=Integer.parseInt(br.readLine());
System.out.print("Enter Name : ");
String name=br.readLine();
System.out.print("Enter Salary : ");
float sal=Float.parseFloat(br.readLine());
System.out.print("Enter Designation");
String job=br.readLine();
int rc=st.executeUpdate("insert into emp values("+id+",'"+name+"',"+sal+",'"+job+"')");
System.out.println(rc+" row inserted");
System.out.println("Do you insert more? (yes/no)");
check=br.readLine();
}while(!check.equalsIgnoreCase("no"));
System.out.println("----------------End of Application -----------------");
}
catch(SQLException|IOException e)//Multi Catch Block supported in jdk1.7 or higher version
{
e.printStackTrace();
}
}
}

Jdbc Program to drop 'emp' table by using type-4 driver of oracle database .

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc7
{
public static void main(String[] args)
{
try
{
Class.forName("oracle.jdbc.OracleDriver");
}
catch(ClassNotFoundException cn)
{
cn.printStackTrace();
}
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
st.executeUpdate("drop table emp");
System.out.println("Table Dropped");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to create table 'emp' in oracle database by using type-4 driver.

To use type-4 driver of oracle database we have to set classpath(if we are using normal  editor like editplus,notepad++) and we have to import that jar file if we are using
IDE(like Eclipse, NetBeans) of that jar file(ojdbc6.jar) provided by database
vendors(Oracle Corporation) which is available in
 C:\oraclexe\app\oracle\product\11.2.0\server\jdbc\lib\ojdbc6.jar.
How to set classpath or import ojdbc6.jar file in our program search in google.


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc6
{
public static void main(String[] args)
{
// Loading & Register the Type-4 Driver Class(OracleDriver). But this line is optional
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
//We can also use this driver Class.
//Class.forName("oracle.jdbc.OracleDriver")
}
catch(ClassNotFoundException cnfe)
{
cnfe.printStackTrace();
}
// Establishing the connection
// this is try with resources can be applied in jdk1.7 or above version
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{// port_No='1522' & database_name='xe'/'orcl' ,  username='system' & password='manager'
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
st.executeUpdate("create table emp(id number(3)primary key,name varchar2(10),sal number(4),job varchar2(10))");
System.out.println("Table created");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to retrieve all data from 'emp' table of oracle database type-1 driver.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc5
{
public static void main(String[] args)throws ClassNotFoundException
{
// Loading & Register the Type-1 Driver Class(JdbcOdbcDriver). But this line is optional
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:odbc:alt","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
ResultSet rs=st.executeQuery("select * from emp");
System.out.println("ID\tName\tSalary");
System.out.println("--------------------------------------");
while(rs.next())
{
System.out.println(rs.getInt(1)+"\t"+rs.getString(2)+"\t"+rs.getFloat(3));
}
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to update column data on 'emp' table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc4
{
public static void main(String[] args)throws ClassNotFoundException
{
// Loading & Register the Type-1 Driver Class(JdbcOdbcDriver). But this line is optional
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:odbc:alt","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
int rc=st.executeUpdate("update emp set sal=sal+500");
System.out.println(rc+" row updated");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to insert data in 'emp' table in Oracle database using type-1 driver.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class Jdbc3
{
public static void main(String[] args)throws ClassNotFoundException
{
// Loading & Register the Type-1 Driver Class(JdbcOdbcDriver). But this line is optional
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:odbc:alt","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
String check=null; // to check user want to enter more data or not
do
{
System.out.print("Enter id : ");
int id=Integer.parseInt(br.readLine());
System.out.print("Enter Name : ");
String name=br.readLine();
System.out.println("Enter Salary : ");
float sal=Float.parseFloat(br.readLine());
int rc=st.executeUpdate("insert into emp values("+id+",'"+name+"',"+sal+")");
System.out.println(rc+" row inserted");
System.out.println("Do you insert more? (yes/no)");
check=br.readLine();
}while(!check.equalsIgnoreCase("no"));
System.out.println("----------------End of Application -----------------");
}
catch(SQLException|IOException e) //Multi Catch Block supported in jdk1.7 or higher version
{
e.printStackTrace();
}
}
}

Jdbc Program to drop the 'emp' table.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Jdbc2 {

public static void main(String[] args) throws ClassNotFoundException
{
// Loading & Register the Type-1 Driver Class(JdbcOdbcDriver). But this line is optional
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establishing the connection
try(Connection con=DriverManager.getConnection("jdbc:odbc:alt","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
st.executeUpdate("drop table emp");
System.out.println("Table Dropped");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Jdbc Program to create a table 'emp' in Oracle database.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Jdbc1
{
public static void main(String[] args)throws ClassNotFoundException
{
// Loading & Register the Type-1 Driver Class(JdbcOdbcDriver). But this line is optional

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
// Establishing the connection
// this is try with resources can be applied in jdk1.7 or above version
try(Connection con=DriverManager.getConnection("jdbc:odbc:alt","system","manager"))
{
// Creating statement to execute query
Statement st=con.createStatement();
// Executing Query
st.executeUpdate("create table emp(id number(3)primary key,name varchar2(10),sal number(4))");
System.out.println("Table created");
}
catch(SQLException e)
{
e.printStackTrace();
}
}
}

Sunday, February 12, 2017

Java Program to sort List(LinkedList) Elements in Descending order(customized sorting order).

import java.util.LinkedList;
import java.util.Collections;
import java.util.Comparator;
import static java.lang.System.out;
class SortList2
{
public static void main(String...alt)
{
LinkedList ll=new LinkedList();
ll.add("ravi");
ll.add("altaf");
ll.add("kanta");
ll.add("zahid");
ll.add("nani");
out.println("Before Sorting : "+ll);
Collections.sort(ll,new MyComparator());
out.println("After Sorting : "+ll);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return -s1.compareTo(s2); //Descending order
}
}

Java Program to sort List(ArrayList) Elements in ascending order(default sorting order).

import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.out;
class SortList
{
public static void main(String...alt)
{
ArrayList al=new ArrayList();
al.add("z");
al.add("a");
al.add("k");
al.add("z");
al.add("n");
out.println("Before Sorting : "+al);
Collections.sort(al);
out.println("After Sorting : "+al);
}
}

Java program to sort in descending order of user defined Object(comapre by name).

import java.util.*;
class Emp implements Comparable
{
int id;
String name;
float sal;
Emp(int id,String name,float sal)
{
this.id=id;
this.name=name;
this.sal=sal;
}
public String toString()
{
return "["+this.id+","+this.name+","+this.sal+"]";
}
public int compareTo(Object obj)
{
Emp e=(Emp)obj;
int val=this.name.compareTo(e.name);
return -val;
}
}
class Sorting2
{
public static void main(String...alt)
{
Emp e1=new Emp(111,"Prashant",5000);
Emp e2=new Emp(222,"Ravi",2000);
Emp e3=new Emp(555,"Kalyani",3000);
Emp e4=new Emp(333,"Namita",4500);
Emp e5=new Emp(444,"Govinda",1500);
TreeSet ts=new TreeSet();
ts.add(e1);
ts.add(e2);
ts.add(e3);
ts.add(e4);
ts.add(e5);
System.out.println(ts);
}
}

Java program to sort in ascending order of user defined Object(comapre by name).

import java.util.*;
class Emp implements Comparable
{
int id;
String name;
float sal;
Emp(int id,String name,float sal)
{
this.id=id;
this.name=name;
this.sal=sal;
}
public String toString()
{
return "["+this.id+","+this.name+","+this.sal+"]";
}
public int compareTo(Object obj)
{
Emp e=(Emp)obj;
int val=this.name.compareTo(e.name);
return val;
}
}
class Sorting
{
public static void main(String...alt)
{
Emp e1=new Emp(111,"Prashant",5000);
Emp e2=new Emp(222,"Ravi",2000);
Emp e3=new Emp(555,"Kalyani",3000);
Emp e4=new Emp(333,"Namita",4500);
Emp e5=new Emp(444,"Govinda",1500);
TreeSet ts=new TreeSet();
ts.add(e1);
ts.add(e2);
ts.add(e3);
ts.add(e4);
ts.add(e5);
System.out.println(ts);
}
}

Java Program to sort Object/Double Array Elements in descending order with customized sorting order in a particular range .

import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SortArray6
{
static public void main(String...alt)
{
Double[] a={10.6,15.3,10.5,2.3,6.4,1.7,9.78,2.34};
out.println("Before Sorting : ");
for(double x:a)
out.print(x+"   ");
Arrays.sort(a,1,5,new MyComparator());
out.println("\n\nAfter Sorting : ");
for(double x:a)
out.print(x+"   ");
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
Double i1=(Double)o1;
Double i2=(Double)o2;
if(i1>i2)
return -1;
else
return 1;
}
}

Java Program to sort Object/Integer Array Elements in descending order with customized sorting order.

import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SortArray5
{
static public void main(String...alt)
{
Integer[] a={12,3,5,48,1,6,47,9,2}; //Autoboxing[Integer.valueOf(int a)]
out.println("Before Sorting : ");
for(int x:a) //Auto Unboxing[Integer.intValue()]
out.print(x+" ");
Arrays.sort(a,new MyComparator());
out.println("\n\nAfter Sorting : ");
for(int x:a) //Auto Unboxing[Integer.intValue()]
out.print(x+" ");
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
if(i1>i2)
return -1;
else
return 1;
}
}

Java Program to sort primitive Array Elements in Ascending order in a particular range.

Ex:- we have 9 array elements index will be(0-8) like : 12,3,5,48,1,6,47,9,2 and if we want to
sort in the range like 2-7 then sorted elements will be 12,3,1,5,6,47,48,9,2

import static java.lang.System.out;
import java.util.Arrays;
class SortArray4
{
static public void main(String...alt)
{
int[] a={12,3,5,48,1,6,47,9,2};
out.println("Before Sorting : ");
for(int x:a)
out.print(x+" ");
Arrays.sort(a,2,7);
out.println("\n\nAfter Sorting : ");
for(int x:a)
out.print(x+" ");
}
}

Java Program to sort Object/String class elements with customized sorting order.

This program will sort in descending order.

import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SortArray3
{
static public void main(String...alt)
{
String[] s={"zoo","apple","cat","banana","lock"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+" ");
out.println("\n\nAfter Sorting : ");
Arrays.sort(s,new MyComparator()); // public static void sort(java.lang.Object[])
for(String x:s)
out.print(x+" ");
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
return s2.compareTo(s1); // compareTo(String s) available in String class
// s2.compareTo(s1)--> Descending Order
// s1.compareTo(s2)--> Ascending Order
}
}

Java Program to sort Object/String class elements with default natural sorting order.

import static java.lang.System.out;
import java.util.Arrays;
class SortArray2
{
static public void main(String...alt)
{
String[] s={"zoo","apple","cat","banana","lock"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+" ");
out.println("\n\nAfter Sorting : ");
Arrays.sort(s); // public static void sort(java.lang.Object[])
for(String x:s)
out.print(x+" ");
}
}

Java Program to sort primitive Array Elements with default natural sorting order.

import static java.lang.System.out;
import java.util.Arrays;
class SortArray
{
static public void main(String...alt)
{
int[] a={12,3,5,48,1,6,47};
out.println("Before Sorting : ");
for(int x:a)
out.print(x+" ");
Arrays.sort(a);
out.println("\n\nAfter Sorting : ");
for(int x:a)
out.print(x+" ");
}
}

Java Program to push StringBuffer object elements in Stack(List) and search an element.

import java.util.Stack;
import java.util.Collections;
import java.util.Comparator;
import static java.lang.System.out;
class SearchList
{
public static void main(String...alt)
{
Stack v=new Stack();
v.push(new StringBuffer("ravi"));
v.push(new StringBuffer("altaf"));
v.push(new StringBuffer("kanta"));
v.push(new StringBuffer("zahid"));
v.push(new StringBuffer("nani"));
out.println("Before Sorting : "+v);
Collections.sort(v,new MyComparator());
out.println("After Sorting : "+v);
int result1=Collections.binarySearch(v,"nani",new MyComparator());
int result2=Collections.binarySearch(v,"NANI",new MyComparator());
out.println("nani is available in index : "+result1);
out.println("NANI is not available in Vector So it insertion point is : "+result2);
//NANI is less than nani(ASCII value of upper case letter is less than ASCII value of lower case letter(but sorting is performed in Descending order)
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s2.compareTo(s1); //Descending order
}
}

Java Program to search an element in List(Vector).

import java.util.Vector;
import java.util.Collections;
import static java.lang.System.out;
class SearchList
{
public static void main(String...alt)
{
Vector v=new Vector();
v.add("ravi");
v.add("altaf");
v.add("kanta");
v.add("zahid");
v.add("nani");
out.println("Before Sorting : "+v);
Collections.sort(v);
out.println("After Sorting : "+v);
int result1=Collections.binarySearch(v,"nani");
int result2=Collections.binarySearch(v,"NANI");
out.println("nani is available in index : "+result1);
out.println("NANI is not available in Vector So it insertion point is : "+result2);
//NANI is less than nani(ASCII value of upper case letter is less than ASCII value of lower case letter)
}
}

Java Program to search an element in an Object/StringBuffer Array within a range.

import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class Test
{
static public void main(String...alt)
{
StringBuffer[] sb={new StringBuffer("Anil"),new StringBuffer("Ravi"),new StringBuffer("Ali"),new StringBuffer("Ram"),new StringBuffer("Mohan"),new StringBuffer("Anthony")};
out.println("Before Sorting : ");
for(StringBuffer x:sb)
out.print(x+"  ");
MyComparator mc=new MyComparator();
Arrays.sort(sb,mc);
out.println("\nAfter Sorting : ");
for(StringBuffer x:sb)
out.print(x+"  ");
int result1=Arrays.binarySearch(sb,0,3,"Anil",mc);
out.println("\n\nAnil is available in index : "+result1);
int result2=Arrays.binarySearch(sb,0,3,"Ram",mc);
// Ram is available in array but not available in this range(0-3) in unsorted array.
out.println("Ram is not available So its insertion point is : "+result2);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString(); // Converting StringBuffer->Object to String
String s2=o2.toString(); // Converting StringBuffer->Object to String
return s1.compareTo(s2); //Ascending order
}
}

Java Program to search an element in an Object/StringBuffer Array.

import static java.lang.System.out;
import java.util.Arrays;
import java.util.Comparator;
class SearchArray5
{
static public void main(String...alt)
{
StringBuffer[] sb={new StringBuffer("Anil"),new StringBuffer("Ravi"),new StringBuffer("Ali"),new StringBuffer("Ram"),new StringBuffer("Mohan"),new StringBuffer("Anthony")};
out.println("Before Sorting : ");
for(StringBuffer x:sb)
out.print(x+"  ");
MyComparator mc=new MyComparator();
Arrays.sort(sb,mc);
out.println("\nAfter Sorting : ");
for(StringBuffer x:sb)
out.print(x+"  ");
int result1=Arrays.binarySearch(sb,"Mohan",mc);
out.println("\n\nMohan is available in index : "+result1);
int result2=Arrays.binarySearch(sb,"Mohas",mc);
out.println("Mohas is not available So its insertion point is : "+result2);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString(); // Converting StringBuffer->Object to String
String s2=o2.toString(); // Converting StringBuffer->Object to String
return s1.compareTo(s2); //Ascending order
}
}

Java Program to search an element in a primitive Array within a range.

import static java.lang.System.out;
import java.util.Arrays;
class SearchArray4
{
static public void main(String...alt)
{
int[] f={5,12,36,14,20,1,3,30};
out.println("Before Sorting : ");
for(int x:f)
out.print(x+"  ");
Arrays.sort(f); // Default natural sorting(Ascending Order)
out.println("\nAfter Sorting : ");
for(int x:f)
out.print(x+"  ");
int result1=Arrays.binarySearch(f,1,6,3);
out.println("\n\n3 is available in index : "+result1);
int result2=Arrays.binarySearch(f,1,6,30);//30 is available in array but not available
//in this range(1-6) in unsorted array. So it returns unpredictible value.
out.println("30 is not available so its insertion point is : "+result2);
}
}

Java Program to search an element in a primitive Array.

Note:- To search an element in an array elements must be sorted before search otherwise we will get
unpredictable result. because java.util.Arrays uses binary search mechanism.
If element is found then it will return its index value and if element is not found then it
will return insertion point(Insertion point is a place where we can place target element
in sorted list.
Note:- Index starts from 0 to (n-1) . But Insertion point starts from -1 to -(n+1).
if there are 3 elements in an array then index will be 0-2.
and insertion point may be -1 to -4.
*/
import static java.lang.System.out;
import java.util.Arrays;
class SearchArray3
{
static public void main(String...alt)
{
float[] f={5f,12f,36f,14f,20f,1f,3f,30f};
out.println("Before Sorting : ");
for(float x:f)
out.print(x+"  ");
Arrays.sort(f); // Default natural sorting(Ascending Order)
out.println("\nAfter Sorting : ");
for(float x:f)
out.print(x+"  ");
int result1=Arrays.binarySearch(f,14f);
out.println("\n\n14.0 is available in index : "+result1);
int result2=Arrays.binarySearch(f,15f);
out.println("15.0 is not available So its insertion point is : "+result2);
}
}

Java Program to search an element in an String/Object Array.

Note:- To search an element in an array elements must be sorted before search otherwise we will get
unpredictable result. because java.util.Arrays uses binary search mechanism.
If element is found then it will return its index value and if element is not found then it
will return insertion point(Insertion point is a place where we can place target element
in sorted list.
Note:- Index starts from 0 to (n-1) . But Insertion point starts from -1 to -(n+1).
if there are 3 elements in an array then index will be 0-2.
and insertion point may be -1 to -4.
*/

import static java.lang.System.out;
import java.util.Arrays;
class SearchArray2
{
static public void main(String...alt)
{
String[] s={"anil","ravi","ali","ram","mohan","anthony"};
out.println("Before Sorting : ");
for(String x:s)
out.print(x+"  ");
Arrays.sort(s); // Default natural sorting(Alphabetical Order)
out.println("\nAfter Sorting : ");
for(String x:s)
out.print(x+"  ");
int result1=Arrays.binarySearch(s,"ram");
out.println("\n\nram is available in index : "+result1);
int result2=Arrays.binarySearch(s,"rama");
out.println("rama is not available So its insertion point is : "+result2);
}
}

Java Program to search an element in a Double/Object Array.

Note:- To search an element in an array elements must be sorted before search otherwise we will get
unpredictable result. because java.util.Arrays uses binary search mechanism.
If element is found then it will return its index value and if element is not found then it
will return insertion point(Insertion point is a place where we can place target element
in sorted list.
Note:- Index starts from 0 to (n-1) . But Insertion point starts from -1 to -(n+1).
if there are 3 elements in an array then index will be 0-2.
and insertion point may be -1 to -4.
*/

import static java.lang.System.out;
import java.util.Arrays;
class SearchArray
{
static public void main(String...alt)
{
Double[] a={10.6,15.3,10.5,2.3,6.4,1.7,9.78,2.34};
out.println("Before Sorting : ");
for(double x:a)
out.print(x+"   ");
Arrays.sort(a); // Default natural sorting(Ascending Order)
out.println("\nAfter Sorting : ");
for(double x:a)
out.print(x+"   ");
int result=Arrays.binarySearch(a,6.4);
out.println("\n\n6.4 is available in index : "+result);
int result2=Arrays.binarySearch(a,6.5);
out.println("6.5 is not available So its insertion point is : "+result2);
}
}

WAP to enter an string and reverse it.

import java.io.Console;
class ReverseString3
{
public static void main(String[] args)
{
Console c=System.console();
String s=c.readLine("Enter String to reverse : ");
char[] rev=s.toCharArray();
System.out.println("Original String = "+s);
System.out.print("Reversed String = ");
for(int i=rev.length-1;i>=0;i--)
System.out.print(rev[i]);
}
}

Java program to enter an string and reverse it

import java.io.Console;
class ReverseString2
{
public static void main(String[] args)
{
Console c=System.console();
String s=c.readLine("Enter String to reverse : ");
// StringBuffer sb=new StringBuffer(s);
StringBuilder sb=new StringBuilder(s);
System.out.println("Original String = "+sb);
System.out.println("Reversed String = "+sb.reverse());
}
}

Java program to enter an string and reverse it.

import java.io.Console;
class ReverseString
{
public static void main(String[] args)
{
Console c=System.console();
String s=c.readLine("Enter String to reverse : ");
String rev="";
for(int i=s.length()-1;i>=0;i--)
rev=rev+s.charAt(i);
System.out.println("Original String = "+s);
System.out.println("Reversed String = "+rev);
}
}

Java Program to insert element in List and print in reverse order.

import java.util.ArrayList;
import java.util.Collections;
import static java.lang.System.out;
class ReverseList
{
public static void main(String...alt)
{
ArrayList al=new ArrayList();
al.add(20);
al.add(1);
al.add(12);
al.add(35);
al.add(16);
al.add(2);
out.println("Before Reverse : "+al);
Collections.reverse(al);
out.println("After Reverse : "+al);
}
}

Write a Program in Java to input a number and check whether it is a Unique Number or not.

Note: A Unique number is a positive integer (without leading zeros) with no duplicate digits. For example 7, 135, 214 are all unique numbers whereas 33, 3121, 300 are not. import static java.lang.System.out; import java.io.BufferedReader; import java.io.InputStreamReader; class Unique { public static void main(String...alt)throws Exception { int flag=0; BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); out.print("Enter a Number : "); String n=br.readLine(); label: for(int i=0;i

Saturday, February 11, 2017

Java Program to insert an image in Oracle database

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class StoreImage {
public static void main(String[] args) {
try(Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1522:xe","system","manager"))
{
File f=new File("D:/Lovely/Image/flower1.jpg");
FileInputStream fis=new FileInputStream(f);
PreparedStatement ps=con.prepareStatement("insert into emp2 values(?,?,?)");
ps.setInt(1, 111);
ps.setString(2, "Sameer");
ps.setBinaryStream(3,fis,f.length());
int rc=ps.executeUpdate();
System.out.println(rc+" row inserted");
}
catch(SQLException|IOException e)
{
e.printStackTrace();
}
}
}

Java Program to print & count all prime number between 1 to 100.

Note: A Prime number is a natural number which is greater than 1 and that has no posotive divisor
other than 1 & itself.
Ex :- 2,3,5,7,11,13,17,19,23......
*/
import static java.lang.System.out;
import java.util.Scanner;
class Prime2
{
static public void main(String...alt)
{
int count=0;
for(int j=2;j<=100;j++)
{
int flag=0;
for(int i=2;i<=j/2;i++)
{
if(j%i==0)
{
flag=1;
break;
}
}
if(flag==0)
{
count++;
out.println(j);
}
}
out.println("Total Prime No b/w 1 to 100 = "+count);
}
}

Java Program to enter a number & check whether it is prime no or not.

Note: A Prime number is a natural number which is greater than 1 and that has no positive divisor
other than 1 & itself.
Ex :- 2,3,5,7,11,13,17,19,23......
*/
import static java.lang.System.out;
import java.util.Scanner;
class Prime
{
static public void main(String...alt)
{
Scanner sc=new Scanner(System.in);
out.print("Enter a Number : ");
int n=sc.nextInt();
int flag=0;
for(int i=2;i<=n/2;i++)
{
if(n%i==0)
{
flag=1;
break;
}
}
if(flag==0)
out.println(n+" is prime Number");
else
out.println(n+" is Not prime Number");
}
}

Write a Java Program to display all Harshad /Niven Number between 1 to 100.

Harshad Number : In recreational mathematics, a Harshad number (or Niven number), is an integer
(in base 10) that is divisible by the sum of its digits.

Ex1:
The number 18 is a Harshad number in base 10, because the sum of the digits 1 and 8 is 9 (1 + 8 = 9)
and 18 is divisible by 9 (since 18 % 9 = 0). hence 18 is harshad no.

Ex2:-
The number 1729 is a Harshad number in base 10, because the sum of the digits 1 ,7, 2, 9 is
19 (1 + 7 + 2 + 9 = 19), and 1729 is divisible by 19 (1729 % 19 = 0)

Ex3:-
The number 19 is not a Harshad number in base 10, because the sum of the digits 1 and 9 is
10 (1 + 9 = 10), and 19 is not divisible by 10 (since 19 % 10 = 9)  */

import static java.lang.System.out;
import java.util.Scanner;
class Niven
{
public static void main(String...alt)throws Exception
{
for(int i=1;i<=100;i++)
{
int count=0;
int n=i;
int rem=0,sum=0;
while(n!=0)
{
rem=n%10;
sum+=rem;
n/=10;
}
if(i%sum==0)
out.println(i);
}
}
}

Write a Java Program to all Keith Number between 1 to 1000.

Note:A Keith Number is an integer N with ‘d’ digits with the following property:
If a Fibonacci-like sequence (in which each term in the sequence is the sum of the ‘d’ previous terms)
is formed, with the first ‘d’ terms being the decimal digits of the number N, then N itself occurs as a
term in the sequence.

For example, 197 is a Keith number since it generates the sequence
1, 9, 7, 17, 33, 57, 107, 197, ………..

Some keith numbers are: 14 ,19, 28 , 47 , 61, 75, 197, 742, 1104, 1537……………   */
import java.io.Console;
import static java.lang.System.out;
class Keith2
{
public static void main(String...alt)
{
int arr[]=new int[50];
for(int i=1;i<=1000;i++)
{
String s=Integer.toString(i);
int n=i,j=s.length();
while(n!=0)
{
int rem=n%10;
arr[j-1]=rem;
n/=10;
j--;
}
j=s.length();
int sum=0;
while(sum<i)
{
sum=0;
for(int k=1;k<=s.length();k++)
sum+=arr[j-k];
arr[j]=sum;
j++;
}
if(sum==i)
out.println(i);
}
}

}

Write a Program in Java to input a number and check whether it is a Keith Number or not.

Note:A Keith Number is an integer N with ‘d’ digits with the following property:
If a Fibonacci-like sequence (in which each term in the sequence is the sum of the ‘d’ previous terms)
is formed, with the first ‘d’ terms being the decimal digits of the number N, then N itself occurs as a
term in the sequence.

For example, 197 is a Keith number since it generates the sequence
1, 9, 7, 17, 33, 57, 107, 197, ………..

Some keith numbers are: 14 ,19, 28 , 47 , 61, 75, 197, 742, 1104, 1537……………   */

import java.util.ArrayList;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import static java.lang.System.out;
class Keith
{
public static void main(String args[])throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.print("Enter a No : ");
String s=br.readLine();
int n=Integer.parseInt(s);
int temp=n;
int i=s.length();
int[] arr=new int[50];
while(n!=0)
{
arr[i-1]=n%10;
n=n/10;
i--;
}
int sum=0;i=s.length();
while(sum<temp)
{
sum=0;
for(int j=1;j<=s.length();j++)
sum+=arr[i-j];
arr[i]=sum;
i++;
}
if(sum==temp)
out.println(temp+" is a keith no");
else
out.println(temp+" is a not keith no");
}
}

Write a Program in Java to show all Kaprekar number between 1 to 1000.

Note: A positive number ‘n’ is squared that has ‘d’ number of digits and split into two pieces.
right-hand piece that has ‘r’ digits and a left-hand piece that has remaining  ‘d-r=l’ digits.
If the sum of the two pieces(r+l) is equal to the number, then ‘n’ is a Kaprekar number.
The first few Kaprekar numbers are: 9, 45, 297 ......
Example 1: 9
Square of 9 = 9*9  = 81, right-hand piece of 81 = 1 and left hand piece of 81 = 8
Sum = 1 + 8 = 9, i.e. equal to the number. Hence, 9 is a Kaprekar number.

Example 2: 297
Square of 297 = 297*297 = 88209, right-hand piece of 88209 = 209 and left hand piece of 88209 = 88
Sum = 209 + 88 = 297, i.e. equal to the number. Hence, 297 is a Kaprekar number.   */

import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Kaprekar2
{
public static void main(String...alt)throws Exception
{
for(int i=1;i<=1000;i++)
{
long sqr1=i*i;
String sqr2=Long.toString(sqr1);
if(i<=9)
sqr2="0"+sqr2;
int mid=sqr2.length()/2;
int left=Integer.parseInt(sqr2.substring(0,mid));
int right=Integer.parseInt(sqr2.substring(mid));
if(left+right==i)
out.println(i);
}
}
}

Write a Program in Java to input a number and check whether it is a Kaprekar number or not.

Note: A positive number ‘n’ is squared that has ‘d’ number of digits and split into two pieces.
right-hand piece that has ‘r’ digits and a left-hand piece that has remaining  ‘d-r=l’ digits.
If the sum of the two pieces(r+l) is equal to the number, then ‘n’ is a Kaprekar number.
The first few Kaprekar numbers are: 9, 45, 297 ......
Example 1: 9
Square of 9 = 9*9  = 81, right-hand piece of 81 = 1 and left hand piece of 81 = 8
Sum = 1 + 8 = 9, i.e. equal to the number. Hence, 9 is a Kaprekar number.

Example 2: 297
Square of 297 = 297*297 = 88209, right-hand piece of 88209 = 209 and left hand piece of 88209 = 88
Sum = 209 + 88 = 297, i.e. equal to the number. Hence, 297 is a Kaprekar number.   */

import static java.lang.System.out;
import java.io.BufferedReader;
import java.io.InputStreamReader;
class Kaprekar
{
public static void main(String...alt)throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
out.println("Enter a Number : ");
long n=Long.parseLong(br.readLine());
long sqr1=n*n;
String sqr2=Long.toString(sqr1);
if(n<=9)
sqr2="0"+sqr2;
int mid=sqr2.length()/2;
int left=Integer.parseInt(sqr2.substring(0,mid));
int right=Integer.parseInt(sqr2.substring(mid));
if(left+right==n)
out.println(n+" is Kaprekar No");
else
out.println(n+" is not Kaprekar No");
}
}

Friday, February 10, 2017

Write a java program to all valid IMEI no(15 digit) between 999999999990000 to 999999999999999.

import java.util.Scanner;
import static java.lang.System.out;
class Imei3
{
public static int sumDigit(int d)
{
int s=0;
while(d!=0)
{
s=s+(d%10);
d/=10;
}
return s;
}
static public void main(String...alt)
{
long a=999999999990000l,b=999999999999999l;
for(long j=a;j<=b;j++)
{
long n=j;
String s=Long.toString(n);
int l=s.length(),sum=0;
if(l!=15)
out.println(n+" is wrong input for IMEI");
else
{
int d=0,rem=0;
for(int i=15;i>=1;i--)
{
rem=(int)(n%10);
if(i%2==0)
rem=2*rem;
sum=sum+sumDigit(rem);  // if rem has 2 digit of value like(14) call sumDigit()
n/=10;
}
if(sum%10==0)
out.println(s);
}
}
}
}