Java substring with one char - java

I have
String x = g.substring(0, 1);
if (x == "S") {
stuff
}
I have a string, "Safety", but "stuff" doesn't run and my watch say x value = S and x=="S" = false.

== is used for identity comparison, and it checks whether the two reference points to the same object (in your case the object is String).
You should use the equals method to compare the contents of your string:
if (x.equals("S"))

This compares references not string equality x=="S" you should use "S".equals(x).

Use equals() method of String class instead, not ==.

if(x.equals("S"))
== checks the reference and not the value.

You should use the .equals method to compare Strings (and any non-primitives in general).
if (x.equals("S")) {
//stuff
}

Many problems...
Your variable x is a String! You shouldn't use == operator with that, use .equals() instead
Also, while you're at it, you should use .equalsIgnoreCase() to ignore case.
By the way, I should note that there is the String.charAt(int) function too, which returns the character at the specified place...
But if you would like to select all Strings (your question didn't reveal your original intentions why and what you are trying to achieve), but I'd look into regular expressions, and using String.matches()

You need to use String.equals for comparing string content. The == operator is used for comparing object references.
Switching the positions of the arguments will avoid a NullPointerException:
if ("S".equals(x))

In Java equals() checks equality and == checks identity.

Why don't you use the charAt function and do it like this:
char x = g.charAt(0);
if (x == 'S') {
// Stuff
}
If you don't want to use char, use the equals method in the if block comparison as:
String x = g.substring(0, 1);
if (x.equals("S")) {
// stuff
}

Related

What is the difference between python and java == operator

Can somebody explain to me why Python is able to print the following statement bellow while Java doesn't. I know it's something to do with == in Java and equals() but I don't really understand the difference.
Python code
str1 = "Pro"
str2 = str1 + ""
if str1 == str2:
print("the strings are equal")```
Java Code
public class StringEq {
public static void main(String[] args) {
String str1 = "Pro";
String str2 = str1 + "";
if (str1 == str2) {
System.out.println("The strings are equal");
}
}
}
Python's str class uses value-equality for its __eq__ method. In Python, classes can override __eq__ to define how == behaves.
Contrast that with Java where == always does reference-equality. In Java, == will only return true if both objects are literally the same object; regardless of their content. Java's == is more comparable to Python's is operator.
A better comparison, as noted in the comments, would be to compare these:
"a".equals("a") // Java
"a" == "a" # Python
Java's String class has its equals do a value equality instead of of reference equality.
In python == is used to compare the content of the objects by overriding the operator.eq(a, b) method, str class has overridden this in order to compare the content of objects
These are the so-called “rich comparison” methods. The correspondence
between operator symbols and method names is as follows: x<y calls
x.__lt__(y), x<=y calls x.__le__(y), x==y calls x.__eq__(y), x!=y calls
x.__ne__(y), x>y calls x.__gt__(y), and x>=y calls x.__ge__(y).
But in java == operator is used compare the reference of objects here
Using the “==” operator for comparing text values is one of the most common mistakes Java beginners make. This is incorrect because “==” only checks the referential equality of two Strings, meaning if they reference the same object or not.
so in java to compare the content of object you have to use equals which is overridden in String class.
if (str1.equals(str2))
so java == operator is equal to is operator in python which compare both references are pointed to same object or not
It explains it well here:
And here is a quote from that site:
"We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects."

Can't get else if statement to work in Java

Ok I am trying to make this simple thing but it won't work. I am a beginner in Java and would like some help. Every time I run the code below I get the output That is not a valid option. What am I doing wrong?
package test;
import java.util.Scanner;
public class options {
public void options() {
Scanner scnr = new Scanner(System.in);
String slctn;
System.out.println("What would you like to do?");
System.out.println("a) Travel the expedition");
System.out.println("b) Learn more about the expedition");
slctn = scnr.nextLine();
if (slctn == "a"){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn=="b"){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}
}
}
Well, first off, == is a fundamental operator in the language. The result type of the expression is a boolean. For comparing boolean types, it compares the operands for the same truth value. For comparing reference types, it compares the operands for the same reference value (i.e., refer to the same object or are both null). For numeric types, it compares the operands for the same integer value or equivalent floating point values. See the Java Language Specification.
In contrast, equals() is an instance method which is fundamentally defined by the java.lang.Object class. This method, by convention, indicates whether the receiver object is "equal to" the passed in object. The base implementation of this method in the Object class checks for reference equality. Other classes, including those you write, may override this method to perform more specialized equivalence testing. See the Java Language Specification.
The typical "gotcha" for most people is in using == to compare two strings when they really should be using the String class's equals() method. From above, you know that the operator will only return "true" when both of the references refer to the same actual object. But, with strings, most uses want to know whether or not the value of the two strings are the same -- since two different String objects may both have the same (or different) values.
slctn = scnr.nextLine();
if (slctn.equals("a")){
travel exeTravel = new travel();
exeTravel.travel();
}else if (slctn.equals("b")){
learn exeLearn = new learn();
exeLearn.learn();
}else{
System.out.println("That is not a valid option");
}
slctn.equals("a") will work.
Read this to understand why: What is difference between == and equals() in java?
In Java, when you need to compare two objects for equality (that is, to determine if they have the same value) you must use equals(). The == operator is used for testing if two objects are identical, that is: if they're exactly the same object in memory. In your code, replace this:
slctn == "a"
slctn == "b"
With this:
"a".equals(slctn)
"b".equals(slctn)
Also notice that it's a good idea to invert the order of the comparison ("a" before slctn), just in case slctn is null.
In java when matching any object the == operator will only match the reference of those two objects.
If we take your example slctn == "a". Say slctn has its reference value at abc123, your other sting "a" will have a different reference value as it is not the same object.
The method .equals checks what the letters in the string object are and matches the value of the letters in the two strings. Therefore if your object slctn contains "a", it will match with the string "a"
In java == operator compare reference of two objects, for sample :
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1 == s_2);
result will is :
false
this happen because s_1 is a reference at memory and s_2 is difference refernce at memroy also.
For solve this issue , you have to compare tow objects by equals method. for sample
String s_1 = new String("Sample");
String s_2 = new String("Sample");
System.out.println(s_1.equals(s_2));
result will is :
true

how to check reference equality in an object which implements content equality?

...in other words:
let's suppose I have 2 Strings declared as so:
String one = new String("yay!");
String two = new String("yay!");
these two Strings are two different objects, but if I run
if(one.equals(two))
System.out.println("equals() returns true.");
I get "equals() returns true".
This is because the String class overrides the equals() method to implement a content level equality.
However, I need to access a reference level equality (like the one implemented in Object) to distinguish the object one form the object two.
How can I do that?
I tried this:
one.getClass().getSuperclass().equals();
to try to invoke the Object equals() method of the String one but it didn't work.
Any advice?
If you want to check reference just perform:
one == two
But be careful with strings. There is a thing called String constant pool so they may refer to the same object.
String in java uses a String Literal Pool, this means is: "When you try construct a string, first String class search in Literal Pool for traditional same string ,if exist return it, and if don't exist create it", so you can't check by equals method compare refernce of String instance, you have to use == operator as following:
String one = new String("yay!");
String two = new String("yay!");
if(one.equals(two))
System.out.println("equals() returns true.");
if(one == two)
System.out.println(" == operator returns true.");
result is :
equals() returns true.
see following link for more information:
http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/
Java String.equals versus ==
Use simple == comparison. However to avoid String interning you have to create your Strings using char arrays such as: String me = new String(new char[] { 'm', 'e' }); instead of using String literals "me" such as String me = new String("me");.
if (one == two)
System.out.println("one and two are the same object");
The only this you need is "==" equality operator.

Comparing two identical strings with == returns false [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 9 years ago.
I am making an archive for my family. There are no syntax errors, however whenever I type in "Maaz", it evaluates realName == "Maaz" to false and goes to the else statement.
import java.util.Scanner;
public class MainFamily {
public static void main (String [] args) {
System.out.println("Enter you're name here");
Scanner name = new Scanner(System.in);//Scanner variable = name
String realName;
realName = name.nextLine();//String variable = user input
System.out.println("Name: "+ realName);
if (realName == "Maaz") {
System.out.println("Name: Maaz");
} else {
System.out.println("This person is not in the database");
}
}
}
TL;DR
You wrote (this doesn't work):
realName == "Maaz"
You meant this:
realname.equals("Maaz")
or this:
realname.equalsIgnoreCase("Maaz")
Explanation
In Java (and many other Object-Oriented programming languages), an object is not the same as a data-type. Data-types are recognized by the runtime as a data-type.
Examples of data-types include: int, float, short.
There are no methods or properties associated with a data-type. For example, this would throw an error, because data-types aren't objects:
int x = 5;
int y = 5;
if (x.equals(y)) {
System.out.println("Equal");
}
A reference is basically a chunk of memory that explicitly tells the runtime environment what that data-block is. The runtime doesn't know how to interpret this; it assumes that the programmer does.
For example, if we used Integer instead of int in the previous example, this would work:
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x.equals(y)) {
System.out.println("Equal");
}
Whereas this would not give the expected result (the if condition would evaluate to false):
Integer x = new Integer(5);
Integer y = new Integer(5);
if (x == y) {
System.out.println("Equal");
}
This is because the two Integer objects have the same value, but they are not the same object. The double equals basically checks to see if the two Objects are the same reference (which has its uses).
In your code, you are comparing an Object with a String literal (also an object), which is not the same as comparing the values of both.
Let's look at another example:
String s = "Some string";
if (s == "Some string") {
System.out.println("Equal");
}
In this instance, the if block will probably evaluate to true. Why is this?
The compiler is optimized to use as little extra memory as is reasonable, although what that means depends on the implementation (and possibly runtime environment).
The String literal, "Some string", in the first line will probably be recognized as equivalent to the String literal in the second line, and will use the same place in memory for each. In simple terms, it will create a String object and plug it into both instances of "Some string". This cannot be relied upon, so using String.equals is always a better method of checking equivalence if you're only concerned with the values.
do this instead
if (realName.equals("Maaz"))
equals() should be used on all non-primitive objects, such as String in this case
'==' should only be used when doing primitive comparisons, such as int and long
use
if(realName.equals("Maaz"))
use == with primitive data type like int boolean .... etc
but if you want to compare object in java you should use the equals method
You have to compare objects with realName.equals ("Maaze"), not with ==.
It is best practice to compare Strings using str.equals(str2) and not str == str2. As you observed, the second form doesn't work a lot of the time. By contrast, the first form always works.
The only cases where the == approach will always work are when the strings are being compared are:
string literals or references to string literals, or
strings that have been "interned" by application-level code calling str = str.intern();.
(And no, strings are not interned by default.)
Since it is generally tricky to write programs that guarantee these preconditions for all strings, it is best practice to use equals unless there is a performance-related imperative to intern your strings and use ==.
Before that you decide that interning is a good idea, you need to compare the benefits of interning with the costs. Those costs include the cost of looking up the string in the string pool's hash table and the space and GC overheads of maintaining the string pool. These are non-trivial compared with the typical costs of just using a regular string and comparing using equals.
You can also use
realname.equalsIgnoreCase("Maaz")
This way you can accept Maaz, maaz, maaZ, mAaZ, etc.
== tests shallow equality. It checks if two objects reference the same location in memory.
Intriguing. Although, as others have stated, the correct way is to use the .equals(...) method, I always thought strings were pooled (irrespective of their creation). It seems this is only true of string literals.
final String str1 = new String("Maaz");
final String str2 = new String("Maaz");
System.out.println(str1 == str2); // Prints false
final String str3 = "Laaz";
final String str4 = "Laaz";
System.out.println(str3 == str4); // Prints true
Since you are working on strings, you should use equals to equalsIngnorecase method of String class. "==" will only compare if the both objects points to same memory location, in your case, both object are different and will not be equal as they dont point to same location. On the other hand, equals method of String class perform a comparison on the basis of the value which objects contains. Hence, if you will use equals method, your if condition will be satisfied.
== compares object references or primitive types (int, char, float ...)
equals(), you can override this method to compare how both objects are equal.
for String class, its method equal() will compare the content inside if they are the same or not.
If your examples, both strings do not have the same object references, so they return false, == are not comparing the characters on both Strings.
It seems nobody yet pointed out that the best practice for comparing an object with a constant in Java is calling the equals method of the constant, not the variable object:
if ("Maaz".equals (realName)) {}
This way you don't need to additionally check if the variable realName is null.
if(realName.compareTo("Maaz") == 0) {
// I dont think theres a better way do to do this.
}

Creating Strings from Bytes/Ints in Java

I'm wondering why the following code doesn't work:
String test = new String(new byte[] {92, 92, 92, 92, 92});
System.out.println(test);
String compare = "\\\\\\\\\\";
System.out.println(compare);
if (test == compare) {
System.out.println("Yes!");
}
The output is:
\\\\\
\\\\\
Where is a data type conversion happening that I'm not understanding?
Edit: /fail :(
Strings are compared with .equals(), not with ==
The reason is that with references (as string variables are), == just checks equality in memory location, not in content.
The literal \\\ existed in one place in memory. the other one is created somewhere else where you build the string. They're not in the same location, so they don't return true when you do ==
You should do
if(test.equals(compare))
Strings in Java are reference types, and == checks whether they are the same string, rather than equal strings. Confusing I know. Long story short you need to do this:
if( test.equals( compare ) ) {
For more you can see here: http://leepoint.net/notes-java/data/strings/12stringcomparison.html
You are testing to see if those are the same object, not if they are equal strings.
However the following test will be true:
test.intern() == compare.intern()
You are using identity comparison, rather than string comparison.
Try test.equals(compare). Then try test.intern() == compare. Both should work. The intern method is the only reliable way to perform object identity comparisons on String objects.

Categories