I am writing some code to check if two strings are anagrams, in Java. This is for the Anagrams problem on Hackerrank.
My code is failing only 1 of the 17 test cases, and I'm guessing it's due to invalid inputs. This is where my issue lies. At the very beginning of the method, I want to check if either input string is null or an empty string, and if it is, I return false.
This is the relevant code block -
private static boolean isAnagram(String a, String b) {
System.out.println(a + " " + b);
if( a == null || b == null || a.equals("") || b.equals("") ) {
System.out.println("Inside");
return false;
}
HashMap<String, Integer> map1 = new HashMap<>();
HashMap<String, Integer> map2 = new HashMap<>();
The problem is, when I test this method with invalid inputs, like "hello" and "", the if block doesn't seem to execute. I've tried replacing the .equals() method with .isEmpty() and .length() == 0, but no matter which method I use, the if doesn't work.
Using JShell, I've checked that if I create an empty string with "", all these methods work -
jshell> String a = ""
a ==> ""
jshell> a.isEmpty()
$2 ==> true
jshell> a.length()
$3 ==> 0
jshell> a.equals("")
$4 ==> true
jshell> a == null
$5 ==> false
jshell> "" == ""
$6 ==> true
jshell>
jshell> "".equals("")
$7 ==> true
jshell> "".length()
Is there a reason why this way of checking for empty string won't work in an if block?
UPDATE - Complete code on Pastebin
I see that you don't pass one test case, and it does not involve invalid inputs. You've missed one thing, you should take into consideration case sensitivity
a = a.toLowerCase();
b = b.toLowerCase();
Just make your strings lowercase after validation and it should be alright
Related
How to break the conditional code you can see below into a regular if-statement to understand how it works, since it has three results.
I changed values just to see where its going:
System.out.print(("A"=="A")?("B"=="B")?"1":"2":"3");
/*
if A is False (Output = 3)
if B is False (Output = 2)
if A&B are True (Output = 1)
*/
The conditional (ternary) operator works in the following manner:
(predicate) ? (onTrueValue) : (onFalseValue);
so in your case what we have is :
("A"=="A" ? ("B"=="B" ? "1" : "2") : "3");
Which evals to:
Is A equal to A?
If yes -> return Is B equal to B
If yes -> return 1;
If no -> return 2;
If no -> return 3;
Similar to:
condition1 ? (condition2 ? val1 : val2) : val3;
And some tests for verification
// Prints 1 as both conditions are true.
System.out.println("A"=="A" ? ("B"=="B" ? "1" : "2") : "3");
// Prints 3 as first condition fails.
System.out.println("A"=="notA" ? ("B"=="B" ? "1" : "2") : "3");
// Prints 2 as second condition fails.
System.out.println("A"=="A" ? ("B"=="notB" ? "1" : "2") : "3");
Also note that your are uising the == operator for comparing strings. In this particular case this will give no difference just use it with caution...
Your code can be split like this:
String message;
if ("A" == "A") {
if ("B" == "B") {
message = "1";
} else {
message = "2";
}
} else {
message = "3";
}
System.out.print(message);
A ternary operator works like an if-statement that returns a value. However it can only be places where an expression could stand, so it cannot stand on it's own.
The part before the ? is the condition, the one after is the then expression. Behind the : is the else expression.
Nested ternary ?: operators are very bad to read, and should definetly be avoided.
If i understand you correctly and A, B, and C are booleans, this might be what you want:
System.out.print( ((!A)? "3" : (!B)? "2" : "1"));
For Strings you'd have to make sure to use A.equals(B).
please help me i cant figure out how does the operators(AND, NOT, XOR ,,..ETC) work in java. I know the output of AND and OR but i am clueless at NOT. For example i don't completely understand statement such as a variable != integer(i!= 3). i mean how does the NOT operator work.for example how does NOT work here.
class Demo {
public static void main(String args[]) throws java.io.IOException {
char ch;
do {
System.out.print("Press a key followed by ENTER: ");
ch = (char) System.in.read(); // get a char
} while (ch != 'q');
}
}
if you make some System outs you will figure out:
char ch = 'l';
System.out.print(2 != 3);
--true, they are not equal
System.out.print('q' != 'q');
-- false, they are equals
System.out.print(ch != 'q');
-- true, they are not equals
it means, they != checks if they are exactly the same (be careful in this case is used for primitive types, such as int, char, bool, etc. this operator work differently in objects, such as String)
int x = 4;
int y = 5;
!case a means not case a
x == y means x and y are referencing the same place in memory (to understand what that means, see this question).
x != y is the opposite of the above, and is the same as writing !(x == y) (not x equals y)
case a && case b And operator - Both case a and case b are true.
case a || case b Or operator - Either case a or case b are true.
Here are same examples so everything is clearer:
1==1 // true, as 1 is equal to 1
2==1 // false, as 1 is not equal to 2.
!true // false, as not true is false.
1!=1 // false, as 1 is equal to one.
!(1==1) // The same as above - exact same output.
// You need the brackets, because otherwise it will throw an error:
!1==1 // Error - what's '!1'? Java is parsed left-to-right.
true && false // false - as not all cases are true (the second one is false)
true || false // rue - as at least one of the cases are true (the first one)
The ! operator is unary. When applied to Boolean values it switches, for example
bool on = true;
System.out.print(!on); //false
System.out.print(on); //true
When used next to an equal sign, it checks if the values are not equal. If they are not equal, it returns true. Otherwise, it returns false. For example,
int two = 2;
int three = 3;
System.out.print(two != three);
//returns true, since they are not equal
System.out.print(two == three);
//returns false, since they are not equal
I've been using JShell a bit just to test it out, and today I came across quite the interesting bit of behavior.
jshell> String a = "A"
a ==> "A"
jshell> String b = "A"
b ==> "A"
jshell> a == b
$4 ==> true
jshell> "A" == "A"
$5 ==> true
I was first wondering if this was a feature of Java 9, and I checked it out by compiling and running this program with Java 9
public class Equus {
public static void main(String... args) {
String a = "A";
String b = "A";
System.out.println("a == b");
System.out.println(a == b);
System.out.println("\"A\" == \"A\"");
System.out.println("A" == "A");
}
}
And interestingly enough I got
a == b
true
"A" == "A"
true
As my output as well. What's going on here? Why are a and b equal to each other and why is "A" == "A" true?
Why shouldn't it be? This behaviour is exhibited in previous Java versions as well - String literals are interned.
As you know, == checks for reference equality - the two variables have the same memory address. When a String is interned, all references of that string point to the intern pool and thus will be equal using ==.
I just wanted to add this demonstration alongside Sinkingpoint's fine answer.
It's not safe to use == on Strings unless you know the origin of each, since a String that is built-up in some way (such as the new String("A") in Eli's comment or the .toString() used here) is not the same reference even if the two do use the same underlying character array.
class Main
{
public static void main(String[] args)
{
String oneA = "A";
String twoA = "A";
String three = new StringBuilder().append('A').toString();
// We expect constant literals to be ==
System.out.print("A == A -> ");
System.out.println("A" == "A");
// Variables assigned the same literal are also ==
System.out.print("oneA == twoA -> ");
System.out.println(oneA == twoA);
// but a built-up String var is not == to the "literal" var.
System.out.print("oneA == three -> ");
System.out.println(oneA == three);
// If we intern() them they are again ==
System.out.print("oneA.intern() == three.intern() -> ");
System.out.println(oneA.intern() == three.intern());
// and of course, .equals() is always safe.
System.out.print("oneA .equals three -> ");
System.out.println(oneA.equals(three));
}
}
The output from this (run on https://repl.it/languages/java) is:
A == A -> true
oneA == twoA -> true
oneA == three -> false
oneA.intern() == three.intern() -> true
oneA .equals three -> true
You can safely use string1.equals(string2) or string1.intern() == string2.intern()
I have a password rule that needs to satisfy those condition below:
At least 2 out of the following:
- At least 1 lowercase character
- At least 1 uppercase character
- At least 2 (numbers AND special characters)
I build my regex like this below:
String oneLowercaseCharacter = ".*[a-z].*";
String oneUppercaseCharacter = ".*[A-Z].*";
String oneNumber = ".*\\d.*";
String oneSpecialCharacter = ".*[^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*";
String threeNumbersAndCharacters = ".*[0-9\\^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*[0-9\\^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*[0-9\\^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*";
And then I build the function like this below:
if ((Pattern.compile(oneLowercaseCharacter).matcher(s).find() && Pattern.compile(oneUppercaseCharacter).matcher(s).find())
|| (Pattern.compile(oneLowercaseCharacter).matcher(s).find()
&& Pattern.compile(oneSpecialCharacter).matcher(s).find()
&& Pattern.compile(oneNumber).matcher(s).find()
&& Pattern.compile(threeNumbersAndCharacters).matcher(s).find())
|| (Pattern.compile(oneUppercaseCharacter).matcher(s).find()
&& Pattern.compile(oneSpecialCharacter).matcher(s).find()
&& Pattern.compile(oneNumber).matcher(s).find()
&& Pattern.compile(threeNumbersAndCharacters).matcher(s).find())) {
//Do my stuff here
}
However, it does not work as expected. Not really sure why but if I test with different passwords, results show like this:
qwerty123 true (not expected)
qwerty!## false
qwerty12. true
Qwerty123 true
Qwerty12. true
Anyone has any idea where I missed?
Note: I search around stackoverflow already and look elsewhere already so that I came up with the above code, however could not go further.
The problem is in this line:
String oneSpecialCharacter = ".*[^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*";
The character ^ has a special meaning ("not") when it is used in the first position inside [].
This is why you need to escape it.
String oneSpecialCharacter = ".*[\\^\\`\\~\\<\\,\\>\\\"\\'\\}\\{\\]\\[\\|\\)\\(\\;\\&\\*\\$\\%\\#\\#\\!\\:\\.\\/\\?\\\\\\+\\=\\-\\_\\ ].*";
Now your result should looks like this:
qwerty123 -> false
qwerty!## -> false
qwerty12. -> true
Qwerty123 -> true
Qwerty12. -> true
Other examples that emphasize the meaning of ^:
// the first character cannot be a
System.out.println(Pattern.compile("[^a]bc").matcher("abc").find()); // false
// the first character cannot be x, y or z, but it can be a
System.out.println(Pattern.compile("[^xyz]bc").matcher("abc").find()); // true
// the first character can be ^ or a
System.out.println(Pattern.compile("[\\^a]bc").matcher("abc").find()); // true
// the first character can be ^, x, y or z, but not a
System.out.println(Pattern.compile("[\\^xyz]bc").matcher("abc").find()); // false
This question already has answers here:
String equals and == with String concatenation [duplicate]
(4 answers)
Closed 7 years ago.
String a = "abc";
String b = "abc";
System.out.println("Result .... " + a==b); // false
System.out.println(a==b); // true
1st print statement prints false and 2nd prints true, though ideally it has to be true. Why is it false in 1st print statement ?
System.out.println("Result .... " +a==b); -> the result string will be appended with 'a' and then compares with b so it results false.
Order of operations:
"Result .... " + a==b
is equivalent to
("Result .... " +a) == b
which will be false since the two strings are not the same reference.
The explanation for this is that the + addition operator has a higher precedence than == logical equivalence.
The expression a == b is returning true in your second statement due to interning, in which a and b actually refer to same string object.
Click here for a link to Oracle's table of operator precedence in Java.
Forgot checking equality by == in java. In Java this operation checks equality of object link. Additionally it is applicable for checking equality of simple numbers. You should use .equals method
String a = "abc";
String b = new String(a);
System.out.printLn(a == b);//false
System.out.println(a.equals(b));//true
Learn about operation order in java
It is because in "Result .... " +a==b it first add "Result .... " with a and then == to b. If you write like this "Result .... " +(a==b), then it will be OK.
In the first statement, you're comparing "Result .... " + a with b. In the second one, you're comparing a with b, hence the difference. Change your first statement as follows:
System.out.println("Result .... " + (a==b));
And keep in mind that strings should be compared using the equals() method instead of ==.
System.out.println("Result .... " +a==b);
String Result is appended with 'a' and then compares with b so it provides false. (Result .... a == b) which is false.
Follow this link to understand precedence of operators in java and this.
Operator + has more precedence than == operator.
try adding brackets, you will see the diff. Bracket is evaluated separately.
public static void main(String[] args) {
String a = "abc";
String b = "abc";
System.out.println("Result .... " + (a == b)); // false
System.out.println(a == b); // true}
}
output
Result .... true
true