Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
4 views

Java Program

Some basic questions and answers of Java program
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Program

Some basic questions and answers of Java program
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

JAVA ASSIGNMENT 2

Caution:Writing these answers are subjected to your risk

What are constructors? Explain Default constructors and Parameterized constructors?


 It is a special method which invoked automatically when the object is created and it is used to initialize the variables of
the objects.
 Java allows objects to initialize themselves when they are created. This automatic initialization is performed through the
use of a constructor.
 A constructor initializes an object immediately upon creation.
 They have no return type, not even void. This is because the implicit return type of a class’ constructor is the class type
itself.
 Constructor name should be same as class name.
 Once defined, the constructor is automatically called immediately after the object is created, before the new operator
completes.

Default / no argument constructor

The constructor which doesn’t consist any parameters are called as default constructor

By default every class has a default constructor.

class Box

Box()

System.out.println(“this is Default constructor”);

class Main

public static void main(String[] args)

Box ob=new Box();

}}

Parameterized Constructor

The constructor which consist of arguments in their parameter list is known as parameterized constructor.

Ex. For parameterized constructor

class Box
{
Box(int x)
{
System.out.println("the value of x is " + x);
}
}
9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

class Main
{
public static void main(String[] args)
{
Box ob;
ob=new Box(10);
}}

Define a class? Explain how to Declare and initialize of objects in JAVA?


 a class is a template for an object, and an object is an instance of a class. or
 Class=It is a group of objects with similar characteristics and behavior or
 a class is a logical construct. An object has physical reality.

Declaration and initialization:

Creating an objet is known as instansitiating of an object ,

 Declaration − A variable declaration with a variable name with an object type.(here it just creates a
reference of class type to an object)
 Instantiation − The 'new' keyword is used to create the object.
(The new operator instantiates a class by allocating memory for a new object and returning a
reference to that memory is known as instantiation.)
<"instantiating a class" means the same thing as "creating an object." When you create an object, you are
creating an "instance" of a class, therefore "instantiating" a class >

 Initialization − The 'new' keyword is followed by a call to a constructor. This call initializes the new
object.

General syntax:
class_name object_name = new constructor_name(); //initialization at the time of declaration

or

class_name object_name ; //Declaration.


object_name= new constructor_name(); //initialization

Snippet for object decl and initialization:


//Consider class name as Box
Box ob =new Box();

9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

 The new operator dynamically allocates (that is, allocates at run time) memory for an object and returns
a reference to it.
 Here in the java programming the memory is allocated dynamically.
3 Write a JAVA program describing Method overloading. Explain use of this in JAVA.

class Addition
{
void add(int x, int y)
{
return(x+y);
}

void add(int x, int y ,int z)

return(x+y+z);

class Main

public static void main(String[] args)

Addition ob=new Addition();

System.out.println(“Addition of two variables” + ob.add(10,20));

System.out.println(“Addition of three variables” + ob.add(10,20,30));

Use of this

 The this keyword refers to the current object in a method or constructor.

 The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter).

 This is used to invoke current class method explicitly.

 This is used to overcome the instance variable hiding.


9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

 This is used to invoke the current class constructor [this();]

Explain different types of inheritance in JAVA. Why do we need to use inheritance?

Inheritance :

Creating a new class from an already exixting class.

1. Single level inheritance:

 Only one class is derived from the parent class.

 In this type of inheritance, the properties are derived from a single parent class and not more than that.

2. Multi-level Inheritance:
 One class inherits the features from a parent class and the newly created sub-class becomes
the base class for another new class. Or the class is derived from the already derived class
from the bas class.
3. Hierarchical Inheritance:
 The type of inheritance where many subclasses inherit from one single class is known as
Hierarchical Inheritance.
 multiple classes are being derived from one superclass. These newly derived classes inherit
the features, methods, etc, from this one superclass.

4. Multiple Inheritance :

 the newly derived class can have more than one superclass.

 In java, multiple inheritances can be achieved through interfaces.

9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

(Write the structures as above*)

9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

5. Create a JAVA class called Student with the following details as variables within it.
USN
NAME
BRANCH
PHONE
PERCENTAGE
Write a JAVA program to create n Student objects and print the USN, Name, Branch, Phone, and
percentage of these objects with suitable headings.
importjava.util.Scanner;
importjava.util.List;
importjava.util.ArrayList;

class StudentType{
private StringUSN,NAME,BRANCH,PHONE,PERCENTAGE;

public StudentType(StringUSN,StringNAME,StringBRANCH,StringPHONE,doublePERCENTAGE){
this.USN=USN;
this.NAME=NAME;
this.BRANCH=BRANCH;
this.PHONE=PHONE;
this.PERCENTAGE=PERCENTAGE;
}

publicString getUSN(){
returnUSN;

Public String getNAME(){


returnNAME;
}

Public String getBRANCH(){


returnBRANCH;
}

Public String getPHONE(){

9
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

Return PHONE;
}

publicdoublegetPERCENTAGE(){
returnPERCENTAGE;
}

public classStudent Demo{


public static void main(String[]args){
Scannersc=newScanner(System.in);
List<StudentType>students=newArrayList<>();

System.out.println("Enterthenumberofstudents:");
intn=sc.nextInt();
for(inti=1;i<=n;i++){
System.out.println("Enterthedetailsofstudent"+i+":");
System.out.print("USN:");
String USN=sc.next();
System.out.print("NAME:");
String NAME=sc.next();
System.out.print("BRANCH:");
String BRANCH=sc.next();
System.out.print("PHONE:");
String PHONE=sc.next();
System.out.print("PERCENTAGE:");
double PERCENTAGE=sc.nextDouble();

students.add(newStudentType(USN,NAME,BRANCH,PHONE,PERCENTAGE));
}

System.out.println("\nSTUDENTDETAILS\n=====================");
System.out.println("USN"+"\t\t"+"NAME"+"\t"+"BRANCH"+"\t"+"PHONE"+"\t\t"+"PERCENTAGE");
for(StudentTypestudent:students){
System.out.println(student.getUSN() + "\t" + student.getNAME() + "\t"
+student.getBRANCH()+"\t"+student.getPHONE()+"\t"+student.getPERCENTAGE());
}

14
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

6 Write a JAVA program demonstrating Method overloading and Constructor overloading.


class Addition
{
Addition(int x,int y )
{
System.out.println(“Multiplication of two numbers is”+x*y)
}
Addition(int x,int y,int z)
{
System.out.println(“Multiplication of three numbers is”+x*y*z)
}

void add(int x, int y)


{
return(x+y);
}

void add(int x, int y ,int z)

return(x+y+z);

class Main

public static void main(String[] args)

Addition ob;

ob=new Addition(10,20);

ob=new Addition(10,20,30);

System.out.println(“Addition of two variables” + ob.add(10,20));

System.out.println(“Addition of three variables” + ob.add(10,20,30));

14
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

7 Design a super class called Staff with details as Staff Id, Name, Phone, Salary. Extend this class by
writing three subclasses namely teaching (domain, publications). Write a JAVA program to read and
display at least 3 staff objects.

1 classStaff{
2 privateintstaffId;
3 privateStringname;
4 privateStringphone;
5 privatedoublesalary;
6

7 publicStaff(intstaffId,Stringname,Stringphone,doublesalary){
8 this.staffId=staffId;
9 this.name=name;
10 this.phone=phone;
11 this.salary=salary;
12 }
13

14 publicintgetStaffId(){
15 returnstaffId;
16 }
17

18 publicStringgetName(){
19 returnname;
20 }
21

22 publicStringgetPhone(){
23 returnphone;
24 }
25

26 publicdoublegetSalary(){
27 returnsalary;
28 }
29

30 publicvoidDisplayInfo(){
31 System.out.println("Name:"+this.getName());
32 System.out.println("StaffID:"+this.getStaffId());
33 System.out.println("Phone:"+this.getPhone());
34 System.out.println("Salary:"+this.getSalary());
35 }
36 }
37

14
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

39

38

40 classTeachingextendsStaff{
privateintpublications;
41

42 publicTeaching(intstaffId,Stringname,Stringphone,doublesalary,domain, String
intpublications){
43 super(staffId,name,phone,salary);
44 this.domain=domain;
45 this.publications=publications;
46 }
47

48 publicStringgetDomain(){
49 returndomain;
50 }
51

52 publicintgetPublications(){
53 returnpublications;
54 }
55

56 publicvoidDisplayInfo(){
57 super.DisplayInfo();
58 System.out.println("Domain:"+this.getDomain());
59 System.out.println("Publications:"+this.getPublications());
60 }
61 }
62

63 classTechnicalextendsStaff{
64 privateStringskills;
65

66 publicTechnical(intstaffId,Stringname,Stringphone,doublesalary,Stringskills){
67 super(staffId,name,phone,salary);
68 this.skills=skills;
69 }
70

71 publicStringgetSkills(){
72 returnskills;
73 }

74 publicvoidDisplayInfo(){
75 super.DisplayInfo();
76 System.out.println("Skills:"+this.getSkills());
77 }

78 }
79

80 classContractextendsStaff{
81 privateintperiod;
82

15
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

83 publicContract(intstaffId,Stringname,Stringphone,doublesalary,intperiod){
84 super(staffId,name,phone,salary);
85 this.period=period;
86 }
87

88 publicintgetPeriod(){
89 returnperiod;
90 }

91 publicvoidDisplayInfo(){
92 super.DisplayInfo();
93 System.out.println("Period:"+this.getPeriod()+"months");
94 }

9 publicclassStaffTypeDemo{

100 publicstaticvoidmain(String[]args){
101
Teachingt1=newTeaching(1,"RajeshNayak","9822546534",75000,"ComputerScience"
,15);
102 Teachingt2=newTeaching(2,"SitaDevi","8787432499",80000,"Mathematics",20);
103 Teachingt3=newTeaching(3,"JohnPeter","8528734373",85000,"Physics",25);
104 Technicalte1=newTechnical(4,"Ramesha","9473673642",90000,"Java,Python,C
++");
105
Technicalte2=newTechnical(5,"Suresha","8917612332",95000,"JavaScript,Rea
ct,Node.js");
106
Technicalte3=newTechnical(6,"Dinesha","9944222323",100000,"Python,Ten
sorFlow,Keras");
107 Contractc1=newContract(7,"AbidaBegum","9323786211",75000,6);
108 Contractc2=newContract(8,"LilyThomas","8776551219",80000,12);
109 Contractc3=newContract(9,"SeemaJain","9922324343",85000,18);
110 //displaythestaffobjects
111 System.out.println("TeachingStaff1:");
112 t1.DisplayInfo();
113 System.out.println("\nTeachingStaff2:");
114 t2.DisplayInfo();
115 System.out.println("\nTeachingStaff3:");
116 t3.DisplayInfo();
117

118 System.out.println("\nTechnicalStaff1:");
119 te1.DisplayInfo();
120

121 System.out.println("\nTechnicalStaff2:");
122 te2.DisplayInfo();
123

124 System.out.println("\nTechnicalStaff3:");
125 te3.DisplayInfo();
126

127 System.out.println("\nContractStaff1:");
128 c1.DisplayInfo();
129

130 System.out.println("\nContractStaff2:");
131 c2.DisplayInfo();
132

16
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

133 System.out.println("\nContractStaff3:");
134 c3.DisplayInfo();
135 }

136 }

17
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

8. Develop a program to show the use super keyword.

18
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

Write System.out.println in the place of S.O.P

Or

class Name { // Superclass (parent)

void name() {

System.out.println("Name is Murali ");

class Full_Name extends Name {

void name() //here the methd is overrided.

super.name();//her it calls the method of the base class if the super was not used here then Name is Murali would not be displayed

System.out.println("Full name is Murali Manohar MGA");

19
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

class Main {

public static void main(String[] args) {

Full_Name ob = new Full_Name();

ob.name(); }

20
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

9 Explain switch selection statement with program?


import java.util.*;

class Name

public static void main(String[] args)

Scanner sc=new Scanner(System.in);

System.out.printf("Select your choice \n 1- Sannidhi \n 2- Soundarya \n 3-Amrutha \n 4-


Mr.Hirematt \n 5-Darshan \n");

int x=sc.nextInt();

switch(x)

case 1 : System.out.print("Sannidhi");

break;

case 2 : System.out.print("Soundaryaa");

break;

case 3 : System.out.print("Amrutha ");

break;

21
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

case 4: System.out.print("Mr.Hirematt");

break;

case 5: System.out.print("Darshan");

break;

default:System.out.print(“you have entered a wrong number”);

break;

}}

 Switch is a multiway branching statement.


 Switch is a selective statement
 It is an alternative for if else if statement
 The expression in the switch must be of type of byte,short,int or char.
 As soon as the control starts executing the expressions it checks for the input if it matches
with the case value then it executes the corresponding case or else it will execute the
default statement,if there is no default statement then there will be no further action will
be taken
 Default statement is optional.
 <switch looks only for a match between the value of the expression and one of
its case constants.
 Switch can be nested
10. Explain the following control statements?
i) Break
ii) Continue
Break:
 It is a jumping statement
 It is a used to terminate the statement, terminate the loop(cancel the loop)
 When the break is encountered inside any loop,control automatically passes to the first
statement after the loop.
 Break is also used in if and switch statements.
 It is also used as a form of goto.
Short snippet for ref.
for(int i=0;i<50;i++)
{

22
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

if (i==10)
break;
System.out.print("i=" +i);
}
System.out.print("Loop is completed") ;

Continue
 It is also a jumping statement
 There are some programming situations where we need to bypass the statements then
continue statement passes the control directly to the conditional expression of the loop
 It can be used in while,do while for loop and even with if statements
Short snippet for ref.
for (int i = 0; i < 10; i++) {
if (i % 2==0) {
System.out.println(i);
continue;

}
System.out.println(i);
}
}
Output: 0

23
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

Or

for (int i = 0; i < 10; i++) {

if (i == 4) {

continue;

System.out.println(i);

Output:

0
1
2

24
JAVA ASSIGNMENT 2
Caution:Writing these answers are subjected to your risk

3
5
6
7
8
9

25

You might also like