Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Create a class called Lab3. Use the same setup for setting up your class and mai

ID: 675312 • Letter: C

Question

Create a class called Lab3. Use the same setup for setting up your class and main method as you did for the previous assignments. Be sure to name your file Lab3. In your main method, write a segment of code which will read in two strings and output whether the strings are equal or not. For example, if both Strings have the value "hello", the following should be printed: If the strings have different values, for example the first String had "hello" and the second String had "world", then the following should be printed: The strings are not the same. The strings can contain spaces in them, so be sure to use the nextLine() method of the Scanner class to read them in. Question for thought (You do not have to submit your answer): What happens if instead of using the equals method, you use = to compare two Strings? Change your code and input the same string and see what the output is.

Explanation / Answer

import java.util.Scanner;


public class Lab3 {

   public static void main(String[] args) throws Exception{

       Scanner sc = new Scanner(System.in);
      
       System.out.println("Enter first string: ");
       String str1 = sc.nextLine();
      
       System.out.println("Enter second string: ");
       String str2 = sc.nextLine();
      
       //if you want to eliminate spaces at both ends then use str1.trim() and str2.trim() - below line
       //if(str1.trim().equals(str2.trim()))
      
       if(str1.equals(str2))
           System.out.println("The strings are the same");
       else
           System.out.println("The strings are not the same");
   }
}

------------------------output----------------------------------

Enter first string:
Hello
Enter second string:
hello
The strings are not the same

Enter first string:
Hellow World
Enter second string:
Hellow World
The strings are the same

import java.util.Scanner;


public class Lab3 {

   public static void main(String[] args) throws Exception{

       Scanner sc = new Scanner(System.in);
      
       System.out.println("Enter first string: ");
       String str1 = sc.nextLine();
      
       System.out.println("Enter second string: ");
       String str2 = sc.nextLine();
      
        if(str1 == str2) //its comparing objects
           System.out.println("The strings are the same");
       else
           System.out.println("The strings are not the same");
   }
}

--------------------output-----------------------------

Enter first string:
Hello
Enter second string:
Hello
The strings are not the same

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote