Friday 13 December 2013

Basic Core Java Interview Questions




1.           What are Web Services?
Web services are business logic components which provide functionality via. Internet using standard protocols such as HTTP. It is created using Soap or Rest. For E.g. in google search page we got results like feeds, advertisement , news etc.,   from multiple sites, it is by web services which enables various websites to talk to each other and share data between them.

2.           Differences between Soap vs. Rest.
SOAP - "Simple Object Access Protocol"
·        SOAP is a method of transferring messages, or small amounts of information, over the Internet. SOAP messages are formatted in XML and are typically sent using HTTP (hypertext transfer protocol).

Rest - Representational state transfer
·        Rest is a simple way of sending and receiving data between client and server and it doesn't have very many standards defined. You can send and receive data as JSON, XML or even plain text. Its light weighted compared to SOAP.

3.           How to create a DB connection.
Five steps to query a database:
1.   Load the driver
2.   Get connection
3.   Query the database
4.   Process the result set
5.   Close connection

4.           Differences between prepared statement and callable statement.
Prepared Statement – Execute a precompiled SQL with/without input parameters.
Callable Statements – Execute a call to database stored procedure.

5.           Difference between Application server and Web server.

Application server
Web server
Web server serves HTTP content
Application server serves HTTP, RMI/RPC etc.
Webserver is suitable for static content.
Application server supports dynamic content also.
Webserver does not contain inbuilt web server component.
Application server contains inbuilt web server component.
IIS, Jetty, Tomcat, Apache etc... Is webserver
SharePoint, JBOSS, EJB, WAS etc… Is application server.
Webserver does not add any functionality
Application server adds functionality
To applications.

6.           Difference between System. Out and System. Err.  
System. Err is a PrintStream. System. Err works like System. Out except it is normally only used to output error texts. Some programs (like Eclipse) will show the output to System. Err in red text, to make it more obvious that it is error text.    

7.           Difference between http and https.
         HTTP 
HTTPS
URL begins with “http://”
URL begins with “https://”
It uses port 80 for communication.
It uses port 443 for communication
Unsecured
Secured
Operates at Application Layer
Operates at Transport Layer
No encryption
Encryption is present
No certificates required
Certificates required

8.           What is Key Store?
Java Key Store (JKS) is a repository of security certificates, either authorization certificates or public key certificates - used for instance in SSL encryption.

9.           Write a Java program to print Fibonacci series.

10.        Difference between Static and Non-Static variable/Method.
Static
Non-static
Static members are one per class
Non-static Variables are 1 per instance.
Static members are accessed by their class name which encapsulates them
Non-static members are accessed by object reference.
Static methods can be accessed directly from the class
Non-static methods (or instance methods as I like to call them) have to be accessed from an instance.
static members can't use non-static methods without instantiating an objet
Non-static members can use static members directly.
static constructor is used to initialize static fields
Non-static fields normal instance constructor is used.

11.        What is immutability in java?
Once created the objects state cannot be changed .E.g. string

12.        How to create read only values in java.
Using final keyword
Final int a=4;

13.        Difference between String and StringBuffer.
String
StringBuffer
String is used to manipulate character strings that cannot be changed (read-only and immutable).
StringBuffer is used to represent characters that can be modified.
String is slow when performing concatenations because concatenating a string created new object.
StringBuffer is faster when performing concatenations.
String is immutable
StringBuffer is mutable
String is not synchronized
StringBuffer is synchronized

14.        Difference between Hashmap and Hashtable.
·        Hashtable is synchronized but Hashmap is not.
·        Hashtable can't contain null values but Hashmap permits null values.

15.        Difference between Iterator and Enumeration.
·        Iterator has remove () method but Enumeration do not have.
·        Iterator is used to Add and remove object, enumeration is used to traverse and fetch objects.
·        Iterator is used to manipulate text but Enumeration is used for read-only access.

16.        Define Class-object relationship.
Object - Objects have states and behaviors. Example: A dog has states-color, name, and breed as well as behaviors -wagging, barking, and eating. An object is an instance of a class.
Class - A class can be defined as a template/ blue print that describe the behaviors/states that object of its type support.
Class is a blueprint while objects are actual objects existing in real word.

17.        What  to test while testing Client-server application.
·        Performance
·        Load
·        Integration between multiple components
·        MUT
·        SOAK testing
·        Multiple clients for same server

18.        How to Read/write excel file in Java.

19.        Difference between Method Overloading and Overriding.

 Method Overloading 
 Method Overriding
Arguments Must change
Arguments  Must not change
Return type Can change
Return type  Can’t change except for covariant returns
Exceptions Can change
Exceptions  Can reduce or eliminate. Must not throw new or broader checked exceptions
Access Can change
Access  Must not make more restrictive (can be less restrictive)
Invocation  Reference type determines which overloaded version is selected. Happens at compile time.
Invocation  Object type determines which method is selected. Happens at runtime

20.  Write a java program to count number of unique words separated by comma (,) and their occurrence from text file.

21.        Difference between int & INTEGER.
int is a primitive type. Variables of type int store the actual binary value for the integer you want to represent. int.parseInt("1") doesn't make sense because int is not a class and therefore doesn't have any methods.

Integer is a class, no different from any other in the Java language. Variables of type Integer store a reference to Integer objects, just as with any other reference type. Integer.parseInt("1") is calling the static method parseInt from class Integer (note that this method actually returns an int and not an Integer).

int type Declaration:
 int count;
·        count is a primitive
·        count stores 32 bits of information (in the range Integer.MIN_VALUE to Integer.MAX_VALUE)
·        Literal integers (e.g. 123 or 0x7b) are of type int

Integer type Declaration:
 Integer count2;
·        count2 is an object reference
·        count2 points to an object of type java.lang.Integer (or to null)
·        The object count2 points at has an int member variable as described above.

To be more specific, Integer is a class with a single field of type int. This class is used where you need an int to be treated like any other object.


22.        Difference between abstract class and interface.
Abstract Class
Interfaces
An abstract class can provide complete, default code and/or just the details that have to be overridden.
An interface cannot provide any code at all, just the signature.
In case of abstract class, a class may extend only one abstract class.
A Class may implement several interfaces.
An abstract class can have non-abstract methods.
All methods of an Interface are abstract.
An abstract class can have instance variables.
An Interface cannot have instance variables.
An abstract class can have any visibility: public, private, protected.
An Interface visibility must be public (or) none.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
An abstract class can contain constructors.
An Interface cannot contain constructors.
Abstract classes are fast.
Interfaces are slow as it requires extra indirection to find corresponding method in the actual class.

23.        Difference between Serialization and synchronization.
·        Serialization is a process by which object instance is converted into stream of bytes.
·        Synchronization ensures that object data is into accessed by multiple threads at the same time.

24.        Difference between sleep and wait. Which is better?
·        Wait is better than sleep.
·        Sleep cannot be waken but Wait can be woken using notify method.
·        Sleeps do not release lock but Wait releases lock.

25.        Difference between Array and ArrayList.
·        Array size is fixed at the time of declaration. We can’t modify it.
·        ArrayList size is not fixed at the time of declaration. We can change its contents.

26.        Difference between Set and Map.
·        Set – It is also an interface to represent linear collection with no duplicates. Order of insertion is not maintained. Example:- Harshest, Tree Set.
·        Map – It represents an indexed collection i.e. key-value pairs. Example: - Hashmap.

27.        What is AJAX?
·        AJAX stands for Asynchronous JavaScript and XML. AJAX is a new technique for creating better, faster, and more interactive web applications with the help of XML, HTML, CSS and Java Script.
·        Ajax uses XHTML for content and CSS for presentation, as well as the Document Object Model and JavaScript for dynamic content display.
·        Conventional web application transmit information to and from the sever using synchronous requests. This means you fill out a form, hit submit, and get directed to a new page with new information from the server.
·        With AJAX when submit is pressed, JavaScript will make a request to the server, interpret the results and update the current screen. In the purest sense, the user would never know that anything was even transmitted to the server.
·        XML is commonly used as the format for receiving server data, although any format, including plain text, can be used.
·        AJAX is a web browser technology independent of web server software.
·        A user can continue to use the application while the client program requests information from the server in the background
·        Intuitive and natural user interaction.
·        No clicking required only Mouse movement is a sufficient event trigger.
·        Data-driven as opposed to page-driven

28.        Write a java program for swapping of two numbers

29.        What is final modifier?
The final modifier keyword makes that the programmer cannot change the value anymore. The actual meaning depends on whether it is applied to a class, a variable, or a method.
·         Final Methods- A final method cannot be overridden by subclasses.
·         Final Variables- A final variable cannot be changed once it is initialized.
·         Final Classes- A final class cannot have subclasses.

30.        Write a java program for factorial of a given number.

31.        What is the different between inheritance and interface?
·        Inheritance:
In java classes can be derived from classes. Basically if you need to create a new class and here is already a class that has some of the code you require, then it is possible to derive your new class from the already existing code. This concept allows you to reuse the fields and methods of the existing class without having to rewrite the code in a new class. In this scenario the existing class is called the super class and the derived class is called the subclass.

·        Interface:
In Java language an interface can be defined as a contract between objects on how to communicate with each other. Interfaces play a vital role when it comes to the concept of inheritance. An interface defines the methods, a deriving class (subclass) should use. But the implementation of the methods is totally up to the subclass.

32.        Write a Program  to search in pdf.

33.        What are Access Modifiers in Java?
·        Default: A variable or method declared without any access control modifier is available to any other class in the same package
·        Public: A class, method, constructor, interface etc. declared public can be accessed from any other class
·        Protected Variables methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class
·        Private: Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself.
Non-access Modifiers: final, abstract.

34.        What is the difference between abstraction and encapsulation?
Encapsulation: - it means binding up of data and methods it means the concept of class in which we put together the data members and methods or function members.

Abstraction: - it means that hiding the background details which are not useful to the user for it we use normally private or protected access specifier by it data is not let free to move around the system.
1) Abstraction is implemented in Java using interface and abstract class while Encapsulation is implemented using private, package-private and protected access modifier.
2) Encapsulation is also called data hiding.
3) Design principles "programming for interface than implementation" is based on abstraction and "encapsulate whatever changes" is based upon Encapsulation.

35.        What is i18n and L10n?
·        I18n stands for Internationalization (18 char between I and n).
·        L10n stands for Localization (10 char between l and n.)It is the means by which i18n applications can be used for local regions.
·        What is the difference between Inheritance and Interface?

36.        Write a program to reverse a String in Java.

37.        What are the difference between Java and JavaScript?
Java
JavaScript
Java is an Object Oriented Programming (OOP) language
JavaScript is a scripting language
Java is very much Complex.
JavaScript s comparatively easy.
Java contains rich set of commands.
JavaScript contains a much smaller and simpler set of commands
Java can stand on its own that creates "standalone" applications.
JavaScript must (primarily) be placed inside an HTML document to function
Java must be compiled into what is known as a "machine language" before it can be run on the Web.
JavaScript is text-based. You write it to an HTML document and it is run through a browser.

38.        What is the base class of all classes?
java.lang.Object

39.        Write a Java program to print Palindrome number after number n   passed by user.

40.        What is the difference between Checked and Unchecked exceptions?
The compiler forces you to either catch checked exceptions or throw them to the calling method. For e.g.  IOException.
Unchecked exceptions (Runtime exception) are due to programming bugs (for ex. index out of bound exception). The compiler expects you to handle this in the code so it does not force you to catch unchecked exceptions. Exceptions extending Runtime Exception are unchecked.

41.        What is Auto boxing and unboxing.
Auto boxing-Automatic conversion of primitives into corresponding objects wrapper classes.
Unboxing - Automatic conversion of wrapper classes into primitives.
Need
The collections like ArrayList store only the objects so primitives need to converted to object wrapper classes.
Auto boxing/Unboxing helps to do automatic conversion.

42.        What is the difference between executequery and executeupdate.
·        executeQuery method is used to execute SQL which returns ResultSet.
·        executeUpdate method is used to execute update queries like insert, update, or delete.

43.        What is Annotation?
An annotation indicates that the declared element should be processed in some special way by a compiler, development tool, and deployment tool or during runtime.

44.        What is the Difference between put and post?
HTTP PUT:

PUT puts a file or resource at a specific URI, and exactly at that URI. If there's already a file or resource at that URI, PUT replaces that file or resource. If there is no file or resource there, PUT creates one HTTP 1.1 RFC location for PUT.

HTTP POST:
POST sends data to a specific URI and expects the resource at that URI to handle the request. The web server at this point can determine what to do with the data in the context of the specified resource.

45.        What are Java Annotations?
Java 5 comes with several pre built annotations
·        Override
·        Deprecated
·        SupressWarning
·        Retention
·        Target

46.        Write a program to generate 15 random integers between 0 and 10.
Random r = new Random();
for(int i=0;i<15;i++){
    System.out.println(r.nextInt(10));
}

47.        Write a program to fetch unique elements from Array.

48.        Write a program to transpose a Matrix.

49.        Difference between Throw and Throws.
·        Throws – used to advertise that the method might throw some exceptions.
·        Throw – used to throw exception from method definition.

50.        Write a difference between System.exit(0) and System.exit(1).
·        System.exit(0) is used in any method to come out of the program. It terminates the program normally where as
·        System.exit(1) terminates the program because of some error encountered in the program.






32 comments:

  1. Hi Ruchi Goyal Ji,Thank You for providing the core java interview questions.We would be Thankful if you can provide answers for the same.Thank You.

    ReplyDelete
  2. As Promised, Answers Posted

    ReplyDelete
  3. Hi Ruchi Goyal Ji,Thank You for providing the answers for the questions that you posted earlier.We would be Thankful to you if you can provide the same on Selenium(WebDriver) Interview Questions and Answers for beginners and experienced people too.Thanks Again.

    ReplyDelete
  4. Sure ,I will post the answers on selenium as well post new questions asap.

    ReplyDelete
  5. Hi Ruchi ... Very Nice Blog.. Can u provide sample prog for webservices and rest services using with Soap Classes..

    ReplyDelete
  6. Sorry Aman, I don't have much idea about Webservices.

    ReplyDelete
  7. hi ruchi .....nice answers ,plz tel me .what are inner classes ..name them ???
    .in public static void main(String arr[])... what if i replace public with private ........... remove static ........replace void with string?????
    . in hash map we have (key and value ) pair , can we store inside a value =(key, value ) again ?????

    ReplyDelete
  8. hi ruchi,
    plz tel me
    what is String builder?
    what is String tokenizer?
    what is the capacity of String Buffer?

    ReplyDelete
  9. The java.lang.StringBuilder class is mutable sequence of characters. This provides an API compatible with StringBuffer, but with no guarantee of synchronization.

    The java.util.StringTokenizer class allows an application to break a string into tokens.
    This class is a legacy class that is retained for compatibility reasons although its use is discouraged in new code.
    Its methods do not distinguish among identifiers, numbers, and quoted strings.
    This class methods do not even recognize and skip comments.

    capacity

    public int capacity()

    Returns the current capacity. The capacity is the amount of storage available for newly inserted characters, beyond which an allocation will occur.

    ReplyDelete
  10. What is the different between inheritance and interface?

    can u explain with example so it is better to understand
    Thanks u

    ReplyDelete
  11. very nice information it is very helpful.thanks to sharing this

    ReplyDelete
  12. Hi Ruchi,
    Can you please verify the answer for the below question. It seems the answer's are switched bet Application server and Web server. Thank you for your effort!!
    5. Difference between Application server and Web server.

    ReplyDelete
  13. Why Method Overloaing is not possible by changing the return type of method?

    ReplyDelete
    Replies
    1. Method Retrun Type doesn't matter in Method Overloading...

      Delete
    2. Method Retrun Type doesn't matter in Method Overloading...

      Delete
  14. Hi,
    Ruchi
    Please help me I am new to Selenium Webdriver
    I am Looking for a Sample Java Code to generate Excel report using the Selenium and TestNg framework using Java.
    For example -
    To check if the Sign In button is enable or not then I need to send following data to the excel sheet

    a. Test CaseID
    b. Expected result - To verify that sign in button is in enable mode
    c. Actual result - Sign in button is in enable mode.
    d. Test Status : Pass/Fail
    e. If Test Case Fail, then log screenshot next to Status column.

    ReplyDelete
  15. Is it possible to correct Column header for Application server & Web server. I think they are need to be reversed.

    ReplyDelete
  16. Is it possible to correct the title for Application server Vs Web server comparison. It should be reversed.

    ReplyDelete
  17. Hi ruchi i need testNg materials and interview Questions

    ReplyDelete
  18. Hi, Ruchi, are these the FAQ for selenium interview. If not please share those as well

    ReplyDelete
  19. Hi Ruchi, are these FAQ for selenium interview? can u pls share those as well

    ReplyDelete
    Replies
    1. http://ruchi-myseleniumblog.blogspot.in/2013/12/100-selenium-interview-questions.html

      Delete
  20. "Great blog created by you. I read your blog, its best and useful information. You have done a great work. Super blogging and keep it up.php jobs in hyderabad.
    "

    ReplyDelete
  21. It is really a great work and the way in which u r sharing the knowledge is excellent.
    Core Java Online Training Hyderabad

    ReplyDelete
  22. This makes radio employ a very cost-effective supply of communications in position for just about any
    event. Also, the brand new applications which are specific to certain droid phones really shine
    around the HTC model. Without question i - Pad 2 could be declared as the top among these previously discussed best tablets.

    ReplyDelete
  23. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Selenium training in electronic city

    ReplyDelete
  24. Good Post. I like your blog. Thanks for Sharing.
    Core JAVA Training in Noida

    ReplyDelete