Experience 1
Experience 1
1. Oops?
In Python object-oriented Programming (OOPs) is a programming
paradigm that uses objects and classes in programming. It aims to
implement real-world entities like inheritance, polymorphisms,
encapsulation, etc. in the programming. The main concept of
object-oriented Programming (OOPs) or oops concepts in Python is
to bind the data and the functions that work together as a single unit
so that no other part of the code can access this data.
2. Why Oops?
The main concept of object-oriented Programming (OOPs) or oops
concepts in Python is to bind the data and the functions that work
together as a single unit so that no other part of the code can access
this data.
JRE (Java
JDK (Java
Runtime
Developme
Environmen
nt Kit)
t)
To develop
and deploy To run Java
Purpose
Java applications
applications
Includes the
Includes the
JRE,
Java Virtual
compilers,
Componen Machine
debuggers,
ts (JVM) and
and other
class
developmen
libraries
t tools
Used by
Used by end-
developers
users to run
Usage to create
Java
Java
applications
applications
developmen
JDK
t tools
Must be
Optional, but
installed to
required to
Installation develop and
run Java
deploy Java
applications
applications
System.out.println(b); // Prints 65
System.out.println(c); // Prints A
In this example, the variable is assigned the value 65, which is the
ASCII value for the character 'A'. The variable is directly assigned
the character 'A', which is represented using Unicode. When we
print , it prints the integer value 65. When we print , it prints the
character 'A'.
Q10. Why do we need a constructor in Java?
Constructors are an essential part of the Java programming
language and serve several purposes. Here are a few reasons why
constructors are needed in Java:
1. Object Initialization: Constructors are used to initialize the
object's state, i.e., the instance variables of the object. When a new
object is created using the keyword, the constructor is
automatically called to initialize the object's state. Without a
constructor, the object's state would be undefined, and the program
would likely crash.
2. Provide Default Values: Constructors can provide default values
for instance variables if no values are specified during object
creation. This can help avoid errors or incorrect behavior in the
program.
3. Encapsulation: Constructors can be used to enforce encapsulation
by ensuring that the object's state is properly initialized and
validated before any other methods are called on the object.
4. Inheritance: Constructors play a critical role in inheritance. When
a subclass is created, the constructor of its superclass is
automatically called first to initialize the inherited state. This
process continues up the inheritance hierarchy until the root class's
constructor is called.
5. Polymorphism: Constructors can be used to create objects of
different types and classes, allowing for polymorphic behavior in
the program. For example, a constructor can be defined in an
abstract class to create objects of its concrete subclasses.
Overall, constructors are a critical part of the Java programming
language and are necessary for proper object initialization,
encapsulation, inheritance, and polymorphism.
Q11. How many types of constructors does Java support?
Java supports two types of constructors:
1. Default Constructor: A default constructor is a constructor that is
automatically generated by the compiler if no constructor is
explicitly defined in the class. It has no arguments and does not
perform any initialization. It is used to create an object with default
values for all its instance variables.
2. Parameterized Constructor: A parameterized constructor is a
constructor that takes one or more parameters and is explicitly
defined in the class. It is used to create an object with specific
values for its instance variables. When a parameterized constructor
is defined, the default constructor is not generated by the compiler.
Here is an example of a class with a default constructor and a
parameterized constructor:
public class Person {
String name;
int age;
// Default constructor
public Person() {
// No initialization performed
}
// Parameterized constructor
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
n this example, the class has a default constructor that does not
perform any initialization and a parameterized constructor that
takes two parameters ( and ) and initializes the instance variables
with the passed values using the keyword.
Q12. Why constructors cannot be final, static, or abstract in
Java?
In Java, constructors cannot be declared as final, static, or abstract
for several reasons:
1. Final Constructors: Constructors are used to initialize objects and
the primary purpose of a final keyword is to prevent further
modifications to a variable, method or class. A final constructor
would defeat the purpose of a constructor because if a constructor
were declared final, it would not be possible to create a subclass
and override the constructor. Therefore, final constructors are not
allowed in Java.
2. Static Constructors: Constructors are called when an object is
created, and they initialize instance variables of the object. Since
static members are associated with the class and not with objects, it
does not make sense to have a static constructor. Static initializers,
on the other hand, are used to initialize static variables and are run
once when the class is loaded, not when objects are created.
3. Abstract Constructors: An abstract class is a class that cannot be
instantiated, so if a constructor was declared abstract, it would
never be used. The abstract keyword is used to specify that a class
or method should be implemented by subclasses, but since
constructors are always implemented by the class that defines them,
it is not possible to declare a constructor as abstract.
In summary, constructors cannot be final, static, or abstract because
they have a specific purpose and behavior that does not fit with the
semantics of those keywords.
Q13. How to implement constructor chaining using the Java
super keyword?
Constructor chaining in Java is a technique that allows one
constructor to call another constructor in the same class or in a
parent class using the keyword. This technique is useful when you
want to reuse code from one constructor in another constructor or
when you want to avoid duplicating code. Here's how you can
implement constructor chaining using the keyword in Java:
1. Calling a Parent Class Constructor: You can call a constructor of
a parent class using the keyword followed by parentheses that
contain the arguments passed to the constructor. Here's an example:
public class Parent {
public Parent(int arg1, int arg2) {
// constructor code
}
}
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone(); // Shallow copy
}
}
//Copy constructor
public Main(Main emp) {
empId = emp.empId;
empName = emp.empName;
}
This Super
3. Used to access
3. Used to access parent
the current class's
class method.
methods.
4. Used for
4. Used for pointing the
pointing the current
superclass instance
class instance
Break Continue
//Copy constructor
public Main(Main emp) {
empId = emp.empId;
empName = emp.empName;
}
public void displayDetails() {
System.out.println("Employee ID:" + empId);
System.out.println("Employee Name:" + empName);
}
}
In this code, we are attempting to use the non-static variable in a
static method . This will result in a compilation error, since is not
associated with the class itself, but with instances of the class.
Q23. Why do we mark the main method as static in Java?
In Java, we mark the method as static because it allows the method
to be called without creating an instance of the class. When a Java
program is run, the JVM looks for a method with a specific
signature () to begin executing the program. Since the method is the
entry point of the program, it must be accessible without creating
an object of the class.
Marking the method as static ensures that the method belongs to the
class itself, and not to a specific instance of the class. This allows
the JVM to call the method without creating an instance of the class
first. If the method were not static, the JVM would have to create
an instance of the class to call the method, which would be
unnecessary since the method typically does not require access to
instance variables or methods.
Q24. What is Inheritance?
Inheritance is a fundamental concept in object-oriented
programming (OOP) that allows a class to inherit properties and
behavior from a parent class. In Java, inheritance is implemented
using the keyword.
When a class inherits from a parent class, it automatically includes
all the public and protected members of the parent class in its own
definition. This includes fields, methods, and nested classes. The
child class can also define its own fields and methods, and can
override the behavior of the parent class methods using the
annotation.
Inheritance creates a hierarchical relationship between classes,
where each child class is more specialized than its parent class.
This allows for code reuse and modularization, since common
functionality can be defined in a parent class and inherited by
multiple child classes.
Q25. What are the different types of inheritance in Java?
In Java, there are five types of inheritance:
1. Single inheritance: This is the most common type of inheritance,
where a subclass extends a single parent class. The subclass inherits
all the fields and methods of the parent class, and can also override
the parent class methods.
2. Multilevel inheritance: This is where a subclass inherits from a
parent class, and then another subclass inherits from that subclass.
In this way, a chain of inheritance is created, where each subclass
inherits from its immediate parent class.
3. Hierarchical inheritance: This is where multiple subclasses
inherit from a single parent class. In other words, a single-parent
class is the superclass of multiple subclasses.
4. Multiple inheritance (through interfaces): This is where a
subclass implements multiple interfaces, each of which defines a
set of methods that the subclass must implement. This allows the
subclass to inherit behavior from multiple sources, without the
potential conflicts that can arise with multiple inheritance of
implementation.
5. Hybrid inheritance: This is a combination of any two or more
types of inheritance. For example, a subclass might use single
inheritance to inherit from a parent class, and then use multiple
inheritance through interfaces to inherit from multiple interfaces.
It's important to note that Java does not support multiple
inheritance of implementation (i.e., where a subclass inherits from
multiple parent classes that define the same method with different
implementations). However, it does allow multiple inheritance
through interfaces, as described above.
Q26. Why is multiple inheritances not supported in Java?
Multiple inheritances occur when a child class inherits properties
from several other classes. Extending several classes in Java is not
possible.
Multiple inheritances have the drawback of making it difficult for
the compiler to decide which method from the child class to
execute at runtime if multiple parent classes have the same method
name.
As a result, multiple inheritances in Java are not supported. The
Diamond Problem is a well-known name for the issue. If you have
any difficulties answering these Java interview questions, please
leave a remark below.
import java.io.*;
class classP {
public void display() {
System.out.println("Class P");
}
}
class classQ {
public void display() {
System.out.println("Class Q");
}
}
class Main extends classP, classQ {
public static void main(String[] args) {
Main obj = new Main();
obj.display();
}
}
Q27. How will you implement method overloading in Java?
Method overloading is a feature in Java that allows a class to have
multiple methods with the same name, but different parameter lists.
This allows a class to provide different methods that perform
similar operations, but with different inputs.
To implement method overloading in Java, you can define multiple
methods with the same name in a class, but with different
parameters. The parameters can differ in their number, type, or
order. When you call the method, Java determines which method to
call based on the number and types of the arguments passed to the
method.
Here is an example of method overloading in Java:
public class MathUtils {
public static int add(int x, int y) {
return x + y;
}
public static double add(double x, double y) {
return x + y;
}
In this example, the class defines three methods with the same
name, , but with different parameter lists. The first method takes
two parameters and returns an result. The second method takes two
parameters and returns a result. The third method takes three
parameters and returns an result.
When you call the method, Java determines which method to call
based on the types of the arguments you pass to it. For example, if
you call , Java will call the first method, which takes two
parameters. If you call , Java will call the second method, which
takes two parameters. And if you call , Java will call the third
method, which takes three parameters.
By overloading the method with different parameter lists, the class
provides a flexible and convenient way to perform addition with
different types and numbers of inputs.
Q28. What is Polymorphism?
"One interface, many implementations" is a precise description of
polymorphism. Polymorphism is the ability to ascribe a distinct
meaning or usage to something in different situations - especially,
the ability to have many forms for an item such as a variable, a
function, or an object. There are two types of polymorphism
Compile-Time Polymorphism: Method overloading is compile-
time polymorphism
class Calculator
return a + b;
return a + b + c;
System.out.println(obj.add(15, 20));
}
}
35
80
Run time polymorphism or Dynamic
Polymorphism: Inheritance and interfaces are used to implement
runtime time polymorphism.
Q29. Can we change the scope of the overridden methods in the
subclass?
No, we cannot change the scope of the overridden methods in the
subclass. In Java, when a subclass overrides a method of its parent
class, it must provide the same method signature (i.e., same method
name, return type, and parameter list) as the parent class method.
The only thing that can be changed in the overridden method is its
implementation.
The scope of a method (i.e., its access modifier) is part of its
method signature, and changing the scope of an overridden method
in the subclass would change its signature, which would break the
inheritance contract.
For example, if a method in the superclass is declared as , the same
method in the subclass cannot be overridden with a narrower scope,
such as or . Similarly, if a method in the superclass is declared as ,
the same method in the subclass cannot be overridden with a wider
scope, such as .
However, it is possible to provide a new method in the subclass
with a different scope that has the same name as the method in the
superclass. This is not overriding, but rather method hiding.
Method hiding occurs when a subclass defines a static method with
the same name and signature as a static method in the superclass. In
this case, the subclass method "hides" the superclass method, and
the scope of the subclass method can be different from that of the
superclass method.
Q30. What is the difference between method overloading and
method overriding in Java?
In Method Overloading, method signature of the same class share
the same name but each method must have a different number of
parameters or parameters having different types and order.
Method Overloading is to “add” or “extend” more to the method’s
behavior.
It is a compile-time polymorphism.
The methods must have a different signature.
It may or may not need inheritance in Method Overloading.
In Method Overriding, the subclass has the same method with the
same name and exactly the same number and type of parameters,
and the same return type as a superclass.
Method Overriding is to “Change” the existing behavior of the
method.
It is a run time polymorphism.
The methods must have the same signature.
It always requires inheritance in Method Overriding.
Q31. What is encapsulation in Java?
}
public static Main getInstance(){
return myObj;
}
Several interfaces
A class can only extend
can be
one abstract class in the
implemented by a
case of an abstract class
single class.
System.out.println("Default speed");
}
}
6.9
25.0
StringBuffer is StringBuilder is
thread-safe not thread-safe
since it is since it is not
synchronized. It synchronized. It
indicates that indicates that
1)
two threads two threads can
can't call the call
StringBuffer StringBuilder's
functions at the methods at the
same time. same time.
StringBuffer StringBuilder
is less is more
2)
efficient than efficient than
StringBuilder. StringBuffer.
In Java 1.0, the In Java 1.5, the
StringBuffer StringBuilder
3)
class was class was
introduced introduced.
Error Exception
Indicates a severe
Indicates a less severe
system-level error
error that can be
that should not be
caught and potentially
caught or recovered
recovered from
from
incorrect usage of a
circumstances
library or API, or
outside the control
incorrect program
of the program
logic
Generally indicates a
Generally indicates a
serious problem that
recoverable problem
may require
that can be handled by
intervention by a
the program itself
system administrator
Usually can be
handled or recovered
Usually cannot be from within the
handled or recovered program, either by
from within the catching the exception
program or allowing it to
propagate up the call
stack
throw
throws keyword
keyword
To explicitly
throw an For method declaration; to
exception, use declare an exception, use
the throw the throws keyword.
keyword.
Throwing only
will not Throws can be used to
propagate propagate checked
checked exceptions.
exceptions.
Throw is
Throws is followed by
followed by an
class.
instance.
List Set
71. In Java, how will you decide when to use a List, Set, or a
Map collection
ArrayList Vector
There is no
The vector is
synchronization in the
synchronized.
Array List.
When an element is
By default, a
added to the Array List,
vector's array is
it increases its Array
doubled in size.
size by 50%.
HashMap Hashtable
HashMap is a new
Hashtable is
class introduced in
a legacy class.
JDK 1.2.
A HashMap
A TreeMap sorts the
implementation by
mappings based on
LinkedHashMap
the ascending order
maintains the insertion
of keys.
order of elements
Enumerator and
Iterator traverses the
Iterator traverse the
HashMap.
hashtable.
HashMap Hashtable
inherits AbstractMap inherits Dictionary
class. class.
HashMap TreeMap
implements Map, implements Navigabl
Cloneable, eMap, Cloneable,
and Serializable inte and Serializable inter
rfaces. faces.
HashMap allows
TreeMap allows
heterogeneous
homogeneous actual
elements because it
values as a key
does not perform
because of sorting.
sorting on keys.
A TreeMap uses
A HashMap uses
compareTo() method
equals() method to
for maintaining
compare keys.
natural ordering.
A HashMap gives
A TreeMap gives the
constant time
order of log(n) time
performance for
performance for get()
operations like get()
and put() methods.
and put().
In Java, shallow copy and deep copy are two different techniques to
copy objects. The main difference between shallow copy and deep
copy is that shallow copy only creates a new object that references
the original object's memory location, while deep copy creates a
new object with a new memory location that has the same values as
the original object.
In a shallow copy, the new object that is created shares the same
memory location as the original object, so any changes made to the
original object will also be reflected in the new object. Shallow
copy is performed using the clone() method or copy constructor,
which creates a new object and copies the references to the data
members of the original object.
In contrast, in a deep copy, a new object is created with its own
memory location and all the data members are copied to the new
object. Deep copy is performed by manually copying all the fields
of the original object into the new object or by implementing the
Serializable interface and using object serialization to create a deep
copy.
To summarize, the key difference between shallow copy and deep
copy in Java is that shallow copy creates a new object that
references the same memory location as the original object, while
deep copy creates a completely new object with its own memory
location and values that are equal to the original object's values to
maintain code reusability.
79. What is the difference between Collection and Collections
Framework in Java?
In Java, Collection and Collections Framework are related concepts
but have different meanings.
Collection is an interface in the Java programming language that
represents a group of objects, where each object is a separate entity
and can be accessed and manipulated independently of the others.
Examples of Collection classes in the Java Collections Framework
(JCF) include List, Set, and Queue.
On the other hand, the Collections Framework in Java refers to a
set of interfaces, classes, and algorithms provided by the Java
library to manipulate collections of objects. The Collections
Framework includes several core interfaces such as Collection,
List, Set, Queue, Map, and others, as well as their implementing
classes such as ArrayList, HashSet, and TreeMap.
80. Why Map interface does not extend the Collection interface
in the Java Collections Framework?
The Map interface in the Java Collections Framework (JCF) does
not extend the Collection interface because it represents a different
kind of data structure than the Collection interface.
A Collection represents a group of objects, where each object is a
separate entity and can be accessed and manipulated independently
of the others. Examples of Collection classes in the JCF include
List, Set, and Queue.
On the other hand, a Map represents a mapping between keys and
values, where each key is associated with a single value. The key-
value pairs in a Map are not considered separate entities that can be
accessed or manipulated independently of each other. Examples of
Map classes in the JCF include HashMap, TreeMap, and
LinkedHashMap.
Because Maps and Collections represent different kinds of data
structures with different characteristics and behaviors, it would not
make sense for Map to extend Collection or vice versa. However,
both interfaces do share some common methods, such as size() and
isEmpty(), which are inherited from the parent interface, Iterable.
81. What is the difference between an Iterator and a
ListIterator in Java?
Here is a table that summarizes the main differences between and
interfaces in Java:
Iterator ListIterator
Provides methods to
Provides methods check if the iteration
to check if the has more elements in
iteration has more both forward and
elements, to backward directions, to
retrieve the next retrieve the next and
element, and to previous elements, and
remove the current to add and remove
element. elements at the current
position.
Implemented by the
Implemented by
interface, which
the interface.
extends .
Queue and Stack are both data structures in Java, but they differ in
their ordering of elements and the methods used to access those
elements.
A Queue is a collection of elements in which an element is added to
the end of the queue and removed from the beginning of the queue.
It follows the "first-in, first-out" (FIFO) principle. This means that
the first element that is added to the queue will be the first one to be
removed. In Java, the Queue interface is implemented by classes
like LinkedList, PriorityQueue, and ArrayDeque.
On the other hand, a Stack is a collection of elements in which an
element is added and removed from the top of the stack. It follows
the "last-in, first-out" (LIFO) principle. This means that the last
element that is added to the stack will be the first one to be
removed. In Java, the Stack class is available in the java.util
package.
To summarize, the main difference between a Queue and a Stack is
the order in which elements are added and removed. A Queue
follows the FIFO principle, whereas a Stack follows the LIFO
principle.
85. What is a classloader?
In Java, a class loader is a part of the Java Runtime Environment
(JRE) that loads compiled Java classes into the Java Virtual
Machine (JVM). It is responsible for loading classes from their
bytecode representation and linking them into a running program.
The JVM has three built-in class loaders:
1. Bootstrap Class Loader: It is responsible for loading the core Java
classes, such as java.lang, java.util, etc. It is implemented in native
code and is a part of the JVM.
2. Extension Class Loader: It loads classes from the extension
directory, which is defined by the java.ext.dirs system property. It is
implemented in Java and is a child of the bootstrap class loader.
3. Application Class Loader: It loads classes from the classpath,
which is defined by the java.class.path system property. It is
implemented in Java and is a child of the extension class loader.
Class loaders provide a way to dynamically extend the functionality
of Java applications by allowing new classes to be loaded at
runtime. They also provide a level of security by separating the
classes of different applications or modules.
86. What is the covariant return type?
The covariant return type is a feature introduced in Java 5 that
allows a subclass method to return a subtype of the return type of
the overridden method in the superclass. In simple terms, it allows
a method in a subclass to return a more specific type than the
method it overrides in the superclass.
For example, consider a class hierarchy where is a superclass and is
a subclass. Suppose has a method called that returns an object. If
we override this method in the class and return a object instead,
then we are using covariant return types.
Here is an example:
class Animal {
public Animal getAnimal() {
return this;
}
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ImmutablePerson that = (ImmutablePerson) o;
return age == that.age && Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}
88. Can you have virtual functions in Java?
Java does not have a virtual keyword like C++ to indicate that a
method should be dynamically bound at runtime. However, in Java,
all non-private, non-static, and non-final methods are by default
virtual functions, which means that the actual method to be called
is determined at runtime based on the actual type of the object.
This is because Java uses dynamic method dispatch to resolve the
appropriate method to be executed at runtime. When a method is
invoked on an object, the JVM determines the actual type of the
object and then looks up the appropriate method implementation
for that type at runtime.
So, in Java, all non-private, non-static, and non-final methods can
be considered virtual functions, since their actual implementation is
determined at runtime based on the type of the object they are
called on.
89. Mention the uses of the synchronized block
In Java, the block is used to ensure that only one thread at a time
can execute a critical section of code. The block uses a monitor
lock to achieve this, which allows only one thread at a time to
acquire the lock and execute the code enclosed in the block.
Here are some of the common uses of the block in Java:
1. Thread safety: The block is commonly used to ensure that access
to shared resources is synchronized across multiple threads. This
helps prevent race conditions and other synchronization issues that
can occur when multiple threads access the same resource
concurrently.
2. Deadlock prevention: The block can also be used to prevent
deadlocks in multi-threaded applications. By ensuring that only one
thread at a time can acquire a lock on a shared resource, the
likelihood of two threads becoming deadlocked is reduced.
3. Performance optimization: In some cases, the block can be used
to optimize performance in multi-threaded applications. For
example, by synchronizing access to a resource only when
necessary, the overhead of locking and unlocking the resource can
be reduced, improving the overall performance of the application.
Overall, the block is a powerful tool for synchronizing access to
shared resources in multi-threaded applications, and is commonly
used in Java programs to ensure thread safety and prevent
synchronization issues.
90. Distinguish between static loading and dynamic class
loading?
In Java, class loading is the process of loading a Java class into
memory at runtime. There are two types of class loading: static
loading and dynamic loading.
1. Static loading: In static loading, classes are loaded at compile
time, and the Java compiler includes them in the byte code of the
application. This means that all the classes required by the
application are loaded into memory at startup, even if they are not
used during the execution of the program. Static loading is the
default behavior in Java.
2. Dynamic loading: In dynamic loading, classes are loaded at
runtime when they are needed. Dynamic loading is useful in
situations where classes are large or rarely used because it reduces
the memory footprint of the application. Dynamic loading is
achieved using the Java method or by creating an instance of the
class. When the method is called, the class is loaded into memory
and initialized. When the class is used, the class is loaded into
memory, but not initialized until it is used.
Overall, static loading and dynamic loading are two different
approaches to class loading in Java, and both have their own
advantages and disadvantages. Static loading is simpler and faster,
but requires more memory. Dynamic loading is more flexible and
efficient, but requires more complex programming techniques.
91. What are the different scenarios causing "Exception in
thread main"?
The following are some examples of frequent main thread
exceptions:
Exception in thread main
java.lang.UnsupportedClassVersionError: This exception occurs
when you try to run a java class that was compiled with a different
JDK version.
Exception in thread main
java.lang.NoClassDefFoundError: This exception comes in two
flavors. The first is where you give the whole name of the class,
including the.class extension. When Class is not identified, the
second situation occurs.
Exception in thread main java.lang.NoSuchMethodError:
main: When you try to launch a class that doesn't have a main
function, you'll get this exception.
Exception in thread "main"
java.lang.ArithmeticException: When an exception is thrown
from the main method, the exception is sent to the console. The
first section specifies that the main method throws clause an
custom exception, the second part publishes the custom exception
class name, and the third part displays the exception message after
a colon.
92. Explain the externalizable interface.
class Main{
void show(int a){
System.out.println("int method");
}
void show(String a){
System.out.println("string method");
}
public static void main(String[] args) {
Main s = new Main();
s.show('a');
}
}
98. What is the Java instanceOf operator?
Java instanceOf operator is a comparison operator that checks if the
object is an instance of some type of class. The return value is
either true or false. If there is no value, then it returns false. Here is
the code for the same:
99. What is the use of the System class and Runtime class?
The and classes in Java are used to interact with the operating
system and perform system-level tasks.
The class provides a set of static methods and variables that allow
you to access and modify system properties, environment variables,
and standard input/output streams. Some common uses of the class
include:
Getting and setting system properties (e.g., and )
Accessing environment variables (e.g., )
Reading from and writing to the standard input/output streams
(e.g., and )
The class provides a way to execute external processes and manage
the Java Virtual Machine (JVM) environment. Some common uses
of the class include:
Running external processes (e.g., )
Terminating the JVM (e.g., )
Getting the amount of free and total memory available to the JVM
(e.g., and )
Both the and classes are part of the Java core API and are widely
used in Java applications to perform system-level tasks.
100. What is the difference between abstraction and
encapsulation?
Abstraction Encapsulation
Abstraction is the
The technique of
process of hiding
encapsulating code
implementation
and data into a single
details from the user
unit is known as
and only displaying
encapsulation.
functionality.
Abstraction refers to
Encapsulation refers
the use of interfaces
to the use of setters
and abstract classes to
and getters to hide
hide implementation
data.
difficulties.
C++ Java
Platform-dependent. Platform-independent.
Designed as a support
Designed for
network computing
systems and
with a goal of being
applications
easy to use and
programming. It is
accessible to a broader
an extension of C.
audience.
Doesn't support
Supports multiple
multiple inheritance
inheritance.
through class.
Uses a single
Creates a new inheritance tree always
inheritance tree because all classes are
always. the child of an object
class in Java.
variable of objects
Uses dynamic
allocation where there
Always reserved in a
is no fixed pattern for
LIFO (last in first
allocating and de-
out) order
allocating blocks in
memory
with the same name in a single class but the arguments are
different.
Overriding happens in inheritance. For example: when two
methods have the same name and same signature, one is parent
class and another is child class. Here the method of child class is
overridden to make sure that is any changes are done to the parent
class, the child class also gets changed accordingly.
Q12. What are the various access specifiers in Java?
Access specifiers are the keywords used to define the access scope
of the method, class, or variable in Java. There are four access
specifiers:
Public: Can be accessed by any class or method.
Protected: Can be accessed by the class of the same package, by
the sub-class of this class, or within the same class.
Default: Are accessible within the package only. All the variables,
classes, and methods are of default scope.
Private: Class, methods, or variables defined as private can be
accessed within the class only.
Q13. Differentiate between Array list and vector in Java.
ArrayList Vector
Stands for
Stands for
Java Stands for
Java
Runtime Java Virtual
Developm
Environmen Machine.
ent Kit.
t.
It is a It is an It is a
software implementat platform-
developm ion of JVM independent
ent kit that
develops
applicatio and is a type
abstract
ns in Java. of software
machine that
Along package that
has three
with JRE, provides
notions in
the JDK class
the form of
also libraries of
specification
consists of Java, JVM,
s. It
various and various
describes the
developm other
requirement
ent tools components
of JVM
(Java for running
implementati
Debugger, Java
on.
JavaDoc, applications.
compilers,
etc.)
Assists in
executing
Creates an Providing all
codes. It
environment of the
primarily
for the implementati
functions
execution of ons to the
in
code. JRE.
developm
ent.
Platform-
Platform- Platform-
dependent
dependent. independent.
.
Q16. Define the term 'Double Brace Initialization' in Java
Double Brace Initialization is a term that refers to the combination
of two independent processes. It has two braces. The first brace
creates an anonymous inner class. The second brace is an
initialization block. When used together, it is known as Double
Brace Initialization.
Advantages:
Has lesser lines of code compared to the native way of creation and
initialization.
The code is more readable.
Creation and Initialization are done in the same expression.
Disadvantages:
It is obscure.
Creates an extra class every time.
Holds a hidden reference to the enclosing instance that may cause
memory leaks.
Q17. What are the advantages of packages in Java?
Packages in Java are used to group related classes. Following are
the advantages of packages in Java.
Avoid name clashes.
Provides easy access control.
Makes it easier to locate the related classes.
Q18. Explain object-oriented paradigm
The object-oriented paradigm is a programming paradigm that aims
to incorporate the advantages of modularity and reusability. It is
based on objects having data and methods defined in the class to
which it belongs. Following are the features of the object-oriented
paradigm:
Focus on data with methods to operate upon the data of the object.
Follows the bottom-up approach in program design.
Includes concepts like encapsulation and abstraction which hides
the complexities from the user and highlights only the functionality.
Examples of the object-oriented paradigm are C++, Python, C#,
etc.
Q19. What is the major difference between an object-oriented
programming language and an object-based programming
language?
The major difference between an object-oriented programming
language and an object-based programming language is as follows:
Object-oriented Object-based
Programming Programming
Language Language
Characteristics of
object-oriented
All features of object-
programming such
oriented programming
as inheritance and
are supported.
polymorphism are
not supported.
Have built-in
Don't have a built-in
objects. Example:
object. Example: C+
JavaScript has a
+.
window object.
Cannot be
overridden by Can be overridden by
compile time dynamic binding.
binding.
Multi-level Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Java concepts.
More Reads:
1. Important Accenture Interview Questions That You Must Not
Ignore!
2. Most Common Programming Interview Questions With Answers
2022
3. Top 50 OOPs Interview Questions With Answers 2022
4. 50 Frequently Asked LinkedList Interview Questions With Answers
2022
Top 15+ Difference Between C++ And Java Explained!
(+Similarities)
There are multiple differences between C++ and Java that you
must understand when deciding which language to work with.
Some common points for Java Vs. C++ includes the syntax,
platform dependence/ independence, memory management, and
more.
17 mins read
memory
manageme
nt with new memory
and delete management
operators. through
Requires automatic
explicit garbage
allocation collection
Manageme and feature.
nt deallocatio Memory is
n of reclaimed by
memory. the JVM
However, when objects
there is are no
allowance longer in
of dynamic use.
memory
allocation.
However,
factors like
compilers,
operating cross-
system platform
APIs, compatibilit
hardware y without
architecture recompilatio
, and third- n. That is,
party the Java
libraries interpreter
can executes the
introduce bytecode at
platform runtime.
dependenci
es in C++
programs.
for
achieving
abstraction.
Slightly
slower
Generally, execution
it has faster speed due to
execution bytecode
speed, is interpretatio
closer to n and
Performan hardware, garbage
ce and has collection
more overhead.
control JIT
over compilation
system helps narrow
resources. the
performance
gap.
being an
object
paradigms. except for
primitive
data types.
Exception
handling is Exception
available b handling is
ut not an integral
mandatory. part of the
This way, language.
the All
Exception community exceptions
Handling of must be
developers/ caught or
programme declared,
rs have promoting
more robust error-
control handling
over error practices.
handling.
essential
functionaliti
es such as
range of
networking,
data
I/O
structures
operations,
and
concurrency,
algorithms.
and GUI
development
.
Compiled
directly Compiled
into into
machine- platform-
Compilatio
specific independent
n vs.
executable bytecode,
Interpretat
binaries, which is
ion
i.e., direct interpreted
machine by the JVM
code at runtime.
execution.
nt,
allowing manipulatio
direct n, enhancing
access to security and
memory stability.
addresses.
Typically
used with
Supports a IDEs like
wide range Eclipse,
of IDEs IntelliJ
Developme and text IDEA, or
nt editors, NetBeans,
Environme with offering
nt compilers integrated
available debugging,
for various profiling,
platforms. and
development
tools.
widely used
in various
domains.
Java uses a
C++ single
always inheritance
Inheritanc creates a tree; all
e Tree new classes are
inheritance children of
tree. the Object
class.
enterprise-
grade
applications
and web
development
.
Java
C++
supports the
Unsigned doesn't
>>>
Right Shift support the
operator for
>>> >>>
unsigned
operator.
right shift.
Java is less
C++ is
interactive
Hardware closer to
with
hardware.
hardware.
Java has no
C++
virtual
supports
keyword; all
Virtual the virtual
non-static
Keyword keyword fo
methods are
r method
virtual by
overriding.
default.
Advantages Disadvantages
Advantages Disadvantages
Platform Performance
Independence: Java's Overhead: Java's
"write once, run platform
anywhere" principle independence and
allows for easy automatic memory
deployment on management come
different platforms with a performance
without modification. overhead compared
Object-Oriented: Jav to lower-level
a's OOP features languages like C++.
promote code Complexity: Java's
reusability, extensive feature set
modularity, and and ecosystem can
maintainability. lead to a steep
Automatic Memory learning curve for
Management: Java's beginners.
garbage collection Resource
mechanism reduces Consumption: Java
the risk of memory applications may
leaks and simplifies consume more
memory management. system resources
Robustness: Java's (such as memory
strong type system, and CPU) compared
exception handling,
and built-in security
features enhance to lightweight
application reliability languages.
and robustness. Limited Low-Level
Large Access: Java's
Ecosystem: Java abstraction layer
boasts a vast shields developers
ecosystem of libraries, from low-level
frameworks, tools, and system access,
community support, limiting performance
accelerating optimization in
development and certain scenarios.
solving complex
problems efficiently.
int main() {
// Define an integer variable 'i' with value 5
int i = 5;
return 0;
}
Output:
Value is 5
The new value: 6
Code Explanation:
As mentioned in the code comment, we first create a variable called
i, of integer data type and assign a value of 5 to it. The C++
program then prints the value to the console using the cout
command. After that, we increment the value of the i by 1 (using
increment operator) and again print it to the console.
Java Program to Increment the Value of a Variable
Source Code Example:
public class IncrementDemo {
and polymorphism.
Conclusion
Both C++ and Java are powerful and popular programming
languages with their own sets of advantages and trade-offs. C++
excels in performance-critical applications and systems
programming, offering unparalleled control over hardware
resources. On the other hand, Java's platform independence,
automatic memory management, and ease of learning make it well-
suited for enterprise applications, web development, and cross-
platform software.
Ultimately, the choice between C++ and Java depends on the
specific requirements of the project, the target platform, and the
developer's expertise and preferences. Understanding the
differences between C++ and Java, which we have outlined in this
article, can help developers make informed decisions when
selecting the appropriate language for their next endeavour.
Frequently Asked Questions
Q. Is C++ more powerful than Java?
Both C++ and Java have their strengths, and determining which is
"more powerful" depends on the context of use. C++ is often
considered a more powerful language in terms of performance and
low-level programming control due to its closer-to-the-hardware
nature, allowing developers to directly manage memory and
optimize code for speed and efficiency. This makes C++ a preferred
choice for resource-intensive applications like game development,
operating systems, and system programming.
On the other hand, Java is renowned for its portability, ease of use,
and robust ecosystem, making it a popular language choice for
enterprise-level software development, web applications, and
Android app development. Additionally, Java's garbage collection
mechanism simplifies memory management, reducing the
likelihood of memory leaks and buffer overflows compared to C++.
Ultimately, the choice between C++ and Java depends on the
specific requirements of the project and the trade-offs between
performance, development time, and ease of maintenance.
Q. Which is better for beginners? C++ or Java?
For beginners, Java is often considered a better choice due to its
simpler syntax, automatic memory management, and extensive
documentation. Java's object-oriented nature and built-in libraries
make it easier for beginners to grasp programming fundamentals
and build applications more quickly. Additionally, Java's platform
independence and vast community support provide ample resources
and tutorials for beginners to learn from. While C++ offers greater
control and a deeper understanding of computer systems, its syntax
and concepts can be more complex for beginners to grasp initially,
making Java a more accessible starting point for novice
programmers.
Q. Java vs C++ which is better for competitive programming?
For competitive programming, both Java and C++ have their
advantages. C++ is often considered a preferred language due to its
faster execution speed, which can be crucial for solving time-
sensitive problems in competitive programming contests. Its ability
to directly manage memory and optimize code for efficiency makes
it a popular choice among competitive programmers. Additionally,
C++ provides access to powerful standard template libraries (STL),
which offer a wide range of data structures and algorithms ready
for use.
Q. Does Java support manual memory management like C++?
No, Java does not support manual memory management like C++.
In C++, software developers have explicit control over memory
allocation and deallocation using new and delete operators, which
can lead to memory leaks and segmentation faults if not managed
carefully.
In contrast, Java features automatic memory management through
garbage collection. The Java Virtual Machine (JVM) automatically
handles memory allocation and deallocation, reclaiming memory
from objects that are no longer in use. This process, known as
garbage collection, helps prevent memory leaks and reduces the
risk of runtime errors related to memory management. By
abstracting away manual memory management, Java simplifies the
development process and promotes safer, more reliable code.
Test Your Skills: Quiz Time
Click here to view quiz
Click here to view quiz
Click here to view quiz
By now, you must know all about the difference between C++ and
Java programming languages. You might also be interested in
reading:
1. Difference Between Java And JavaScript Explained In Detail!
2. Difference Between Java And Python Decoded
3. Top 100+ Java Interview Questions And Answers (2024)
4. Difference Between C And C++ Explained With Code Example
5. 51 C++ Interview Questions For Freshers & Experienced (With
Answers)