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
Subscribe to:
Posts (Atom)