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

Understand browser, context, and page in Playwright

๐ŸŽฅ Playwright: Browser, Context & Page - Real-time Demo and Multi-User Testing  . ๐ŸŽฏ Goal: Understand browser , context , and page in Playwright ๐Ÿง  1. What is a browser ? ✅ Definition: A browser in Playwright is a launched instance of a real browser (Chromium, Firefox, WebKit) that can be used for automated testing. ✅ Purpose: It starts and controls the browser process. It is the root of your test execution. Required to create contexts and pages . ✅ Code Example: ts Copy Edit import { chromium } from 'playwright' ; const browser = await chromium. launch ({ headless : false }); ๐Ÿง  2. What is a context (browser context)? ✅ Definition: A context is like a separate browser profile (or incognito tab) inside the browser. Each context is isolated — no cookies, local storage, or sessions are shared. ✅ Purpose: Simulates multiple users or sessions. Enables parallel and isolated testing. Allows setting user-specific prefer...

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));     ...

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