Sunday, November 7, 2010

Programming Java:

www.javabeginner.com
www.dreamincode.net
www.java2s.com


The Complete Reference of Java Programming:
Data Types, Variable and Arrays:
f
Operators:
f
Control Statements:
f
Method and Classes:
f
Inheritance:
f
Packages:
f
Interface:
f
Exception Handling:
f
Multithread:
f
Input/Output ,Applet, and Other Topics:

We can Take input in java using Scanner
//How to take input in java

import java.util.Scanner.
public class inputs
   {
         public static void main(String args[])
              {
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("Inputs");
                    String  s_name = scanner.nextLine();                //type   variable_name  = scanner.nextLine();
                    Int       number = scanner.nextInt();                  //type variable_name = scanner.nextInt();
              }
   }


String Handling:
f
Exploring Java.lang:
f
java.util:
f
File in java:
f
Networking:
f
Applet Class:
f
Event Handling:
f
AWT: Working with Windows, Graphics and Text:
f
AWT Control, Layout Managers, and Menus:
f
Image:
f

Min,max,average and sum of array

    public int min (int []nums){
        int min=nums[0];
         for(int i=0;i
            if(min>nums[i])
                min=nums[i];
        }
        return min;
    }

        public int max (int []nums){
        int max=nums[0];
         for(int i=0;i
            if(max
                max=nums[i];
        }
        return max;
    }

 //Mean Average
   public int mean (int [] nums){
       int avg=0;
        for(int i=0;i
          avg+=nums[i];
        }
       return avg/nums.length;
   }

 //Median Average
   public int median(int[] nums) {
    Arrays.sort(nums);
    int middle = nums.length/2;
     if (nums.length%2 == 1) {
      return nums[middle];
   }
     return (nums[middle-1] + nums[middle]) / 2;

}
   //Range
   public int range(int[] nums) {
    Arrays.sort(nums);
    return nums[nums.length-1]-nums[0];
}
          public int sum (int []nums){
          int add=0;
           for(int i=0;i
            add+=nums[i];
          }
         return add;
     }

-------------------------------------------------------------------------------------------
/* Snippet: Binary Search
 * Author: SPlutard
 *
 *Description: An efficient method for searching SORTED arrays. Returns the number if found, otherwise returns -1.
 */

public static int binarySearch(int[] list, int listLength, int searchItem) {
    int first=0;
    int last = listLength - 1;
    int mid;
   
    boolean found = false;
   
    //Loop until found or end of list.
    while(first <= last &&!found) {
        //Find the middle.
        mid = (first + last) /2;
       
        //Compare the middle item to the search item.
        if(list[mid] == searchItem) found = true;
        else { //Not found, readjust search parameters, halving the size & start over.
            if(list[mid] > searchItem) last = mid -1;
            else first = mid + 1;
        }
    }
   
    if(found) return mid;
    else return(-1);
}

-----------------------------------------------------------------------------------------------------
/* Snippet: Bubble Sort Method
 * Author: SPlutard
 *
 * Description: The Bubble Sort method works like this:
 *      In a series of n-1 iterations, the successive elements, list[index] and list[index + 1] of list are compared.
 *      If list[index] is greater than list[index + 1], then the elements of list[index] and list[index + 1] are swapped.
 *      This process is repeated through the list until no swaps are necessary.
 *      On average, for a list with length 'n', the Bubble Sort method takes:
 *          key comparisons:    (n*(n-1))/2             
 *          item assignments:   (n*(n-1))/4             
 */

public class TestBubbleSort {
    public static void main(String[] args) {
        int unsortedArray[] = {10, 97, 6, 23, 0, -45, 697, -1000, 1, 0}; //Random set of numbers for example.
        int i;
       
        bubbleSort(unsortedArray, unsortedArray.length); //Pass the array to be sorted and its length.
       
        System.out.println("After sorting, the list elements are: "); //Just to show you it worked. :)
       
        for(i=0; i
            System.out.print(unsortedArray[i] + " ");
        }
    }

    private static void bubbleSort(int[] unsortedArray, int length) {
        int temp, counter, index;
       
        for(counter=0; counter
            for(index=0; index
                if(unsortedArray[index] > unsortedArray[index+1]) { //Test if need a swap or not.
                    temp = unsortedArray[index]; //These three lines just swap the two elements:
                    unsortedArray[index] = unsortedArray[index+1];
                    unsortedArray[index+1] = temp;
                }
            }
        }
    }
}

----------------------------------------------------------------------------------
/* Snippet: Insert Sort
 * Author: SPlutard
 *
 *Description: Sorts an array of integers using the insertion sort algorithm (moving each element to its proper place).
 *              More efficient than Bubble Sort.
 */

public static void insertionSort(int[] list, int length) {
    int firstOutOfOrder, location, temp;
   
    for(firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++) { //Starts at second term, goes until the end of the array.
        if(list[firstOutOfOrder] < list[firstOutOfOrder - 1]) { //If the two are out of order, we move the element to its rightful place.
            temp = list[firstOutOfOrder];
            location = firstOutOfOrder;
           
            do { //Keep moving down the array until we find exactly where it's supposed to go.
                list[location] = list[location-1];
                location--;
            }
            while (location > 0 && list[location-1] > temp);
           
            list[location] = temp;
        }
    }
}

--------------------------------------------------
Java with Database MySQL:

Installing the Driver:
1. Download MySQL ODBC Connector. I have a copy for windows users at www.mysqlodbccon.4shared.com . Please refer to the links below for more info.(Don't bother the filename if it says noinstall, you're still going to be installing it anyway)

2. Extract the Zip File and Run Install.bat (see, like I told you... although the batch (.bat) file copies the library(.dll) files into your operating system unlike real installers where they involve file extraction)
 

3. A message will prompt that the installation (copying of libraries) was successful.

Setting up the Data Source:
1. We will now create a Data Source Name(DNS) which will be used as a reference by the program. First go to your control panel then Administrative Tools > Data Sources (ODBC)
 
3. Click on the Add button then another Dialog Box containing the Drivers will appear. Select MySQL ODBC Driver then click Finish.
 
4. Another Dialog Box will appear for the final configuration. Just fill up the necessary inputs, the Data Source Name that you will be using on the text box. The Server should contain the local server name (you can use localhost or your computer name). Enter the user and password fields, and the database that you will be using as source.
 
Creating table in database/Coding in database:
For portability and general purposes, we will be using the Open Database Connectivity (ODBC). Connecting to MySQL with the use of Open Database is similar to connecting to MS Access only with some additional steps.
We will first be creating a table in mysql for our example:
CREATE TABLE `humans` (
  `ID` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `LastName` varchar(90) NOT NULL,
  `FirstName` varchar(90) NOT NULL,
  `Gender` varchar(90) NOT NULL,
  `Address` varchar(255) NOT NULL,
  `Phone` varchar(45) NOT NULL,
  PRIMARY KEY (`ID`)
)

Coding in Java:
We will now explain the coding for connecting to the database

Step 1: First import the necessary libraries for Database connection, java.sql

import java.sql.*;

These are the necessary tools we will be needing:
Connection - This represents the connection to a specific database. This is used to establish the connection with the database drive.
Statement - This is used to execute the SQL statement.
ResultSet - This holds the table of the data that is generated from an sql statement. For statements other than select, this is not necessary used since the statement would not return a table.

Step 2: Then instantiate your connection variables
Connection con;
Statement stmt;
ResultSet rs
 
Step 3: On your procedural method, create an exception handler

try{
 
//Your Code Goes Here
}catch(Exception e){
System.err.println(e);
}

To make your exception handling more specific, you can add 2 more catch before Exception containing SQLException and ClassNotFoundException


4.In the try block, insert your connection code, First is the forced loading of the Database Driver in
 Class.forName() followed by the declaration of objects we instantiated earlier.

//Load the JdbcOdbc Driver
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
 
//Specify the Database URL where the DNS will be and the user and password
con = DriverManager.getConnection("jdbc:odbc:TOY2","root","root");
 
//Initialize the statement to be used, specify if rows are scrollable
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
//ResultSet will hold the data retrieved
rs = stmt.executeQuery("SELECT * FROM Humans");
 
on our con.createStatement() method, we had 2 parameters, (these are optional but it would be recommended for you to add this for some convenience): ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY

According to javadoc, TYPE_SCROLL_SENSITIVE is a constant indicating the type for a ResultSet object that is scrollable and generally sensitive to changes made by others. I add this to make the buffer of the ResultSet move back to the beginning whenever needed. While CONCUR_READ_ONLY is The constant indicating the concurrency mode for a ResultSet object that may NOT be updated. I only use this for retrieving data, this also ensures that no changes will be made on the database.

Then we now get the data from the ResultSet object
//Display the results
while(rs.next()){
System.out.println(rs.getInt("ID") + " " + rs.getString("LastName") + " " + rs.getString("FirstName"));
}
For a full source code listing:
import java.sql.*;
 
public class ViewingMySQL {
 
public static void main(String[] args) {
Connection con;
Statement stmt;
ResultSet rs;
try{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:TOY2","root","root");
 
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = stmt.executeQuery("SELECT * FROM Humans");
 
while(rs.next()){
System.out.println(rs.getInt("ID") + " " + rs.getString("LastName") + " " + rs.getString("FirstName"));
}
}catch(Exception e){
System.err.println(e);
}
}
}
 

No comments:

Post a Comment

Total Pageviews