Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.If any class implement Comparable interface in Java then collection of that object either List or Array can be sorted automatically by using Collections.sort() or Arrays.sort() method and object will be sorted based on there natural order defined by CompareTo method.

Comparator is for objects without a natural ordering or when you wish to use a different ordering.

Natural ordering is the Ordering implemented on the objects of each class. This ordering is referred to as the class’s natural ordering.For example Strings Natural Ordering is defined in String Class

Comparable
Compares object of itself with some other objects.Comparable overrides compareTo

Employee.java

package com.acme.users;

public class Employee implements Comparable<Employee> {
	public String EmpName;
	public Integer EmpId;
	public Integer Age;
	
	public Employee(Integer pEmpId, String pEmpName, Integer pAge)
	{
		this.EmpName = pEmpName;
		this.EmpId   = pEmpId;
		this.Age     = pAge;
	}
	
	
	public String getEmpName() {
		return EmpName;
	}
	public void setEmpName(String empName) {
		EmpName = empName;
	}
	public Integer getEmpId() {
		return EmpId;
	}
	public void setEmpId(Integer empId) {
		EmpId = empId;
	}
	public Integer getAge() {
		return Age;
	}
	public void setAge(Integer age) {
		Age = age;
	}
	
	@Override
	public int compareTo(Employee arg0) 
	{	
		if(this.getEmpId() == arg0.getEmpId())
			return 0;
		else if (this.getEmpId() > arg0.getEmpId())
			return 1;
		else
			return -1;
	}
}

EmpDashBoard.java

package com.acme.users;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmpDashBoard {
	public static void main(String[] args) {

		List<Employee> arrEmpList = new ArrayList();

		Employee objEmp1 = new Employee(101, "Ahmed", 31);
		Employee objEmp2 = new Employee(127, "Mahesh", 24);
		Employee objEmp3 = new Employee(109, "Viparna", 85);
		Employee objEmp4 = new Employee(101, "Abdul", 26);
		Employee objEmp5 = new Employee(104, "Muthu", 23);
		Employee objEmp6 = new Employee(115, "Monalisa", 25);

		arrEmpList.add(objEmp1);

		arrEmpList.add(objEmp2);
		arrEmpList.add(objEmp3);
		arrEmpList.add(objEmp4);
		arrEmpList.add(objEmp5);
		arrEmpList.add(objEmp6);

		System.out.println("Sorted based on Natural Sorting(Emp Id)");
		System.out.println("Before Sorting");
		dispListContent(arrEmpList);
		
		Collections.sort(arrEmpList);
		
		System.out.println("After Sorting");
		dispListContent(arrEmpList);
	}

	public static void dispListContent(List<Employee> parrEmployeeLst) {
		System.out.println(" ");

		System.out.println("EmpId" + " " + "EmpName" + "     " + "Age");
		System.out.println("---------------------------");
		for (Employee object : parrEmployeeLst) {
			System.out.print(object.getEmpId() + "   ");
			System.out.print(object.getEmpName() + "     ");
			System.out.println(object.getAge() + " ");
		}
	}
}

Output

Sorted based on Natural Sorting(Emp Id)

Before Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed       31 
127   Mahesh      24 
109   Viparna     85 
101   Abdul       26 
104   Muthu       23 
115   Monalisa    25 

After Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed       31 
101   Abdul       26 
104   Muthu       23 
109   Viparna     85 
115   Monalisa    25 
127   Mahesh      24 

Comparator
In some situations, you may not want to change a class and make it comparable. In such cases, Comparator can be used.Comparator overrides compare

Comparator provides a way for you to provide custom comparison logic for types that you have no control over.

In the below Example I have Sorted the Employee class Objects based on Name(EmpNameComparator), Age(EmpAgeComparator) and based on EmpIDName(EmpIdNameComparator)

EmpDashBoard.java

package com.acme.users;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class EmpDashBoard {
	public static void main(String[] args) {

		List<Employee> arrEmpList = new ArrayList();

		Employee objEmp1 = new Employee(101, "Ahmed", 31);
		Employee objEmp2 = new Employee(127, "Mahesh", 24);
		Employee objEmp3 = new Employee(109, "Viparna", 85);
		Employee objEmp4 = new Employee(101, "Abdul", 26);
		Employee objEmp5 = new Employee(104, "Muthu", 23);
		Employee objEmp6 = new Employee(115, "Monalisa", 25);

		arrEmpList.add(objEmp1);

		arrEmpList.add(objEmp2);
		arrEmpList.add(objEmp3);
		arrEmpList.add(objEmp4);
		arrEmpList.add(objEmp5);
		arrEmpList.add(objEmp6);

		System.out.println("Sorted based on Natural Sorting(Emp Id)");

		System.out.println("Before Sorting");
		dispListContent(arrEmpList);

		System.out.println("Sorting based on Emp Name");
		Collections.sort(arrEmpList, new EmpNameComparator());
		dispListContent(arrEmpList);

		System.out.println("Sorting based on Emp Age");
		Collections.sort(arrEmpList, new EmpAgeComparator());
		dispListContent(arrEmpList);

		System.out.println("Sorting based on EmpId and Name");
		Collections.sort(arrEmpList, new EmpIdNameComparator());
		dispListContent(arrEmpList);
	}

	public static void dispListContent(List<Employee> parrEmployeeLst) {
		System.out.println(" ");

		System.out.println("EmpId" + " " + "EmpName" + "     " + "Age");
		System.out.println("---------------------------");
		for (Employee object : parrEmployeeLst) {
			System.out.print(object.getEmpId() + "   ");
			System.out.print(object.getEmpName() + "     ");
			System.out.println(object.getAge() + " ");
		}
	}
}

EmpNameComparator.java

public class EmpNameComparator implements Comparator<Employee>{

	@Override
	public int compare(Employee o1, Employee o2) {
		String a = o1.getEmpName();
		String b = o2.getEmpName();
		
		//Strings Natural Order Comparable Method
		int compare = a.compareTo(b);
		
		if (compare > 0){
		    return 1;
		}
		else if (compare < 0) {
			return -1;
		}
		else {
			return 0;
		}
	}
}

EmpAgeComparator.java

public class EmpAgeComparator  implements Comparator<Employee> {
	
	@Override
	public int compare(Employee o1, Employee o2) {
		Integer a = o1.getAge();
		Integer b = o2.getAge();
		
		if (a > b){
		    return 1;
		}
		else if (a < b) {
			return -1;
		}
		else {
			return 0;
		}
	}
}

EmpIdNameComparator.java

public class EmpIdNameComparator  implements Comparator<Employee>{
	
	@Override
	public int compare(Employee o1, Employee o2) {
		String a = o1.getEmpName();
		String b = o2.getEmpName();
		
		
		int i = Integer.compare(o1.getEmpId(), o2.getEmpId());
		if (i != 0) return i;

	    return a.compareTo(b);
	}
	
}

Output

Before Sorting
 
EmpId EmpName     Age
---------------------------
101   Ahmed      31 
127   Mahesh     24 
109   Viparna    85 
101   Abdul      26 
104   Muthu      23 
115   Monalisa   25 

Sorting based on Emp Name
 
EmpId EmpName     Age
---------------------------
101   Abdul      26 
101   Ahmed      31 
127   Mahesh     24 
115   Monalisa   25 
104   Muthu      23 
109   Viparna    85 

Sorting based on Emp Age
 
EmpId EmpName     Age
---------------------------
104   Muthu       23 
127   Mahesh      24 
115   Monalisa    25 
101   Abdul       26 
101   Ahmed       31 
109   Viparna     85 

Sorting based on EmpId and Name
 
EmpId EmpName     Age
---------------------------
101   Abdul       26 
101   Ahmed       31 
104   Muthu       23 
109   Viparna     85 
115   Monalisa    25 
127   Mahesh      24 


comparable for natural order, (natural order definition is obviously open to interpretation), and write a comparator for other sorting or comparison needs.

If there is a natural or default way of sorting Object already exist during development of Class than use Comparable. This is intuitive and you given the class name people should be able to guess it correctly like Strings are sorted chronically, Employee can be sorted by there Id etc. On the other hand if an Object can be sorted on multiple ways and client is specifying on which parameter sorting should take place than use Comparator interface. for example Employee can again be sorted on name, salary or department and clients needs an API to do that. Comparator implementation can sort out this problem.

As others have said, Dependency Injection(DI) removes the responsibility of direct creation, and management of the lifespan, of other object instances upon which our class of interest (consumer class) is dependent. These instances are instead passed to our consumer class, typically as constructor parameters or via property setters (the management of the dependency object instancing and passing to the consumer class is usually performed by an Inversion of Control (IoC) container, but that’s another topic).

Any application is composed of many objects that collaborate with each other to perform some useful stuff. Traditionally each object is responsible for obtaining its own references to the dependent objects (dependencies) it collaborate with. This leads to highly coupled classes and hard-to-test code.

For example, consider a Car object.

A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object.

Without Dependency Injection (DI):

class Car{
  private Wheel wh= new NepaliRubberWheel();
  private Battery bt= new ExcideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial NepaliRubberWheel() punctures? We need to recreate the Car object with its new dependency say ChineseRubberWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

class Car{
  private Wheel wh= [Inject an Instance of Wheel at runtime]
  private Battery bt= [Inject an Instance of Battery at runtime]
  Car(Wheel wh,Battery bt) {
      this.wh = wh;
      this.bt = bt;
  }
  //Or we can have setters
  void setWheel(Wheel wh) {
      this.wh = wh;
  }
}

BeanFactory

The BeanFactory is the actual container which instantiates, configures, and manages a number of beans. These beans typically collaborate with one another, and thus have dependencies between themselves. These dependencies are reflected in the configuration data used by the BeanFactory (although some dependencies may not be visible as configuration data, but rather be a function of programmatic interactions between beans at runtime).

ApplicationContext

While the beans package provides basic functionality for managing and manipulating beans, often in a programmatic way, the context package adds ApplicationContext, which enhances BeanFactory functionality in a more framework-oriented style. Many users will use ApplicationContext in a completely declarative fashion, not even having to create it manually, but instead relying on support classes such as ContextLoader to automatically start an ApplicationContext as part of the normal startup process of a Java EE web-app. Of course, it is still possible to programmatically create an ApplicationContext.

The basis for the context package is the ApplicationContext interface, located in the org.springframework.context package. Deriving from the BeanFactory interface, it provides all the functionality of BeanFactory. To allow working in a more framework-oriented fashion, using layering and hierarchical contexts, the context package also provides the following:

  1. MessageSource, providing access to messages in, i18n-style
  2. Access to resources, such as URLs and files
  3. Event propagation to beans implementing the ApplicationListener interface
  4. Loading of multiple (hierarchical) contexts, allowing each to be focused on one particular layer, for example the web layer of an application

As the ApplicationContext includes all functionality of the BeanFactory, it is generally recommended that it be used over the BeanFactory, except for a few limited situations such as perhaps in an applet, where memory consumption might be critical, and a few extra kilobytes might make a difference. The following sections described functionality which ApplicationContext adds to basic BeanFactory capabilities.

Dependency Injection

What is Dependency

Quick Example:EMPLOYEE OBJECT WHEN CREATED,
              IT WILL AUTOMATICALLY CREATE ADDRESS OBJECT
   (if address is defines as dependency by Employee object)

Now in the above EMPLOYEE Class is dependent on ADDRESS Class.

You can not create the Address Object unless you create Employee Object

EMPLOYEE Class is dependent and ADDRESS Class is dependency

What is the purpose of DI?
With dependency injection, objects don’t define their dependencies themselves, the dependencies are injected to them as needed.The purpose of Dependency Injection is to reduce coupling in your application to make it more flexible and easier to test.

How does it benefit ? The objects don’t need to know where and how to get their dependencies, which results in loose coupling between objects, which makes them a lot easier to test.

When to use Dependency Injection
One of the most compelling reasons for DI is to allow easier unit testing without having to hit a database and worry about setting up ‘test’ data.Dependency Injection gives you the ability to test specific units of code in isolation.

Dependency injection is basically providing the objects that an object needs (its dependencies) instead of having it construct them itself. It’s a very useful technique for testing, since it allows dependencies to be mocked or stubbed out.

Dependencies can be injected into objects by many means (such as constructor injection or setter injection). One can even use specialized dependency injection frameworks (e.g Spring) to do that, but they certainly aren’t required.

Example
A Car depends on wheels, engine, fuel, battery, etc. to run. Traditionally we define the brand of such dependent objects along with the definition of the Car object

Without Dependency Injection (DI):

class Car
{
  private Wheel wh   = new ApolloWheel();
  private Battery bt = new ExideBattery();

  //The rest
}

Here, the Car object is responsible for creating the dependent objects.

What if we want to change the type of its dependent object – say Wheel – after the initial ApolloWheel() punctures? We need to recreate the Car object with its new dependency say SpareWheel(), but only the Car manufacturer can do that.

Then what does the Dependency Injection do us for…?

When using dependency injection, objects are given their dependencies at run time rather than compile time (car manufacturing time). So that we can now change the Wheel whenever we want. Here, the dependency (wheel) can be injected into Car at run time.

After using dependency injection:

class Car
{
  private Wheel wh   = [Inject an Instance of Wheel at runtime];
  private Battery bt = [Inject an Instance of Battery at runtime];

  Car(Wheel wh,Battery bt) 
  {
      this.wh = wh;
      this.bt = bt;
  }

  //Or we can have setters
  void setWheel(Wheel wh) 
  {
      this.wh = wh;
  }
}

Lets take the below example

public class Foo
{
    private Bar _bar;

    public Foo(Bar bar)
    {
        _bar = bar;
    }

    public bool IsPropertyOfBarValid()
    {
        return _bar.SomeProperty == PropertyEnum.ValidProperty;
    }
}

without dependency injection the Bar object is dependent and tightly coupled with Foo class like below

public class Foo
{
    private Bar _bar = new Bar();
    .
    . 
}

But by using dependency injection like before code you can mock the Bar Object at runtime and call the IsPropertyOfBarValid() method over it.

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.

Say the Excel Jar files with utility methods used the application uses the methods in the Utility Class and the flow is controlled by the way the method gets called in order the get the things done.

whereas

In framework like spring the implementation is defined in XML files and by using annotation and the framework calls the methods as per defined in xml.

Without Ioc

  Application -> Methods -> Framework      

With Ioc

  Framework -> XML File ->  Method Call (or) Implementation      

Inversion of Control(IoC) Container:
Common characteristic of frameworks IOC manages java objects

  1. From instantiation to destruction through its BeanFactory.
  2. Java components that are instantiated by the IoC container are called beans, and the IoC container manages a bean’s scope, lifecycle events, and any AOP features for which it has been configured and coded.

Flow of control is “inverted” by dependency injection because you have effectively delegated dependencies to some external system

The Inversion of Control (IoC) and Dependency Injection (DI) patterns are all about removing dependencies from your code.

For example, say your application has a text editor component and you want to provide spell checking. Your standard code would look something like this:

public class TextEditor
{
    private SpellChecker checker;
    public TextEditor()
    {
        this.checker = new SpellChecker();
    }
}

What we’ve done here is create a dependency between the TextEditor and the SpellChecker. In an IoC scenario we would instead do something like this:

public class TextEditor
{
    private ISpellChecker checker;
    public TextEditor(ISpellChecker checker)
    {
        this.checker = checker;
    }
}

Now, the client creating the TextEditor class has the control over which SpellChecker implementation to use. We’re injecting the TextEditor with the dependency.

Without IoC: you ask for “apple”, and you are always served apple when you ask more.

With IoC:
You can ask for “fruit”. You can get different fruits each time you get served. for example, apple, orange, or water melon.

Inversion of Control, (or IoC), is about getting
freedom (You get married, you lost freedom and you are being controlled. You divorced, you have just implemented Inversion of Control. That’s what we called, “decoupled”. Good computer system discourages some very close relationship.)

flexibility (The kitchen in your office only serves clean tap water, that is your only choice when you want to drink. Your boss implemented Inversion of Control by setting up a new coffee machine. Now you get the flexibility of choosing either tap water or coffee.)

less dependency (Your partner has a job, you don’t have a job, you financially depend on your partner, so you are controlled. You find a job, you have implemented Inversion of Control. Good computer system encourages in-dependency.)

IoC is a generic term meaning rather than having the application call the methods in a framework, the framework calls implementations provided by the application.Inversion of Control (IoC) means any sort of programming style where an overall framework or run-time controlled the program flow.

Dependency Injection is a Type of IoC

IoC means that objects do not create other objects on which they rely to do their work. Instead, they get the objects that they need from an outside service (for example, xml file or single app service).

DI means the IoC principle of getting dependent object is done without using concrete objects but abstractions (interfaces). This makes all components chain testable, cause higher level component doesn’t depend on lower level component, only from interface.

Techniques to implement inversion of control

  1. using a factory pattern
  2. using a service locator pattern
  3. using a dependency injection of any given below type:
    1. a constructor injection
    2. a setter injection
    3. an interface injection

DI is a form of IoC, where implementations are passed into an object through constructors/setters/service look-ups, which the object will ‘depend’ on in order to behave correctly.

IoC without using DI, for example would be the Template pattern because the implementation can only be changed through sub-classing.

DI Frameworks are designed to make use of DI and can define interfaces (or Annotations in Java) to make it easy to pass in implementations.

String Questions

  1. How to find the Longest Substring in String
  2. Swapping Letters in 2 Words
  3. Print String in Reverse Order
  4. Print Left Right Angle Triangle
  5. Inverted Right Triangle
  6. Print Right Angle Triangle
  7. Print Pyramid
  8. Sum of Pairs in Array of Numbers
  9. Check 2nd List has all elements in 1st List
  10. How to find String is anagram
  11. Check Palindrome
  12. Reverse of String without for loop and array
  13. Check Palindrome with recursion

1.How to find the Longest Substring in String
Input

String strSample = "ABCAAABCD"

Output

ABCD
public static void main(String[] args) 
{
   String Test = "ABCAAABCD";
   String dummy = ""; 
		
   String[] arrTest = Test.split("");
		
   List<String> seenChars = new ArrayList<String>();
   List<String> subStrings = new ArrayList<String>();
		
   int j = 0;
		
   for (int i = 1; i < arrTest.length; i++) 
   {
      if(seenChars.contains(arrTest[i]))
      {
	 subStrings.add(dummy);
	 dummy = "";
	 seenChars.clear();
      }
			
      seenChars.add(arrTest[i]);
      dummy += arrTest[i];
			
       j = i + 1;
			
       if(j == arrTest.length)
	  subStrings.add(dummy);
   }
		
   int highestNo = 0;
   int lastHighest = 0;
   int currHighestNo = 0;
   int highestPOS = 0;
	
   for(int k = 0; k < subStrings.size() ; k++)
   {
	currHighestNo = subStrings.get(k).length();
		
	if(currHighestNo  > lastHighest)
	{
  	  highestNo = currHighestNo;
	  highestPOS = k;
	}		
	  lastHighest = currHighestNo;
	}
		
	System.out.println(subStrings.get(highestPOS));		
}

Method 2

public static void main(String args[]) 
{
	String Test = "ABCDEAAABCDA";
	String dummy = "";

	String[] arrTest = Test.split("");
	String longestSubString = "";

	List<String> seenChars  = new ArrayList<String>();
	List<String> subStrings = new ArrayList<String>();

	for (String strTest : arrTest) 
	{
		if (seenChars.contains(strTest)) 
		{
			if (dummy.length() > longestSubString.length())
				longestSubString = dummy;

			subStrings.add(dummy);
			dummy = "";
			seenChars.clear();
		}
		
		seenChars.add(strTest);
		dummy += strTest;
	}
	
	if (dummy.length() > longestSubString.length())
	{
		longestSubString = dummy;		
		subStrings.add(dummy);	
	}
	 
	System.out.println("Longest subString is: " + "'" + longestSubString + "'" + " and length is: "
			+ longestSubString.length());
}

2.Swapping Letters in 2 Words
Input

MUGIL XXX

Output

MXUXGXIL
public class Array1 
{
 static List arrNewList1 = new ArrayList();
 
 public static void main(String[] args) 
 { 
   String text1 = "MUGIL";
   String text2 = "XXX"; 
 
   String[] arrList1 = text1.split("");
   String[] arrList2 = text2.split("");
 
   if(arrList2.length > arrList1.length)
    swapArrays(arrList2, arrList1);
   else 
    swapArrays(arrList1, arrList2);

 
 
   StringBuilder strBr = new StringBuilder();
 
   for (int i = 0; i < arrNewList1.size(); i++) 
    strBr.append(arrNewList1.get(i));
 
    System.out.println(strBr); 
 }
 
 public static void swapArrays(String[] pBigList, String[] pSmallList)
 { 
   for (int i = 0; i < pBigList.length; i++) 
   { 
     arrNewList1.add(pBigList[i]);
 
     if(i < pSmallList.length)
      arrNewList1.add(pSmallList[i]);
   }
 }
}

Note

 .
 .
 String Text1 = "M,U,G,I,L";
 String Text2 = "MUGIL";
		
 System.out.println(Text1.split(",").length);
 System.out.println(Text2.split("").length);
 .
 .

Output

5
6

you may be puzzled why first prints 5 and second prints 6.Thats because the empty space between “M is taken as 1 element in Text2

3.Print String in Reverse Order
Input

asanam

Output

asanam
package com.mugil.test;

public class ReverseString {

 public static void main(String[] args) {
  String strName = "manasa";

  //char[] arrNames = strName.toCharArray();

  String[] arrNames = strName.split("");

  for (int i = arrNames.length - 1; i >= 0; i--) {
   System.out.print(arrNames[i]);
  }
 }
}

4.Print Left Right Angle Triangle
Input

Total number of Rows - 5

Output

* 
** 
*** 
**** 
***** 
package com.mugil.test;

public class Patterns2 {
 public static void main(String[] args) {
  int rows = 5;

  for (int i = 1; i <= rows; i++) {
   for (int j = 1; j <= i; j++) {
    System.out.print("*");
   }

   System.out.println(" ");
  }
 }
}

5.Inverted Right Triangle
Input

Total number of Rows - 5

Output

***** 
**** 
*** 
** 
*  
.
int rows = 5;

for (int i = rows; i >= 0; i--) {
 for (int j = 1; j <= i; j++)
  System.out.print("*");

 System.out.println(" ");
}
.

6.Print Right Angle Triangle
Input

Total number of Rows - 5

Output

     * 
    ** 
   *** 
  **** 
 *****  
int n = 5;
int j = 0;
int k = 0;

for (int i = 0; i < n; i++) {
 for (j = n - i; j > 1; j--)
  System.out.print(" ");

 for (j = 0; j <= i; j++)
  System.out.print("*");

 System.out.println();

}

7.Print Pyramid
Input

Total number of Rows - 5

Output

    * 
   * * 
  * * * 
 * * * * 
* * * * *  
int n = 5;
int j = 0;
int k = 0;

for (int i = 0; i < n; i++) 
{
 for (j = n - i; j > 1; j--)
  System.out.print(" ");

 for (j = 0; j <= i; j++)
  System.out.print("* ");

 System.out.println();

}

The only Difference between Right Angle Triangle and Pyramid is Space in *

8.Sum of Number Pairs in Array
Input

Array of Numbers - {0,1,2,2,3,4}
Sum - 4

Output

(0,4)
(1,3)
(2,2)
.
Integer[] arrNumbers = { 0, 1, 2, 2, 3, 4, 5};
int sum = 4;

for (int i = 0; i < arrNumbers.length; i++) {
 for (int j = i + 1; j < arrNumbers.length; j++) {
  if (arrNumbers[i] + arrNumbers[j] == sum) {
   System.out.println("(" + arrNumbers[i] + "," + arrNumbers[j] + ")");
  }
 }
}
.

9.Check 2nd List has all elements in 1st List
Input

2 List of Elements
{1,2,3,4}{2,3}
{1,2,3,4}{2,5}
{2,3}{2,5,6}  
{2,3}{2,3,9}  

Output

{1,2,3,4}{2,3}  -> true
{1,2,3,4}{2,5}  -> false
{2,3}{2,5,6}    -> false
{2,3}{2,3,9}    -> false
public boolean checkEquals()
{
  Integer orig[] = {1,2,3,4};
  Integer act[] = {2,3};
           
  List origList = new ArrayList(Arrays.asList(orig));
  List actList = Arrays.asList(act);
   
  origList.retainAll(actList);
  System.out.println(origList);
      
  if(actList.size()==origList.size())   
    return true;
  else
    return false; 
}

10.How to find String is anagram?
Output

Keep and Peek are anagrams
silent and listen are anagrams
MotherInLaw and HitlerWoman are anagrams
public class AnagramString 
{
 static void isAnagram(String str1, String str2) 
 {
  String s1 = str1.replaceAll("\\s", "");
  String s2 = str2.replaceAll("\\s", "");
  boolean status = true;

  if (s1.length() != s2.length()) 
   status = false;
  else 
  {
   char[] ArrayS1 = s1.toLowerCase().toCharArray();
   char[] ArrayS2 = s2.toLowerCase().toCharArray();
   Arrays.sort(ArrayS1);
   Arrays.sort(ArrayS2);
   status = Arrays.equals(ArrayS1, ArrayS2);
  }

  if (status)
   System.out.println(s1 + " and " + s2 + " are anagrams");
  else
   System.out.println(s1 + " and " + s2 + " are not anagrams");  
 }

 public static void main(String[] args) 
 {
  isAnagram("Keep", "Peek");
  isAnagram("silent", "listen");
  isAnagram("Mother In Law", "Hitler Woman");
 }
}

11.Check Palindrome
Input

malayalam

Output

Entered string is a palindrome
 public static void main(String args[])
 {
      String original, reverse = "";
      original = "madam";
 
      int length = original.length();
 
      for ( int i = length - 1; i >= 0; i-- )
         reverse = reverse + original.charAt(i);
 
      if (original.equals(reverse))
         System.out.println("Entered string is a palindrome.");
      else
         System.out.println("Entered string is not a palindrome."); 
  }

12.Reverse of String without for loop and array
Input

mugil

Output

ligum
static String reverseMe(String s) 
{
   if(s.length() <= 1)
     return s;

   return s.charAt(s.length() - 1) + reverseMe(s.substring(0,s.length()-1));
 }

13.Check palindrome using recursion
Input

malayalam

Output

palindrome

Call the above reverse function and check with string equals method

public static boolean isPalindrome(String input) 
{
 if (input == null)
  return false;

 String reversed = reverse(input);
 return input.equals(reversed);
}

public static String reverse(String str) 
{ 
 if (str == null) 
  return null;
 
 if (str.length() <= 1) 
  return str;
 
 return reverse(str.substring(1)) + str.charAt(0);
}

length – arrays (int[], double[], String[]) —- to know the length of the arrays.

length() – String related Object (String, StringBuilder etc)to know the length of the String

size()– Collection Object (ArrayList, Set etc)to know the size of the Collection

length is not a method, so it completely makes sense that it will not work on objects. Its only works on arrays.

Points to Note

  1. ArrayList allows NULL values many times
  2. Set and HashMap allows NULL once
  3. In HashMap the values will be overwritten when keys are same

List An ordered collection (also known as a sequence). The user of this interface has precise control over where in the list each element is inserted. The user can access elements by their integer index (position in the list), and search for elements in the list.

MapAn object that maps keys to values. A map cannot contain duplicate keys; each key can map to at most one value.

Test.java

public class Test
{
 public static void main(String[] args) 
 {
 List<String> arrNames = new ArrayList<String>();
 
 arrNames.add("Hello");
 arrNames.add(null);
 arrNames.add(null);
 arrNames.add("Hi"); 
 System.out.println("List - "+arrNames.size());
 
 Map hmTest = new HashMap();
 hmTest.put("1", "mugil");
 hmTest.put(null, null);
 hmTest.put(null, null);
 hmTest.put("1", "vannan");
 System.out.println("HashMap - "+ hmTest.size());
 
 Set<Integer> setTest = new HashSet<Integer>();
 
 setTest.add(new Integer("10"));
 setTest.add(new Integer("20"));
 setTest.add(new Integer("10"));
 
 System.out.println("Set - "+ setTest.size());
 }
}

Output

List - 4
HashMap - 2
Set - 2

If I write something like this

 System.out.println(19);

Which type has the ’19’? Is it int or byte? Or doesn’t it have a type yet?
This 19 is known as an integer literal. There are all sorts of literals, floating point, String, character, etc.

What is integer literal
Integer data types consist of the following primitive data types: int,long, byte, and short.byte, int, long, and short can be expressed in decimal(base
10), hexadecimal(base 16) or octal(base 8) number systems as well.
Prefix 0 is used to indicate octal and prefix 0x indicates hexadecimal when using these number systems for literals.

Examples:

int decimal = 100;
int octal = 0144;
int hexa =  0x64;

Literal means any number,Text or Other information that represents a value.

Different Values that can be assigned to Integer Variable (Integer data type Literal) are

  1. Decimal Literals
  2. Octal Literals
  3. Hexadecimal Literals
  4. Binary Literals
  5. Long Literals
  6. Values with Underscore in Between

Why main() method is Static

  1. the main function is where a program starts execution. It is responsible for the high-level organization of the program’s functionality, and typically has access to the command arguments given to the program when it was executed.
  2. main() is static because at that point in the application’s lifecycle, the application stack is procedural in nature due to there being no objects yet instantiated.It’s a clean slate. Your application is running at this point, even without any objects being declared (remember, there’s procedural AND OO coding patterns). You, as the developer, turn the application into an object-oriented solution by creating instances of your objects and depending upon the code compiled within.
  3. static allows main() to be called before an object of the class has been created. This is neccesary because main() is called by the JVM before any objects are made. Since it is static it can be directly invoked via the class.
  4. The method is static because there would be ambiguity: which constructor should be called? Especially if your class looks like this:
    public class JavaClass
    {
      protected JavaClass(int x){}
    
      public void main(String[] args)
      {
      }
    }
    

    If the JVM call new JavaClass(int)? What should it pass for x?

What would be the Output

public class Test 
{
    static
    {
      System.out.println("Hi static 1");        
    }

    public static void main(String[] args) 
    {
        System.out.println("Hi main");
    }

    static
    {
        System.out.println("Hi static 2");        
    }
}

Output

Hi static 1
Hi static 2
Hi main

What happens when you run a class without main() method
Say, file Demo.java contains source code as

public class Demo{ 

}

when this code is compiled as it’s compile successfully as

$javac Demo.java

but when it’s executed as

$java Demo

then it shows an exceptional error

Main method not found in class Demo, please define the main method as: public static void main(String[] args)

so compiler is not responsible to check whether main() method is present or not. JVM is responsible for it. JVM check for main() method with prototype as

public static void main(Strings[] args)

Why JVM search main() method? Is it possible to change main() method into any other method main_hero()?
JVM is instructed to find main() method from inside JVM. Yes, it’s possible to change main() method into main_hero() method but inside JVM you must have to instruct to search main_hero() method.

Why public?
call from anywhere public is used.

Why void?
JVM is going to call main() method but what can JVM do with return value if main() method return.

Can we declare main() method as private or protected or with no access modifier?
No, main() method must be public. You can’t define main() method as private or protected or with no access modifier. This is because to make the main() method accessible to JVM. If you define main() method other than public, compilation will be successful but you will get run time error as no main method found.

Can We Declare main() Method As non-static?
No, main() method must be declared as static so that JVM can call main() method without instantiating it’s class. If you remove ‘static’ from main() method signature, compilation will be successful but program fails at run time.

Most of the Errors incase of change of main() method are runtime errors