Sie sind auf Seite 1von 16

1.

Differentiate between Method overloading and method overriding with example

Ans:
Method Overloading Method Overriding
1 Method overloading is used to increase the readability of the program.
2 Method overloading is performed within class.
3 In case of method overloading, parameter must be different.
4 Method overloading is the example of compile time polymorphism.

// Demonstrate method overloading.


class OverloadDemo {
void test()
{
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b)
{
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
double test(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
// call all versions of test()
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
}
}
• This program generates the following output:
• No parameters
• a: 10
• a and b: 10 20
• double a: 123.25
• Result of ob.test(123.25): 15190.5625

1. Method overriding is used to provid specific implementation of the


method that is already provided by its super class
2.Method overriding occurs in two classes that have IS-A (inheritancerelationship.
3. In case of method overriding parameter must be same
4.Method overriding is the example of run time polymorphism

// Method overriding.
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}

class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// display k – this overrides show() in A
void show() {
System.out.println("k: " + k);
}
}

class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
The output produced by this program is shown here:
k: 3
2. Explain the followings with example
i) this ii) super iii) final iv) finalize

ANS: this can be used inside any method to refer to the current
object.
That is, this is always a reference to the object on which the
method was invoked.
consider the following version of Box( ):
// A redundant use of this.
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
The this keyword can be used to refer current
class instance variable.
If there is ambiguity between the instance
variables and parameters, this keyword
resolves the problem of ambiguity.
3. Discuss public, private, protected and default access modifier with example.
• ANS: Protected: Can be accessed by all the class & subclass in the same package and all
the subclasses in other package.
• Public: can be accessed any where.
• Default: Can be accessed by all the class & subclass within the same package.
• Private : can be accessed only within the class & thus completely hidden from outside the
class.
class ABC{
protected double num = 100;
protected int square(int a){
return a*a;
}
}
public class example{
public static void main(String args[]){
ABC obj = new ABC();
System.out.println(obj.num);
System.out.println(obj.square(10));
}
}
4. Explain the following terms with respect to exception handling. i) try ii) catch iii) throw
iv) finally
Exception Handling Fundamentals
➢ Java exception handling is managed via five keywords:
try, catch, throw, throws, and finally.
➢ Program statements that you want to monitor for exceptions are contained within a try block.
If an exception occurs within the try block, it is thrown.
➢ Your code can catch this exception (using catch) and handle it.
➢ System-generated exceptions are automatically thrown by the Java run-time system.
To manually throw an exception, use the keyword throw.
➢ Any exception that is thrown out of a method must be specified as such by a throws clause.
➢ Any code that absolutely must be executed after a try block completes is put in a finally block.

This is the general form of an exception-handling block:


try {
// block of code to monitor for errors
}
catch (ExceptionType1 exOb) {
// exception handler for ExceptionType1
}
catch (ExceptionType2 exOb) {
// exception handler for ExceptionType2
}
// ...
finally {
// block of code to be executed after try block ends
}

5. Describe multiple Inheritance with suitable example.

6. Explain use of Interface with suitable example.


➢ Using interfaces, you can perform multiple inheritance.
➢ Using interface, you can fully abstract a class.
➢ Methods within interfaces are declared without any body.
➢ Any number of classes can implement an interface.
➢ One class can implement any number of interfaces
This is the general form of an interface:
access interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
}

Here is an example of a simple interface that contains one method called callback( ) that takes a
single integer parameter.
interface Callback
{
void callback(int param);
}
Implementing Interface
➢ Once an interface has been defined, one or more classes can implement that interface.
➢ Syntax:

➢ If a class implements more than one interface, the interfaces are separated with a comma.
➢ The methods that implement an interface must be declared public.
➢ Also, the type signature of the implementing method must match exactly the type
signature specified in the in terface definition
Example:
class c1 implements Example
{
public void print()
{
System.out.println(“Hello World”);
}
}.

7. Differentiate between interface and class. Class Interface


Uses a keyword class
Keyword interface
*Contains data members and methods
*may contain data members and
method But the methods are not
defined.
*Can create an instance of a class
* Cannot create instance
*class can use private protected and
public
*Interface makes use of only public
access specifier
*Members of a class can be final.
*Members of interface are always
declared as final.
8. Explain Java garbage collection mechanism.
garbage collection is an automatic process. The programmer does not need to explicitly
mark objects to be deleted. The garbage collection implementation lives in the JVM
Java programs compile to bytecode that can be run on a Java Virtual Machine, or JVM
for short. When Java programs run on the JVM, objects are created on the heap, which
is a portion of memory dedicated to the program.
The garbage collector finds these unused objects and deletes them to free up
memo ry

In the first step, unreferenced objects are identified and marked as ready for garbage
collection.
In the second step, marked objects are deleted.
Optionally, memory can be compacted after the garbage collector deletes objects, so
remaining objects are in a contiguous block at the start of the heap

9. Explain package in java. List out all packages with short description
Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces.

Defining a Package
➢ Include a package command as the first statement in a Java source file.
➢ Any classes declared within that file will belong to the specified package.
➢ The package statement defines a name space in which classes are stored.
➢ Syntax: package package_name;
package pkg1[.pkg2[.pkg3]];
➢ Packages in Java are used to prevent naming conflicts, to control access, visibility
control mechanism, etc.
➢ Package in Java is nothing but a folder in directory structure.
➢ Java Packages are stored in hierarchical manner

➢ Ex: Existing packages in Java:


.
java.io - consists of I/O classes
. java.lang Classes that are fundamental to the design of the Java programming language.
java.util Contains the collections frame work, legacy collection classes, event model, date and
time facilities,
java.math Arbitrary-precision integer (BigInteger) and decimal (BigDecimal) arithmetic.
java.text For handling text, dates, numbers, and messages in a manner independent of natural
languages.
java.text.spi Service provider classes for the classes in the java.text package.
1) java.lang: Contains language support classes(e.g classed which defines primitive
data types, math operations). This package is automatically imported.
2) java.io: Contains classed for supporting input / output operations.
3) java.util: Contains utility classes which implement data structures like Linked List,
Dictionary and support ; for Date / Time operations.
4) java.applet: Contains classes for creating Applets.
5) java.awt: Contain classes for implementing the components for graphical user
interfaces (like button , ;menus etc).
6) java.net: Contain classes for supporting networking operations.

10. How super can be used in java? Illustrate with example


. 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. It is
majorly used in the following contexts:
1. Use of super with variables: This scenario occurs when a derived class and base
class has same data members. In that case there is a possibility of ambiguity for the JVM.
We can understand it more clearly using this code snippet:
/* Base class vehicle */
class Vehicle
{
int maxSpeed = 120;
}

/* sub class Car extending vehicle */


class Car extends Vehicle
{
int maxSpeed = 180;

void display()
{
/* print maxSpeed of base class
(vehicle) */
System.out.println("Maximum Speed: " +
super.maxSpeed);
}
}

/* Driver program to test */


class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Run on IDE
Output:

Maximum Speed: 120

In the above example, both base class and subclass have a member maxSpeed. We could
access maxSpeed of base class in sublcass using super keyword.

11. What is Exception? Explain any three built in exceptions


An “exception” is an event that occurs during the execution of a program that disrupts
the normal flow of the program.
Built-in Exceptions in Java with examples
Types of Exceptions in Java
Built-in exceptions are the exceptions which are available in Java libraries
Examples of Built-in Exception:
1. Arithmetic exception : It is thrown when an exceptional condition has occurred in an
arithmetic operation.
// Java program to demonstrate
// ArithmeticException
class ArithmeticException_Demo {
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a / b; // cannot divide by zero
System.out.println("Result = " + c);
}
catch (ArithmeticException e) {
System.out.println("Can't divide a number
by 0");
}
}
}
Output:
2. Can't divide a number by 0

3. ArrayIndexOutOfBounds Exception : It is thrown to indicate that an array has been


accessed with an illegal index. The index is either negative or greater than or equal to the
size of the array.
// Java program to demonstrate
// ArrayIndexOutOfBoundException
class ArrayIndexOutOfBound_Demo {
public static void main(String args[])
{
try {
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an
array of
// size 5
}
catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array Index is Out Of
Bounds");
}
}
}
4. Output:
5. Array Index is Out Of Bounds

6. ClassNotFoundException : This Exception is raised when we try to access a class whose


definition is not found.
// Java program to illustrate the
// concept of ClassNotFoundException
class Bishal {

} class Geeks {

} class MyClass {
public static void main(String[] args)
{
Object o = class.forName(args[0]).newInstance();
System.out.println("Class created for" +
o.getClass().getName());
}
}

12. What is the difference between Checked and Unchecked exception


Checked Exception:
 These are the classes that extend Throwable except RuntimeException and Error.
 They are also known as compile time exceptions because they are checked at compile time,
meaning the compiler forces us to either handle them with try/catch or indicate in the
function signature that it throws them and forcing us to deal with them in the caller.
 They are programmatically recoverable problems which are caused by unexpected conditions
outside the control of the code (e.g. database down, file I/O error, wrong input, etc).
 Example: IOException, SQLException, etc.
Unchecked Exception:
 The classes that extend RuntimeException are known as unchecked exceptions.
 Unchecked exceptions are not checked at compile-time, but rather at runtime, hence the
name.
 They are also programmatically recoverable problems but unlike checked exception they are
caused by faults in code flow or configuration.
 Example: ArithmeticException,NullPointerException, ArrayIndexOutOfBound
sException, et

13. Wh

No. throw throws

1) Java throw keyword is Java throws keyword is used to


used to explicitly declare an exception.
throw an exception.

2) Checked exception Checked exception can be


cannot be propagated propagated with throws.
using throw only.

3) Throw is followed by Throws is followed by class.


an instance.

4) Throw is used within Throws is used with the method


the method. signature.
5) You cannot throw You can declare multiple
multiple exceptions. exceptions e.g.
public void method()throws
IOException,SQLException.

14. How do we create user defined exception types in Java?

15. Define package? How to create package in java with example.

A java package is a group of similar types of classes, interfaces and sub-


packages.

Package in java can be categorized in two form, built-in package and user-
defined package.

There are many built-in packages such as java, lang, awt, javax, swing, net,
io, util, sql etc.

16. How does the Java run-time system know where to look for packages that you create?

MULTITHREADING
17. What is multithreading? List advantages of multithreading?
Multithreading in java is a process of executing multiple threads
simultaneously.

Java Multithreading is mostly used in games, animation etc.

• Advantages of Java Multithreading


• 1) It doesn't block the user because threads are
independent and you can perform multiple
operations at same time.
• 2) You can perform many operations together so it
saves time.
• 3) Threads are independent so it doesn't affect other
threads if exception occur in a single thread
18. Write a program to create two threads, one thread will print numbers from 1 to 10 and
second thread will print numbers from 10 to 1.

1. class Ascending extends Thread {


2.
3. public void run() {
4.
5. for(int i=1; i<=10;i++) {
6. System.out.println("Ascending Thread : " + i);
7. }
8. }
9. }
10.
11. class Descending extends Thread {
12.
13. public void run() {
14.
15. for(int i=10; i>0;i--) {
16. System.out.println("Descending Thread : " + i);
17. }
18. }
19. }
20.
21. public class AscendingDescendingThread {
22.
23. public static void main(String[] args) {
24.
25. new Ascending().start();
26. new Descending().start();
27. }
28. }
OUTPUT
C:\javac AscendingDescendingThread.java
C:\java AscendingDescendingThread
Ascending Thread : 1
Ascending Thread : 2
Ascending Thread : 3
Ascending Thread : 4
Ascending Thread : 5
Ascending Thread : 6
Ascending Thread : 7
Ascending Thread : 8
Ascending Thread : 9
Ascending Thread : 10
Ascending Thread : 11
Ascending Thread : 12
Ascending Thread : 13
Ascending Thread : 14
Ascending Thread : 15
Descending Thread : 15
Descending Thread : 14
Descending Thread : 13
Descending Thread : 12
Descending Thread : 11
Descending Thread : 10
Descending Thread : 9
Descending Thread : 8
Descending Thread : 7
Descending Thread : 6
Descending Thread : 5
Descending Thread : 4
Descending Thread : 3
Descending Thread : 2
Descending Thread : 1

19. Desc. ribe the life cycle of thread with diagram.

• Life cycle of a Thread (Thread States)


• When we create a new Thread object using new operator, thread
state is New Thread.
• A thread can be running. It can be ready to run as soon
as it gets CPU time.
• A running thread can be suspended, which temporarily
suspends its activity.
• A suspended thread can then be resumed, allowing it to
pick up where it left off.
• A thread can be blocked when waiting for a resource.
• At any time, a thread can be terminated, which halts its
execution immediately
• Each thread have a priority.
• Priorities are represented by a number between 1
and 10.
• In most cases, thread scheduler schedules the
threads according to their priority.
• Default priority of a thread is 5 (NORM_PRIORITY).
• MIN_PRIORITY is 1
• MAX_PRIORITY is 10
20. How to Create a Thread in java.
In the most general sense, you create a thread by
instantiating an object of type Thread.
Java defines two ways in which this can be
accomplished:
1. Extending the Thread class
2. Implementing the Runnable Interface
• Thread class:
• Thread class provide constructors and methods to
create and perform operations on a thread.
• Thread class extends Object class and implements
Runnable interface.
• Commonly used Constructors of Thread class:
• Thread()
• Thread(String name)
• Thread(Runnable r)
• Thread(Runnable r, String name)
• Commonly used methods of Thread class:
• void start(): Creates a new thread and makes it runnable.
• void run(): The new thread begins its life inside this method.
• public void sleep(long miliseconds): Causes the currently
executing thread to sleep for the specified number of
milliseconds.
• public Thread currentThread(): returns the reference of
currently executing thread.
1) class Multi extends Thread
{
public void run()
{
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi t1=new Multi();
t1.start();
}
}
Output: thread is running...
The class should extend Java Thread class.
• The class should override the run() method.
• The functionality that is expected by the Thread to be executed
is written in the run() method.
2)Java Thread Example by implementing Runnable interface
class Multi3 implements Runnable{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Multi3 m1=new Multi3();
Thread t1 =new Thread(m1);
t1.start();
}}
Output:thread is running...
• An instance of the class can then be allocated, passed as an
argument when creating Thread, and started.
• Eg: To have the run() method executed by a thread, pass an
instance of Multi3 to a Thread in its constructor.
• The class should implement the Runnable interface.
• The class should implement the run() method in the
Runnable interface.
• The functionality that is expected by the Thread to be
executed is put in the run() method.
21. Explain isAlive() and join() method in multithreading

Two ways exist to determine whether a thread has finished.


isAlive()
join()
➢ isAlive( ) method returns true if the thread upon which it is called is still
running. It returns false otherwise.
Syntax:
final boolean isAlive( ) ➢ join( ) method waits until the thread on which it is called terminates.
➢ Its name comes from the concept of the calling thread waiting until the specified
thread joins it.
Syntax:
final void join( ) throws InterruptedException
Ex: isAlive1.java
Join_Example.java

Das könnte Ihnen auch gefallen