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
void print(int i){
System.out.println(i);
}
void print(double d){
System.out.println(d);
}
void print(char c){
System.out.println(c);
}
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, int b)
void add (int a, float b)
void add (float a, int b)
void add (int a, int b, float c)
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.
void print(int i){
System.out.println(i);
}
int print(int i)){
System.out.println(i);
return i;
}
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 class Student{
public Student(){
mark = 100;
}
public Student(int rollNo, double mark){
this.rollNo = rollNo;
this.mark = mark;
}
}
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".
Student student = new Student();
All the public members of the object can be accessed with the help of the reference.
Student student = new Student();
student.setRollNo(20);
System.out.println(student.getRollNo());
The reference can be treated as the name of an object.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
new Student()
The above statement returns a reference to the newly created object. Creation of objects and arrays are very similar in Java.The following statement creates a reference to the class "Student".
Student student;
The reference "student" can be used for referring to any object of type "Student".//Declare a reference to class "Student"
Student student;
//Create a new Student object
//Make student refer to the new object
Student student = new 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.
int [][] x;
//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 */
//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[];
int [] x;
int [] x;
The reference x can be used for referring to any int array.
//Declare a reference to an int array
int [] x;
//Create a new int array and make x refer to it
x = new int[5];
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
int [] x = new int[5];
In simple terms, reference can be seen as the name of the array. Arrays can be created only using dynamic memory allocation in Java. The memory is allocated dynamically using the keyword new.A reference type can be assigned ‘null’ to show that it is not referring to any object. ‘null’ is a keyword in Java
int [] x = null;
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.
new int[5]
The above statement returns a reference to the newly created array. References in Java are very similar to pointers in C
Initializing an array in Java
An array can be initialized while it is created as followsint [] x = {1, 2, 3, 4};
char [] c = {‘a’, ‘b’, ‘c’};
char [] c = {‘a’, ‘b’, ‘c’};
The length of an array
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
for(int i = 0; i < x.length; ++i){ x[i] = 5; }
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
int i = 10;
double d;
d = i;
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.
double d = 10;
int i;
i = (int) d;
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 flag;
int maxCount=100;
int maxCount=100;
Unlike C, in Java, variables can be declared anywhere in the program.
int index = 10;
System.out.println(“Program starts here”);
int j = 20;
for (int index=0; index <maxCount; index++) {
int z = index * 10;
}
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.
Local Variables in Java
In Java, if a local variable is used without initializing it, the compiler will show an errorclass Sample{
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}
public static void main (String [] args){
int count;
System.out.println(count);//This will give Error
}
}
Instance variables
Instance variables are declared in a class, but outside a method. They are also called member or field variables. When an object is allocated in the heap, there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed. Visible in all methods and constructors of the defining class, should generally be declared private, but may be given greater visibility.Class/static variables
Class/static variables are declared with the static keyword in a class, but outside a method. There is only one copy per class, regardless of how many objects are created from it. They are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.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[];
int [] x;
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.
Why Requirements Engineering?
40 - 60 percent of known defects found in a project are errors made during requirements stage. Many software development organizations struggle to gather, document, and manage their product requirements. Most of the surveys done indicates that, incomplete and changing requirements with lack of user input and their involvement, are the major reasons why IT projects fail to deliver on schedule, within budget.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.
Cookie Constructor of Servlet Cookie API
Cookie(java.lang.String name, java.lang.String value) - Constructs a cookie with a specified name and value.Methods of Servlet Cookie API
- 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)
API to add cookie in the Responce header
HttpServletResponseMethod:- void addCookie(Cookie cookie)
API to Read cookie from the client
HttpServletRequestMethod:- 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,Cookies in Java
The class Cookie in the package javax.servlet.http can be used to create a cookie. This java class Cookie has a constructor that takes two string objects as parameters- name and value.Cookie as a Session tracking Mechanism
Session tracking through HTTP cookies is the most used session tracking mechanism and is required to be supported by all servlet containers. The servlet container sends a cookie to the client. The client will then return the cookie on each subsequent request to the server unambiguously associating the request with a session. The name of the session tracking cookie must be JSESSIONID.Cookie is a threat to privacy?
A cookie is an object that a server creates and places on the client when the client connects to it. A cookie contains state information. Cookies are valuable for tracking user activities. For example, assume that a user visits an online bookstore. A cookie can save the recent item you visited on that site and other information. So, each time he or she visits the online bookstore, it will be displaying recent item you have visited.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
Advantages of Cookies
- 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
Disadvantages of Cookies
- 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
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.
Importance of Session Tracking
Consider a client browser downloads a page from a server, and then subsequently clicks on a hyperlink on the page to connect to another related page as part of the workflow of an application. In this case, the server has no way of knowing that it is the same client who now wants to access another related page as part of the work-flow of the same application. User-specific data on the first page is something that the server will not be able to relate to the subsequent page, because as far as the server is concerned, it is a fresh hit even though the same user or client has made a hit to another subsequent page as part of the workflow of the application. The server is therefore, not able to maintain state (user or client specific data between accesses by the same client to different pages of an application.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.
Services provided by 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?
The following are the 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.
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.
Responsibilities of JEE containers
- 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)
Various JEE Components
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 component of JEE architecture
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 component of JEE architecture
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 component of JEE architecture
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
Advantages of Session Tracking by Url Rewriting
- 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.
Disadvantages of Session Tracking by Url Rewriting.
- 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
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.
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
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
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
// This is a single line comment in Java
Multi-Line Comments in Java
/* This is a multi line
comment
in Java */
comment
in Java */
0 Primitive Data Types in Java
Integer 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.
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?
A virtual machine which will execute java byte code (.class file) is called Java Virtual Machine or the JVM. In other words, the compiled java code -the java byte code (.class file) is in the machine language format of a machine known as the Java Virtual Machine or the JVM. We always needs a JVM to execute the byte code. JVM is not a real machine, it is just a virtual machine; implemented in software.
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.
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?
The java compiler is the program which compiles a .java file into byte code (.class files).
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.
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)?
Unified Modeling Language (UML) is a set of diagrams which pictorially represent object oriented design.
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
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 the feature by which one class can acquires the properties and functionality of another class.
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.
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?
Polymorphism is a feature that allows one interface to be used for a general class of actions. An operation may exhibit different behavior in different instances. The behavior depends on the types of data used in the operation. It plays an important role in allowing objects having different internal structures to share the same external interface.
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
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?
The one who is driving a car need not know how the car engine works.
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.
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
The Encapsulation, an object-oriented concept can be correlated with either data hiding or data bundling.
In an object-oriented concept, encapsulation is used to refer to one of two related but distinct notions, and sometimes to the combination thereof:
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.
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.
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 blue print used to create objects.
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.
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?
In structured programming, focus is on the algorithm and importance is given to the procedure (logic) and not to the data on which these procedures operate.
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.
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 a very powerful Object Oriented programming language developed by Sun Micro systems.
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.
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.
Subscribe to:
Posts (Atom)