Servlet interview Questions - 1




1- How many objects of a servlet is created?

Only one object at the time of first request by servlet or web container.

2- What is the life-cycle of a servlet?

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet: 
Servlet class is loaded.
Servlet instance is created.
init method is invoked.
service method is invoked.
destroy method is invoked.


As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all the tasks. When the web container invokes the destroy() method, it shifts to the end state.


1) Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is received by the web container.

2) Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in the servlet life cycle.

3) init method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is used to initialize the servlet. It is the life cycle method of the javax.servlet.Servlet interface. Syntax of the init method is given below:

public void init(ServletConfig config) throws ServletException

4) service method is invoked
The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below

public void service(ServletRequest request, ServletResponse response)

throws ServletException, IOException

5) destroy method is invoked
The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet interface is given below:

public void destroy()

3- What are the life-cycle methods for a servlet?

public void init(ServletConfig config)
It is invoked only once when first request comes for the servlet. It is used to initialize the servlet.

public void service(ServletRequest request,ServletResponse)throws ServletException,IOException

It is invoked at each request.The service() method is used to service the request.
public void destroy()

It is invoked only once when servlet is unloaded.

4- Who is responsible to create the object of servlet?

The web container or servlet container.

5- When servlet object is created?

At the time of first request.

6- What is difference between Get and Post method?

Get -
1) Limited amount of data can be sent because data is sent in header.
2) Not Secured because data is exposed in URL bar.
3) Can be bookmarked
4) Idempotent
5) It is more efficient and used than Post
Post
1) Large amount of data can be sent because data is sent in body.
2) Secured because data is not exposed in URL bar.
3) Cannot be bookmarked
4) Non-Idempotent
5) It is less efficient and used

7- What is difference between PrintWriter and ServletOutputStream?

PrintWriter is a character-stream class where as ServletOutputStream is a byte-stream class. The PrintWriter class can be used to write only character-based information whereas ServletOutputStream class can be used to write primitive values as well as character-based information.

8- What is difference between GenericServlet and HttpServlet?

The GenericServlet is protocol independent whereas HttpServlet is HTTP protocol specific. HttpServlet provides additional functionalities such as state management etc.

9- What is servlet collaboration?

When one servlet communicates to another servlet, it is known as servlet collaboration. There are many ways of servlet collaboration:
RequestDispacher interface
sendRedirect() method etc.

10- What is the purpose of RequestDispatcher Interface?

The RequestDispacher interface provides the facility of dispatching the request to another resource it may be html, servlet or jsp. This interceptor can also be used to include the content of antoher resource.

11- Can you call a jsp from the servlet?

Yes, one of the way is RequestDispatcher interface for example:
RequestDispatcher rd=request.getRequestDispatcher("/login.jsp");
rd.forward(request,response);

12- Difference between forward() method and sendRedirect() method ?

forward() method
1) forward() sends the same request to another resource.2) forward() method works at server side.
3) forward() method works within the server only.

sendRedirect() method
1) sendRedirect() method sends new request always because it uses the URL bar of the browser.
2) sendRedirect() method works at client side
3) sendRedirect() method works within and outside the server.

13- What is difference between ServletConfig and ServletContext?

The container creates object of ServletConfig for each servlet whereas object of ServletContext is created for each web application.

14- What is Session Tracking?

Session simply means a particular interval of time.
Session Tracking is a way to maintain state of an user.Http protocol is a stateless protocol.Each time user requests to the server, server treats the request as the new request.So we need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:


Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
Session Tracking Techniques
There are four techniques used in Session tracking:

Cookies
Hidden Form Field
URL Rewriting
HttpSession

15- What are Cookies?

There are 2 types of cookies in servlets.
Non-persistent cookie
Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout or signout.

Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.

16- What is difference between Cookies and HttpSession?

Cookie works at client side whereas HttpSession works at server side.

17- What is filter?

A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input validation etc.

18- How can we perform any action at the time of deploying the project?

By the help of ServletContextListener interface.

19- What is the disadvantage of cookies?

It will not work if cookie is disabled from the browser.

20- How can we upload the file to the server using servlet?

One of the way is by MultipartRequest class provided by third party.

21- What is load-on-startup in servlet?

The load-on-startup element of servlet in web.xml is used to load the servlet at the time of deploying the project or server start. So it saves time for the response of first request.

22- What if we pass negative value in load-on-startup?

It will not affect the container, now servlet will be loaded at first request.

23- What is war file?

A war (web archive) file specifies the web elements. A servlet or jsp project can be converted into a war file. Moving one servlet project from one place to another will be fast as it is combined into a single file.

24- How to create war file?
The war file can be created using jar tool found in jdk/bin directory. If you are using Eclipse or Netbeans IDE, you can export your project as a war file.
To create war file from console, you can write following code.

jar -cvf abc.war *

25- What are the annotations used in Servlet 3?

There are mainly 3 annotations used for the servlet.
@WebServlet : for servlet class.
@WebListener : for listener class.
@WebFilter : for filter class.

26- Which event is fired at the time of project deployment and undeployment?

ServletContextEvent.

27- Which event is fired at the time of session creation and destroy?

HttpSessionEvent.

28- Which event is fired at the time of setting, getting or removing attribute from application scope?

ServletContextAttributeEvent.

29- What is the use of welcome-file-list?

It is used to specify the welcome file for the project.


30- What is the use of attribute in servlets?
Attribute is a map object that can be used to set, get or remove in request, session or application scope. It is mainly used to share information between one servlet to another.


JDBC Interview Questions




1- What is JDBC?

Java JDBC is a java API to connect and execute query with the database. JDBC API uses jdbc drivers to connect with the database.




Why use JDBC- Before JDBC, ODBC API was the database API to connect and execute query with the database. But, ODBC API uses ODBC driver which is written in C language (i.e. platform dependent and unsecured). That is why Java has defined its own API (JDBC API) that uses JDBC drivers (written in Java language).

2- What is JDBC Driver?
JDBC Driver is a software component that enables java application to interact with the database.There are 4 types of JDBC drivers:
JDBC-ODBC bridge driver
Native-API driver (partially java driver)
Network Protocol driver (fully java driver)
Thin driver (fully java driver)

1) JDBC-ODBC bridge driver
The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls. This is now discouraged because of thin driver.


Advantages:
easy to use.
can be easily connected to any database.

Disadvantages:
Performance degraded because JDBC method call is converted into the ODBC function calls.
The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method calls into native calls of the database API. It is not written entirely in java. 



Advantage:
performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
The Native driver needs to be installed on the each client machine.
The Vendor client library needs to be installed on client machine.

3) Network Protocol driver
The Network Protocol driver uses middleware (application server) that converts JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully written in java.



Advantage:
No client side library is required because of application server that can perform many tasks like auditing, load balancing, logging etc.

Disadvantages:
Network support is required on client machine.
Requires database-specific coding to be done in the middle tier.
Maintenance of Network Protocol driver becomes costly because it requires database-specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it is known as thin driver. It is fully written in Java language.



Advantage:
Better performance than all other drivers.
No software is required at client side or server side.

Disadvantage:
Drivers depends on the Database.

3- What are the steps to connect to the database in java?
There are 5 steps to connect any java application with the database in java using JDBC. They are as follows:
Register the driver class
Creating connection
Creating statement
Executing queries
Closing connection

4- What are the JDBC API components?
The java.sql package contains interfaces and classes for JDBC API.

Interfaces:
Connection
Statement
PreparedStatement
ResultSet
ResultSetMetaData
DatabaseMetaData
CallableStatement etc.

Classes:
DriverManager
Blob
Clob
Types
SQLException etc.

5- What are the JDBC statements?
There are 3 JDBC statements.
Statement
PreparedStatement
CallableStatement

6- What is the difference between Statement and PreparedStatement interface?
In case of Statement, query is complied each time whereas in case of PreparedStatement, query is complied only once. So performance of PreparedStatement is better than Statement.

7- How can we execute stored procedures and functions?
By using Callable statement interface, we can execute procedures and functions.

8- What is the role of JDBC DriverManager class?
The DriverManager class manages the registered drivers. It can be used to register and unregister drivers. It provides factory method that returns the instance of Connection.

9- What does the JDBC Connection interface?
The Connection interface maintains a session with the database. It can be used for transaction management. It provides factory methods that returns the instance of Statement, PreparedStatement, CallableStatement and DatabaseMetaData.

10- What does the JDBC ResultSet interface?
The ResultSet object represents a row of a table. It can be used to change the cursor pointer and get the information from the database.

11- What does the JDBC ResultSetMetaData interface?
The ResultSetMetaData interface returns the information of table such as total number of columns, column name, column type etc.

12- What does the JDBC DatabaseMetaData interface?
The DatabaseMetaData interface returns the information of the database such as username, driver name, driver version, number of tables, number of views etc.

13- Which interface is responsible for transaction management in JDBC?
The Connection interface provides methods for transaction management such as commit(), rollback() etc.

14- What is batch processing and how to perform batch processing in JDBC?
By using batch processing technique in JDBC, we can execute multiple queries. It makes the performance fast.

15- How can we store and retrieve images from the database?
By using PreparedStatement interface, we can store and retrieve images.


Collection Framework Based Questions- 1



1.What is the difference between 
java.util.Iterator and java.util.ListIterator?
Iterator - Enables you to traverse through a collection in the forward direction only, for obtaining or removing elements
ListIterator - extends Iterator, and allows bidirectional traversal of list and also allows the modification of elements.

2. What is the difference between the HashMap and a Map? 

Map is an Interface which is part of Java collections framework. It stores data as key-value pairs.
Hashmap is class that implements that using hashing technique.

3. What does synchronized means in Hashtable context?
Synchronized means only one thread can modify a hash table at one point of time. Any thread before performing an update on a hashtable will have to acquire a lock on the object while others will wait for lock to be released. 
This adds an overhead which makes the Hashtable slower when compared to the Hashmap. You must choose a Hashmap when you want faster performance and choose the Hashtable when you want thread safety

4. Can we make a Hashmap thread safe? If so, how?
HashMap can be made thread safe by synchronizing it. Example: 
Map m = Collections.synchronizedMap(hashMap);

5. Why should I always use ArrayList over Vector?
You should choose an ArrayList over a Vector because – not all systems are multi-threaded and thread safety is not a mandatory requirement. In such cases, using a Vector is not only overkill but also adds a lot of overhead which might slow down system performance. Even if you are just iterating through a vector to display its contents, the lock on it still needs to be obtained which makes it much slower. So, choose the ArrayList over a Vector unless your system is multi-threaded.

6. What is an enumeration?
An enumeration is an interface containing methods for accessing the underlying data structure from which the enumeration is obtained. It is a construct which collection classes return when you request a collection of all the objects stored in the collection. It allows sequential access to all the elements stored in the collection.

7. What is the difference between Enumeration and Iterator?
The functionality of Enumeration interface is duplicated by the Iterator interface. Iterator has a remove() method while Enumeration doesn't. Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objects, whereas using Iterator we can manipulate the objects also like adding and removing the objects. So Enumeration is used whenever we want to make Collection objects as Read-only.

8. What is the difference between Sorting performance of Arrays.sort() vs Collections.sort()? Which one is faster? Which one to use and when?
Actually speaking, the underlying sorting algorithm & mechanism is the same in both cases. The only difference is type of input passed to them. Collections.sort() has a input as List so it does a conversion of the List to an array and vice versa which is an additional step while sorting. So this should be used when you are trying to sort a list. Arrays.sort is for arrays so the sorting is done directly on the array. So clearly it should be used when you have an array available with you and you want to sort it.

9. What is java.util.concurrent BlockingQueue? How it can be used?
The BlockingQueue is available since Java 1.5. Blocking Queue interface extends collection interface, which provides you the power of collections inside a queue. Blocking Queue is a type of Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element. A typical usage example would be based on a producer-consumer scenario. Note that a BlockingQueue can safely be used with multiple producers and multiple consumers.

10. What is the ArrayBlockingQueue?
Ans- ArrayBlockingQueue is a implementation of blocking queue with an array used to store the queued objects. The head of the queue is that element that has been on the queue the longest time. The tail of the queue is that element that has been on the queue the shortest time. New elements are inserted at the tail of the queue, and the queue retrieval operations obtain elements at the head of the queue. ArrayBlockingQueue requires you to specify the capacity of queue at the object construction time itself. Once created, the capacity cannot be increased. This is a classic "bounded buffer" (fixed size buffer), in which a fixed-sized array holds elements inserted by producers and extracted by consumers. Attempts to put an element to a full queue will result in the put operation blocking; attempts to retrieve an element from an empty queue will be blocked.

11. Why doesn't Map interface extend Collection?
Though the Map interface is part of collections framework, it does not extend collection interface. This was done as a design decision by Sun when the Collection framework was created. Think of it this way – A Map contains key-value pair data while a general collection contains only a bunch of values. If the map were to extend the collection class, what will we do with the keys and how will we link the values to their corresponding keys? Alternately, if the collection were to extend the Map, then, where will we go to get the key information for all the values that are already in the Collection?

Get the idea? For all practically purposes a Map is considered a collection because it contains a bunch of data in key-value pairs but it does not explicitly extend the collection interface.

12. Which implementation of the List 
interface (ArrayList or LinkedList) provides for the fastest insertion of a new element into the list? 
LinkedList.

If you are surprised about the answer you see above, read the question again “Fastest Insertion of a new element into the list”. The question is about inserts and not reading data. So, the linkedlist is faster. Because, when an element is inserted into the middle of the list in an ArrayList, the elements that follow the insertion point must be shifted to make room for the new element. The LinkedList is implemented using a doubly linked list; an insertion requires only the updating of the links at the point of insertion. Therefore, the LinkedList allows for fast insertions and deletions.

13. Which implementation of the List Interface (ArrayList or LinkedList) provides for faster reads during random access of data?
ArrayList implements the RandomAccess interface, and LinkedList does not. The commonly used ArrayList implementation uses primitive Object array for internal storage. Therefore an ArrayList is much faster than a LinkedList for random access, that is, when accessing arbitrary list elements using the get method. Note that the get method is implemented for LinkedLists, but it requires a sequential scan from the front or back of the list. This scan is very slow. For a LinkedList, there's no fast way to access the Nth element of the list.

14. Which implementation of the List Interface (ArrayList or LinkedList) uses more memory space for the same amount (number) of data?
Each element of a linked list (especially a doubly linked list) uses a bit more memory than its equivalent in array list, due to the need for next and previous pointers. So, the LinkedList uses more memory space when compared to an ArrayList of the same size

15. Where will you use ArrayList and Where will you use LinkedList?
If you frequently add elements to the beginning of the List or iterate over the List to delete elements from its interior, you should consider using LinkedList. These operations require constant-time in a LinkedList and linear-time (depending on the location of the object being added/removed) in an ArrayList.

If the purpose of your collection is to populate it once and read it multiple times from random locations in the list, then the ArrayList would be faster and a better choice because Positional access requires linear-time (depending on the location of the object being accessed) in a LinkedList and constant-time in an ArrayList.

In short - If you need to support random access, without inserting or removing elements from any place other than the end, then ArrayList offers the optimal collection. If, however, you need to frequently add and remove elements from the middle of the list and only access the list elements sequentially, then LinkedList offers the better implementation.

16.Why insertion and deletion in ArrayList is slow compared to LinkedList?
ArrayList internally uses and array to store the elements, when that array gets filled by inserting elements a new array of roughly 1.5 times the size of the original array is created and all the data of old array is copied to new array.

During deletion, all elements present in the array after the deleted elements have to be moved one step back to fill the space created by deletion. In linked list data is stored in nodes that have reference to the previous node and the next node so adding element is simple as creating the node an updating the next pointer on the last node and the previous pointer on the new node. Deletion in linked list is fast because it involves only updating the next pointer in the node before the deleted node and updating the previous pointer in the node after the deleted node.

17.How do you traverse through a collection using its Iterator?
To use an iterator to traverse through the contents of a collection, follow these steps:
1. Obtain an iterator to the start of the collection by calling the collection’s iterator() method.
2. Set up a loop that makes a call to hasNext(). Have the loop iterate as long as hasNext() returns true.
3. Within the loop, obtain each element by calling next().

18.How do you remove elements during Iteration?
Iterator also has a method remove() when remove is called, the current element in the iteration is deleted.

19.What are the main implementations of the List interface?
The main implementations of the List interface are as follows :
ArrayList : Resizable-array implementation of the List interface. The best all-around implementation of the List interface.
Vector : Synchronized resizable-array implementation of the List interface with additional "legacy methods."
LinkedList : Doubly-linked list implementation of the List interface. May provide better performance than the ArrayList implementation if elements are frequently inserted or deleted within the list. Useful for queues and double-ended queues (deques).

20.What are the advantages of ArrayList over arrays?
Some of the advantages ArrayList has over arrays are:
It can grow dynamically
It provides more powerful insertion and search mechanisms than arrays.

21.How to obtain Array from an ArrayList?
Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
arrayList.add(obj1);
arrayList.add(obj2);
arrayList.add(obj3);

Object a[] = arrayList.toArray();

22.Why are Iterators returned by ArrayList called Fail Fast?
Because, if list is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove or add methods, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future. So, it is considered fail fast.

23.How do you sort an ArrayList (or any list) of user-defined objects?
Create an implementation of the java.lang.Comparable interface that knows how to order your objects and pass it to java.util.Collections.sort(List, Comparator).

24.What is the Comparable interface?
The Comparable interface is used to sort collections and arrays of objects using the Collections.sort() and java.utils.Arrays.sort() methods respectively. The objects of the class implementing the Comparable interface can be ordered.
The Comparable interface in the generic form is written as follows:
interface Comparable
where T is the name of the type parameter.

All classes implementing the Comparable interface must implement the compareTo() method that has the return type as an integer. The signature of the compareTo() method is as follows:

int i = object1.compareTo(object2)

If object1 < object2: The value of i returned will be negative.

If object1 > object2: The value of i returned will be positive.

If object1 = object2: The value of i returned will be zero.

25.What are the differences between the Comparable and Comparator interfaces?
The Comparable uses the compareTo() method while the Comparator uses the compare() method
You need to modify the class whose instance is going to be sorted and add code corresponding to the Comparable implementation. Whereas, for the Comparator, you can have a separate class that has the sort logic/code.
In case of Comparable, Only one sort sequence can be created while Comparator can have multiple sort sequences.



OOPs based interview questions




1- What are different oops concept in java?
Object means a real word entity such as pen, chair, table etc. Object-Oriented Programming is a methodology or paradigm to design a program using classes and objects.



It simplifies the software development and maintenance by providing some concepts:
Object
Class
Inheritance
Polymorphism
Abstraction
Encapsulation

2- What is polymorphism?
Polymorphism in java is a concept by which we can perform a single action by different ways. Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many and "morphs" means forms. So polymorphism means many forms.

There are two types of polymorphism in java: compile time polymorphism and runtime polymorphism. We can perform polymorphism in java by method overloading and method overriding.

If you overload static method in java, it is the example of compile time polymorphism. Here, we will focus on runtime polymorphism in java.

1- Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden method is resolved at runtime rather than compile-time.
2- Compile time Polymorohism - If a class have multiple methods by same name but different parameters, it is known as Method Overloading. 

3- What is multiple inheritance and does java support?
If a child class inherits the property from multiple parent classes is known as multiple inheritance. Java does not allow to extend multiple classes, to overcome this problem it allows to implement multiple Interfaces.

4- What is an abstraction ?
Hiding internal details and showing functionality is known as abstraction. For example: phone call, we don't know the internal processing. In java, we use abstract class and interface to achieve abstraction.

5- What is Encapsulation?
Binding (or wrapping) code and data together into a single unit is known as encapsulation. For example: capsule, it is wrapped with different medicines.

A java class is the example of encapsulation. Java bean is the fully encapsulated class because all the data members are private here.

6- What is Association?
It represents a relationship between two or more objects where all objects have their own lifecycle and there is no owner. The name of an association specifies the nature of relationship between objects. This is represented by a solid line.



Let’s take an example of relationship between Teacher and Student. Multiple students can associate with a single teacher and a single student can associate with multiple teachers. But there is no ownership between the objects and both have their own lifecycle. Both can be created and deleted independently.



8- What is Aggregation?
It is a specialized form of Association where all object have their own lifecycle but there is ownership. This represents “whole-part or a-part-of” relationship. This is represented by a hollow diamond followed by a line.



Let’s take an example of relationship between Department and Teacher. A Teacher may belongs to multiple departments. Hence Teacher is a part of multiple departments. But if we delete a Department, Teacher Object will not destroy.







Top Java Frequently Asked Questions



1. Can you write a Java class that could be used both as an applet as well as an application?
Yes. Just, add a main() method to the applet.

2. Explain the usage of Java packages.
This is a way to organize files when a project consists of multiple modules. It also helps resolve naming conflicts when different packages have classes with the same names. Packages access level also allows you to protect data from being used by the non-authorized classes.

3. If a class is located in a package, what do you need to change in the OS environment to be able to use it?
You need to add a directory or a jar file that contains the package directories to the CLASSPATH environment variable. Once the class is available in the CLASSPATH, any other Java program can use it.

4. What's the difference between J2SDK 1.5 and J2SDK 5.0?
There's no difference, Sun Microsystems just re-branded this version.

5. What are the static fields & static Methods ?
If a field or method defined as a static, there is only one copy for entire class, rather than one copy for each instance of class. static method cannot accecss non-static field or call non-static methods

6. How are Observer and Observable used?
Objects that subclass the Observable class maintain a list of observers. When an Observable object is updated it invokes the update() method of each of its observers to notify the observers that it has changed state. The Observer interface is implemented by objects that observe Observable objects.

7. Is null a keyword?
No, the null value is not a keyword.

8. Which characters may be used as the second character of an identifier, but not as the first character of an identifier?
The digits 0 through 9 may not be used as the first character of an identifier but they may be used after the first character of an identifier.

9. How does Java handle integer overflows and underflows?
It uses those low order bytes of the result that can fit into the size of the type allowed by the operation.

10. What is the difference between the >> and >>> operators?
The >> operator carries the sign bit when shifting right. The >>> zero-fills bits that have been shifted out.

11. How many bits are used to represent Unicode, ASCII, UTF-16, and UTF-8 characters?
Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

12. Is sizeof a keyword?
No, the sizeof operator is not a keyword.

13. What restrictions are placed on the location of a package statement within a source code file?
A package statement must appear as the first line in a source code file (excluding blank lines and comments). It cannot appear anywhere else in a source code file.

14. What value does readLine() return when it has reached the end of a file?
The readLine() method returns null when it has reached the end of a file.

15. What is a native method?
A native method is a method that is implemented in a language other than Java.

16. Can a for statement loop indefinitely?
Yes, a for statement can loop indefinitely.
Ex:
for(;;) ;

17. What are order of precedence and associativity, and how are they used?
Order of precedence determines the order in which operators are evaluated in expressions. Associatity determines whether an expression is evaluated left-to-right or right-to-left

18. What is the range of the short type?

The range of the short data type is -(2^15) to 2^15 - 1.

19. What is the range of the char type?
The range of the char type is 0 to 2^16 - 1.

20. What is the difference between the Boolean & operator and the && operator?
&& is a short-circuit AND operator - i.e., The second condition will be evaluated only if the first condition is true. If the first condition is true, the system does not waste its time executing the second condition because, the overall output is going to be false because of the one failed condition.

& operator is a regular AND operator - i.e., Both conditions will be evaluated always.

21. What is the GregorianCalendar class?
The GregorianCalendar provides support for traditional Western calendars.

22. What is the purpose of the Runtime class?
The purpose of the Runtime class is to provide access to the Java runtime system.

23. What is the argument type of a program's main() method?
A program's main() method takes an argument of the String[] type. (A String Array)

24. Which Java operator is right associative?
The = operator is right associative.

25. What is the Locale class?
This class is used in conjunction with DateFormat and NumberFormat to format dates, numbers and currency for specific locales. With the help of the Locale class you’ll be able to convert a date like “10/10/2005” to “Segunda-feira, 10 de Outubro de 2005” in no time. If you want to manipulate dates without producing formatted output, you can use the Locale class directly with the Calendar class

26. Can a double value be cast to a byte?
Yes, a double value can be cast to a byte. But, it will result in loss of precision.

27. What is the difference between a break statement and a continue statement?
A break statement results in the termination of the statement to which it applies (switch, for, do, or while). A continue statement is used to end the current loop iteration and return control to the beginning of the loop.

28. How are commas used in the intialization and iterationparts of a for statement?
Commas are used to separate multiple statements within the initialization and iteration parts of a for statement.

29. How are Java source code files named?
A Java source code file takes the name of a public class or interface that is defined within the file. A source code file may contain at most one public class or interface. If a public class or interface is defined within a source code file, then the source code file must take the name of the public class or interface. If no public class or interface is defined within a source code file, then the file can take on a name that is different than its classes and interfaces. Source code files use the .java extension.

30. What value does read() return when it has reached the end of a file?
The read() method returns -1 when it has reached the end of a file.

31. Can a Byte object be cast to a double value?
No, an object cannot be cast to a primitive value.

32. What is the Dictionary class?
The Dictionary class provides the capability to store key-value pairs. It is the predecessor to the current day HashMap and Hashtable.

33. What is the % operator?
It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

34. What is the difference between the Font and FontMetrics classes?
The FontMetrics class is used to define implementation-specific properties, such as ascent and descent, of a Font object.

35. How is rounding performed under integer division?

The fractional part of the result is truncated. This is known as rounding toward zero.

36. What is the difference between the Reader/Writer class hierarchy and the InputStream/OutputStream class hierarchy?
The Reader/Writer class hierarchy is character-oriented, and the InputStream/OutputStream class hierarchy is byte-oriented.

37. What is the SimpleTimeZone class?

The SimpleTimeZone class provides support for a Gregorian calendar. You can use it to manipulate dates & times.

38. For which statements does it make sense to use a label?
The only statements for which it makes sense to use a label are those statements that can enclose a break or continue statement.

39. What is the purpose of the System class?
The purpose of the System class is to provide access to system resources.

40. Is &&= a valid Java operator?
No, it is not a valid operator.

41. Name the eight primitive Java data types.
The eight primitive types are byte, char, short, int, long, float, double, and boolean.

42. What restrictions are placed on the values of each case of a switch statement?
During compilation, the values of each case of a switch statement must evaluate to a value that can be promoted to an int value.

43. What is the difference between a while statement and a do statement?

A while statement checks at the beginning of a loop to see whether the next loop iteration should occur. A do statement checks at the end of a loop to see whether the next iteration of a loop should occur. The do statement will always execute the body of a loop at least once.


44. What is the difference between static and non-static variables?
A static variable is associated with the class as a whole rather than with specific instances or objects of a class. Non-static variables take on unique values with each object instance.

45. What is the purpose of the File class?
The File class is used to create objects that provide access to the files and directories of a local file system.

46. Which Math method is used to calculate the absolute value of a number?
The abs() method is used to calculate absolute values.

47. Which non-Unicode letter characters may be used as the first character of an identifier?
The non-Unicode letter characters $ and _ may appear as the first character of an identifier

48. What restrictions are placed on method overloading?
Two methods may not have the same name and argument list but different return types.

49. What is the return type of a program's main() method?
A program's main() method has a void return type. i.e., the main method does not return anything.

50. What an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another.



How can you determine if String has all Unique Characters.



public class DetermineDuplicate 
{
    public static void main(String args[]) 
    {
        String s = "Umesh Kushwaha";
        int check = 0;
        for (int i = 0; i < s.length(); i++) 
        {
            for (int j = 0; j < s.length(); j++) 
            {
                if (s.charAt(i) == s.charAt(j) && i != j)
                {
                    check = 1;
                    break;
                }
            }
        }
        if (check == 1)
        {
            System.out.println("String does not have all unique character");
        } else 
        {
            System.out.println("String have all unique character");
        }
    }
}


Output: String does not have all unique character