Skip to main content

Generate Code with GitHub Copilot-Examples


Example 1: Generate a Simple Java Program

// Write a Java program that prints "Hello, GitHub Copilot!"

 

Example 2: Generate a Java Method

Write a Comment

// Write a Java method to calculate factorial of a number

Example 3: Generate a Java Class with Getters & Setters

Let's create a User class with name, age, and their respective getters and setters

// Create a User class with name and age attributes, and generate getters and setters

 

Example 4: Generate a Java Class with Open Google website and verify the title .

 // Write a Selenium test script to open Google and verify the title

 

Summary

Use Copilot to autocomplete code by typing comments.

Generate functions, classes, and even full programs with minimal effort.

Boost your coding speed and learn Java faster.

 

 

 

Step 3: Generate Code with GitHub Copilot

Example 1: Generate a Simple Java Program

🔹 Start by typing a comment, and let Copilot suggest code

👉 Step 3.1: Write a Comment in Main.java

 

// Write a Java program that prints "Hello, GitHub Copilot!"

👉 Step 3.2: Press Enter & Accept the Suggested Code

 

public class Main {

    public static void main(String[] args) {

        System.out.println("Hello, GitHub Copilot!");

    }

}


🛠 Example 2: Generate a Java Method

Let's generate a method that calculates the factorial of a number.

👉 Step 3.1: Write a Comment

 

// Write a Java method to calculate factorial of a number

👉 Step 3.2: Copilot Suggests the Following Code

 

public class FactorialCalculator {

    public static int factorial(int n) {

        if (n == 0 || n == 1) {

            return 1;

        }

        return n * factorial(n - 1);

    }

 

    public static void main(String[] args) {

        int num = 5;

        System.out.println("Factorial of " + num + " is: " + factorial(num));

    }

}

🔹 Output when you run the program:

 

Factorial of 5 is: 120


🛠 Example 3: Generate a Java Class with Getters & Setters

Let's create a User class with name, age, and their respective getters and setters.

👉 Step 3.1: Write a Comment

 

// Create a User class with name and age attributes, and generate getters and setters

👉 Step 3.2: Copilot Generates Code

java

CopyEdit

public class User {

    private String name;

    private int age;

 

    public User(String name, int age) {

        this.name = name;

        this.age = age;

    }

 

    public String getName() {

        return name;

    }

 

    public void setName(String name) {

        this.name = name;

    }

 

    public int getAge() {

        return age;

    }

 

    public void setAge(int age) {

        this.age = age;

    }

 

    public static void main(String[] args) {

        User user = new User("Alice", 25);

        System.out.println("Name: " + user.getName());

        System.out.println("Age: " + user.getAge());

    }

}

🔹 Output:

 

Name: Alice 

Age: 25 


Java Code Review Checklist

  • Clean Code
    • Naming Conventions (classes, constants, variables, methods (void vs return), etc)
    • No hard-coded variables
    • Indentation
    • No spelling mistakes
    • The code does what it says it does
    • The code is easy to read (Readability)
    • Avoid duplicate code
    • Check if the code could be replaced by calling functions in other libraries/components
  • Best Practices
    • OOP Principles are correctly used
    • The code follows the SOLID PRINCIPLES
    • Design Patterns
      • Recommend a design pattern when you fill that a pattern could fit there
  • Exception Handling
    • Ensure that each exception is raised and handled correctly
    • Ensure that you have a well-defined exception hierarchy
    • Split the exceptions in two types: technical and business

 

 

 

 

 

 

 

package org.example.pages;

public class CodeReviewTestClass {
    public void addnunbers(int a) {

        int c =200;
        int sum = a + c;
        System.out.println("Sum of two numbers is: " + sum);

    }


    public void addoftwonunbers(int a, int b) {
        int sum = a + b;
        System.out.println("Sum of two numbers is: " + sum);
        int c =200;
        int sum1 = a + c;
        System.out.println("Sum of two numbers is: " + sum1);

    }

    public void suboftwonunbers(int a, int b) {
        int sub = a - b;
        System.out.println("Subtraction of two numbers is: " + sub);

        int mul = a * b;
        System.out.println("Multiplication of two numbers is: " + mul);

       int div = a / b;
        System.out.println("Division of two numbers is: " + div);
    }
    public void PrintLargeNumber(int a, int b,int c, int d, int f, int e,int g,int h) {
        System.out.println(" print largest number ");
    }


    public String GetStringMethod(String str){
           String str2 =null;
        System.out.println(" print str value ");

        return str2;


    }
    public void finddupwords(){
        String string = "Big black bug bit a big black dog on his big black nose";
        int count;

        //Converts the string into lowercase
       
string = string.toLowerCase();

        //Split the string into words using built-in function
       
String words[] = string.split(" ");

        System.out.println("Duplicate words in a given string : ");
        for(int i = 0; i < words.length; i++) {
            count = 1;
            for(int j = i+1; j < words.length; j++) {
                if(words[i].equals(words[j])) {
                    count++;
                    //Set words[j] to 0 to avoid printing visited word
                   
words[j] = "0";
                }
            }

            //Displays the duplicate word if count is greater than 1
           
if(count > 1 && words[i] != "0")
                System.out.println(words[i]);
        }
    }
}

}

 

 

 

 

Comments

Popular posts from this blog

Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript)

🎥 Setup Browser, Context, Page & Run Config Test Scripts with package.json & playwright.config.js Step-by-Step: Launch Browser, Context, and Page in Playwright and Run Test and Configuration (JavaScript) 1. Install Playwright You can install Playwright using the following command: npm init playwright@latest 2. Create a Basic Test Script Understand the core Playwright architecture: Element Description browser Controls the browser instance (like Chrome, Firefox, etc.) context Acts like a separate browser profile (cookies, localStorage are isolated) page A single browser tab where interaction happens 3. Run the Test npx playwright test example.spec.js Ways to Run TypeScript Tests Way Command Notes 🟢 Via npx npx playwright test Uses built-in TypeScript support 🟢 With s...

Playwright Test Structure in Details -Session-02

🎥 Playwright: test.only, Hooks & Grouping with test.describe Explained Let’s go step-by-step , showing how to build from a single test , to using beforeEach / afterEach , and then organizing things with test.describe . ✅ Step 1: Basic Single Test with test.only import { test, expect } from '@playwright/test' ; test. only ( '🚀 Basic test - check title' , async ({ page }) => { await page. goto ( 'https://example.com' ); await expect (page). toHaveTitle ( /Example Domain/ ); }); test.only ensures only this test runs — great for debugging. ✅ Step 2: Add beforeEach and afterEach import { test, expect } from '@playwright/test' ; test. beforeEach ( async ({ page }) => { console . log ( '🔄 Setting up before each test' ); await page. goto ( 'https://example.com' ); }); test. afterEach ( async ({ page }, testInfo) => { console . log ( `📦 Finished test: ${testInfo.title} `); }); test. only ( ...

How to Maximize a Browser window using Playwright Java

  Playwright itself does not have a direct maximize () method like some other browser automation tools, but you can achieve the effect by setting the viewport to the screen size of your display. Below are ways to handle Maximize a browser in Playwright Java  Ø   Setting the viewport to the screen size  o    setViewportSize(1920, 1080): This sets the browser window to a full HD resolution, effectively maximizing it. o    setHeadless(false): Ensures the browser runs in a visible mode so you can see the window being maximized.  Code Snapshot  Playwright playwright = Playwright. create ()   ;   Browser browser = playwright.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));     // Create a new browser context   BrowserContext context = browser.newContext(new Browser.NewContextOptions()          .setViewportSize(1920, 1080));     ...