import java.util.Scanner; public class main {      public static void main(String[] args) {     boolean a = true;          do {                 Scanner input = new Scanner(System.in);                 System.out.println("Press any on keyboard:");                 String keys = input.nextLine();                 System.out.println("You pressed:");                 System.out.println(keys);                 System.out.println("Your hash is:");                 String B = "#B";                 String hash = B+keys;                 System.out.println(hash);                 System.out.println("To end loop press f");                 //End Loop                 Scanner exit = new Scanner(System.in);                 String end = exit.nextLine();                 if (end=="f") {                     a=false;                     }             }                while(a);     }            }   I've been using python and I decided to start learning java since android studio requires it. I'm learning how to do loops again. I can't get this to work. I already looked this up I couldn't find it. How would I end this by pressing 'f'? My thought process was that once it was done going though the first lines of the do loop, it would go though the if statement changing the value of a ending the loop.
93
I've been using the == operator in my program to compare all my strings so far. However, I ran into a bug, changed one of them into .equals() instead, and it fixed the bug.  Is == bad? When should it and should it not be used? What's the difference?
81621
If I write the following class:  public class Example {        int j;       int k;        public Example(int j, int k) {            j = j;            k = k;       }        public static void main(String[] args) {            Example exm = new Example(1,2);            System.out.println(exm.j);            System.out.println(exm.k);       }  }   The program compiles, but when I run the program, the main method will print out two 0s. I know that in order to say that I want to initialize the instance variables in the constructor I have to write:  this.j = j; this.k = k;   But if I don't write it, then which variable is evaluated (or considered) in the constructor (on the left and on the write hand side of the expressions)? Is is the argument or the instance variable? Does it make a difference?  Are there other cases where the use of this is obligatory?
16499
If yes, on which operating system, shell or whatever?  Consider the following java program (I'm using java just as an example, any language would be good for this question, which is more about operation systems):  public class ExitCode {     public static void main(String args[]) {         System.exit(Integer.parseInt(args[0]));     } }   Running it on Linux and bash, it returns always values less equal 255, e.g. (echo $? prints the exit code of the previous executed command)  &gt; java ExitCode 2; echo $? 2  &gt; java ExitCode 128; echo $? 128  &gt; java ExitCode 255; echo $? 255  &gt; java ExitCode 256; echo $? 0  &gt; java ExitCode 65536; echo $? 0     EDITED: the (only, so far) answer below fully  explain what happens on UNIXes. I'm still wondering about other OSes.
110717
In Java, you can qualify local variables and method parameters with the final keyword.  public static void foo(final int x) {   final String qwerty = "bar";  }   Doing so results in not being able to reassign x and qwerty in the body of the method.  This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?
2156
In Java is there a way to check the condition:  "Does this single character appear at all in string x"  without using a loop?
116653
I have this:  If String.IsNullOrEmpty(editTransactionRow.pay_id.ToString()) = False Then     stTransactionPaymentID = editTransactionRow.pay_id 'Check for null value End If   Now, when editTransactionRow.pay_id is Null Visual Basic throws an exception. Is there something wrong with this code?
57572
I normally use the following idiom to check if a String can be converted to an integer.  public boolean isInteger( String input ) {     try {         Integer.parseInt( input );         return true;     }     catch( Exception e ) {         return false;     } }   Is it just me, or does this seem a bit hackish?  What's a better way?    See my answer (with benchmarks, based on the  by ) to see why I've reversed my position and accepted  to this problem.  I think this original code will be used by most people because it's quicker to implement, and more maintainable, but it's orders of magnitude slower when non-integer data is provided.
24985
I saw , but I didn't see a JavaScript specific example. Is there a simple string.Empty available in JavaScript, or is it just a case of checking for ""?
62170
How does the code  work with Ctrl + K? I am new to Stack Overflow.   I can't get it with Ctrl + K. I  press space button for 4 times in each line I post.
58461
Consider the code:  PreparedStatement ps = null; ResultSet rs = null; try {   ps = conn.createStatement(myQueryString);   rs = ps.executeQuery();   // process the results... } catch (java.sql.SQLException e) {   log.error("an error!", e);   throw new MyAppException("I'm sorry. Your query did not work."); } finally {   ps.close();   rs.close(); }   The above does not compile, because both PreparedStatement.close() and ResultSet.close() throw a java.sql.SQLException.  So do I add a try/catch block to the finally clause?  Or move the close statements into the try clause?  Or just not bother calling close?
119736
I have a try...except block in my code and When an exception is throw. I really just want to continue with the code because in that case, everything is still able to run just fine. The problem is if you leave the except: block empty or with a #do nothing, it gives you a syntax error. I can't use continue because its not in a loop. Is there a keyword i can use that tells the code to just keep going?
3961
Considering this code, can I be absolutely sure that the finally block always executes, no matter what something() is?  try {       something();       return success;   }   catch (Exception e) {        return failure;   }   finally {       System.out.println("I don't know if this will get printed out"); }
106441
I have a method like this:  public static &lt;T&gt; boolean isMemberOf(T item, T[] set) {     for (T t : set) {         if (t.equals(item)) {             return true;         }     }     return false; }   Now I try to call this method using a char for T:  char ch = 'a'; char[] chars = new char[] { 'a', 'b', 'c' }; boolean member = isMemberOf(ch, chars);   This doesn't work. I would expect the char and char[] to get autoboxed to Character and Character[], but that doesn't seem to happen.  Any insights?
1992
While working in a Java app, I recently needed to assemble a comma-delimited list of values to pass to another web service without knowing how many elements there would be in advance. The best I could come up with off the top of my head was something like this:  public String appendWithDelimiter( String original, String addition, String delimiter ) {     if ( original.equals( "" ) ) {         return addition;     } else {         return original + delimiter + addition;     } }  String parameterString = ""; if ( condition ) parameterString = appendWithDelimiter( parameterString, "elementName", "," ); if ( anotherCondition ) parameterString = appendWithDelimiter( parameterString, "anotherElementName", "," );   I realize this isn't particularly efficient, since there are strings being created all over the place, but I was going for clarity more than optimization.  In Ruby, I can do something like this instead, which feels much more elegant:  parameterArray = []; parameterArray &lt;&lt; "elementName" if condition; parameterArray &lt;&lt; "anotherElementName" if anotherCondition; parameterString = parameterArray.join(",");   But since Java lacks a join command, I couldn't figure out anything equivalent.  So, what's the best way to do this in Java?
78122
Please take a look on the following pseudo-code:  boolean blocked[2]; int turn; void P(int id) {       while(true) {              blocked[id] = true;              while(turn != id) {                     while(blocked[1-id])                     /* do nothing */;                     turn = id;              }              /* critical section */              blocked[id] = false;              /* remainder */       } } void main() {       blocked[0] = false;       blocked[1] = false;       turn = 0;       parbegin(P(0), P(1)); //RUN P0 and P1 parallel }   I thought that a could implement a simple Mutual - Exclution solution using the code above. But it's not working. Has anyone got an idea why?  Any help would really be appreciated!
9051
Check out the below program.   try {     for (String data : Files.readAllLines(Paths.get("D:/sample.txt"))){         String[] de = data.split(";");         System.out.println("Length = " + de.length);     } } catch (IOException e) {     e.printStackTrace(); }   Sample.txt:   1;2;3;4 A;B;; a;b;c;   Output:   Length = 4 Length = 2 Length = 3   Why second and third output is giving 2 and 3 instead of 4. In sample.txt file, condition  for 2nd and 3rd line is should give newline(\n or enter) immediately after giving delimiter for the third field. Can anyone help me how to get length as 4 for 2nd and 3rd line without changing the condition of the sample.txt file and how to print the values of de[2] (throws  ArrayIndexOutOfBoundsException)?
91805
Short prestory. Typical problem: you have a lot of small string and you want to concatenate them all in one big string. The code like for(Integer i = 0; i &lt; smallStringsSize; i++){     bigString += smallStrings[i]; }  will solve this problem, but it has to produce a lot of unnecessary string objects that consume your heap. That is why Java has classes like StringBuilder and StringBuffer that allow you to solve this problem wihtout consuming too many memory. Thus, I decided to try to do my own StringBuilder in apex. String class has two methods that looked suitable for it:   and  . Here is the code that i used to test these methods against &quot;+=&quot; concatenantion (ready to execute in anonymous): List&lt;String&gt; chars = new List&lt;String&gt;(); List&lt;Integer&gt; charsCode = new List&lt;Integer&gt;(); Integer size = 10000; String chartToAdd = 'Ω'; for(Integer i = 0; i &lt; size; i++){     chars.add(chartToAdd);     charsCode.add(String.valueOf(chartToAdd).charAt(0)); } String joinS = '', forS = '', fromS = ''; Integer initialHeapSize = Limits.getHeapSize(); Integer initialCPUtime = Limits.getCpuTime(); System.debug('initialHeapSize ' + initialHeapSize); System.debug('initialCPUtime ' + initialCPUtime); joinS = String.join(chars, ''); Integer joinHeapSize = Limits.getHeapSize() - initialHeapSize; Integer joinCPUtime = Limits.getCpuTime() - initialCPUtime; System.debug('-------- String.join ---------'); System.debug('joinHeapSize ' + joinHeapSize); System.debug('joinCPUtime ' + joinCPUtime); for(Integer i = 0; i &lt; size; i++){     forS += chars[i]; } Integer forHeapSize = Limits.getHeapSize() - joinHeapSize - initialHeapSize; Integer forCPUtime = Limits.getCpuTime() - joinCPUtime - initialCPUtime; System.debug('-------- for each += ---------'); System.debug('forHeapSize ' + forHeapSize); System.debug('forCPUtime ' + forCPUtime); fromS = String.fromCharArray(charsCode); Integer fromHeapSize = Limits.getHeapSize() - forHeapSize - joinHeapSize - initialHeapSize; Integer fromCPUtime = Limits.getCpuTime() - forCPUtime - joinCPUtime - initialCPUtime; System.debug('-------- String.fromCharArray ---------'); System.debug('fromHeapSize ' + fromHeapSize); System.debug('fromCPUtime ' + fromCPUtime); System.debug(''); System.debug('-------- strings ----------'); System.debug('joins ' + joins); System.debug('fors ' + fors); System.debug('fromS ' + fromS);  The result of this code execution:  initialHeapSize 161166 initialCPUtime 242 -------- String.join --------- joinHeapSize 10016 joinCPUtime 17 -------- for each += --------- forHeapSize 10024 forCPUtime 48 -------- String.fromCharArray --------- fromHeapSize 10016 fromCPUtime 5  As you can see, the heap size for each approach is so close to 10 kilobytes, what is a size of the string of 10 000 characters (size) if each character takes only one byte. In case of creating 10 000 additional string objects, the heap size would be a bit more than 50 megabytes (10 000 * (1 + 10 000)/2). Taking into consideration the above,  Does not the '+=' concatenation create any additional string objects that devour your heap? Did not I miss anything? I am so amazed.  As you see, I use Omega 'Ω' as a chartToAdd. It has  the high-surrogate code point equals to 937, that needs at least 2 bytes to be encoded. How can 10 000 Omegas consume only 10 000 bytes of the heap size?  What weightful reasons Salesforce has that they do not to add the character data type? Any ideas?