Record Class in Java with Examples

Get Job-ready: Java Course with 45+ Real-time Projects! - Learn Java

Program 1

// class Employee
// {
//     private int empid;
//     private String empname;
//     private int empsalary;

//     public Employee(int empid, String empname, int empsalary) {
//         this.empid = empid;
//         this.empname = empname;
//         this.empsalary = empsalary;
//     }

//     @Override
//     public String toString() 
//     {
//             return "emp id="+this.empid + " name="+ this.empname + " Salary="+this.empsalary;
//     }

//     @Override
//     public int hashCode() {
//         final int prime = 31;
//         int result = 1;
//         result = prime * result + empid;
//         result = prime * result + ((empname == null) ? 0 : empname.hashCode());
//         result = prime * result + empsalary;
//         return result;
//     }

//     @Override
//     public boolean equals(Object obj) {
//         if (this == obj)
//             return true;
//         if (obj == null)
//             return false;
//         if (getClass() != obj.getClass())
//             return false;
//         Employee other = (Employee) obj;
//         if (empid != other.empid)
//             return false;
//         if (empname == null) {
//             if (other.empname != null)
//                 return false;
//         } else if (!empname.equals(other.empname))
//             return false;
//         if (empsalary != other.empsalary)
//             return false;
//         return true;
//     }
  
// }
 record Employee(int empid,String empname,int empsalary)
 {
           public Employee   // Cronical Constructor
           {
                if(empsalary<0)
                   System.out.println("Invalid Salary");
                   if(empid<0)
                   System.out.println("Invalid employee Id");   
           }
           
 } 
    



public class TestRecord1
 {
   public static void main(String[] args)
    {
       Employee E1=new Employee(101,"Vivek", 1000);
      

        System.out.println(E1.empid());
        System.out.println(E1.empname());
        System.out.println(E1.empsalary());
        
               
   }    
}

 

Your 15 seconds will encourage us to work even harder
Please share your happy experience on Google

courses

DataFlair Team

DataFlair Team provides high-impact content on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. We make complex concepts easy to grasp, helping learners of all levels succeed in their tech careers.

Leave a Reply

Your email address will not be published. Required fields are marked *