Sunday, June 9, 2013

Define different main method format in Java

Do you know what do you mean of “public static void main()”?

Public

It  is “access specifier” ; so it is basically define the scope of methods, classes and interface and etc.  you know JRE (Java Run-time Environment) is the outside part of class. if we use other access specifier (private, protected) so you can’t access the that class. If you are not used any access specifier. So compiler use the default access specifier.
Static

In class there are two type members
      1-Instance member
          represent attributes and behavior of individual object. By default all the      member of class is instance member.
     2-class member
          represent attributes and behavior of whole class. Denoted  by  “static”   keyword.
So static keyword are used define the class member.
Void

Functions are always requires a return type so void is one of them to returns value implicitly. If any error occur in the program so O.S returns the value with the help of  JRE.
Main:

only method name
Are you know the given below syntax are valid or not valid  in JAVA?

Syntex-(Modifier ReturnType MethodName() )

Static public void main (String [] arg ) true
Static public void main(String[][] arg) runtime error NoSuchMethodError
Static void public main (String [][] arg) compile time error
Void static public main (String arg[]) compile time error
 public static void main (String arg) runtime error NoSuchMethodError
Public void static main ([] String arg) compile time error
Public static void main (String[] arg[]) runtime error NoSuchMethodError
Public static void main() runtime error NoSuchMethodError

                                                 Author-Ravi Kumar


Wednesday, June 5, 2013

Joins in SQL

Introduction

SQL joins are used to relate information in different table or say joins are used to combine two or more tables.

Types of Join

 Types of joins are
  1. Self Join
  2. Inner Join
  3. Outer Join
    Outer Join are three types:

    (a) Right Outer Join
    (b) Left Outer Join
    (c) Full Outer Join
     
  4. Cross Join
    Cross  Join are two types:

    (a) Implicit cross join
    (b) Explicit cross join
Now, I explain each and every separately.

1- Self Join

A "self-join" joins a table itself. Basically "self-join" are rare, they are some time useful for retrieving data that can't retrieved any other way.

Syntax

SELECT a.columnName, b.columnName.... FROM table1 a, table1 b where a.commonField=b.common_field;
Example

This example describes you how to play with SELF-JOIN.
Look "empdtl" table design

Now I am inserting some data in that table, After inserting some values table data look like

Now, I want to get details of those "employee's", who are manager. Then I simply write a query for it.

SELECT distinct e1.empid, e1.empname FROM empdtl e1, empdtl e2 where e1.empid=e2.managerid;Output


2- Inner Join
The Join condition indicates how the two table should be compared. The "inner join" is a join in which the values in the columns being joined are compare using a common operator. You can simple say "inner join" selects all rows from both table as long as there is a match between the columns in both tables.
Syntax
SELECT columnsName or selectlist FROM table1 INNER JOIN table2 ON table1.columnName=table2.columnName

OR
SELECT columnsName or selectlist FROM table1  JOIN table2 ON table1.columnName=table2.columnName
Here I shown "empdtl" and "dept" table data as a image for using the INNER JOIN

Query For Inner Join 



Here I want to get the "deptname" from  the "dept" table, "id" and "name" from "empdtl" table, on the behalf of "id"  of the "empdtl" table, Let's see how to do it:

SELECT empdtl.id,empdtl.name,dept.deptname from empdtl join dept on empdtl.id=dept.deptid;
 Output

 

3- Outer Join

The "outer join" are three types I explain each and every separately:
(a) Right Outer Join
 
Right Outer join returns all rows from the right table, with the matching row in the left table, the result is NULL in the left side when there is no match.Data of both "empdtl" and "dept" table 

Example

SELECT empdtl.id,empdtl.name, dept.deptname from empdtl RIGHT OUTER JOIN dept on empdtl.id=dept.deptid;Output


(b) Left Outer Join

The "left outer join" is used to returning the all rows from the left table, with the matching row in the right table and the NULL is appear in the right side when there is no match.
Data of both "empdtl" and "dept" table 

Example
SELECT empdtl.id,empdtl.name, dept.deptname from empdtl LEFT OUTER JOIN dept on empdtl.id=dept.deptid;Output

(c) Full Outer Join

The "full outer join" is used to returns all woes from the left and right table or you can say full outer join combines the result of both left and right joins.

Example

SELECT empdtl.id,empdtl.name, dept.deptname from empdtl FULL OUTER JOIN dept on empdtl.id=dept.deptid;Output

4- Cross Join

A "cross join" produces a result set that indicates each row from the first table joined with each row of the second table and this result set is known as the Cartesian Product of the table and the "cross join" have two types.

(a) Explicit cross join

To use an "explicit cross join", write the "cross join" keywords after the first table name and before the second table name
Syntax
SELECT columnsName or selectList FROM table1 CROSS JOIN table2

Example
SELECT id,name,deptname from empdtl CROSS JOIN deptOutput

(b) Implicit  cross join

To use an "implicit  cross join", you do not need to write the "cross join" keywords after the first table name and before the second table name, you just simply write comma (,) symbol after the first table name and before the second table name.
Syntax
SELECT columnsName or selectList FROM table1, table2

Example
SELECT id,name,deptname from empdtl,deptOutput

Sunday, June 2, 2013

Basic Interview Question in Java



Introduction

Java, now it’s time to play with JAVA. I started with a new existing point.

Can we use multiple main in a program

Yes; we can use multiple “main()” method in a java program. But the both main methods argument should not be same, as you know, the  java programs execution is start from “main()” method means (
public static void main(String arg[]), then simply declare the second ‘main()” method in this main method for execution, Now the given below example shown you how to do it.

E
xample

 class A
{
public static void main(String arg[])
{System.out.println("welcome");
main();

}
public static void main()
{
System.out.println("first");
}
}

Output

Can we run the program without main(String [] args) method

Yes we can run a java program without  main() method. Because java provide a functionality with the use of “static” keyword and that “static” keyword can be a block or static data member or static method,  firstly execute whenever you compile a  java program. Let’s see, it works or not.

Example
 class A
{
static
{
System.out.println("welcome");
System.exit(0);
}
}Output



Can we change the main thread name?

Yes, we can change the main thread name.

Can we print the message before the main method execution?

Yes, we can print the message before the main method. Let’s see how

Example
class A
{
static
{
System.out.println("welcome");
}
public static void main(String arg[])
{System.out.println("main method");}}Output

Friday, May 31, 2013

Find Duplicate Record in Sql Server


Introduction

In this article i will explain how to find or count duplicate record in SQL Server.

In this example i have a datatable and this table doesn't contain any primary key because of that duplicate records inserted in table.

First i will create table without contain any primary key

Query


CREATE TABLE [dbo].[Emp_Info]
(
      [Emp_Id] [int] NULL,
      [Name] [varchar](50) NULL,
      [Salary] [int] NULL,
      [City] [varchar](50) NULL

)
Now insert some duplicate record in this table.




Now count how many duplicate record exits in datatable with the help of below query

Query


select Emp_Id, Name, Count(*) as DuplicateRecord
From Emp_Info
Group By Emp_Id, Name, City

Having Count(*) >1 Order By Emp_Id


Wednesday, May 29, 2013

Find vowels character in a String

Introduction

Some one ask a question to me, how to find all vowels from a string without repeating vowels ( means you can find out vowels from a string but if one is come out like 'E' from that string, then next time it is not included with the output.

Now I write a code for Find out vowels from a given string.

Example

using System;
class Program
{
    static void Main()
    {
        string value1 = RemoveDuplicateChars("AERTJEIUO");
        for (int i = 0; i <= value1.Length - 1; i++)
        {
                // code that checks the char is vowel or not
            if (65 == (int)value1[i] || 69 == (int)value1[i] || 73 == (int)value1[i] || 79 == (int)value1[i] || 85 == (int)value1[i]) 
            {
                Console.WriteLine(value1[i]);
            }
        }
        Console.ReadKey();
    }
 
    // method for removing the duplicate characters
        static string RemoveDuplicateChars(string key)
    {
        string val1 = "";
        string result = "";
        foreach (char value in key)
        {
            if (val1.IndexOf(value) == -1)
            {
                val1 += value;
                result += value;
            }
        }
        return result;
    }
}

Output


Monday, May 27, 2013

SQL interview questions:Part1


1-  Difference in Delete truncate and Drop
  1. Truncate
     
    • Truncate is faster and used by fewer system.
    • Truncate can not be roll back.
    • It is DDL (Data Definition Language) command.
    • You can not use where clause with  Truncate command.
    • Truncate table statement deletes all data from a table without deleting the definition of table.
  2. Delete 
     
    •  Delete removes rows once at a time, means you can use delete with and without where clause.
    • Delete can be roll back.
    • It is DML (Data Manipulation Language) command.
    • DELETE does not reset the identity of the table.
  3. Drop
     
    • Drop command removes table definition including indexer, trigger, constraints.
2-  Difference between clustered and non-clustered index
  1. A clustered index
     
    • A clustered index is a type of index where the table records are physically re-ordered to math the index. A table can have only one clustered index. One of the most important point about clustered index is that "Primary Key has to be Clustered Index".
  2. A non-clustered index
     
    •  A non-clustered index is a special type of index in which the logical order of the index does not match physical order of the rows on disk.
3-  Important Data Types in SQL
Data Type Syntax
integer integer
numeric numeric (p,s)
decimal decimal (p,s)
float float (p,s)
character char (x)
date date
time time
bit bit (x)
real real
smallint smallint
4-  Create, Drop or Delete, Select and show Database
  1. Create a Database
     
    Syntax
    CREATE DATABASE  databaseName

    Example

    SQL>CREATE DATABASE test;
     
  2. Delete or drop a Database

    syntax

    DROP DATABASE dataBaseName

    Example

    SQL>DROP DATABASE TEST;
     
  3. Select a Database

    syntax

    USE DataBaseName;

    Example

    SQL> USE Test;
     
  4. Show all Databases
    Example

    For SQL
    sp_databases

    And For mysql

    mysql>Show DATABASES;

Thursday, May 23, 2013

Difference between Primary key and Unique Key in Sql


Difference between Unique key and Primary key

A UNIQUE constraint and PRIMARY key both are similar and it provide unique enforce uniqueness of the column on which they are defined.
Some are basic differences between Primary Key and Unique key are as follows.

Primary key
  1. Primary key cannot have a NULL value.
  2. Each table can have only single primary key.
  3. Primary key is implemented as indexes on the table. By default this index is clustered index.
  4. Primary key can be related with another table's as a Foreign Key.
  5. We can generated ID automatically with the help of Auto Increment field. Primary key supports Auto Increment value. 
Unique Constraint
  1. Unique Constraint may have a NULL value.
  2. Each table can have more than one Unique Constraint.
  3. Unique Constraint is also implemented as indexes on the table. By default this index is Non-clustered index.
  4. Unique Constraint can not be related with another table's as a Foreign Key.
  5. Unique Constraint doesn't supports Auto Increment value.
Define Primary and Unique Key

Create table Student
(
StuId int primary key, ---- Define Primary Key
StuName varchar(50) Not Null,
ContactNo int Unique --- Define Unique Key
)
Insert some data in table


Now you will see above fig. StuId can not have NULL value but ContactNo can have NULL value.

Wednesday, May 22, 2013

Gridview checkbox validation using JavaScript in Asp.net


Introduction

In this article i will explain check the checkbox selected status in gridview using JavaScript in Asp.net.

The following example check whether checkboxes selected in gridview or not. In this example I have taken one gridview with checkboxes and I have taken one button If user click on button without check any checkbox it rise validation.

Firstly I am created a database EmpDetail. and Now I am created a table in this database. 

Query Code

CREATE TABLE [dbo].[Emp_Info](
      [Emp_Id] [int] NULL,
      [Name] [varchar](50) NULL,
      [Salary] [int] NULL,
      [City] [varchar](50) NULL
) ON [PRIMARY]
Now Insert some Data in Emp_Info table. Then use the following procedure.
Complete Program

Checkbox_Validation.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Checkbox_Validation.aspx.cs" Inherits="Checkbox_Validation" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function CheckBox_Validation()
        {
            var valid = false;
            var gdvw = document.getElementById('<%= gdview.ClientID %>');
            for (var i = 1; i < gdvw.rows.length; i++)
            {
                var value = gdvw.rows[i].getElementsByTagName('input');
                if (value != null)
                {
                    if (value[0].type == "checkbox")
                    {
                        if (value[0].checked)
                        {
                            valid = true;
                            alert("Checkbox selected successfully");
                            return true;
                        }
                    }
                }
            }
            alert("Please select atleast one checkbox");
            return false;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <asp:GridView ID="gdview" CssClass="Gridview" runat="server" AutoGenerateColumns="false" HeaderStyle-BackColor="#669999"
HeaderStyle-Font-Bold="true" HeaderStyle-ForeColor="Black" HeaderStyle-BorderColor="#333300" HeaderStyle-BorderWidth="1">
        <Columns>
            <asp:TemplateField>
                <HeaderTemplate>
                    <asp:CheckBox ID="chkbox" runat="server" />         
                </HeaderTemplate>
                <ItemTemplate>
                    <asp:CheckBox ID="chkboxchild" runat="server" />
                </ItemTemplate>
            </asp:TemplateField>
            <asp:BoundField HeaderText="Emp_Id" DataField="Emp_Id" HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>
            <asp:BoundField HeaderText="Name" DataField="Name" HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>
            <asp:BoundField HeaderText="Salary" DataField="Salary" HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>
            <asp:BoundField HeaderText="City" DataField="City" HeaderStyle-HorizontalAlign="Left" >
<HeaderStyle HorizontalAlign="Left"></HeaderStyle>
            </asp:BoundField>
        </Columns>
        <EditRowStyle Font-Bold="False" Font-Italic="False" />
<HeaderStyle BackColor="#99CCFF" Font-Bold="True" ForeColor="Black" BorderColor="#663300" BorderWidth="1px"></HeaderStyle>
    </asp:GridView>
        <br />
        <asp:Button runat="server" Text="Submit" OnClientClick="javascript:CheckBox_Validation()" Font-Bold="True" Font-Italic="False" />
    </div>
    </form>
</body>
</html>

Checkbox_Validation.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
 
public partial class Checkbox_Validation : System.Web.UI.Page
{
    SqlConnection con;
    SqlDataAdapter da;
    DataSet ds;
    protected void Page_Load(object sender, EventArgs e)
    {
        using (con = new SqlConnection("Data Source=.;Initial Catalog=EmpDetail;Integrated Security=True"))
        {
            using (da = new SqlDataAdapter("Select * from Emp_Info", con))
            {
                ds = new DataSet();
                da.Fill(ds);
                gdview.DataSource = ds.Tables[0];
                gdview.DataBind();
            }
        }
    }
}
Output 1


Click on "Submit" button without any check checkbox


Output 2

Click on "Submit" button after check checkboxes