What is the difference between makin an ArrayList these two difference ways? i know the method will be the same and both will essentially do the same thing. but why two ways to initializing arraylist?

ArrayList<String> list = new ArrayList<String>();
List<String> myList = new ArrayList<String>();

No difference

i know the method will be the same and both will essentially do the same thing. but why two ways to initializing arraylist?

The second form is called "programming to an interface". Any further use of "myList" in your code would adhere to the "List" interface and as such would allow you to change the implementation class by just changing a single line.

This distinction plays an important role when it comes to designing an API since you wouldn't really want to bind your users to a specific implementation which might change in the future. Establishing a common interface (by using either Java interfaces or super-classes) helps when it comes to re-factoring and writing unit tests.

Yes. A good rule of thumb, I've found, is that public (and maybe protected) methods should use the interface (I.E. list) as parameter and return types. Whereas private (and maybe default) methods could easily use the implementation (I.E. ArrayList). This second part can make changes more widespread when a change is made, but it does not change the public interface and so those changes could still be made without affecting (theoretically) anybody else's code that may be using your API. Also, local variables should always use the implementation (if there is any chance you'll be using, or relying upon, functionality/behaviour that the implementation guaranties that the interface does not). They declare more functionalities than the Interface does, and there is no reason to restrict yourself in a local scope.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.