[go: up one dir, main page]

0% found this document useful (0 votes)
3 views41 pages

java solve Final

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)
3 views41 pages

java solve Final

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
You are on page 1/ 41

2016

What's the difference between an interface and an abstract class?

Abstract class Interface

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.

2) Abstract class doesn't support Interface supports multiple inheritance.


multiple inheritance.

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.

5) The abstract keyword is used to The interface keyword is used to declare


declare abstract class. interface.

6) An abstract class can extend An interface can extend another Java


another Java class and implement interface only.
multiple Java interfaces.

7) An abstract class can be extended An interface can be implemented using


using keyword "extends". keyword "implements".

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();
} }

Explain the garbage collection technique in Java

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.

Explain the usage of Java packages.

A package in Java is used to group related classes. Think of it as a folder in a file


directory. We use packages to avoid name conflicts, and to write a better
maintainable code.

What is mutable object and immutable object?

Simple put, a mutable object can be changed after it is created, and an


immutable object can't. Objects of built-in types like (int, float, bool, str, tuple,
Unicode) are immutable. Objects of built-in types like (list, set, dict) are mutable.
Custom classes are generally mutable.

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.

Differentiable between break and continue statements

break Statement Continue Statement


The Break statement is used to exit from The continue statement is not used to
the loop constructs. exit from the loop constructs.
The break statement is usually used with The continue statement is not used with
the switch statement, and it can also use the switch statement, but it can be used
it within the while loop, do-while loop, within the while loop, do-while loop, or
or the for-loop. for-loop.
When a break statement is encountered When the continue statement is
then the control is exited from the loop encountered then the control
construct immediately. automatically passed from the
beginning of the loop statement.
Syntax: break; Syntax: continue;
What is inheritance?

Inheritance is one of the key features of OOP that allows us to create a new class
from an existing class.

Define interface

An interface is declared by using the interface keyword. It provides total abstraction;


means all the methods in an interface are declared with the empty body, and all the
fields are public, static and final by default.

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.

Distinguish between component and container

A component represents an object with graphical representation. The class Container


is the superclass for the containers of AWT. The container object can contain other
AWT components

What are Byte Stream in Java?

Java byte streams are used to perform input and output of 8-bit bytes

List any three common run time errors

Common examples include dividing by zero, referencing missing files, calling invalid
functions, or not handling certain input correctly.

Java program can be possible without main method

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

Why is Java Architectural Neutral?

Java is architecture neutral because there are no implementation dependent features,


for example, the size of primitive types is fixed
What is a constructor?

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.

Properties

An interface cannot have the constructor.


Constructors cannot be private.
A constructor cannot be abstract, static, final, native, strictfp, or synchronized.
A constructor can be overloaded.
Constructors cannot return a value.
Constructors do not have a return type; not even void.

Give an example of constructor overloading in java.

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

Difference between extends Thread vs implements Runnable in Java?

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{

public static void main(String[] args){

Scanner a=new Scanner(System.in);

int vow=0,cons=0,digit=0, space=0;

String p=a.nextLine();

String q=p.toLowerCase();
System.out.println(q);

for(int i=0; i<q.length();++i)

char c=q.charAt(i);

if(c=='a'||c=='e'||c=='i'||c=='o'||c=='u'){

++vow;

else if(c >= 'a' && c <= 'z'){

++cons;

else if (c >= '0' && c <= '9') {

++digit;

else if (c== ' '){

++space;

System.out.println("Vowels: " + vow);

System.out.println("Consonants: " + cons);

System.out.println("Digits: " + digit);

System.out.println("White spaces: " + 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

What is the use of “finally” keyword

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);
}
}

Difference String, String Buffer and String Builder in Java

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.

Run-Time Polymorphism: Whenever an object is bound with the functionality at run


time, this is known as runtime polymorphism

Compare and contrast overloading and overriding methods with proper


examples

Method Overloading Method Overriding


S.NO

Method overloading is a Method overriding is a run-time


1. compile-time polymorphism. polymorphism.

It is used to grant the specific


implementation of the method
It helps to increase the which is already provided by its
2. readability of the program. parent class or superclass.

It is performed in two classes


3. It occurs within the class. with inheritance relationships.

Method overloading may or Method overriding always needs


4. may not require inheritance. inheritance.

In method overloading, In method overriding, methods


methods must have the same must have the same name and
5. name and different signatures. same signature.

In method overloading, the


return type can or can not be In method overriding, the return
the same, but we just have to type must be the same or co-
6. change the parameter. variant.
Write short notes on Final, finally and finalize with example.

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.

How can a programmer define a class that cannot be inherited

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:

How to use Multiple Threads in Java – example

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.

Difference between Daemon Thread vs User Thread in Java?

User Thread Daemon Thread

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.

Its life independent. Its life depends on user threads.

What is the difference between error and exception in java

Errors Exceptions

We can recover from exceptions by


Recovering from Error is not either using try-catch block or throwing
possible. exceptions back to the caller.

All errors in java are Exceptions include both checked as well


unchecked type. as unchecked type.

Errors are mostly caused by


the environment in which Program itself is responsible for causing
program is running. exceptions.

Errors can occur at compile


time as well as run time.
Compile Time: eg Syntax Error All exceptions occurs at runtime but
checked exceptions are known to the
Run Time: Logical Error.
compiler while unchecked are not.

They are defined in They are defined in java.lang.Exception


java.lang.Error package. package
Describe different stage of life cycle of an Applet

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;

void change(int data){


data=data+100;//changes will be in the local variable only
}

public static void main(String args[]){


Operation op=new Operation();

System.out.println("before change "+op.data);


op.change(500);
System.out.println("after change "+op.data);

}
}
download this example
Output:before change 50
after change 50

Another Example of call by value in java

In case of call by reference original value is changed if we made changes in the


called method. If we pass object in place of any primitive value, original value will
be changed. In this example we are passing object as a value. Let's take a simple
example:

class Operation2{
int data=50;

void change(Operation2 op){


op.data=op.data+100;//changes will be in the instance variable
}
public static void main(String args[]){
Operation2 op=new Operation2();

System.out.println("before change "+op.data);


op.change(op);//passing object
System.out.println("after change "+op.data);
}
}
download this example
Output:before change 50after change 150
What is unreachable catch block error? With example
A block of statements to which the control can never reach under any case can
be called as unreachable blocks. Unreachable blocks are not supported by Java. The
catch block mentioned with the reference of Exception class should and must be
always last catch block because Exception is the superclass of all exceptions.

What is the difference between ClassNotFoundException and


NoClassDefFoundError in java

ClassNotFoundException is an exception that occurs when you try to load a class at


run time using Class. forName() or loadClass() methods and mentioned classes are
not found in the classpath. NoClassDefFoundError is an error that occurs when a
particular class is present at compile time, but was missing at run time.

Explain the JDBC Architecture with different components.

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.

What is Prepared Statement

A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of


Statement. Prepared Statement objects have some useful additional features than
Statement objects.
What is JDBC Driver interface

JDBC is an application program interface (API) specification for connecting programs


written in Java to the data in popular databases. Each JDBC driver allows
communication with a different database.

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.

Why is Java known as platform-neutral language

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" .

What are command line arguments? How they are useful

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

Explain with an example.

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

Explain Method Overriding with an example.

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

In Java, an interface is an abstract type that contains a collection of methods and


constant variables

What are the advantages of using

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.

Give an example where interface can be used to support multiple inheritance.

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.

describe the complete life cycle of a thread in java


A thread goes through various stages in its lifecycle. For example, a thread is born,
started, runs, and then dies. The following diagram shows the complete life cycle of a
thread.
Following are the stages of the life cycle −

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.

Terminated (Dead) − A runnable thread enters the terminated state when it


completes its task or otherwise terminates

What are the ways by which we can create threads

There are two ways to create a thread

By extending Thread class

By implementing Runnable interface.

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.

What happens if we declare a member function of a class as static

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

3 constants defined in Thread class:


public static int MIN_PRIORITY

public static int NORM_PRIORITY

public static int MAX_PRIORITY


List some of the most common types of exceptions that might occur in Java.

S.
No. Class Object

Class is used as a template for


declaring and An object is an instance of a
1 creating the objects. class.

Objects are allocated memory


When a class is created, no space whenever they are
2 memory is allocated. created.

The class has to be declared An object is created many


3 only once. times as per requirement.

A class cannot be manipulated


as they are not
4 available in the memory. Objects can be manipulated.

5 A class is a logical entity. An object is a physical entity.

It is created with a class name


It is declared with the class in C++ and
6 keyword with the new keywords in Java.

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.

A class is used to bind data as


well as methods together as a Objects are like a variable of
8 single unit. the class.
When do we declare a method as abstract? Answer with an example.

A method without body (no implementation) is known as abstract method. A


method must always be declared in an abstract class, or in other words you can
say that if a class has an abstract method, it should be declared abstract as well.

Distinguish between InputStream and Reader classes

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

FileReader is used for


reading text files in
FileInputStream is used for reading binary platform default
files. encoding.

Serialization and DeSerialization can be done


with FileInputStream and ObjectInputStream, FileReader is not used for
and serialized objects can be saved to a file. Serialization and
Serialization converts an object to a byte DeSerialization, as it
stream, and deserialization converts it back to reads characters not
an object. bytes.

FileInputStream is descendant of InputStream FileReader extends from


class. Reader class

read() method of FileInputStream can read read() method of


one byte at a time or multiple bytes in a byte FileReader can read one
array. character at a time or
FileInputStream FileReader

multiple characters into


an array

public class CountCharacter


{
public static void main(String[] args) {
String string = "The best of both worlds";
int count = 0;

//Counts each character except space


for(int i = 0; i < string.length(); i++) {
if(string.charAt(i) != ' ')
count++;
}

//Displays the total number of characters present in the given string


System.out.println("Total number of characters in a string: " + count);
}
}

Output:

Total number of characters in a string: 19

2019
What are the benefits of object-oriented programming

4 Advantages of Object-Oriented Programming


Modularity for easier troubleshooting. When working with object-oriented
programming languages, you know exactly where to look when something goes
wrong. ...
Reuse of code through inheritance. ...
Flexibility through polymorphism. ...
Effective problem solving.

Write a short note on Java Development Kit (JDK)

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.

How is Java more secured than other languages

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

It is a keyword that is when associated with a method, making it a class-related


method. The main() method is static so that JVM can invoke it without instantiating
the class. This also saves the unnecessary wastage of memory which would have
been used by the object declared only for calling the main() method by the JVM.

Void

It is a keyword and is used to specify that a method doesn’t return anything. As


the main() method doesn’t return anything, its return type is void. As soon as
the main() method terminates, the java program terminates too. Hence, it doesn’t
make any sense to return from the main() method as JVM can’t do anything with the
return value of it.

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:

void func() { ... }

void func(int a) { ... }

float func(double a) { ... }

float func(int a, float b) { ...

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

charAt() Returns the character at the specified index (position)

codePointAt() Returns the Unicode of the character at the specified index

codePointBefore() Returns the Unicode of the character before the specified index

codePointCount() Returns the number of Unicode values found in a string.


compareTo() Compares two strings lexicographically

compareToIgnoreCase() Compares two strings lexicographically, ignoring case differences

concat() Appends a string to the end of another string

contains() Checks whether a string contains a sequence of characters

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

endsWith() Checks whether a string ends with the specified character(s)

equals() Compares two strings. Returns true if the strings are equal, and false

equalsIgnoreCase() Compares two strings, ignoring case considerations

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

getChars() Copies characters from a string to an array of chars

hashCode() Returns the hash code of a string

indexOf() Returns the position of the first found occurrence of specified chara
string

intern() Returns the canonical representation for the string object

isEmpty() Checks whether a string is empty or not

lastIndexOf() Returns the position of the last found occurrence of specified chara
string

length() Returns the length of a specified 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

split() Splits a string into an array of substrings

startsWith() Checks whether a string starts with specified characters

subSequence() Returns a new character sequence that is a subsequence of this seq

substring() Returns a new string which is the substring of a specified string

toCharArray() Converts this string to a new character array

toLowerCase() Converts a string to lower case letters

toString() Returns the value of a String object

toUpperCase() Converts a string to upper case letters

trim() Removes whitespace from both ends of a string

valueOf() Returns the string representation of the specified value

indexOf() Used to find characters and substrings in a string. ...


toCharArray() Used to form a new character array from this string. .

When do we declare a method as final? Answer with an example.

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

The keyword used to create a The keyword used to create an


class is “class” interface is “interface”

A class can be instantiated i.e, An Interface cannot be instantiated


objects of a class can be created. i.e, objects cannot be created.

Classes does not support multiple Interface supports multiple


inheritance. inheritance.

It can be inherit another class. It cannot inherit a class.

It can be inherited by a class by


using the keyword ‘implements’ and
It can be inherited by another it can be inherited by an interface
class using the keyword ‘extends’. using the keyword ‘extends’.

It can contain constructors. It cannot contain constructors.

It cannot contain abstract


methods. It contains abstract methods only.

Variables and methods in a class


can be declared using any access
specifier(public, private, default, All variables and methods in a
protected) interface are declared as public.

Variables in a class can be static,


final or neither. All variables are static and final.

import java.util.*;

// Main Class
class GFG {

// Main driver method

public static void main(String[] args)

// Scanner to take input from the user object

Scanner myObj = new Scanner(System.in);

String userName;

// Display message

// Enter Your Name And Press Enter

System.out.println("Enter You Name");

// Reading the integer age entered using

// nextInt() method

userName = myObj.nextLine();

// Print and display

System.out.println("Your Name IS : " + userName);

}
}

Package create

Java Application Java Applet

Applets are small Java programs that


Applications are just like a Java are designed to be included with the
programs that can be execute HTML web document. They require a
independently without using the Java-enabled web browser for
web browser. execution.

Application program requires a Applet does not require a main


main function for its execution. function for its execution.

Java application programs have


the full access to the local file Applets don’t have local disk and
system and network. network access.

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.

Applications can executes the Applets cannot execute programs


programs from the local system. from the local machine.

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

Method overloading is a Method overriding is a run-


1. compile-time polymorphism. time polymorphism.

It is used to grant the specific


implementation of the method
It helps to increase the which is already provided by its
2. readability of the program. parent class or superclass.

It is performed in two classes


3. It occurs within the class. with inheritance relationships.

Method overloading may or Method overriding always


4. may not require inheritance. needs inheritance.

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.

In method overloading, the


return type can or can not be In method overriding, the
the same, but we just have to return type must be the same
6. change the parameter. or co-variant.
How to use Multiple Threads in Java – example.

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

Methods of Applet Life Cycle

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.

https://www.javatpoint.com/design-of-jdbc jdbc read this

What is Prepared Statement

A PreparedStatement is a pre-compiled SQL statement. It is a subinterface of


Statement. Prepared Statement objects have some useful additional features than
Statement objects. Instead of hard coding queries, PreparedStatement object
provides a feature to execute a parameterized query

JDBC is an application program interface (API) specification for connecting


programs written in Java to the data in popular databases. Each JDBC driver
allows communication with a different database.

Sr. Key Thread Runnable


No.

1 Basic Thread is a class. It is used to Runnable is a functional


create a thread interface which is used to
create a thread
Sr. Key Thread Runnable
No.

2 Methods It has multiple methods including It has only abstract method


start() and run() run()

3 Each thread creates a unique Multiple threads share the


object and gets associated with it same objects.

4 Memory More memory required Less memory required

5 Limitation Multiple Inheritance is not If a class is implementing the


allowed in java hence after a runnable interface then your
class extends Thread class, it can class can extend another
not extend any other class class.
2015

What's the difference between constructors and other methods

Constructor is used to initialize an object whereas method is used to exhibits


functionality of an object

What is a Static member class

In Java, static members are those which belongs to the class and you can access
these members without instantiating the class.

What is finalize () method

The Finalize method is used to perform cleanup operations on unmanaged


resources held by the current object before the object is destroyed

What is the difference between Array and vector

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.

What is the difference between this () and super ()

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

A Daemon thread is a background service thread which runs as a low priority


thread and performs background operations like garbage collection

What is the basic difference between string and StringBuffer object

No. String StringBuffer

1) The String class The StringBuffer class is mutable.


is immutable.

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.

4) String class is StringBuffer class is faster while performing concatenation operation.


slower while
performing
concatenation
operation.
5) String class StringBuffer uses Heap memory
uses String
constant pool.

What is the purpose of Void class

The Void class is an uninstantiable placeholder class to hold a reference to the


Class object representing the Java keyword void

What is an exception

Definition: An exception is an event, which occurs during the execution of a


program, that disrupts the normal flow of the program's instructions.

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

What is thread priority

Thread priority in Java is a number assigned to a thread that is used by Thread


scheduler to decide which thread should be allowed to execute.

What is the full form of AWT

The Abstract Window Toolkit (AWT) supports Graphical User Interface (GUI)
programming.
What is package

A package is a namespace that organizes a set of related classes and interfaces.

How to implement multiple inheritance concepts in Java

The only way to implement multiple inheritance is to implement multiple


interfaces in a class

What are the types of Exceptions in Java

https://www.javatpoint.com/types-of-exception-in-java

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 different types of access modifiers (Access specifies)

There are six different types of access modifiers.


Public.
Private.
Protected.
Internal.
Protected Internal.
Private Protected.

What is method overloading and method overriding

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.

What is Garbage Collection


Garbage Collection is process of reclaiming the runtime unused memory
automatically. In other words, it is a way to destroy the unused objects.

What are inner class and anonymous 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.

What are the methods provided by the object class

public final void notify() public final void notifyAll() public final void wait()

What are the advantages of using exception handling

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.

What are wrapper classes

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/

Write short notes on different string handling.

No. Method Description

1 char charAt(int index) It returns char value for the particular


index

2 int length() It returns string length

3 static String format(String format, Object... args) It returns a formatted string.

4 static String format(Locale l, String format, Object... It returns formatted string with given
args) locale.

5 String substring(int beginIndex) It returns substring for given begin


index.

What is multithreading in Java?


Multithreading is a Java feature that allows concurrent execution of two or more
parts of a program for maximum utilization of CPU.
Benefits of Multithreading*
Improved throughput. ...
Simultaneous and fully symmetric use of multiple processors for computation and
I/O.
Superior application responsiveness. ...
Improved server responsiveness. ...
Minimized system resource usage. ...
Program structure simplification. ...
Better communication.

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

AWT stands for Abstract window toolkit is an Application programming interface


(API) for creating Graphical User Interface (GUI) in Java

Write a program in Java that stores information in the array and then sort
the array.

public class SortAsc {


public static void main(String[] args) {

//Initialize array
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;

//Displaying elements of original array


System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}

//Sort the array in ascending order


for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] > arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}

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:

Elements of original array:


52871
Elements of array sorted in ascending order:
12578

What is the need of synchronized block

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.

Explain with example constructor overloading

https://www.programiz.com/cpp-programming/constructor-
overloading#:~:text=Constructors%20can%20be%20overloaded%20in,the
%20corresponding%20constructor%20is%20called.

Sr.No Compile Time Polymorphism Run time Polymorphism

In Compile time Polymorphism, In Run time Polymorphism,


the call is resolved by the the call is not resolved by
1 compiler. the compiler.
Sr.No Compile Time Polymorphism Run time Polymorphism

It is also known as Static It is also known as Dynamic


binding, Early binding and binding, Late binding and
2 overloading as well. overriding as well.

Method overloading is the


compile-time polymorphism Method overriding is the
where more than one methods runtime polymorphism
share the same name with having same method with
different parameters or same parameters or
signature and different return signature, but associated in
3 type. different classes.

It is achieved by function
overloading and operator It is achieved by virtual
4 overloading. functions and pointers.

It provides slow execution


It provides fast execution as compare to early binding
because the method that needs because the method that
to be executed is known early needs to be executed is
5 at the compile time. known at the runtime.

Compile time polymorphism is Run time polymorphism is


less flexible as all things more flexible as all things
6 execute at compile time. execute at run time.

Read definition

What is object cloning

Object cloning refers to the creation of an exact copy of an object. It creates a


new instance of the class of the current object and initializes all its fields with
exactly the contents of the corresponding fields of this object.

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.

You might also like