logo codesdope
Level 1
1.
Write a program to print the names of students by creating a Student class. If no name is passed while creating an object of Student class, then the name should be "Unknown", otherwise the name should be equal to the String value passed while creating object of Student class.
Answer
class Student{
  String name;
  public Student(String s){
    name = s;
  }
  public Student(){
    name = "Unknown";
  }
}

class Ans{
  public static void main(String[] args){
    Student s = new Student("xyz");
    Student a = new Student();

    System.out.println(s.name);
    System.out.println(a.name);
  }
}
									

2.
Create a class named 'Rectangle' with two data members- length and breadth and a method to claculate the area which is 'length*breadth'. The class has three constructors which are :
1 - having no parameter - values of both length and breadth are assigned zero.
2 - having two numbers as parameters - the two numbers are assigned as length and breadth respectively.
3 - having one number as parameter - both length and breadth are assigned that number.
Now, create objects of the 'Rectangle' class having none, one and two parameters and print their areas.

3.
Suppose you have a Piggie Bank with an initial amount of $50 and you have to add some more amount to it. Create a class 'AddAmount' with a data member named 'amount' with an initial value of $50. Now make two constructors of this class as follows:
1 - without any parameter - no amount will be added to the Piggie Bank
2 - having a parameter which is the amount that will be added to Piggie Bank
Create object of the 'AddAmount' class and display the final amount in Piggie Bank.

4.
Create a class named 'Programming'. While creating an object of the class, if nothing is passed to it, then the message "I love programming languages" should be printed. If some String is passed to it, then in place of "programming languages" the name of that String variable should be printed.
For example, while creating object if we pass "Java", then "I love Java" should be printed.
Answer
class Programming{
  public Programming(String s){
    System.out.println("I love "+s);
  }
  public Programming(){
    System.out.println("I love programming languages");
  }
}

class Ans{
  public static void main(String[] args){
    Programming s = new Programming("Java");
    Programming a = new Programming();
  }
}
									
Doubt? Ask question
Close

Welcome.please sign up.

Close

Welcome.please login.