Enormous Input Test - reducing program runtime This is my solution to SPOJ Problem 442.  How can I make this code run faster? What are some techniques that can be used to make this faster? I am getting a Time Limit Exceed Error here.

import java.util.Scanner;

class main{
   public static void main(String args[]){
      Scanner input = new Scanner(System.in);
      int n,k,m=0;
      n = input.nextInt();
      k = input.nextInt();

      for(int c = 0 ; c &lt; n ; c++){
         if(input.nextInt() % k == 0) m++;
      }

      System.out.println(m);
    }
}
The main reasons are


Scanner is pretty slow
System.in is unbuffered


By using a BufferedReader instead of the Scanner you get it to barely acceptable levels. The following approach runs in roughly 8.2 seconds and get's accepted.

public class Main {
    public static void main(String args[]) throws java.io.IOException {
        java.io.InputStreamReader isr = new java.io.InputStreamReader(System.in);
        java.io.BufferedReader br = new java.io.BufferedReader(isr, 16 * 1024);
        String[] line0 = br.readLine().split(" ");
        int n, k, m = 0;
        n = Integer.parseInt(line0[0]);
        k = Integer.parseInt(line0[1]);
        for (int c = 0; c &lt; n; c++) {
            if (Integer.parseInt(br.readLine()) % k == 0)
                m++;
        }

        System.out.println(m);
    }
}


But it's still really slow compared to the top scoring solutions that run in under 2 seconds.

I've got it down to a bit over 2 seconds by reading into a byte[] buffer and doing custom number parsing based on that buffer roughly like the following incomplete piece (which just prints the parsed numbers)

public class Main {
    public static void main(String args[]) throws java.io.IOException {
        byte[] buffer = new byte[16 * 1024];
        int currentNumber = 0;
        boolean inNumber = false;
        int read;
        while((read = System.in.read(buffer)) &gt;= 0) {
            for (int i = 0; i &lt; read; i++) {
                char c = (char) buffer[i];
                if (c &gt;= '0' &amp;&amp; c &lt;= '9') {
                    inNumber = true;
                    currentNumber = currentNumber * 10 + (c - '0');
                } else if (inNumber) {
                    inNumber = false;
                    System.out.println("I've read number: " + currentNumber);
                    currentNumber = 0;
                }
            }
        }
    }
}


See http://ideone.com/lQ4ImB for above code with input

The reason why this is so much faster is basically that there is almost 0 overhead in reading &amp; parsing the input into numbers. BufferedReader in comparison is transforming each line into a String (thus creating a new Object), then parses that String. Above approach allocates no new Objects besides the single byte[] buffer.