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();
}

}
}

Posted by Unknown on 1:39 AM
Labels:

The default behaviour of an object’s clone() method automatically yields a shallow copy. So to achieve a deep copy the classes must be edited or adjusted.

Shallow copy: If a shallow copy is performed on obj-1 then it is copied but its contained objects are not. The contained objects Obj-1 and Obj-2 are affected by changes to cloned Obj-2. Java supports shallow cloning of objects by default when a class implements the java.lang.Cloneable interface.




Deep copy: If a deep copy is performed on obj-1 then not only obj-1 has been copied but the objects contained within it have been copied as well. Serialization can be used to achieve deep cloning. Deep cloning through serialization is faster to develop and easier to maintain but carries a performance overhead.




class A {
int l = 1;
}

class B extends A implements Cloneable {
int m = 2;
}

class CloneDemo4 extends B {
int n = 3;
A a = new A();

public static void main(String[] args) throws CloneNotSupportedException {
CloneDemo4 c = new CloneDemo4();
CloneDemo4 c2 = (CloneDemo4) c.clone();

System.out.println(c.l);
System.out.println(c2.l);
System.out.println(c.m);
System.out.println(c2.m);
System.out.println(c.n);
System.out.println(c2.n);

System.out.println(c.a == c2.a);
}

protected Object clone() throws CloneNotSupportedException {
// First, perform a shallow copy.

CloneDemo4 temp = (CloneDemo4) super.clone();

if (a != null)
temp.a = new A();

return temp;
}
}

Posted by Unknown on 1:09 AM
Labels:

Other languages use pass-by-reference or pass-by-pointer. But in Java no matter what type of argument you pass the corresponding parameter (primitive variable or object reference) will get a copy of that data, which is exactly how pass-by-value (i.e. copy-by-value) works.


In Java, if a calling method passes a reference of an object as an argument to the called method then the passed-in reference gets copied first and then passed to the called method. Both the original reference that was passed-in and the copied reference will be pointing to the same object. So no matter which reference you use, you will be always modifying the same original object, which is how the pass-by-reference works as well.


If call involves inter-process (e.g. between two JVMs) communication, then the reference of the calling method has a different address space to the called method sitting in a separate process (i.e. separate JVM). Hence inter-process communication involves calling method passing objects as arguments to called method by-value in a serialized form, which can adversely affect performance due to marshalling and unmarshalling cost.

P.S: If image is not visible, open this in new window.


Posted by Unknown on 11:24 PM
Labels:

Polymorphism – means the ability of a single variable of a given type to be used to reference objects of different types, and automatically call the method that is specific to the type of object the variable references. In a nutshell, polymorphism is a bottom-up method call. The benefit of polymorphism is that it is very easy to add new classes of derived objects without breaking the calling code (i.e. getTotArea() in the sample code shown below) that uses the polymorphic classes or interfaces. When you send a message to an object even though you don’t know what specific type it is, and the right thing happens, that’s called polymorphism. The process used by object-
oriented programming languages to implement polymorphism is called dynamic binding.
Let us look at some sample code to demonstrate polymorphism

Inheritance – is the inclusion of behavior (i.e. methods) and state (i.e. variables) of a base class in a derived class so that they are accessible in that derived class. The key benefit of Inheritance is that it provides the formal mechanism for code reuse. Any shared piece of business logic can be moved from the derived class into the base class as part of re factoring process to improve maintainability of your code by avoiding code duplication. The existing class is called the superclass and the derived class is called the subclass. Inheritance can also be defined as the process whereby one object acquires characteristics from one or more other objects the same way children acquire characteristics from their parents.

There are two types of inheritances:
1. Implementation inheritance (Class inheritance): You can extend an applications’ functionality by reusing functionality in the parent class by inheriting all or some of the operations already implemented. In Java, you can only inherit from one superclass. Implementation inheritance promotes reusability but improper use of class inheritance can cause programming nightmares by breaking encapsulation and making future changes a problem. With implementation inheritance, the subclass becomes tightly coupled with the superclass. This will make the design fragile because if you want to change the superclass, you must know all the details of the subclasses to avoid breaking them. So when using implementation inheritance, make sure that the subclasses depend only on the behavior of the superclass, not on the actual implementation. For example in the above diagram the subclasses should only be concerned about the behavior known as area() but not how it is implemented.

2. Interface inheritance (Type inheritance): This is also known as subtyping. Interfaces provide a mechanism for specifying a relationship between otherwise unrelated classes, typically by specifying a set of common methods each implementing class must contain. Interface inheritance promotes the design concept of program to interfaces not to implementations. This also reduces the coupling or implementation dependencies between systems. In Java, you can implement any number of interfaces. This is more flexible than implementation inheritance because it won’t lock you into specific implementations which make subclasses difficult to maintain. So care should be taken not to break the implementing classes by modifying the interfaces.


Encapsulation – refers to keeping all the related members (variables and methods) together in an object. Specifying members as private can hide the variables and methods. Objects should hide their inner workings from the outside view. Good encapsulation improves code modularity by preventing objects interacting with each other in an unexpected way, which in turn makes future development and re factoring efforts easy. Being able to encapsulate members of a class is important for security and integrity. We can protect variables from unacceptable values. The sample code below describes how encapsulation can be used to protect the MyMarks object from having negative values. Any modification to member variable “vmarks” can only be carried out through the setter method setMarks(int mark). This prevents the object “MyMarks” from having any negative values by throwing an exception.
Sample code:
Class MyMarks {
private int vmarks = 0;
private String name;
public void setMarks(int mark)
throws MarkException {
if(mark > 0)
this.vmarks = mark;
else {
throw new MarkException("No negative Values");
}
}
public int getMarks(){
return vmarks;
}
//getters and setters for attribute name goes here.
}

Posted by Unknown on 9:51 AM
Labels:

Class loaders are hierarchical. Classes are introduced into the JVM as they are referenced by name in a class that is already running in the JVM. So how is the very first class loaded? The very first class is specially loaded with the help of static main() method declared in your class. All the subsequently loaded classes are loaded by the classes, which are already loaded and running. A class loader creates a namespace. All JVMs include at least one class loader that is embedded within the JVM called the primordial (or bootstrap) class loader. Now let’s look at non-primordial class loaders. The JVM has hooks in it to allow user defined class loaders to be used in place of primordial class loader. Let us look at the class loaders created by the JVM.

Bootstrap : JDK internal classes, java.* packages.
Extensions : jar files from JDK extensions directory
System : classes from system classpath.


Classes loaded by Bootstrap class loader have no visibility into classes loaded by its descendants (i.e Extensions and Systems class loaders).

The classes loaded by system class loader have visibility into classes loaded by its parents (i.e Extensions and Bootstrap class loaders).

If there were any sibling class loaders they cannot see classes loaded by each other. They can only see the classes loaded by their parent class loader.

Class loaders are hierarchical and use a delegation model when loading a class. Class loaders request their parent to load the class first before attempting to load it themselves. When a class loader loads a class, the child class loaders in the hierarchy will never reload the class again. Hence uniqueness is maintained. Classes loaded by a child class loader have visibility into classes loaded by its parents up the hierarchy but the reverse is not true.Two objects loaded by different class loaders are never equal even if they carry the same values, which mean a class is uniquely identified in the context of the associated class loader.

Dynamic class loading :
Dynamic loading is a technique for programmatically invoking the functions of a class loader at run time.
Class.forName (String className); //static method which returns a Class

static method returns the class object associated with the class name. The string className can be supplied dynamically at run time. Unlike the static loading, the dynamic loading will decide whether to load the class House at runtime based on a properties file and/or other runtime conditions. Once the class is dynamically loaded the following method returns aninstance of the loaded class. It’s just like creating a class object with no arguments.

class.newInstance (); //A non-static method, which creates an instance of a class (i.e. creates an object).

House myHouse = null ;
//myClassName should be read from a properties file or Constants interface.
String myClassName = "com.hiren.House" ;
Class houseClass = Class.forName(myClassName) ;
myHouse = (House) houseClass.newInstance();
myHouse.setArea(5000);

Posted by Unknown on 3:37 PM
Labels:


  • Runnable — waiting for its turn to be picked for execution by the thread schedular based on thread priorities.
  • Running: The processor is actively executing the thread code. It runs until it becomes blocked, or voluntarily
  • gives up its turn with this static method Thread.yield(). Because of context switching overhead, yield() should not be used very frequently.
  • Waiting: A thread is in a blocked state while it waits for some external processing such as file I/O to finish.
  • Sleeping: Java threads are forcibly put to sleep (suspended) with this overloaded method: Thread.sleep(milliseconds), Thread.sleep(milliseconds, nanoseconds);
  • Blocked on I/O: Will move to runnable after I/O condition like reading bytes of data etc changes.
  • Blocked on synchronization: Will move to Runnable when a lock is acquired.
  • Dead: The thread is finished working.
When a task invokes yield(), it changes from running state to runnable state. When a task invokes sleep(), it changes from running state to waiting/sleeping state.
Creation of Thread:

Threads can be used by either :
  • Extending the Thread class
  • Implementing the Runnable interface.
class Counter extends Thread {

//method where the thread execution will start
public void run(){
//logic to execute in a thread
}

//let’s see how to start the threads
public static void main(String[] args){
Thread t1 = new Counter();
Thread t2 = new Counter();
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd
thread. This calls the run() method
}
}
class Counter extends Base implements Runnable {

//method where the thread execution will start
public void run(){
//logic to execute in a thread
}

//let us see how to start the threads
public static void main(String[] args){
Thread t1 = new Thread(new Counter());
Thread t2 = new Thread(new Counter());
t1.start(); //start the first thread. This calls the run() method
t2.start(); //this starts the 2nd
thread. This calls the run() method
}
}

The runnable interface is preferred, as it does not require your object to inherit a thread because when you need multiple inheritance, only interfaces can help you. In the above example we had to extend the Base class so implementing runnable interface is an obvious choice. Also note how the threads are started in each of the different cases as shown in the code sample.

Daemon threads :
Daemon threads are sometimes called "service" threads that normally run at a low priority and provide a basic service to a program or programs when activity on a machine is reduced. An example of a daemon thread that is continuously running is the garbage collector thread. This thread, provided by the JVM, will scan programs for variables that will never be accessed again and free up their resources back to the system. A thread can set the daemon flag by passing a true boolean value to the setDaemon() method. If a false boolean value is passed, the thread will become a user thread. However, this must occur before the thread has been started.

Scheduling :
Java has a Thread Scheduler that monitors all running threads in all programs and decides which threads should be running and which are in line to be executed. There are two characteristics of a thread that the scheduler identifies in its decision process. One, the most important, is the priority of the thread, the other is the daemon flag. The scheduler's basic rule is if there are only daemon threads running, the Java Virtual Machine (JVM) will exit. New threads inherit the priority and daemon flag from the thread that created it. The scheduler determines which thread should be executed by analyzing the priorities of all threads. Those with the highest priority are allowed execution before any lower priority threads.
The scheduler can be of two flavors, preemptive or non-preemptive. Preemptive schedulers give a certain time-slice to all threads running on the system. The scheduler decides which thread is next to run and resume() that thread for some constant period of time. When the thread has executed for that time period it will be suspended() and the next thread scheduled will be resumed(). Non-preemptive schedulers decide which thread should run and run it until the thread is complete. The thread has full control of the system for as long as it likes. The yield() method is a way for a thread to force the scheduler to start executing another waiting thread. Depending on the system Java is running on, the scheduler can be either preemptive or non-preemptive.