Monday 19 September 2011

Swap Numbers Without Using Third Variable Java Example

Swap Numbers Without Using Third Variable Java Example

  1. /*
  2. Swap Numbers Without Using Third Variable Java Example
  3. This Swap Numbers Java Example shows how to
  4. swap value of two numbers without using third variable using java.
  5. */
  6.  
  7. public class SwapElementsWithoutThirdVariableExample {
  8.  
  9. public static void main(String[] args) {
  10.  
  11. int num1 = 10;
  12. int num2 = 20;
  13.  
  14. System.out.println("Before Swapping");
  15. System.out.println("Value of num1 is :" + num1);
  16. System.out.println("Value of num2 is :" +num2);
  17.  
  18. //add both the numbers and assign it to first
  19. num1 = num1 + num2;
  20. num2 = num1 - num2;
  21. num1 = num1 - num2;
  22.  
  23. System.out.println("Before Swapping");
  24. System.out.println("Value of num1 is :" + num1);
  25. System.out.println("Value of num2 is :" +num2);
  26. }
  27.  
  28.  
  29. }
  30.  
  31. /*
  32. Output of Swap Numbers Without Using Third Variable example would be
  33. Before Swapping
  34. Value of num1 is :10
  35. Value of num2 is :20
  36. Before Swapping
  37. Value of num1 is :20
  38. Value of num2 is :10
  39. */

Swap Numbers Without Using Third Variable Java Example

Swap Numbers Without Using Third Variable Java Example

  1. /*
  2. Swap Numbers Without Using Third Variable Java Example
  3. This Swap Numbers Java Example shows how to
  4. swap value of two numbers without using third variable using java.
  5. */
  6. public class SwapElementsWithoutThirdVariableExample {
  7. public static void main(String[] args) {
  8. int num1 = 10;
  9. int num2 = 20;
  10. System.out.println("Before Swapping");
  11. System.out.println("Value of num1 is :" + num1);
  12. System.out.println("Value of num2 is :" +num2);
  13. //add both the numbers and assign it to first
  14. num1 = num1 + num2;
  15. num2 = num1 - num2;
  16. num1 = num1 - num2;
  17. System.out.println("Before Swapping");
  18. System.out.println("Value of num1 is :" + num1);
  19. System.out.println("Value of num2 is :" +num2);
  20. }
  21. }
  22. /*
  23. Output of Swap Numbers Without Using Third Variable example would be
  24. Before Swapping
  25. Value of num1 is :10
  26. Value of num2 is :20
  27. Before Swapping
  28. Value of num1 is :20
  29. Value of num2 is :10
  30. */

Reverse Number using Java

Reverse Number using Java

  1. /*
  2.   Reverse Number using Java
  3.   This Java Reverse Number Example shows how to reverse a given number.
  4. */
  5.  
  6. public class ReverseNumber {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. //original number
  11. int number = 1234;
  12. int reversedNumber = 0;
  13. int temp = 0;
  14.  
  15. while(number > 0){
  16.  
  17. //use modulus operator to strip off the last digit
  18. temp = number%10;
  19.  
  20. //create the reversed number
  21. reversedNumber = reversedNumber * 10 + temp;
  22. number = number/10;
  23.  
  24. }
  25.  
  26. //output the reversed number
  27. System.out.println("Reversed Number is: " + reversedNumber);
  28. }
  29. }
  30.  
  31. /*
  32. Output of this Number Reverse program would be
  33. Reversed Number is: 4321
  34. */

Java Factorial Using Recursion Example

Java Factorial Using Recursion Example

Submitted By: Mohit Garg

  1. /*
  2. Java Factorial Using Recursion Example
  3. This Java example shows how to generate factorial of a given number
  4. using recursive function.
  5. */
  6.  
  7. import java.io.BufferedReader;
  8. import java.io.IOException;
  9. import java.io.InputStreamReader;
  10.  
  11. public class JavaFactorialUsingRecursion {
  12.  
  13. public static void main(String args[]) throws NumberFormatException, IOException{
  14.  
  15. System.out.println("Enter the number: ");
  16.  
  17. //get input from the user
  18. BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
  19. int a = Integer.parseInt(br.readLine());
  20.  
  21. //call the recursive function to generate factorial
  22. int result= fact(a);
  23.  
  24.  
  25. System.out.println("Factorial of the number is: " + result);
  26. }
  27.  
  28. static int fact(int b)
  29. {
  30. if(b <= 1)
  31. //if the number is 1 then return 1
  32. return 1;
  33. else
  34. //else call the same function with the value - 1
  35. return b * fact(b-1);
  36. }
  37. }
  38.  
  39. /*
  40. Output of this Java example would be
  41.  
  42. Enter the number:
  43. 5
  44. Factorial of the number is: 120
  45. */

Java Interface example

Java Interface example

  1. /*
  2. Java Interface example.
  3. This Java Interface example describes how interface is defined and
  4. being used in Java language.
  5.  
  6. Syntax of defining java interface is,
  7. <modifier> interface <interface-name>{
  8.   //members and methods()
  9. }
  10. */
  11.  
  12. //declare an interface
  13. interface IntExample{
  14.  
  15. /*
  16.   Syntax to declare method in java interface is,
  17.   <modifier> <return-type> methodName(<optional-parameters>);
  18.   IMPORTANT : Methods declared in the interface are implicitly public and abstract.
  19.   */
  20.  
  21. public void sayHello();
  22. }
  23. }
  24. /*
  25. Classes are extended while interfaces are implemented.
  26. To implement an interface use implements keyword.
  27. IMPORTANT : A class can extend only one other class, while it
  28. can implement n number of interfaces.
  29. */
  30.  
  31. public class JavaInterfaceExample implements IntExample{
  32. /*
  33.   We have to define the method declared in implemented interface,
  34.   or else we have to declare the implementing class as abstract class.
  35.   */
  36.  
  37. public void sayHello(){
  38. System.out.println("Hello Visitor !");
  39. }
  40.  
  41. public static void main(String args[]){
  42. //create object of the class
  43. JavaInterfaceExample javaInterfaceExample = new JavaInterfaceExample();
  44. //invoke sayHello(), declared in IntExample interface.
  45. javaInterfaceExample.sayHello();
  46. }
  47. }
  48.  
  49. /*
  50. OUTPUT of the above given Java Interface example would be :
  51. Hello Visitor !
  52. */

Find Largest and Smallest Number in an Array Example

Find Largest and Smallest Number in an Array Example

  1. /*
  2.   Find Largest and Smallest Number in an Array Example
  3.   This Java Example shows how to find largest and smallest number in an
  4.   array.
  5. */
  6. public class FindLargestSmallestNumber {
  7.  
  8. public static void main(String[] args) {
  9.  
  10. //array of 10 numbers
  11. int numbers[] = new int[]{32,43,53,54,32,65,63,98,43,23};
  12.  
  13. //assign first element of an array to largest and smallest
  14. int smallest = numbers[0];
  15. int largetst = numbers[0];
  16.  
  17. for(int i=1; i< numbers.length; i++)
  18. {
  19. if(numbers[i] > largetst)
  20. largetst = numbers[i];
  21. else if (numbers[i] < smallest)
  22. smallest = numbers[i];
  23.  
  24. }
  25.  
  26. System.out.println("Largest Number is : " + largetst);
  27. System.out.println("Smallest Number is : " + smallest);
  28. }
  29. }
  30.  
  31. /*
  32. Output of this program would be
  33. Largest Number is : 98
  34. Smallest Number is : 23
  35. */

Create New Thread Using Runnable Example

  1. /*
  2. Create New Thread Using Runnable Example
  3. This Java example shows how to create a new thread by implementing
  4. Java Runnable interface.
  5. */
  6.  
  7. /*
  8.  * To create a thread using Runnable, a class must implement
  9.  * Java Runnable interface.
  10.  */
  11. public class CreateThreadRunnableExample implements Runnable{
  12.  
  13. /*
  14. * A class must implement run method to implement Runnable
  15. * interface. Signature of the run method is,
  16. *
  17. * public void run()
  18. *
  19. * Code written inside run method will constite a new thread.
  20. * New thread will end when run method returns.
  21. */
  22. public void run(){
  23.  
  24. for(int i=0; i < 5; i++){
  25. System.out.println("Child Thread : " + i);
  26.  
  27. try{
  28. Thread.sleep(50);
  29. }
  30. catch(InterruptedException ie){
  31. System.out.println("Child thread interrupted! " + ie);
  32. }
  33. }
  34.  
  35. System.out.println("Child thread finished!");
  36. }
  37.  
  38. public static void main(String[] args) {
  39.  
  40. /*
  41. * To create new thread, use
  42. * Thread(Runnable thread, String threadName)
  43. * constructor.
  44. *
  45. */
  46.  
  47. Thread t = new Thread(new CreateThreadRunnableExample(), "My Thread");
  48.  
  49. /*
  50. * To start a particular thread, use
  51. * void start() method of Thread class.
  52. *
  53. * Please note that, after creation of a thread it will not start
  54. * running until we call start method.
  55. */
  56.  
  57. t.start();
  58.  
  59. for(int i=0; i < 5; i++){
  60.  
  61. System.out.println("Main thread : " + i);
  62.  
  63. try{
  64. Thread.sleep(100);
  65. }
  66. catch(InterruptedException ie){
  67. System.out.println("Child thread interrupted! " + ie);
  68. }
  69. }
  70. System.out.println("Main thread finished!");
  71. }
  72. }
  73.  
  74. /*
  75. Typical output of this thread example would be
  76.  
  77. Main thread : 0
  78. Child Thread : 0
  79. Child Thread : 1
  80. Main thread : 1
  81. Main thread : 2
  82. Child Thread : 2
  83. Child Thread : 3
  84. Main thread : 3
  85. Main thread : 4
  86. Child Thread : 4
  87. Child thread finished!
  88. Main thread finished!
  89.  
  90. */

java.lang.NoClassDefFoundError and java.lang.NoSuchMethodError


Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp
If you receive this error, java cannot find your bytecode file, HelloWorldApp.class.
One of the places java tries to find your .class file is your current directory. So if your .class file is in C:\java, you should change your current directory to that. To change your directory, type the following command at the prompt and press Enter:
cd c:\java
The prompt should change to C:\java>. If you enter dir at the prompt, you should see your .java and .class files. Now enter java HelloWorldApp again.
If you still have problems, you might have to change your CLASSPATH variable. To see if this is necessary, try clobbering the classpath with the following command.
set CLASSPATH=
Now enter java HelloWorldApp again. If the program works now, you'll have to change your CLASSPATH variable. To set this variable, consult the Update the PATH variable section in the JDK 6 installation instructions. The CLASSPATH variable is set in the same manner.
 
Exception in thread "main" java.lang.NoClassDefFoundError: HelloWorldApp/class A common mistake made by beginner programmers is to try and run the java launcher on the .class file that was created by the compiler. For example, you'll get this error if you try to run your program with java HelloWorldApp.class instead of java HelloWorldApp. Remember, the argument is the name of the class that you want to use, not the filename.
Exception in thread "main" java.lang.NoSuchMethodError: main
The Java VM requires that the class you execute with it have a main method at which to begin execution of your application. A Closer Look at the "Hello World!" Application discusses the main method in detail.

A simple JDBC application sample code

The basic process for a single data retrieval operation using JDBC would be as follows.
  • a JDBC driver would be loaded;
  • a database Connection object would be created from using the DriverManager (using the database driver loaded in the first step);
  • a Statement object would be created using the Connection object;
  • a SQL Select statement would be executed using the Statement object, and a ResultSet would be returned;
  • the ResultSet would be used to step through (or iterate through) the rows returned and examine the data.
The following JDBC code sample demonstrates this sequence of calls.
JDBCSample.java
  1. import java.sql.*
  2.  
  3. public class JDBCSample {
  4.  
  5. public static void main( String args[]) {
  6.  
  7. String connectionURL = "jdbc:postgresql://localhost:5432/movies;user=java;password=samples";
  8. // Change the connection string according to your db, ip, username and password
  9.  
  10. try {
  11.  
  12.     // Load the Driver class.
  13.     Class.forName("org.postgresql.Driver");
  14.     // If you are using any other database then load the right driver here.
  15.  
  16.     //Create the connection using the static getConnection method
  17.     Connection con = DriverManager.getConnection (connectionURL);
  18.  
  19.     //Create a Statement class to execute the SQL statement
  20.     Statement stmt = con.createStatement();
  21.  
  22.     //Execute the SQL statement and get the results in a Resultset
  23.     ResultSet rs = stmd.executeQuery("select moviename, releasedate from movies");
  24.  
  25.     // Iterate through the ResultSet, displaying two values
  26.     // for each row using the getString method
  27.  
  28.     while (rs.next())
  29.         System.out.println("Name= " + rs.getString("moviename") + " Date= " + rs.getString("releasedate");
  30. }
  31. catch (SQLException e) {
  32.     e.printStackTrace();
  33. }
  34. catch (Exception e) {
  35.     e.printStackTrace();
  36. }
  37. finally {
  38.     // Close the connection
  39.     con.close();
  40. }
  41. }
  42. }

Read a file line by line in Java - Sample Program

This sample Java program demonstrates how to read a file in Java Line by Line. For this the following two classes DataInputStream and BufferedReader are used. This program can be used to read any text file line by line and process the contents of the file within a Java Program.
Class DataInputStream
A data input stream is use to read primitive Java data types from an underlying input stream in a machine-independent way. An application uses a data output stream to write data that can later be read by a data input stream.
Data input streams and data output streams represent Unicode strings in a format that is a slight modification of UTF-8. (For more information, see X/Open Company Ltd., "File System Safe UCS Transformation Format (FSS_UTF)", X/Open Preliminary Specification, Document Number: P316. This information also appears in ISO/IEC 10646, Annex P.) Note that in the following tables, the most significant bit appears in the far left-hand column.
BufferedReader Read text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.
In general, each read request made of a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. For example,
BufferedReader in
   = new BufferedReader(new FileReader("foo.in"));
will buffer the input from the specified file. Without buffering, each invocation of read() or readLine() could cause bytes to be read from the file, converted into characters, and then returned, which can be very inefficient.
Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
import java.io.*;
class FileRead 
{
   public static void main(String args[])
  {
      try{
    // Open the file that is the first 
    // command line parameter
    FileInputStream fstream = new FileInputStream("textfile.txt");
    // Get the object of DataInputStream
    DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
    String strLine;
    //Read File Line By Line
    while ((strLine = br.readLine()) != null)   {
      // Print the content on the console
      System.out.println (strLine);
    }
    //Close the input stream
    in.close();
    }catch (Exception e){//Catch exception if any
      System.err.println("Error: " + e.getMessage());
    }
  }
}

Convert numbers to word as per Indian number system in java

This java program converts the number to its equivalent word representation according to indian numbering system. Eg. Lakhs, Crores etc..This program works upto 999999999.
import java.util.*;
public class NumtoWord 
{ 
public static void main(String[] args) 
{ 
String a;
Scanner s = new Scanner(System.in);
System.out.print("Enter a Number : ");
a = s.next();
int b = a.length();
String str[] = {"1","One","2","Two","3","Three","4","Four","5","Five","6","Six","7","Seven","8","Eight","9","Nine","10","Ten","11","Eleven","12","Twelve","13","Thirteen","14","Forteen","15","Fifteen","16","Sixteen","17","Seventeen","18","Eighteen","19","Nineteen","20","Twenty","30","Thirty","40","Fourty","50","Fifty","60","Sixty","70","Seventy","80","Eighty","90","Ninty","100","Hundred"};
System.out.println("");
if (b==9) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s5= a.substring(4,5);
String s6= a.substring(5,6);
String s7= a.substring(6,7);
String s8= a.substring(7,8);
String s9= a.substring(8,9);
String s10= a.substring(0,2);
String s11= a.substring(2,4);
String s12= a.substring(4,6);
String s14= a.substring(7,9);
{
if (s10.equals("00"))
System.out.print("");
else if (s1.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print("\n" + str[r+1] + " Crore ");
}
else
{
{
for (int i=0;i<=40;i++)
if (str[i].equals(s1))
System.out.print("\n" + str[i+37] + " ");
}
{
if(s2.equals("0"))
{
System.out.print("Crore ");
}
else 
for (int j=0;j<=40;j++)
{
if (str[j].equals(s2))
System.out.print(str[j+1] + " Crore ");
}
}
}
}
{
if (s11.equals("00"))
System.out.print("");
else if (s3.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s11)) 
System.out.print(str[r+1] + " Lacks ");
}
else
{
{
for (int k=0;k<=38;k++)
if (str[k].equals(s3))
System.out.print(str[k+37] + " ");
}
{
if(s4.equals("0"))
{
System.out.print("Lacks ");
}
else 
for (int l=0;l<=38;l++)
{
if (str[l].equals(s4))
System.out.print(str[l+1] + " Lacks ");
}
}
}
}
{
if (s12.equals("00"))
System.out.print("");
else if (s5.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s12)) 
System.out.print(str[r+1] + " Thousand ");
}
else
{ 
{
for (int m=0;m<=38;m++)
if (str[m].equals(s5))
System.out.print(str[m+37] + " ");
}
{
if(s6.equals("0"))
{
System.out.print("Thousand ");
}
else 
for (int n=0;n<=38;n++)
{
if (str[n].equals(s6))
System.out.print(str[n+1] + " Thousand ");
}
}
}
}
{
for (int o=0;o<=40;o++)
if (str[o].equals(s7))
System.out.print(str[o+1] + " Hundred ");
}
{
if (s14.equals("00"))
System.out.print("");
else if (s8.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s14)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s8))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s9))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==8) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s5= a.substring(4,5);
String s6= a.substring(5,6);
String s7= a.substring(6,7);
String s8= a.substring(7,8);
String s10= a.substring(1,3);
String s11= a.substring(3,5);
String s12= a.substring(6,8);
{
if (s1.equals("0"))
System.out.print("");
else
for (int i=0;i<=40;i++)
if (str[i].equals(s1))
System.out.print("\n" + str[i+1] + " Crore ");
} 
{
if (s10.equals("00"))
System.out.print("");
else if (s2.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1] + " Lacks ");
}
else
{
{
for (int k=0;k<=38;k++)
if (str[k].equals(s2))
System.out.print(str[k+37] + " ");
}
{
if(s3.equals("0"))
{
System.out.print("Lacks ");
}
else 
for (int l=0;l<=38;l++)
{
if (str[l].equals(s3))
System.out.print(str[l+1] + " Lacks ");
}
}
}
}
{
if (s11.equals("00"))
System.out.print("");
else if (s4.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s11)) 
System.out.print(str[r+1] + " Thousand ");
}
else
{ 
{
for (int m=0;m<=38;m++)
if (str[m].equals(s4))
System.out.print(str[m+37] + " ");
}
{
if(s5.equals("0"))
{
System.out.print("Thousand ");
}
else 
for (int n=0;n<=38;n++)
{
if (str[n].equals(s5))
System.out.print(str[n+1] + " Thousand ");
}
}
}
}
{
for (int o=0;o<=40;o++)
if (str[o].equals(s6))
System.out.print(str[o+1] + " Hundred ");
}
{
if (s12.equals("00"))
System.out.print("");
else if (s7.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s12)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s7))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s8))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==7) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s5= a.substring(4,5);
String s6= a.substring(5,6);
String s7= a.substring(6,7);
String s10= a.substring(0,2);
String s11= a.substring(2,4);
String s12= a.substring(5,7);
{
if (s10.equals("00"))
System.out.print("");
else if (s1.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1] + " Lacks ");
}
else
{
{
for (int k=0;k<=38;k++)
if (str[k].equals(s1))
System.out.print(str[k+37] + " ");
}
{
if(s2.equals("0"))
{
System.out.print("Lacks ");
}
else 
for (int l=0;l<=38;l++)
{
if (str[l].equals(s2))
System.out.print(str[l+1] + " Lacks ");
}
}
}
}
{
if (s11.equals("00"))
System.out.print("");
else if (s3.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s11)) 
System.out.print(str[r+1] + " Thousand ");
}
else
{ 
{
for (int m=0;m<=38;m++)
if (str[m].equals(s3))
System.out.print(str[m+37] + " ");
}
{
if(s4.equals("0"))
{
System.out.print("Thousand ");
}
else 
for (int n=0;n<=38;n++)
{
if (str[n].equals(s4))
System.out.print(str[n+1] + " Thousand ");
}
}
}
}
{
for (int o=0;o<=40;o++)
if (str[o].equals(s5))
System.out.print(str[o+1] + " Hundred ");
}
{
if (s12.equals("00"))
System.out.print("");
else if (s6.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s12)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s6))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s7))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==6) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s5= a.substring(4,5);
String s6= a.substring(5,6);
String s10= a.substring(1,3);
String s11= a.substring(4,6);

{
if(s1.equals("0"))
System.out.print("");
else 
{
for (int j=0;j<=40;j++)
if (str[j].equals(s1)) 
System.out.print(str[j+1] + " Lacks ");
}
}
{
if (s10.equals("00"))
System.out.print("");
else if (s2.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1] + " Thousand ");
}
else
{ 
{
for (int m=0;m<=40;m++)
if (str[m].equals(s2))
System.out.print(str[m+37] + " ");
}
{
if(s3.equals("0"))
{
System.out.print("Thousand ");
}
else 
for (int n=0;n<=38;n++)
{
if (str[n].equals(s3))
System.out.print(str[n+1] + " Thousand ");
}
}
}
}
{
if(s4.equals("0"))
System.out.print("");
else 
{
for (int o=0;o<=40;o++)
if (str[o].equals(s4)) 
System.out.print(str[o+1] + " Hundred ");
}
}
{
if (s11.equals("00"))
System.out.print("");
else if (s5.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s11)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s5))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s6))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==5) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s5= a.substring(4,5);
String s10= a.substring(0,2);
String s11= a.substring(3,5);
{
if (s10.equals("00"))
System.out.print("");
else if (s1.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1] + " Thousand ");
}
else
{ 
{
for (int m=0;m<=38;m++)
if (str[m].equals(s1))
System.out.print(str[m+37] + " ");
}
{
if(s2.equals("0"))
{
System.out.print("Thousand ");
}
else 
for (int n=0;n<=38;n++)
{
if (str[n].equals(s2))
System.out.print(str[n+1] + " Thousand ");
}
}
}
}
{
for (int o=0;o<=40;o++)
if (str[o].equals(s3))
System.out.print(str[o+1] + " Hundred ");
}
{
if (s11.equals("00"))
System.out.print("");
else if (s4.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s11)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s4))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s5))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==4) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s4= a.substring(3,4);
String s10= a.substring(2,4);
{
if(s1.equals("0"))
System.out.print("");
else 
{
for (int j=0;j<=40;j++)
if (str[j].equals(s1)) 
System.out.print(str[j+1] + " Thousand ");
}
}
{
if(s2.equals("0"))
System.out.print("");
else 
{
for (int o=0;o<=40;o++)
if (str[o].equals(s2)) 
System.out.print(str[o+1] + " Hundred ");
}
}
{
if (s10.equals("00"))
System.out.print("");
else if (s3.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s3))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s4))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==3) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s3= a.substring(2,3);
String s10= a.substring(1,3);
{
if(s1.equals("0"))
System.out.print("");
else 
{
for (int o=0;o<=40;o++)
if (str[o].equals(s1)) 
System.out.print(str[o+1] + " Hundred ");
}
}
{
if (s10.equals("00"))
System.out.print("");
else if (s2.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s2))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s3))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==2) 
{ 
String s1= a.substring(0,1);
String s2= a.substring(1,2);
String s10= a.substring(0,2);
{
if (s10.equals("00"))
System.out.print("");
else if (s1.equals("1"))
{
for (int r=0;r<=40;r++)
if (str[r].equals(s10)) 
System.out.print(str[r+1]);
System.out.print("\n"); 
}
else
{
for (int p=0;p<=40;p++)
if (str[p].equals(s1))
System.out.print(str[p+37]);
for (int q=0;q<=40;q++)
{
if (str[q].equals(s2))
System.out.print(" " + str[q+1]);
}
} 
System.out.print("\n"); 
}
}
else if (b==1) 
{ 
String s1= a.substring(0,1);
for (int q=0;q<=40;q++)
if (str[q].equals(s1))
System.out.print(" " + str[q+1]);
} 
System.out.println("\n"); 
}
}

Iterate a List in Java

This tutorial demonstrates the use of ArrayList, Iterator and a List. There are many ways to iterate a list of objects in Java. This sample program shows you the different ways of iterating through a list in Java.
In java a list object can be iterated in following ways:
  • Using Iterator class
  • With the help of for loop
  • With the help of while loop
  • Java 5 for-each loop
Following example code shows how to iterate a list object:
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
 
public class IterateAList {
  public static void main(String[] argv) {
 
                ArrayList arrJavaTechnologies = new ArrayList();

                arrJavaTechnologies.add("JSP");
                arrJavaTechnologies.add("Servlets");
                arrJavaTechnologies.add("EJB");
                arrJavaTechnologies.add("JDBC");
                arrJavaTechnologies.add("JPA");
                arrJavaTechnologies.add("JSF");


                //Iterate  with the help of Iterator class
                System.out.println("Iterating with the help of Iterator class");
                Iterator iterator = arrJavaTechnologies.iterator();
                while(iterator.hasNext()){
                        System.out.println( iterator.next() );
                }

                //Iterate  with the help of for loop
                System.out.println("Iterating with the help of for loop");
                for (int i=0; i< arrJavaTechnologies.size(); i++)
                {
                        System.out.println( arrJavaTechnologies.get(i) );
                }

                //Iterate  with the help of while loop
                System.out.println("Iterating with the help of while loop");
                int j=0; 
                while (j< arrJavaTechnologies.size())
                {
                        System.out.println( arrJavaTechnologies.get(j) );
                        j++;
                }
                //Iterate  with the help of java 5 for-each loop
                System.out.println("Iterate  with the help of java 5 for-each loop");
                for (String element : arrJavaTechnologies) // or sArray
                {
                        System.out.println( element );
                }
 
  }
}

Friday 26 August 2011

Important Basic C Programs in Interview Asked

(A) Write a c program to check given string is palindrome number or not

#include<string.h>
#include<stdio.h>
int main(){
  char *str,*rev;
  int i,j;
  printf("\nEnter a string:");
  scanf("%s",str);
  for(i=strlen(str)-1,j=0;i>=0;i--,j++)
      rev[j]=str[i];
      rev[j]='\0';
  if(strcmp(rev,str))
      printf("\nThe string is not a palindrome");
  else
      printf("\nThe string is a palindrome");
  return 0;
}

Definition of Palindrome string:

A string is called palindrome if it symmetric. In other word a string is called palindrome if string remains same if its characters are reversed. For example: asdsa
If we will reverse it will remain same i.e. asdsa

Example of string palindrome:  a,b, aa,aba,qwertrewq etc.

(B) check the given number is palindrome number or not using c program

#include<stdio.h>
int main(){
int num,r,sum=0,temp;
printf("\nEnter a number:");
scanf("%d",&num);
temp=num;
while(num){
r=num%10;
num=num/10;
sum=sum*10+r;
}
if(temp==sum)
printf("\n%d is a palindrome",temp);
else
printf("\n%d is not a palindrome",temp);
return 0;
}

Definition of Palindrome number:

A number is called palindrome number if it is remain same when its digits are reversed. For example 121 is palindrome number. When we will reverse its digit it will remain same number i.e. 121

Examples of palindrome number: 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191 etc.

(C) CHECKING LEAP YEAR USING C PROGRAM

#include<stdio.h>
#include<conio.h>
void main(){
    int year;
    clrscr();
    printf("Enter any year: ");
    scanf("%d",&year);
    if(((year%4==0)&&(year%100!=0))||(year%400==0))
         printf("%d is a leap year",year);
    else
         printf("%d is not a leap year",year);
    getch();
}

Definition of leap year :

Rule 1 : A year is called leap year if it is divisible by 400.
For example : 1600,2000  etc leap year while 1500,1700 are not leap year.
Rule 2 : If year is not divisible by 400 as well as 100 but it is divisible by 4 then
that year are also leap year.
For example:  2004,2008,1012 are leap year.

Algorithm of leap year :

IF year MODULER 400 IS 0
THEN leap_year
ELSE IF year MODULER 100 IS 0
THEN not_leap_year
ELSE IF year MODULER 4 IS 0
THEN leap_year
ELSE
not_leap_year



(D) Write a c program to check given number is strong number or not.

#include<stdio.h>
int main(){
  int num,i,f,r,sum=0,temp;
  printf("\nEnter a number");
  scanf("%d",&num);
  temp=num;
  while(num){
      i=1,f=1;
      r=num%10;
      while(i<=r){
      f=f*i;
          i++;
      }
      sum=sum+f;
      num=num/10;
  }
  if(sum==temp)
      printf("%d is a strong number",temp);
  else
      printf("%d is not a strong number",temp);
  return 0;
}

Definition of strong number:

A number is called strong number if sum of the factorial of its digit is equal to number itself. For example: 145 since
1! + 4! + 5! = 1 + 24 + 120 = 145

(E) Check the given number is armstrong number or not using c program

#include<stdio.h>
int main(){
int num,r,sum=0,temp;
printf("\nEnter a number:-");
scanf("%d",&num);
temp=num;
while(num!=0){
r=num%10;
num=num/10;
sum=sum+(r*r*r);
}
if(sum==temp)
printf("\nThe number %d is an armstrong number",temp);
else
printf("\nThe number %d is not an armstrong number",temp);
return 0;
}

Definition of Armstrong number:

Definition for c programming point of view:
Those numbers which sum of the cube of its digits is equal to that number are known as Armstrong numbers. For example 153 since 1^3 + 5^3 + 3^3 = 1+ 125 + 9 =153
Other Armstrong numbers: 370,371,407 etc.
In general definition:
Those numbers which sum of its digits to power of number of its digits is equal to that number are known as Armstrong numbers.
Example 1: 153
Total digits in 153 is 3
And 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
Example 2: 1634
Total digits in 1634 is 4
And 1^4 + 6^4 + 3^4 +4^4 = 1 + 1296 + 81 + 64 =1634
Examples of Armstrong numbers: 1, 2, 3, 4, 5, 6, 7, 8, 9, 153, 370, 371, 407, 1634, 8208, 9474, 54748, 92727, 93084, 548834, 1741725

(F) write the program for prime numbers?
Answer
# 1    

main()
{
int i,j=2,ch=0;
clrscr();
       printf("\nENTER ANY NUMBER");
       scanf("%d",&i);
  while(j<=i/2)
       {
        if(i%j==0)
          {
            printf("%d IS NOT PRIME",i);
            ch=1;
            break;
          }
        else
          {
           j++;
          }
      }
 if(ch==0)
   {
   printf("%d IS PRIME",i);
   }
}

(G) TO FIND FACTORIAL OF A NUMBER USING C PROGRAM

#include<stdio.h>
int main(){
  int i=1,f=1,num;
  printf("\nEnter a number:");
  scanf("%d",&num);
  while(i<=num){
      f=f*i;
      i++;
  }
  printf("\nFactorial of %d is:%d",num,f);
  return 0;
}

Tuesday 16 August 2011

JAVA 7 Features

Virtul Machine

JSR 292: Support for dynamically-typed languages (InvokeDynamic)

VM and language extensions to support the implementation of dynamically-typed languages at performance levels near to that of the Java language itself

Strict class-file checking [NEW]
Per the Java SE 6 specification, class files of version 51 (SE 7) or later must be verified with the typechecking verifier introduced by JSR 202 in Java SE 6; the VM must not fail over to the old inferencing verifier

Language

JSR 334: Small language enhancements (Project Coin)

A set of small language changes intended to simplify common, day-to-day programming tasks:

1.      Strings in switch statements
2.      Automatic resource management
3.      Improved type inference for generic instance creation ("diamond")
4.      Simplified varargs method invocation,
5.      Better integral literals,
6.       Improved exception handling (multi-catch)

Core

Upgrade class-loader architecture

Modifications to the ClassLoader API and implementation to avoid deadlocks in non-hierarchical class-loader topologies

Method to close a URLClassLoader

A method that frees the underlying resources, such as open files, held by a URLClassLoader

Concurrency and collections updates (jsr166y)

A lightweight fork/join framework, flexible and reusable synchronization barriers, transfer queues, a concurrent-reference HashMap, and thread-local pseudo-random number generators

Internationalization

Unicode 6.0

Upgrade the supported version of Unicode to 6.0

Locale enhancement

Upgrade the java.util.Locale class to support IETF BCP 47 and UTR 35 (CLDR/LDML)

Separate user locale and user-interface locale

Upgrade the handling of locales to separate formatting locales from user-interface language locales, as is done on Vista and later versions of Windows

I/O and Networking

JSR 203: More new I/O APIs for the Java platform (NIO.2)

New APIs for filesystem access, scalable asynchronous I/O operations, socket-channel binding and configuration, and multicast datagrams

NIO.2 filesystem provider for zip/jar archives

A fully-functional and supported NIO.2 filesystem provider for zip and jar files

SCTP (Stream Control Transmission Protocol)

An implementation-specific API for the Stream Control Transmission Protocol on Solaris

SDP (Sockets Direct Protocol)

Implementation-specific support for reliable, high-performance network streams over Infiniband connections on Solaris and Linux

Use the Windows Vista IPv6 stack

Upgrade the networking code to use the Windows Vista IPv6 stack, when available, in preference to the legacy Windows stack

TLS 1.2

Add support for TLS 1.2, which was standardized in 2008 as RFC 5246

Security & Cryptography

Elliptic-curve cryptography (ECC)

A portable implementation of the standard Elliptic Curve Cryptographic (ECC) algorithms, so that all Java applications can use ECC out-of-the-box

JDBC

JDBC 4.1

Upgrade to JDBC 4.1 and Rowset 1.1

Client

XRender pipeline for Java 2D

A new Java2D graphics pipeline based upon the X11 XRender extension, which provides access to much of the functionality of modern GPUs

Create new platform APIs for 6u10 graphics features

Create new platform APIs for features originally implemented in the 6u10 release: Translucent and shaped windows, heavyweight/lightweight mixing, and the improved AWT security warning

Nimbus look-and-feel for Swing

A next-generation cross-platform look-and-feel for Swing

Swing JLayer component

Add the SwingLabs JXLayer component decorator to the platform

Web

Update the XML stack

Upgrade the JAXP, JAXB, and JAX-WS APIs to the most recent stable versions

Management

Enhanced JMX Agent and MBeans [NEW]

An implementation-specific enhanced JMX management agent, ported from JRockit, which makes it easier to connect to the platform MBean server through firewalls, together with a richer set of MBeans which expose additional information about the internal operation of the VM

Deferred to JDK 8 or later

JSR 294: Language and VM support for modular programming

Enhancements to the Java language and virtual-machine specifications to support modular programming, at both compile time and run time

JSR 308: Annotations on Java types

An extension to the Java annotation syntax to permit annotations on any occurrence of a type

JSR TBD: Language support for collections

Literal expressions for immutable lists, sets, and maps, and indexing-access syntax for lists and maps

JSR TBD: Project Lambda

Lambda expressions (informally, "closures") and defender methods for the Java programming language

Modularization (Project Jigsaw)

A simple, low-level module system focused upon the goal of modularizing the JDK, and the application of that system to the JDK itself

JSR 296: Swing application framework

An API to define the basic structure of a typical Swing application, thereby eliminating lots of boilerplate code and providing a much-improved initial developer experience

Swing JDatePicker component

Add the SwingLabs JXDatePicker component to the platform

Courtesy:http://sharad-java-j2ee-interview-questions.blogspot.com/search/label/Core%20Java

Java SE 7 Features and Enhancements

Highlights of Technology Changes in Java SE 7

The following list contains links to the the enhancements pages in the Java SE 7 guides documentation. Choose a technology for further information.

What is difference between Unchecked and Checked Exceptions? and What is difference between Synchronized method and Synchronized block?

What is difference between Unchecked and Checked Exceptions?

Unchecked exceptions :
  • represent defects in the program (bugs) - often invalid arguments passed to a non-private method. To quote from The Java Programming Language, by Gosling, Arnold, and Holmes : "Unchecked runtime exceptions represent conditions that, generally speaking, reflect errors in your program's logic and cannot be reasonably recovered from at run time."
  • are subclasses of RuntimeException, and are usually implemented using IllegalArgumentException, NullPointerException, or IllegalStateException
  • a method is not obliged to establish a policy for the unchecked exceptions thrown by its implementation (and they almost always do not do so)
Checked exceptions :
  • represent invalid conditions in areas outside the immediate control of the program (invalid user input, database problems, network outages, absent files)
  • are subclasses of Exception
  • a method is obliged to establish a policy for all checked exceptions thrown by its implementation (either pass the checked exception further up the stack, or handle it somehow)

What is difference between Synchronized method and Synchronized block?

What is difference between Synchronized method and Synchronized block?


The key difference is this: if you declare a method to be synchronized, then the entire body of the method becomes synchronized; if you use the synchronized block, however, then you can surround just the "critical section" of the method in the synchronized block, while leaving the rest of the method out of the block.
If the entire method is part of the critical section, then there effectively is no difference. If that is not the case, then you should use a synchronized block around just the critical section. The more statements you have in a synchronized block, the less overall parallelism you get, so you want to keep those to the minimum.

What is difference between ArrayList and Vector ?

  1. The Vector class is synchronized, the ArrayList is not.
  2. ArrayList is fast than the Vector.

JDK 5 Enhancements in Java Language

JDK 5 Enhancements in Java Language


1.      Generics - This is an enhancement to the type system allows a type or method to operate on objects of various types while providing compile-time type safety. It adds compile-time type safety to the Collections Framework and eliminates the drudgery of casting.
e.g.
Previously
Array List numbers = new ArrayList();

Now in JDK 5.0
Array List<Integer> numbers = new ArrayList<Integer> ();

2.      Enhanced for Loop - This new language construct eliminates the drudgery and error-proneness of iterators and index variables when iterating over collections and arrays.
e.g.      
Previously
Iterator itr = numbers.iterator();
while
 (itr.hasNext()) 
{
      Integer element = (Integer)itr.next();
      System.out.println (number);
}

Now in JDK 5.0
for (Integer number: numbers)
{
            System.out.println (number);
}

3.      Autoboxing/Unboxing - This facility eliminates the drudgery of manual conversion between primitive types (such as int, long) and wrapper types (such as Integer, Long).
e.g.      
int number = 1;
Previously
Integer number2 = (Integer) number;

Now in JDK 5.0
Integer number2 = number;

4.      Typesafe Enums - This flexible object-oriented enumerated type facility allows you to create enumerated types with arbitrary methods and fields. It provides all the benefits of the Typesafe Enum pattern ("Effective Java," Item 21) without the verbosity and the error-proneness.
e.g.
Previously
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL   = 3;

Now in JDK 5.0
enum Season {WINTER, SPRING, SUMMER, FALL}

5.      Varargs - This facility eliminates the need for manually boxing up argument lists into an array when invoking methods that accept variable-length argument lists.
e.g.
Previously
Object[] arguments = {
    new Integer(7),
    new Date(),
    "a disturbance in the Force"
};

String result = MessageFormat.forma("At {1,time} on {1,date}, there was {2} on planet "
     + "{0,number,integer}.", arguments);

Now in JDK 5.0
Using Varargs no need to create object array separately, we can give arguments directy.

String result = MessageFormat.format("At {1,time} on {1,date}, there was {2} on planet "
    + "{0,number,integer}.",
    7, new Date(), "a disturbance in the Force");

6.      Static Import - This facility lets you avoid qualifying static members with class names without the shortcomings of the "Constant Interface antipattern."
e.g.
Previously
double r = Math.cos(Math.PI * theta);

Now in JDK 5.0
import static java.lang.Math.*;
Once the static members have been imported, they may be used without qualification or class names:
double r = cos(PI * theta);

7.      Annotations (Metadata) - This language feature lets you avoid writing boilerplate code under many circumstances by enabling tools to generate it from annotations in the source code. This leads to a "declarative" programming style where the programmer says what should be done and tools emit the code to do it. Also it eliminates the need for maintaining "side files" that must be kept up to date with changes in source files. Instead the information can be maintained in the source file.
Now in JDK 5.0
public @ interface Test{}

Complete Details about eLitmus pH Test at Rs:699/- Share your java material and fresher interview Information for us to Help Others... mail to : vhkrishnan.v@gmail.com