Wednesday, July 16, 2008

Settting SSL with Tomcat..!

Hi Guys,

I found this article of great help..! how can u make ur website secure and safe by adding SSL..! 3 simple steps to add SSL to Tomcat..! Please follow this article..!

Setting SSL with Tomcat..!

Tuesday, July 15, 2008

A sample web.xml file

This is a sample XML File, which can be useful to all who are preparing for SCWCD.
Please do the following after copy and paste on your text pad:
Replace : '<' --> <
Replace : '>' --> >
Enjoy..!

'<'web-app id="WebApp_ID2" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"'>'


'<'context-param'>'
'<'param-name'>'web-master-email'<'/param-name'>'
'<'param-value'>'webmaster@scwcdtest.com'<'/param-value'>'
'<'/context-param'>'

'<'description'>'Testing for SCWCD Exam'<'/description'>'

'<'display-name'>'SCWCD TEST'<'/display-name'>'

'<'distributable/'>'

'<'ejb-local-ref'>'
'<'ejb-ref-name'>'ejb/Customer'<'/ejb-ref-name'>'
'<'ejb-ref-type'>'Entity'<'/ejb-ref-type'>'
'<'local-home'>'com.example.CustHome'<'/local-home'>'
'<'local'>'come.exampleCust'<'/local'>'
'<'/ejb-local-ref'>'

'<'ejb-ref'>'
'<'ejb-ref-name'>'ejb/Customer'<'/ejb-ref-name'>'
'<'ejb-ref-type'>'Entity'<'/ejb-ref-type'>'
'<'home'>'com.example.CustHome'<'/home'>'
'<'remote'>'com.example.Cust'<'/remote'>'
'<'/ejb-ref'>'

'<'!-- ALL EJD/JNDI RELATED CONFIGURATIONS --'>'
'<'env-entry'>'
'<'env-entry-name'>'jndi/TestEnv'<'/env-entry-name'>'
'<'env-entry-type'>'java.lang.String'<'/env-entry-type'>'
'<'env-entry-value'>'TEST_ENV'<'/env-entry-value'>'
'<'/env-entry'>'

'<'!-- ERROR PAGE CONFIGURATION --'>'
'<'error-page'>'
'<'exception-type'>'java.lang.ArithimeticException'<'/exception-type'>'
'<'!-- or
'<'error-code'>'500'<'/error-code'>'
--'>'

'<'location'>'/WEB-INF/error.jsp'<'/location'>'
'<'/error-page'>'

'<'!-- FILTER CONFIGURATION --'>'
'<'filter'>'
'<'filter-name'>'MyFilter'<'/filter-name'>'
'<'filter-class'>'com.example.HelloFilter'<'/filter-class'>'
'<'init-param'>'
'<'param-name'>'FilterName'<'/param-name'>'
'<'param-value'>'Hello Filter'<'/param-value'>'
'<'/init-param'>'
'<'/filter'>'

'<'filter-mapping'>'
'<'filter-name'>'MyFilter'<'/filter-name'>'
'<'url-pattern'>'/*.do'<'/url-pattern'>'
'<'!-- or
'<'servlet-name'>'MyServlet'<'/servlet-name'>' --'>'

'<'dispatcher'>'REQUEST'<'/dispatcher'>'
'<'!-- or
'<'dispatcher'>'INCLUDE'<'/dispatcher'>'
'<'dispatcher'>'FORWARD'<'/dispatcher'>'
'<'dispatcher'>'ERROR'<'/dispatcher'>'
--'>'

'<'/filter-mapping'>'

'<'!-- JSP CONFIGURATION --'>'
'<'jsp-config'>'
'<'taglib'>'
'<'taglib-uri'>'helloWorld'<'/taglib-uri'>'
'<'taglib-location'>'/WEB-INF/hello.tld'<'/taglib-location'>'
'<'/taglib'>'
'<'jsp-property-group'>'
'<'url-pattern'>'*.do'<'/url-pattern'>'
'<'el-ignored'>'false'<'/el-ignored'>'
'<'scripting-invalid'>'true'<'/scripting-invalid'>'
'<'/jsp-property-group'>'
'<'/jsp-config'>'

'<'!-- LISTENER CONFIGURATION --'>'
'<'listener'>'
'<'listener-class'>'com.example.MyContextListener'<'/listener-class'>'
'<'/listener'>'

'<'login-config'>'
'<'auth-method'>'BASIC'<'/auth-method'>'
'<'realm-name'>'LDAP REALM'<'/realm-name'>'
'<'!-- or
'<'auth-method'>'DIGEST'<'/auth-method'>'
'<'auth-method'>'CLIENT-CERT'<'/auth-method'>'
'<'auth-method'>'FORM'<'/auth-method'>'
'<'form-login-config'>'
'<'form-login-page'>'/login.html'<'/form-login-page'>'
'<'form-error-page'>'/error.jsp'<'/form-error-page'>'
'<'/form-login-config'>'
--'>'

'<'/login-config'>'

'<'resource-env-ref'>'
'<'resource-env-ref-name'>'jndi/someQueue'<'/resource-env-ref-name'>'
'<'resource-env-ref-type'>'javax.jms.Queue'<'/resource-env-ref-type'>'
'<'/resource-env-ref'>'

'<'resource-ref'>'
'<'res-ref-name'>'jdbc/EmpDB'<'/res-ref-name'>'
'<'res-type'>'javax.sql.Datasource'<'/res-type'>'
'<'res-auth'>'Container'<'/res-auth'>'
'<'res-sharing-scope'>'Shareable'<'/res-sharing-scope'>'
'<'/resource-ref'>'

'<'security-constraint'>'
'<'web-resource-collection'>'
'<'web-resource-name'>'My Security'<'/web-resource-name'>'
'<'url-pattern'>'/hello/*.do'<'/url-pattern'>'
'<'http-method'>'GET'<'/http-method'>'
'<'http-method'>'POST'<'/http-method'>'
'<'/web-resource-collection'>'
'<'auth-constraint'>'
'<'role-name'>'admin'<'/role-name'>'
'<'role-name'>'manager'<'/role-name'>'
'<'/auth-constraint'>'
'<'user-data-constraint'>'
'<'transport-guarantee'>'NONE'<'/transport-guarantee'>'
'<'!-- or
'<'transport-guarantee'>'CONFIDENTIAL'<'/transport-guarantee'>'
'<'transport-guarantee'>'INTEGRAL'<'/transport-guarantee'>'
--'>'

'<'/user-data-constraint'>'
'<'/security-constraint'>'

'<'!-- ALL SECURITY RELATED CONFIGURATIONS --'>'
'<'security-role'>'
'<'role-name'>'admin'<'/role-name'>'
'<'/security-role'>'

'<'security-role'>'
'<'role-name'>'manager'<'/role-name'>'
'<'/security-role'>'


'<'!-- SERVLET CONFIGURATION --'>'
'<'servlet'>'
'<'servlet-name'>'MyServlet'<'/servlet-name'>'
'<'servlet-class'>'com.example.HelloServlet'<'/servlet-class'>'
'<'!-- or
'<'jsp-file'>'/hello.jsp'<'/jsp-file'>'
--'>'

'<'init-param'>'
'<'param-name'>'emailid'<'/param-name'>'
'<'param-value'>'hello@hcl.com'<'/param-value'>'
'<'/init-param'>'
'<'load-on-startup'>'1'<'/load-on-startup'>'
'<'security-role-ref'>'
'<'role-name'>'Manager-TOM HENRY'<'/role-name'>'
'<'role-link'>'admin'<'/role-link'>'
'<'/security-role-ref'>'
'<'/servlet'>'

'<'servlet-mapping'>'
'<'servlet-name'>'MyServlet'<'/servlet-name'>'
'<'url-pattern'>'*.do'<'/url-pattern'>'
'<'/servlet-mapping'>'

'<'!-- SESSION CONFIGURATION --'>'
'<'session-config'>'
'<'session-timeout'>'15'<'/session-timeout'>'
'<'/session-config'>'

'<'!-- CONTENT TYPE CONFIGURATION --'>'
'<'mime-mapping'>'
'<'extension'>'text'<'/extension'>'
'<'mime-type'>'text/html'<'/mime-type'>'
'<'/mime-mapping'>'

'<'welcome-file-list'>'
'<'welcome-file'>'index.jsp'<'/welcome-file'>'
'<'welcome-file'>'default.jsp'<'/welcome-file'>'
'<'/welcome-file-list'>'

'<'/web-app'>'

Sunday, March 23, 2008

SCRIPTLESS JSP

Hi guys,

This is my first presentation after joining the company..!! i have put a lot of effort to prepare it..!! I hope you guys will like it..!! if u find any problem..please feel free to comment me..!!

this is the first part of presentation..i m in middle of second part..will upload as soon as its done!!
Overall you can say that this presentation is concrete form of Chapter 8 of Heah first servlet and jsp.

thanks
Sunny

download link :
http://www.zshare.net/download/93882358c94cde/

Tuesday, March 4, 2008

Need any help ??

Hi Guys,

If any one need any help about SCJP? Please drop your email address and request type as a comment..!!
Request can be any thing like for book or some notes..exam..mock simulators etc..

My Experience with SCJP exam

Hi All,

I took SCJP and cleared it with 90%. I am so happy to say " I am Sun Certified now". I would like to express my gratitude to all the JAVA RANCHERS who helped me when I was perplexed with JAVA concepts. I would also like to give a special thanks to KATHY AND BERT for writing such a fantastic and I will say relevant or focussed material. Well After I cleared the exam I analyzed my self and I found below flaws and good deed in my preparation, I am mentioning them below
with a hope that It will help those who are preparing:

Do:
1) Read the K&B carefully. Every line is worth to read. In the exam you will encounter question from every topic. Every means EVERY, If you miss one topic, then its sure you will miss some questions. In My case EXAM was a nice blend of question from all the sections.

2) Do a lot of mock exams, Talking as a third party member with no personal benefit, i would mention two website:
1) http://www.onlinemockexams.com/

Five free test are available, with two attemp to each test. Test are quite good and difficulte level is same as that of SCJP Test.

2) http://www.javablackbelt.com/

Now this is really a bliss to all JAVA buzzs, Register on this website, n number of test are available. They have a belt system there. If you are able to get a Orange belt there,then dont waste time, just go and take the SCJP exam. you will clear it with more than 90%. Altho' I was at the boundry to get Orange belt before I took the exam. But literally This is the best website. For me getting a good belt here is worth more than a SCJP. Difficulty level is bit higher than real exam.

3) Revise K&B book atleast two times and do all the questions given at the back of exercise.

Don't :

If you studying specifically to get Certification then dont read here and there. Whatever is given in the book if sufficient and more than enough. Dont waste time.I
did the same mistake.For eg: I read Concurrency from somewhere else. This was actually good and made my concept really strong. I was able to solve every question on thread. Actually I get an extra Over confidence on that and I accept that. Due to this confidence i did not read the K&B book Concurrency Chapter so I paid plenty for that. I got 12 question on concurrency out of which I was able to solve 9 of them.
So My recommendation would be,Even if read any concept from somewhere else, Do read the same from K&B, Becuase K&B have written that from exam point of view and you have read that concept point of view.
Just before the exam's day, it is always tempting to cram the things, But make concepts. Do not learn things. Learning can make you clear the exam but it is the concepts which help you to score. There is always a difference between passing an exam and scoring in an exam.

About the exam:
First of all forget that exam is easy. IT IS DIFFICULT, well in my case I found 25 questions were so easy to respond with in a second but rest were need re consideration. But exam is not that much difficult that you wont be able to solve the questions, Overall i can say that:
More easy the concept, More difficult the question and More difficult the concept is, more easy the question.
if you have time after attempting all the questions, please have a look once again. In my case i was feeling so hungry so that I did not have a re look. It might help you.If you have not practiced enough via mock exam you will find exam a bit difficult. So Please do a lot of mocks.

Best of luck for your exam.

Monday, February 18, 2008

Calculate time according to Locale in JAVA

We Often get confuse in calculating time ?
For eg: If I ask you what is the Time in New York by now? If you are not in New York, then it will be a problem? Here is the code that can be used to find time in any part of the world..Enjoy..!!!


/**
*Copyright (C) 2010  Jovial Java admin [email: jovialjava.blogspot@gmail.com]
*
*This program is free software: you can redistribute it and/or modify
*it under the terms of the GNU General Public License as published by
*the Free Software Foundation, version 3 of the License.
*
*This program is distributed in the hope that it will be useful,
*but WITHOUT ANY WARRANTY; without even the implied warranty of
*MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*GNU General Public License for more details.
*
*You should have received a copy of the GNU General Public License
*along with this program.  If not, see .
*@author JovialJava
*/
package com.jovialjava.blog.utils;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimeAsPerLocale {
 
 private static long NEW_YORK_OFFSET = -5L*60L*60L*1000L;
 private static long SINGAPORE_OFFSET = 8L*60L*60L*1000L;
 private static long INDIA_OFFSET = (long)(5.5*(60L*60L*1000L));
 
 public static void main(String[] args) throws Exception {
  Date date = new Date();
  Calendar c = Calendar.getInstance( );
  c.setTime(date);
  /**
   * Getting the CURRENT LOCALE OFFSET from GMT
   */
  int offset = c.get(Calendar.ZONE_OFFSET);
  /**
   * Getting the GMT time
   */
  long GMTTime = date.getTime( ) - offset;
  /**
   * New York Time = GMT - 5
   */
  long newYorkTime = GMTTime + NEW_YORK_OFFSET;
  /**
   * Singapore Time = GMT + 8
   */
  long singaporeTime = GMTTime + SINGAPORE_OFFSET;
  /**
   * India Time = GMT + 5.5
   */
  long indiaTime = GMTTime + INDIA_OFFSET;
  
  /**
   * Display and formatting
   */
  DateFormat df = DateFormat.getInstance( );
  System.out.println("GMT Time    : " + df.format(new Date(GMTTime)));
  System.out.println("New York Time   : " + df.format(new Date(newYorkTime)));
  System.out.println("Singapore Time   :"  + df.format(new Date(singaporeTime)));
  System.out.println("India Time    : " + df.format(new Date(indiaTime)));

  }
}

Sunday, February 17, 2008

Concept of Broadening, Widening, and Casting in JAVA 1.5

Compile the following thing:
code:

Byte b= new Byte(100);
Long d=new Long(100);


First line fail to compile, where as Second line compiled successfully..Why..why why ??
Lets try to find out:
when you write :
byte b = 120;
its compiles fine..!! why because compiler see that int 120 in in RANGE of byte..
Now when you write
byte b = 150;
Compiler complains since 150 is out of RANGE..!!
Now lets come to your question :
Part 1 :
Byte b = new Byte(100);
When ever compiler encounters new keyword, it let the Object creation on JVM..!! so in case of new Object..Objects are created at run time..!! so according to compiler point of view:
Byte b = new Byte(int);
Here int may or may not be in the RANGE of byte, if it is in range then its ok, if it is not then !!!! SCARY THINGS!!!!..so as a friend compiler wont let you to write something that has possibility of crashing..that why it gives you an error..
in case of
Long l = new Long(int);
now whatsoever be the value of int ,it ALWAYS be in the RANGE of long..so compiler allows..!!!
You got to know now..take a deep breath now..!!see the next line of code
code:
Byte b=100;
Long d=100;


Ohh My god..!! Now first line workd but second doesn't..Let see why?

In JAVA 5, we can not WIDEN and BOX Together...!!! Repeat this line 5 times..!!! Done..lets move forward.
Now in
Long l = 100;
In this case 100 is an integer..so first we have to widen it to long then we have to box long to Long...!!
so compiler complain..
Long l = new Long(100);

Here we are widening int(100) to long..but we are not boxing it...!! as we have used new keyword here..so we have explicitly defined the Object creation syntax..
so compile successfully...!!!
now
Byte b = new Byte(100)..

this i already explain you why it can not be compile..!!
now come to following:

Byte b = 100;

Here we have int 100....we are not widening it...infact we are narrowing it..but we call it implicit casting..!!
and since this implicit casting is in range..and the object will be created at compile time..so it works..
so here we can say that..
implicit casting(with in range) + Boxing is acceptable..!!

But again one thing concern me..!!
suppose the following condition..

public static void printMe(Byte b) { }

public static void main(String... args)
{
printMe(100);

}

from compiler point of view...it is calling printMe(int)..again possibility of crashing..so It wont allow..

Tuesday, February 12, 2008

Difference between Waiting and Yielding in JAVA Threads - Part 2

Yielding

Yielding is the act of politely offering up your turn in the queue while maintaining your resources.

For example, suppose there are several person queuing up to use a bank’s automated teller machine(ATM).

In the Analogy-
People in Queue acting as Running Threads.
ATM acting as CPU.


Bingo! Your turn has arrived to use ATM. You know that this process will take a while because you’re going to transfer funds,check your balance, make a deposit, and so forth. So you decides to offer the person behind you to use ATM before you. This activity is referred as "YIELDING".Of course, you wouldn’t give that person your resources (money, ATM card, and so on). However, you would offer to give up your spot at the ATM (analogous to the CPU). The process of making this offer,even if there’s no one to accept it, is yielding. It may possible that person behind you is too nice and he/she says that please continue to use ATM, I would rather wait for you to finish. So it is possible that, even though you yielded, you may still get first access. In computer terms, though, when you yield, all threads (including your own) then get to compete for the lock on the object—your thread does not get a lesser or greater chance of getting the lock on the object. But what decides which thread actually wins that competition and gets access to the lock on the object? The thread scheduler does.

The thread scheduler is like an office manager. It takes threads into consideration and decides which thread should be allowed to run based on the underlying operating system, thread priorities, and other factors. There are two important points to note-
First, you must be aware that your thread of execution is not guaranteed to be next in line when you yield, even though you originally volunteered to give up the CPU. Once a thread yields and the CPU is taken by another thread, the original yielding thread does not have any special status in being next in line. It must wait and hope, like every other thread.
Second, it’s important to realize that your thread didn’t give up resources that you have exclusive locks on. That is, even though you’re letting someone else use the ATM, you didn’t give him your ATM card. When a thread yields, it steps out of the CPU, but it retains control over any resources it had originally marked for exclusive use.

Difference between Waiting and Yielding in JAVA Threads - Part 1


Waiting in Thread with Real world Metaphor:

Running Threads in JVM can be consider children playing in a park. As they are playing so they must be looking for some toys or rides in park. As we all know that there are some rides which can be shared by several children and some rides which can be used by only one child at a time. Lets call them shared~Rides and Rides respectively.

In this analogy -
> Park acting as JVM
> Children acting as Threads
> Shared~Rides acting as System Resources which can be shared by server children(Threads) at a time.
> Rides acting as System resources which can be used by one Children at a time.



Lets assume following scenario-

Two children A and B are playing. At this point of time A is playing with Ride_1 and B is playing with Ride_2. Suddenly B wants to play with Ride_1 so B looks at Ride_1 and what he sees? A is already playing with it, so B decides to wait until A finish with Ride_1. While B is waiting for A, he/she will opt either of the following activity:
1) Continue to use Ride_2 and when A finishes, Jump to Ride_1 and free the Ride_2 for other children.
2) Release Ride_2 for other children and patiently wait for A to finishes.

The Activity of B is referred as "WAITING".

Lets assume following scenario-

Imagine a group of children trying to buy ice cream from an ice cream truck. If the boy who currently has the ice cream vendor’s attention does not have enough money to pay for his ice cream, he won’t force everyone else to wait while his father brings him the funds he needs. He will get out the way, probably weep quietly to himself, and wait. Then he’ll step back into the fray and try to claim the ice cream vendor’s attention. The other children won’t wait for him, because he can’t order anyway.


In Technical world, if 2 threads are running and one thread wants to use a resource currently being used by another thread, and decides to wait until another threads finishes using the resource, in addition to this while waiting the threads may decides to either release or not to release the resource.

The Occupation of resource is referred as "LOCKING" in JAVA.

Waiting is the act of getting out of the way when you can’t be productive. As the name implies, waiting is an inactive process. This means that a waiting thread does not waste CPU time it cannot use. If a thread is waiting, then other threads are free to use its allotted quota of CPU time. The waiting thread will certainly not need it.

A Technical Example  :

 In this case, there is one thread representing the minister waiting for the collection to exceed $100. There are a further six threads representing attendees adding $20 to the collection plate. Each of these threads synchronizes on the collectionPlate object. Since the threads adding to the collection plate need to obtain the lock on the collectionPlate object, the minister thread must temporarily release it from time to time, which it does by calling the wait method. As each thread adds to the collection plate, it wakes the minister by calling the notify method.

Please see the attached image for source code



Calling the wait method is different than calling sleep or yield, or even pausing for I/O.
The wait method actually allows other threads to acquire the lock on the object in question,
while sleep, yield, and pausing for I/O do not.
============================================================== 
Click here : Yielding in JAVA
============================================================== 

Sunday, February 10, 2008

Answers of Practice Questions

Solutions:


Answer 1
b is the correct answer. Like static methods, member variables are also computed using the type of the reference.
Answer 2
a, d & e are the correct answers. These are the names of interfaces.
Answer 3
b is the correct answer. File object represents a filename, not a physical file, and not in charge on creating files.
Answer 4
c is the correct answer. i variable is declared in a for block, and therefore can�t be used in line 8 � outside that block.
Answer 5
a is the correct answer. The intern method in the String class makes the system search for a pre-existing String object with a given content.
Answer 6
a is the correct answer. The inner class is written perfectly correct. This block of code will call the doAction() when button is clicked.
Answer 7
b & d are the correct answers. d is correct because exceptions obey a hierarchy just like other objects. Answer d is correct because these exceptions descend from RuntimeException, so they don�t have to be declared.
Answer 8
a, c & e are the correct answers. Those methods can be overridden by the programmer in order to create an Applet.
Answer 9
c, d & e are the correct answers. The call to super() constructor must be first statement in constructor. Therefore compiler can�t find a legal call to super constructor and adds its own one � to the constructor that accepts no parameters, that can�t be found in a super class. Finally, after casting Oharada object to Vapenka variable field nationality can�t be accessed.
Answer 10
b is the correct answer. 27 is an int by default. In line 2 casting is done by the compiler, in line 4 the compiler will demand an implicit casting.
Answer 11
b, d & e are the correct answers. The reference, stored in flag variable can�t be changed because it is final. The check (||) can�t be applied on primitive and object simultaneously. You don�t have to use a Boolean object to get String representative of a boolean primitive. It is more convenient to use a static method in Boolean class, that doesn�t require a Boolean object.
Answer 12
c is the correct answer. When applied to primitives, the == sign checks the equality of a value, but when applied to objects, it checks the equality of a reference, not a value.
Answer 13
a & e are the correct answers. a is correct because local variable can be garbage collected after the program exits the block that contains the variable. e is correct because once the reference to local variable stored in object which scope lasts beyond the local block it can�t be garbage collected.
Answer 14
a, c & e are the correct answers. b and d are incorrect because the overriding method can throw less exceptions, in term that they are the same, or subclasses of those which where thrown is original method, or no exceptions at all.
Answer 15
c is the correct answer. RandomAccessFile stands outside other Java IO hierarchies and derives directly from Object.

Saturday, February 9, 2008

Practice Questions

SCJP/OCPJP Practice Exam 1
Question 1
Consider the following classes:
<pre class="brush: java">
class Animal extends Object {
public boolean ok = true;
 }


class Horse extends Animal {
public boolean ok = false;
 }


public class Oharada {
  public static void main( String args[] ) {
    Horse palm = new Horse;
   Animal vap = palm;
   System.out.println( vap.ok );
}
 }
</pre>


What will be the result of trying to compile and execute the class?
a.Some address in memory will be printed to the standard output.
b.true will be printed to the standard output.
c.false will be printed to the standard output.
d.The compiler will object line 8.
e.A runtime exception will be thrown in the main method.


Question 2
Which of the following are interfaces?
a.java.util.List
b.java.util.TreeMap
c.java.util.AbstractList
d.java.util.SortedMap
e.java.util.Iterator


Question 3
If an instance of the class File is created in order to represent a file, which isnt exist, the file will be created.
a.True.
b.False.


Question 4
Consider the following Animal class:
<pre class="brush: java">
  public class Animal {
    static String[] nameList={ McNealy , Gates , Thompson , Ritchie };
    public static int findName( String name ) {
             for(int i=0; i<nameList.length; i++) 
                   if (name.equals( nameList[i] )) 
break;
                  return i;
}
   public static void main( String args[] ) {
               System.out.print( findName( "Zindell" ));
    }
 }
</pre>
What will be the result of trying to compile and execute the class?
a."3" will be printed to the standard output.
b.A runtime exception will be thrown in the main method.
c.A compiler error will prevent compilation.
d.The program will run, but nothing will be produced to the standard output.
e.None of above.


Question 5
Which method is in charge for searching in memory for pre-existing String objects with similar text?


a.String.intern()
b.String.equals()
c.StringNameHelper.id()
d.Runtime.freeMemory()
e.MemoryHandler.push()


Question 6
Which of the following anonymous inner classes is written correctly?
<pre class="brush: java">
a.button.addActionListener(
    new ActionListener(){
      public void actionPerformed(ActionEvent evt){
           doAction();
     }
});


b.button.addActionListener(
     new Object implements ActionListener(){
       public void actionPerformed(ActionEvent evt) {
          doAction();}
});


c.button.addActionListener(
new ActionListener(){
doAction();
} );


d.button.addActionListener(
ActionListener Animal = new ActionListener(){
public void actionPerformed(ActionEvent evt){
doAction();}
} );


e.button.addActionListener(
new Animal extends Object implements ActionListener(){
public void actionPerformed(ActionEvent evt){
doAction();
}
} );
</pre>


Question 7
Consider the following hierarchy of classes:
Exception
|
+--RuntimeException

+--BadException
|
+--VeryBadException
|
+--AwfulException
|
+--DisastrousException


Suppose that you have a method X that could throw both awful and disastrous exceptions. Assuming that X does not have try-catch statements, which of the following statements are correct?
a.The declaration of X must include throws AwfulException, DisastrousException.
b.If a method calling X catches VeryBadException, both awful and disastrous exceptions are caught.
c.If the declaration of X includes throws VeryBadException, any calling method must use a try-catch block.
d.The declaration for X does not have to mention exceptions.
e.The declaration for X has to mention at least one of the exceptions in given hierarchy.


Question 8
In order to create an Applet, the programmer must derive its class from java.applet.Applet. Which of the following methods expects the JVM to find when creates an instance of this class?
a.run()
b.init()
c.stop()
d.pause()
e.start()


Question 9
Consider the following classes:
<pre class="brush: java">
class Animal{
private String name;
private int age;
public Animal( String name , int age ){
this.name=name;
this.age=age;
}
}


 public class Oharada extends Animal {
private boolean nationality;
public Oharada ( String name , int age , boolean  nationality ) {
this.nationality=nationality;
super( name , age );
}
 public static void main( String args[] ) {
Animal oh = new Oharada( Zaharya , 118 ,  true );
System.out.print( oh.nationality );
   }
}
</pre>


What will be the result of trying to compile and execute the class?
a."true" will be printed to the standard output.
b.A runtime exception will be thrown in the main method.
c.A compiler will object line 16.
d.A compiler will object line 21.
e.A compiler will search for Animal() constructor and wont find it.


Question 10
Consider the following code:
1 byte b = 0;
2 b += 27;
3 b = 0;
4 b = b + 27;


Line 2 is interchangeable with line 4.
a.True.
b.False.


Question 11
Consider the following code:


<pre class="brush: java">
final Boolean flag = new Boolean( true );
final boolean flaggy = false;
</pre>


Which of the following statements are false?
a.The value that object, which reference is stored in flag variable, contains can not be changed.
b.The reference, stored in flag variable, can be changed.
c.The flaggy variable can not be stored in a Vector, while the flag can.
d.The check ( flaggy || !flag ) is legal.
e.When you want to convert boolean to String you have to use a Boolean object.




Question 12
Consider the following Animal class:


<pre class="brush: java">
public class Animal{
 public static void main(String args[]){ 
byte b = 3;
Byte bb = new Byte( b );
byte c = 3;
Byte cc = new Byte( c );
boolean r = ( b == c );
Boolean rr = new Boolean( bb == cc );
System.out.print( r );
System.out.print(   );
System.out.println( rr );
   }
}
</pre>
What will be result of the execution?
a.The program will produce true true to the standard output.
b.A compiler error will prevent compilation, objecting line 13.
c.The program will produce true false to the standard output.
d.A runtime exception will be thrown in the main method.
e.A compiler error will prevent compilation, objecting line 10.






Question 13
Here is a method that takes an array of Object references, adds them to a Vector, and calls the action method on the Vector (assume that the action method does not keep a reference to any of the objects involved):


<pre class="brush :java">
 public void Animal( Object[] arr ) {
    Vector vec = new Vector();
for(int i=0; i<arr.length; i++) {
vec.addElement( arr[ I ] );
}
    action(vec);
 }
 </pre>


Which of the following statements are correct?
a.The Vector object can be garbage collected after line 9.
b.The array can be garbage collected after line 9.
c.The content of the array can be garbage collected after line 9.
d.The references from array prevent the Vector from being garbage collected after line 9.
e.It is enough to add a reference to Vector to the array to prevent them both from being garbage collected after line 9.


Question 14
Regarding a method which throws exceptions, which of the following statements about its overriding methods are true?
a.An overriding method may legitimately throw fewer exceptions than its original, but it may not throw more. 
b.An overriding method must be able to throw exactly the same number of exceptions as the original one.
c.An overriding method may throw and exception that is a subclass of the original.
d.An overriding method must be able to throw exactly the same exceptions as the original one.
e.An overriding method does not have to throw exceptions at all.


Q)15
Which is the right hierarchy of RandomAccessFile?
a.java.Object
|
+--java.io.File
|
+--java.io.RandomAccessFile
b.java.Object
|
+--java.io.DataInput
|
+--java.io.RandomAccessFile


c.java.Object
|
+--java.io.RandomAccessFile


d.java.Object
|
+--java.io.DataInputStream
|
+--java.io.RandomAccessFile
e.java.Object
|
+--java.io.Reader
|
+--java.io.RandomAccessFile

Thursday, February 7, 2008

Part 4 of 4: Continue.. (Solution of Questions)

Answer to Previous Quiz:


Answers :

1) Compilation fails

2) Yes, but with Warning.

3) True

4) True

5)Prints Hi
  bye..

6)Compilation fails.

7) A

8)Compilation fails.

9) No

10) 0

11) 1

12 ) No

Part 4 of 4 : Practice Questions for Generics in JAVA

Question No: 1

What will be the output of this program?



Question No : 2

Will this code compile?


Question No: 3
3) Generics are implemented by Type Erasure ??

True or False?


Question No: 4
4) It is legal to create an ArrayList without a type (i.e. without the < ... > ) statement.

True or false?


Question No: 5
5)What happens when you try to compile and run the following program??



Question No: 6

6)
What happens when you try to compile and run the following program??



Question No: 7
7)While writing the generic classes in Java, which of the following can be used as Generic Parameters? (Can be more than one)

a) Classes
b) Primitive Types
c) Compile time Constants.



Question No: 8

What happens when you try to compile the following code?




Question No: 9


Question No:10 
Given the following: What will be the output of the program?


Question No: 11
Given the following, What is true here? 
1) This code will compile without warning and give output equal to 89.
2) This code will compile with warning and give output equal to 89. 
3) This code will not compile. 
4) Run time exception. 

Question No: 12 
Is the following code legal?
For Answers, Please look at this page >>ANSWERS<<

Wednesday, February 6, 2008

Part 3 of 4: GENERICS in JAVA

How polymorphism works in Generic?

Lets start with a basic analogy between collection and array. Both are more or less similar in the sense that we can use both to hold objects.

Polymorphism in Array and related problems:
In arrays following statement is perfectly valid-
Number[] obj = new Integer[5];

How this statement is interpreted by JAVA Complier and Java Executor?
Java Compiler:
obj will refer to a "Number" object and Object itself can refer to 5 "Number" Object or "subclasses of Number" Objects.

Continuing the compiler behavior, below statements compile fine:
obj[1]= new Intger(123);
obj[2]= new Double(123);

As Both Double and Integer are subclasses of Number.

Java Executor:
After executing this statement one "Number" object will created onto HEAP memory and object itself can refer to 5 "Integer" Objects.But as compiler has allowed to store a "Double" object, at Runtime - Java Executor will throw "ArrayStoreException".so Executor has to suffer because of COMPILER stupidity.

THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS.

Polymorphism in GENERICS:

If we try this-
ArrayList< Object > store_room = new ArrayList< String >( );

COMPILER WILL NOT ALLOWED THIS.

Correct expression is -
ArrayList< String > store_room = new ArrayList< String >( );

As it is clear that all this is because JAVA wants to AVOID EXCEPTION in STORING the objects in STORE ROOM (COLLECTION).

How we create STORE ROOM (COLLECTION OBJ) has been given the liberty, which means-

List< String > store_room = new ArrayList< String >( );


So POLYMORPHISM is ALLOWED While creating a STORE ROOM ( COLLECTION ), but POLYMORPHISM is NOT ALLOWED while storing the objects in STORE ROOM.

Refer to the line above:
"THIS IS THE SITUATION WHICH THE SUN ENGINEERS ARE TRYING TO AVOID IN GENERICS. So THEY are trying to improve COMPILER to DETECT this kind of problems in GENERICS."

so its COMPILER which checks that there is no polymorphism when it comes to STORING of DATA in GENERICS.

JAVA COMPILER:

List< Object> store_room = new ArrayList< String >( );

Result : Compilation error, I am trying to avoid Object storing exceptions.

List< String > store_room = new ArrayList< String >( );

Result: OK, but as now JAVA Executor doesn't need to worry about Object storing, I should remove the unncessary things. So after compilation-

List< String > store_room = new ArrayList< String >( ) -->
                                                                                     List store_room = new ArrayList( );

This is called as TYPE ERASURE.GENERICS ARE FOR COMPILE TIME ONLY. Thats why it makes a strict check at the compile time.

Part 2 of 4: Generics in Java

GENERICS WITH LEGACY CODE :

Lets see how GENERICS work with Legacy Code. By Legacy code we mean - code which has been written with Java Version 1.4 and before.

Analogy:

In this era of digital world, everything has been digitalized so is the PASSPORT. Now a days information is stored in bar-code fashion on passport.Based on this suppose we have one List.
List< digital_Passport > passportList = new ArrayList< digital_Passport >( );

Suppose we have a Legacy Method -

public void legacy_Add_Method( List passportData ){
passportData.add( new Old_Passport() );
}


Lets say we made a call to Legacy Method-

legacy_Add_Method( passportList );



This actually means -
List passportData = new ArrayList< digital_Passport>( )


Think from another point of view, Just because you have a new passport and airport system can recognize your passport, airport authority can not reject people with old passport. Similar way, although this sound odd but JAVA has to allow an old Legacy method be called with new Generic Type Collection Object, but being good JAVA tells this unusual assignment by issuing a COMPILER WARNING.

Another point to remember is - COMPILATION and ERROR are different thing and COMPILATION WITH WARNING is a SUCCESSFUL COMPILATION.

Practice Question :
import java.util.*;
class Test {
public static void main(String [] args) {
Set vals = new TreeSet< String >();
vals.add("one");
vals.add(1);
vals.add("two");
System.out.println(vals);
}
}

What is true about the above question:
a)Does not Compile
b)Compiles with warning and prints output [one, 1, two]
c)Compiles without warning and prints output [one, 1, two]
d)Compiles with warning and throws exception at runtime
e)Compiles without warning and throws exception at runtime


Answer :
we know that it will compile with warning, so this removes option A and C. Another point about Set
is - Its ordered and sorted collection and String/Integer can not be sorted together. So answer is D.