Pages

Monday 31 March 2014

Java JDBC Connection with MySql Simple Example

Hello friends , this is a very simple Java program for connecting your MySql Database with Java using Java code...

Here is the code :
------------------------

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.SQLException;
 
public class JDBCExample {
 
  public static void main(String[] argv) {
 
 System.out.println("-------- MySQL JDBC Connection Testing --------");
 
 try {
  Class.forName("com.mysql.jdbc.Driver");
 } catch (ClassNotFoundException e) {
  System.out.println("Where is your MySQL JDBC Driver?");
  e.printStackTrace();
  return;
 }
 
 System.out.println("MySQL JDBC Driver Registered!");
 Connection connection = null;
 
 try {
  connection = DriverManager.getConnection("jdbc:mysql://localho                st:3306/dbname","root", "password");
 
 } catch (SQLException e) {
  System.out.println("Connection Failed! Check output console");
  e.printStackTrace();
  return;
 }
 
 if (connection != null) {
  System.out.println("Connection established.");
 } else {
  System.out.println("Failed to make connection!");
 }
  }
}

How to get local computer OS and IP address related detail using Java code

Hello friends this is a very simple Java Program to get your local computer OS related information and IP address related information...

Here is the code:
------------------------

import java.net.InetAddress;

public class GetDayOfWeekOfAnyDate {

public static void main(String[] args) {
try {
InetAddress address = InetAddress.getLocalHost();
System.out.println("Using InetAddress");
System.out.println("Host Address: " + address.getHostAddress());
System.out.println("Host Name: " + address.getHostName());
System.out.println("CanonicalHostName: "
+ address.getCanonicalHostName());
System.out.println("Address: " + address.getAddress());
System.out.println("LocalHost: " + address.getLocalHost());
System.out.println("LoopbackAddress: "
+ address.getLoopbackAddress());

String os = "os.name";
String version = "os.version";
String arch = "os.arch";
System.out.println("Name of the OS: " + System.getProperty(os));
System.out.println("Version of the OS: "
+ System.getProperty(version));
System.out.println("Architecture of the OS: "
+ System.getProperty(arch));
} catch (Exception e) {
e.printStackTrace();
}

}

}


KEEP SHARING THE KNOWLEDGE

Sunday 30 March 2014

Latest Mostly Asked HR interview Question Answer

1. Tell us something about yourself.

This is the first question, you can expect during any interview you face. This usually is a question to start the communication and set the ball rolling for the interview. You can answer this question by providing some information about your work experience, technologies you have worked upon, educational qualifications. If you are a fresh graduate, you can provide some information about your family also.
The trick is to put the full stop at the right place to provoke the next question you want. For e.g. “Recently I developed a website using Drupal. It was quite an interesting but challenging job which I enjoyed.”

2. Why do you consider yourself a suitable candidate for this position?

The answer to this question lies in the preparation you did before the interview. It is extremely important that you research the requirements of the position well and match them with your skills.
For e.g. if the position requires an Asp.net developer with good knowledge of health care domain, tell the interviewer about your technical skills and your domain knowledge.
Fresh graduates can talk about their technical skills, ability to learn and grasp things quickly.

3. Why do you want to leave your present job or company?

You may want to leave your present job for any reason but make sure that you do not talk bad about your manager, company or job. It reflects your complaining attitude.
Provide a sincere reason for e.g. “I think, I have grown up with my last employer as much as I could. I want to grow further and I believe that is possible with a new employer.”

4. You have stayed in your current job for quite a long time, why?

There are many people who do not change their jobs for years and when they go out looking for a new employer, this is one of the most important questions they are asked. Some people might look upon staying with the same employer for long as “lack of ambition”.
A good answer to this question can be something like, “Yes, you are right. I stayed with my last employer for almost 5 years but I was continuously growing in the company, doing new things, handling bigger challenges. So, I was quite happy working with them for these many years.” You can then talk about how you grew with your last employer.

5. What do you know about us?

Research the company and its business a bit before appearing for the interview. Also, find out a bit about the technologies they work upon. You don’t need to know everything inside out but having a fair idea about the company makes you appear interested in the position, to be taken seriously.
For e.g. I see that your company does a lot of projects based on OpenSource platforms like Joomla, Drupal, Magento which is quite interesting as I have a similar kind of experience.

6. What do you do to improve your knowledge?

The field of IT is very revolutionary. It is extremely important to keep yourself abreast with the new technological developments and this needs you to take some time out of your work schedule so that you can keep sharpening your saw.
To answer this question, you can tell the recruiter about the forums which you keep visiting, blogs which you keep reading. It will be an advantage if you are a member of some local user group.

7. Can you perform under pressure?

Most of the times, the job of software development is that of working under pressure. Sometimes, it will be the pressure of delivering on time while it can be that of a bug that has sprung all of a sudden in your code.
So, expect pressure in everything you do. It is important to maintain your performance and develop strategies to deliver under pressure. You can then go ahead an talk about your way of dealing with pressure and performing under it.

8. Tell us some of your strengths.

Again, it is important to study the requirements of the position before you appear for the interview. List out your strengths and offer the ones that this role demands.
For e.g. if you are appearing for the position of a Tech Lead – VB.net, talk about your VB.net skills, any extra knowledge which you have about coding with VB.net in comparison to other candidates, your team management skills etc.

9. Tell us some of your weaknesses.

You have to be careful while answering this question. Do not offer a weakness which will directly affect your selection but at the same time saying that you do not have any weakness will not be right too. Every human being has weaknesses, so it is perfectly OK for you to have some too.
The best way to answer this question will be to turn one of your strengths as a weakness and say that others accuse you of having this weakness but you think it is important to work in this manner. For e.g.: “My colleagues accuse me of paying to much attention to syntaxes but I believe it is important when you are writing the code to avoid spending too much time on finding and fixing the bugs later on.”
Another way to answer this question is to offer a totally un-related weakness for e.g. “I have been staying alone for so many years now but I still can’t cook independently.”

10. Are you comfortable working in a team?

The whole work of software development or IT is a team work. So, the only answer to this question can be: “Yes, I am comfortable working in a team.” If you have any problems in working as a team, it is important to work on them and develop yourself as a team player.

11. How do you rate your communication skills?

Again, IT is about dealing with people within and out of the company. So, it is important to have good communication skills. By good communication skills we mean, ability to understand and explain in a common language. So, if you believe that your communication skills are weaker, you need to work on them.
Anything less than average or good is not acceptable here.

12. You do not have all the experience we need for this position?

It is not possible for a candidate to have all the experience an employer requires. Even if you match yourself up to the expectations on technical front, there will be some difference in the work environment. And, it is absolutely fine.
The best way to deal with this question is to analyse the requirements of the position well and match your skills as close to them as possible. If something is still left untouched, offer your quick grasping power and ability to learn quickly as a solution & back it up with an example from the past.

13. How would you compensate for the lack of experience you have for this position?

As we discussed in the last question, your ability to understand and pick up new things quickly should be able to compensate for the lack of work experience you have.

14. If you were hiring for this position, what qualities would you look for in a potential candidate?

Closely understand the qualities and skills a person holding the position would need and match them with the qualities you have.
If you believe that you are missing a big quality required for the position under discussion, say that, “I understand that this is an important quality required in the person holding this position but given a chance, I will inculcate it in me.” Back it up with a confident body language.

15. Do you know anyone who works for us?

Offer some one’s name if they really know you well and can offer a positive feedback about you.

16. What is your style of management?

In today’s scenario, everything needs customization, so here also, one size can’t fit all i.e. one management style won’t work in all situations. So, offer “situational” as your style of management.

17. Have you ever fired anyone? How would you go about firing a person, if required?

The basic purpose of asking this question is to check your EQ and see if you have the guts to make tough decisions. If you have fired anyone in the past, discuss your experience and approach. If you have never done so in the past, discuss the approach you would take to make and implement such a decision. Keep the focus of your answer on the fact that you would try to do your best to ensure that your team performs to its best but if a particular member is not able to perform even after you taking all the steps to help him, you would make the tough decision to ensure that the project doesn’t suffer.

18. What irritates you about co-workers?

The purpose of this question is to see how well you can fit into a team. Basically, you should not have a problem with a person, although you can have a problem with the style of working.
So, to answer this question you can simply say, “I understand that IT is about team work, so we can’t afford to problems with co-workers but if someone is not serious about their work or does a low quality work affecting the whole project, I definitely do not like it”

19. Is there any particular kind of person you can not work with?

For the reason given in the above questions, the answer to this question should be a “No”. This is basically a different way of putting up the last question.

20. What qualities would you look for in your senior?

You can mention some generic qualities like intelligence, good sense of humour, dedicated to his team etc., which all the managers think that they have in abundance.

21. What motivates you at work?

To answer this question, you can mention things like – new challenges, good environment which all employers think that they offer.

22. Will you be happy to work in night shifts or over the weekends?

You need to answer this question taking into consideration what is suitable for you. Say that you can work in the night shifts, only if you can really do it.

23. Have you ever committed a mistake at work?

To err is human. So, it is perfectly OK if you committed a mistake at work but before answering the question analyse the magnitude of mistake you did and the effect it had on the company.
What is more important is – what did you do to rectify the mistake and make sure that you don’t do it again?
So, mention the mistake you committed and keep the focus of the answer on the steps you took to rectify it.

24. What position would you prefer while working on a project?

This question is for you to answer based on the skills and qualities you have. If you have the capability to handle different positions, discuss that also in the interview.

25. What are the most important things for you as a manager?

The two things which should be most important for a manager to succeed in his role are: 
a.) His team should be happy and keep performing 
b.) The project he is working on with his team is successfully finished with minimum problems.

26. Will you be happy to re-locate, if required?

Again, a question for you to answer based on your position. If you are anticipating this question in the interview, it is better to discuss this with your family also before you go to face the interview.

27. What kind of a salary are you looking for?

Try to put the ball back in interviewer’s court by asking him about the salary they offer for a position like this. Most of the big companies will have a fixed remuneration for each level.
However, if this is negotiable, you will have more negotiation power if you have some work experience. So, know your lower limit (amount below which you can’t go) and also know the maximum salary in the industry for the position then put forward a figure which is not very exact. It is better to mention a range. For e.g. if you are expecting something around 55 K, say that you expect something in mid fifties. Don’t keep the range to broad otherwise you will be offered something towards the lower end.
If you are a fresher, most of the times you will have to accept the company’s offering for the position. However, if you find it too less, you can definitely discuss that during the interview.

28. Do you have any questions for us?

This is usually the last question you can expect during an interview. It is extremely important to have some intelligent questions to ask the interviewer otherwise you may just sound dull and un-interested. Research the company a bit and discuss if they have been in news recently. You can also discuss about the growth prospects for you within the company etc.

29. Discuss the most stressful situation you came across in your previous job.

Here you should discuss a stressful situation that you were able to overcome and keep a positive tone, do not say you never came across a stressful situation. Typical answers can be:
-Our team’s targets were increased three fold and initially everyone was overwhelmed by the number, but we discussed it with our manager and he was co-operative and understood the situation. But he wanted us to give it a try and was ready to reduce the targets to a more realistic number.
-You can also talk about a very demanding project where you worked for long hours/2 shifts and had to sacrifice on family time, but once the project was done you got recognition for the hard work and you were over the stress.

30. For how long do you expect to stay with our organization?

You should ensure that you give an impression that you will pay back more than what you take from the company:
-You can say I will stay here as far as I see an opportunity for growth, as I am looking for a stability in work place
-If they stress on number of years say 3-4 years, and more if I can explore new challenges/growth opportunities

31. Why should we hire you?

-Here you should discuss the profile you have applied for and your strengths/experience with which you can add value to the job
-Discuss your achievements at your previous job, and say that I have developed my skills to suit my current profile, but I want to develop myself futher and face new challenges, and for that I need to change my job.
- I will always be willing to change roles share responsibilities to suit company requirements

32. Discuss your strengths

Discuss strengths that show your professional expertise, some of the answers could be:
-Multi tasking: Say I have been working on mulitple project and I am required to keep tabs on each project and co-ordinate with a lot of teams, and I am able to do it efficiently.
-Problem Solving: You can say that in my current job role I have spent a good time to know how to solve problems. My team members see me as a go-to person to solve issues. 
-Communication
-Team player
-Quick learner
Support each point with your examples

33. Discuss your weaknesses and how do you plan to overcome it

Discuss weaknesses in positive light always discuss how you plan to overcome it, some of the answers could be:
-I am always willing to take up additional responsibilities, but I end up being over worked so now I am realistic about what I can do, so that I do work to the required standards
-If you lack certain technical skill, which is not crucial for the job you can state that and say you are planning to take up a training course/certification to get over it 
-If you do not wish to discuss your weakness, you can say, I cannot compete with Rajnikant :P

34. What is your idea of an ideal company?

Do not go over board and ask for , it might give an impression that you are too demanding, some of the answers could be:
-An ideal company provides maximum opportunities for growth of employees. 
-They provide comfortable and flexible work environment, so that employees can perform at their best and work towards company’s benefit.
-A company that encourages learning 
-A company that encourages open culture

35. Why are you leaving your previous job?

Do not go around defaming your company, it will give a bad impression about you. 
Give reasons such as:
-Professional Growth
-New challenges 
-Change in profile
-Planning to relocate (if applicable)
-With time I found my job was becoming monotonous and I didn’t want this to have any impact on the job I was doing for my employer
-I am not actively looking for a job change but, I saw this opening and it looked interesting.

36. Tell us something about your achievements at your previous job.

-Talk about your professional acheivements, if you were recognised as a high performer or you got good feedback from your manager
-You can also discuss you annual ratings 
-Discuss your promotions/appraisals

37. Tell us what do you know about our company

-Browse through the company website and make sure you know what the company does and make sure you do so in short
-Discuss the positives aspects of the company, the interviewer should feel that you have done your home work
10. Why do you want to work for us?
-Start by discussing the profile you have applied for and go on to say that the organization would provide an opportunity to enhance your knowledge and help you to grow professionally
-Discuss how you would be of use to the organization and how you plan to develop your professional competencies

38. Are you willing to relocate/travel?

-Always say yes if you need the job
-You can ask whether they will compensate for relocation costs

39. Are you a good team player?

Companies look for team players as well as those who are self starters and can work independently, so you need to be versatile:
-You should show that you enjoy working in a team. Say that you are open to suggestions from team members and seniors.
-It is always good to work in a team as one can get the support of other members and in times of crisis everyone can work together to achieve the goal.

40. Can you work independently?

-Yes, I can work independently without supervision or support from a team
Do not emphasize on working independently as that will be seen as an inability to work with others.

41. Do you have any questions for us?

Always have a question ready to answer this one:
-You can ask whether the company allows for lateral and vertical role changes
-You can also ask whether the company encourages learning and development of employees
-Ask whether the company has plans for expansion 
-You can also discuss your role in detail

42. Are you willing to work for long hours, if the project demands that from you?

-Discuss situations when you must have done so to fulfill project requirements in the past

43. What is your current CTC and what are your expectations?

-Be honest about your CTC, as you will have to produce you salary slip as a proof of emplyment
-Be realistic when you state your expected CTC, you can ask for a 30-40% hike
-If you are underpaid at your current company you can look for the standard salary paid for the experience you have and ask for that amount

44. Are you planning to go for further studies?

Be transparent in your answer. 
-If you are pursuing further studies, say so. Tell them why you want to go for that course
-If you are taking up a distance education course or a part time course, they should know, as you will need to take leaves when you appear for exams

45. Tell us something about yourself, discuss 5 characteristics

List down points that will help you professionally:
-Independent
-Responsible
-Hard working
-Multi tasker
-Prompt
-Add your characteristcs

46. Tell us something about your hobbies

Answer it with honesty, as they can go deeper into this discussion. You can include:
-Browsing the internet
-Blogging, 
-Listening to music, 
-Chatting with friends 
-Reading newspapers, 
-Reading books, 
-Shopping, 
-Watching movies….

47. What is more important to you money or success?

This is tricky question, as money and success both are important and you cannot outweigh the importance of one over the other. Personally you might prefer money over success or success over money, but it is better to be neutral when answering this question in an interview:
You can say, that money and success both are important for you, but if you have to choose you would choose success. The reason being, if one is successful money often follows and you need not focus on money over success..

Saturday 29 March 2014

Most Frequently Asked Java Interview Question For Fresher and Experienced

1.What are the principle concepts of OOPS?
ANS :- 
There are four principle concepts upon which object oriented design and programming rest. They are:
  • Abstraction
  • Polymorphism
  • Inheritance
  • Encapsulation
  • (i.e. easily remembered as A-PIE).



2.What is Abstraction?

ANS :- 
Abstraction refers to the act of representing essential features without including the background details or explanations.


3.What is Encapsulation?

ANS :-
Encapsulation is a technique used for hiding the properties and behaviors of an object and allowing outside access only as appropriate. It prevents other objects from directly altering or accessing the properties or methods of the encapsulated object.


4.What is the difference between abstraction and encapsulation?

ANS :- 
  • Abstraction focuses on the outside view of an object (i.e. the interface) Encapsulation (information hiding) prevents clients from seeing it’s inside view, where the behavior of the abstraction is implemented.
  • Abstraction solves the problem in the design side while Encapsulation is the Implementation.
  • Encapsulation is the deliverables of Abstraction. Encapsulation barely talks about grouping up your abstraction to suit the developer needs.



5.What is Inheritance?

ANS :-
  • Inheritance is the process by which objects of one class acquire the properties of objects of another class.
  • A class that is inherited is called a superclass.
  • The class that does the inheriting is called a subclass.
  • Inheritance is done by using the keyword extends.
  • The two most common reasons to use inheritance are:
    • To promote code reuse
    • To use polymorphism



6.What is Polymorphism?

ANS :-
Polymorphism is briefly described as "one interface, many implementations." Polymorphism is a characteristic of being able to assign a different meaning or usage to something in different contexts - specifically, to allow an entity such as a variable, a function, or an object to have more than one form.


7.How does Java implement polymorphism?

ANS :-
(Inheritance, Overloading and Overriding are used to achieve Polymorphism in java).
Polymorphism manifests itself in Java in the form of multiple methods having the same name.
  • In some cases, multiple methods have the same name, but different formal argument lists (overloaded methods).
  • In other cases, multiple methods have the same name, same return type, and same formal argument list (overridden methods).



8.Explain the different forms of Polymorphism.

ANS :-
There are two types of polymorphism one is Compile time polymorphism and the other is run time polymorphism. Compile time polymorphism is method overloading. Runtime time polymorphism is done using inheritance and interface.
NoteFrom a practical programming viewpoint, polymorphism manifests itself in three distinct forms in Java:
  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface


9.What is runtime polymorphism or dynamic method dispatch?
ANS:-

In Java, runtime polymorphism or dynamic method dispatch is a process in which a call to an overridden method is resolved at runtime rather than at compile-time. In this process, an overridden method is called through the reference variable of a superclass. The determination of the method to be called is based on the object being referred to by the reference variable.


10.What is Dynamic Binding?

ANS :-
Binding refers to the linking of a procedure call to the code to be executed in response to the call. Dynamic binding (also known as late binding) means that the code associated with a given procedure call is not known until the time of the call at run-time. It is associated with polymorphism and inheritance.


11.What is method overloading?

ANS :-
Method Overloading means to have two or more methods with same name in the same class with different arguments. The benefit of method overloading is that it allows you to implement methods that support the same semantic operation but differ by argument number or type.
Note:
  • Overloaded methods MUST change the argument list
  • Overloaded methods CAN change the return type
  • Overloaded methods CAN change the access modifier
  • Overloaded methods CAN declare new or broader checked exceptions
  • A method can be overloaded in the same class or in a subclass



12.What is method overriding?

ANS :-
Method overriding occurs when sub class declares a method that has the same type arguments as a method declared by one of its superclass. The key benefit of overriding is the ability to define behavior that’s specific to a particular subclass type.
Note:
  • The overriding method cannot have a more restrictive access modifier than the method being overridden (Ex: You can’t override a method marked public and make it protected).
  • You cannot override a method marked final
  • You cannot override a method marked static



13.What are the differences between method overloading and method overriding?

ANS :-
 Overloaded MethodOverridden Method
ArgumentsMust changeMust not change
Return typeCan changeCan’t change except for covariant returns
ExceptionsCan changeCan reduce or eliminate. Must not throw new or broader checked exceptions
AccessCan changeMust not make more restrictive (can be less restrictive)
InvocationReference type determines which overloaded version is selected. Happens at compile time.Object type determines which method is selected. Happens at runtime.


14.Can overloaded methods be override too?

ANS :-
Yes, derived classes still can override the overloaded methods. Polymorphism can still happen. Compiler will not binding the method calls since it is overloaded, because it might be overridden now or in the future.


15.Is it possible to override the main method?

ANS :-
NO, because main is a static method. A static method can't be overridden in Java.


16.How to invoke a superclass version of an Overridden method?

ANS :-
To invoke a superclass method that has been overridden in a subclass, you must either call the method directly through a superclass instance, or use the super prefix in the subclass itself. From the point of the view of the subclass, the super prefix provides an explicit reference to the superclass' implementation of the method.
// From subclass
super.overriddenMethod();



17.What is super?

ANS :-
super is a keyword which is used to access the method or member variables from the superclass. If a method hides one of the member variables in its superclass, the method can refer to the hidden variable through the use of the super keyword. In the same way, if a method overrides one of the methods in its superclass, the method can invoke the overridden method through the use of the super keyword.
Note:
  • You can only go back one level.
  • In the constructor, if you use super(), it must be the very first code, and you cannot access any this.xxx variables or methods to compute its parameters.



18.How do you prevent a method from being overridden?

ANS :-
To prevent a specific method from being overridden in a subclass, use the final modifier on the method declaration, which means "this is the final implementation of this method", the end of its inheritance hierarchy.
                       public final void exampleMethod() {
                        // Method statements
                        }



19.What is an Interface?

ANS :
An interface is a description of a set of methods that conforming implementing classes must have.
Note:
  • You can’t mark an interface as final.
  • Interface variables must be static.
  • An Interface cannot extend anything but another interfaces.


20.Can we instantiate an interface?
ANS :-
You can’t instantiate an interface directly, but you can instantiate a class that implements an interface.


21.Can we create an object for an interface?

ANS :-
Yes, it is always necessary to create an object implementation for an interface. Interfaces cannot be instantiated in their own right, so you must write a class that implements the interface and fulfill all the methods defined in it.


22.Do interfaces have member variables?

ANS :-
Interfaces may have member variables, but these are implicitly public, static, and final- in other words, interfaces can declare only constants, not instance variables that are available to all implementations and may be used as key references for method arguments for example.


23.What modifiers are allowed for methods in an Interface?

ANS :-
Only public and abstract modifiers are allowed for methods in interfaces.


24.What is a marker interface?

ANS :-
Marker interfaces are those which do not declare any required methods, but signify their compatibility with certain operations. The java.io.Serializableinterface and Cloneable are typical marker interfaces. These do not contain any methods, but classes must implement this interface in order to be serialized and de-serialized.


25.What is an abstract class?

ANS :-
Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation.
Note:
  • If even a single method is abstract, the whole class must be declared abstract.
  • Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods.
  • You can’t mark a class as both abstract and final.



26.Can we instantiate an abstract class?

ANS :-
An abstract class can never be instantiated. Its sole purpose is to be extended (subclassed).


27.What are the differences between Interface and Abstract class?

ANS :-
Abstract ClassInterfaces
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.


28.When should I use abstract classes and when should I use interfaces?

ANS :-
Use Interfaces when…
  • You see that something in your design will change frequently.
  • If various implementations only share method signatures then it is better to use Interfaces.
  • you need some classes to use some methods which you don't want to be included in the class, then you go for the interface, which makes it easy to just implement and make use of the methods defined in the interface.
Use Abstract Class when…
  • If various implementations are of the same kind and use common behavior or status then abstract class is better to use.
  • When you want to provide a generalized form of abstraction and leave the implementation task with the inheriting subclass.
  • Abstract classes are an excellent way to create planned inheritance hierarchies. They're also a good choice for nonleaf classes in class hierarchies.




29.When you declare a method as abstract, can other nonabstract methods access it?

ANS :- 
Yes, other nonabstract methods can access a method that you declare as abstract.


30.Can there be an abstract class with no abstract methods in it?

ANS :-
Yes, there can be an abstract class without abstract methods.

31.What is Constructor?
ANS :-
  • A constructor is a special method whose task is to initialize the object of its class.
  • It is special because its name is the same as the class name.
  • They do not have return types, not even void and therefore they cannot return values.
  • They cannot be inherited, though a derived class can call the base class constructor.
  • Constructor is invoked whenever an object of its associated class is created.



32.How does the Java default constructor be provided?

ANS :-
If a class defined by the code does not have any constructor, compiler will automatically provide one no-parameter-constructor (default-constructor) for the class in the byte code. The access modifier (public/private/etc.) of the default constructor is the same as the class itself.


33.Can constructor be inherited?

ANS :-
No, constructor cannot be inherited, though a derived class can call the base class constructor.


34.What are the differences between Contructors and Methods?

ANS :-
 ConstructorsMethods
PurposeCreate an instance of a classGroup Java statements
ModifiersCannot be abstract, final, native, static, or synchronizedCan be abstract, final, native, static, or synchronized
Return TypeNo return type, not even voidvoid or a valid return type
NameSame name as the class (first letter is capitalized by convention) -- usually a nounAny name except the class. Method names begin with a lowercase letter by convention -- usually the name of an action
thisRefers to another constructor in the same class. If used, it must be the first line of the constructorRefers to an instance of the owning class. Cannot be used by static methods.
superCalls the constructor of the parent class. If used, must be the first line of the constructorCalls an overridden method in the parent class
InheritanceConstructors are not inheritedMethods are inherited


35.How are this() and super() used with constructors?

ANS :-
  • Constructors use this to refer to another constructor in the same class with a different parameter list.
  • Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.



36.What are the differences between Class Methods and Instance Methods?

ANS :-
Class MethodsInstance Methods
Class methods are methods which are declared as static. The method can be called without creating an instance of the classInstance methods on the other hand require an instance of the class to exist before they can be called, so an instance of a class needs to be created by using the new keyword.
Instance methods operate on specific instances of classes.
Class methods can only operate on class members and not on instance members as class methods are unaware of instance members.Instance methods of the class can also not be called from within a class method unless they are being called on an instance of that class.
Class methods are methods which are declared as static. The method can be called without creating an  instance of the class.Instance methods are not declared as static.


37.How are this() and super() used with constructors?

ANS :-
  • Constructors use this to refer to another constructor in the same class with a different parameter list.
  • Constructors use super to invoke the superclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will complain.



38.What are Access Specifiers?

ANS :- 
One of the techniques in object-oriented programming is encapsulation. It concerns the hiding of data in a class and making this class available only through methods. Java allows you to control access to classes, methods, and fields via so-called access specifiers..


39.What are Access Specifiers available in Java?

ANS :- 
Java offers four access specifiers, listed below in decreasing accessibility:
  • Publicpublic classes, methods, and fields can be accessed from everywhere.
  • Protectedprotected methods and fields can only be accessed within the same class to which the methods and fields belong, within its subclasses, and within classes of the same package.
  • Default(no specifier)- If you do not set access to specific level, then such a class, method, or field will be accessible from inside the same package to which the class, method, or field belongs, but not from outside this package.
  • Privateprivate methods and fields can only be accessed within the same class to which the methods and fields belong. private methods and fields are not visible within subclasses and are not inherited by subclasses.

 Situation  public  protected  default  private 
 Accessible to class
 from same package? 
yesyesyesno
 Accessible to class
 from different package? 
yes no, unless it is a subclass nono



40.What is final modifier?

ANS :-
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 Classes- A final class cannot have subclasses.
  • final Variables- A final variable cannot be changed once it is initialized.
  • final Methods- A final method cannot be overridden by subclasses.


41.What are the uses of final method?
ANS :-
There are two reasons for marking a method as final:
  • Disallowing subclasses to change the meaning of the method.
  • Increasing efficiency by allowing the compiler to turn calls to the method into inline Java code.



42.What is static block?

ANS :-
Static block which exactly executed exactly once when the class is first loaded into JVM. Before going to the main method the static block will execute.


43.What are static variables?

ANS :-
Variables that have only one copy per class are known as static variables. They are not attached to a particular instance of a class but rather belong to a class as a whole. They are declared by using the static keyword as a modifier.
 		static type  varIdentifier;
where, the name of the variable is varIdentifier and its data type is specified by type.
Note: Static variables that are not explicitly initialized in the code are automatically initialized with a default value. The default value depends on the data type of the variables.


44.What is the difference between static and non-static variables?

ANS :- 
A static variable is associated with the class as a whole rather than with specific instances of a class. Non-static variables take on unique values with each object instance.


Methods declared with the keyword static as modifier are called static methods or class methods. They are so called because they affect a class as a whole, not a particular instance of the class. Static methods are always invoked without reference to a particular instance of a class.


45.What are static methods?
ANS :- 
Note:The use of a static method suffers from the following restrictions:
  • A static method can only call other static methods.
  • A static method must only access static data.
  • A static method cannot reference to the current object using keywords super or this.

46.What is an Iterator ?
ANS :-
  • The Iterator interface is used to step through the elements of a Collection.
  • Iterators let you process each element of a Collection.
  • Iterators are a generic way to go through all the elements of a Collection no matter how it is organized.
  • Iterator is an Interface implemented a different way for every Collection.


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


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

49.What is the difference between Enumeration and Iterator?
ANS :-
EnumerationIterator
Enumeration doesn't have a remove() methodIterator has a remove() method
Enumeration acts as Read-only interface, because it has the methods only to traverse and fetch the objectsCan be abstract, final, native, static, or synchronized
Note: So Enumeration is used whenever we want to make Collection objects as Read-only.

50.How is ListIterator?
ANS :-
ListIterator is just like Iterator, except it allows us to access the collection in either the forward or backward direction and lets us modify an element

51.What is the List interface?
ANS :-
  • The List interface provides support for ordered collections of objects.
  • Lists may contain duplicate elements.


52.What are the main implementations of the List interface ?
ANS :- 
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).


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


54.Difference between ArrayList and Vector ?
AND :-
ArrayListVector
ArrayList is NOT synchronized by default.Vector List is synchronized by default.
ArrayList can use only Iterator to access the elements.Vector list can use Iterator and Enumeration Interface to access the elements.
The ArrayList increases its array size by 50 percent if it runs out of room.A Vector defaults to doubling the size of its array if it runs out of room
ArrayList has no default size.While vector has a default size of 10.

55.How to obtain Array from an ArrayList ?
AND :-
Array can be obtained from an ArrayList using toArray() method on ArrayList.
List arrayList = new ArrayList();
arrayList.add(…
Object  a[] = arrayList.toArray();

56.Why insertion and deletion in ArrayList is slow compared to LinkedList ?
ANS :- 
  • 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.


57.Why are Iterators returned by ArrayList called Fail Fast ?
ANS :-
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.

58.How do you decide when to use ArrayList and When to use LinkedList?
ANS : -
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.


59.What is the Set interface ?
ANS :-
  • The Set interface provides methods for accessing the elements of a finite mathematical set
  • Sets do not allow duplicate elements
  • Contains no methods other than those inherited from Collection
  • It adds the restriction that duplicate elements are prohibited
  • Two Set objects are equal if they contain the same elements

60.What are the main Implementations of the Set interface ?
ANS :-
The main implementations of the List interface are as follows:
  • HashSet
  • TreeSet
  • LinkedHashSet
  • EnumSet

61.What is a HashSet ?
ANS :-
  • A HashSet is an unsorted, unordered Set.
  • It uses the hashcode of the object being inserted (so the more efficient your hashcode() implementation the better access performance you’ll get).
  • Use this class when you want a collection with no duplicates and you don’t care about order when you iterate through it.

62.What is a TreeSet ?
ANS :-
TreeSet is a Set implementation that keeps the elements in sorted order. The elements are sorted according to the natural order of elements or by the comparator provided at creation time.

63.What is an EnumSet ?
ANS :-
An EnumSet is a specialized set for use with enum types, all of the elements in the EnumSet type that is specified, explicitly or implicitly, when the set is created.

64.Difference between HashSet and TreeSet ?
ANS :-
HashSetTreeSet
HashSet is under set interface i.e. it  does not guarantee for either sorted order or sequence order.TreeSet is under set i.e. it provides elements in a sorted  order (acceding order).
We can add any type of elements to hash set.We can add only similar types
of elements to tree set.


65.
What is a Map ?
ANS :-
A map is an object that stores associations between keys and values (key/value pairs).
  • Given a key, you can find its value. Both keys  and  values are objects.
  • The keys must be unique, but the values may be duplicated.
  • Some maps can accept a null key and null values, others cannot.

66.
What are the main Implementations of the Map interface ?
ANS :-
The main implementations of the List interface are as follows:
  • HashMap
  • HashTable
  • TreeMap
  • EnumMap

67.What is a TreeMap ?
ANS :-
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

68.How do you decide when to use HashMap and when to use TreeMap ?
ANS :-
For inserting, deleting, and locating elements in a Map, the HashMap offers the best alternative. If, however, you need to traverse the keys in a sorted order, then TreeMap is your better alternative. Depending upon the size of your collection, it may be faster to add elements to a HashMap, then convert the map to a TreeMap for sorted key traversal.

69.Difference between HashMap and Hashtable ?
ANS :-
HashMapHashtable
HashMap lets you have null values as well as one null key.HashTable  does not allows null values as key and value.
The iterator in the HashMap is fail-safe (If you change the map while iterating, you’ll know).The enumerator for the Hashtable is not fail-safe.
HashMap is unsynchronized.Hashtable is synchronized.
Note: Only one NULL is allowed as a key in HashMap. HashMap does not allow multiple keys to be NULL. Nevertheless, it can have multiple NULL values.

70.How does a Hashtable internally maintain the key-value pairs?
ANS :- 
TreeMap actually implements the SortedMap interface which extends the Map interface. In a TreeMap the data will be sorted in ascending order of keys according to the natural order for the key's class, or by the comparator provided at creation time. TreeMap is based on the Red-Black tree data structure.

71.
What Are the different Collection Views That Maps Provide?
ANS :- 
Maps Provide Three Collection Views.
  • Key Set - allow a map's contents to be viewed as a set of keys.
  • Values Collection - allow a map's contents to be viewed as a set of values.
  • Entry Set - allow a map's contents to be viewed as a set of key-value mappings.

72.What is a KeySet View ?
ANS :-
KeySet is a set returned by the keySet() method of the Map Interface, It is a set that contains all the keys present in the Map.

73.What is a Values Collection View ?
ANS :-
Values Collection View is a collection returned by the values() method of the Map Interface, It contains all the objects present as values in the map.

74.What is an EntrySet View ?
ANS :-
Entry Set view is a set that is returned by the entrySet() method in the map and contains Objects of type Map. Entry each of which has both Key and Value.

75.How do you sort an ArrayList (or any list) of user-defined objects ?
ANS :- 
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).

76.What is the Comparable interface ?
ANS :-
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<T>
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 thecompareTo() 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.

77.What are the differences between the Comparable and Comparator interfaces ?
ANS :- 
ComparableComparato
It uses the compareTo() method.
int objectOne.compareTo(objectTwo).
t uses the compare() method.

int compare(ObjOne, ObjTwo)
It is necessary to modify the class whose instance is going to be sorted.A separate class can be created in order to sort the instances.
Only one sort sequence can be created.Many sort sequences can be created.
It is frequently used by the API classes.It used by third-party classes to sort instances.