Posted by Unknown on 5:27 PM
Labels:

Accessing Static Methods and Variables:

Since you don't need to have an instance in order to invoke a static method or access a static variable, then how do you invoke or use a static member? What's the syntax? We know that with a regular old instance method, you use the dot operator
on a reference to an instance:

class Frog {

int frogSize = 0;

public int getFrogSize() {

return frogSize;

}

public Frog(int s) {

frogSize = s;

}

public static void main (String [] args) {

Frog f = new Frog(25);

System.out.println(f.getFrogSize()); // Access instance

// method using f

}

}

In the preceding code, we instantiate a Frog, assign it to the reference variable f, and then use that f reference to invoke a method on the Frog instance we just created. In other words, the getFrogSize() method is being invoked on a specific Frog object on the heap. But this approach (using a reference to an object) isn't appropriate for accessing a static method, because there might not be any instances of the class at all! So, the way we access a static method (or static variable) is to use the dot operator on the class name, as opposed to using it on a reference to an instance, as follows:

class Frog {

static int frogCount = 0; // Declare and initialize

// static variable

public Frog() {

frogCount += 1; // Modify the value in the constructor

}

}

class TestFrog {

public static void main (String [] args) {

new Frog();

new Frog();

new Frog();

System.out.print("frogCount:"+Frog.frogCount); //Access

// static variable

}

}

But just to make it really confusing, the Java language also allows you to use an object reference variable to access a static member:

Frog f = new Frog();

int frogs = f.frogCount; // Access static variable

// FrogCount using f


In the preceding code, we instantiate a Frog, assign the new Frog object to the reference variable f, and then use the f reference to invoke a static method! But even though we are using a specific Frog instance to access the static method, the rules haven't changed. This is merely a syntax trick to let you use an object reference variable (but not the object it refers to) to get to a static method or variable, but the static member is still unaware of the particular instance used to invoke the static member. In the Frog example, the compiler knows that the reference variable f is of type Frog, and so the Frog class static method is run with no awareness or concern for the Frog instance at the other end of the f reference. In other words, the compiler cares only that reference variable f is declared as type Frog.

Posted by Unknown on 5:17 PM
Labels:

Static Variables and Methods:

The static modifier has such a profound impact on the behavior of a method or variable that we're treating it as a concept entirely separate from the other modifiers. To understand the way a static member works, we'll look first at a reason for using one. Imagine you've got a utility class with a method that always runs the same way; its sole function is to return, say, a random number. It wouldn't matter which instance of the class performed the method—it would always behave exactly the same way. In other words, the method's behavior has no dependency on the state (instance variable values) of an object. So why, then, do you need an object when the method will never be instance-specific? Why not just ask the class itself to run the method?
Let's imagine another scenario: Suppose you want to keep a running count of all instances instantiated from a particular class. Where do you actually keep that variable? It won't work to keep it as an instance variable within the class whose instances you're tracking, because the count will just be initialized back to a default value with each new instance. The answer to both the utility-method-always-runs-the-same scenario and the keep-a-running-total-of-instances scenario is to use the static modifier. Variables and methods marked static belong to the class, rather than to any particular instance. In fact, you can use a static method or variable without having any instances of that class at all. You need only have the class available to be able to invoke a static method or access a static variable. static variables, too, can be accessed without having an instance of a class. But if there are instances, a static variable of a class will be shared by all instances of that class; there is only one copy.
The following code declares and uses a static counter variable:

class Frog {
static int frogCount = 0; // Declare and initialize
// static variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println("Frog count is now " + frogCount);
}
}
In the preceding code, the static frogCount variable is set to zero when the Frog class is first loaded by the JVM, before any Frog instances are created! (By the way, you don't actually need to initialize a static variable to zero; static variables get the same default values instance variables get.) Whenever a Frog instance is created, the Frog constructor runs and increments the static frogCount variable. When this code executes, three Frog instances are created in main(), and the result is Frog count is now 3
Now imagine what would happen if frogCount were an instance variable (in other words, nonstatic):
class Frog {
int frogCount = 0; // Declare and initialize
// instance variable
public Frog() {
frogCount += 1; // Modify the value in the constructor
}
public static void main (String [] args) {
new Frog();
new Frog();
new Frog();
System.out.println("Frog count is now " + frogCount);
}
}
When this code executes, it should still create three Frog instances in main(),
but the result is...a compiler error! We can't get this code to compile, let alone run.

The JVM doesn't know which Frog object's frogCount you're trying to access. The problem is that main() is itself a static method, and thus isn't running against any particular instance of the class, rather just on the class itself. A static method can't access a nonstatic (instance) variable, because there is no instance! That's not to say there aren't instances of the class alive on the heap, but rather that even if there are, the static method doesn't know anything about them. The same applies to instance methods; a static method can't directly invoke a nonstatic method. Think static = class, nonstatic = instance. Making the method called by the JVM (main()) a static method means the JVM doesn't have to create an instance of your class just to start running code.

Posted by Unknown on 2:27 PM
Labels:

Viewing html source of a page running on the server:
You can view complete html code of a page running on the server with the help of Java.
This section provides you the complete code of the above program. This program takes a url starting from “http://” otherwise it sends an error message indicating invalid url. In the program, HttpURLConnection is the abstract class of the java.net package. This class extends the URLConnection class of the java.net package and facilitates all same facilities of the URLConnection class with the specific HTTP features specially. getResponseCode() method of the HttpURLConnection class returns an integer value which is the code for the status from the http response message. getResponseMethod() method of the HttpURLConnection class shows the message with the http response code from the server. getHeaderFieldKey(int j) method returns the key for the given jth header field.

import java.io.*;
import java.net.*;

public class ViewSource{
public static void main (String[] args) throws IOException{
System.out.print("Enter url to view html source code: ");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String url = br.readLine();
try{
URL u = new URL(url);
HttpURLConnection uc = (HttpURLConnection) u.openConnection();
int code = uc.getResponseCode();
String response = uc.getResponseMessage();
System.out.println("HTTP/1.x " + code + " " + response);
for(int j = 1; ; j++){
String header = uc.getHeaderField(j);
String key = uc.getHeaderFieldKey(j);
if(header == null || key == null)
break;
System.out.println(uc.getHeaderFieldKey(j) + ": " + header);
}
InputStream in = new BufferedInputStream(uc.getInputStream());
Reader r = new InputStreamReader(in);
int c;
while((c = r.read()) != -1){
System.out.print((char)c);
}
}
catch(MalformedURLException ex){
System.err.println(url + " is not a valid URL.");
}
catch(IOException ie){
System.out.println("Input/Output Error: " + ie.getMessage());
}
}
}

Posted by Unknown on 2:08 PM
Labels:

Send data from database in PDF file as servlet response:
This example retrieves data from MySQL and sends response to the web browser in the form of a PDF document using Servlet. This program uses iText, which is a java library containing classes to generate documents in PDF, XML, HTML, and RTF. For this you need to place iText.jar file to lib folder of your JDK and set classpath for it. You can download this jar file from the link http:// www.lowagie.com/iText/download.html The program below will embed data retrieved from database in PDF document.

import java.io.*;
import java.util.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.lowagie.text.*;
import com.lowagie.text.pdf.*;

public class ShowPdf extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
res.setContentType("application/pdf");
//Create a document-object
Document document = new Document();
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");

java.util.List list = new ArrayList();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select * from employee");
while(rs.next()){
String id = rs.getString("empId");
String add = rs.getString("empAdd");
list.add(id+" "+add);
}
// Create a PDF document writer
PdfWriter.getInstance(document, res.getOutputStream());
document.open();
// Create paragraph
Paragraph paragraph = new Paragraph("Data from database:");
// Add paragraph to the document
document.add(paragraph);

com.lowagie.text.List list1=new com.lowagie.text.List(true);
Iterator i = list.iterator();
while(i.hasNext()){
list1.add(new ListItem((String)i.next()));
}
// Add list of data retrieved from database to the document
document.add(list1);
document.close();
}
catch (Exception e) {
e.printStackTrace();
// Close the document
document.close();
}

}
}