Wednesday, June 5, 2013

Access Specifiers In Java with real time example

Definition :
- Java Access Specifiers (also known as Visibility Specifiers ) regulate access to classes, fields and methods in Java.These Specifiers determine whether a field or method in a class, can be used or invoked by another method in another class or sub-class. Access Specifiers can be used to restrict access. Access Specifiers are an integral part of object-oriented programming.

Types Of Access Specifiers :
In java we have four Access Specifiers and they are listed below.

1. public
2. private
3. protected
4. default(no specifier)

We look at these Access Specifiers in more detail.



 public specifiers :
Public Specifiers achieves the highest level of accessibility. Classes, methods, and fields declared as public can be accessed from any class in the Java program, whether these classes are in the same package or in another package.

Example :
  1. public class Demo {  // public class  
  2. public x, y, size;   // public instance variables   
  3. }

private specifiers :

Private Specifiers achieves the lowest level of accessibility.private methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses. So, the private access specifier is opposite to the public access specifier. Using Private Specifier we can achieve encapsulation and hide data from the outside world.

Example :
  1. public class Demo {   // public class  
  2. private double x, y;   // private (encapsulated) instance variables  
  3.   
  4. public set(int x, int y) {  // setting values of private fields  
  5. this.x = x;  
  6. this.y = y;  
  7. }  
  8.   
  9. public get() {  // setting values of private fields  
  10. return Point(x, y);  
  11. }  
  12.  }  
    protected specifiers :

    Methods and fields declared as protected can only be accessed by the subclasses in other package or any class within the package of the protected members' class. The protected access specifier cannot be applied to class and interfaces.

    default(no specifier):

    When you don't set access specifier for the element, it will follow the default accessibility level. There is no default specifier keyword. Classes, variables, and methods can be default accessed.Using default specifier we can access class, method, or field which belongs to same package,but not from outside this package.

    Example :
    1. class Demo  
    2. {  
    3. int i; (Default)  
    4. }  

    Real Time Example : 
  13.                                      

How many ways of creating objects in Java?

Well... there aren't many different ways I suppose. But from an application programmer perspective here are the different possible ways of creating objects in Java:-
  • Using new operator - the most commonly used way by far. 'new' is an operator and the only operand it requires is a constructor which will be used for initializting the newly created instance. 'new' operator allocates the memory space and initializes the fields with their default values. Then it executes the code inside the specified constrcutor which normally re-writes the default values of some (or all) fields with the particular values mentioned in the constructor definition.
  • Using clone() method - Cloning (Shallow or Deep) makes a new copy of the specified object. It doesn't call the 'new' operator internally. Object.clone() is a native method which translates into instructions for allocating the memory and copying the data. Remember that even if we override the clone() method either to implement Deep Cloning or to make the clone() method as 'public' but then also we keep the line super.clone() inside the overriden definition which ultimately calls Object.clone() method only. You might wonder about what the 'new' operator actually translates into and how this approach is different from that. Okay... we all know that 'new' does three tasks - allocating the memory, initializing the fields with default values, and calling the specified constructor. Now the first task is same in both the approaches and there would probably be the same native allocator being used in both the cases. But in case of Cloning, the allocated memory is not initialized with default values and also no constructor is called in this case. Only a datacopy instruction will be executed which copies the data from the original object to the cloned object. Read more about Cloing in this article - Cloning in Java >>
Using Class.forName() and newInstance() - A calss can be dynamically loaded using the Class.formName() method. This method has two variants - one which accepts only a String type parameter which is the qualifies name of the class to be loaded and the other variant expects three parameters - the String type qualifies class name, boolean type flag to specify if the class should be initialized, and the ClassLoader name which should be used to load the class. The former variant also internally calls the three-parameter variant only by assuming the boolean flag as 'true' and the ClassLoader as returned by the getClassLoader() method. That means 'Class.forName("qualified.ClassName")' is internally translated into 'Class.forName("qualifies.ClassName", true, this.getClass().getClassLoader())'. Once the class has been loaded then a call of the method newInstance() on the loaded Class object will first check if the Class object is initialized or not and if not then it will initialize the Class object and create a new object as if the 'new' operator has been called with the default constructor of the class under consideration. Again you may argue how is this different from an explicit 'new' call and it won't take much of an effort to identify the most obvious difference between the two as the inability of this approach to call any other constructor except the default constructor. Another difference is that the newInstance() call may throw a SecurityException as well because it checks if a Security Manager is installed or not and if it finds a security manager then it checks for access to the class as wellas to the package (if any package specified in the qualified name). Either of two checks may throw a SecurityException. This step is obviously not involved with an explicit 'new' call. Another slightly different way of object creation is by using the loadClass() method of the ClassLoader class which returns a Class object of the specified class and then on the returned Class object we may call newInstance() method to create a new object. I've not put this as a completely separate way because I think Class.forName() method also internally calls this method only - either for the explcitly supplied ClassLoader or for the implcitily obtained ClassLoader as discussed above. What's the difference between the two approaches then? The only difference which I can see is that the former checks for the access to the class (and package) and hence it may throw SecurityException if a Security Manager is installed. But the latter doesn't do these checks and hence doesn't throw SecurityException. It's normally advised not to call the loadClass() method directly as almost always you can call Class.forName() by supplying the particular ClassLoader reference

Java Object oriented programming concepts with real time examples

Java Object oriented programming concepts with real time examples



OOPS Concepts are mainly 4 
 1.Abstraction
 2.Encapsulation
 3.Inheritance 
 4.Polymorphism
Abstraction:-Hiding non-essential features and showing the
essential features
              (or)
Hiding unnecessary data from the users details,is called
abstraction.
Real Time example:1.TV Remote Button 
in that number format and power buttons and other buttons
there.just we are seeing the buttons,we don't see the
button circuits.i.e buttons circuits and wires all are
hidden.so i think its good example.

Encapsulation:It is a process of binding or wrapping the data and the
codes that operates on the data into a single entity. This
keeps the data safe from outside interface and misuse. One
way to think about encapsulation is as a protective wrapper
that prevents code and data from being arbitrarily accessed
by other code defined outside the wrapper.

Real Time Example:  

1.Ink is the important component in pen but it is hiding
by some other material 
2.Medical Tablet
i.e one drug is stored in bottom layer and another drug is
stored in Upper layer these two layers are combined in
single Tablet.

Inheritance:The new classes, known as derived classes, take over (or
inherit) attribute and behavior of the pre-existing classes,
which are referred to as base classes (or Parent classes).
It is intended to help reuse existing code with little or no
modification.
Real Time Example:
1. Father and Son Relationship

Polymorphism:Single Form behaving differently in different Situations. A single 

function or single operator has different characters in different places. 

Real Time Example:
1.A girl plays a role of daughter at home and a manager at
office.
2. Person
Person in Home act is husband/son,
       in Office acts Employer.
       in Public Good Citizen. 
 
<<<<<<<<<<<<<<<<------------------------->>>>>>>>>>>>>
 

OOPS Concepts with realtime examples

1. Abstraction

Abstraction helps to hide the non essential features from the user and makes the application user friendly.

Eg. Take your mobile phone. You are having buttons and know the purpose but no need to understand how it prints number on the screen when it is pressed.

2. Encapsulation

It bundles the code into a single unit which makes the code very easy to handle.

Eg.

Take computer keyboard. All the buttons have been enclosed.

3. Inheritance

It helps to inherit the superclass properties to subclasses.

Eg. Father - Son relationship.

4. Polymorphism

A entity which behaves differntly at different places.

Eg. A person behaves as a good husband in family.
He behaves as a good employee at company.
He also behaves as a good citizen in public.
 

Monday, May 20, 2013

switch case in jsp


<%    switch (tabNavigator)

     {

                            

      case QUALIFICATION:

                         %>

<jsp:include page="classmaster.jsp"></jsp:include>

                   <%

                        break;

                        case RACKSHELF:

                   %>

<jsp:include page="rackshelfmaster.jsp"></jsp:include>

                   <%

                        break;

                            case MEDIA:

                   %>

                   <jsp:include page="mediamaster.jsp"></jsp:include>

                   <%

                   break;

                             case MEMBER:

                   %>

                   <jsp:include page="membermaster.jsp"></jsp:include>

                   <%

                        break;

                             case PLAN:

                   %>

                   <jsp:include page="planmaster.jsp"></jsp:include>

                   <%

                        break;

                             case DEPARTMENT:

                   %>

                   <jsp:include page="departmentmaster.jsp"></jsp:include>

                        <%

                        break;

                             case VENDOR:

                   %>

                   <jsp:include page="vendormaster.jsp"></jsp:include>

                   <%

                        break;

             

                        default:

                   %>

                             <jsp:include page="index.jsp"></jsp:include>

                   <%

                        }

                             session.removeAttribute("NAVIGATOR_REQUEST");

                   }

                   %>



Tuesday, April 30, 2013

Dynamically adding textbox and labels in jsp

1)ajax.jsp:


<%@page import="java.sql.*"%><html>
<head>
<script type="text/javascript">
function showData(value){ 

xmlHttp=GetXmlHttpObject()
var url="getdata.jsp";
url=url+"?name="+value;
xmlHttp.onreadystatechange=stateChanged 
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() { if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){ 
    var showdata = xmlHttp.responseText; 
    document.getElementById("lab").innerHTML="Address";
    document.getElementById("address").style.visibility="visible";
    document.getElementById("address").value= showdata;
        } }
function GetXmlHttpObject(){
var xmlHttp=null;
try {
  xmlHttp=new XMLHttpRequest();
 }
catch (e) {
 try  {
  xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
 catch (e)  {
  xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
return xmlHttp;
}
</script>
</head>
<body>
<form name="employee">
<br><br>
<pre>
<label>Name</label>     <input  type="text" name="name" id="name" onkeyup="showData(this.value);">
<label id="lab">       </label>  <input style="visibility:hidden" type="text" name="address" id="address">
</form>    </html>
 
 
--------------------------------------------------
 
 
2)getdata.jsp:

<%@ page import="java.sql.*" %> <%
String name = request.getParameter("name").toString();
System.out.println(name);
String data ="";
try{
           
Class.forName("com.mysql.jdbc.Driver");
           
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
           
Statement st=con.createStatement();
           
ResultSet rs=st.executeQuery("select * from employee where name='"+name+"'");
while(rs.next())
{
data
=rs.getString("address");
}
out.println(data);
System.out.println(data);
}
catch (Exception e) {
System.out.println(e);
}
%>

How to create drop down list using JSP

how to display values from database into table using jsp


Code---->                                                             Link
---------------------------------------------------------------------------------
 
<%@ page language="java" %><%@ page import="java.sql.*" %><script>
function change(){
var cid=document.getElementById("book").selectedIndex;
var val = document.getElementById("book").options[cid].text;
window.location.replace("http://localhost:8080/examples/jsp/dependentDropdown.jsp?id="+cid+"&&value="+val);
}
function extract(){
var ide=document.getElementById("info").selectedIndex;
var bookname = document.getElementById("info").options[ide].text;
window.location.replace("http://localhost:8080/examples/jsp/dependentDropdown.jsp?book="+bookname);
}
</script>
<%!
Connection conn = null;
ResultSet rs =null;
Statement st=null;
String query="";

%><%
String value=request.getParameter("value");
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/register","root";, "root");
st = conn.createStatement();
rs = st.executeQuery("select * from book");
%><select id="book" onchange="change();">
<option value="0">--Please Select--</option>
<% while(rs.next()){ %>
<option value="<%=rs.getString("books")%>"><%=rs.getString("books")%></option>
<% if(rs.getString("books").equals(value)){%>
<option value="<%=value%>" selected disabled><%=value%></option>
<%
}
}
%></select>
<select id="info" onchange="extract(this)">
<option value="0">--Please Select--</option>
<%
String id=request.getParameter("id");
rs=st.executeQuery("select * from bookInformation where bookid='"+id+"'");
while(rs.next()){
%>
<option value="<%=rs.getString("id")%>" ><%=rs.getString("booknames")%></option>
<%
}
%></select>
<%
String book=request.getParameter("book");
String author="";
String price="";
rs=st.executeQuery("select * from bookInformation where booknames='"+book+"'");
while(rs.next()){
author=rs.getString("writer");
price=rs.getString("price");
}
if((book!=null)&&(author!=null)&&(price!=null)){
%><table >
<tr><td>Book Name</td><td><input type="text" value="<%=book%>"></td></tr>
<tr><td>Author</td><td><input type="text" value="<%=author%>"></td></tr>
<tr><td>Price</td><td><input type="text" value="<%=price%>"></td></tr>
</table>
<%
}
%></body>
</html>
 
 
-------------------------------------------------------
Book
 
CREATE TABLE `book` (
`bookid` bigint(20) NOT NULL auto_increment,
`books` varchar(255) default NULL,
PRIMARY KEY (`bookid`)
);
 
------------------------------------------------------
  BookInformation

CREATE TABLE `bookinformation` (
`id` bigint(255) NOT NULL auto_increment,
`bookid` int(255) default NULL,
`booknames` varchar(255) default NULL,
`writer` varchar(255) default NULL,
`Price` double default NULL,
PRIMARY KEY (`id`)
);
 
 

Monday, April 29, 2013

CheckBox Example in jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Show all names</title>
</head>
<body>


<form method="GET" action='Controller' name="showall">
<table>
  <tr>
    <td><input type="checkbox" name="id1" /></td>
    <td>Jim</td>
    <td>Knopf</td>
  </tr>
  <tr>
    <td><input type="checkbox" name="id2" /></td>
    <td>Jim</td>
    <td>Bean</td>
  </tr>
</table>

<p><input type="submit" name="delete" value="delete" />&nbsp;
   <input type="submit" name="edit" value="edit" />&nbsp;
  <input type="reset"
  value="reset" /></p>
</form>



</body>
</html>