20 October 2010
1 Memory DeAllocation-Garbage Collection in Java
Memory DeAllocation or Garbage Collection in Java
A major difficulty in dynamic memory allocation in C/C++ was that the programmer is responsible for de-allocating the dynamic memory at the right time. Even though experienced programmers can do this very well, beginners and average programmers often missed the statements for de-allocated which led to memory-leak in many systems.An object that is not referred by any reference variable will be removed from the memory by the garbage collector, this process is known as Garbage Collection
Garbage Collection is Automatically done by JVM, the Automatic Garbage Collection of Java de-allocates the dynamic memory automatically when this memory is no more used by the program. This relieves the programmer from the overhead of memory de-allocation.
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends.
Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use.
Primitive types are not objects and they cannot be assigned null.
0 Memory Allocation in Java
Memory Allocation in Java
All local variables are stored in a stack. local variables are de-allocated in a last in first out order as soon as the method terminates.
All dynamically allocated arrays and objects are stored in heap. They need not be de-allocated in any specific order. They can be garbage collected (removed from the memory) as and when their use is over.
Garbage Collection in Java
An object that is not referred by any reference variable will be removed from the memory by the garbage collector. Garbage Collection is automatic.
If a reference variable is declared within a function, the reference is invalidated soon as the function call ends.
Programmer can explicitly set the reference variable to null to indicate that the referred object is no longer in use.
0 What is Method Overloading in Java?
Method Overloading in Java
Two or more methods in a Java class can have the same name, if their argument lists are different, this feature is known as Method Overloading.Argument list could differ in
- No of parameters
- Data type of parameters
- Sequence of parameters
System.out.println(i);
}
void print(double d){
System.out.println(d);
}
void print(char c){
System.out.println(c);
}
Method Overloading in Java is Static Polymorphism
Calls to overloaded methods will be resolved during compile time, In otherwords, when the overloaded methods are invoked, JVM will choose the appropriate method based on the arguments used for invocation. For example, if the print method is invoked with an int argument, the overloaded print method that accepts an int parameter will be chosen by the JVM.
Example of Different implementation of Method Overloading in Java
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)
Methods differing only in return type
Methods differing only in return type will not be treated as overloaded methods, it will be compilation error. For Example, the below given methods will give compilation error.
System.out.println(i);
}
int print(int i)){
System.out.println(i);
return i;
}
Overloading the Constructors
Just like other methods, constructors also can be overloaded.
public Student(){
mark = 100;
}
public Student(int rollNo, double mark){
this.rollNo = rollNo;
this.mark = mark;
}
}
0 How to Invoke methods in a Java class?
Invoking methods in a class
The following statement creates a new "Student" object and assigns its reference to "student".
All the public members of the object can be accessed with the help of the reference.
student.setRollNo(20);
System.out.println(student.getRollNo());
For using a Student object, a programmer need not know the internal implementation details of the class. One needs to know only the public methods to use a Student object. Abstraction is achieved by hiding the irrelevant implementation details and exposing the relevant interface details.
0 How to Create Objects in Java?
Creating Objects in Java
In Java, all objects are created dynamically. The operator "new" is used for dynamic memory allocation.The following statement creates an object of the class Student
The following statement creates a reference to the class "Student".
Student student;
//Create a new Student object
//Make student refer to the new object
Student student = new Student();
0 Multidimensional Arrays in Java
Multidimensional Arrays in Java
- Multidimensional arrays are arrays of arrays.
- To declare a multidimensional array variable, specify each additional index using another set of square brackets.
//x is a reference to an array of int arrays
x = new int[3][4];
/*Create 3 new int arrays, each having 4 elements
x[0] refers to the first int array, x[1] to the second etc
x[0][0] is the first element of the first array
x.length will be 3
x[0].length, x[1].length and x[2].length will be 4 */
0 What is Reference variables in Java?
Reference variables in Java
Reference variables are used in Java to store the references of the objects created by the operator new
Any one of the following syntax can be used to create a reference to an int array.
int [] x;
The reference x can be used for referring to any int array.
int [] x;
//Create a new int array and make x refer to it
x = new int[5];
The following statement also creates a new int array and assigns its reference to x
A reference type can be assigned ‘null’ to show that it is not referring to any object. ‘null’ is a keyword in Java
19 October 2010
0 Arrays in Java
array in Java
In Java, all arrays are created dynamically. The operator "new" is used for dynamic memory allocation.
The following statement creates an array of 5 integers.
The above statement returns a reference to the newly created array. References in Java are very similar to pointers in C
char [] c = {‘a’, ‘b’, ‘c’};
Java will not allow the programmer to exceed its boundary
If x is a reference to an array, x.length will give you the length of the array
The for loops can be set up as follows
0 What is Methods in Java?
Methods in Java
Methods in Java is nothing but functions (As in C) the syntax of writing methods in Java is similar to that of functions in C.
Unlike C, all methods in Java should be written inside a class.
Unlike C, there is no default return type for a Java method.
In C language, a function whose return type is not specified is assumed to return an int. In Java there is no default return type for a method. Specifying the return type of a method is mandatory in Java.
0 What are the Operators in Java?
0 Typecasting of primitive data types in Java
Typecasting of primitive data types in Java
Variable of smaller capacity can be assigned to another variable of bigger capacity without any explicit typecasting
double d;
d = i;
Whenever a larger type is converted to a smaller type, the typecast operator has to be explicitly specified. This prevents accidental corruption of data.
int i;
i = (int) d;
0 What is Variables in Java?
Variables in Java
Declaring and using primitive data types is Java similar to that of C.
int maxCount=100;
Unlike C, in Java, variables can be declared anywhere in the program.
System.out.println(“Program starts here”);
int j = 20;
for (int index=0; index <maxCount; index++) {
int z = index * 10;
}
Best Practice while dealing with Java Variables: Declare a variable in program only when required. Do not declare variables upfront like in C.
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}
Any one of the following syntax can be used to create a reference to an int array
int [] x;
0 What is Phishing in Network Security?
Phishing
Some unreliable site gets your information (passwords, bank account details, etc) without your knowledge.Mostly phishing is done by, sending emails to the users, which will be claimed to be sent by your bank or some other reliable sites.
Most of the Phishing websites can easily be filtered using Phishing Filters.
Phishing Filters are available in Internet Explorer 7.0 and Mozilla FireFox.
To enable Phishing Filters option, click Tools, then Phishing Filter. With this option enabled, if any Phishing site is found, IE and Mozilla displays a warning icon in the status bar which means that the site may be unsafe.
17 October 2010
0 What is ServletContext in Java?
ServletContext
The servlet's view of the web application within which the servglet is running is defined by the ServletContext. It also allows access to resources available for it. Within a web server a ServletContext is routed at a specific path.ServletContext Scope
There will be one instance of the ServletContext interface associated with each web application deployed into a container.
In cases where the container is distributed over many virtual machines, there is one instance per web server per virtual machine.
Servlet that exists in a container that were not deployed as part of a web application are implicitly part of the default web application and are contained by the default ServletContext. In a distributed container,the default ServletContext is non-distributable and must only exist on one virtual machine.
ServletContext Attributes
A servlet can bind an object into the context by name.
Any object bound to a context is available to any other servlet which is part of the same application.
Following are the methods of ServletContext which allow access to this functionalty.
- setAttribute()
- getAttribute()
- getAttributeNames()
- removeAttribute()
0 What is Requirements Engineering
Requirements Engineering
“Requirements Engineering involves all life-cycle activities devoted to identification of user requirements, analysis of the requirements to derive additional requirements, documentation of the requirements as a specification, and validation of the documented requirements against user needs, as well as processes that support these activities.”-DoD(Department of Defense). Software Technology Strategy.
In a software industry, no one can bear the consequences of ineffective requirements engineering. The cost of inaccurate, misunderstood, and not signed off requirements affects everyone in the industry in terms of time, money and opportunities lost. The result will be of total chaos in terms of frustration, confusion, mistrust, higher cost, lack of quality, overtime, over budget, a general lack of understanding and incapability to handle issues. The interests of all the known stakeholders in a software system, coincide more in requirement engineering phase than in other phases. This leads to exciting products, happy developers and delighted customer, if requirements are handled well, else it can become the source of frustration, friction and misunderstanding that can undermine product's business value and quality. As requirements is the base for both software development and project management activities, all stakeholders should follow an effective requirements engineering process.
0 Servlet Cookie API in Java
Servlet Cookie API in Java
HttpServletInterface.getCookie() method is used to retrieve an array of cookies from the request object.The cookie is the data sent as a part of the request object by the client.
The client sends only the cookie name and cookie value.
- java.lang.Object clone(): Overrides the standard java.lang.Object.clone method to return a copy of this cookie.
- java.lang.String getComment(): Returns the comment describing the purpose of this cookie, or null if the cookie has no comment.
- java.lang.String getDomain(): Returns the domain name set for this cookie.
- Int getMaxAge() : Returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will persist until browser shutdown.
- java.lang.String getName() : Returns the name of the cookie.
- java.lang.String getPath()
- java.lang.String getValue
- int getVersion()
- void setComment(java.lang.String purpose)
- void setDomain(java.lang.String pattern)
- void setMaxAge(int expiry)
- void setValue(java.lang.String newValue)
- void setVersion (int version)
Method:- void addCookie(Cookie cookie)
Method:- Cookies[] getCookies()
0 What is Cookie?
Cookies
Cookies are some plain text files mainly used for session tracking. A Cookiie is an object created ny server which contains the state information and will be sent to the client browser and will be accepted and stored by browser (Provided Cookies are not disabled at the browser). In otherwords,The names and values of cookies are stored on the client machine. Some of the information that is saved includes the cookie’s:
- Name
- Value
- Expiration date
- path
- Cookies are the simplest and most effective of all session tracking mechanisms
- As cookies are plain text files, they are never interpreted or executed and cannot be used to insert viruses
- Some browsers doesn't support cookies.
- Cookies cannot be stored on the client side if the browser has disabled the cookies. So, cookies cannot be used as a session tracking mechanism in such cases.
- Cookies presents a significant threat to privacy.
0 HTTP Session Tracking Java
Importance of Session Tracking
When a client (Web browser) makes a request for a page or a file, the web server locates it and send back the requested file. Once the web server sends the requested file back to the web browser, there ends the connection. No session or state is maintained between the client and server, Otherwise it would increase the overheads of keeping a lot of sessions alive between the client and the server that would pose a serious performance issue. While this model scores from a performance viewpoint, it becomes a severe constraint when designing applications for the Web.
This problem can be overcome if a session is kept alive between a client and a server. For example, consider a typical scenario of a client application connecting to a database server. Once the client connects to a database, a session is established between the client and the database server. The client can invoke a stored procedure as part of its application logic. The call to the stored procedure can return data to the client that can be conditionally evaluated and different branches of execution can be initiated as part of continuing with the same application.
The Hypertext Transfer Protocol (HTTP) is by design a stateless protocol. To build effective Web applications, it is imperative that a series of different requests from a particular client can be associated with each other. Many strategies for session tracking have evolved over time, but all are difficult or troublesome for the programmer to use directly. State maintenance and session tracking became serious bottlenecks for designing effective Web-based applications. The cookie evolved as a solution to the problem of state maintenance and session tracking.
0 Why HTTP protocol is Stateless protocol
HTTP protocol is Stateless protocol
In HTTP protocol, Web servers and web browsers will transfer hypertext and images (sometimes files like swf etc also).When a client (Web browser) makes a request for a page or a file, the web server locates it and send back the requested file. Once the web server sends the requested file back to the web browser, there ends the connection.
No session or state is maintained between the client and server, Otherwise it would increase the overheads of keeping a lot of sessions alive between the client and the server that would pose a serious performance issue. While this model scores from a performance viewpoint, it becomes a severe constraint when designing applications for the Web which needs session tracking.
0 How to Access HTTP Request Header in Java?
Accessing Request Header in Java
In Java, HTTP request headers can be accessed by the following methods of the HttpServletRequest interface.
- getHeaderNames
- getHeader
- getHeaders
0 What is Http Request Header?
Http Request Header
The Http Request Header contains the client side information which may be useful for the web server to generate responce. Http Request headers are very much different from the Form data. Request Headers are directly sent by the browser. Request headers comes immediately after POST or GET request line.
The Http Request object includes the following headers: Host, Accept-Encoding, Accept, Cookie, Host, Referrer, User-Agent,Connection etc.
Accessing Request Header in Java
In Java, HTTP request headers can be accessed by the following methods of the HttpServletRequest interface.
- getHeaderNames
- getHeader
- getHeaders
12 October 2010
0 init service destroy methods of Servlet
1 What is GenericServlet?
GenericServlet
GenericServlet is a class which can be used for easy servlet programming than using Servlet interface.
Most often a web programmer will be intersted only in the service method of Servlet interface. But For implementing the Servlet interface, the programmer has to implement all the methods of it.
The class GenericServlet of javax.servlet package implements the servlet interface. And GenericServlet implements the init() and destroy() methods. The service() method is left as an abstract method for the servlet programmer to implement. So, for creating a servlet, it is easy to extend the GenericServlet class than to implement the Servlet interface.
0 Request Handling using Servlet
Request Handling using Servlet
The servlet can handle the request only after proper initialization. The request handling phase is carried out by the service method of the servlet life cycle. The service method of the Servlet takes ServletRequest and ServletRespose as the parameters. HTTPRequest object holds information about the request, client and the form data. Servlet then create a response to the request by using the provided object of type ServletResponse. For a HTTP request, the request and response objects are of type HttpServletRequest and HttpServletResponse respectively.
Most of the containers will create only one instance of a Servlet. The same instance is used for servicing all the client request. For each client request, the container executes the service method in a thread. So for multiple client requests, only multiple threads are created and not multiple objects. This model requires lesser memory and lesser cpu time compared to the multiple object model.
The Servlet need not to be alive throughout. It can be active in a container for milliseconds or as long as the container is up or any amount of time in between. Before unloading the servlet from the memory it may be required to release the resource or save the persistence state. To do this the servlet container provides the destroy method which is called by the server before removing the servlet from the memory. But before calling the servlet destroy() method servlet container waits for the threads that are running in the service to either complete, or exceed a server defined time limit. Once the destroy is called no further requests can be processed by that instance of the servlet. In order to process new requests servlet container needs to create a new instance of the servlet's class. Once the destroy method finishes, the servlet container releases the servlet. And is collected by the garbage collector.
0 Adavntages of Servlets over CGI
2 What is a Servlet Container in Java?
Servlet Container
A standalone Java program is directly invoked by the end user and starts its execution from the main method. But in case of a servlet, the client makes a http request to the Web-Server in order to execute the servlet. For the servlet to execute it has to be loaded into the memory, receive the client request and respond back to the client. These responsibilities are carried out by a service known as the Servlet container.
Network Service
The Servlet Container along with a web server or application server, provides the necessary network services so that the request and response can be communicated over the network between the client and the server.
Coding/decoding
The container decodes MIME (Multipurpose Internet Mailing Extensions) based requests and then passes on the request object to the servlet. Similarly formats the response generated by the servlet into MIME based responses so that the client browser understands the output generated by the servlet.
LifeCycle Management
It manages the lifecycle of the servlet.
Servlet Container can either be a part of the host web server or installed as an add-on component to a Web Server.
Servlet Container can also be built into Application Servers. HTTP protocol is supported by all the vendors for requests and response. But along with HTTP they may support other request/response based protocols such as HTTPS (HTTP over SSL).
0 What is Servlet in JEE Java?
Servlets
Servlets are Java codes which is used to generate dynamic webpages. Servlets are programs written in Java code and will be executed in a webserver. That’s why named as servlet similar to applet which is executed at the Browser (client end). Servlets are used for generating the dynamic pages. Servlets are not meant for any specific client server protocol . But, as it is mostly used by the HTTP protocol, word “Servlet” refers to HTTPServlet. Servlet was introduced by the Sun Microsystems as an alternative to CGI. The output of a servlet can be a HTML/XML/Text or any other format as well.
11 October 2010
0 What are JEE containers?
Application client container
Application client container is the one which is responsible for managing the application client components. Both application client and its container resides at the client machine and are executed on the client end. Example of application container is JVM.
Applet container
Applet container is the container to manage the execution of applets. Examples of an applet container include Web browser and applet viewer.
Enterprise JavaBeans (EJB) container
Enterprise JavaBeans (EJB) container is used to manage the execution of EJB component of the J2EE application. Both the EJBs and its container run on the J2EE server. J2EE server provides the EJB container, and an example of J2EE server is WebLogic.
Web container
Web container is used to manage the execution of the Servlets and the JSP. Both the Web components and its container run on the J2EE server. An example of a web container is Tomcat.
- Life cycle Management- Creating and deleting components
- Persistence- Saving information in the components
- Naming- Recording the name of a server component and locating it for the client.
- Deployment- Placing components in the server
- Messaging- Exchanging information between components.
2 What is JEE Architecture?
JEE Architecture
JEE follows the distributed multi-tiered application approach which means the entire application may not reside at a single location, but distributed. And the applications is divided into various tiers. J2ee application is composed of various components which can be created by the different developers and then assembled together. These components can be installed on different machines across various tiers. And the distribution of application components across the solely different tiers depends upon the functionality it performs.JEE Architecture Diagrom
J2ee application tiers are as follows
- Client Tier (Web Browser or any other kinds of clients)
- Web tier
- Business Tier
- Enterprise Information tier (Database or sometimes XMLs or flatfiles)
Components are self contained piece of software that are reusable across applications and are configurable external to the source code.
J2EE components are of three types : client component, web component and business component. The client components interact with the user, the web components interact with the web browsers using the HTTP protocol, and the business components interact with the application server and execute the business logic.
Client components is of two types : web client and application client.
- A web client, generally a browser, sends a request to the server and renders the webpage sent back by the server. However, it may not perform any complex tasks such as querying a database or performing any complicated business tasks and hence is also referred to as thin client. The complex tasks are performed on the server. For displaying web pages with applets, the web clients may require Java plug-ins and security policy files for executing the applets.
- An application client is a standalone application that doesn’t run in browsers. It can access components in the business tier directly. Note that web clients that require access to a servlet running in the Web tier can open an HTTP connection with the servlet.
Web components for java are Servlets and JavaServer Pages (JSP). A servlet receives HTTP requests from the client, processes them, and returns the output. It can also generate dynamic responses. Similar to servlets, JSP also create dynamic web pages. JSP pages are converted into servlets and executed within a servlet container. They are used to display the results processed by a servlet.
Business components implement the business logic or the functional process logic that defines the business rules and constraints. For example business process such as withdrawing amount from the bank. Business components are of three types : session beans, entity beans, and message-driven beans. Session beans represent a session with a client. Being a transient object, they lose their data on completion of the session. On the other hand, entity beans are persistent objects and so retain data even after the session. They represent a row of data in a database table. Message-driven beans are for receiving the receiving Java Message Service (JMS) messages asynchronously.
07 October 2010
0 Url Rewriting using for Session Tracking
Session Tracking by Url Rewriting
- Client appends some extra data on the end of each URL that identifies the session
- Server associates that identifier with data it has stored about that session
- URL Rewriting can be used when working with the browsers that don’t support cookies.
- URL Rewriting can be used when the user has disabled the cookies.
- URL Rewriting also supports anonymous session tracking.
- Url Rewriting has Security risk : Session id appears in the URL , it can be easily seen by other users: Users may copy and paste those link without knowing attached session id which compromises the security.
- Server log files may record the Referer header which may record the session id in the log.
- Must encode all URLs that refer to your own site.
- All pages must be dynamically generated.
- Fails for bookmarks and links from other sites.
0 What is constructor in Java
A constructor is a special method that is called to create a new object. It is not mandatory to write a constructor for the class. Constructor can be treated as a readily available, implicit method in every class.
If a user defined constructor is available, it is called just after the memory is allocated for the object.
If no user defined constructor is provided for a class, the implicit constructor initializes the member variables to its default values.
Numeric data types are set to 0,
Char data types are set to null character(‘\0’),
Boolean data types are set to false,
Reference variables are set to null
The user defined constructor is usually used to initialize the data members of the objects to some specific values, other than the default values. A constructor method will have the same name as that of the class. A constructor method will not have any return type, not even void.
Just like other methods, constructors also can be overloaded.
The constructor without any parameter is called a default constructor.
0 How to add Comments in Java
In java, two kinds of commenting options are available, single line comments and multiline comments.
A single line comment in Java will start with //
A multi line comment starts with a /* and ends with a */
Single Line Comments in Java
Multi-Line Comments in Java
comment
in Java */
0 Primitive Data Types in Java
byte- 1 byte
short- 2 bytes
int- 4 bytes
long- 8 bytes
Floating Data Types in JAVA
float- 4 bytes
double- 8 bytes
Textual Data Types in JAVA
char- 2 bytes
The char data type in Java is 2 bytes because it uses UNICODE character set to support internationalization.
Logical Data Types in JAVA
boolean- 1 byte (true/false)
All numeric data types are signed
The size of data types remain the same on all platforms
UNICODE is a character set which covers all known scripts and language in the world.
Declaring and using primitive data types is Java similar to that of C.
int iCount;
int flag=100;
Unlike C, in Java variables can be declared anywhere in the program. and the best practice is Declare a variable in program only when required. Do not declare variables upfront like in C.
In Java, if a local variable is used without initializing it, the compiler will show an error.
06 October 2010
0 What is JVM-Java Virtual Machine?
JVM is platform dependent, Java Code is platform independent.
JVM is platform dependant; that is, there is one JVM for Windows, another one for UNIX, yet another one for Mac etc. All JVMs accept the same input, the byte code. Hence java code is platform independent- "write somewhere, run anywhere". Its JVM which interprets the byte code into the machine language format of the platform on which it is running.
The same byte code can be run on any platform, if the JVM for that platform is available.
The JVMs for all platforms are available free (http://java.sun.com/) and hence we say that the byte code runs in all platforms.
0 What is Java Compiler?
As you all know, the source code of Java will be stored in a text file with extension .java, the Java compiler compiles the .java file into byte code which will be in a file with extension .class
Byte Code is NOT in the machine language format of the hardware platform on which the code is compiled, that means the hardware processor cannot understand the byte code (Languages like C compiles the program into the machine language format of the hardware platform on which it is running). Instead, the byte code is in the machine language format of a machine known as the Java Virtual Machine or the JVM. That means you always need a JVM to execute the byte code.
JVM is not a real machine, it is just a virtual machine; implemented in software.
05 October 2010
0 What is UML(Unified Modeling Language)?
UML is mostly used by software engineers to communicate design.
In OO Design Pictures are easier to understand than textual explanation.
UML Class diagram is a technique to represent classes and their relationships pictorially.
Some notations in UML
- ‘+’ before a member (method or behavior) indicates ‘public’
- ‘-’ before a member (method or behavior) indicates ‘private’
0 What is Inheritance in Java OOP?
Inheritance is important as it supports the concept of hierarchical classification. Inheritance provides the idea of re-usability of code and each sub class defines only those features that are unique to it.
0 What is Polymorphism in Java OOP?
In Java, Polymorphism can be easily explained as the Method Overloading. In fact, Method Overloading is a way to achieve polymorphism.
Method Overloading the practice of using same method name to denote several different operations.
In the case of Method Overloading any number of functions can have the same name as long as they differ in any one of the following
- Type of arguments
- Number of arguments
0 What is Abstraction in Java OOP?
Consider the case of Stack, programmer need to know just how to invoke the push method and pop method to make the Stack object work. But internally, Stack can be implemented using an array or a linked list, programmer need not know this to use the Stack object.
Thus Abstraction is the process of exposing only the relevant details and ignoring (hiding) the irrelevant details (Don't get confused with "datahiding" of the "Encapsulation").
Abstraction simplifes the understanding and using of any complex system.
Another example, user does not have to understand the internal implementation of a software object to use it.
4 Difference between Class and object in Java?
Difference between Class and object in Java |
"Student" is a class. And "Jenna" is an object of the class "Student". And "John" is another object of the class "Student".
A Class is template for an object, a user-defined datatype that contains the variables and methods in it.
A class defines the abstract characteristics of a thing (object), including its characteristics (its attributes, fields or properties) and the thing's behaviors (the things it can do, or methods, operations or features).
That is, Class is a blue print used to create objects. In other words, each object is an instance of a class.
One class can have multiple number of instances. (There can be Number of instances of the class "Student", like "Jenna", "John" etc).
A class is a blue print, in which its mentioning what all variables it (it means an object of that class) will have, what all methods it will have.
0 What is Encapsulation in Java OOP
In an object-oriented concept, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:
- A mechanism for restricting access to some of the object's components (Access restriction to the variables of an object using the "private", "protected", "public" etc).
- A mechanism that facilitates the bundling of data with the methods(functions) operating on that data (Think about an object with some private variables and some public getter and setter methods).
The second definition is motivated by the fact that in many OOP languages hiding of components is not automatic or can be overridden; thus information hiding is defined as a separate notion by those who prefer the second definition.
Consider the case of Java, we can implement various levels of access restrictions using "private", "protected" or "public", So Encapsulation is always not about data hiding.
Encapsulation is the process of binding code and data together in the form of a capsule.
Java Example for Encapsulation
Consider a class Stack, the data could be stored in an array which will be private.
- The methods push and pop will be public.
- A program cannot access the array directly from outside the class.
- A program can access the array indirectly through the push and pop methods.
In OOP, code and data are merged into an object so that the user of an object can never peek inside the box. This is defined as encapsulation (i.e. Object is a capsule encapsulating data and behavior). All communication to it is through messages (i.e function calls which we use to communicate to the object). Messages define the interface to the object. Everything an object can do is represented by its message interface.
0 What is a Class in Java?
A Class is a software template that defines the methods and variables to be included in a particular kind of Object.
Examples - Automobiles, Bank Account, Customer
A class contains state and behavior.
State (Variables)
State is the variables defined inside the class.
State (Member Variables) will not be exposed to external world.
Behavior (Methods)
Behavior of a class is the methods (Functions) defined inside the class.
Behavior is exhibited by the class to external world.
Behavior of a class will be exposed to external world (Exposure can be controlled by access specifiers like private, protected, public etc).
An object is an instance of a class.
0 What are the Limitations of Structured Programming?
The entire problem was divided into a number of smaller units Functions or Procedures.
All these units need to work on a data item to produce the result.
The data need to be global,Global data makes the code complex.
As the code size grows, maintaining code becomes difficult, sometimes impossible.
0 What is Java?
Java is widely used for developing web applications, as it is open source.
Java is a platform independent language, that is "code it somewhere, run it anywhere".
Java was developed initially for consumer devices
But, now it is a popular platform to develop web based enterprise applications.
23 August 2010
0 JAVA installation and Set Up
Installation and Set Up of JAVA in Windows and UNIX machines
Before we begin JAVA installation, some points on JAVA installation• For executing Java Programs Java 2 SDK Version 1.4 or higher Version needs to be installed.
• Java 2 SDK Can be downloaded freely from http://java.sun.com
• IDEs for JAVA are Eclipse and Netbeans, and Eclipse can be downloaded freely and doesnot require installation
Setting Environment variables for Java
We need to set some Environmental variables.
• Environmental variable is a variable that describes the operating environment of the process
• Common environment variables describe the home directory, command search path etc.
Environment variables used by JVM
JAVA_HOME
This environment variable is pointing to the Java Installation directory. This environment variable is used to derive all other environment variables used by JVM
set JAVA_HOME=C:\ProgramFiles\JAVA\jdk1.4.3
In UNIX:
export JAVA_HOME=/var/usr/java
CLASSPATH
Path variable is used by OS to locate executable files
set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar
In UNIX:
set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.
Do the Environmental variable settings by typing the given commands in the Command Prompt and Type ‘javac’. It will display all the options of using javac as shown in the diagram. If it says bad command or file name then check the path setting.
Alternate way to set CLASSPATH
set PATH=%PATH%;%JAVA_HOME%\bin
In UNIX:
set PATH=$PATH:$JAVA_HOME/bin
0 How to set Environment variables for Java
How to set Environment variables for Java?
• Environmental variable is a variable that describes the operating environment of the process
• Common environment variables describe the home directory, command search path etc.
Environment variables used by JVM
JAVA_HOME
This environment variable is pointing to the Java Installation directory. This environment variable is used to derive all other environment variables used by JVM
set JAVA_HOME=C:\ProgramFiles\JAVA\jdk1.4.3
In UNIX:
export JAVA_HOME=/var/usr/java
CLASSPATH
Path variable is used by OS to locate executable files
set PATH=%PATH%;%JAVA_HOME%\lib\tools.jar
In UNIX:
set PATH=$PATH:$JAVA_HOME/lib/tools.jar:.
Do the Environmental variable settings by typing the given commands in the Command Prompt and Type ‘javac’. It will display all the options of using javac as shown in the diagram. If it says bad command or file name then check the path setting.
Alternate way to set CLASSPATH
set PATH=%PATH%;%JAVA_HOME%\bin
In UNIX:
set PATH=$PATH:$JAVA_HOME/bin
0 How to get data from session Java
How to Extract data from session in Java?
Get the session
Extract data from session
• If you cast to a generic type, use @SuppressWarnings
0 Challenges in Session Tracking Java
support for distributed Web applications
Load balancing used to send different requests to different machines. Sessions should still work even if different hosts are hit.support for persistent sessions
Session data written to disk and reloaded when server is restarted(as long as browser stays open).• Tomcat 5 supports this
22 August 2010
0 CRUD operations in MySQL Database
CRUD operations
CRUD is the acronym for Create, Read, Update and Delete. Create, Read, Update and Delete (CRUD) are the 4 basic functions of a Database or persistent storage. CRUD refers to all of the major functions that need to be implemented in a RDBMS.Each letter in the CRUD can be mapped to a standard SQL statement:
Read SELECT
Update UPDATE
Delete DELETE
CRUD operations in MySQL Database
Insert Data Into MySQL Database Table
The INSERT INTO statement is used to add new records to a database table.
Syntax
It is possible to write the INSERT INTO statement in two forms.
The first form doesn't specify the column names where the data will be inserted, only their values:
VALUES (value1, value2, value3,...)
The second form specifies both the column names and the values to be inserted:
VALUES (value1, value2, value3,...)
Select Data From MySQL Database Table
The SELECT statement is used to select data from a database.
Syntax
FROM table_name
Update Data In MySQL Database Table
The UPDATE statement is used to update existing records in a table.
Syntax
SET column1=value, column2=value2,...
WHERE some_column=some_value
Delete Data from MySQL Database Table
The DELETE FROM statement is used to delete records from a database table.
Syntax
WHERE some_column = some_value
20 June 2010
0 How to Remove navBar (Navigation Bar) from Blogger blog
Every blogspot blog by default recieves a Navigation Bar on the top, with buttons for switching to the next blog, searching yor blog and more. Some bloggers may find the Navigation Bar useful, But most of the bloggers may feel it irritating. If you feel that disabling the navigation bar would improve the layout of your blog then You may want to disable it.
Blogspot is not giving you any options for hiding or disabling the so called 'NavBar', there is no menu entry to disable it, But you can still hide it.
Disabling the Blogger NavBar: Detailed Steps
Dashboard--> Layout--> Edit HTMLIn the edit HTML text field, find the style defenitions( which is enclosed in { } brackets).Then paste the below given code somewhere near other style defenitions.
height:0px;
visibility:hidden;
display: none !important
}
In my personal experience this is a perfect hack. After these changes click on the save template button, reresh the page. If there is no navigation bar in the screen, then the Hack is perfect. Check out with all the leading browsers (atleast Internet explorer, Mozilla firefox, Safari and Google chrome).
Explanations
<style>...</style> encloses stylesheet instructions that define a page's layout. The actual layout instruction is now targeting the element of the ID navbar IFrame, which you define to not display. The !important tells the browser to override other layout defenitions for this element, if exists.Exceptions
If there is still the navigation bar exists(hopefully it won't happen), perhaps Google has since adjusted the way their page design displays the navigation bar. If so you may need to read the HTML source code of you blog and adjust your stylesheet instructions accordingly.Not For Newbies
The blogger navigation bar is also disabled when using FTP to transfer the blog pages to your own domain, because the navigation bar includes many elements that work only in the context of a blogger hosted blog.However,FTP publishing(Dashboard-->Settings-->Publishing) comes with its own set of disadvantages, so a move must be carefully planned.
Please make a note that in order to switch to FTP uploading , Your blog must be public and use a classic template.
You can set your blog to be public via Dashboard-->Settings-->Permission
You can set your template to classic via Dashboard-->Settings-->Edit HTML
18 June 2010
0 Session Tracking in Java Tutorial
• Sessions automatically associated with client via cookies or URL-rewriting
– Use request.getSession to get session
• Behind the scenes, the system looks at cookie or URL extra info and sees if it matches the key to some previously stored session object. If so, it returns that object. If not, it creates a new one, assigns a cookie or URL info as its key, and returns that new session object.
• Hashtable-like mechanism lets you store arbitrary objects inside session
– setAttribute stores values
– getAttribute retrieves values
• Access the session object
– Call request.getSession to get HttpSession object
• This is a hashtable associated with the user
• Look up information associated with a session.
– Call getAttribute on the HttpSession object, cast the return value to the appropriate type, and check whether the result is null.
• Store information in a session.
– Use setAttribute with a key and a value.
• Discard session data.
– Call removeAttribute discards a specific value.
– Call invalidate to discard an entire session
0 Disadvantages of Session Tracking using Hidden Form Fields
0 Session Tracking using Hidden Form Fields
Below given is the core idea of Session Tracking using Hidden Form Fields
Advantages of Session Tracking using Hidden Form Fields
Works even if cookies are disabled or unsupportedDisadvantages of Session Tracking using Hidden Form Fields
- Lots of tedious processing
- All pages must be the result of form submissions
0 Disadvantages of Session Tracking using URL Rewriting
0 Session Tracking using URL Rewriting in JAVA
The below given is the core idea of Session Tracking using URL Rewriting in JAVA
- Client appends some extra data on the end of each URL that identifies the session
- Server associates that identifier with data it has stored about that session
E.g. http://host/filePath/fileName.html;jsessionid=1234
Advantages of Session Tracking using URL Rewriting
Works even if cookies are disabled or unsupportedDisadvantages of Session Tracking using URL Rewriting
- Must encode all URLs that refer to your own site
- All pages must be dynamically generated
- Fails for bookmarks and links from other sites
1 What are HttpSession Methods in JAVA
getAttribute
– Extracts a previously stored value from a session object. Returns null if no value is associated with given name.setAttribute
– Associates a value with a name. Monitor changes: values implement HttpSessionBindingListener.removeAttribute
– Removes values associated with name.getAttributeNames
– Returns names of all attributes in the session.getId
– Returns the unique identifier.isNew
– Determines if session is new to client (not to page)getCreationTime
– Returns time at which session was first createdgetLastAccessedTime
– Returns time at which session was last sent from clientgetMaxInactiveInterval, setMaxInactiveInterval
– Gets or sets the amount of time session should go without access before being invalidatedinvalidate
– Invalidates current session0 What is the Importance of Session Tracking
- When clients at on-line store add item to their shopping cart, how does server know what’s already in cart?
- When clients decide to proceed to checkout, how can server determine which previously created cart is theirs?
- Cookies
- URL-Rewriting
- Hidden Form Fields
17 June 2010
0 What is CRUD Operations in Database
CRUD is the acronym for Create, Read, Update and Delete. Create, Read, Update and Delete (CRUD) are the 4 basic functions of a Database or persistent storage. CRUD refers to all of the major functions that need to be implemented in a RDBMS.
Each letter in the CRUD can be mapped to a standard SQL statement:
Read SELECT
Update UPDATE
Delete DELETE
0 Rails versus Java web frameworks
There are many other web application frameworks other than Rails. Apache Cocoon, Apache Struts, AppFuse, Google Web Toolkit, Grails, Hamlets, Spring Framework, Tapestry are frameworks just to name a few. This blog post compares Rails framework with these other Java frameworks.
Vastly reduced code footprint – Field results place productivity increases over modern Java methodologies (e.g., J2EE, Struts, etc.) in the 10-fold range.
Minimal configuration – Rails applications require a few lines of specification to identify each database connection you will use, as well as a line of configuration for each different type of routing you will use (typically 3-4 lines for an entire application). Both of these are necessary in any environment. By contrast, rather than the 20 or so lines required in a Railes application, typical medium-scale Java applications require thousands of lines of XML configuration, many of which are stronglycoupled across application layers.
IDE automation not required – Much of the productivity improvement in Java comes from the widespread use of tools to automate code writing and change. In comparison, Rails productivity improvement is based on the ease of programming it offers.
0 Ruby on Rails as an Agile Framework
Here we will discuss about the characteristics of Rails framework that make it most suitable for Agile methodologies.
Scaffolding – Most database backed Web applications must provide a user interface to do CRUD operations – Create, Read, Update, and Delete – for nearly every major table in the system. Building these user interfaces should be automated, not repeated. Rails eliminates some of the CRUD operation repetitions through scaffolding. With Rails, you can build a full scaffold application from scratch in just a few simple operations.
Convention over Configuration – A developer needs to specify only the unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called sales by default. It is only if one deviates from this convention, such as calling the table "products_sold", that one needs to write code regarding these specific deviations from conventions. Also the well formed set of conventions alleviates the need of detailed configuration files providing mapping between objects and tables etc.
Don't Repeat Yourself (DRY) – Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.
Portable programming skills – Managers will appreciate the fact that Rails minimizes configuration and encourages standardization. This feature enables programming skills to be more portable.
Rapid feedback loop – In Rails, you get nearly-instant feedback as you code. Hence results of the changes made can be immediately seen, improving the overall client experience. Changes can be made promptly as well.
Easy migration with vendor neutral implementation – Command pattern has been applied in Ruby to enable migrations using the ActiveRecord migration facility. Database schemas can be defined in a database-vendor neutral way.
Meta Programming – The most useful application of dynamic features, such as adding methods to objects, is meta programming. Such features allow developers to create a library that adapts to the environment. An example application of this is swapping proxies to easily change protocols from SOAP to XMLRPC.
2 Architecture of Ruby on Rails Framework
Architecture of Rails framework is illustrated in the above given figure.
Rails architecture consists of 2 major elements:
- Active Record
- Action Pack
Active Record is an Object Relational Mapping (ORM) layer, which handles the Model element of the MVC application. This layer exposes the data table rows as model objects to the rest of the application.
Action Pack handles the View and Controller elements of the MVC application. Action Pack consists of two parts viz. Action View and Action Controller which handle View and Controller of the MVC application respectively.
Each of the architectural element in the picture above is elaborated below:
User Component – Rails web applications are accessed by browsers using various protocol interfaces such as HTTP, ATOM, RSS or consumed as Web Services using SOAP.
Web Server – The developed Rails application resides on a Web Server, which handles requests from the user component and forwards them to the Dispatcher.
Dispatcher – Dispatcher invokes appropriate controller based on the current user request.
Controller – Controller processes the user request, and invokes appropriate action. The action collaborates with appropriate model objects and prepares the response. If the request was from a browser, the response will be rendered through Action View component. Else, an appropriate response is relayed by either the Action Webservices or the Action Mailer component.
16 June 2010
0 Overview of Ruby on Rails RoR
Ruby on Rails – the Framework
Ruby on Rails is an open source web application development and persistence framework that supports agile development and sustained productivity. It is a common observation that web application development using Rails framework is at least 10 times faster compared to other frameworks.
Rails framework was extracted from working applications that were written in Ruby. This means that Rails code base was practical, proven and well tested before it took shape as a framework.
Rails framework includes everything needed to create database backed web applications according to the Model-View-Control (MVC) pattern of separation.
This pattern splits the view (also called the presentation) into "dumb" templates that are primarily responsible for inserting pre-built data in between HTML tags.
The model contains the "smart" domain objects (such as Account, Product, Person, Post) that hold all the business logic and know how to persist themselves to a database.
The controller handles the incoming requests (such as Save New Account, Update Product, Show Post) by manipulating the model and directing data to the view.
Following are the typical set of tasks that one needs to perform to build a bare bones database backed web application using Rails:
- Create a new Rails project using the utility script provided as part of the framework. Doing this creates a directory structure for the new project which is common across all the Rails projects.
- Create necessary database with associated tables. Each of these tables maps to a model class.
- Generate a scaffold specifying the model and controller names to the scaffolding utility. This step needs to be repeated for all the different models that are needed for the project.
The above process generates views for CRUD (Create, Read, Update and Delete) and list actions, wired to corresponding controller classes. Data fields associated with these actions are automatically picked up from the database tables created in the previous step. - A barebones application that can show the core application data with capability to add, modify, view and delete is now ready!
Over and above the barebones application created above, sophistications can be added easily. Each of these additional sophistications is also a piece of cake if we follow the conventions of Rails framework. For example, the table name associated with each model class name follows a convention that the table name will be a plural of the model class name. Such conventions over configurations make the amount of code very less, and hence make the amount of work to be done by the programmer very less, eventually resulting in increased productivity. Another principle followed in Rails paradigm is called DRY (Don’t Repeat Yourself) that aims at eliminating code redundancy.
Rails framework has the following salient features:
- User friendly
- Agile
- Rapid prototyping capability
- Built in testing capabilities
- Easy to maintain
- Scalable
- On par performance with other frameworks
- Support for Webservices
- Support for emails
- Support for AJAX
- Support for development , testing and production environments
0 Features and Advantages of Rails Framework
Rails framework has the following salient features:
- User friendly
- Agile
- Rapid prototyping capability
- Built in testing capabilities
- Easy to maintain
- Scalable
- On par performance with other frameworks
- Support for Webservices
- Support for emails
- Support for AJAX
- Support for development , testing and production environments
1 Features of Ruby on Rails RoR
Ruby – the programming language
Ruby is an object oriented language that is interpreted. It has syntax similar to Perl and semantics similar to Smalltalk. Ruby itself was developed in C. Rails web application framework is developed on Ruby.
Salient features of Ruby language are:
- Pure OOP
- Support for Reflection – can query Ruby objects about themselves
- Duck Typing – Ruby “ducks” the issue of typing, letting the type of a variable be determined by its value.
0 DRY in Ruby On Rails- Don't Repeat Yourself
DRY- Don't Repeat Yourself is the principle of Ruby On Rails (RoR). Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.
- Reusing data
e.g. no need to declare table field names – can be read from database - Metaprogramming
dynamically created methods - Less code – more work on each line of code
e.g. specific keywords like find_all to query database
15 June 2010
0 What is DRY- Don't Repeat Yourself
DRY- Don't Repeat Yourself is the principle of Ruby On Rails (RoR). Information is located in a single, unambiguous place. DRY principle means that settings only need to be specified in one place. Rails ensures that these definitions are visible to all the other web components that need them. For example, the developer does not need to specify database column names in class definitions. Instead, Ruby can retrieve this information from the database.
- Reusing data
e.g. no need to declare table field names – can be read from database - Metaprogramming
dynamically created methods - Less code – more work on each line of code
e.g. specific keywords like find_all to query database
1 Advantages of Ruby On Rails - RoR
The following are the advantages of Ruby On Rails (RoR).
- Less code by avoiding redundancy and following Rails conventions.
- Increased productivity and, ideally, decreased development times.
- Rails is written in Ruby – Ruby is a very easy to understand and work.
- Extensive standard library.
- Easily ported among Linux, Windows and Macintosh environments.
- Well suited for Agile development.
- Growing Ruby On Rails users community (Mailing list, Wiki, IRC & bug tracking)
0 Disadvantages of Ruby On Rails -Rails ver. 1.2
0 What is RoR or Ruby on Rails ?
Ruby on Rails - often called RoR, or just Rails, is an open source web application development framework. It was written using Ruby programming language. The web applications developed using this framework closely follow the Model-View-Controller (MVC) architecture. Rails framework strives for simplicity and allows real-world applications to be developed in less amount of code compared to other frameworks and with a minimum of configuration. It aims at increasing the speed and ease with which database-driven web applications can be created. Skeleton code frameworks (scaffolds) can be created in a jiffy.
- Ruby is an Object-Oriented programming language.
- Rails is an open source Ruby framework for developing database-driven web applications.
- Ruby on Rails (RoR) is open source web application framework written in the Ruby programming language and using the Rails framework with MVC design pattern.
- It aims to increase the speed and ease with which database-driven web sites can be created and offers skeleton code frameworks.
- Emphasis is on simplicity and elegance.
- RoR principles include Don't repeat yourself (DRY) and Convention over Configuration.
- Focus on developer productivity and getting the job done – fast!
Ruby – the programming language
Ruby is an object oriented language that is interpreted. It has syntax similar to Perl and semantics similar to Smalltalk. Ruby itself was developed in C. Rails web application framework is developed on Ruby.
References:http://www.rubyonrail.org
0 JAVA- A Comparison between Static Polymorphism and Dynamic Polymorphism
Static Polymorphism And Dynamic Polymorphism in JAVA
Static Polymorphism in JAVA is also known as Function Overloading in JAVA. Dynamic Polymorphism in JAVA is also known as Function Overriding in JAVA. Let us compare Function Overloading and Function Overriding in JAVA. Here it goes,the difference between Function Overloading and Function Overriding in JAVA
Static Polymorphism | Dynamic Polymorphism |
Function Overloading – within same class more than one method having same name but differing in signature | Function Overriding – keeping the signature and return type same, method in the base class is redefined in the derived class |
Resolved during compilation time | Resolved during run time |
Return type is not part of method signature | Which method to be invoked is decided by the object that the reference points to and not by the type of the reference |
0 Compare Static Polymorphism and Dynamic Polymorphism in JAVA
Static Polymorphism And Dynamic Polymorphism in JAVA
Static Polymorphism in JAVA is also known as Function Overloading in JAVA. Dynamic Polymorphism in JAVA is also known as Function Overriding in JAVA. Let us compare Function Overloading and Function Overriding in JAVA. Here it goes,the difference between Function Overloading and Function Overriding in JAVA
Static Polymorphism | Dynamic Polymorphism |
Function Overloading – within same class more than one method having same name but differing in signature | Function Overriding – keeping the signature and return type same, method in the base class is redefined in the derived class |
Resolved during compilation time | Resolved during run time |
Return type is not part of method signature | Which method to be invoked is decided by the object that the reference points to and not by the type of the reference |
0 How to make a field auto incremental in DB2 ?
14 June 2010
3 DB Migration from Oracle 8.0.5 to Oracle 10g
What is the easiest method to do this, will export taken in Oracle 8.0.5 work with import of Oracle 10g. Is there any other easy way?
There are verious ways to migrate data from Oracle 8.0.5 to Oracle 10.2.*. Details are mentioned below,
Using Export/ Import:
1. Export Full Oralce 8.0.5 database using 8.0.5 EXP utility.
2. Take a cold backup of 8.0.5 database.
3. Apply Oracle 10g related operating system patches to server.
4. Install Oracle 10g Software.
5. Create Oracle 10g instance.
6. Create DATA and INDEX tablespaces with same name as Oracle 8.0.5 database.
7. Import Full database in new Oralce 10g instance using 10.2.* IMP utility.
8. Recompile all invalid objects.
Using File System:
1. Take a cold backup of 8.0.5 database
2. Apply Oracle 10g related operating system patches to server.
3. Install Oracle 10g Software.
4. Create Oracle 10g instance.
5. Detach file system of Oracle 8.0.5 database and attach it to new Oracle 10g database.
6. Run database upgrade scripts manually on the new 10g database.
7. Recompile all inavalid objects.
You can also use Oracle Database Upgrade Assistance tool. This is a GUI based tool provided by oracle for upgrading database to higher version.