Java Strings : Issue with Ascii values - java

I have array of strings, String[] data and it's 10 elements has value P and so data[10]={java.lang.String#587}"P"
When I do inspect on data[10], i get data[10].value[0] = 'P' 80, am not sure what that 80 is referring too.
In my program, am trying to check
if (data[10] == "P") {
lookUp = data[7] + "." + data[8]+ "." + "Old";
} else if (data[10] == "C") {
lookUpCode = data[7] + "." + data[8] + "." + "Old";
} else {
lookUpCode = data[7] + "." + data[8];
}
So challenge I have here is that even if data[10]="P" even then i hit last else and not first if loop, any suggestions?

You need to compare strings by value, not by reference:
if ("P".equals(data[10]))

In Java to compare strings you have to use the equals(String s) method. In your code:
data[10].equals("P")
This because strings are objects, and "==" compares the objects references.

Related

Why printing "" + variables output each variable individually without spacing?

One of my assignments has this code:
System.out.println("" + x + y + count);
that outputs the value of x, y and count individually without any spaces. I would like to know more about it online. However, I can't seem to find the right keywords to search it up online. Can someone please explain to me the logic behind this or perhaps point to me a name or keyword for such a situation?
I have always known the " " as a tool to print out a string so I'm confused by this.
Thanks in advance.
If we apply standard Java precedence rules, the statement:
System.out.println("" + x + y + count);
is equivalent to
System.out.println((("" + x) + y) + count);
Then we look at the meaning of +
If the static types of both a and b are numeric types (either primitive numeric or their boxed types) then a + b is numeric addition.
Otherwise, a + b is string concatenation. The two arguments are converted to strings and the strings are concatenated.
Based on this we can say that all of the + operators in the example will be treated as string concatenations.
If you want spaces between x, y and count you need to add some string literals; e.g.
System.out.println("" + x + " " + y + " " + count);
or, more simply:
System.out.println(x + " " + y + " " + count);
If you wanted x, y and count to be added (assuming that they are numeric), then you could write this:
System.out.println("" + (x + y + count));
or, more simply:
System.out.println(x + y + count);
The latter is using a different overload of println.
I have always known the "" as a tool to print out a string so I'm confused by this.
Ummm ... it is actually an empty string literal. The usage "" + x is simply an idiom for converting x to a String. The empty string literal has other uses too. The main one is to represent a String with zero characters.
Or you can use String format like this:
System.out.printf("%d%d%d", x, y, count);
The "" is an empty String. In Java when you concatenate a String with other primitives that can be cast to String the result is a String. That means that the code
System.out.println("" + something);
is a different way to write
System.out.println(String.valueOf(something));
However in your scenario the "" + x + y + count means that the elements are converted to String and then concatenated - this means that if x==1, y==2, count==3 the result would be 123. If you wanted to just cast the result to String you would have to indicate that the computation should happen before casting to String for example by using brackets
System.out.println("" + (x+y+count));
The output of this would be 6.

String.equals comparison fails to match

I am using .equals for String comparison below, but x does not match "OU":
String memberOfValue="CN=cn,​OU=ou,​OU=roles,​OU=de,​OU=apps,​DC=meta,​DC=cc,​DC=com";
String[] pairs = memberOfValue.split(",");
for (int i=0;i<pairs.length;i++) {
String pair = pairs[i];
String[] keyValue = pair.split("=");
System.out.println(keyValue[0]);
String x = keyValue[0];
String y = "OU";
System.out.println(x);
System.out.println(x.equals(y));
}
Where am I going wrong?
Adding these two lines of code shows the problem:
System.out.println("x: " + x + " - " + x.chars().boxed().collect(Collectors.toList()));
System.out.println("y: " + y + " - " + y.chars().boxed().collect(Collectors.toList()));
It gives
x: ​OU - [8203, 79, 85]
y: OU - [79, 85]
Which shows that you have some invisible char whose integer value is 8203 (zero width space, see What's HTML character code 8203?) in your string. Not sure how you got that.
As #JB Nizet says, you have non-printable characters in your memberOfValue variable, there are some types of characters as for example:
control, format, private use, surrogate, unassigned, etc...
Here is the complete list: http://www.fileformat.info/info/unicode/category/index.htm
In these cases, you can remove all characters from your string using this regular expression: \\P{Print}
For example:
String x = keyValue[0].replaceAll("[\\P{Print}", "");
When you compare the strings again, the result will be correct.
There are two possible problems from what I'm seeing.
A.) If the strings are capitalized differently they will not return equal unless you use the method .equalsIgnoreCase() instead of .equals()
B.) You're not getting the right strings that you're expecting. Be sure to print out or debug which string is getting parsed through.

Using only 1 System.out.print() instead of 3. More details below [duplicate]

I am trying to concatenate strings in Java. Why isn't this working?
public class StackOverflowTest {
public static void main(String args[]) {
int theNumber = 42;
System.out.println("Your number is " . theNumber . "!");
}
}
You can concatenate Strings using the + operator:
System.out.println("Your number is " + theNumber + "!");
theNumber is implicitly converted to the String "42".
The concatenation operator in java is +, not .
Read this (including all subsections) before you start. Try to stop thinking the php way ;)
To broaden your view on using strings in Java - the + operator for strings is actually transformed (by the compiler) into something similar to:
new StringBuilder().append("firstString").append("secondString").toString()
There are two basic answers to this question:
[simple] Use the + operator (string concatenation). "your number is" + theNumber + "!" (as noted elsewhere)
[less simple]: Use StringBuilder (or StringBuffer).
StringBuilder value;
value.append("your number is");
value.append(theNumber);
value.append("!");
value.toString();
I recommend against stacking operations like this:
new StringBuilder().append("I").append("like to write").append("confusing code");
Edit: starting in java 5 the string concatenation operator is translated into StringBuilder calls by the compiler. Because of this, both methods above are equal.
Note: Spaceisavaluablecommodity,asthissentancedemonstrates.
Caveat: Example 1 below generates multiple StringBuilder instances and is less efficient than example 2 below
Example 1
String Blam = one + two;
Blam += three + four;
Blam += five + six;
Example 2
String Blam = one + two + three + four + five + six;
Out of the box you have 3 ways to inject the value of a variable into a String as you try to achieve:
1. The simplest way
You can simply use the operator + between a String and any object or primitive type, it will automatically concatenate the String and
In case of an object, the value of String.valueOf(obj) corresponding to the String "null" if obj is null otherwise the value of obj.toString().
In case of a primitive type, the equivalent of String.valueOf(<primitive-type>).
Example with a non null object:
Integer theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
Example with a null object:
Integer theNumber = null;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is null!
Example with a primitive type:
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
Output:
Your number is 42!
2. The explicit way and potentially the most efficient one
You can use StringBuilder (or StringBuffer the thread-safe outdated counterpart) to build your String using the append methods.
Example:
int theNumber = 42;
StringBuilder buffer = new StringBuilder()
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer.toString()); // or simply System.out.println(buffer)
Output:
Your number is 42!
Behind the scene, this is actually how recent java compilers convert all the String concatenations done with the operator +, the only difference with the previous way is that you have the full control.
Indeed, the compilers will use the default constructor so the default capacity (16) as they have no idea what would be the final length of the String to build, which means that if the final length is greater than 16, the capacity will be necessarily extended which has price in term of performances.
So if you know in advance that the size of your final String will be greater than 16, it will be much more efficient to use this approach to provide a better initial capacity. For instance, in our example we create a String whose length is greater than 16, so for better performances it should be rewritten as next:
Example optimized :
int theNumber = 42;
StringBuilder buffer = new StringBuilder(18)
.append("Your number is ").append(theNumber).append('!');
System.out.println(buffer)
Output:
Your number is 42!
3. The most readable way
You can use the methods String.format(locale, format, args) or String.format(format, args) that both rely on a Formatter to build your String. This allows you to specify the format of your final String by using place holders that will be replaced by the value of the arguments.
Example:
int theNumber = 42;
System.out.println(String.format("Your number is %d!", theNumber));
// Or if we need to print only we can use printf
System.out.printf("Your number is still %d with printf!%n", theNumber);
Output:
Your number is 42!
Your number is still 42 with printf!
The most interesting aspect with this approach is the fact that we have a clear idea of what will be the final String because it is much more easy to read so it is much more easy to maintain.
The java 8 way:
StringJoiner sj1 = new StringJoiner(", ");
String joined = sj1.add("one").add("two").toString();
// one, two
System.out.println(joined);
StringJoiner sj2 = new StringJoiner(", ","{", "}");
String joined2 = sj2.add("Jake").add("John").add("Carl").toString();
// {Jake, John, Carl}
System.out.println(joined2);
You must be a PHP programmer.
Use a + sign.
System.out.println("Your number is " + theNumber + "!");
"+" instead of "."
Use + for string concatenation.
"Your number is " + theNumber + "!"
This should work
public class StackOverflowTest
{
public static void main(String args[])
{
int theNumber = 42;
System.out.println("Your number is " + theNumber + "!");
}
}
For exact concatenation operation of two string please use:
file_names = file_names.concat(file_names1);
In your case use + instead of .
For better performance use str1.concat(str2) where str1 and str2 are string variables.
String.join( delimiter , stringA , stringB , … )
As of Java 8 and later, we can use String.join.
Caveat: You must pass all String or CharSequence objects. So your int variable 42 does not work directly. One alternative is using an object rather than primitive, and then calling toString.
Integer theNumber = 42;
String output =
String // `String` class in Java 8 and later gained the new `join` method.
.join( // Static method on the `String` class.
"" , // Delimiter.
"Your number is " , theNumber.toString() , "!" ) ; // A series of `String` or `CharSequence` objects that you want to join.
) // Returns a `String` object of all the objects joined together separated by the delimiter.
;
Dump to console.
System.out.println( output ) ;
See this code run live at IdeOne.com.
In java concatenate symbol is "+".
If you are trying to concatenate two or three strings while using jdbc then use this:
String u = t1.getString();
String v = t2.getString();
String w = t3.getString();
String X = u + "" + v + "" + w;
st.setString(1, X);
Here "" is used for space only.
In Java, the concatenation symbol is "+", not ".".
"+" not "."
But be careful with String concatenation. Here's a link introducing some thoughts from IBM DeveloperWorks.
You can concatenate Strings using the + operator:
String a="hello ";
String b="world.";
System.out.println(a+b);
Output:
hello world.
That's it
So from the able answer's you might have got the answer for why your snippet is not working. Now I'll add my suggestions on how to do it effectively. This article is a good place where the author speaks about different way to concatenate the string and also given the time comparison results between various results.
Different ways by which Strings could be concatenated in Java
By using + operator (20 + "")
By using concat method in String class
Using StringBuffer
By using StringBuilder
Method 1:
This is a non-recommended way of doing. Why? When you use it with integers and characters you should be explicitly very conscious of transforming the integer to toString() before appending the string or else it would treat the characters to ASCI int's and would perform addition on the top.
String temp = "" + 200 + 'B';
//This is translated internally into,
new StringBuilder().append( "" ).append( 200 ).append('B').toString();
Method 2:
This is the inner concat method's implementation
public String concat(String str) {
int olen = str.length();
if (olen == 0) {
return this;
}
if (coder() == str.coder()) {
byte[] val = this.value;
byte[] oval = str.value;
int len = val.length + oval.length;
byte[] buf = Arrays.copyOf(val, len);
System.arraycopy(oval, 0, buf, val.length, oval.length);
return new String(buf, coder);
}
int len = length();
byte[] buf = StringUTF16.newBytesFor(len + olen);
getBytes(buf, 0, UTF16);
str.getBytes(buf, len, UTF16);
return new String(buf, UTF16);
}
This creates a new buffer each time and copies the old content to the newly allocated buffer. So, this is would be too slow when you do it on more Strings.
Method 3:
This is thread safe and comparatively fast compared to (1) and (2). This uses StringBuilder internally and when it allocates new memory for the buffer (say it's current size is 10) it would increment it's 2*size + 2 (which is 22). So when the array becomes bigger and bigger this would really perform better as it need not allocate buffer size each and every time for every append call.
private int newCapacity(int minCapacity) {
// overflow-conscious code
int oldCapacity = value.length >> coder;
int newCapacity = (oldCapacity << 1) + 2;
if (newCapacity - minCapacity < 0) {
newCapacity = minCapacity;
}
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
return (newCapacity <= 0 || SAFE_BOUND - newCapacity < 0)
? hugeCapacity(minCapacity)
: newCapacity;
}
private int hugeCapacity(int minCapacity) {
int SAFE_BOUND = MAX_ARRAY_SIZE >> coder;
int UNSAFE_BOUND = Integer.MAX_VALUE >> coder;
if (UNSAFE_BOUND - minCapacity < 0) { // overflow
throw new OutOfMemoryError();
}
return (minCapacity > SAFE_BOUND)
? minCapacity : SAFE_BOUND;
}
Method 4
StringBuilder would be the fastest one for String concatenation since it's not thread safe. Unless you are very sure that your class which uses this is single ton I would highly recommend not to use this one.
In short, use StringBuffer until you are not sure that your code could be used by multiple threads. If you are damn sure, that your class is singleton then go ahead with StringBuilder for concatenation.
First method: You could use "+" sign for concatenating strings, but this always happens in print.
Another way: The String class includes a method for concatenating two strings: string1.concat(string2);
import com.google.common.base.Joiner;
String delimiter = "";
Joiner.on(delimiter).join(Lists.newArrayList("Your number is ", 47, "!"));
This may be overkill to answer the op's question, but it is good to know about for more complex join operations. This stackoverflow question ranks highly in general google searches in this area, so good to know.
you can use stringbuffer, stringbuilder, and as everyone before me mentioned, "+". I'm not sure how fast "+" is (I think it is the fastest for shorter strings), but for longer I think builder and buffer are about equal (builder is slightly faster because it's not synchronized).
here is an example to read and concatenate 2 string without using 3rd variable:
public class Demo {
public static void main(String args[]) throws Exception {
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(r);
System.out.println("enter your first string");
String str1 = br.readLine();
System.out.println("enter your second string");
String str2 = br.readLine();
System.out.println("concatenated string is:" + str1 + str2);
}
}
There are multiple ways to do so, but Oracle and IBM say that using +, is a bad practice, because essentially every time you concatenate String, you end up creating additional objects in memory. It will utilize extra space in JVM, and your program may be out of space, or slow down.
Using StringBuilder or StringBuffer is best way to go with it. Please look at Nicolas Fillato's comment above for example related to StringBuffer.
String first = "I eat"; String second = "all the rats.";
System.out.println(first+second);
Using "+" symbol u can concatenate strings.
String a="I";
String b="Love.";
String c="Java.";
System.out.println(a+b+c);

Separating string from white space from a vector

So essentially I have an object of vectors and in a specific instance called 'comments' I have comments that actually have String in them and some that are just white space or have a single space. I tried to separate these from each other and I am running into trouble. Everything is outputted for some strange reason. Any thoughts? (display is a JTextArea)
for (int x = 0; x<dogParkProgramMain.infoVector.size(); x++)
{
if(dogParkProgramMain.infoVector.elementAt(x).getComment() == "//s" || dogParkProgramMain.infoVector.elementAt(x).getComment() == null){
System.out.println("Blank");
}
else{
display.append("Name: " + dogParkProgramMain.infoVector.elementAt(x).getFName() + " " + dogParkProgramMain.infoVector.elementAt(x).getLName() + newLine);
display.append("Comment: " + dogParkProgramMain.infoVector.elementAt(x).getComment() + newLine);
display.append("---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------" + newLine);
}
} // end first for loop
Not sure what you mean by \\s it's since you're not using regular expressions there. The following check should work:
String comment = dogParkProgramMain.infoVector.elementAt(x).getComment();
if (comment == null || comment.trim().isEmpty()) {
System.out.println("Blank");
}
trim() function will remove all leading and trailing spaces from the string meaning that if your string only contains spaces it would end up empty after trim. This code will check for any number of spaces as opposed to only one space mentioned in your question.

Something crazy happens with StringBuilder.append(String str);

I've got a problem with my java-project.
following function should deliver a String for a SQL-Statement:
private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();
x.append("" + p.getPatnr() +","+ p.getSvnr());
java.sql.Date andat = null,gebdat;
if(p.getAndat()==null)
andat=null;
else
andat=new java.sql.Date(p.getAndat().getTimeInMillis());
if(p.getGebdat()==null)
gebdat=null;
else
gebdat=new java.sql.Date(p.getGebdat().getTimeInMillis());
x.append("," + andat==null?"null":andat);
x.append("," + p.getTele()==null?"null":p.getTele());
x.append("," + p.getVName() +","+ p.getNname());
x.append("," + p.getKk()==null?"null":p.getKk());
x.append("," + gebdat==null?"null":gebdat);
x.append("," + p.getAdrplzort()==null?"null":6);
x.append("," + p.getAdrstr()==null?"null":p.getAdrstr());
x.append("," + p.getAdrhnr()==null?"null":p.getAdrhnr());
s.append("," + p.getReplzort()==null?"null":p.getReplzort().getPlzortnr());
x.append("," + p.getRestr()==null?"null":p.getRestr());
x.append("," + p.getRehnr()==null?"null":p.getRehnr());
x.append("," + p.getLevel());
x.append("," + p.getCon()==null?"null":p.getCon());
x.append("," + (p.isPa()?"y":"n")+","+ (p.isLonly()?"y":"n") +","+ (p.isGest()?"y":"n"));
x.append("," + p.getBem()==null?"null":p.getBem());
x.append("," + (p.isKat1()?'y':'n') +","+ (p.isKat2()?'y':'n') +","+ (p.isKat3()?'y':'n'));
System.out.println(x);
return x.toString();
}
the output is
6,6465136nullnull,Jürgen,Wieslernullnull6nullnullnullnull,0null,n,n,nnull,n,n,n
but it should be like this:
6,6465136,null,null,Jürgen,Wiesler,null,null,6,null,null,null,null,0,null,n,n,n,null,n,n,n
Anyone an Idea?
I'm using jdk 1.7 on debian(64-bit)
The problem is how the operators bind. Look at this:
x.append("," + andat==null?"null":andat);
Now think of it as:
x.append(("," + andat) == null ? "null" : andat);
The LHS is never going to be null, so it's always just appending andat... and that still converts to "null" if the reference is null, because that's the default behaviour of StringBuilder.
Your code is much more complicated - and inefficient - than it needs to be. Consider rewriting it as:
private static String createInsertString(Pat p)
{
StringBuilder x = new StringBuilder();
java.sql.Date andat = p.andat == null ? null
: new java.sql.Date(p.getAndat().getTimeInMillis());
java.sql.Date gebdat = p.getGebdat() == null ? null
: new java.sql.Date(p.getGebdat().getTimeInMillis());
x.append(p.getPatnr()).append(",")
.append(p.getSvnr()).append(",")
.append(andat).append(",")
.append(p.getTele()).append(",")
// etc
return x.toString();
}
Note that I think you had a bug in the original:
x.append("," + p.getVName() +","+ p.getNname());
Where these meant to be calling two different getters?
You are misusing .append() by putting concatenations inside them! This misses the entire point of what StringBuilder is supposed to be used for.
x.append("," + andat==null?"null":andat);
should be
x.append(",").append( andat == null ? "null" : andat);
which would be the correct logic to make your ternary operator work as you intended.
.append() returns a reference to the StringBuilder so that you can chain .append() calls as much as you need.
Anytime you are putting a string concatenation inside of .append() you are just creating more intermediate String objects that eat up memory, cpu cycles and then use more resources as they now need to be garbage collected.
Also you should pre-allocate your StringBuilder with a default size that is slightly bigger than what you expect your contents to be to avoid wasted allocations and garbage creation.
See the Javadoc for the StringBuilder(int) constructor.
The problem comes from your '+'.
If you use a StringBuilder, don't use '+': it is not efficient
"," + andat==null?"null":andat results in ",null"==null?"null":andat if andat is null.
The '+' string concatenation has priority over the ternary operator
When you use the '+' with String your compiler actually translates that to a StringBuilder (or a StringBuffer before Java5)
So having
String s = a + b + c;
is actually translated to:
String s = new StringBuilder().append(a).append(b).append(c).toString().
Therefore using + within a StringBuilder is counter-productive as you create additional unecessary StringBuilder.

Categories