Get Screen Size in Java

Tags: awt Toolkit awt Dimension screen size

This Java tutorial we learn how to get the size of the screen and return width and height values in pixels.

How to get screen size using Toolkit class

To get the screen resolution we can use Toolkit class’s method Toolkit.getDefaultToolkit().getScreenSize() which return an object of java.awt.Dimension class.

  • To get screen width we can use Dimension.getHeight() method
  • To get screen height we can use Dimension.getWidth() method

GetScreenSizeExample1.java

import java.awt.Dimension;
import java.awt.Toolkit;

public class GetScreenSizeExample1 {

    public static void main(String... args) {
        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

        double screenHeight = dimension.getHeight();
        double screenWidth = dimension.getWidth();

        System.out.println("Height: " + screenHeight);
        System.out.println("Width: " + screenWidth);
    }

}
The output as below.
Height: 1080.0
Width: 2560.0

How to get screen width and height as integer values

The java.awt.Dimension class also support public variable to get screen width and height as integer values as Java example below.

GetScreenSizeExample2.java

import java.awt.Dimension;
import java.awt.Toolkit;

public class GetScreenSizeExample2 {
    public static void main(String... args) {

        Dimension dimension = Toolkit.getDefaultToolkit().getScreenSize();

        int screenHeight = dimension.height;
        int screenWidth = dimension.width;

        System.out.println("Height: " + screenHeight);
        System.out.println("Width: " + screenWidth);
        
    }
}
The output as below.
Height: 1080
Width: 2560

Happy Coding 😊