Java Competitive Programming Setup in VS Code with Fast I/O and Snippets


Introduction

In this tutorial, we will walk you through the process of setting up a Java development environment in Visual Studio Code (VS Code) and introduce you to some useful tools and techniques for competitive programming, including fast input/output (I/O) techniques and useful code snippets.

Setting up Java Development Environment in VS Code

To start coding in Java within VS Code, follow these steps −

  • Install Java Extension Pack− Open VS Code and navigate to the Extensions view by clicking on the square icon on the left sidebar or by using the shortcut Ctrl+Shift+X (Windows/Linux) or Cmd+Shift+X (Mac). Search for "Java Extension Pack" and install it. This extension pack includes essential tools for Java development.

  • Create a Java Project− Now, let's create a new Java project. Press Ctrl+Shift+P (Windows/Linux) or Cmd+Shift+P (Mac) to open the Command Palette. Type "Java: Create Java Project" and select it. Choose an appropriate location on your machine for the project and provide a name for it.

  • Run Your First Java Code− Open the auto-generated Java class file (App.java) inside the src folder, and you should see a simple "Hello, World!" program−

Example

public class App {
   public static void main(String[] args) {
      System.out.println("Hello, World!");
   }
}
  • Compile and Run− You can use the integrated terminal in VS Code to compile and run the Java code. Open the integrated terminal by selecting "View" → "Terminal" or by using the shortcut Ctrl + backtick (Windows/Linux) or Cmd + backtick (Mac). In the terminal, use the following commands−

javac Main.java
java Main

Output

Hello, World!

Now, let's explore some techniques to improve your competitive programming experience.

Fast I/O for Competitive Programming

Method 1

In competitive programming, efficient input/output (I/O) operations can significantly impact the performance of your program. Let's explore a fast I/O technique using BufferedReader and StringTokenizer.

  • Import Required Classes− Add the following import statements at the beginning of your Java class file−

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
  • Set up Input Reader− Declare a BufferedReader object to read input from the console and initialize it in the main method as follows−

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  • Read Input− To read space-separated integers from a line, use the StringTokenizer class as shown below−

StringTokenizer st = new StringTokenizer(br.readLine());
int a = Integer.parseInt(st.nextToken());
int b = Integer.parseInt(st.nextToken());
  • Set up Output Writer− Declare a StringBuilder object to efficiently build the output and initialize it in the main method as follows−

StringBuilder sb = new StringBuilder();
  • Write Output− Instead of using System.out.println(), append the output strings to the StringBuilder object−

sb.append("Result: ").append(result).append('\n');
  • Flush Output− Finally, after processing all the test cases, print the output using System.out and flush it−

System.out.print(sb);
System.out.flush();

Example

Let's see an example that calculates the sum of two integers−

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class App{
   public static void main(String[] args) throws IOException {
      BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
      StringTokenizer st = new StringTokenizer(br.readLine());

      int a = Integer.parseInt(st.nextToken());
      int b = Integer.parseInt(st.nextToken());
      int sum = a + b;
      
      StringBuilder sb = new StringBuilder();
      sb.append("Sum: ").append(sum).append('\n');
      
      System.out.print(sb);
      System.out.flush();
   }
}

Input

Output

Method 2

Alternatively, you can use two files for input, and output is much easier to copy and paste longer input and write the output to separate files rather than using the console/terminal window. To use this technique, follow these steps−

  • Create two files in the same folder as your Java program, one for reading the input and the other for writing the output. You can put those files in a separate folder, be sure to use the appropriate paths of the files in the program.

  • Declare a BufferedReader object to read input from the input file and initialize it in the main method as follows−

BufferedReader reader = new BufferedReader(new FileReader(“input.txt”));
  • Declare a PrintStream object to write the output to the output file and initialize it in the main method as follows−

PrintStream printStream = new PrintStream(new FileWriter(“output.txt”));
  • Instead of using System.out.println(), write the output to the output file with the help of the PrintStream object−

printStream.print("Product: " + product);

Example

Let's see another example that calculates the product of two integers−

import java.io.BufferedReader;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;

public class App {
   public static void main(String[] args) throws IOException {
      BufferedReader reader = new BufferedReader(new FileReader("input.txt"));
      int num1 = Integer.parseInt(reader.readLine());
      int num2 = Integer.parseInt(reader.readLine());
      reader.close();
      int product = num1 * num2;
      PrintStream printStream = new PrintStream(new FileOutputStream("output.txt"));
      printStream.print("Product: " + product);
      printStream.close();
    }
}

Output

Code Snippets for Productivity

You can utilize code snippets in VS Code to boost your productivity while coding in Java. Code snippets allow you to quickly insert commonly used code templates with just a few keystrokes.

Method 1

You can use the Java Snippets VS Code extension as follows−

  • Install Java Snippets− Open the Extensions view in VS Code (Ctrl+Shift+X or Cmd+Shift+X) and search for "Java Snippets." Install the extension provided by "Visual Studio Code Team."

  • Insert Snippets− To insert a code snippet, type the snippet keyword and select the desired snippet from the IntelliSense dropdown. For example, typing main will display the "Java Main Method" snippet. Press Enter to insert the snippet at the current cursor position.

Consider a scenario where you frequently need to create a for loop. Instead of typing the entire for loop structure, you can use the for snippet. Type for and select the "Java For Loop" snippet from the IntelliSense dropdown.

Syntax

The syntax to create a 'for' loop in Java is as follows−

for (initialization; condition; update) {
   // code to be executed
}

The snippet will be inserted as follows−

The snippet example above provides placeholders for length, which you can replace with the desired loop length. This saves you time and effort when creating repetitive code structures.

Method 2

VS Code offers convenient support for creating and utilizing your code snippets. Let's create a custom code snippet for a binary search algorithm.

  • Creating a Code Snippet− Open VS Code and navigate to the User Snippets by going to File > Preferences > Configure User Snippets. Choose the language "Java" and add the following snippet−

"Binary Search": {
   "prefix": "binarysearch",
   "body": [
      "int low = 0;",
      "int high = ${1:array.length} - 1;",
      "while (low <= high) {",
      "    int mid = low + (high - low) / 2;",
      "    if (array[mid] == ${2:target}) {",
      "        // Target found",
      "        break;",
      "    } else if (array[mid] < ${2:target}) {",
      "        low = mid + 1;",
      "    } else {",
      "        high = mid - 1;",
      "    }",
      "}"
   ],
   "description": "Binary search algorithm"
}
  • Utilizing the Code Snippet− In your Java code file, type the snippet prefix binarysearch and press Tab to expand it. Modify the necessary placeholders and use the snippet as a starting point for your binary search implementation.

Conclusion

In this tutorial, we have walked through the process of setting up a Java development environment in VS Code for competitive programming. We learned about configuring the JDK, creating Java projects, and executing Java code within VS Code. Additionally, we explored the fast I/O technique using BufferedReader and StringTokenizer for efficient input/output operations and PrintStream for fast copying of input.

Updated on: 24-Jul-2023

358 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements