Debarghya Sir Java
Debarghya Sir Java
Group-B
between
1. Explain method overloading and method overriding ?or What is difference
function overloading and function overriding ? Explain with example.
Ans : 1 Part : Method Overloading:Method Overloading is a Compile time polymorphism. In different
method overloading, more than one method shares the same method name with
signature in the class. In method overloading, return type can or can not be be same, but we must
method overloadingg by
have to change the parameter because in java, we can not achieve the
changing only the return type of the method.
Example :
class MethodOverloadingEx {
static int add(int a, int b) {return a+b;}.
static int add (int a, int b, int c) {return atbtci}
Output:
//Here, add witn two parameter method runs
10
parent and
20 Part: Method Overriding : Inheritance in java involves a relationship between arguments or
child classes. Whenever both the classes contain methods with the same náme and
during execution.
parameters it is certain that one of the methods will override the other method
The method that will be executed depends on theIf object.
the child class object calls the method, the
class object
child class method will override the parent class method. Otherwise, if the parent
calls the method, the parent class method will be executed.
Example:
class Animal{
void eat () {System. out.println ("eating. ") ;}
class Dog eztends Aninal {
void eat() (Systen.cut.println("Dog is eating. ") :}
class MethodOverridingEx {
public static void main (String args )) {
Dog dl=new Dog):
Aninal al=new Anirnal ();
dl.eat ();
al.eat();
Output :
71 Derived class
method eat () runs
Dog is eating 6) An abs
77 Base class and imp
method eat) runs 7) An a
eating
keywo
Z. What do you mean by interface ? why do we need interface ? Differentiate 8)A
between like
abstraet.class and interface, OR What is similarity/difference between an abstract class 9)E
and interface ?
pu
Ans: 1 Part : Interface : An interface is a reference type in Java. It is
similar to
collection of abstract methods. A class implements an interface, thereby inheriting class. It is a
the abstract
methods of the interface.
Along with abstract methods, an interface may also contain
methods, and nested types. Method bodies exist onlyfor defaultconstants,
methods
default methods, static
and
Writing an interface is similar to writing a clasS. But a class static methods.
behaviors of an object. And an interface contains behaviors that a describes the attributes and
Syntax: class implements.
interface <interface name>
7/ declare constant fields
/1 declare methods that abstract
77 by default.
9)Example: 9) Example:
publicabstract class Shape{ public interface Drawable
public abstract void draw();
void draw(0:
accomplished in java ?
3. What is meant by dynamic method dispatch ? How is it
in which a call to an overridden
Ans: 1" Part: Dynamic Method Dispatch: It is the mechanism
important concept because of
method is resolved at run time instead of compile time. This is an
howJava implements run-time polymorphism.
determines which version of
2nd Part: When an overridden method is called by a reference, java
words the type of object
that method to execute based on the type of object it refer to. In simple called.
will be
which it referred determines which version of overridden method
Upcasting
known as
Upcasting: When Parent class reference variable refers to Child class object, it is
Upcasting
Example :
class Game
ck.type();
gm=ck; //gm refers to Cricket object
gm.type(0://calls Cricket's version of type
Output:
Indoor &outdoor
Outdoor game
Outdoor game
Notice the last output. This is
because of gm =ck; Now gm. type () will call
method. Because here gm refers to cricket Cricket version of type
object.
4. What is thedifference between rün
Compile Time Polymorphism time and compile time polymorphism ?
1) In Compile time Run time Polymorphism
Polymorphism, the callis
resolved by the compiler. 1) In Run time
2) Method overloading is the resolved by thePolymorphism,
compiler.
the call is not
polymorphism compile-time
where more than one 2) Method
share the same name with different methods overriding is the runtime
parameters or having same methodwith same polymorphism
signature and different return type. parameters or
signature, but associated in different
3) It is also known as Static binding, Early classes.
and overloading as well. binding 3) It is also known as
4) It is achieved by function binding and overridingDynamic
as well.
binding, Late
overloading and
operator overloading. 4) It is achieved by
5) Compile tirne polymorphism is less virtual functions and pointers.
flexible as all 5)Run time
things execute at compile time.
things executepolymorphism
at run time.
is more flexible as all
6) It provides fast execution because the
method 6) It provides slow
binding because theexecution as compare to early
that needs to be executed is known early at the
method that
compile time. executed is known at the runtime. needs to be
5. What is garbage collection ? what is static
variable ? Give examples for both.
Ans: 1 Part: Garbage Collection: Java garbage
collection is the process by which Iava
programs perform automatic memory management. Java programs compile to bytecode that cn
he run on a Jaya Virtual Machine, or JVM for
short. When Java programs run on the IVM
objccts are created on the heap, which is a portion of memory dedicated to thc progran.
Eventually, some objects will no longer be needed. The garbage collector finds these unused
objccts and deletes them to free up memory.
Example :
1. public class TestGarbage l{
2. public void finalize(){System.out.printIn("object is garbage collected");)
3. publicstatic void main(String args[]D{
4 TestGarbagel sl=new TestGarbagel);
TestGarbagel s2=new TestGarbagel();
6 sl=null;
7. s2=null;
8 System.gc);
9.}
10. }
Output:
object is garbage collected
object is qarbage collected
NB:
collected. This method
(The finalize() method is invoked each time before the object is garbage
can be used to perform cleanup processing.
The gc) method is used to invoke the garbage collector to perform cleanup processing. The gc)
is found in System and Runtime classes.
Collector(GC). This thread
Garbage collection is performed by a daemon thread called Garbage
calls the finalize) method before object is garbage collected.)
initialized only once
20 Part: Static variable in Java is variable which belongs to the class and
not to object(instance
at the start of the execution. It is a variable which belongs to the class and
These variables will be
). Static variables are initialized only once, at the start of the execution.
initialized first, before the initialization of any instance variables.
Example:
variable
1. //Java Program to demonstrate the use of static
2. class Student
3 int rollno;//instance variable
4 String name;
static String college ="ITS";//static variable
6. llconstructor
7 Student(int r, String n){
8 rollno Fr;
the
9 name Fn,
In
Jav
"+name+" "tcollege):
10. values
11. l/method to display the
(){System.out.printin(rollno+" clas
Output :
111 Karan ITS
222 Aryan ITs
6. What is wrapper class ? Explain with example the utility 'of final keyword in java.
Ans : 1"Part : Wrapper Class: in the0OPs concepts guide, we learned that object oriented
programming is all about objects. The eight primitive data types byte, short, int, long, float,
double, char and boolean are not objects, Wrapper classes are used for converting primitive data
types into objects, like int to Integer etc. Lets take a simple example to understand why we need
rapper class in java.
Some Primitive Data types and their Corresponding Wrapper classes are :
Primitive Data Wrapper Class
Type
char Character
byte Byte
short Short
long Integer
float Float
double Double
boolean Boolean
2d Part : In Java, the final keyword is used to denote constants. It can be used with variables
methods, and classes.
Once any entity (variable, method or class) is declared final, it can be assigned only once. That
IS,
In the above program, we have created a final variable named age. And we have tried to change
the value ofthefinal variable. Whenwe run the program,we will geta compilation error with
the following message.
cannot assign a value to final variable AGE
AGE = 45;
8.How can a programnner define a class that cannot be inherited? Illustrate using an
Thismeans that the Account class cannot be a superclass, and the OverdraftAccount class can no
longer be its subclass.
Sometimes, you may wish to limit only certain behaviors of a superclass to avoid corruption by a
subclass. For example, OverdraftAccount still could be asubclass of Account, but it should be
prevented from overriding the getBalance) method.
In this case use, the "final" keyword in the method declaration:
public class Account {
relurn this.balance;
A Base Class
Derived Class of A
Derived Class of B
C parent
that in Multilevel inheritance there is a concept of grandinherits
diagram class B
It's pretty clear with the inherits class B and
this diagram, then class C class ofB. So in this case class C
we take the example of
class. If parent class ofCand A is a
parent
that's what is
class A which means B is aproperties and methods of class A along with class B
is implicitly inheriting the
called multilevel inheritance.
of constructor of parent
class in the program, then, the body word, we can say that
gnd Part:
If we create an object of the child
class will be executed. In simple
class will execute first, then body of child class.
first, then of the child
theparent constructor get called
give below
Have a look at this constructor call orders image
Order ofconstructors callin inheritance
class Parent (
rarne(U/Parent
Par constructor
SYstee. out.println( "Parent ()... ");
Elass Child
exfends Parent {
chil¢()// Childconstructor
ystem.out.println(" Child()...")
In the picture, there are parent and child class with main program. And with
"new child() "
statement the constructor has been invoked. How the controls flows in the program for parent
child constructors calls is shown by arrow diagram.
Here are the steps how the program control flows in the image.
1.You create an object of child class in main) as new Child()"
2. Control goes to child constructor, but, its body is not getting
3. Control goes to parent constructor, body ofit getexecuted. exxecuted.
4. Then, control comes back to child constructor and body get
5. Then, the controls come back to new Child)" executed.
statement and exit.
11. $Java is a platform independent language" -
What is final modifier? Justify the statement. What is super?
Part:
Java is a platform independent programming language,
your system then automatically JVM are installed on Because when you install jdk software on
your system. For every operating system
separate JVM isavailable which is capable to read the .class file or byte code. When we compile
your Java code then .class file is generated by javac
compiler
and every operating system have its own JVM so JVM is these codes are readable by JVM
java language is become platform independent. platform dependent but due to JVM
12. a) Describe the life cycle of applet. Or What are the different states in the life cycle of
applet ? sketch the life cycle of applet ?
a) 1 Part : Applet is a special type of program that is embedded in the webpage to generate the
dynamiccontent. It runs inside the browser and works at client side.
Applet life cycle defined as how the object created, started, stopped and destroyed during the
entire execution of the application is saidto 'applet life cycle. Applet life cycle has 5 methods
init), start(), stop), paint() and destroy().These methods are invoked by the browser to execute.
startO
painto
stop0
destrOY0
init): init() method is used to initialize an applet. It is invoking only once at the time of
initialization. Initialized objects are created by the web browser. We can compare this
method with a Thread class born state.
start): start() method is used to start the applet. It is invoking after the init()method
invoked. It is invoking each time when browser loading or refreshing. Until init() method
is invoked start(0 method is inactive state, We can compare this method with Thread
class. start state
stop): stop) method is used to stop the applet. It is invoked every time when browser
stopped or minimized or abrupt failure of the application. After stop()method called, we
can also start() method whenever we want. This method mainly deals with clean up code.
We can compare this method with Thread class blocked state
destroy): destroy() method is used to destroy the application once we have done with
our applet work. It is invoked only once. Once applet is destroyed we can't start()the
applet. We can compare this method with Thread class dead state
paint):paint() method is used for painting any shapes like square, rectangle, trapezium,
eclipse, etc. paint)method has parameter as ClassGraphics. This Graphics class gives
painting features in an applet. We can compare this method with Thread class runnable
State.
13. What is meant by specifieinport ? The string type is not a primitive type. But known
as a reference type. Justify.
Ist Part : Specific imports are hard dependencies, whereas wildcard imports are not. If you
specifically inport a class, then that class must exist. But if you import a package with a
wildcard, no particular classes need to exist. The import statement simply adds the package to
the search path when hunting for names. So no true dependency is created by such imports, and
they therelore serve to keep our modules less coupled.
There are times when the long list of
specilic imports can be useful. For example, if you are dealing with legacy code and you want to
iind out what classes you need to build mocks and stubs for, you ican walkidown the list of
pecifie imrorts io find out he true qualified names of all those classes and then put the
priake tubs ia place. However, this use for specific imports is very rare. Furthermore, most
nodern lDIs will allow you to convert the wildcarded imports to a list of specific imports with a
gle comn d. So even in the legacy case it's better to import wildcards.
i arsttpes of variables in Java, primitive, and reference type. All the basic types e.g. int,
boolean, char, short, float, 1ong and double are known as primitive types. JVM treats them
differently than reference types, which is used to point objects e.g. String, Thread, File, and
others. Reference variables are not pointers but a handle to the object which is created in heap
memory. The main difference between primitive and reference type is that
has a value, it can never be null but reference type can be null, which primitive type always
denotes the absence of
value. So if you crcate a primitive variable of type int and forget to
would be 0, the default value of integral type in Java, but a reference initialize
it then it's value
iull value. ..c ilc.ns no reference is assigned to it.
variable by default has a
kyounown Protected
Public
Yes
Yes
Yes
Yes
Yes
Yes
No
Yes
2nd Part:
The finally keyword is used to create a block of code that follows a try block. A finally block of
code always executes, whether or not an exception has occurred. Using a finally block allows
you to run any cleanup-type statements that you just wish to execute, despite what happens
within the protected code.
Example:
public class Tester {
public static void main (String [) args) {
try{
int a = 10;
int b = 0;
int result = a/b;
}catch (Exception e){
System. out.println("Error: e.getMessage());
finally!
System. out.println(Finished."):
Output :
Error: / by zero
Finished.
applet? What are meant by local applet and
15. How does an applieation differ from an
rennote applet ? or explain types of applets.
IPart: Differenees between Application &Applet :
Applet
Applieation are
programs that APPplets are snall Java programs thatweb
Applications are stand-alone to be included in a HTML
indopeudontly without havine lo designed
document. They requirea Java-enabled
n beruu
LsO a Wob browser. browser for execution.
Java applications have fullaCcess to local Applets have no disk and network access.
iile syste and network.
It does not require a main method() for its
1licquires amain method0 for its execution.
NVCulion.
Applets cannot run programs from the local
picaions can run programs fron the
svslem. machine.
pplilion program is used to perform An applet program is usedto perform small
tas k directly for the user. tasks or part of it.
wCeSS all kinds of resources available It can only access the browser specific
0in. services.
art: Weh pages can contain two types of applets which are named after the location at
hey re storecd.
!pplet
poet
Aiocal applet is the onc that is stored on our own computer system. When the
hd a local applet, it doesn't need to retrieve information from the Internet. A
i p l c l is specilied by a path name and a file name as shown below in which the codebase
uttibute specifies apath name, whereas the code attribute specifies the name of the byte-code
file that contains the applet's code.
code="MyApp.class" width=200
<applet codebase="htp://www.apoorvacollege.com"
height-200> </applet>