個人資料
  • 博客訪問:
正文

Found something interesting for java developer

(2007-10-07 21:11:05) 下一個

Credit:AnupSabbi.com


Core Java interview questions

Declarations

Q: Can there be more than one public class per source code file?
A: No

Q: Can a file have more than one nonpublic class?
A: Yes

Q: If there is a public class in a file, does the name of the file match the name of the public class?
A: Yes

Q: Can files with no public classes have a name that does not match any of the classes in the file?
A: Yes

Q: What are final classes? Name some in the Java core libraries.
A: Final classes can't be subclassed. Ex: java.lang.String, java.lang.Boolean, java.lang.Double

Q: What are final methods?
A: Final methods cannot be overridden in subclasses.

Q: What are synchronized methods?
A: Synchronized methods can be accessed by only one thread at a time.

Q: What are abstract classes?
A: An abstract class can never be instantiated. Even if a single method is abstract, the whole class must be declared abstract.

Q: What is the difference between an interface and an abstract class?
A: All methods in an interface are abstract, where as an abstract class can have both abstract and non-abstract methods.

Q: Can you define variables in an interface?
A: Yes, all variables defined in a interface must be public, static and final. In other words only constants.

Q: What are instance variables?
A: Instance variables are defined inside the class, but outside of any method.

Q: What are local variables?
A: Local variables are variables declared within a method. Local variables are also called Automatic, Stack or Method variables.

Q: What are final variables?
A: Once a final variable has been initialized, it can't be reinitialized.

Q: What are transient variables?
A: Transient variables are ignored while the object containing it is being serialized.

Serialization

Q:What interface must an object implement before it can be written to a stream as an object?
A: Serializable

Q: What are the methods involved in serialization?
A: ObjectOutputStream.writeObject(); and ObjectInputStream.readObject();

Q: What methods need to be implemented by a class that extends Serializable interface?
A: Serializable is a marker interface. It has no methods to implement.

Q: What are the signatures of the methods that must be implemented in your class if it needs customized serialization?
A:private void writeObject(ObjectOutputStream os) and private void readObject(ObjectInputStream is)

Q: Are Static variables saved during serailization?
A: No, because they are class variables and do not belong to the object.

Q: What is the significance of serialVersionUID?
A: When deserializing an object, Java must establish that the incomming data is sufficiently compatible with the local class definition. This is accomplished by comparing stream-unique identifiers (SUIDs) of the incomming and local class definitions. If the two SUIDs do not match, deserialization fails. If you don't do anything, the SUID is computed as a hash of various class elements. But, it is also possible to take control of this value by declaring the following class field: private static final long serialVersionUID = LONG_VALUE;

Strings

Q: What is the difference between String and StringBuffer?
A: String objects are immutable while StringBuffer objects are not. StringBuffer performs well in applications involving lot of String modifications.

Q: What is "String constant pool"?
A: "String constant pool" is a special area of memory set aside by JVM. When ever the complier encounters a new String, it checks the pool for a match. If a match is found, it points the reference to the String in the pool and no new object is created. This make Java more memory efficient.

Collections

Q: While iterating through a Collection using an Iterator, Can the Collection be modified directly without effecting the behaviour of the Iterator?
A: The only defined behavior is to delete objects from the Collection using Iterator.remove().

Hibernate Interview Questions

Q: What is Hibernate?
A: Hibernate is a java-based Object/relational mapping(ORM) tool.

Q: What are ORM tools?
A: ORM tools provide automated solutions for the Object/relational paradigm mismatch problem, using metadata that describes the mapping between the objects and the database.

Q: What is Object/relational paradigm mismatch?
A: Object-Oriented paradigm is based on software engineering principles, whereas relational paradigm on mathematical principles. Object-oriented technology supports the building of applications out of networks of objects with both data and behavior. Relational technology supports the storage of data in tables and manipulation of that data using data manipulation language (DML). Because the underlying paradigms are different the two technologies do not work seamlessly, hence the name Object/relational paradigm mismatch.

Q: What role does the Session interface play in Hibernate?
A: The Session is a persistence manager that manages operation like storing and retrieving objects. Instances of Session are inexpensive to create and destroy. They are not threadsafe.

Q: What is SessionFactory interface?
A: The application obtains Session instances from a SessionFactory. SessionFactory instances are not lightweight and typically one instance is created for the whole application. If the application accesses multiple databases, it needs one per database

Q: What is Configuration interface?
A: The application uses a Configuration instance to specify the location of mapping documents and Hibernate-specific properties and then creates the SessionFactory.

Q: What is the naming convention for Hibernate XML mapping file extensions?
A: .hbm.xml

Q: What are the most common methods of configuring Hibernate?
A: 1. By placing hibernate.properties file in the classpath.
2. Including elements in hibernate.cfg.xml in the classpath.

Q: How can the mapping files be configured in Hibernate?
A: 1. Mapping files can be added to Configuration in the application code or,
2. They can be configured in hibernate.cfg.xml using the elements.

Q: What happens when both hibernate.properties and hibernate.cfg.xml are in the classpath?
A: The settings of the XML configuration file will override the settings used in the properties.

Q: Since SessionFactory instances are not lightweight, where is the single created instance placed in J2EE environments?
A: Usually it is bound to JNDI, it will bind itself automatically if hibernate.session_factory_name is set to the name of directory node.

Q: How to set Hibernate to log all generated SQL to the console?
A: By setting the hibernate.show_sql property to true.

Q: In hibernate, what interfaces/classes must the persistent classes (classes that are mapped to database tables) implement/extend?
A: NONE, they can be regular POJOs.

Q: Does hibernate require persistent classes to implement Serializable?
A: Hibernate doesn't require that persistent classes implement Serializable. However, when objects are stored in an HttpSession or passed by value using RMI, serialization is necessary.

Q: What methods must the persistent classes implement in Hibernate?
A: Since Hibernate instantiates persistent classes using Constructor.newInstance(), it requires a constructor with no arguments for every persistent class. And getter and setter methods for all the instance variables.

Q: How can Hibernate be configured to access a instance variable directly and not through a setter method?
A: By mapping the property with access="field" in Hibernate metadata. This forces hibernate to bypass the setter method and access the instance variable directly while initializing a newly loaded object.

Q: What is dirty checking in Hibernate?
A: Hibernate automatically detects object state changes in order to synchronize the updated state with the database, this is called dirty checking. An important note here is, Hibernate will compare objects by value, except for Collections, which are compared by identity. For this reason you should return exactly the same collection instance as Hibernate passed to the setter method to prevent unnecessary database updates.

Q: What is the root level element in a hibernate mapping file?
A:

Q: Is it possible to declare mappings for multiple classes in one mapping file?
A: Yes, by using multiple elements. But, the recommended practice is to use one mapping file per persistent class.

Q: How are the individual properties mapped to different table columns?
A: By using multiple elements inside the element.

Q: What are derived properties?
A: The properties that are not mapped to a column, but calculated at runtime by evaluation of an expression are called derived properties. The expression can be defined using the formula attribute of the element.

Q: How can you make a property be read from the database but not modified in anyway (make it immutable)?
A: By using the insert="false" and update="false" attributes.

Q: How can a whole class be mapped as immutable?
A: By using the mutable="false" attribute in the class mapping.

Q: What is the use of dynamic-insert and dynamic-update attributes in a class mapping?
A: They tell hibernate whether to include unmodified properties in SQL INSERT and SQL UPDATE.

Q: How do you achieve table-per-class hierarchy while mapping classes in Hibernate?
A: By using several elements one for each sub-class inside the element. The class element can in turn contain other elements.

Q: How do you achieve table-per-subclass while mapping classes in Hibernate?
A: By using element inside the element. A element may contain other elements.

Q: Does hibernate allow mixing table-per-class hierarchy and table-per-subclass strategies?
A: No, you cannot have a inside and vice versa.

*******************************************
Essential Topics for Java Developers

Below is a list of concepts and technologies that every Java Web Developer must be familiar with. I update this list very often and provide you with links and references.

Web Programming

Core Java

  • Object Oriented concepts
  • Strings
  • Collections API
  • Classloaders
  • Concurrency (threading, locking, deadlocks, java.util.concurrent package, memory model)
  • Performance (Profiling)
  • Debugging/Monitoring
  • Object Serialization
  • Object identity (hashcode, equals, practical implications on collections and ORM)
  • Java Security
  • Reflection and Introspection (Dynamic proxies)
  • What’s new in Java 5
    • Implementing generics
    • Annotations
  • What's new in Java 6
    • scripting language support
  • Reference Books
    • Effective Java
    • Java Puzzlers

Servlets and JSPs

  • Velocity

Struts

  • Struts 2 Web Toolkit

Ajax

  • Google Web Toolkit
  • DWR

Databases

  • SQL
  • JDBC

EJB

  • JNDI interfacing with LDAP
  • What’s new in EJB 3

    JMS & Messaging

    XML

    • SAX
    • DOM
    • XPath

    Hibernate

    Spring Framework

    Web Services

    • Service Oriented Architecture

    Business Rules and Rule Engines

    Tools

    • Eclipse
    • Apache Tomcat
    • JBoss
    • Junit
    • ANT
    • Cruise Control - continuous integration tool

      Key Java Open Source Projects

      Current Trends

      • XP Methodologies
      • Agile Programming
      • Refactoring
      • Aspect Oriented programming
        • AspectJ

      Architecture and design patterns

      Ruby

      • JRuby and other scripting languages in the JVM, Groovy and Grails
      • Ruby on rails

      ***************************************

      URL data encryption:

      Sometimes we would like to have the user not see some of the information in the url, especially while sending data using the GET method. For example if you are doing in a jsp, something like

      Then the users browser will be ponting to something like:

      http://localhost/urlencryption/jsp/process.jsp?id=101&item=22&conf=12234

      here users will be able to see the "id", "item" and "conf" details clearly in the URL. What if some of this information is sequential in the database, some curious users or some hackers can modify this data and might access sensitive data which they are not supposed to see. In such cases it would be helpfull to encrypt the parameters in the query string. Now lets modify the jsp as below:

      The helper class code is:

      import java.io.IOException;import java.io.UnsupportedEncodingException;import java.net.URLDecoder;import java.net.URLEncoder;import java.security.InvalidKeyException;import java.security.NoSuchAlgorithmException;import java.security.spec.InvalidKeySpecException;import java.security.spec.KeySpec;import javax.crypto.BadPaddingException;import javax.crypto.Cipher;import javax.crypto.IllegalBlockSizeException;import javax.crypto.NoSuchPaddingException;import javax.crypto.SecretKey;import javax.crypto.SecretKeyFactory;import javax.crypto.spec.DESKeySpec;public class EncryptionHelper {    private static final String PASS_PHRASE = "passphrase";       public static String encrypt(String msg){        try {            KeySpec keySpec = new DESKeySpec(PASS_PHRASE.getBytes());            SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);            Cipher ecipher = Cipher.getInstance(key.getAlgorithm());            ecipher.init(Cipher.ENCRYPT_MODE, key);            //Encode the string into bytes using utf-8            byte[] utf8 = msg.getBytes("UTF8");            //Encrypt            byte[] enc = ecipher.doFinal(utf8);            //Encode bytes to base64 to get a string            return new sun.misc.BASE64Encoder().encode(enc);        } catch (InvalidKeyException e) {            e.printStackTrace();        } catch (InvalidKeySpecException e) {            e.printStackTrace();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (NoSuchPaddingException e) {            e.printStackTrace();        } catch (IllegalStateException e) {            e.printStackTrace();        } catch (IllegalBlockSizeException e) {            e.printStackTrace();        } catch (BadPaddingException e) {            e.printStackTrace();        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return null;    }       public static String decrypt(String msg){        try {            KeySpec keySpec = new DESKeySpec(PASS_PHRASE.getBytes());            SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);            Cipher decipher = Cipher.getInstance(key.getAlgorithm());            decipher.init(Cipher.DECRYPT_MODE, key);            // Decode base64 to get bytes            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(msg);            //Decrypt            byte[] utf8 = decipher.doFinal(dec);            //Decode using utf-8            return new String(utf8, "UTF8");        } catch (InvalidKeyException e) {            e.printStackTrace();        } catch (InvalidKeySpecException e) {            e.printStackTrace();        } catch (NoSuchAlgorithmException e) {            e.printStackTrace();        } catch (NoSuchPaddingException e) {            e.printStackTrace();        } catch (IOException e) {            e.printStackTrace();        } catch (IllegalStateException e) {            e.printStackTrace();        } catch (IllegalBlockSizeException e) {            e.printStackTrace();        } catch (BadPaddingException e) {            e.printStackTrace();        }        return null;    }       public static String encodeURL(String url){        try {            return URLEncoder.encode(url,"UTF-8");        } catch (UnsupportedEncodingException e) {            e.printStackTrace();        }        return null;    }}

      now the user's browser will show some obscured data like:

      http://localhost/urlencryption/jsp/process.jsp?data=6ITbVZYPZNWDf%2F3J0lGo%2FJYXYr%2BdhKMHAcqjmqtfJ%2BA%3D

      Now in the process.jsp we can get the original parameters by decoding, decrypting and parsing the decrypted string in the data parameter. The jsp decrypting the contents of data parameter will look something like:

      Similarly, if the encrypted data can be decrypted and accessed in a servlet. A sample implementation of the doGet() method is shown below:

      public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        String data = request.getParameter("data");        System.out.println("data: "+data);        String decodedData = URLDecoder.decode(data);        System.out.println("decodedData: "+decodedData);        System.out.println("Decrypted data: "+EncryptionHelper.decrypt(data));    }

      References:

    • Java Cryptography Extension (JCE)
    • *************************************

      [ 打印 ]
      閱讀 ()評論 (0)
      評論
      目前還沒有任何評論
      登錄後才可評論.