Java: 3 Easy programs for Class and Objects basics in Java.
Programs:
// 1. Create a class Vehicle.
// a. The class should have two fields:
// i. no_of_seats and no_of_wheels.
// b. Create two objects
// i. Motorcycle and Car for this class.
// c. Your output should show the descriptions for Car and Motorcycle
package A6;
class Vehicle {
// Initialize attributes:
int no_of_seats;
int no_of_wheels;
// Two-argument constructor:
Vehicle(int seats, int wheels) {
no_of_seats = seats;
no_of_wheels = wheels;
}
// Displays values of attributes:
String display() {
return "no_of_seats = "+no_of_seats+", no_of_wheels = "+no_of_wheels+".";
}
public static void main(String args[])
{
// Create two objects: Motorcycle and Car.
Vehicle motorcycle = new Vehicle(1,2);
Vehicle car = new Vehicle(5,4);
// Output descriptions of the two objects:
System.out.println("Object motorycle: "+ motorcycle.display());
System.out.println("Object car: "+ car.display());
}
}
// 2. Create a class with a method. The method has to decide whether a given year is a leap year or not.
// a. Note: A year is considered a leap year if:
// i. It has an extra day i.e. 366 instead of 365.
// ii. It occurs every 4 years e.g. 2008, 2012 are leap years.
// iii. For every 100 years, a special rule applies -
// 1900 is not a leap year but 2000 is a leap year.
// In those cases, we need to check whether it is divisible by 400 or not.
package A6;
class LeapYear {
static String checkifLeapYear(int y)
{
return y % 4 == 0 && y % 100 != 0 || y % 4 == 0 && y % 100 == 0 && y % 400 == 0 ? "leap" : "non-leap";
}
public static void main(String args[])
{
int[] years = {1900,2000,2001,2002,2003,2004,2005,2006,2007,2008,2009,2010};
for (int year: years)
System.out.println("The year "+year+" is a "+checkifLeapYear(year)+" year.");
}
}
// 3. Create a class with a method to calculate the factorial of a number.
package A6;
class Q3 {
static int calculateFactorial(int num){
int factorial = 1;
for (int i = 1; i <= num; ++i)
factorial *= i;
return factorial;
}
public static void main(String args[])
{
int[] numbers = {4,5,10,15};
for (int n : numbers)
System.out.println("Factorial of "+n+" is "+calculateFactorial(n));
}
}