1 . Need to understand Boxing in core java?

Answer :

Since there is no sifer(int) method, the compiler will try to find the "closest match". In this case, the other 2 sifer methods take arrays as parameters, which an int clearly isn't.

The last method, sifer(Object) can be applied to any objects, including an Integer so that's the method that is used for sifer(7).

The reality is a little more complex, and the JVM will look for a matching mathod in the following order:

  • an identity conversion
    • in your case: sifer(int) but there is no such method
  • a widening primitive conversion
    • in your case: sifer(long) for example, but there is no such method
  • a widening reference conversion
    • in your case: not applicable, int is not an object
  • a boxing conversion optionally followed by widening reference conversion
    • in your case that's what's happening: int is boxed to Integer which is widened to Object
  • an unboxing conversion optionally followed by a widening primitive conversion
    • in your case: not applicable

Leave a Comment

1 . Useful Java Annotations?

Answer :

I doled out a bunch of upvotes for other users, but just to give my two cents the only three annotations I use with any regularity in development are the main annotations used directly by the compiler:

@Override - Great for making it explicit in your code when you're overriding another method. Also has the extra benefit of being flagged as a compilation error if you don't override a method the way you think you are (see this other SO post). This flag informs the compiler that you're intending to override something, so if you don't (e.g. you forget an argument in the method signature), the compiler will catch it.

@Deprecated - Indicate whatever you're marking as something that should not be used from this point forward. The compiler will generate warnings for use of any code elements you've marked as deprecated. In general, deprecation says "this was in here in the past, but it may go away in a future version." Make sure you also use the associated "@deprecated" Javadoc flag in conjunction with this too to tell people what they should use instead.

@SuppressWarnings - Tell the compiler to suppress specific warnings it would otherwise generate. This can be useful for things like when you intentionally want to use deprecated methods, you can block out the deprecation warning. I tend to use it a lot to block out everyone's favorite "Serialization UID" warning on serializable classes (whether or not you should do that is another debate for another time). Just handy for those cases where you know something you're doing is generating a warning, but you're 100% sure it's the proper behavior you want.

Look at the Sun Annotations Guide and check out the section "Annotations Used by the Compiler". These three are given a fairly lengthy discussion.

2 . How to determine the optimal number of java threads when using a hyperthreaded multi core CPU?

Answer :

The ideal number of threads depend on the task itself. Context switching in modern CPU's can be somewhat expensive due to the fact that data used in the computation is cached heavily. Consider the situation where there are no IO related activities and the CPU cycles need not be wasted waiting. Then the maximum throughput would be achieved by having n_threads = n_cores. Context switching might be expensive even when hyper threading is available. But if there are IO activities, increasing the thread count beyond the number of cores can benefit.



3 . The enhanced forstatement?

Answer :

You don't get an index in an enhanced for-loop. you get a reference to the value in the containeryou are iterating. So, you can directly print it.

Change the below statement in your 1st snippet:




For your 2nd snippet, this:

for (int g: greeting)

doesn't make sense at all. As I said, you get the copy of reference to the elements in greeting, and since the element in greeting are of type String, your loop variable should be String g as in first snippet.

4 . Some basic questions about javax vs java packages?

Answer :

I think it's fairly arbitrary. As Jon Skeet says in his answer to the question you link to, much of it historical. A good example of this is javax.sql - it contains classes to do with JDBC that were originally part of J2EE, but which were brought into J2SE in 1.4. So now there is a pointless split of classes between java.sql and javax.sql. There's no particular meaning attached to the java/javax split inside the JDK.

  1. The CORBA classes are where they are because they aren't defined by the Java standard; they're translations of interfaces defined in the CORBA specifications.
  2. There are plenty of javax.* packages that come with the standard J2SE JDK/JRE (javax.sql, javax.xml). There are also javax.* packages which don't (javax.inject, javax.servlet, etc). But there are no java.* packages which are not in the JDK.
  3. I believe the bootstrap classloader loads java.* and javax.* classes alike.

5 . Java jsr310: difference between dates and times?

Answer :

Answering wrt to the final JDK1.8 version.

There are two amount classes - Duration and Period. Duration is time-based (nanos) and Period is date-based (year/month/day).

The amount of time between two temporal objects of the same type can be easily calculated in one of two ways (I prefer the first):

long days = ChronoUnit.DAYS.between(start, end);
long days = start.until(end, ChronoUnit.DAYS);

The Duration between two temporal objects of the same type can be calculated as follows:

Duration d = Duration.between(start, end);

The Period between two LocalDate objects can be calculated as follows:

Period p = Period.between(start, end);

6 . Make getSystemService() recognize our new system service?

Answer :

Are these 2 files the same? or is it just missing(the content/app folder)?

These are the same files.

Any idea on what to do?

As I said the implementation has been changed. I looked into the code and here what you can change to make your code working (I can only suppose because I did not actually build my code). In the static block of ContextImpl class you need to add the following code:

registerService(ACCOUNT_SERVICE, new ServiceFetcher() {
    public Object createService(ContextImpl ctx) {
        IBinder b = ServiceManager.getService(OPERSYS_SERVICE);
        IOpersysService service = IOpersysService.Stub.asInterface(b);
        return new OpersysManager(service);

7 . Core reading resources for Java Multithreading / Concurrency? [closed]?

Answer :

I propose you something slightly different: Programming Concurrency on the JVM.

This will explain to you the different models and the different problems with concurrency on the JVM. Not entirely targeted at Java, but at the JVM ecosystem, it will give you a deep understanding, along with the technical tools.

8 . Dual-core CPU utilization w/ single Java thread running [duplicate]?

Answer :

When the OS executes threads, it runs each thread for a certain period of time (say 10-20ms), then saves the state of the thread, and looks for other threads to run.

Now, despite what you might think from looking at the CPU Utilization graph, the OS is actually running a lot more threads than those from your program. There are threads running UI loops, threads waiting on I/O, threads running background services, etc. Most of the threads spend most of their time blocked waiting on something.

The reason why I'm talking about this is to explain that from OS's point of view, the situation is more complex than it might look. There are a whole bunch of threads doing a whole bunch of things, and the OS is attempting to switch between them. Suppose that you wanted to implement a heuristic that if a thread used up its entire quantum the last time, then the OS will make an effort to schedule it to the same core. The OS needs to track and take into account more information, and the success of the optimization may depend on a lot of hard-to-predict factors.

In addition, the benefit of affinitizing a thread to a core are often negligible in practice, so OSes don't attempt to do it automatically. Instead, they expose a feature that allows the developer to explicitly say that a particular thread should be affinitized to a core, and then the OS will respect the decision.

That seems like a reasonable trade-off: if your thread performs better when affinitized to a core, just ask the OS to do that. But, the OS won't bother attempting to figure it out for you.

9 . Generic programming in java?

Answer :

If the above were true, then you could take your collection of managers, treat it as a collection of employees, and then put any employee into a collection of managers (i.e. not just a manager, but a (say) graduate trainee, a CIO etc.)

It's a little counter-intuitive. An orange is a fruit. A list of oranges is not a list of fruit (otherwise you could put an apple in it). There's a concise explanation in the Java Generics Tutorial.

10 . Cant compile and run java code in IntelliJ IDEA?

Answer :

Sergey, it's look like you are working wrong with Idea. There is a step-by-step tutorial at wiki, that describes some basic concepts, about roots, run configurations, sdk-s and dependencies. It will be good, if you look at it. (Exploring the project structure and Building(Running) the projectespecially)

IDE is a great helper to learn language, especially such intellegent one, as Idea, so, it will be a good start, to get familiar with it.

Basically, for a start, all your code(not compiled classes) must be under the source roots, and runConfiguration must specify application entry point (class with static void main() method).

You shouldn't think about class files, jar archives or command line tools, IDEA can do all this for you.

Better concentrate on learning, as I think!

11 . Java: How to scale threads according to cpu cores?

Answer :

You can determine the number of processes available to the Java Virtual Machine by using the static Runtime method, availableProcessors. Once you have determined the number of processors available, create that number of threads and split up your work accordingly.

Update: To further clarify, a Thread is just an Object in Java, so you can create it just like you would create any other object. So, let's say that you call the above method and find that it returns 2 processors. Awesome. Now, you can create a loop that generates a new Thread, and splits the work off for that thread, and fires off the thread. Here's some psuedocode to demonstrate what I mean:

int processors = Runtime.getRuntime().availableProcessors();
for(int i=0; i < processors; i++) {
  Thread yourThread = new AThreadYouCreated();
  // You may need to pass in parameters depending on what work you are doing and how you setup your thread.

12 . Why is (a*b != 0) faster than (a != 0 && b != 0) in Java?

Answer :


I'm ignoring the issue that your benchmarking might be flawed, and taking the result at face value.

Is it the compiler or is it at the hardware level?

That latter, I think:

  if (a != 0 && b != 0)

will compile to 2 memory loads and two conditional branches

  if (a * b != 0)

will compile to 2 memory loads, a multiply and one conditional branch.

The multiply is likely to be faster than the second conditional branch if the hardware-level branch prediction is ineffective. As you increase the ratio ... the branch prediction is becoming less effective.

The reason that conditional branches are slower is that they cause the instruction execution pipeline to stall. Branch prediction is about avoiding the stall by predicting which way the branch is going to go and speculatively choosing the next instruction based on that. If the prediction fails, there is a delay while the instruction for the other direction is loaded.

(Note: the above explanation is oversimplified. For a more accurate explanation, you need to look at the literature provided by the CPU manufacturer for assembly language coders and compiler writers. The Wikipedia page on Branch Predictors is good background.)

However, there is one thing that you need to be careful about with this optimization. Are there any values where a * b != 0 will give the wrong answer? Consider cases where computing the product results in integer overflow.


Your graphs tend to confirm what I said.

  • There is also a "branch prediction" effect in the conditional branch a * b != 0 case, and this comes out in the graphs.

  • If you project the curves beyond 0.9 on the X-axis, it looks like 1) they will meet at about 1.0 and 2) the meeting point will be at roughly the same Y value as for X = 0.0.


I don't understand why the curves are different for the a + b != 0 and the a | b != 0 cases. There could be something clever in the branch predictors logic. Or it could indicate something else.

(Note that this kind of thing can be specific to a particular chip model number or even version. The results of your benchmarks could be different on other systems.)

However, they both have the advantage of working for all non-negative values of a and b.


13 . Start Instances of Java Program, Each on a Separate Core?

Answer :

I don't know of any way to attach instances of Java programs to specific CPUs / cores. As an alternative, consider making the program concurrent, i.e. start multiple executor threads internally. This way you need to run only a single instance of it, but its individual threads would run on distinct processors/cores if there are multiple available ones.

This in fact probably yields better performance and is more scalable than running multiple processes - the Executor framework allows you to choose different thread pools, change the number of threads even dynamically, manages dead threads for you etc.

14 . Oozie java-action does not include core-site.xml?

Answer :

The reason of that the core-site.xml is not included in the class-path of the java-action is because the property mapreduce.application.classpath points to the wrong directory:


It should point to


i.e, the full property should be something like, in mapred-site.xml:


15 . Integrate C and JAVA in Blackberry?

Answer :

You can't integrate C, as RIM does not expose any API for the platform. Since BlackBerry use a j2me-compliant JVM, JNI is not exposed.

Prior answer is partially correct - you may write code that uses only the J2ME API, but you can also use RIM's own Java API for better/more advanced features and functionality.