Menu
Topics Index
...
`

Data validation using classes - Java Example Program


Data validation using classes
class ClassDataValidation
{
    public static void main(String arg[])
    {
        Student adarsh = new Student("Adarsh");
        adarsh.setSection('B');
        adarsh.setMarks(80);
        adarsh.print("LINE A");    // LINE A
        
        adarsh.setSection('Z'); // LINE B
        adarsh.print("LINE B");
        
        adarsh.setMarks(150); // LINE C
        adarsh.print("LINE C");
        
        adarsh.setDetails(90, 'C'); // LINE D
        adarsh.print("LINE D");    
    }
}

class Student
{
    String name;
    int marks;
    char section;

    Student(String name)
    {
        this.name = name;
    }

    void setMarks(int marks)
    {
        if( marks >= 0 && marks <= 100 )
        {
            this.marks = marks;
        }
    }


    void setSection(char section)
    {
        if( section == 'A' || section == 'B' || section == 'C' || section == 'D')
        {
            this.section = section;
        }
    }

    void setDetails(int marks, char section)
    {
        setMarks(marks);
        setSection(section);
    }

    void print(String prefix)
    {
        System.out.println(prefix + " : " + name + " - " + marks + " - " + section);
    }

}
OUTPUT

LINE A : Adarsh - 80 - B
LINE B : Adarsh - 80 - B
LINE C : Adarsh - 80 - B
LINE D : Adarsh - 90 - C

DESCRIPTION

Here we created three methods - setMarks, setSection and setDetails - in the Student class which will ensure the validity of the marks and section. It will not be possible to set invalid marks or invalid section. Before LINE A, we set the marks and section to 80 and 'B' respectively and the details are printed. At LINE B, section is set to 'Z', since the section is invalid, it is not changed. Similarly at LINE C, the marks are set to 150, but they are not changed because the marks can not be greater than 150. At LINE D, the details are changed to 90 and 'A', since both of them are valid, they are changed to the passed parameter values. Also observe that this keyword is used to differentiate between member variables and parameters.

THINGS TO TRY
  • Add one more section 'E', to the list of valid sections and see if we can change the section to 'E', using the setSection method.
  • Add one more variable percentage of type double to the the Student class. Create a method setPercentage which validates that the percentage is between 0.0 and 100.0, before changing the data. Add one more parameter - double percentage to the setDetails method and call setPercentage internally with that passed parameter.

© meritcampus 2019

All Rights Reserved.

Open In App