Domino java example code does not work properly [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Check whether a String is not Null and not Empty
(35 answers)
Closed 8 years ago.
Here is a code from the Domino 8 designer help to get database categories.
The condition "if(cat != "") always return true though database category is empty or non-empty. What is catch?
import lotus.domino.*;
public class JavaAgent extends AgentBase {
public void NotesMain() {
try {
Session session = getSession();
AgentContext agentContext =
session.getAgentContext();
// (Your code goes here)
Database db = agentContext.getCurrentDatabase();
String title = db.getTitle();
String cat = db.getCategories();
if (cat != "")//This condition does not work
System.out.println("Database \"" +
title + "\" has the categories: " + cat);
else
System.out.println("Database \"" +
title + "\" has no categories");
} catch(Exception e) {
e.printStackTrace();
}
}
}

Use this for the if condition
!"".equals (cat)
Direct equal checks for reference equality, not content equality.
Inverting cat and the empty string takes care of the null condition without any crutches since the empty string is never null.

I like to use Google's Guava for these kinds of things especially when dealing with String
In Guava there exist a Class Strings which provide
public static boolean isNullOrEmpty(#Nullable
String string)
Returns true if the given string is null or is the empty string.
so use Strings.isNullOrEmpty(cat)

It worked as if (!cat.isEmpty())!
Even without braces!

Related

Check if string contains an # symbol or if the string is null [duplicate]

This question already has answers here:
How can I check if a single character appears in a string?
(16 answers)
Closed 4 years ago.
Basically, I have a form where people can enter stuff in, and there is one part where they input an email address. Sometimes, people just put in their name and don't put an actual email address. Sometimes they do not fill it out at all.
Is there any easy way to check to see if the string has an # symbol in it and check to see if its Null?
Any help is appreciated
Use an AND boolean operator. str != null && str.contains("#")
We first check the string is not null, then check that it contains '#'. Note: The reason that the null check is first is so that we do not attempt to access the string if it is null.
String s = "email#email.it";
if(s!= null && !s.isEmpty() && s.contains("#") ) {
System.out.println("ok");
}
else System.out.println("ko");
}
The String class contains a contains method to check the # symbol, and you can simply check for null with a != null call:
public static void main(String[] args) {
String a = "should be false";
String b = "should be #true";
String c = null;
System.out.println(checkString(a));
System.out.println(checkString(b));
System.out.println(checkString(c));
}
static boolean checkString(String str) {
return str != null && str.contains("#");
}
Output:
false
true
false
Here is some really simple code to achieve this:
String ourString = "example#emailIsCool.com";
if(/* Check if our string is null: */ ourString != null &&
/* Check if our string is empty: */ !ourString.isEmpty() &&
/* Check if our string contains "#": */ ourString.contains("#")) {
System.out.println("String Fits the Requirements");
} else {
System.out.println("String Does Not Fit the Requirements");
}
For future reference, this is extremely broad for Stack Overflow, and you should try checking the javadoc before you make a post asking for the answer. For example, here is the javadoc for the String class: https://docs.oracle.com/javase/7/docs/api/java/lang/String.html
Javadocs provided by Oracle detail every method and attribute for all of the classes included in the standard java library. Here is a link to the javadoc homepage for Java 7.
https://docs.oracle.com/javase/7/docs/api/overview-summary.html
I think use Optional is the best way to do this.
Codes like this:
String nullEmail = null;
System.out.println(Optional.ofNullable(nullEmail).filter(s -> s.contains("#")).isPresent());
String rightEmail = "478309639#11.com";
System.out.println(Optional.ofNullable(rightEmail).filter(s -> s.contains("#")).isPresent());
String wrongEmail = "chentong";
System.out.println(Optional.ofNullable(wrongEmail).filter(s -> s.contains("#")).isPresent());
The output is:
false
true
false

can not match the String get from properties file in Java [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 4 years ago.
I have a line in file config.properties
clean=true
and use following code to get this property
private static String clean;
Properties prop = new Properties();
try {
prop.load(new FileInputStream("config.properties"));
clean = prop.getProperty("clean");
}
I use System.out.println(">"+clean+"<") to see the output and get ">true<", which indicates there is no blank, no \n
However, when I use
if (clean == "true") {
// program does not go here
}
else {
// program goes here
}
what is the possible reason?...
Try the following:
== checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
if (clean.equals("true")) {
// program does not go here
}
else {
// program goes here
}
The Problem is you are using equality operator which doesn't compare literal instead references. So you have to use equals method to do literal check
if ("true".equals(check)) {
// Now Program will go here
}
else {
// and now here
}

Java if Statement under enhanced for loop did not work [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
This is a code fragment that I am working with for a logon system using hashset Users.
I checked the enhanced for loop part it works but the if statement seems like it never works out, even if the values are equal.
if (comm.equals("Sign in")) {
user urs = new user(p_name, p_pass, p_id );
Iterator<user> iter = Users.iterator();
for(user obj : Users) {
if (p_u == obj.getUsername()&& p_pw == obj.getPassword ()&& p_sn== obj.getStudentID()) {
JOptionPane.showConfirmDialog(
jf,
"Success", "Success",
JOptionPane.DEFAULT_OPTION);
break;
} else {
log_in.setText("Try Again");
exit.setText("Create User");
}
Remember, in Java == operators test the equality of the value, in this case, two references. These two references do not point to the same memory location and therefore will never equate to true. Use the equals() method to test for equality of the values of strings.
I think you need to changed it to something like this:
if (comm.equals("Sign in")) {
user urs = new user(p_name, p_pass, p_id );
Iterator<user> iter = Users.iterator();
for(user obj : Users) {
if (p_u.equalsIgnoreCase(obj.getUsername())&& p_pw.equals(obj.getPassword())&& p_sn.equals(obj.getStudentID())) {
JOptionPane.showConfirmDialog(
jf,
"Success", "Success",
JOptionPane.DEFAULT_OPTION);
break;
} else {
log_in.setText("Try Again");
exit.setText("Create User");
}
Assuming that p_u, p_pw and p_sn are String object references the code below is checking whether those two objects are the same object (or whether their refences to the object's position in memory are the same) rather than whether the String objects share the same character sequence.
if (p_u == obj.getUsername()&& p_pw == obj.getPassword ()&& p_sn== obj.getStudentID())
Instead, to check whether their character sequence matches up you should use the .equals() method. Example below;
if (p_u.equals(obj.getUsername())&& p_pw.equals(obj.getPassword ())&& p_sn.equals(obj.getStudentID()))
I hope this helps.

if statement comparing strings in java android [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Java String.equals versus ==
I'm trying to write a method in az DBOpenHelper extends SQLOpenHelper class.
It supposed to evaluate if there's an entry in the DB with the same name.
public boolean existsContact(Contact contact) {
SQLiteDatabase db = this.getReadableDatabase();
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
Cursor cursor = db.rawQuery(selectQuery, null);
if (cursor.moveToFirst()) {
do {
String name = cursor.getString(1);
String cname = contact.getName();
if (name == cname) {
cursor.close();
db.close();
return true;
}
} while (cursor.moveToNext());
}
db.close();
return false;
}
Here's the relevant part of Contact class:
public class Contact {
String _name;
public String getName(){
return this._name;
}
}
Now here's the strange thing:
Scenario A : if (name == cname) where name = "foo" and cname = "foo" equals false.
Eclipse debugger show name's foo and cname's foo have different id's.
both variables filled as seen before in code.
Scenario B: if(name == cname) where variabales are loaded like this:
String name = "foo";
String cname = "foo";
statement equals true as it's supposed to.
Scenario C: if("foo" == "foo") equals true...BUT...debugger goes out the window. LogCat show debugger connected, but there's no activity in eclipse's Debug perspective. Breakpoints have no effect. No Threads shown.
In java, when using == on two objects, you're not actually comparing the strings themselves. You'll need to use .equals(String).
== actually compares the two object's references, not their values.
string1.equals(String target) compares the two strings based off of the actual characters in the strings.
See: http://www.leepoint.net/notes-java/data/expressions/22compareobjects.html
== operator check object reference are equal or not but equals() method check values are same or not
if (name == cname)
{
cursor.close();
db.close();
return true;
}
change with it
if (name.equals(cname)){
cursor.close();
db.close();
return true;
}
When comparing objects in java that are not primitive data types (int, char, boolean, etc...), you have to use the method Object#equals(Object), which returns a boolean.
So, when you are comparing two Strings, you are actually checking if the two Objects are the same instance, instead of the actual value.
All you have to do is just change name == cname to name.equals(cname).

String comparison to constant error [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How do I compare strings in Java?
I have this code its working fine in retreiving the value from the url, but its not recognizing that the string is "True" is the toString() what I need or something else?
try {
URL url = new URL("http://www.koolflashgames.com/test.php?id=1");
URLConnection yc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(yc
.getInputStream()));
inputLine = in.readLine();
inputLine = inputLine.toString();
if(inputLine == "True") {
logger.info(inputLine);
player.sendMessage("Thanks");
}else{
logger.info(inputLine);
player.sendMessage("HAHAHA");
}
in.close();
} catch (Exception e) {
e.printStackTrace();
}
You cannot use == to compare the content of Strings, as they are objects. You have to create a method to compare objects. In the case of strings, you can use stringName.equals(otherString).
I beg to differ. Use .equalsIgnoreCase() method to compare the string ignoring the case. This will match all cases, such as "True", "TRue", "tRue".. etc approximately 16 matches.
You must use equals to compare strings. Replace:
if(inputLine == "True") {
with:
if(inputLine.equals("True")) {
The operator == tells you if two references refer to the same object, not if the values are the same.
In order to compare String objects, use the equals() method.
The == operator checks whether the two Strings have the same reference.
See How do I compare strings in Java? for more info.

Categories