Thursday, December 8, 2011
Java Crazy: Sleep() and Wait()
Java Crazy: Sleep() and Wait(): Difference between sleep() and wait() ? 1) wait() is a method of Object class. sleep() is a method of Thread class. 2) sleep() allows the ...
Java Crazy: Threads Example
Java Crazy: Threads Example: This programme checks the numbers between 0 to 100 and prints the numbers that are not divisible by 10 with a sleeping period of 500 millis...
Java Crazy: Structure of HttpRequest and HttpResponse
Java Crazy: Structure of HttpRequest and HttpResponse: The HttpRequest contains the following things. 1. Request Line ---- It will provide the information about the type of method called, the...
Java Crazy: Structure of HttpRequest and HttpResponse
Java Crazy: Structure of HttpRequest and HttpResponse: The HttpRequest contains the following things. 1. Request Line ---- It will provide the information about the type of method called, the...
Java Crazy: Retrieving form Parameters using HttpServletReques...
Java Crazy: Retrieving form Parameters using HttpServletReques...: Form parameters are key,value pairs where both are string objects. A Form parameter can be associated with single or multiple values. ...
Java Crazy: Statics Example
Java Crazy: Statics Example: class Test{ static int i=10; int j=20; public static void main(String[] args){ Test t1=new Test(); Test t2=new Test(); t2.i...
Java Crazy: Static in java
Java Crazy: Static in java: If you want print something in java without using static blocks or main method. class Google { static int i=m1();` public static...
Static in java
If you want print something in java without using static blocks or main method.
class Google
{
static int i=m1();`
public static int m1()
{
System.out.println("Hi......");
return 10;
}
}
---------- Output ----------
Hi......
java.lang.NoSuchMethodError: main
Exception in thread "main"
class Google
{
static int i=m1();`
public static int m1()
{
System.out.println("Hi......");
return 10;
}
}
---------- Output ----------
Hi......
java.lang.NoSuchMethodError: main
Exception in thread "main"
Wednesday, December 7, 2011
Statics Example
class Test{
static int i=10;
int j=20;
public static void main(String[] args){
Test t1=new Test();
Test t2=new Test();
t2.i=200;
t2.j=400;
System.out.println(t1.i+"......."+t1.j);
}
}
O/P : 200,20
static int i=10;
int j=20;
public static void main(String[] args){
Test t1=new Test();
Test t2=new Test();
t2.i=200;
t2.j=400;
System.out.println(t1.i+"......."+t1.j);
}
}
O/P : 200,20
Saturday, December 3, 2011
Retrieving form Parameters using HttpServletRequest
- Form parameters are key,value pairs where both are string objects.
- A Form parameter can be associated with single or multiple values.
public String getParameter(String pname) ---- returns the value associated with the specified
parameter.
public String[] getParameterValues(String pname) ---- returns all values associated with specified
paremter.
public Enumeration getParameternames() ---- returns all formParameter names associated with
the request.
public Map getParameterMap() ---- returns map object containing parameter names
as keys and parameter values as map values.
key String value String[]
---------------- ---------------------
user { degree }
course { SCJP,SCWCD }
age { 67 }
Sales { 1000 }
Programme to retrieve the above parameters :
Map m=req.getParameterMap();
for(object o1 : m) {
mapentry m1=(map.entry)o1;
String pname=(String) m1.getkey();
String[] pValues=(String[])m1.getValue();
out.println(pname);
for(String s1:pValues)
{
out.println(s1);
}
}
Thursday, December 1, 2011
Why is HttpSerlvet declared abstract ?
The HttpServlet doesnot contain any abstract methods.But, still it is declared as abstract because to prevent instantiation of HttpServlet. HttpServlet contains implementations of all the Http methods to send error information. So if you crreate an instance of HttpServlet and try to acess the methods we will get error information so the HttpServlet class is declared as abstract.
Structure of HttpRequest and HttpResponse
The HttpRequest contains the following things.
1. Request Line ---- It will provide the information about the type of method called, the requested
resource,and the Http protocol version followed by client.
2. Request Header ---- Provides configuration information of the browser like media types,encoding types
supported by the browser. Server will use this request header to prepare response.
3. Request Body ---- Contains information about client. For 'get' request request body is optional. For 'post'
it is mandatory.
1. Request Line ---- It will provide the information about the type of method called, the requested
resource,and the Http protocol version followed by client.
2. Request Header ---- Provides configuration information of the browser like media types,encoding types
supported by the browser. Server will use this request header to prepare response.
3. Request Body ---- Contains information about client. For 'get' request request body is optional. For 'post'
it is mandatory.
Wednesday, November 30, 2011
Threads Example
This programme checks the numbers between 0 to 100 and prints the numbers that are not divisible by 10 with a sleeping period of 500 milliseconds.
class ThreadExercise extends Thread
{
public void run(){
for(int i=0;i<=100; i++)
{
if ((i%10) != 0)
{
System.out.println("numbers.... "+i);
try{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public static void main(String[] args)
{
ThreadExercise te=new ThreadExercise();
te.start();
}
}
class ThreadExercise extends Thread
{
public void run(){
for(int i=0;i<=100; i++)
{
if ((i%10) != 0)
{
System.out.println("numbers.... "+i);
try{
Thread.sleep(500);
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
}
public static void main(String[] args)
{
ThreadExercise te=new ThreadExercise();
te.start();
}
}
Sleep() and Wait()
Difference between sleep() and wait() ?
1) wait() is a method of Object class. sleep() is a method of Thread class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object
1) wait() is a method of Object class. sleep() is a method of Thread class.
2) sleep() allows the thread to go to sleep state for x milliseconds. When a thread goes into sleep state it doesn’t release the lock. wait() allows thread to release the lock and goes to suspended state. The thread is only active when a notify() or notifAll() method is called for the same object
The javax.servlet.Servlet interface
?
init() :
public void init(ServletConfig config) throws ServletException
It is executed only once after the instantiation of servlet to perform initialization
activities. Web Container doesnot place the servlet into the context if the method
throws any exception or if the method execution is not completed in the specified
time.
service() :
public void service(ServletRequest req,ServletResponse res) throws ServletException,
IOException
This method will be executed for every request. The request and response objects
created for this request are eligible for garbage collection once the service method
execution completes succesfully.
destroy() :
public void destroy()
This method is executed only once just before taking servlet out of service to
perform clean up activities.
init() :
public void init(ServletConfig config) throws ServletException
It is executed only once after the instantiation of servlet to perform initialization
activities. Web Container doesnot place the servlet into the context if the method
throws any exception or if the method execution is not completed in the specified
time.
service() :
public void service(ServletRequest req,ServletResponse res) throws ServletException,
IOException
This method will be executed for every request. The request and response objects
created for this request are eligible for garbage collection once the service method
execution completes succesfully.
destroy() :
public void destroy()
This method is executed only once just before taking servlet out of service to
perform clean up activities.
Sunday, November 27, 2011
Java Programme5
class CGG192{
public static void main(String[] args){
String CG="-" ;
switch(Friends.nares){
case praveen : CG+="L";
case nares: CG+="M";
default : CG+="P";
case aravind : CG+="Q";
}
System.out.println(CG);
}
}
enum Friends {praveen, aravind, nares}
Ans: -MPQ
We can use enums in switch .
public static void main(String[] args){
String CG="-" ;
switch(Friends.nares){
case praveen : CG+="L";
case nares: CG+="M";
default : CG+="P";
case aravind : CG+="Q";
}
System.out.println(CG);
}
}
enum Friends {praveen, aravind, nares}
Ans: -MPQ
We can use enums in switch .
Java Programme4
class ExException
{
static String v="-" ;
public static void main(String[] args){
new ExException().v1();
System.out.println(v);
}
void v1(){
try{
v2();
}
catch(Exception e){
s+="C";
}
}
void v2() throws Exception{
v3(); v+="2";
v3(); v+="2b"
}
void v3() throws Exception{
throw new Exception();
}
}
Ans : -c
Once v3 throws the exception to v2,v2 throws it to v1() and no more of v2()'s code is executed.
{
static String v="-" ;
public static void main(String[] args){
new ExException().v1();
System.out.println(v);
}
void v1(){
try{
v2();
}
catch(Exception e){
s+="C";
}
}
void v2() throws Exception{
v3(); v+="2";
v3(); v+="2b"
}
void v3() throws Exception{
throw new Exception();
}
}
Ans : -c
Once v3 throws the exception to v2,v2 throws it to v1() and no more of v2()'s code is executed.
Saturday, November 26, 2011
Java Programme3
What will be the result of the following code:
public class Tester {
public static void main(String[] args) {
System.out.print("1");
try {
System.out.print("2");
System.exit(0);
} finally {
System.out.print("3");
}
}
}
Ans : 12 : System.exit(0) will cause the program to exit and finally block will not be executed
public class Tester {
public static void main(String[] args) {
System.out.print("1");
try {
System.out.print("2");
System.exit(0);
} finally {
System.out.print("3");
}
}
}
Ans : 12 : System.exit(0) will cause the program to exit and finally block will not be executed
Thursday, November 24, 2011
Polymorphism --- OOP Feature
Polymorphism provides one of the most useful programming techniques of the
object-oriented paradigm. Polymorphism,
means "many forms," is the ability to treat an object of any subclass
of a base class as if it were an object of the base class. A base class has,
therefore, many forms: the base class itself, and any of its subclasses.
If you need to
write code that deals with a family of types, the code can ignore type-specific
details and just interact with the base type of the family. Even though the
code thinks it is sending messages to an object of the base class, the object's
class could actually be the base class or any one of its subclasses. This makes
your code easier for you to write and easier for others to understand. It also
makes your code extensible, because other subclasses could be added later to
the family of types, and objects of those new subclasses would also work with
the existing code.
Tuesday, November 22, 2011
Design Pattern -- Singleton
Singleton
Design patttern is used to control object creation, limiting the number
to one but allowing the flexibility to create more objects if the
situation arises.To prevent direct instantiation we create a private
default constructor,so that other classes can’t create a new Instance. The following few lines of code demonstrates a way of creating a singleton object.
public class SingletonObject
{
private static SingletonObject ref;
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if(ref == null)
public Object clone() throws CloneNotSupportedException
public class SingletonObject
{
private static SingletonObject ref;
private SingletonObject()
{
}
public static SingletonObject getSingletonObject()
{
if(ref == null)
{
ref = new SingletonObject();
return ref;
}
}public Object clone() throws CloneNotSupportedException
{
throws new CloneNotSupportedException();
}
}}
Monday, November 21, 2011
Java Programme2
class MyExample{
public static void main(String[] args){
String v="-";
try{
calculate(args[0]);
v=v+"k";
}
finally{
System.out.println(s+="f");}
}
public static void calculate(String b)
{
int y=7/Integer.parseInt(a);
}
}
At the command line :
java MyExample
java MyExample 0
What would be the ouput of the above.
On both the invocations finally block will be executed. ArrayIndexOutOfBoundsException,ArithmeticException will be thrown respectively.
public static void main(String[] args){
String v="-";
try{
calculate(args[0]);
v=v+"k";
}
finally{
System.out.println(s+="f");}
}
public static void calculate(String b)
{
int y=7/Integer.parseInt(a);
}
}
At the command line :
java MyExample
java MyExample 0
What would be the ouput of the above.
On both the invocations finally block will be executed. ArrayIndexOutOfBoundsException,ArithmeticException will be thrown respectively.
Saturday, November 19, 2011
Java Programme1
public class ExampleClass1 {
public int exMethod()
{
int r = 1;
r+=x;
if( (x>4) && (x<10) )
{
r+=2*x;
}
else(x<=4)
{
r+=3*x;
}
else()
{
r+=4*x;
}
r+=5*x;
return x;
}
public static void main(String[] args)
{
Function1 f1=new Function1();
System.out.println("OF(11) is "+ f1.exMethod(11));
}
}
The above programme on compilation gives out compilation error. This is because 'if' should not be followed by two 'else' statements immediately.
public int exMethod()
{
int r = 1;
r+=x;
if( (x>4) && (x<10) )
{
r+=2*x;
}
else(x<=4)
{
r+=3*x;
}
else()
{
r+=4*x;
}
r+=5*x;
return x;
}
public static void main(String[] args)
{
Function1 f1=new Function1();
System.out.println("OF(11) is "+ f1.exMethod(11));
}
}
The above programme on compilation gives out compilation error. This is because 'if' should not be followed by two 'else' statements immediately.
Appropriate use of Assertions
- AssertionError is a sub class of Throwable, so it can be caught. But sun not doesnot allow access to the object that generated it. We only get a String message.
- We should not use Assertions to validate arguments of a public method.
- We can use Assertions to validate arguments of a private method.
- We should not use Assertions to validate command line arguments.
- We should use Assertions which doesnot leave the state of the program in the same state.
Friday, November 18, 2011
Assertions
Assertions in java help us in testing our assumptions during development. The assertion code gets erased when the programme is deployed. While we are developing an application we use 'System.out.println()' in a java class for debugging purpose. We use it inorder to find out any logical problems. Instead we can use Assertions concept.
Ex:
public int myAccNum(int accno)
{
assert(accno > 0);// line 1
int myAccno=accno;
}
If the accno is negative on line 1 then the compiler throws an assertion error.
Assertions needed to be turned on then they will work. Other wise the compiler will overlook the Assertion code. There are two ways to write assertion code.
1. assert( X > A);
2. assert(X > A) : "X value is" + X + "A value is" + A
java -ea com.venkates.TestClass
java -enableassertions com.venkates.Testclass
The above two commands enable assertions at runtime. The below commands disable assertions .
java -da com.venkates.TestClass
java -disableassertions com.venkates.TestClass
Ex:
public int myAccNum(int accno)
{
assert(accno > 0);// line 1
int myAccno=accno;
}
If the accno is negative on line 1 then the compiler throws an assertion error.
Assertions needed to be turned on then they will work. Other wise the compiler will overlook the Assertion code. There are two ways to write assertion code.
1. assert( X > A);
2. assert(X > A) : "X value is" + X + "A value is" + A
java -ea com.venkates.TestClass
java -enableassertions com.venkates.Testclass
The above two commands enable assertions at runtime. The below commands disable assertions .
java -da com.venkates.TestClass
java -disableassertions com.venkates.TestClass
Monday, October 24, 2011
Action Servlet
It is the front controller of struts application. It has the generic flow control of any struts application. It is the built in controller class of struts framework.
ActionServlet is a simple HttpServlet. Struts developer should register the ActionServlet ,Pre-initialize, map every client request to ActionServlet.
ActionServlet knows about the flow control information from struts-config.xml, during its initializtion phase.When the application is deployed and before any client request comes servlet container instantiates ActionServlet class and calls its inti().
In the init() of ActionServlet 'Digester' API is used to parse the struts-config.xml and create a set of Java configuration objects based on the content of the struts-config.xml file .
ActionServlet is a simple HttpServlet. Struts developer should register the ActionServlet ,Pre-initialize, map every client request to ActionServlet.
ActionServlet knows about the flow control information from struts-config.xml, during its initializtion phase.When the application is deployed and before any client request comes servlet container instantiates ActionServlet class and calls its inti().
In the init() of ActionServlet 'Digester' API is used to parse the struts-config.xml and create a set of Java configuration objects based on the content of the struts-config.xml file .
Wednesday, October 19, 2011
Friday, September 30, 2011
Thursday, September 29, 2011
JNDI --- Java Naming and Directory Interface
It is an API that is used by java programs to interact with any naming service and directory service that implements JNDI.
Tuesday, September 20, 2011
Java Bits -1
--> Importing packages doesnot recursively import subpackages
--> Unicode characters can appear anywhere in the source code. The following code is valid.
--> Unicode characters can appear anywhere in the source code. The following code is valid.
ch\u0061r a = 'a';
char \u0062 = 'b';
char c = '\u0063';
·
Subscribe to:
Posts (Atom)
