As far as I know, you cannot write to custom labels through Apex. However, it sounds like what you are actually looking for is a custom text field, in which case it's fairly easy to do what you are asking. Pretend I've added a field called Vehicles__c
to the object, with a default value of blank:
public void addVehicle(string vehicle)
{
myObject.Vehicles__c = String.isBlank(myObject.Vehicles__c) ? vehicle : myObject.Vehicles__c + ', ' + vehicle;
}
public boolean containsVehicle(string vehicle)
{
return myObject.Vehicles__c.contains(vehicle);
}
public void test()
{
addVehicle('car');
addVehicle('truck');
if (containsVehicle('bike'))
{
//do stuff
}
else
{
//do other stuff
}
}
Based on your comment, the answer is that you can retrieve custom labels in Apex using System.Label.Label_Name
(https://help.salesforce.com/apex/HTViewHelpDoc?id=cl_about.htm&language=en). In your case though, my guess is that you'll actually want a custom setting, since you can just add or remove settings and treat them like a list.
As a label, you would need to modify the label string whenever you wanted to add or remove a value:
public void test()
{
List<String> myVehicles = System.Label.MyLabel__c.Split(', ');
for (String i : myVehicles)
{
if (i == 'bike')
//do something
}
}
On the other hand, a custom setting naturally is a collection of records, which easily translates into a list. On top of that, you can add whatever other information you want to each record. For example:
public void test()
{
for (Vehicle__c vehicle : Vehicle__c.getAll())
{
if (vehicle.Name == 'bike')
{
System.debug(vehicle.MPH__c);
}
}
}
Alternatively, if what you are asking is whether you can write code as the value of some field and execute it, there are a few solutions. Doing this with Javascript on a Visualforce page should be pretty simple, just use:
<script>
eval('{!myObject.javascript_field__c}');
</script>
On the other hand, executing a string as Apex code is a bit more involved, you can look at this answer for an explanation of how to do it through the Tooling API.
If this is what you are planning on doing, be very careful if users are allowed to modify the code evaluated in any way.