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 ( ...

Playwright Locators in JavaScript (Complete Guide)

๐ŸŽฏ Playwright Locators in JavaScript (Complete Guide) This guide explains each Playwright locator with: ✅ What it is ๐Ÿ• When to use ⚙️ How to use it ๐ŸŽฏ Benefits ๐Ÿงช Code Examples ๐Ÿ”น 1. Locator by ID ✅ What: Selects an element with a unique id . ๐Ÿ• When: Element has a unique id . ⚙️ How: page.locator('#username') ๐ŸŽฏ Benefit: Fast and reliable. <input id="username" /> await page.locator('#username').fill('John'); ๐Ÿ”น 2. Locator by Class ✅ What: Selects by class . ๐Ÿ• When: Repeated or styled elements. ⚙️ How: page.locator('.password') ๐ŸŽฏ Benefit: Useful for shared styling. <input class="password" /> await page.locator('.password').fill('12345'); ๐Ÿ”น 3. Locator by Text ✅ What: Matches visible element text. ๐Ÿ• When: For buttons, links, etc. ⚙️ How: page.getByText('Login') ๐ŸŽฏ Benefit: Human-readable. <button>Login...