smallseo.info

java interview questions

Top java frequently asked interview questions

Why is printing "B" dramatically slower than printing "#"?

I generated two matrices of 1000 x 1000:

First Matrix: O and #.
Second Matrix: O and B.

Using the following code, the first matrix took 8.52 seconds to complete:

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("#");
        }
    }

   System.out.println("");
 }

With this code, the second matrix took 259.152 seconds to complete:

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
            System.out.print("O");
        } else {
            System.out.print("B"); //only line changed
        }
    }

    System.out.println("");
}

What is the reason behind the dramatically different run times?


As suggested in the comments, printing only System.out.print("#"); takes 7.8871 seconds, whereas System.out.print("B"); gives still printing....

As others who pointed out that it works for them normally, I tried Ideone.com for instance, and both pieces of code execute at the same speed.

Test Conditions:

  • I ran this test from Netbeans 7.2, with the output into its console
  • I used System.nanoTime() for measurements

Source: (StackOverflow)

Generating random integers in a specific range

I am trying to generate a random intvalue with Java, but in a specific range.

For example:

My range is 5-10, meaning that 5 is the smallest possible value and 10 is the biggest. Any other number in between these numbers is possible to be a value, too.

In Java, there is a method random() in the Math class, which returns a double value between 0.0 and 1.0. In the class Random there is the method nextInt(int n), which returns a random int value in the range of 0 (inclusive) and n (exclusive). I couldn't find a method, which returns a random integer value between two numbers.

I have tried the following things, but I still have problems: (minimum and maximum are the smallest and biggest numbers).

Solution 1:

randomNum = minimum + (int)(Math.random() * maximum); 

Problem:

randomNum can be bigger than maximum.

Solution 2:

Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;

Problem:

randomNum can be smaller than minimum.

How do I solve these problems?

I have tried also browsing through the archive and found:

But I couldn't solve the problem.


Source: (StackOverflow)

Avoiding != null statements

The idiom I use the most when programming in Java is to test if object != null before I use it. This is to avoid a NullPointerException. I find the code very ugly, and it becomes unreadable.

Is there a good alternative to this?

I want to address the necessity to test every object if you want to access a field or method of this object. For example:

if (someobject != null) {
    someobject.doCalc();
}

In this case I will avoid a NullPointerException, and I don't know exactly if the object is null or not. These tests appear throughout my code as a consequence.


Source: (StackOverflow)

Why is processing a sorted array faster than an unsorted array?

Here is a piece of C++ code that seems very peculiar. For some strange reason, sorting the data miraculously makes the code almost six times faster.

#include <algorithm>
#include <ctime>
#include <iostream>

int main()
{
    // Generate data
    const unsigned arraySize = 32768;
    int data[arraySize];

    for (unsigned c = 0; c < arraySize; ++c)
        data[c] = std::rand() % 256;

    // !!! With this, the next loop runs faster
    std::sort(data, data + arraySize);

    // Test
    clock_t start = clock();
    long long sum = 0;

    for (unsigned i = 0; i < 100000; ++i)
    {
        // Primary loop
        for (unsigned c = 0; c < arraySize; ++c)
        {
            if (data[c] >= 128)
                sum += data[c];
        }
    }

    double elapsedTime = static_cast<double>(clock() - start) / CLOCKS_PER_SEC;

    std::cout << elapsedTime << std::endl;
    std::cout << "sum = " << sum << std::endl;
}
  • Without std::sort(data, data + arraySize);, the code runs in 11.54 seconds.
  • With the sorted data, the code runs in 1.93 seconds.

Initially, I thought this might be just a language or compiler anomaly. So I tried it in Java.

import java.util.Arrays;
import java.util.Random;

public class Main
{
    public static void main(String[] args)
    {
        // Generate data
        int arraySize = 32768;
        int data[] = new int[arraySize];

        Random rnd = new Random(0);
        for (int c = 0; c < arraySize; ++c)
            data[c] = rnd.nextInt() % 256;

        // !!! With this, the next loop runs faster
        Arrays.sort(data);

        // Test
        long start = System.nanoTime();
        long sum = 0;

        for (int i = 0; i < 100000; ++i)
        {
            // Primary loop
            for (int c = 0; c < arraySize; ++c)
            {
                if (data[c] >= 128)
                    sum += data[c];
            }
        }

        System.out.println((System.nanoTime() - start) / 1000000000.0);
        System.out.println("sum = " + sum);
    }
}

With a somewhat similar, but less extreme result.


My first thought was that sorting brings the data into the cache, but my next thought was how silly that is, because the array was just generated.

  • What is going on?
  • Why is a sorted array faster than an unsorted array?
  • The code is summing up some independent terms, and the order should not matter.

Source: (StackOverflow)

How can I test if an array contains a certain value?

I have a String[] with values like so:

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

Given String s, is there a good way of testing whether VALUES contains s?


Source: (StackOverflow)

Differences between HashMap and Hashtable?

What are the differences between a HashMap and a Hashtable in Java?

Which is more efficient for non-threaded applications?


Source: (StackOverflow)

How to test a class that has private methods, fields or inner classes?

How do I use JUnit to test a class that has internal private methods, fields or nested classes? It seems bad to change the access modifier for a method just to be able to run a test.


Source: (StackOverflow)

Converting String to Int in Java?

How can I convert a String to an int in Java?

My String contains only numbers and I want to return the number it represents.

For example, given the string "1234" the result should be the number 1234.


Source: (StackOverflow)

Initialization of an ArrayList in one line

I want to create a list of options for testing purposes. At first, I did this:

ArrayList<String> places = new ArrayList<String>();
places.add("Buenos Aires");
places.add("Córdoba");
places.add("La Plata");

Then I refactored the code as follows:

ArrayList<String> places = new ArrayList<String>(
    Arrays.asList("Buenos Aires", "Córdoba", "La Plata"));

Is there a better way to do this?


Source: (StackOverflow)

Java += operator

Until today I thought that for example:

i += j;

is just a shortcut for:

i = i + j;

But what if we try this:

int i = 5;
long j = 8;

Then i = i + j; will not compile but i += j; will compile fine.

Does it mean that in fact i += j; is a shortcut for something like this i = (type of i) (i + j)?


Source: (StackOverflow)

How do I call one constructor from another in Java?

Is it possible to call a constructor from another (within the same class, not from a subclass)? If yes how? And what could be the best way to call another constructor (if there are several ways to do it)?


Source: (StackOverflow)

What is a serialVersionUID and why should I use it?

Eclipse issues warnings when a serialVersionUID is missing.

The serializable class Foo does not declare a static final serialVersionUID field of type long

What is serialVersionUID and why is it important? Please show an example where missing serialVersionUID will cause a problem.


Source: (StackOverflow)

Creating a memory leak with Java [closed]

I just had an interview, and I was asked to create a memory leak with Java. Needless to say I felt pretty dumb having no clue on how to even start creating one.

What would an example be?


Source: (StackOverflow)

Using java.net.URLConnection to fire and handle HTTP requests

Use of java.net.URLConnection is asked about pretty often here, and the Oracle tutorial is too concise about it.

That tutorial basically only shows how to fire a GET request and read the response. It doesn't explain anywhere how to use it to among others perform a POST request, set request headers, read response headers, deal with cookies, submit a HTML form, upload a file, etc.

So, how can I use java.net.URLConnection to fire and handle "advanced" HTTP requests?


Source: (StackOverflow)

Is Java "pass-by-reference" or "pass-by-value"?

I always thought Java was pass-by-reference; however I've seen a couple of blog posts (for example, this blog) that claim it's not. I don't think I understand the distinction they're making.

What is the explanation?


Source: (StackOverflow)