Ulcers can be prevented by avoiding risk factors such as smoking, excessive alcohol consumption, and long-term use of NSAIDs. Additionally, practicing good hygiene, maintaining a healthy diet rich in fruits, vegetables, and fiber, managing stress effectively, and treating underlying conditions such as H. pylori infection can help prevent ulcers.