I'm working on a Java question for my school which gives me this utility class:  import java.util.*;  public class PassByValue {      private PassByValue() {}      public static void add(int a)     {         a = a + 1;     }      public static void add(Set&lt;String&gt; b)     {         b = new HashSet&lt;String&gt;();         b.add("ABC");     }      public static void add(List&lt;Integer&gt; c)     {         c.add(new Integer(1));     } }   It also gives me this class with the main method  import java.io.PrintStream; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set;  public class PassByValueClient {     public static void main(String[] args)     {         PrintStream output = System.out;          int a = 1;         PassByValue.add(a);         output.println(a);          Set&lt;String&gt; b = new HashSet&lt;String&gt;();         PassByValue.add(b);         output.println(b.size());          List&lt;Integer&gt; c = new ArrayList&lt;Integer&gt;();         PassByValue.add(c);         output.println(c.size());     } }   We are supposed to predict the output. When I predicted what the output would be, my guess was 1, 0, and 0 respectively. However, when I ran the code the output I got was 1, 0, and 1 respectively. From what I understand about passing parameters/arguments into methods, the client's code should remain unchanged. Can someone tell me why the output is 1 instead of 0?
121
I always thought Java uses pass-by-reference. However, I've seen a couple of blog posts (for example, ) that claim that it isn't (the blog post says that Java uses pass-by-value). I don't think I understand the distinction they're making. What is the explanation?
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)?
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?
62295
Is there in the JDK or Jakarta Commons (or anywhere else) a method that can parse the output of Arrays.toString, at least for integer arrays?  int[] i = fromString(Arrays.toString(new int[] { 1, 2, 3} );
4525
To be specific, I was trying this code:  package hello;  public class Hello {      Clock clock = new Clock();      public static void main(String args[]) {         clock.sayTime();     } }   But it gave the error      Cannot access non-static field in static method main   So I changed the declaration of clock to this:  static Clock clock = new Clock();   And it worked. What does it mean to put that keyword before the declaration? What exactly will it do and/or restrict in terms of what can be done to that object?
7194
I read about Java's type erasure .  When does type erasure occur? At compile time or runtime? When the class is loaded? When the class is instantiated?  A lot of sites (including the official tutorial mentioned above) say type erasure occurs at compile time. If the type information is completely removed at compile time, how does the JDK check type compatibility when a method using generics is invoked with no type information or wrong type information?  Consider the following example: Say class A has a method, empty(Box&lt;?&nbsp;extends&nbsp;Number&gt;&nbsp;b). We compile A.java and get the class file A.class.  public class A {     public static void empty(Box&lt;? extends Number&gt; b) {} }     public class Box&lt;T&gt; {}   Now we create another class B which invokes the method empty with a non-parameterized argument (raw type): empty(new Box()). If we compile B.java with A.class in the classpath, javac is smart enough to raise a warning. So A.class has some type information stored in it.  public class B {     public static void invoke() {         // java: unchecked method invocation:         //  method empty in class A is applied to given types         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         // java: unchecked conversion         //  required: Box&lt;? extends java.lang.Number&gt;         //  found:    Box         A.empty(new Box());     } }   My guess would be that type erasure occurs when the class is loaded, but it is just a guess. So when does it happen?
81630
Why does this test program result in a java.lang.IllegalMonitorStateException?  public class test {     static Integer foo = new Integer(1);     public static void main(String[] args) {         synchronized(foo) {             foo++;             foo.notifyAll();         }         System.err.println("Success");     } }   Result:  Exception in thread "main" java.lang.IllegalMonitorStateException         at java.lang.Object.notifyAll(Native Method)         at test.main(test.java:6)
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?
1624
The very common beginner mistake is when you try to use a class property "statically" without making an instance of that class. It leaves you with the mentioned error message:     You can either make the non static method static or make an instance of that class to use its properties.   Why? I am not asking for solutions. I would be grateful to know what is the reason behind it. The very core reason!  private java.util.List&lt;String&gt; someMethod(){     /* Some Code */     return someList;             }  public static void main(String[] strArgs){                // The following statement causes the error. You know why..     java.util.List&lt;String&gt; someList = someMethod();          }
6108
Why do I get compiler errors with this Java code?  1  public List&lt;? extends Foo&gt; getFoos() 2  { 3    List&lt;? extends Foo&gt; foos = new ArrayList&lt;? extends Foo&gt;(); 4    foos.add(new SubFoo()); 5    return foos; 6  }  Where 'SubFoo' is a concrete class that implements Foo, and Foo is an interface.  Errors I get with this code:   On Line 3: "Cannot instantiate ArrayList&lt;? extends Foo&gt;" On Line 4: "The method add(capture#1-of ? extends Foo) in the type List&lt;capture#1-of ? extends Foo&gt; is not applicable for the arguments (SubFoo)"   Update: Thanks to Jeff C, I can change Line 3 to say "new ArrayList&lt;Foo&gt;();".  But I'm still having the issue with Line 4.
872
In Java, arrays don't override toString(), so if you try to print one directly, you get the className + '@' + the hex of the  of the array, as defined by Object.toString():  int[] intArray = new int[] {1, 2, 3, 4, 5}; System.out.println(intArray);     // prints something like '[I@3343c8b3'   But usually, we'd actually want something more like [1, 2, 3, 4, 5]. What's the simplest way of doing that? Here are some example inputs and outputs:  // Array of primitives: int[] intArray = new int[] {1, 2, 3, 4, 5}; //output: [1, 2, 3, 4, 5]  // Array of object references: String[] strArray = new String[] {"John", "Mary", "Bob"}; //output: [John, Mary, Bob]
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.
52524
So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following working code:  class Test {   private int privateInt;   [...]   public boolean equals(Object obj) {     [...]     Test t = (Test) obj;     if ( t.privateInt == privateInt ) {     [...]   } }   t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.  So what is happening here? How is this called? Where would somebody use this? Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?  Generally, where can I find information about this?  Thank you.
65745
I have created an Apex InterfaceFactory that the user can use to get an instance of a specified implementation of an interface. For this I use the System.Type class. The actual name of the class can be set in a custom setting. I wanted to be able to pass some parameters to the constructor of the dynamically instantiated class. In short; this is the code I'm talking about:  public static MyInterface GetMyInterfaceImplementationByClassName(String settingName){     String implementationClassName;     Type t;     MyInterface implementation = null;      //get the actual class name from the custom setting     Interface_Implementations__c settings = Interface_Implementations__c.getInstance(settingName);      //just make sure there actually is a className found     if (settings != null &amp;&amp; settings.Class__c != null) {         implementationClassName = settings.Class__c;         //get the type object for the class name retrieved from the custom setting         t = Type.forName(implementationClassName);         //this line is where my question comes in; how can I pass parameters here         implementation = (MyInterface)t.newInstance();     }      return implementation; }
14089
I'm creating a function where I need to pass an object so that it can be modified by the function. What is the difference between:  public void myFunction(ref MyClass someClass)   and  public void myFunction(out MyClass someClass)   Which should I use and why?
38591
class someclass {};  class base {     int a;     int *pint;     someclass objsomeclass;     someclass* psomeclass; public:     base()     {         objsomeclass = someclass();         psomeclass = new someclass();         pint = new int();          throw "constructor failed";         a = 43;     } }  int main() {     base temp(); }   In the above code, the constructor throws. Which objects will be leaked, and how can the memory leaks be avoided?  int main() {     base *temp = new base(); }   How about in the above code? How can the memory leaks be avoided after the constructor throws?
112656
I have a problem with FeedItems in my Test class, it's very weird behaviour Does someone explain to me why this happens?  Callout Class  public with sharing class Callout {  public static void runProccess(Case[] records) {     Database.executeBatch(new CalloutBatch(records), 10); }  public static void send(Case[] records) {     Case[] toUpdate = new Case[]{};       for (case record : records) {         HttpRequest req = new HttpRequest();         req.setEndpoint('callout:test/SOME_URL');         req.setMethod('POST');         req.setHeader('Content-Type', 'application/json');         req.setBody('');         Http http = new Http();         HTTPResponse res = http.send(req);          Map&lt;String, Object&gt; response = (Map&lt;String, Object&gt;) JSON.deserializeUntyped(res.getBody());          toUpdate.add(new Case(Id = (Id) response.get('Id'), Status = (String) response.get('Status')));     }      update toUpdate;  } }   CalloutBatch Class  global with sharing class CalloutBatch implements Database.Batchable&lt;Case&gt;, Database.AllowsCallouts{  private final Case[] records;  global CalloutBatch (Case[] records) {     this.records = records; }  global Iterable&lt;Case&gt; start(Database.BatchableContext BC) {     return records; }  global void execute(Database.BatchableContext BC, Case[] scope) {     Callout.send(scope); }  global void finish(Database.BatchableContext BC) { } }   Test Class  @IsTest  private class CalloutTest { @IsTest static void shouldReaciveData() {     String status = 'Closed';     Case caseRecord = new Case(Type = 'Web', Status = 'New');     insert caseRecord;      //insert new FeedItem(ParentId = caseRecord.Id, Visibility='AllUsers', Type = 'TextPost', Body = '');      System.assertEquals(0, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]);      Test.startTest();     Test.setMock(HttpCalloutMock.class, new CalloutTestMock(caseRecord.Id, status));     Callout.runProccess(new Case[]{caseRecord});     Test.stopTest();      System.assertEquals(1, [SELECT Count() FROM Case WHERE Id = :caseRecord.Id AND Status = :status]); } }   Mock Class  public with sharing class CalloutTestMock implements HttpCalloutMock {  private Id recordId; private String status;  public CalloutTestMock(Id recordId, String status) {     this.recordId = recordId;     this.status = status; }  public HTTPResponse respond(HTTPRequest req) {     HttpResponse response = new HttpResponse();      response.setStatusCode(200);     response.setBody('{"Id": "' + recordId + '", "Status": "' + status + '"}');      return response; } }   This code works, but when I uncomment insert FeedItem in Test Class I receive an error message:     System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out   Class.Callout.send: line 23, column 1   Class.CalloutBatch.execute: line 20, column 1   FeedItem doesn't have an impact on this functionality, (I don't have any Process Builders, triggers etc. on FeedItem object)