hi guys im working on a project for creating my own custom datepicker in java. but I got stuck here in a place when using the split method.when i split a string into array of strings, and run a loop through the array to find a specific value and if that specific value is found within the array, then to print that "the value blalala is found,but it doesn’t work the way i expect it to.even if "dd" is available it doesn’t print "dd is here".ill provide the code below here
public static void main(String[] args) {
String date="dd/mm/yyyy";
String[] datesplit=date.split("/", 5);
for(int c=0;c<=2;c++)
{
if(datesplit[c]=="dd")
{
System.out.println("dd is here");
}
}
}
but if i loop through the array and print every value, it outputs every value
public static void main(String[] args) {
String date="dd/mm/yyyy";
String[] datesplit=date.split("/", 5);
for(int c=0;c<=2;c++)
{
System.out.println(datesplit[c]);
}
but I’ve tried it without the split method by creating an array manually and then looping through it to find the value i want and print "the value is found". surprisingly it works.
public static void main(String[] args) {
String[] date={"dd","mm","yyyy"};
for(int c=0;c<=2;c++)
{
if(date[c]=="dd")
{
System.out.println("dd is here");
}
}
I’m baffled why the array is buggy when using the split method().any ideas
>Solution :
You’re confronting two references with the == operator.
if(datesplit[c]=="dd")
You cannot do that. References must be confronted with the equals method. The == operator checks the content of two variables. A reference contains the memory address of the object it points to, therefore when you’re performing if(datesplit[c]=="dd"), you’re checking if the address contained within datesplit[c] is equal to the address of the reference containing "dd", which are of course different since they point to two different objects in memory. The == can be used only for primitive types as they contain the actual value they represent.
What you need to do is write your comparison with the equals method like so:
public static void main(String[] args) {
String date = "dd/mm/yyyy";
String[] datesplit = date.split("/", 5);
for (int c = 0; c <= 2; c++) {
if (datesplit[c].equals("dd")) {
System.out.println("dd is here");
}
}
}