Write a Java Program to Differentiate String == operator and equals() method

Java Program to Differentiate String == operator and equals() method

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn Java programming concepts. You can learn Java  language at your own speed and time. One can learn concepts of Java language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Java Program to Differentiate String == operator and equals() method
Java Program to Differentiate String == operator and equals() method

Write a Java Program to Differentiate String == operator and equals() method

PROGRAM: Java Program to Differentiate String == operator and equals() method

/*Java Program to Differentiate String == operator and equals() method*/

1: Java program to differentiate == and equals()

class Main {

public static void main(String[] args) {

String name1 = new String(“Programiz”);
String name2 = new String(“Programiz”);

System.out.println(“Check if two strings are equal”);

// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println(“Using == operator: ” + result1);

// using equals() method
boolean result2 = name1.equals(name2);
System.out.println(“Using equals(): ” + result2);
}
}

2: Differentiate == and equals()

class Main {

public static void main(String[] args) {

String name1 = new String(“Programiz”);
String name2 = name1;

System.out.println(“Check if two strings are equal”);

// check if two strings are equal
// using == operator
boolean result1 = (name1 == name2);
System.out.println(“Using == operator: ” + result1);

// using equals() method
boolean result2 = name1.equals(name2);
System.out.println(“Using equals(): ” + result2);
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *