Salesforce Sharing Record Using Apex

For Custom Object:

//Create sharing object for the custom object Student
Student__Share studentShare  = new Student__Share();
studentShare.ParentId = recordId; //Set the ID of record being shared
studentShare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
studentShare.AccessLevel = 'Edit'; //Set the access level
Database.SaveResult sr = Database.Insert(studentShare,false);

For Standard Object:

//Create sharing object for the Standard object Account
AccountShare accshare = new AccountShare();
accshare.AccountId = accountId; //Set the Account ID of record being shared
accshare.UserOrGroupId = userOrGroupId; //Set the ID of User or Group or Territory being granted access
accshare.AccountAccessLevel = 'Edit'; //Set the Account access level
accshare.ContactAccessLevel = 'Edit'; //Set the Contact access level
accshare.OpportunityAccessLevel = 'Edit'; //Set the Opportunity access level
Database.SaveResult sr = Database.Insert(accshare,false);