java solve Final
java solve Final
1) Abstract class can have abstract Interface can have only abstract methods.
and non-abstract methods. Since Java 8, it can have default and static
methods also.
3) Abstract class can have final, non- Interface has only static and final variables.
final, static and non-static variables.
4) Abstract class can provide the Interface can't provide the implementation
implementation of interface. of abstract class.
8) A Java abstract class can have class Members of a Java interface are public by
members like private, protected, etc. default.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Java garbage collection is the process by which Java programs perform automatic
memory management. Java programs compile to bytecode that can be run on a Java
Virtual Machine, or JVM for short.
What's the difference between the methods sleep () and wait ()?
Wait () method releases lock during Synchronization. Sleep () method does not
release the lock on object during Synchronization.
What are the differences between static and non-static nested classes?
A non-static nested class has full access to the members of the class within which
it is nested. A static nested class does not have a reference to a nesting instance,
so a static nested class cannot invoke non-static methods or access non-static
fields of an instance of the class within which it is nested.
Inheritance is one of the key features of OOP that allows us to create a new class
from an existing class.
Define interface
Define deadlock
Deadlock in Java is a condition where two or more threads are blocked forever,
waiting for each other. This usually happens when multiple threads need the same
locks but obtain them in different orders.
Java byte streams are used to perform input and output of 8-bit bytes
Common examples include dividing by zero, referencing missing files, calling invalid
functions, or not handling certain input correctly.
Yes, we can execute a java program without a main method by using a static block.
Static block in Java is a group of statements that gets executed only once when the
class is loaded into the memory by Java Class Loader
Properties
Example. In the above example, the Student class constructor is overloaded with
two different constructors, I.e., default and parameterized. Here, we need to
understand the purpose of constructor overloading
When we extend Thread class, each of our thread creates unique object and
associate with it. When we implements Runnable, it shares the same object to
multiple threads
Write a java program, which takes a message from a user and count the number
of vowels, consonant, and extra characters
PROGRAMME CODE-
import java.util.Scanner;
class Assignment{
String p=a.nextLine();
String q=p.toLowerCase();
System.out.println(q);
char c=q.charAt(i);
if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){
++vow;
++cons;
++digit;
++space;
What is the difference between the character stream and byte stream?
The main difference between Byte Stream and Character Stream in Java is that the
Byte Stream helps to perform input and output operations of 8-bit bytes while
the Character Stream helps to perform input and output operations of 16-bit
Unicode. A stream is a sequence of data that is available over time
Finally defines a block of code we use along with the try keyword. It defines code
that's always run after the try and any catch block, before the method is completed.
How to swap two numbers without using temp variable using java?
import java.io.*;
class Geeks {
public static void main(String a[])
{
int x = 10;
int y = 5;
x = x + y;
y = x - y;
x = x - y;
System.out.println("After swapping:"
+ " x = " + x + ", y = " + y);
}
}
Parame
String StringBuffer StringBuilder
ter
Storage String Pool Heap Heap
Mutabil
Immutable Mutable Mutable
ity
Not used in a Used in a multi- Used in a single-
Thread
threaded threaded threaded
Safe
environment environment environment
Slower than
Perfor Faster than
Slow StringBuilder but
mance StringBuffer
faster than String
String var
=“Edureka”; StringBuffer var StringBuilder var
Syntax String = new StringBuffer( = new StringBuilder(
var=new String(“E "Edureka"); "Edureka");
dureka”);
Differentiate between component class and container class
The class Component is the abstract base class for the non-menu user-interface
controls of AWT. A component represents an object with graphical representation.
The class Container is the superclass for the containers of AWT.
The final keyword can be used with class method and variable. A final class cannot
be inherited, a final method cannot be overridden and a final variable cannot be
reassigned.
The finally keyword is used to create a block of code that follows a try block. A
finally block of code always executes, whether or not an exception has occurred.
Using a finally block allows you to run any cleanup-type statements that you just
wish to execute, despite what happens within the protected code.
The finalize() method is used just before object is destroyed and can be called just
prior to object creation.
To stop a class from being extended, the class declaration must explicitly say it
cannot be inherited. This is achieved by using the "final" keyword:
Thread creation by extending the Thread class. We create a class that extends the
java. lang. Thread class. ...
Thread creation by implementing the Runnable Interface. We create a new class
which implements java. lang. Runnable interface and override run() method. ...
Thread Class vs Runnable Interface.
JVM wait until user threads to finish The JVM will’t wait for daemon threads to
their work. It never exit until all user finish their work. The JVM will exit as soon
threads finish their work. as all user threads finish their work.
JVM will not force to user threads for If all user threads have finished their work
terminating, so JVM will wait for user JVM will force the daemon threads to
threads to terminate themselves. terminate
User threads are created by the Mostly Daemon threads created by the
application. JVM.
Mainly user threads are designed to do Daemon threads are design as to support
some specific task. the user threads.
User threads are foreground threads. Daemon threads are background threads.
User threads are high priority threads. Daemon threads are low priority threads.
Errors Exceptions
There are five methods of an applet life cycle, and they are:
init(): The init() method is the first method to run that initializes the applet. It can
be invoked only once at the time of initialization. The web browser creates the
initialized objects, i.e., the web browser (after checking the security settings) runs
the init() method within the applet.
start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from one tab to another in
the browser. It is in an inactive state until the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that
page, the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage
is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
Describe with example how to implement call be value and call by reference
concept in java
In case of call by value original value is not changed. Let's take a simple example:
class Operation{
int data=50;
}
}
download this example
Output:before change 50
after change 50
class Operation2{
int data=50;
JDBC API: JDBC API provides various interfaces and methods to establish easy
connection with different databases.
javax.sql.*;
java.sql.*;
2) JDBC Test suite: JDBC Test suite facilitates the programmer to test the various
operations such as deletion, updation, insertion that are being executed by the JDBC
Drivers.
3) JDBC Driver manager: JDBC Driver manager loads the database-specific driver into
an application in order to establish the connection with the database. The JDBC Driver
manager is also used to make the database-specific call to the database in order to do
the processing of a user request.
4) JDBC-ODBC Bridge Drivers: JDBC-ODBC Bridge Drivers are used to connect the
database drivers to the database. The bridge does the translation of the JDBC method
calls into the ODBC method call. It makes the usage of the sun.jdbc.odbc package that
encompasses the native library in order to access the ODBC (Open Database
Connectivity) characteristics.
2017
What is JDBC ResultSet
The java. sql. ResultSet interface represents the result set of a database query. A
ResultSet object maintains a cursor that points to the current row in the result set.
The term "result set" refers to the row and column data contained in a ResultSet
object.
What is an Applet
Java applets are used to provide interactive features to web applications and can be
executed by browsers for many platforms. They are small, portable Java programs
embedded in HTML pages and can run automatically when the pages are viewed.
Java is Platform Neutral because the same Java code will run on multiple platforms
(Operating Systems) without modification, provided that the code does not
intentionally put any specific demands on the system, holding true to the slogan,
"Write Once, Run Anywhere" .
Command line arguments are nothing but simply arguments that are specified after
the name of the program in the system's command line, and these argument values
are passed on to your program during program execution
to control program from outside instead of hard coding those values inside the code
For example, if your program processes data read from a file, then you can pass the
name of the file to your program, rather than hard-coding the value in your source
code.
What is inheritance and how does it help us to create new classes quickly
Inheritance is one of the key features of OOP that allows us to create a new class
from an existing class
The idea behind the inheritance to create new classes , that are built upon
existing classes . When we inherit from an existing classes , we can reuse methods
fields of the parent class . Moreover we can add. new methods in our current
class also
The subclass inherits the attributes and methods of the superclass. Now, if the
same method is defined in both the superclass and the subclass, then the method
of the subclass class overrides the method of the superclass. This is known as
method overriding.
What is an interface
Without bothering about the implementation part, we can achieve the security of the
implementation.
In Java, multiple inheritance is not allowed, however, you can use an interface to
make use of it as you can implement more than one interface.
An interface contains variables and methods like a class but the methods in an
interface are abstract by default unlike a class. Multiple inheritance by interface
occurs if a class implements multiple interfaces or also if an interface itself
extends multiple interfaces.
New − A new thread begins its life cycle in the new state. It remains in this state
until the program starts the thread. It is also referred to as a born thread.
Runnable − After a newly born thread is started, the thread becomes runnable. A
thread in this state is considered to be executing its task.
Waiting − Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. Thread transitions back to the
runnable state only when another thread signals the waiting thread to continue
executing.
Timed Waiting − A runnable thread can enter the timed waiting state for a
specified interval of time. A thread in this state transitions back to the runnable
state when that time interval expires or when the event it is waiting for occurs.
Finally block
finally defines a block of code we use along with the try keyword. It defines code
that's always run after the try and any catch block, before the method is
completed
Distinguish between init() and start() method of applet
It is also called to restart an applet after it has been stopped. Note that init( ) is
called once i.e. when the first time an applet is loaded whereas start( ) is called
each time an applet's HTML document is displayed onscreen. So, if a user leaves a
web page and comes back, the applet resumes execution at start( ).
2018
Features of Java
Simple. Java is easy to learn and its syntax is quite simple, clean and easy to
understand. ...
Object Oriented. In java, everything is an object which has some data and behaviour.
...Robust. ...
Platform Independent. ...
Secure. ...
Multi Threading. ...
Architectural Neutral. ...
Portable.
When we declare a member of a class as static it means no matter how many objects
of the class are created, there is only one copy of the static member. A static member
is shared by all objects of the class. All static data is initialized to zero when the first
object is created, if no other initialization is present.
List the names of some Java API packages with their applications.
Paini
S.
No. Class Object
Class does not contain any Each object has its own values,
values which which are
7 can be associated with the field. associated with it.
FileInputStream FileReader
Reader is Character
Stream is a byte-based object that can read Based, it can be used to
and write bytes. read or write characters.
FileReader is Character
FileInputStream is Byte Based, it can be used Based, it can be used to
to read bytes. read characters.
Reader is used to
Stream is used to binary input/output character input/output
Output:
2019
What are the benefits of object-oriented programming
The Java Development Kit (JDK) is a software development environment used for
developing Java applications and applets. It includes the Java Runtime Environment
(JRE), an interpreter/loader (java), a compiler (javac), an archiver (jar), a
documentation generator (javadoc) and other tools needed in Java development.
Java has a garbage collection mechanism that automatically frees up memory. The
mechanism also helps programmers to recover unused memory easier and more
securely. This system provides a transparent allocation protocol that guarantees the
integrity of every program execution process.
Public
It is an Access modifier, which specifies from where and who can access the method.
Making the main() method public makes it 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.
Static
Void
main
It is the name of the Java main method. It is the identifier that the JVM looks for as
the starting point of the java program. It’s not a keyword.
Explain Method Overloading with an example
In Java, two or more methods may have the same name if they differ in parameters
(different number of parameters, different types of parameters, or both). These
methods are called overloaded methods and this feature is called method
overloading. For example:
form of inheritance
Single level inheritance
As the name suggests, this type of inheritance occurs for only a single class. Only
one class is derived from the parent class.
Multi-level Inheritance
The multi-level inheritance includes the involvement of at least two or more than
two classes. One class inherits the features from a parent class and the newly
created sub-class becomes the base class for another new class.
Hierarchical Inheritance
The type of inheritance where many subclasses inherit from one single class is
known as Hierarchical Inheritance.
Multiple Inheritance
Multiple inheritances is a type of inheritance where a subclass can inherit features
from more than one parent class.
Write the name of any two most commonly used String methods.
Method Description
codePointBefore() Returns the Unicode of the character before the specified index
contentEquals() Checks whether a string contains the exact same sequence of chara
specified CharSequence or StringBuffer
copyValueOf() Returns a String that represents the characters of the character arra
equals() Compares two strings. Returns true if the strings are equal, and false
format() Returns a formatted string using the specified locale, format string,
arguments
getBytes() Encodes this String into a sequence of bytes using the named chars
result into a new byte array
indexOf() Returns the position of the first found occurrence of specified chara
string
lastIndexOf() Returns the position of the last found occurrence of specified chara
string
matches() Searches a string for a match against a regular expression, and retu
matches
offsetByCodePoints() Returns the index within this String that is offset from the given ind
codePointOffset code points
regionMatches() Tests if two stri
ng regions are equal
replace() Searches a string for a specified value, and returns a new string whe
specified values are replaced
replaceFirst() Replaces the first occurrence of a substring that matches the given
expression with the given replacement
replaceAll() Replaces each substring of this string that matches the given regula
with the given replacement
We can declare a method as final, once you declare a method final it cannot be
overridden. So, you cannot modify a final method from a sub class. The main
intention of making a method final would be that the content of the method should
not be changed by any outsider.
Class Interface
import java.util.*;
// Main Class
class GFG {
String userName;
// Display message
// nextInt() method
userName = myObj.nextLine();
}
}
Package create
Applications can access all kinds Applets can only access the browser
of resources available on the specific services. They don’t have
system. access to the local system.
An application program is
needed to perform some task An applet program is needed to
directly for the user. perform small tasks or the part of it.
Create a try block that is likely to generate three types of exception and then
incorporate necessary
catch blocks to catch and handle them appropriately.
Paini
2021
Run-Time Polymorphism:
Whenever an object is bound with the functionality at run time, this is known as
runtime polymorphism. The runtime polymorphism can be achieved by method
overriding.
Method Overloading Method Overriding
S.NO
In method overloading,
methods must have the same In method overriding, methods
name and different must have the same name and
5. signatures. same signature.
Multithreading in Java
Thread creation by extending the Thread class. We create a class that extends the
java. lang. Thread class. ...
Thread creation by implementing the Runnable Interface. We create a new class
which implements java. lang. Runnable interface and override run() method. ...
Thread Class vs Runnable Interface
There are five methods of an applet life cycle, and they are:
init(): The init() method is the first method to run that initializes the applet. It can
be invoked only once at the time of initialization. The web browser creates the
initialized objects, i.e., the web browser (after checking the security settings) runs
the init() method within the applet.
start(): The start() method contains the actual code of the applet and starts the
applet. It is invoked immediately after the init() method is invoked. Every time the
browser is loaded or refreshed, the start() method is invoked. It is also invoked
whenever the applet is maximized, restored, or moving from one tab to another in
the browser. It is in an inactive state until the init() method is invoked.
stop(): The stop() method stops the execution of the applet. The stop () method is
invoked whenever the applet is stopped, minimized, or moving from one tab to
another in the browser, the stop() method is invoked. When we go back to that
page, the start() method is invoked again.
destroy(): The destroy() method destroys the applet after its work is done. It is
invoked when the applet window is closed or when the tab containing the webpage
is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.
paint(): The paint() method belongs to the Graphics class in Java. It is used to draw
shapes like circle, square, trapezium, etc., in the applet. It is executed after the start()
method and when the browser or applet windows are resized.
In Java, static members are those which belongs to the class and you can access
these members without instantiating the class.
Vector is a sequential container to store elements and not index based. Array
stores a fixed-size sequential collection of elements of the same type and it is
index based.
Difference between super() and this() in java. super() as well as this() both are
used to make constructor calls. super() is used to call Base class's constructor(i.e,
Parent's class) while this() is used to call current class's constructor. super() is use
to call Base class's(Parent class's) constructor.
What is a daemon thread
2) String is slow StringBuffer is fast and consumes less memory when we concatenate t stri
and consumes
more memory
when we
concatenate
too many
strings because
every time it
creates new
instance.
3) String class StringBuffer class doesn't override the equals() method of Object class.
overrides the
equals()
method of
Object class. So
you can
compare the
contents of two
strings by
equals()
method.
What is an exception
What is serialization
To serialize an object means to convert its state to a byte stream so that the byte
stream can be reverted back into a copy of the object
What is casting
Type casting is when you assign a value of one primitive data type to another
type
The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI)
programming.
What is package
https://www.javatpoint.com/types-of-exception-in-java
Wait() method releases lock during Synchronization. Sleep() method does not
release the lock on object during Synchronization
Overloading occurs when two or more methods in one class have the same
method name but different parameters. Overriding occurs when two methods
have the same method name and parameters. One of the methods is in the
parent class, and the other is in the child class.
Java anonymous inner class is an inner class without a name and for which only a
single object is created. An anonymous inner class can be useful when making an
instance of an object with certain "extras" such as overloading methods of a class
or interface, without having to actually subclass a class.
public final void notify() public final void notifyAll() public final void wait()
the benefits of exception handling are as follows, (a) Exception handling can
control run tune errors that occur in the program. (b) It can avoid abnormal
termination of the program and also shows the behavior of program to users. (d)
It can separate the error handling code and normal code by using try-catch block
What are three ways in which a thread can enter the waiting stat
A thread can enter the waiting state by invoking its sleep() method, by blocking
on I/O,by unsuccessfully attempting to acquire an object's lock, or by invoking an
object's wait()method. It can also enter the waiting state by invoking its
(deprecated) suspend() method.
A Wrapper class is a class whose object wraps or contains primitive data types.
When we create an object to a wrapper class, it contains a field and in this field,
we can store primitive data types
Package create
https://www.geeksforgeeks.org/how-to-create-a-package-in-java/
4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.
What is JVM
The Java Virtual Machine (JVM) is the runtime engine of the Java Platform, which
allows any program written in Java or other language compiled into Java
bytecode to run on any computer that has a native JVM
Why java is called “PLATFORM INDEPENDENT LANGUAGE”.
Java is platform-independent because the same java program can run on any
operating system.
What is AWT
Write a program in Java that stores information in the array and then sort
the array.
//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println();
//Displaying elements of array after sorting
System.out.println("Elements of array sorted in ascending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
Output:
Synchronized block is used to lock an object for any shared resource. Scope of
synchronized block is smaller than the method. A Java synchronized block doesn't
allow more than one JVM, to provide access control to a shared resource
contructor
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created.
https://www.programiz.com/cpp-programming/constructor-
overloading#:~:text=Constructors%20can%20be%20overloaded%20in,the
%20corresponding%20constructor%20is%20called.
It is achieved by function
overloading and operator It is achieved by virtual
4 overloading. functions and pointers.
Read definition
State why public, static void and String args[] is used in “public static void
main (String args [])”
String[] args It stores Java command-line arguments and is an array of
type java.lang.String class. Here, the name of the String array is args but it is
not fixed and the user can use any name in place of it.