Essential IntelliJ shortcuts

Essential IntelliJ shortcuts

IntelliJ has more than a 100 shortcuts, but there’s no need to know them all. The based on comparing the most used shortcuts used by my colleagues and me, should give you a headstart in becoming more productive with IntelliJ.

IntelliJ has more than a 100 shortcuts, but there’s no need to know them all. The based on comparing the most used shortcuts used by my colleagues and me, should give you a headstart in becoming more productive with IntelliJ.

A good craftsman knows their tools. Being a software developer is no exception. So, while programming and to stay in the flow of coding, it might be worthwhile to know some keyboard shortcuts and to not be distracted by clicking on menu items. In this blogpost I’ll focus on IntelliJ. While IntelliJ has almost a shortcut for everything, there’s no need to know them all to be a productive programmer. What I’ve done instead is to list only the few me and my colleagues use on a daily basis, and mastering these will make you a slightly more proficient software developer.

I’ve split the keyboard shortcut into a few separate groups. The groups are split into editing and navigation (both the IDE as well as the code), to make the use of IntelliJ easier. The IntelliJ keyboard shortcuts below are based on the default Windows settings, if you’re using a different keymap, please have a look at the keymap reference (Help -> Keymap Reference) for the appropriate shortcut.

IntelliJ keyboard navigation shortcuts

Ctrl+Tab – Switches between Tabs

To quickly switch between open files, press Ctrl + Tab. When holding the Ctrl button, it’s possible to step through the list of open files. Releasing the shortcut will focus on the corresponding file.

Ctrl + E – View recent Files

While Ctrl + Tab lists the currently open files, Ctrl + E opens the list of recently used files.

Ctrl + B – Go to declaration / implementation

When pressing Ctrl + B while on a method, it will jump to to the declaration of this method, for example, the interface. However, pressing Ctrl + Alt + B doesn’t jump to the interface, but to the implementation of this interface, which is quite a time saver.

Double Shift – Search anything

Find anything in your project by quickly double tapping shift. This includes files, actions, classes, basically, anything!

Ctrl + N – Find Class

Instead of finding everything, if you know you’re looking for a class, press Ctrl + N and start typing. You don’t have to type the full class name, you can also type only the uppercased letters, or start with an asterix (*) which will be interpreted as a wildcard.

Ctrl + Shift + N – Find Resource

Handy if you don’t want to find classes, but text or configuration files.

Ctrl + Shift + T – Navigate to Test

When you’re slightly test obsessed, navigating between the test and implementation is instant with this shortcut. Also, when going to an implementation class and pressing ctrl + shift + t will automatically create a test class based on your choice of test framework.

Ctrl + Alt + F7 – Show Usages

This shows all usages of the current method, class or variable in a popup dialog, allowing you to quickly navigate to the locations where this element is being used

Ctrl + F12 – Structure View Popup

Show the list of properties and methods in a popup. Handy to get an idea of what the class is doing.

Ctrl + G – Goto Line (or Column)

Handy when one of your colleagues asks what this piece of code is doing at line 45. Pressing Ctrl + G allows you to quickly navigate to the offending piece of code.

F2 – Goto error / warning

If IntelliJ has an error or warning (you know, that small status icon in the top right part of the editor), pressing F2 will bring you to the next warning, and helps you keep that icon green!). Thanks Anton Arhipov for suggesting this one!

IntelliJ Keyboard Editing Shortcuts

Besides navigation, we also want to be able to speed up our typing. The following shortcuts will help in that.

Ctrl + W – Expand Selection

My personally most used shortcut. No longer select text with your mouse, but navigate to an element in the code, and press Ctrl + W. It will expand the selection in a smart way by expanding the word, the statement, the block of code, the method, etc. Especially handy when you want to extract a method. Ctrl + Shift + W will reduce the selection.

Ctrl + Space – Basic Code Completion

The must have shortcut, completes your code by pressing this shortcut. However, be mindful the the selection can be appended (with Enter) or replaced (with Tab). The Tab completion saves you from adding unnecessary characters which you then have to manually remove.

Alt + Enter – Show intentions

Fixes your imports, runs your tests, optimizes your imports, etc etc. If your code is broken, Alt + Enter fixes is. If your code is not broken, Alt + Enter makes your code even better.

Ctrl + Shift + Enter – Complete statement

In my experience, a very under-used statement. Missing some closing braces? Missing a semi colon at the end of your line? Press Ctrl + Shift + Enter and IntelliJ will complete the necessary characters, even if your cursor is not at the end of the line.

Ctrl + D – Duplicate line

In my experience, a lot of people are still selecting the line with their mouse, copy it, and then paste it. Ctrl Y is a time saver: just press it and it will duplicate the time. And if you have multiple lines selected, it will copy the whole block.

Ctrl + Y – Remove line

Similar to Ctrl + D, but even better: instead it of duplicating a line, it removes the line.

Ctrl + / – Comment line

No matter where you are in the line, just press Ctrl + /, and the line will be commented out. I personally never use this to comment code, since that’s something I hardly ever do, but I sometimes turn pieces of code on and off. Remember to never commit turned off code though.

IntelliJ Keyboard Refactoring Shortcuts

One of IntelliJ’s biggest strengths is it’s plethora of refactoring opportunities. While the opportunities to refactor your code go far, in practice, more than 90% of the refactoring keyboard shortcuts are the ones I’ve listed below.

Ctrl + Alt + M – Extract method

Select a piece of code (preferably using the earlier listed Ctrl + W), press Ctrl + Alt + M, and you can extract the selected code to a new method or lambda expression.

Shift + F6 – Rename

Be it a method, a variable or a class, pressing Shift + F6 will rename the currently selected element everywhere in your code base. Be careful though, the default settings of IntelliJ are slightly aggressive and also rename text occurrences, which is often not what you want. Pressing Shift F6 twice will bring you to the rename options, and allow you to customize the settings. I’d recommend only refactoring code, and turn the text options off.

Ctrl + Alt + V – Introduce variable

Again, using Ctrl + W, select a piece of code, press Ctrl + Alt + V, and a new variable is created, often with the correct type and a sensible name. This is quite handy when passing an expression to another method or class, and introducing an assignment to a variable often increases readability.

Conclusion

IntelliJ has more than a 100 shortcuts, but there’s no need to know them all. The above shortcuts, based on comparing the most used shortcuts used by my colleagues and me, should give you a headstart in becoming more productive with IntelliJ.

An extra recommendation is to install the Key Promoter X plugin. This plugin will suggest the corresponding shortcut whenever you use a mouse or menu action. A very helpful tool in learning how to effectively use IntelliJ keyboard shortcuts. Have I missed your favorite shortcut? Please let me know in the comments below!

IntelliJ IDEA for Beginners - Learn IntelliJ IDEA from Scratch

IntelliJ IDEA for Beginners - Learn IntelliJ IDEA from Scratch

IntelliJ IDEA for Beginners - Learn IntelliJ IDEA from Scratch. How to become an expert IntelliJ IDEA developer. Learn how to use all the features of Intellij IDEA 2020. Complete IntelliJ IDEA 2020 course for Beginners.

Complete IntelliJ IDEA Course for Beginners

IntelliJ IDEA for Beginners - Learn IntelliJ IDEA from Scratch

How to become an expert IntelliJ IDEA Developer

This course takes is specifically designed for developers that either don't have any previous experience using an Integrated Development Environment (IDE) tool or experienced IDE developers new to Intellij IDEA (e.g. experienced Eclipse developers).

With that said, even if you're an experienced Intellij IDEA developer you might still get something out of the course. This is specially true since this course is (almost exclusively) based on version 2019 which introduced features that you may not yet me familiar with. So please still check it out!

Also, no particular programming language knowledge is assumed since Intellij IDEA is pretty much language agnostic and supports many different programming languages.

Sections I, II and III are mandatory and must be taken in order.

Section IV is specifically designed for experienced Eclipse developers interested in a quick migration path to IntelliJ

The rest of the sections (V, VI, VII and VIII) can be taken in any order as they're self contained. I highly recommend that you still taken them all, particularly if you don't have any previous Intellij IDEA experience.

Java 12 and IntelliJ IDEA

Java 12 and IntelliJ IDEA

Java 12 and IntelliJ IDEA. In this article, we’ll cover the pain points of using existing switch statements, define switch expressions, and explain why they are good for you.

With switch expressions, Java 12 is enhancing one of its basic language constructs – switch – to improve everyday coding experience for developers. Benefits are multi-fold. As compared to the ‘traditional’ switch constructs, switch expressions can return a value. The ability to define multiple constants with a switch branch, and improved code semantics, makes it concise. By removing default fall-through switch branches, you are less likely to introduce a logical error in a switch expression.


Let’s get started.


Traditional switch constructs

If you think of a switch construct as a multi-way condition, using an expression seems to be a better fit. However, switch could only be used as a statement until now. The current switch syntax is constrained and verbose. It often leads to error-prone code that is difficult to debug.

Here’s an example that uses a switch statement to calculate the height of a chair, based on the size value passed to it:

public enum Size {S, M, L, XL};
public class Chair {
    public void calcHeight(Size size) {
        int height = 0; 
        switch (size) {
            case S:
                height = 18;
            case M:
                height = 20;
                break;
            case L:
                height = 25;
                break;
        }
    }
}

The preceding code has multiple issues:

  • Repetitive break and assignment statements add noise to code.
  • Code verbosity makes it difficult to comprehend the code.
  • Default fall-through in switch branches sneaks in a logical error – the missing break statement for case label S lets the control fall through to case label M. This results in assignment of 20 instead of 18 to height when you execute calcHeight(Size.S).
Switch expressions

Let’s rewrite the preceding example using a switch expression. In IntelliJ IDEA, you can use Alt+Enter on the switch keyword to see the suggestions. Select ‘Replace with enhanced ‘switch’ statement’ to convert the traditional switch statement to a switch expression:

The preceding code offers multiple benefits:

  • Code in a switch branch is concise and easy to read. You define what to execute to the right of ->.
  • Switch branches can return a value, which can be used to assign value to a variable.
  • Switch branches don’t need a break statement to mark their end. In absence of a break statement, the control doesn’t fall through the switch labels – which helps avoid logical errors.
Returning value vs. executing statements

When you aren’t using a switch expression to return a value, a switch branch can choose to execute a statement or block of statements, or even throw an exception:

public enum Size {S, M, L, XL};
public class NotReturningValueFromSwitchLabel {
    public void calcHeight(Size size) {
        int height = 0; 
        switch (size) {
            case S -> height = 18;
            case M -> { 
                           height = 20; 
                           System.out.println(height);
                      }
            case L -> height = 25;
        }
    }
}
Handling all possible argument values

When you are using a switch expression to return a value, it should be able to handle all possible values that you could pass to it as an argument. For instance, if you miss a case label corresponding to an enum constant, IntelliJ IDEA detects it. It offers to insert the specific case label or default case label.

By default, IntelliJ IDEA inserts a default value depending on the variable type. You can edit the placeholder value:

Types other than an enum can have infinite values. When you pass types like byte, short, int, or String and miss including the default label, IntelliJ IDEA can detect and fix it:


Define multiple constants in the same case label

Unlike switch statements, switch expressions allow you to define comma-separated multiple constants in a case label. This cuts down code redundancy – you can execute the same code for all case labels.

If you define redundant code for your case labels in a switch expression, IntelliJ IDEA can fix it for you:


Local variables and break statements in switch branches

With switch expressions, you can define local variables in switch branches. The block must include a break statement specifying the value to return:

2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

enum Size {S, M, L, XL};

public class LocalVariablesWithSwitch {
public void assignValue(Size size) {
int height = 0;
height = switch(size) {
case S -> 18;
case M -> {
int weight = 19;
break (weight > 10 ? 15 : 20);
}
case L, XL -> 25;
};
}
}

The case label for value M defines a block statement. A block can also define local variables (weight in this case). The scope and accessibility of the local variable weight is limited to the case label M. Notice how a switch expression uses a break statement to return a value.

Just in case you miss defining a return value for a switch branch, IntelliJ IDEA underlines the keyword case. When you hover the mouse pointer over it, you can view the message about the missing return value:


Preview language feature

Switch expressions is a preview language feature. This essentially means that even though it is complete, it has a possibility of not being confirmed as a permanent feature in a future Java release. This happens for a reason.

Java runs on billions of devices and is used by millions of developers. Risks are high for any mistake in a new Java language feature. Before permanently adding a language feature to Java, the architects of Java evaluate what the developers have to say about it – how good or bad it is. Depending on the feedback, a preview feature might be refined before it’s added to Java SE, or dropped completely. So, if you have any feedback on Switch expressions, please share it here.


IntelliJ IDEA Configuration

Since Switch expressions is a Java 12 language feature, please download and install OpenJDK 12 and configure it to use with IntelliJ IDEA:

Java is evolving and switch expressions is one of the welcome changes in Java 12.

Happy Coding!


Originally published by Mala Gupta at https://blog.jetbrains.com

Main class not found in project IntelliJ IDEA: Java Application

IntelliJ does not find a main class in my Java application project. The project was cloned from a git repository so had no run configuration. I go to Edit Configurations, add a new Application template, go to Main class: and it says "No matches found in project".

IntelliJ does not find a main class in my Java application project. The project was cloned from a git repository so had no run configuration. I go to Edit Configurations, add a new Application template, go to Main class: and it says "No matches found in project".

So, manually searching through the hierarchy I find the .java file that contains the main function but it will not accept it as the main class. I've pasted the file below to prove that it has the correct main function.

public class AdvanceWarsGameHandler implements IGame
{
private Image mImage;
private String mTitle;

public AdvanceWarsGameHandler()
{
    mTitle = "Advance Wars Game";
    mImage = new Image("/OffBrandCerealOopsAllCarries2-01.png");
}

//Game logic unrelated to graphics goes here
@Override
public void update(Game game, float deltaTime) 
{

}

//Update, but for graphics
@Override
public void render(Game game, Renderer renderer) 
{
    renderer.drawImage(mImage, game.getInput().getMouseX(), game.getInput().getMouseY());
}

 public static void main(final String args[])
{
    //Creating and starting an instance of AdvanceWarsGameHandler
    AdvanceWarsGameHandler advancewars = new AdvanceWarsGameHandler();
    Game myGame = new Game(advancewars);
    myGame.start();
}

public String getTitle()
{
    return mTitle;
}

}

So the question is, why is the IntelliJ project not recognizing the main function in this file, or what is IntelliJ looking for as the "Main class" of an application?