Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 28

CS ASSIGMENT

1. Give the output of following code:


class inherit_single

{ protected int a;

inherit_single()

{ System.out.println(“inside Superclass Constructor ”);

a = 10;}

class subclass extends inherit_single

{ subclass()

{ System.out.println(“inside subclass Constructor ”);

a=11; }

void display()

{ System.out.println(a); }

class mainclass

{ public static void main (String args[])

{ subclass obj = new subclass();

obj.display(); }

Ans- inside Superclass Constructor

inside Subclass Constructor

11
2. Write the output of following code:
A) public class test

{ public static void main(String args[])

{ int x[] = { 1, 2, 3, 4};

int y[] = x;

x = new int[2];

for (int i=0; i<x.length; i++)

System.out.println( y[i] + “ “);

} }

Ans-2(a)1

B) class Test

{ public static void main(String args[])


{ int x=-4;
System.out.println (x>>1);
System.out.println (x<<1);
int y=4;
System.out.println (y>>1);
System.out.println (y<<1); }
}
}

Ans-2(b) -2

-8

8
3. What do you mean by platform independence of Java?
Ans-3)The meaning of platform independent is that, the java source code can run on all
operating systems. A program is written in a language which is a human readable language.
It may contain words, phrases etc which the machine does not understand. For the source
code to be understood by the machine, it needs to be in a language understood by
machines, typically a machine-level language. So, here comes the role of a compiler. The
compiler converts the high-level language (human language) into a format understood by
the machines. Therefore, a compiler is a program that translates the source code for
another program from a programming language into executable code.

This executable code may be a sequence of machine instructions that can be executed by
the CPU directly, or it may be an intermediate representation that is interpreted by a
virtual machine. This intermediate representation in Java is the Java Byte Code.

Step by step Execution of Java Program:

* Whenever, a program is written in JAVA, the javac compiles it.

* The result of the JAVA compiler is the .class file or the bytecode and not the machine
native code (unlike C compiler).

* The bytecode generated is a non-executable code and needs an interpreter to execute on a


machine. This interpreter is the JVM and thus the Bytecode is executed by the JVM.

* And finally program runs to give the desired output.

In case of C or C++ (language that are not platform independent), the compiler generates an
.exe file which is OS dependent. When we try to run this .exe file on another OS it does not
run, since it is OS dependent and hence is not compatible with the other OS.

4 .What is JVM and is it platform independent?


Ans-4)A Java virtual machine (JVM) is a virtual machine that enables a computer to run
Javaprograms as well as programs written in other languages and compiled to Java
bytecode.

Java is platform independent but JVM is platform dependent


In Java, the main point here is that the JVM depends on the operating system – so if you are
running Mac OS X you will have a different JVM than if you are running Windows or some
other operating system. This fact can be verified by trying to download the JVM for your
particular machine – when trying to download it, you will given a list of JVM ’s
corresponding to different operating systems, and you will obviously pick whichever JVM is
targeted for the operating system that you are running. So we can conclude that JVM is
platform dependent and it is the reason why Java is able to become “Platform
Independent”.

5. What is constructor overloading? Explain with the help of an


example?
Ans-5) Constructor overloading is a concept of having more than one constructor with
different parameters list, in such a way so that each constructor performs a different task.

Constructor Overloading Example:

Here we are creating two objects of class StudentData. One is with default constructor and
another one using parameterized constructor. Both the constructors have different
initialization code, similarly you can create any number of constructors with different-2
initialization codes for different-2 purposes.

StudentData.java

class StudentData

private int sID;

private String sName;

private int sAge;

StudentData()

sID = 100;

sName = "New Student";

sAge = 18;
}

StudentData(int num1, String str, int num2)

//Parameterized constructor

sID = num1;

sName = str;

sAge = num2;

//Getter and setter methods

public int getSID() {

return sID;

public void setSID(int sID) {

this.sID = sID;

public String getSName() {

return sName;

public void setSName(String sName) {

this.sName = sName;

public int getSAge() {

return sAge;

public void setSAge(int sAge) {


this.sAge = sAge;

public static void main(String args[])

//This object creation would call the default constructor

StudentData myobj = new StudentData();

System.out.println("Student Name is: "+myobj.getStuName());

System.out.println("Student Age is: "+myobj.getStuAge());

System.out.println("Student ID is: "+myobj.getStuID());

/*This object creation would call the parameterized

* constructor StudentData(int, String, int)*/

StudentData myobj2 = new StudentData(555, "Chaitanya", 25);

System.out.println("Student Name is: "+myobj2.getStuName());

System.out.println("Student Age is: "+myobj2.getStuAge());

System.out.println("Student ID is: "+myobj2.getStuID());

OUTPUT:

Student Name is: New Student

Student Age is: 18

Student ID is: 100

Student Name is: Chaitanya

Student Age is: 25

Student ID is: 555


Ques-6) Differentiate between following:
a) Overloading and Overriding
Ans-6a) Overriding and Overloading are two very important concepts in Java. They are
confusing for Java novice programmers. This post illustrates their differences by using two
simple examples.
Overloading occurs when two or more methods in one class have the same method name
but different parameters.

Overriding means having two methods with the same method name and parameters (i.e.,
method signature). One of the methods is in the parent class and the other is in the child
class. Overriding allows a child class to provide a specific implementation of a method that
is already provided its parent class.

Here are some important facts about Overriding and Overloading:

1). The real object type in the run-time, not the reference variable's type, determines which
overridden method is used at runtime. In contrast, reference type determines which
overloaded method will be used at compile time.

2). Polymorphism applies to overriding, not to overloading.

3). Overriding is a run-time concept while overloading is a compile-time concept.

Example of overriding

class Dog{

public void bark(){

System.out.println("woof ");

class Hound extends Dog{

public void sniff(){

System.out.println("sniff ");

}
public void bark(){

System.out.println("bowl");

public class OverridingTest{

public static void main(String [] args){

Dog dog = new Hound();

dog.bark();

In the example above, the dog variable is declared to be a Dog. During compile time, the
compiler checks if the Dog class has the bark() method. As long as the Dog class has the
bark() method, the code compilers. At run-time, a Hound is created and assigned to dog.
The JVM knows that dog is referring to the object of Hound, so it calls the bark() method of
Hound. This is called Dynamic Polymorphism.

Example of Overloading

class Dog{

public void bark(){

System.out.println("woof ");

//overloading method

public void bark(int num){

for(int i=0; i<num; i++)


System.out.println("woof ");

In this overloading example, the two bark method can be invoked by using different
parameters. Compiler know they are different because they have different method
signature (method name and method parameter list).

B) Call by value and Call by reference

Ans-B)

Call by Value:-1) In this actual copy of arguments is passed to formal arguments.

2) Any changes made are not reflected in the actual arguments.

3) It can only be implemented in C, as C does not support call by reference.

4) Actual arguments remain preserved and no chance of modification accidentally.

5) It works locally.

Call By reference:-

1) In this location of actual arguments is passed to formal arguments.

2) Any changes made are reflected in the actual arguments.

3) It can only be implemented in C++ and JAVA.

4) Actual arguments will not be preserved.

5) It works globally.

C) Early binding and Late binding?


Ans-C) 1) The static binding occurs at compile time while dynamic binding happens at
runtime.
2) Since static binding happens at an early stage of program's life cycle, it also is known as
early binding. Similarly, dynamic binding is also known as late binding because it happens
late when a program is actually running.
3) Static binding is used to resolve overloaded methods in Java, while dynamic binding is
used to resolve overridden methods in Java.
4) Similarly, private, static and final methods are resolved by static bonding because they
can't be overridden and all virtual methods are resolved using dynamic binding.
5) The actual object is not used in case of Static binding, instead, the type information i.e.
the type of reference variable is used to locate the method. On the other hand, dynamic
binding uses an actual object to find the right method in Java.

D) JDK , JVM and JRE?


Ans-D) JDK – Java Development Kit (in short JDK) is Kit which provides the environment to
develop and execute(run) the Java program. JDK is a kit(or package) which includes two
things
->Development Tools(to provide an environment to develop your java programs)
->JRE (to execute your java program).
JRE – Java Runtime Environment (to say JRE) is an installation package which provides
environment to only run(not develop) the java program(or application)onto your machine.
JRE is only used by them who only wants to run the Java Programs i.e. end users of your
system.
JVM – Java Virtual machine(JVM) is a very important part of both JDK and JRE because it is
contained or inbuilt in both. Whatever Java program you run using JRE or JDK goes into
JVM and JVM is responsible for executing the java program line by line hence it is also
known as interpreter.

7. Can we overload main method?


Ans-7) The short answer to, can we overload the main method in Java is Yes, you can
overloading, nothing stops from overloading, but JVM will always call the original main
method, it will never call your overloaded main method
Example -
class Simple{
public static void main(int a){
System.out.println(a);
}

public static void main(String args[]){


System.out.println("main() method invoked");
main(10);
}
}
Output - main() method invoked
10

8. What is an interface? How is it different from abstract class? Can


we create an instance of interface? Is it possible to declare variables
in that? Give suitable examples.
Ans-8 )An interface in java is a blueprint of a class. It has static constants and abstract
methods.
The interface in Java is a mechanism to achieve abstraction. There can be only abstract
methods in the Java interface, not method body. It is used to achieve abstraction and
multiple inheritance in Java.
Abstract class vs Interface:
Type of methods: Interface can have only abstract methods. Abstract class can have
abstract and non-abstract methods. From Java 8, it can have default and static methods
also.
Final Variables: Variables declared in a Java interface are by default final. An abstract class
may contain non-final variables.
Type of variables: Abstract class can have final, non-final, static and non-static variables.
Interface has only static and final variables.
Implementation: Abstract class can provide the implementation of interface. Interface can ’t
provide the implementation of abstract class.
Inheritance vs Abstraction: A Java interface can be implemented using keyword
“implements” and abstract class can be extended using keyword “extends ”.
Multiple implementation: An interface can extend another Java interface only, an abstract
class can extend another Java class and implement multiple Java interfaces.
In other words, you can say that interfaces can have abstract methods and variables. It
cannot have a method body.
interface contains only abstract methods and as abstract methods do not have a body (of
implementation code), we cannot create an object.

Variables in Interfaces:

You can use interfaces to import shared constants into multiple classes by simply declaring

an interface that contains variables that are initialized to the desired values. When you

include that interface in a class (that is, when you “implement ” the interface), all of those

variable names will be in scope as constants.

Exapmle

interface A

int x=10;

interface B

int x=100;

class Hello implements A,B

public static void Main(String args[])


{

System.out.println(A.x);

System.out.println(B.x);

9. Write a program to acceot 10 integers in an array and print the


same using for...each syntax.
Ans) import java.util.Scanner;
class test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int x[];
x=new int[10];
System.out.println("Enter 10 array elements");
for(int i=0;i<10;i++)
{
x[i]=sc.nextInt();
}
System.out.println("10 array elements are:-");
for(int num : x)
{
System.out.println(num);
}

}
}

Output -
Enter 10 array elements
1
2
3
4
5
6
7
8
9
0
1
2
3
4
5
6
7
8
9
0

Ques10) Write a method in java to swap two numbers. Make use of it in the
main method to read the values of two int variables a,b, invoke the method
swap and display the modified values of the variables a,b.

Ans) import java.util.Scanner;


class Method
{
void swap(int x, int y)
{
System.out.println("Inside swap function");
System.out.println("Values before swapping : First no. - "+x+" ,Second
no.-"+y);
x=x+y;
y=x-y;
x=x-y;
System.out.println("Values after swapping : First no. - "+x+" ,Second no.-"+y);
}
}

class test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int a,b;
Method ob=new Method();
System.out.println("Enter first number");
a=sc.nextInt();
System.out.println("Enter second number");
b=sc.nextInt();
System.out.println("Value of 1st and 2nd number before calling swap "+a+" &
"+b);
ob.swap(a,b);
System.out.println("Value of 1st and 2nd number after exiting swap (in main
function)"+a+"&"+b);

}
}
Output -
Enter first number
2
Enter second number
3
Value of 1st and 2nd number before calling swap 2 & 3
Inside swap function
Values before swapping : First no. - 2 ,Second no.-3
Values after swapping : First no. - 3 ,Second no.-2
Value of 1st and 2nd number after exiting swap (in main function) 2 & 3

11. Explain the prototype of main function a java program.


Ans) PUBLIC KEYWORD: It is an access modifer whichn allow the programs to control the
visibility of the member class.When memnber class is preceeded by public than that
member may be excessed by code outside in which it is declared.

STATIC KEYWORD: It allows main function to be called without having any instance of that
class.It is a function which we want to refer without object.

VOID KEYWORD: Simply tells the complier that main function cannot retrurn anything.

12. Write a Java code to calculate the factorial of a number when number is
accepted from the command line.
Ans) class test
{
public static void main(String args[])
{
int i,fact=1;
for (i=1;i<=Integer.parseInt(args[0]);i++)
fact=fact*i;
System.out.println("Factorial of "+Integer.parseInt(args[0])+" is "+fact);
}
}
Output -
C:\Users\class-I.PC83-05\Downloads\Vatsal\assignment>java test 4
Factorial of 4 is 24

13.What is Java Package and which package is imported by default?


Ans.The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no
name. (This is why you haven’t had to worry about packages before now.) While the default
package is fine for short, sample programs, it is inadequate for real applications. Most of
the time, you will define a package for your code.

14.What are access modifiers? Explain their utility.


Ans.Access modifiers are keywords used to specify the accessibility of a class (or type) and
its members. These modifiers can be used from code inside or outside the current
application. The purpose of using access modifiers is to implement encapsulation, which
separates the interface of a type from its implementation. With this, the following benefits
can be derived:

1.Prevention of access to the internal data set by users to invalid state.

2.Provision for changes to internal implementation of the types without affecting the
components using it.

3.Reduction in complexity of the system by reducing the interdependencies between


software components.

15.What is the purpose of final keyword in terms of a variable, method and


class ?
Ans-Final variable: When a variable is declared with final keyword, its value can ’t be
modified, essentially, a constant. This also means that you must initialize a final variable. If
the final variable is a reference, this means that the variable cannot be re-bound to
reference another object, but internal state of the object pointed by that reference variable
can be changed i.e. you can add or remove elements from final array or final collection.
Final class: When a class is declared with final keyword, it is called a final class. A final class
cannot be extended(inherited). There are two uses of a final class :One is definitely to
prevent inheritance, as final classes cannot be extended. The other use of final with classes
is to create an immutable class like the predefined String class.You can not make a class
immutable without making it final.

Final method: When a method is declared with final keyword, it is called a final method. A
final method cannot be overridden. The Object class does this —a number of its methods
are final.We must declare methods with final keyword for which we required to follow the
same implementation throughout all the derived classes.

16. What is static keyword? Explain its usage.


Ans-16 Static is a non-access modifier in Java which is applicable for the following:

blocks

variables

methods

nested classes

To create a static member(block,variable,method,nested class), precede its declaration


with the keyword static. When a member is declared static, it can be accessed before any
objects of its class are created, and without reference to any object.

Static variable use-

Static variable is used for fulfill the common requirement. For Example company name of
employees,college name of students etc. Name of the college is common for all students.

The static variable allocate memory only once in class area at the time of class loading.

Static method use-

They can only directly call other static methods.

They can only directly access static data.

They cannot refer to this or super in any way.


17. Write a java program to perform the arithmetic operations using the
concept of method overloading, define a method add that accepts as input to
int values and return their sum as int. Overload this method by a method that
accepts two float values and return a float.?
Ans) import java.util.Scanner;
class Add
{
int sum(int x, int y)
{
return x+y;
}
float sum(float x,float y)
{
return x+y;
}
}
class test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
Add ob=new Add();
float y,x;
System.out.println("Enter 1st integer number");
int a=sc.nextInt();
System.out.println("Enter 2nd integer number");
int b=sc.nextInt();
System.out.println("Enter 1st floating number");
x=sc.nextFloat();
System.out.println("Enter 2nd floating number");
y=sc.nextFloat();
System.out.println("Integer sum of "+a+" and "+b+" is "+ob.sum(a,b));
System.out.println("Floating sum of "+x+" and "+y+" is "+ob.sum(x,y));
}
}
Output-
Enter 1st integer number
5
Enter 2nd integer number
6
Enter 1st floating number
1.2
Enter 2nd floating number
3.4
Integer sum of 5 and 6 is 11
Floating sum of 1.2 and 3.4 is 4.6000004

18. Can we declare a class as static? Explain.


Ans-18 The answer is YES, we can have static class in java. In java, we have static instance
variables as well as static methods and also static block. Classes can also be made static in
Java.
Java allows us to define a class within another class. Such a class is called a nested class.
The class which enclosed nested class is known as Outer class. In java, we can ’t make Top
level class static. Only nested classes can be static.

19. Can an interface implement or extend another interface?


Ans-19 An interface can extend another interface in the same way that a class can extend
another class. The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
Example.
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from
Sports.

20. What does super keyword do? Explain its two usages with help of an
example?
Ans-20 The super keyword in java is a reference variable that is used to refer parent class
objects. The keyword “super” came into the picture with the concept of Inheritance.Uses-
1)Use of super with methods: This is used when we want to call parent class method. So
whenever a parent and child class have same named methods then to resolve ambiguity we
use super keyword. This code snippet helps to understand the said usage of super
keyword.example
class Person
{
void message()
{
System.out.println("This is person class");
}
}
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display(); }
}
In the above example, we have seen that if we only call method message() then, the current
class message() is invoked but with the use of super keyword, message() of superclass
could also be invoked.
2)Use of super with constructors: super keyword can also be used to access the parent
class constructor. One more important thing is that, ‘’super ’ can call both parametric as well
as non parametric constructors depending upon the situation. Example -
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{ // invoke or call parent class constructor
super();
System.out.println("Student class Constructor"); }
}
/* Driver program to test*/
class Test {
public static void main(String[] args)
{
Student s = new Student(); }
}
Output - Person class Constructor
Student class Constructor
In the above example we have called the superclass constructor using keyword ‘super ’ via
subclass constructor.

21. What is break and continue statement?


Ans-21 Break: In Java, break is majorly used for:
Terminate a sequence in a switch statement (discussed above).
To exit a loop.
Used as a “civilized” form of goto.
Continue: Sometimes it is useful to force an early iteration of a loop. That is, you might
want to continue running the loop but stop processing the remainder of the code in its
body for this particular iteration. This is, in effect, a goto just past the body of the loop, to
the loop’s end. The continue statement performs such an action.
22. What do you understand by this keyword? Explain with the help of an
example.?
Ans-22 'this’ is a reference variable that refers to the current object.
Using ‘this’ keyword to refer current class instance variables-
class Test
{
int a;
int b; // Parameterized constructor
Test(int a, int b) {
this.a = a;
this.b = b; }
void display()
{
//Displaying value of variables a and b
System.out.println("a = " + a + " b = " + b);
}
public static void main(String[] args) {
Test object = new Test(10, 20);
object.display(); }
}
Output
a=10 b=20

23. What is default constructor?


Ans-23) A constructor is called "Default Constructor" when it doesn't have any
parameter.The default constructor is used to provide the default values to the object like 0,
null, etc., depending on the type.
Example: class NoteBook{
/*This is default constructor. A constructor does
* not have a return type and it's name
* should exactly match with class name
*/
NoteBook(){
System.out.println("Default constructor");
}
public void mymethod()
{
System.out.println("Void method of the class");
}
public static void main(String args[]){
/* new keyword creates the object of the class
* and invokes constructor to initialize object
*/
NoteBook obj = new NoteBook();
obj.mymethod();
}
}
Output - Default constructor
Void method of the class
When we create an obj of notebook then noteboo() which is the default constructor
automatically called.

24. What is Garbage Collection?


Ans-24 In C/C++, programmer is responsible for both creation and destruction of objects.
Usually programmer neglects destruction of useless objects. Due to this negligence, at
certain point, for creation of new objects, sufficient memory may not be available and
entire program will terminate abnormally causing OutOfMemoryErrors.
But in Java, the programmer need not to care for all those objects which are no longer in
use. Garbage collector destroys these objects.
Main objective of Garbage Collector is to free heap memory by destroying unreachable
objects.

25. Define a class Person having name as a data member. Inherit two more
classes Student and Employee from class Person. To class Student, add data
members course, marks and year, and to class employee add data members
department and salary. Write display method in all three classes to display the
relevant details of the corresponding class. Provide the necessary method to
provide dynamic method dispatch?
Ans-25 import java.util.Scanner;

class Person
{
String name;
Person(String name)
{
this.name=name;
}

void display()
{
System.out.println("Inside Person class");
System.out.println("Name entered is "+name);
}
}

class Student extends Person


{
String course;
float marks;
int year;
Student(String name,String c,float m, int y)
{
super(name);
course=c;
marks=m;
year=y;
}

void display()
{
System.out.println("Inside Student class");
System.out.println("Name of student is "+name);
System.out.println("Course - "+course);
System.out.println("Year - "+year);
System.out.println("Aggregate Marks - "+marks);
}
}

class Employee extends Person


{
String department;
int salary;
Employee(String name, String d, int s)
{
super(name);
department=d;
salary=s;
}
void display()
{
System.out.println("Inside Employee class");
System.out.println("Name of employee is "+name);
System.out.println("Department - "+department);
System.out.println("Salary - "+salary);
}
}

class test
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);

System.out.println("Enter name of person");


String n=sc.next();
Person p=new Person(n);

System.out.println("Enter course of student");


String c=sc.next();
System.out.println("Enter year of student");
int y=sc.nextInt();
System.out.println("Enter marks of student");
float m=sc.nextFloat();
Student s=new Student(n,c,m,y);

System.out.println("Enter employee's department");


String dept=sc.next();
System.out.println("Enter Salary");
int sal=sc.nextInt();
Employee e=new Employee(n,dept,sal);

Person ref;
ref=p;
ref.display();

ref=s;
ref.display();

ref=e;
ref.display();
}
}
Output -
Enter name of person
vatsal
Enter course of student
Bsc
Enter year of student
3
Enter marks of student
7.8
Enter employee's department
Management
Enter Salary
500000000
Inside Person class
Name entered is vatsal
Inside Student class
Name of student is vatsal
Course - Bsc
Year - 3
Aggregate Marks - 7.8
Inside Employee class
Name of employee is vatsal
Department - Management
Salary - 500000000

You might also like