VS Code code navigation and code editing for Java development

Quick Navigation

VS Code provides some features for quick navigation when developing in Java.

Code Navigation

  • Outline view: Easily navigate members in the current file
  • Projects view: Detailed overview of projects
  • Java Editor: Supports call hierarchy, type hierarchy, definition navigation, search types in workspace, etc.

Search functionality (# and @)

Search allows you to quickly navigate to code in the current file or workspace.

1. Search in the workspace

Proceed as follows:

  1. Press the Ctrl + T keys
  2. Enter the symbol you want to search to search in the current workspace.
  3. When entering characters, a matching list will be displayed (searching for matching files). If the matching file is not open, the file will be opened first.

Another way to operate is:

  1. Press Ctrl + P to open the command
  2. Enter # and search
    In other words, the # command is a shortcut for Ctrl + T.

2. Search in the current file

The steps to search in the current file are as follows:

  1. Press Ctrl + P to open the command palette

  2. Enter @

  3. Enter the content to be searched in the current file.

  4. When typing, a matching list will be displayed. Just select the matching option and click on it.

Peek Definition

In Visual Studio Code (VS Code), “Peek Definition” is a powerful feature that allows you to quickly view and edit the definition of your code in the same editing window without having to navigate to other files or locations.

How to use the “Peek Definition” function:

  • Method 1: Operation through the right-click menu: Right-click the class, function or variable you want to view the definition in your code, and then select “Peek Definition” in the pop-up right-click menu.

  • Method 2: Operate through shortcut keys: Place the cursor on the class, function or variable you want to view the definition, and then press Alt + F12 (Option + F12 on MacOS).

No matter which way you operate, VS Code will open a small window in the current editing window to display the definition of the item you are viewing. You can view and edit the code in this small window, and you can close it by clicking the “x” in the upper right corner or by pressing the Esc key again.

“Peek Definition” is a very convenient function, especially when dealing with large code bases or complex logical operations. It can save you time switching between different code files and code segments, and improve programming efficiency.

Here is an example of viewing the definition of the println() function:

  1. Select the function, right-click to pop up the menu, select Peek > Peek Definition

  2. After clicking, it displays as follows:

The top will show in which file this method is defined and the specific definition of the method. Click the “x” button on the far right to close this window.

Go to Definition

Use “Go to Definition” to quickly go to the definition. “Go To Definition” is a very practical function for navigating to the definition of code elements. This makes it easier for developers to understand and maintain the code.

There are many ways to use Go To Definition, including:

  • Method 1: Use the right-click menu operation: right-click the variable, function or class that needs to be defined, and then select “Go to Definition” in the pop-up menu.
  • Method 2: Use shortcut keys: Place the cursor on the variable, function or class that needs to be defined, and then press the F12 key. On macOS, the default shortcut key is F12.

After successfully executing “Go to Definition”, VS Code will jump to the definition position of the selected element. If it is defined in the current file, VS Code will jump to the corresponding location in the file; if it is defined in another file, VS Code will open that file and jump to the corresponding location.

If there are multiple definition locations (for example, multiple implementations of a Java interface), VS Code will list all locations in the “Go to Definition” drop-down list and let you choose the target to jump to.

Also taking the definition of the println() function above as an example, the effect after viewing is as follows:

The final results viewed by Go to Definition and Peek Definition are similar, but the display methods are different. The former opens the target file for display, while the latter displays the same file.

Go to Super Implementation (go to parent class)

In Visual Studio Code (VS Code), “Go to Super Implementation” is a feature used to navigate to the superclass (parent class) or interface implementation of the current method or class. It is a very practical function when dealing with object-oriented programming, helping you understand and track the inheritance relationship and interface implementation of classes.

However, it should be noted that VS Code does not support the “Go to Super Implementation” function by default. You need to install the Java Language Support plug-in (provided by Red Hat) to use this function. There are also many ways to use “Go to Super Implementation”:

  • Method 1: Use the right-click menu operation: Right-click the method or class that needs to be navigated to the super class or interface implementation, and then select “Go to Super Implementation” in the pop-up menu.

  • Method 2: Use shortcut keys: Place the cursor on the method or class that needs to be navigated to the super class or interface implementation, then press the Ctrl key and click with the mouse. On macOS, the default shortcut is Cmd + mouse click.

If a method or class has a superclass or interface implementation, VS Code will jump to the corresponding implementation code. If there are multiple implementations, VS Code will display a list of all implementations for you to choose from.

Using the “Go to Super Implementation” feature can help you understand the structure and logic of your code more effectively, especially when dealing with large projects and complex class and interface structures.

For example, the following class is defined:

public class Animal extends Object{
    
    public String toString(){
        return "";
    }
}

  • The Animal class inherits from Object, and the toString() method is also an overridden method of the parent class.

After selecting the toString() method and clicking “Go to Super Implementation”, Object.class will open and locate the definition of the toString() method.

View the hierarchical structure of calls

You can display and navigate the call graph of the current function or method in VS Code.
How to view “Call Hierarchy”:

  • Method 1: Operate through the right-click menu: In your code, right-click the function or method you want to view the call hierarchy, and then select “Peek > Peek Call Hierarchy” in the pop-up menu.
  • Method 2: Right-click the function body and select “Show Call Hierarchy”.
  • Method 3:: Operation via shortcut keys: Place the cursor on the function or method you want to view the call hierarchy, and then press Ctrl + Shift + Alt + H (Ctrl + Option + Shift + H on MacOS).

Regardless of which method you choose, VS Code will open a “Call Hierarchy” window at the bottom of the current window. In this window you can see two options:

  • One is “Calls From”, which shows which other functions or methods called the current function or method;
  • The other is “Calls To”, which shows which other functions or methods are called by the current function or method.
    You can click on any function or method in the window to jump to its location in the code.

“Call Hierarchy” is a convenient and practical function that allows you to quickly understand the code structure and function calling relationships. It can improve your efficiency especially when dealing with large projects or complex logic.

Note: VS Code plugins for different programming languages or frameworks may have different levels of “Call Hierarchy” support. For example, in JavaScript/TypeScript or C++, you may need to have the latest plugins and language services to use this feature. In Java, you need to install the “Language Support for Java? by Red Hat” plug-in to use this feature.

Example:

Click the button on the right to switch between Calls From and Calls To

Type Hierarchy

The type hierarchy view shows the inheritance relationships between Java objects. You can right-click the class and select “Show Type Hierarchy”.

The displayed effect is as follows:

Collapse block

Collapse areas allow code snippets to be collapsed or expanded for a better view of the source code.

Smart selection

Smart selection (semantic selection) allows you to expand or narrow the selection based on semantic information about the caret position in the source code.

  • To expand the selection, use Shift + Alt + Right.
  • To narrow the selection, use Shift + Alt + Left.

semantic Highlighting

With semantic highlighting, VS Code provides more accurate source code coloring based on symbolic information from the Java Language Service.

The following is just an example. The left side is the behavior after enabling semantic highlighting, and the right side is the behavior with only syntax highlighting.

“Sematic Highlighting”, also called semantic highlighting, is a very powerful feature provided by Visual Studio Code (VS Code). It can provide richer and more diverse color highlighting for code elements based on the semantics of the code (such as types and scopes of variables, functions, classes, etc.), not just based on syntax (such as keywords, operators, etc.) ).

How to enable or disable Sematic Highlighting:

The enabled status of “Sematic Highlighting” depends on the language you are using and the corresponding VS Code plug-in. Some language support plugins (such as C++ or TypeScript/JavaScript) enable this feature by default; some other languages may need to be explicitly enabled in your settings (settings.json) file. For example, for TypeScript/JavaScript, you can add “editor.semanticHighlighting.enabled”: true to enable Sematic Highlighting,

This setting has the following options:

  • “editor.semanticHighlighting.enabled”: true: Enables semantic highlighting for all files.
  • “editor.semanticHighlighting.enabled”: false: Disable semantic highlighting for all files.
  • “editor.semanticHighlighting.enabled”: “configuredByTheme”: Whether to enable semantic highlighting according to the currently used theme configuration (this is the default setting).
    Note that if the theme does not support semantic highlighting, you will not see a difference even if semantic highlighting is enabled. You can try switching to a theme that supports semantic highlighting, such as the built-in “Dark +” or “Light +” theme.

Whether or not to use semantic highlighting depends on your personal preference. Some people feel that semantic highlighting makes it easier for them to understand the code, while others feel that it makes code coloring too busy. The most important thing is to find a setup that works for you.

Code Snippets

In Visual Studio Code (VS Code), Code Snippets are a very useful feature that allows you to quickly enter commonly used code snippets. VS Code has some commonly used code snippets built-in, and you can also customize your own code snippets.

You can use code snippets to build classes and methods, and VS Code also provides IntelliSense for automatic code completion.
Visual Studio Code supports a variety of popular Java code snippets to make you more productive, such as class/interface, syserr, sysout, if/else, try/catch, static main method. Using information from the Java language server, it can also provide a preview of the code snippet during the selection process.

For example, entering “sout” or “sysout” will generate a code snippet for System.out.println().
Likewise, typing “main” or “psvm” will produce the code snippet public static void main(String[] args) {}.

Code snippet shortcut:

Shortcut keys Description
ctor Public constructor
dowhile Do-while statement
foreach, iter Iteration over array
fori Iteration over array
if if statement
ifelse If-else statement
ifnull Check if statements that are empty
ifnotnull Check if statements that are not empty
main, psvm Public static main method
new Create a new object
private_method Private method
private_static_method Private static method
prf Private fields
protected_method Protected method
public_method Public method
switch switch statement
syserr, serr Standard error output
sysout, sout Standard output
systrace, soutm Print the current method to standard output
try_catch Try/catch statement Block
try_resources Try-with-resources statement
while While statement

Postfix code snippet shortcut

Shortcut keys Template content Description
cast ((SomeType) expr) Convert an expression to a new type
else if (!expr) Create a negative if statement
for for (T item : expr) Create for statement
fori for (int i = 0; i < expr.length; i + + ) Create a for statement that iterates over an array
forr for (int i = expr.length-1; i >= 0 ; i–) Create a for statement that iterates the array in reverse order
if if (expr) Create if statement
nnull if (expr != null) Create if statement and check expression Whether it is not resolved to null
null if (expr == null) Create an if statement to check the expression Whether the expression resolves to null
sysout System.out.println(expr) Send the affected string to System.out.println
throw throw expr Throws the given exception
var T name = expr Create new variable
while while (expr) {} Create a while loop

shortcut key template content description
cast ((SomeType) expr) Casts the expression to a new type
else if (!expr) Creates a negated if statement
for for (T item : expr) Creates a for statement
fori for (int i = 0; i < expr.length; i + + ) Creates a for statement which iterates over an array
forr for (int i = expr.length-1; i >= 0; i–) Creates a for statement which iterates over an array in reverse order
if if (expr) Creates a if statement
nnull if (expr != null) Creates an if statement and checks if the expression does not resolve to null
null if (expr == null) Creates an if statement which checks if expression resolves to null
sysout System.out.println(expr) Sends the affected string to a System.out.println(…) call
throw throw expr Throws the given Exception
var T name = expr Creates a new variable
while while (expr) {} Creates a while loop

How to create and use snippets:

  • Open snippet settings: You can open snippet settings by clicking File > Preferences > User Snippets from the File menu in the upper left corner.

  • Create a new snippet file: In the opened tab you can select an existing snippet file for editing, or create a brand new snippet by clicking New global snippet file. Global code snippets are available for all projects. If you want to create code snippets for a specific project, you can create yourname.code-snippets file in the .vscode folder in the project root directory.

Writing snippets: In a snippet file, you can write your own snippets. The following is a simple snippet example that creates a Java snippet containing System.out.println():

{
    "Print to console": {
        "prefix": "print",
        "body": [
            "System.out.println($1);"
        ],
        "description": "Print output to console"
    }
}

In this example, “Print to console” is the name of the code snippet, and “print” is the prefix of the active code snippet. When you enter “print” in the editor of VS Code and press the Tab key, the code snippet will inserted in

  • “body” defines the code of the code segment
  • “$1” is a position parameter, representing the position where the cursor automatically jumps to.
  • “description” is the description of the code snippet and will be displayed in the autocomplete list.

Use code snippets: After saving your customized code snippet file, you can use your code snippet in the VS Code editor. Just start typing the prefix you defined for your snippet and VS Code will pop up suggestions for snippets and you just select your snippet in the dropdown.
VS Code’s code snippets are very flexible and powerful. You can create code snippets in any language, including cross-file and multi-line code snippets, which are very suitable for improving development efficiency.

Example:
Save the above content to the file myjava.code-snippets

When encoding, enter print and the following effect will appear.

Code editing

Editing code is easy with IntelliSense for smart code completion and signing details. You can use code snippets as well as various code operations such as generating getters/setters and organizing imports to further increase your productivity.

Java support in Visual Studio Code automatically detects problems in your code and provides quick fix suggestions.

IntelliSense (intelligent sensing)

Code completion in Visual Studio Code for Java is provided by Red Hat’s Language Support for Java?. The extension is powered by the same Java development tools (JDT) behind Eclipse.

There’s also AI-assisted IntelliSense called IntelliCode. Save you time by putting the ones you’re most likely to use at the top of your completion list. IntelliCode recommendations are based on thousands of open source projects on GitHub, each with over 100 stars, so it’s trained on the most common usage for high-quality projects. When combined with the context of the code, completion lists will be customized to promote these practices.

IntelliCode works well with popular Java libraries and frameworks like Java SE and Spring. It will help you whether you are developing a monolithic web application or modern microservices.

Reference

  • https://code.visualstudio.com/docs/java/java-tutorial
  • https://code.visualstudio.com/docs/java/java-editing