Define a class to accept the gmail id and check for its validity. A gmail id is valid only if it has: @ . (dot) gmail com Example: icse2024@gmail.com is a valid gmail id.
Topic: String validation — gmail id
Answer
import java.util.Scanner;
class GmailId { public static void main(String args[]) { Scanner sc = new Scanner(System.in); System.out.println("Enter a valid gmail id"); String id = sc.next();
if(id.indexOf('@') >= 0 && id.indexOf('.') >= 0 && id.indexOf("gmail") >= 0 && id.endsWith("com")) System.out.println(id + " is a valid gmail id"); else System.out.println(id + " is an invalid gmail id"); } }
Four requirements, all of which must hold, so they are chained with && in a single if.
The tool for "does this string contain X" is indexOf(), which returns the position if found and -1 if not. So the test for presence is indexOf(x) >= 0 (equivalently != -1). Note indexOf() accepts either a single character in single quotes ('@') or a whole string in double quotes ("gmail") — both forms are used here.
For the ending, endsWith("com") is neater than indexOf and is stricter: it insists that com comes last, which is what makes abc123@gmail.net fail while a plain indexOf("com") test might not.
Trace the samples: icse2024@gmail.com has @, a dot, "gmail" and ends in "com", so all four hold and it is valid. abc123@gmail.net has the first three but does not end in "com", so the fourth test fails and it is invalid — both match the paper.
Use sc.next() rather than nextLine() here, since an email id contains no spaces.
id String - the gmail id entered by the user sc Scanner - object used to read input