0% found this document useful (0 votes)
15 views25 pages

Java Platform Independence and Features

Java is a platform-independent language as it compiles code into bytecode, which can be executed on any system with a Java Virtual Machine (JVM). Key features of Java include simplicity, robustness, security, and high performance, making it widely used for application programming. The document also explains the roles of JVM, JRE, JDK, and various Java concepts such as data types, packages, and input/output operations.

Uploaded by

rutuparnapati76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views25 pages

Java Platform Independence and Features

Java is a platform-independent language as it compiles code into bytecode, which can be executed on any system with a Java Virtual Machine (JVM). Key features of Java include simplicity, robustness, security, and high performance, making it widely used for application programming. The document also explains the roles of JVM, JRE, JDK, and various Java concepts such as data types, packages, and input/output operations.

Uploaded by

rutuparnapati76
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

1. Is Java Platform Independent if then how?

Yes, Java is a Platform Independent language. Unlike many programming languages javac
compiles the program to form a bytecode or .class file. This file is independent of the software
or hardware running but needs a JVM(Java Virtual Machine) file preinstalled in the operating
system for further execution of the bytecode.
Although JVM is platform dependent, the bytecode can be created on any System and can be
executed in any other system despite hardware or software being used which makes Java
platform independent.

2. What are the top Java Features?


Java is one the most famous and most used language in the real world, there are many features
in Java that makes it better than any other language some of them are mentioned below:

 Simple: Java is quite simple to understand and the syntax


 Platform Independent: Java is platform independent means we can run the same program
in any software and hardware and will get the same result.
 Interpreted: Java is interpreted as well as a compiler-based language.
 Robust: features like Garbage collection, exception handling, etc that make the language
robust.
 Object-Oriented: Java is an object-oriented language that supports the concepts of
class, objects, four pillars of OOPS, etc.
 Secured: As we can directly share an application with the user without sharing the actual
program makes Java a secure language.
 High Performance: faster than other traditional interpreted programming languages.
 Dynamic: supports dynamic loading of classes and interfaces.
 Distributed: feature of Java makes us able to access files by calling the methods from any
machine connected.
 Multithreaded: deal with multiple tasks at once by defining multiple threads
 Architecture Neutral: it is not dependent on the architecture.

3. What is JVM?

JVM stands for Java Virtual Machine it is a Java interpreter. It is responsible for loading,
verifying, and executing the bytecode created in Java.
Although it is platform dependent which means the software of JVM is different for different
Operating Systems it plays a vital role in making Java platform Independent.

4. What is JIT?

JIT stands for (Just-in-Time) compiler is a part of JRE(Java Runtime Environment), it is used
for better performance of the Java applications during run-time. The use of JIT is mentioned in
step by step process mentioned below:
1. Source code is compiled with javac to form bytecode
2. Bytecode is further passed on to JVM
3. JIT is a part of JVM, JIT is responsible for compiling bytecode into native machine code at
run time.
4. The JIT compiler is enabled throughout, while it gets activated when a method is invoked.
For a compiled method, the JVM directly calls the compiled code, instead of interpreting it.
5. As JVM calls the compiled code that increases the performance and speed of the execution.
.

5. What are Memory storages available with JVM?

JVM consists of a few memory storages as mentioned below:


1. Class(Method) Area: stores class-level data of every class such as the runtime constant
pool, field, and method data, and the code for methods.
2. Heap: Objects are created or objects are stored. It is used to allocate memory to objects
during run time.
3. Stack: stores data and partial results which will be needed while returning value for method
and performing dynamic linking
4. Program Counter Register: stores the address of the Java virtual machine instruction
currently being executed.
5. Native Method Stack: stores all the native methods used in the application.

6. What is a classloader?
Classloader is the part of JRE(Java Runtime Environment), during the execution of the
bytecode or created .class file classloader is responsible for dynamically loading the java
classes and interfaces to JVM(Java Virtual Machine). Because of classloaders Java run time
system does not need to know about files and file systems.
7. Difference between JVM, JRE, and JDK.
JVM: JVM also known as Java Virtual Machine is a part of JRE. JVM is a type of interpreter
responsible for converting bytecode into machine-readable code. JVM itself is platform
dependent but it interprets the bytecode which is the platform-independent reason why Java is
platform-independent.
JRE: JRE stands for Java Runtime Environment, it is an installation package that provides an
environment to run the Java program or application on any machine.
JDK: JDK stands for Java Development Kit which provides the environment to develop and
execute Java programs. JDK is a package that includes two things Development Tools to
provide an environment to develop your Java programs and, JRE to execute Java programs or
applications.

8. What are the differences between Java and C++?


Basis C++ Java

Java is Platform
C++ is Platform Dependent
Platform Independent

C++ is mainly used for Java is Mainly used for


Application System Programming Application Programming

Java is not so interactive


C++ is nearer to hardware
Hardware with hardware

C++ supports global and Java doesn't support global


Global Scope namespace scope. scope.

Functionality supported in
Functionality supported in C++ but not in Java are:
Java but not in C++ are:  goto
 thread support  Pointers
 documentation comment  Call by reference
 unsigned right  Structures and Unions
shift(>>>)  Multiple Inheritance
Not Supporting  Virtual Functions

Java is also an object-


oriented language. It is a
C++ is an object-oriented
single root hierarchy as
language. It is not a single
everything gets derived
root hierarchy .
from a single class
OOPS ([Link]).
Basis C++ Java

Java uses a Single


C++ always creates a new inheritance tree as classes in
inheritance tree. Java are the child of object
Inheritance Tree classes in Java.

9. Explain public static void main(String args[]) in Java.

Unlike any other programming language like C, C++, etc. In Java, we declared the main
function as a public static void main (String args[]). The meanings of the terms are mentioned
below:
1. public: the public is the access modifier responsible for mentioning who can access the
element or the method and what is the limit. It is responsible for making the main function
globally available. It is made public so that JVM can invoke it from outside the class as it is
not present in the current class.
2. static: static is a keyword used so that we can use the element without initiating the class
so to avoid the unnecessary allocation of the memory.
3. void: void is a keyword and is used to specify that a method doesn’t return anything. As the
main function doesn't return anything we use void.
4. main: main represents that the function declared is the main function. It helps JVM to
identify that the declared function is the main function.
5. String args[]: It stores Java command-line arguments and is an array of type
[Link] class.
10. What is Java String Pool?
A Java String Pool is a place in heap memory where all the strings defined in the program are
stored. A separate place in a stack is there where the variable storing the string is stored.
Whenever we create a new string object, JVM checks for the presence of the object in the
String pool, If String is available in the pool, the same object reference is shared with the
variable, else a new object is created.

Example:
String str1="Hello";
// "Hello" will be stored in String Pool
// str1 will be stored in stack memory

11. What will happen if we don't declare the main as static?


We can declare the main method without using static and without getting any errors. But, the
main method will not be treated as the entry point to the application or the program.

12. What are Packages in Java?


Packages in Java can be defined as the grouping of related types of classes, interfaces, etc
providing access to protection and namespace management.

13. Why Packages are used?


Packages are used in Java in order to prevent naming conflicts, control access, and make
searching/locating and usage of classes, interfaces, etc easier.

14. What are the advantages of Packages in Java?


There are various advantages of defining packages in Java.
 Packages avoid name clashes.
 The Package provides easier access control.
 We can also have the hidden classes that are not visible outside and are used by the
package.
 It is easier to locate the related classes.

15. How many types of packages are there in Java?


There are two types of packages in Java
 User-defined packages
 Build In packages

16. Explain different data types in Java.


There are 2 types of data types in Java as mentioned below:
1. Primitive Data Type
2. Non-Primitive Data Type or Object Data type
Primitive Data Type: Primitive data are single values with no special capabilities. There are 8
primitive data types:
 boolean: stores value true or false
 byte: stores an 8-bit signed two's complement integer
 char: stores a single 16-bit Unicode character
 short: stores a 16-bit signed two’s complement integer
 int: stores a 32-bit signed two’s complement integer
 long: stores a 64-bit two’s complement integer
 float: stores a single-precision 32-bit IEEE 754 floating-point
 double: stores a double-precision 64-bit IEEE 754 floating-point
Non-Primitive Data Type: Reference Data types will contain a memory address of the
variable's values because it is not able to directly store the values in the memory. Types of
Non-Primitive are mentioned below:
 Strings
 Array
 Class
 Object
 Interface

17. When a byte datatype is used?


A byte is an 8-bit signed two-complement integer. The minimum value supported by bytes is -
128 and 127 is the maximum value. It is used in conditions where we need to save memory and
the limit of numbers needed is between -128 to 127.

18. Can we declare Pointer in Java?


No, Java doesn't provide the support of Pointer. As Java needed to be more secure because
which feature of the pointer is not provided in Java.

19. What is the default value of byte datatype in Java?


The default value of the byte datatype in Java is 0.

20. What is the default value of float and double datatype in Java?
The default value of the float is 0.0f and of double is 0.0d in Java.

21. What is the Wrapper class in Java?


Wrapper, in general, is referred to a larger entity that encapsulates a smaller entity. Here in
Java, the wrapper class is an object class that encapsulates the primitive data types.
The primitive data types are the ones from which further data types could be created. For
example, integers can further lead to the construction of long, byte, short, etc. On the other
hand, the string cannot, hence it is not primitive.
Getting back to the wrapper class, Java contains 8 wrapper classes. They are Boolean, Byte,
Short, Integer, Character, Long, Float, and Double. Further, custom wrapper classes can also
be created in Java which is similar to the concept of Structure in the C programming language.
We create our own wrapper class with the required data types.

22. Why do we need wrapper classes?


The wrapper class is an object class that encapsulates the primitive data types, and we need
them for the following reasons:
1. Wrapper classes are final and immutable
2. Provides methods like valueOf(), parseInt(), etc.
3. It provides the feature of autoboxing and unboxing.

23. Differentiate between instance and local variables.


Instance Variable Local Variable

Declared outside the method, directly Declared within the


invoked by the method. method.

Has a default value. No default value

It can be used throughout the class. The scope is limited to the method.

24. What are the default values assigned to variables and instances in Java?
In Java When we haven’t initialized the instance variables then the compiler initializes them
with default values. The default values for instances and variables depend on their data types.
Some common types of default data types are:
 The default value for numeric types (byte, short, int, long, float, and double) is 0.
 The default value for the boolean type is false.
 The default value for object types (classes, interfaces, and arrays) is null.
 The null character, "u0000, " is the default value for the char type.

25. What is a static variable?


The static keyword is used to share the same variable or method of a given class. Static
variables are the variables that once declared then a single copy of the variable is created and
shared among all objects at the class level.

26. What is the difference between [Link], [Link], and [Link]?


[Link] - It is a PrintStream that is used for writing characters or can be said it can output
the data we want to write on the Command Line Interface console/terminal.

// Java Program to implement


// [Link]
import [Link].*;
// Driver Class
class GFG {
// Main Function
public static void main(String[] args)
{
// Use of [Link]
[Link]("");
}
}

[Link] - It is used to display error messages.

// Java program to demonstrate


// [Link]
import [Link].*;
// Driver Class
class GFG {
// Main function
public static void main(String[] args)
{
// Printing error
[Link](
"This is how we throw error with [Link]");
}
}
Output:
This is how we throw error with [Link]
Although, [Link] have many similarities both of them have quite a lot of difference also,
let us check them.
[Link] [Link]

It will print to the standard out of the


It will print to the standard error.
system.

It is mostly used to display results on the


It is mostly used to output error texts.
console.

It also gives output on the console but most


It gives output on the console with the
of the IDEs give it a red color to
default(black) color.
differentiate.

[Link] - It is an InputStream used to read input from the terminal Window. We can't use
the [Link] directly so we use Scanner class for taking input with the [Link].
Example:
// Java Program to demonstrate
// [Link]
import [Link].*;
// Driver Class
class Main {
// Main Function
public static void main(String[] args)
{
// Scanner class with [Link]
Scanner sc = new Scanner([Link]);
// Taking input from the user
int x = [Link]();
int y = [Link]();
// Printing the output
[Link]("Addition: %d", x + y);
}
}
Output:
3
4
Addition: 7
27. What do you understand by an IO stream?

Java brings various Streams with its I/O package that helps the user to perform all the input-
output operations. These streams support all types of objects, data types, characters, files, etc
to fully execute the I/O operations.

28. How many ways you can take input from the console?
There are two methods to take input from the console in Java mentioned below:
1. Using Command line argument
2. Using Buffered Reader Class
3. Using Console Class
4. Using Scanner Class
The program demonstrating the use of each method is given below.

// Java Program to implement input


// using Command line argument
import [Link].*;
class GFG {
public static void main(String[] args)
{
// check if length of args array is
// greater than 0
if ([Link] > 0) {
[Link](
"The command line arguments are:");
// iterating the args array and printing
// the command line arguments
for (String val : args)
[Link](val);
}
else
[Link]("No command line "
+ "arguments found.");
}
}
// Use below commands to run the code
// javac [Link]
// java Main GeeksforGeeks
// Java Program to implement
// Buffer Reader Class
import [Link].*;
class GFG {
public static void main(String[] args)
throws IOException
{
// Enter data using BufferReader
BufferedReader read = new BufferedReader(
new InputStreamReader([Link]));
// Reading data using readLine
String x = [Link]();
// Printing the read line
[Link](x);
}
}

// Java program to implement input


// Using Console Class
public class GfG {
public static void main(String[] args)
{
// Using Console to input data from user
String x = [Link]().readLine();
[Link]("You entered string " + x);
}
}
// Java program to demonstrate
// working of Scanner in Java
import [Link];
class GfG {
public static void main(String args[])
{
// Using Scanner for Getting Input from User
Scanner in = new Scanner([Link]);
String str = [Link]();
[Link]("You entered string " + str);
}
}

29. What is the difference between int array[] and int[] array?
Both int array[] and int[] array are used to declare an array of integers in java. The only
difference between them is on their syntax no functionality difference is present between them.
int arr[] is a C-Style syntax to declare an Array.
int[] arr is a Java-Style syntax to declare an Array.
However, it is generally recommended to use Java-style syntax to declare an Array. As it is
easy to read and understand also it is more consistent with other Java language constructs.

30. How to copy an array in Java?


In Java, there are multiple ways to copy an array based on the requirements:
1. clone() Method (Shallow Copy)
 The clone() method creates a new array with its own memory but contains references to the
same objects for non-primitive data types.
 For primitive arrays, it behaves like a deep copy since primitive values are directly copied.
int[] arr = {1, 2, 3, 5, 0};
int[] tempArr = [Link](); // Creates a new array with copied values
2. [Link]() Method (Deep Copy)
 This method creates a new array and copies elements from the original array.
 It allows partial copying by specifying an offset and length.
int[] arr = {1, 2, 7, 9, 8};
int[] tempArr = new int[[Link]];
[Link](arr, 0, tempArr, 0, [Link]);
3. [Link]() Method (Creates New Array)
 This method creates a new array and copies the entire original array into it.
 If the specified length is greater than the original array, extra elements are initialized with
default values.
int[] arr = {1, 2, 4, 8};
int[] tempArr = [Link](arr, [Link]);
4. [Link]() Method (Copying a Subset)
 Similar to copyOf(), but allows copying a specific range of elements.
int[] arr = {1, 2, 4, 8};
int[] tempArr = [Link](arr, 0, [Link]);
31. What do you understand by the jagged array?
A jagged Array in Java is just a two-dimensional array in which each row of the array can have
a different length. Since all the rows in a 2-d Array have the same length but a jagged array
allows more flexibility in the size of each row. This feature is very useful in conditions where
the data has varying lengths or when memory usage needs to be optimized.
Syntax:
int[][] Arr = new int[][] {
{1, 2, 8},
{7, 5},
{6, 7, 2, 6}
};

32. Is it possible to make an array volatile?


In Java, it is not possible to make a volatile. Volatile keywords in Java can only be applied to
individual variables but not to arrays or collections. The value of the Variable is always read
from and written to the main memory when it is defined as volatile rather than being cached in
a thread's local memory. This makes it easier to make sure that all threads that access the
variable can see changes made to it.
33. What are the advantages and disadvantages of an array?

The advantages of Arrays are:


 Direct and effective access to any element in the collection is made possible by arrays. An
array's elements can be accessed using an O(1) operation, which means that the amount of
time needed to do so is constant and independent of the array's size.
 Data can be stored effectively in memory using arrays. The size of an array is known at
compile time since its elements are stored in contiguous memory regions.
 Due to the fact that the data is stored in contiguous memory areas, arrays provide quick
data retrieval.
 Arrays are easy to implement and understand, making them an ideal choice for beginners
learning computer programming.
Disadvantages of Arrays are:
 Arrays are created with a predetermined size that is chosen at that moment. This means that
if the array's size needs to be extended, a new array will need to be made, and the data will
need to be copied from the old array to the new array, which can take a lot of time and
memory.
 There may be unused memory space in an array's memory space if the array is not
completely occupied. If you have poor recall, this can be a problem.
 Compared to other data structures like linked lists and trees, arrays might be rigid due to
their fixed size and limited support for sophisticated data types.
 Because an array's elements must all be of the same data type, it does not support complex
data types like objects and structures.
34. What is an object-oriented paradigm?
Paradigm literally means a pattern or a method. Programming paradigms are the methods to
solve a program that is of four types namely, Imperative, logical, functional, and object-
oriented. When objects are used as base entities upon which the methods are applied,
encapsulation or inheritance functionalities are performed, it is known as an object-oriented
paradigm.
35. What are the main concepts of OOPs in Java?
The main concepts of OOPs in Java are mentioned below:
 Inheritance
 Polymorphism
 Abstraction
 Encapsulation
36. What is the difference between an object-oriented programming language and an
object-based programming language?
Object-Oriented Programming Language Object-Based Programming Language

Object-oriented programming language The scope of object-based programming is


covers larger concepts like inheritance, limited to the usage of objects and
polymorphism, abstraction, etc. encapsulation.

It supports all the built-in objects It doesn’t support all the built-in objects

Examples: Java, C#, etc. Examples: Java script, visual basics, etc.

37. How is the ‘new’ operator different from the ‘newInstance()’ operator in Java?
the new operator is used to create objects, but if we want to decide the type of object to be
created at runtime, there is no way we can use the new operator. In this case, we have to use
the newInstance() method.

38. What are Classes in Java?


In Java, Classes are the collection of objects sharing similar characteristics and attributes.
Classes represent the blueprint or template from which objects are created. Classes are not
real-world entities but help us to create objects which are real-world entities.

39. What is the difference between static (class) method and instance method?
Static(Class) method Instance method

Static method is associated with a class The instance method is associated with an
rather than an object. object rather than a class.

Static methods can be called using the class The instance methods can be called on a
name only without creating an instance of a specific instance of a class using the object
class. reference.

Static methods do not have access Instance methods have access


to this keyword. to this keyword.

Static methods can access only static Instance methods can access both static and
members of the class. non-static methods of the class.

Static methods cannot be overridden


Instance methods can be overridden because
because they are resolved at compile time,
they are resolved at run time, not at compile
not at run time. This means that the
time. This means that the compiler decides
compiler decides which method to call
Static(Class) method Instance method

based on the reference type, not on the which method to call based on the object
object type. type, not on the reference type.

40. What is this keyword in Java?

‘this’ is a keyword used to reference a variable that refers to the current object.

41. What are the different ways to create objects in Java?


Methods to create objects in Java are mentioned below:
1. Using new keyword
2. Using new instance
3. Using clone() method
4. Using deserialization
5. Using the newInstance() method of the Constructor class

42. What is the constructor?


Constructor is a special method that is used to initialize objects. Constructor is called when a
object is created. The name of constructor is same as of the class.
Example:
// Class Created
class XYZ{
private int val;

// Constructor
XYZ(){
val=0;
}
};
43. What happens if you don't provide a constructor in a class?
If you don't provide a constructor in a class in Java, the compiler automatically generates a
default constructor with no arguments and no operation which is a default constructor.

44. How many types of constructors are used in Java?


There are two types of constructors in Java as mentioned below:
1. Default Constructor
2. Parameterized Constructor
Default Constructor: It is the type that does not accept any parameter value. It is used to set
initial values for object attributes.
class_Name();
// Default constructor called
Parameterized Constructor: It is the type of constructor that accepts parameters as arguments.
These are used to assign values to instance variables during the initialization of objects.
class_Name(parameter1, parameter2......);
// All the values passed as parameter will be
// allocated accordingly

45. What is the purpose of a default constructor?


Constructors help to create instances of a class or can be said to create objects of a class.
Constructor is called during the initialization of objects. A default constructor is a type of
constructor which do not accept any parameter, So whatever value is assigned to properties of
the objects are considered default values.

46. What do you understand by copy constructor in Java?


The copy constructor is the type of constructor in which we pass another object as a parameter
because which properties of both objects seem the same, that is why it seems as if constructors
create a copy of an object.

47. Where and how can you use a private constructor?


A private constructor is used if you don't want any other class to instantiate the object to avoid
subclassing. The use private constructor can be seen as implemented in the example.
// Java program to demonstrate implementation of Singleton
// pattern using private constructors.
import [Link].*;
class GFG {
static GFG instance = null;
public int x = 10;
// private constructor can't be accessed outside the
// class
private GFG() {}
// Factory method to provide the users with instances
static public GFG getInstance()
{
if (instance == null)
instance = new GFG();
return instance;
}
}
// Driver Class
class Main {
public static void main(String args[])
{
GFG a = [Link]();
GFG b = [Link]();
a.x = a.x + 10;
[Link]("Value of a.x = " + a.x);
[Link]("Value of b.x = " + b.x);
}
}

Output
Value of a.x = 20
Value of b.x = 20

48. What are the differences between the constructors and methods?
Java constructors are used for initializing objects. During creation, constructors are called to
set attributes for objects apart from this few basic differences between them are:
1. Constructors are only called when the object is created but other methods can be called
multiple times during the life of an object.
2. Constructors do not have a return type, whereas methods have a return type, which can
be void or any other type.
3. Constructors are used to setting up the initial state but methods are used to perform specific
actions.

49. What is an Interface?


An interface in Java is a collection of static final variables and abstract methods that define the
contract or agreement for a set of linked classes. Any class that implements an interface is
required to implement a specific set of methods. It specifies the behavior that a class must
exhibit but not the specifics of how it should be implemented.
Syntax:
interface
{
// constant fields
// methds that are abstract by default
}
// Java Program to demonstrate Interface
import [Link].*;
interface Shape {
double getArea();
double getPerimeter();
}
class Circle implements Shape {
private double radius;
public Circle(double radius) { [Link] = radius; }
public double getArea()
{
return [Link] * radius * radius;
}
public double getPerimeter()
{
return 2 * [Link] * radius;
}
}
class GFG {
public static void main(String[] args)
{
Circle circle = new Circle(5.0);
[Link]("Area of circle is "
+ [Link]());
[Link]("Perimeter of circle is"
+ [Link]());
}
}

Output
Area of circle is 78.53981633974483
Perimeter of circle is31.41592653589793

51. What are the advantages of Encapsulation in Java?


The advantages of Encapsulation in Java are mentioned below:
1. Data Hiding: it is a way of restricting the access of our data members by hiding the
implementation details. Encapsulation also provides a way for data hiding. The user will
have no idea about the inner implementation of the class.
2. Increased Flexibility: We can make the variables of the class read-only or write-only
depending on our requirements.
3. Reusability: Encapsulation also improves the re-usability and is easy to change with new
requirements.
4. Testing code is easy: Code is made easy to test for unit testing.

52. What are the different types of inheritance in Java?


Inheritance is the method by which the Child class can inherit the features of the Super or
Parent class. In Java, Inheritance is of four types:
 Single Inheritance: When a child or subclass extends only one superclass, it is known to
be single inheritance. Single-parent class properties are passed down to the child class.
 Multilevel Inheritance: When a child or subclass extends any other subclass a hierarchy
of inheritance is created which is known as multilevel inheritance. In other words, one
subclass becomes the parent class of another.
 Hierarchical Inheritance: When multiple subclasses derive from the same parent class is
known as Hierarchical Inheritance. In other words, a class that has a single parent has many
subclasses.
 Multiple Inheritance: When a child class inherits from multiple parent classes is known as
Multiple Inheritance. In Java, it only supports multiple inheritance of interfaces, not
classes.

53. What is multiple inheritance? Is it supported by Java?


A component of the object-oriented notion known as multiple inheritances allows a class to
inherit properties from many parent classes. When methods with the same signature are present
in both superclasses and subclasses, an issue arises. The method's caller cannot specify to the
compiler which class method should be called or even which class method should be given
precedence.
Note: Java doesn’t support Multiple Inheritance
// Java Program to show multiple Inheritance
import [Link].*;
interface Animal {
void eat();
}
interface Mammal {
void drink();
}
class Dog implements Animal, Mammal {
public void eat() { [Link]("Eating"); }
public void drink() { [Link]("Drinking"); }
void bark() { [Link]("Barking"); }
}
class GFG {
public static void main(String[] args)
{
Dog d = new Dog();
[Link]();
[Link]();
[Link]();
}
}

Output
Eating
Drinking
Barking
51. What is method overloading?
In Java, Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of input
parameters, or a mixture of both.
Method overloading in Java is also known as Compile-time Polymorphism, Static
Polymorphism, or Early binding. In Method overloading compared to the parent argument,
the child argument will get the highest priority.

54. What is method overriding?


Method overriding, also known as run time polymorphism is one where the child class contains
the same method as the parent class. For instance, we have a method named ‘gfg()’ in the
parent class. A method gfg() is again defined in the sub-class. Thus when gfg() is called in the
subclass, the method within the class id executed. Here, gfg() within the class overridden the
method outside.

Method overriding is a method to achieve Run-time polymorphism in Java. Method overriding


is a feature that allows a child class to provide a specific implementation of a method that is
already provided by one of its parent classes. When a method in a child class has the same name,
the same parameters or signature, and the same return type (or sub-type) as a method in its parent
class, then the method in the subclass is said to override the method in the superclass.

55. Differentiate between method overloading and method overriding ?

Method Overloading Method Overriding

When two or multiple methods are in the When a subclass provides its own
same class with different parameters but the implementation of a method that is already
same name. defined in the parent class.

Method overloading can only happen in the


Method overriding can only happen in
same class or between a subclass or parent
Subclass.
class.

When an error occurs it is caught at the When an error occurs it is caught at


compile time of the program. Runtime of the program.

Example of Compile Time Polymorphism. Example of Run Time Polymorphism.

Method Overloading may or may not Method overriding always needs


require Inheritance. Inheritance.

It is performed in two classes with an


It occurs within the class.
inheritance relationship.
56 What is Exception? And what are the different types of exception?
In Java, exception handling is a mechanism to handle runtime errors, allowing the normal
flow of a program to continue. Exceptions are events that occur during program execution
that disrupt the normal flow of instructions.
Types of Java Exceptions
Java defines several types of exceptions that relate to its various class
libraries. Java also allows users to define their it's exceptions.

1. User-Defined Exception
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such
cases, users can also create exceptions, which are called "user-defined Exceptions".
Methods to Print the Exception Information
 printStackTrace(): Prints the full stack trace of the exception, including the name, message
and location of the error.
 toString(): Prints exception information in the format of the Name of the exception.
 getMessage() : Prints the description of the exception

2. Built-in Exception
Build-in Exception are pre-defined exception classes provided by Java to handle common
errors during program execution. There are two type of built-in exception in java.
 Checked Exception: These exceptions are checked at compile time, forcing the
programmer to handle them explicitly.
 Unchecked Exception: These exceptions are checked at runtime and do not require
explicit handling at compile time.
Java Checked vs Unchecked Exceptions
In Java, an exception is an unwanted or unexpected event that occurs during the execution of a
program, i.e., at run time, that disrupts the normal flow of the program’s instructions. In Java,
there are two types of exceptions:
 Checked Exception: These exceptions are checked at compile time, forcing the
programmer to handle them explicitly.
 Unchecked Exception: These exceptions are checked at runtime and do not require
explicit handling at compile time.
Checked Exceptions in Java
If a method throws a checked Exception, then the exception must be handled using a try-catch
block and declared the exception in the method signature using the throws keyword.
Types of Checked Exception
 Fully Checked Exception: A checked exception where all its child classes are also
checked (e.g., IOException, InterruptedException).
 Partially Checked Exception: A checked exception where some of its child classes are
unchecked (e.g., Exception).
Checked exceptions represent invalid conditions in areas outside the immediate control of the
program like memory, network, file system, etc. Any checked exception is a subclass
of Exception.
import [Link].*;

class Geeks
{
public static void main(String[] args)
{
// Getting the current root directory
String root = [Link]("[Link]");
[Link]("Current root directory: " + root);

// Adding the file name to the root directory


String path = root + "\\[Link]";
[Link]("File path: " + path);

// Reading the file from the path in the local directory


FileReader f = new FileReader(path);

// Creating an object as one of the ways of taking input


BufferedReader b = new BufferedReader(f);

for (int counter = 0; counter < 3; counter++)


[Link]([Link]());

[Link]();
}
}
Explanation: In the above program we create a Java program which reads a file from the same
directory this program may throw exceptions like FileNotFoundException or IOException so we
handle it using the try-catch block to handle the exceptions and execute the program without any
interruption.

Unchecked Exceptions in Java


Unchecked exception are exceptions that are not checked at the compile time. In Java, exceptions
under Error and RuntimeException classes are unchecked exceptions, everything else under
throwable is checked.
Consider the following Java program. It compiles fine, but it throws an ArithmeticException
when run. The compiler allows it to compile because ArithmeticException is an unchecked
exception.
class Geeks {
public static void main(String args[]) {

// Here we are dividing by 0 which will not be caught at compile time as there is no mistake
but caught at runtime because it is mathematically incorrect
int x = 0;
int y = 10;
int z = y / x;
}
}

Note:
 Unchecked exceptions are runtime exceptions that are not required to be caught or declared
in a throws clause.
 These exceptions are caused by programming errors, such as attempting to access an index
out of bounds in an array or attempting to divide by zero.
 Unchecked exceptions include all subclasses of the RuntimeException class, as well as the
Error class and its subclasses.
The separation into checked and unchecked exceptions sounded like a good idea at the time.
Over the years, it has introduced more boilerplate and less aesthetically pleasing code patterns
than it solved real problems. The typical pattern within the Java ecosystem is to hide the
checked exception within an unchecked one.

You might also like