CompoundName compareTo() method in Java with Examples
Last Updated :
27 Mar, 2020
The compareTo() method of a javax.naming.CompoundName class is used to compare this CompoundName with the specified object passed as a parameter. It returns a negative integer, zero, or a positive integer as this CompoundName object is less than, equal to, or greater than the given Object as a parameter. If the passed object is null or not an instance of CompoundName then the ClassCastException is thrown by this method.
Syntax:
public int compareTo(Object obj)
Parameters: This method accepts obj which is the non-null object to compare against.
Return value: This method returns a negative integer, zero, or a positive integer as this Name is less than, equal to, or greater than the given Object.
Exception: This method throw ClassCastException if passed obj is not a CompoundName object.
Below programs illustrate the CompoundName.compareTo() method:
Program 1:
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args)
throws InvalidNameException
{
Properties props = new Properties();
props.put( "jndi.syntax.separator" , ":" );
props.put( "jndi.syntax.direction" ,
"left_to_right" );
CompoundName CompoundName1
= new CompoundName( "x:y:z" ,
props);
CompoundName CompoundName2
= new CompoundName( "x:y:m" ,
props);
int value
= CompoundName1
.compareTo(CompoundName2);
if (value > 0 )
System.out.println(
"CompoundName1 is "
+ "greater than CompoundName2" );
else if (value < 0 )
System.out.println(
"CompoundName1 is "
+ "smaller than CompoundName2" );
else
System.out.println(
"CompoundName1 is "
+ "equal to CompoundName2" );
}
}
|
Output:
CompoundName1 is greater than CompoundName2
Program 2:
import java.util.Properties;
import javax.naming.CompoundName;
import javax.naming.InvalidNameException;
public class GFG {
public static void main(String[] args)
throws InvalidNameException
{
Properties props = new Properties();
props.put( "jndi.syntax.separator" , "@" );
props.put( "jndi.syntax.direction" ,
"left_to_right" );
CompoundName CompoundName1
= new CompoundName(
"x@y@z@M@n" ,
props);
CompoundName CompoundName2
= new CompoundName(
"x@y@z@M@n" ,
props);
int value
= CompoundName1
.compareTo(CompoundName2);
if (value > 0 )
System.out.println(
"CompoundName1 is "
+ "greater than CompoundName2" );
else if (value < 0 )
System.out.println(
"CompoundName1 is "
+ "smaller than CompoundName2" );
else
System.out.println(
"CompoundName1 is "
+ "equal to CompoundName2" );
}
}
|
Output:
CompoundName1 is equal to CompoundName2
References: https://docs.oracle.com/javase/10/docs/api/javax/naming/CompoundName.html#compareTo(java.lang.Object)
Share your thoughts in the comments
Please Login to comment...