JAVA Interview Question PDF
JAVA Interview Question PDF
1. What is Java?
Install Java through command prompt so that it can generate necessary log files to
troubleshoot the issue.
Click on the Save button and save Java software on the Desktop
Windows Vista and Windows 7: Click Start -> Type: cmd in the Start Search field.
}"
Threads allow a program to operate more efficiently by doing multiple things at the
same time.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
Mac OS X
To run a different version of Java, either specify the full path or use the java_home tool:
% java -version
This will print the version of the java tool, if it can find it. If the version is old or you get
the error java: Command not found, then the path is not properly set.
Determine which java executable is the first one found in your PATH
% which java
The process by which one class acquires the properties(data members) and
functionalities(methods) of another class is called inheritance. The aim of inheritance in
java is to provide the reusability of code so that a class has to write only the unique
features and rest of the common properties and functionalities can be extended from
another class.
Child Class:
The class that extends the features of another class is known as child class, sub class
or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as parent class, super class or Base class.
9. How to compare two strings in Java?
520
Created by Sushil
JAVA QUIZ
The idea behind encapsulation is to hide the implementation details from users. If a data
member is private it means it can only be accessed within the same class. No outside
class can access private data member (variable) of other class.
However if we setup public getter and setter methods to update (for example void
setName(String Name ))and read (for example String getName()) the private data fields
then the outside class can access those private data fields via public methods.
Collections are like containers that group multiple items in a single unit. For example, a
jar of chocolates, list of names, etc.
Collections are used in every programming language and when Java arrived, it also
came with few Collection classes – Vector, Stack, Hashtable, Array.
Java application programming interface (API) is a list of all classes that are part of the
Java development kit (JDK). It includes all Java packages, classes, and interfaces,
along with their methods, fields, and constructors. These pre-written classes provide a
tremendous amount of functionality to a programmer.
In Java, a static member is a member of a class that isn’t associated with an instance of
a class. Instead, the member belongs to the class itself. As a result, you can access the
static member without first creating a class instance.
Arrays. sort(array);"
A class that is declared using the “abstract” keyword is known as abstract class. It can
have abstract methods(methods without body) as well as concrete methods (regular
methods with body). A normal class(non-abstract class) cannot have abstract methods.
20. What is method in java?
A method is a block of code which only runs when it is called. You can pass data,
known as parameters, into a method. Methods are used to perform certain actions, and
they are also known as functions.
“Core Java” is Sun’s term, used to refer to Java SE, the standard edition and a set of
related technologies, like the Java VM, CORBA, et cetera. This is mostly to differentiate
from, say, Java ME or Java EE. Also, note that they’re talking about a set of libraries
rather than the programming language.
An exception is an event, which occurs during the execution of a program, that disrupts
the normal flow of the program’s instructions.
When an error occurs within a method, the method creates an object and hands it off to
the runtime system. The object, called an exception object, contains information about
the error, including its type and the state of the program when the error occurred.
Creating an exception object and handing it to the runtime system is called throwing an
exception.
After a method throws an exception, the runtime system attempts to find something to
handle it. The set of possible “somethings” to handle the exception is the ordered list of
methods that had been called to get to the method where the error occurred. The list of
methods is known as the call stack.
Java supports multiple inheritance through interfaces only. A class can implement any
number of interfaces but can extend only one class. Multiple inheritance is not
supported because it leads to a deadly diamond problem.
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println(""Enter username"");
String userName = myObj.nextLine(); // Read user input
System.out.println(""Username is: "" + userName); // Output
user input
}
}"
The singleton design pattern is used to restrict the instantiation of a class and ensures
that only one instance of the class exists in the JVM. In other words, a singleton class is
a class that can have only one object (an instance of the class) at a time per JVM
instance.
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed. You have seen an example of arrays already, in the main method of the “Hello
World!” application. This section discusses arrays in greater detail.
An array of 10 elements.
Each item in an array is called an element, and each element is accessed by its
numerical index. As shown in the preceding illustration, numbering begins with 0. The
9th element, for example, would therefore be accessed at index 8.
Java garbage collection is an automatic process. The programmer does not need to
explicitly mark objects to be deleted. The garbage collection implementation lives in the
JVM. Each JVM can implement garbage collection however it pleases; the only
requirement is that it meets the JVM specification. Although there are many JVMs,
Oracle’s HotSpot is by far the most common. It offers a robust and mature set of
garbage collection options.
A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java
programs as well as programs written in other languages that are also compiled to Java
bytecode. The JVM is detailed by a specification that formally describes what is required
in a JVM implementation.
Java was originally developed by James Gosling at Sun Microsystems (which has since
been acquired by Oracle) and released in 1995 as a core component of Sun
Microsystems’ Java platform.
37. How to execute a java program?
Open a command prompt window and go to the directory where you saved the java
program (HelloWorld. java). …
Type ‘javac HelloWorld. java’ and press enter to compile your code.
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println(""Enter username"");
}"
Bytecode is the compiled format for Java programs. Once a Java program has been
converted to bytecode, it can be transferred across a network and executed by Java
Virtual Machine (JVM). Bytecode files generally have a .class extension.
● Click Start
● Select Settings
● Select System
● Select Apps & features
● Select the program to uninstall and then click its Uninstall button
● Respond to the prompts to complete the uninstall
}"
"import java.util.Scanner;
public class CharacterInputExample1
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.print(""Input a character: "");
// reading a character
char c = sc.next().charAt(0);
//prints the character
System.out.println(""You have entered ""+c);
}
} "
class MyClass {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in); // Create a Scanner
object
System.out.println(""Enter username"");
}"
class Program {
public static void main( String args[] ) {
double num1 = 74.65;
System.out.println(Math.round(num1));
}"
System.out.println(df.format(dateobj));"
Dao is a simple java class which contains JDBC logic. The Java Data Access Object
(Java DAO) is an important component in business applications. Business applications
almost always need access to data from relational or object databases and the Java
platform offers many techniques for accessing this data.
50. What is awt in java?
Frameworks are large bodies (usually many classes) of prewritten code to which you
add your own code to solve a problem in a specific domain. Perhaps you could say that
the framework uses your code because it is usually the framework that is in control. You
make use of a framework by calling its methods, inheritance, and supplying “callbacks”,
listeners, or other implementations of the Observer pattern.
Manually updating Java on Windows is typically done through the Java Control Panel.
Windows 10: Type “java” into the Windows/Cortana search box, located in the lower
left-hand corner of your screen. When the pop-out menu appears select Configure Java,
located in the Apps section.
A Java variable is a piece of memory that can contain a data value. A variable thus has
a data type. Data types are covered in more detail in the text on Java data types.
Variables are typically used to store information which your Java program needs to do
its job.
1. JavaScript is used for Front End development while java is used for Back End
Development. i.e.
2. Java Script is dynamically typed language and Java is Statically typed language: i.e
string = 4;
document.write(string); //OUTPUT IS 4
But in Java, the datatype of one variable cannot be changed and Java shows the error.
For example:
<script>
document.write("Hello World");
</script>
5. Both languages are Object Oriented but JavaScript is a Partial Object Oriented
Language while Java is a fully Object Oriented Langauge. JavaScript can be used with
or without using objects but Java cannot be used without using classes.
"import java.util.HashMap;
charCountMap.put(c, charCountMap.get(c)+1);
}
else
{
//If char 'c' is not present in charCountMap,
//putting 'c' into charCountMap with 1 as it's
value
charCountMap.put(c, 1);
}
}
System.out.println(inputString+"" : ""+charCountMap);
}
characterCount(""All Is Well"");
while (rowIterator.hasNext()) {
row = (XSSFRow) rowIterator.next();
Iterator < Cell > cellIterator = row.cellIterator();
while ( cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.print(cell.getNumericCellValue() + ""
\t\t "");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(
cell.getStringCellValue() + "" \t\t "");
break;
}
}
System.out.println();
}
fis.close();"
try {
} "
This is the access modifier of the main method. It has to be public so that java runtime
can execute this method. Remember that if you make any method non-public then it’s
not allowed to be executed by any program, there are some access restrictions applied.
So it means that the main method has to be public. Let’s see what happens if we define
the main method as non-public.
When java runtime starts, there is no object of the class present. That’s why the main
method has to be static so that JVM can load the class into memory and call the main
method. If the main method won’t be static, JVM would not be able to call it because
there is no object of the class is present.
Java programming mandates that every method provide the return type. Java main
method doesn’t return anything, that’s why it’s return type is void. This has been done to
keep things simple because once the main method is finished executing, java program
terminates. So there is no point in returning anything, there is nothing that can be done
for the returned object by JVM. If we try to return something from the main method, it
will give compilation error as an unexpected return value.
It is used to achieve total abstraction. Since java does not support multiple inheritance
in case of class, but by using interface it can achieve multiple inheritance . It is also
used to achieve loose coupling. Interfaces are used to implement abstraction.
Object Serialization is a process used to convert the state of an object into a byte
stream, which can be persisted into disk/file or sent over the network to any other
running Java virtual machine. The reverse process of creating an object from the byte
stream is called deserialization.
The language was at first called Oak after an oak tree that remained external Gosling’s
office. Later the task passed by the name Green and was at last renamed Java, from
Java , a coffee brand, the coffee from Indonesia.
"
Throw is a keyword which is used to throw an exception explicitly in the program inside
a function or inside a block of code. Throws is a keyword used in the method signature
used to declare an exception which might get thrown by the function while executing the
code.
The CLASSPATH variable is one way to tell applications, including the JDK tools, where
to look for user classes. (Classes that are part of the JRE, JDK platform, and extensions
should be defined through other means, such as the bootstrap class path or the
extensions directory.)
At the time of compilation, the java compiler converts the source code into a JVM
interpretable set of intermediate form, which is termed as byte code. This is unlike the
compiled code generated by other compilers and is non-executable. The java virtual
machine interpreter processes the non-executable code and executes it on any specific
machine. Hence the platform dependency is removed.
Example: Animal class has properties like fur colour, sound. Now dog and cat class
inherit these properties and assign values specific to them to the properties.
class Animal {
void sound(){
}
}
class Cat extends Animal{
void sound(){
System.out.println("Meow");
}
}
If multiple functions in a class have the same name but different function definitions it is
called method overloading.
It is used to make a java function serve multiple purposes making the code cleaner and
API less complex.
Example:
– Lack of pointers: Java does not have pointers which make it secure
– Garbage Collection: Java automatically clears out unused objects from memory which
are unused
Java does not allow pointers. Pointers give access to actual locations of variables in a
system. Also, java programs are bytecode executables that can run only in a JVM.
Hence java programs do not have access to the host systems on which they are
executing, making it more secure. Java has its own memory management system,
which adds to the security feature as well.
JDK is a software environment used for the development of Java programs. It’s a
collection of libraries that can be used to develop various applications. JRE (Java
Runtime Environment) is a software environment that allows Java programs to run. All
java applications run inside the JRE. JVM (java virtual machine) is an environment that
is responsible for the conversion of java programs into bytecode executables. JDK and
JRE are platform-dependent whereas JVM is platform-independent.
Java is a pure Object Oriented Programming Language with the following features:
– High Performance
– Platform Independent
– Robust
– Multi-threaded
– Simple
– Secure
Static methods and variables are used in java to maintain a single copy of the entity
across all objects. When a variable is declared as static it is shared by all instances of
the class. Changes made by an instance to the variable reflect across all instances.
static int a;
static int b;
static_variable(){
a=10;
}
int calc_b(){
b=a+10;
return b;
}
void print_val(){
System.out.println(this.b);
}
public static void main(String args[]){
static_variable v=new static_variable();
v.calc_b();
v.print_val();
static_variable v1=new static_variable();
v1.print_val();
}
Static methods are methods that can be called directly inside a class without the use of
an object.
Static variables are variables that are shared between all instances of a class.
Static blocks are code blocks that are loaded as the class is loaded in memory.
Static variables are used for maintaining a common state of certain data which is
modifiable and accessible by all instances of a class.
Abstraction is achieved in Java by the use of abstract class and abstract methods.
Strings in java are frequently used for hashmap keys. Now if someone changes the
value of the string it will cause severe discrepancies. Hence strings are made
immutable.
Wrapper classes are a functionality supported by java to accept primitive data types as
inputs and then later convert those into string objects so that they can be compared to
other objects.
86. Can interfaces in Java be inherited?
Yes, interfaces can be inherited in java. Hybrid inheritance and hierarchical inheritance
are supported by java through inheritable interfaces.
Yes, static methods are allowed in java interfaces. They are treated as default methods
so they need not be implemented.
Java has an automatic built-in garbage collection mechanism in place. Apart from the
built-in mechanism, manual initiation of garbage collection can also be done by using
the gc() of system class.
Yes, there can be two main methods. This also means that the main method is
overloaded. But at the time of execution, JVM only calls the original main method and
not the overloaded main method.
Private variables have a class-specific scope of availability. They can only be accessed
by the methods of the class in which they are present. Hence when the class is
inherited, private variables are not inherited by the subclass.
The size of a java array cannot be increased after declaration. This is a limitation of
Java arrays.
Each int block takes a size of 4 bytes and there are 10 such blocks in the array. Hence,
the size the array takes in memory is 40 bytes.
Java supports 8 primitive data types, namely byte, short, int, long, float, double, char,
boolean.
We have to instantiate an input reader class first. There are quite a few options
available, some of which are BufferedReader, InputStreamReader Scanner.
Then the relative functionality of the class can be used. One of the most prevalently
used is nextLine() of Scanner class.
The size of strings in java can be checked by using the length() function.
The built-in sorting utility sort() can be used to sort the elements. We can also write our
custom functions but it’s advisable to use the built-in function as its highly optimized.
On the other hand, throws is used as part of method declaration and signals which kind
of exceptions are thrown by this method so that its caller can handle them. It’s
mandatory to declare any unhandled checked exception in throws clause in Java. Like
the previous question, this is another frequently asked Java interview question from
errors and exception topic but too easy to answer.
Yes, you can make an array volatile in Java but only the reference which is pointing to
an array, not the whole array. What I mean, if one thread changes the reference
variable to points to another array, that will provide a volatile guarantee, but if multiple
threads are changing individual array elements they won’t be having happens before
guarantee provided by the volatile modifier.
No, you cannot store a double value into a long variable without casting because the
range of double is more than long and we need to type cast. It’s not difficult to answer
this question but many developer get it wrong due to confusion on which one is bigger
between double and long in Java.
An Integer object will take more memory as Integer is an object and it stores metadata
overhead about the object but int is a primitive type, so it takes less space.
103. The difference between nested static class and top-
level class?
A public top-level class must have the same name as the name of the source file, there
is no such requirement for a nested static class. A nested class is always inside a top-
level class and you need to use the name of the top-level class to refer nested static
class e.g. HashMap.Entry is a nested static class, where HashMap is a top-level class
and Entry is nested, static class.
The final keyword is used to declare the final state of an entity in java. The value of the
entity cannot be modified at a later stage in the application. The entity can be a variable,
class, object, etc.
Shallow copy in java copies all values and attributes of an object to another object and
both objects reference the same memory locations.
Deep copy is the creation of an object with the same values and attributes of the object
being copied but both objects reference different memory locations.
The default constructor is a constructor that gets called as soon as the object of a class
is declared. The default constructor is un-parametrized. The generic use of default
constructors is in the initialization of class variables.
class ABC{
int i,j;
ABC(){
i=0;
j=0;
}
}
Here ABC() is a default constructor.
Object cloning is the process of creating an exact copy of an object of a class. The state
of the newly created object is the same as the object used for cloning.
The clone() method is used to clone objects. The cloning done using the clone method
is an example of a deep copy.
They serve the primary function of initializing the static variables. If multiple static blocks
are there they are executed in the sequence in which they are written in a top-down
manner.
This keyword is used to reference an entity using the current object in java. It’s a multi-
purpose keyword which serves various functionalities
Strings are immutable while string Builder class is mutable. The string builder class is
also synchronized.
If a class has an integer, a double variable defined in it then the size of the object of the
class is size(int)+size(double).
If there is an array, then the size of the object would be the length of array*size of data
type of array.
“==” checks if the references share the same location, whereas .equals() checks if both
object values are the same on evaluation.
Object Serialization is a process used to convert the state of an object into a byte
stream, which can be persisted into disk/file or sent over the network to any other
running Java virtual machine. The reverse process of creating an object from the byte
stream is called deserialization.
A servlet is a Java programming language class that is used to extend the capabilities
of servers that host applications accessed by means of a request-response
programming model. Although servlets can respond to any type of request, they are
commonly used to extend the applications hosted by web servers. For such
applications, Java Servlet technology defines HTTP-specific servlet classes.
All servlets must implement the Servlet interface, which defines life-cycle methods.
When implementing a generic service, you can use or extend the GenericServlet class
provided with the Java Servlet API. The HttpServlet class provides methods, such as
doGet and doPost, for handling HTTP-specific services.
Multiple static blocks are executed in the sequence in which they are written in a top-
down manner. The top block gets executed first, then the subsequent blocks are
executed.
Static methods cannot be overridden because they are not dispatched to the object
instance at run time. In their case, the compiler decides which method gets called.
All classes in java inherit from the Object class which is the superclass of all classes.
ClassLoader is a subsystem of JVM which is used to load class files. Whenever we run
the java program, it is loaded first by the classloader. There are three built-in
classloaders in Java.
Serializable interface is used to make Java classes serializable so that they can be
transferred over a network or their state can be saved on disk, but it leverages default
serialization built-in JVM, which is expensive, fragile and not secure. Externalizable
allows you to fully control the Serialization process, specify a custom binary format and
add more security measure.
We can use String in switch case but it is just syntactic sugar. Internally string hash
code is used for the switch. See the detailed answer for more explanation and
discussion.
A checked exception is checked by the compiler at compile time. It’s mandatory for a
method to either handle the checked exception or declare them in their throws clause.
These are the ones which are a subclass of Exception but doesn’t descend from
RuntimeException. The unchecked exception is the descendant of RuntimeException
and not checked by the compiler at compile time. This question is now becoming less
popular and you would only find this with interviews with small companies, both
investment banks and startups are moved on from this question.
java.lang.Cloneable is a marker interface and doesn’t contain any method clone method
is defined in the object class. It is also knowing that clone() is a native method means
it’s implemented in C or C++ or any other native language.
String[] cars;
We have now declared a variable that holds an array of strings.
To insert values to it, we can use an array literal - place the
values in a comma-separated list, inside curly braces:
Polymorphism is one of the OOPs features that allow us to perform a single action in
different ways. For example, let’s say we have a class Animal that has a method
sound(). Since this is a generic class so we can’t give it an implementation like Roar,
Meow, Oink etc. We had to give a generic message.
As you can see that although we had the common action for all
subclasses sound() but there were different ways to do the same
action. This is a perfect example of polymorphism (feature that
allows us to perform a single action in different ways). It
would not make any sense to just call the generic sound() method
as each Animal has a different sound. Thus we can say that the
action this method performs is based on the type of object."
"class Scratch{
public static void main(String[] args){
String str = ""50"";
System.out.println( Integer.parseInt( str )); //
Integer.parseInt()
}
}"
class Convert
{
public static void main(String args[])
{
int a = 786;
int b = -986;
String str1 = Integer.toString(a);
String str2 = Integer.toString(b);
System.out.println(""String str1 = "" + str1);
System.out.println(""String str2 = "" + str2);
The string is Immutable in Java because String objects are cached in String pool. Since
cached String literals are shared between multiple clients there is always a risk, where
one client’s action would affect all another client. For example, if one client changes the
value of String “ABC” to “abc”, all other clients will also see that value as explained in
the first example. Since caching of String objects was important from performance
reason this risk was avoided by making String class Immutable. At the same time,
String was made final so that no one can compromise invariant of String class e.g.
Immutability, Caching, hashcode calculation etc by extending and overriding
behaviours.
class ABC
{
public static void main(String args[])
{
int a = 789;
int b = 123;
String str1 = Integer.toString(a);
String str2 = Integer.toString(b);
System.out.println(""String str1 = "" + str1);
System.out.println(""String str2 = "" + str2);
Open a command prompt window and go to the directory where you saved the java
program (MyFirstJavaProgram. java). …
Type ‘javac MyFirstJavaProgram. java’ and press enter to compile your code
import java.util.Map;
import java.util.HashMap;
class IterationDemo
{
public static void main(String[] arg)
{
Map<String,String> m = new HashMap<String,String>();
System.out.println(num);
}
}
13. What is an interface in java?
An interface in Java is similar to a class, but the body of an interface can include only
abstract methods and final fields (constants). A class implements an interface by
providing code for each method declared by the interface.
import java.io.*;
public class Read
{
public static void main(String[] args)throws Exception
{
File file = new File(""C:\\Users\\LBL\\Desktop\\test.txt"");
String st;
while ((st = br.readLine()) != null)
System.out.println(st);
}
import java.util.Scanner;
class classname{
public methodname(){
//Scanner declaration
Scanner s_name = new Scanner(System.in);
//Use Scanner to take input
int val = s_name.nextInt();
}
class Reverse
{
public static void main(String args[])
{
int num=564;
int reverse =0;
while( num != 0 )
{
reverse = reverse * 10;
reverse = reverse + num%10;
num = num/10;
}
Instance variable in Java is used by Objects to store their states. Variables that are
defined without the STATIC keyword and are Outside any method declaration are
Object-specific and are known as instance variables. They are called so because their
values are instance specific and are not shared among instances.
class CharArrayToString
{
public static void main(String args[])
{
// Method 1: Using String object
char[] ch = {'g', 'o', 'o', 'd', ' ', 'm', 'o', 'r', 'n',
'i', 'n', 'g'};
String str = new String(ch);
System.out.println(str);
Maven is a powerful project management tool that is based on POM (project object
model). It is used for project build, dependency and documentation.
It simplifies the build process like ANT. But it is too much advanced than ANT.
An array is a container object that holds a fixed number of values of a single type. The
length of an array is established when the array is created. After creation, its length is
fixed. You have seen an example of arrays already, in the main method of the “Hello
World!” application.
An applet is a special kind of Java program that runs in a Java-enabled browser. This is
the first Java program that can run over the network using the browser. An applet is
typically embedded inside a web page and runs in the browser.
In other words, we can say that Applets are small Java applications that can be
accessed on an Internet server, transported over the Internet, and can be automatically
installed and run as apart of a web document.
class Human{
//Overridden method
public void eat()
{
System.out.println(""Human is eating"");
}
}
class Boy extends Human{
//Overriding method
public void eat(){
System.out.println(""Boy is eating"");
}
public static void main( String args[]) {
Boy obj = new Boy();
//This will call the child class version of eat()
obj.eat();
}
● Click Start
● Select Control Panel
● Select Programs
● Click Programs and Features
● The installed Java version(s) are listed
import java.util.*;
public class Main
{
public static String[] return_Array() {
//define string array
String[] ret_Array = {""Java"", ""C++"", ""Python"",
""Ruby"", ""C""};
//return string array
return ret_Array;
}
Generics enable types (classes and interfaces) to be parameters when defining classes,
interfaces and methods. Much like the more familiar formal parameters us ed in method
declarations, type parameters provide a way for you to re-use the same code with
different inputs. The difference is that the inputs to formal parameters are values, while
the inputs to type parameters are types.
class ArrayLengthFinder {
public static void main(String[] arr) {
// declare an array
int[] array = new int[10];
array[0] = 12;
array[1] = -4;
array[2] = 1;
// get the length of array
int length = array.length;
System.out.println(""Length of array is: "" + length);
}
Instance variable in Java is used by Objects to store their states. Variables that are
defined without the STATIC keyword and are Outside any method declaration are
Object-specific and are known as instance variables. They are called so because their
values are instance specific and are not shared among instances.
31. How to iterate hashmap in java?
import java.util.Map;
import java.util.HashMap;
class IterationDemo
{
public static void main(String[] arg)
{
Map<String,String> g = new HashMap<String,String>();
}
33. How to sort array in java?
Java main() method is always static, so that compiler can call it without the creation of
an object or before the creation of an object of the class. In any Java program, the
main() method is the starting point from where compiler starts program execution. So,
the compiler needs to call the main() method.
import java.util.*;
class ReverseString
{
public static void main(String args[])
{
String original, reverse = """";
Scanner in = new Scanner(System.in);
System.out.println(""Enter a string to reverse"");
original = in.nextLine();
System.out.println(date); // 2010-01-02
import java.util.*;
public class ArrayListOfInteger {
}
40. How to find the length of a string in java?
To calculate the length of a string in Java, you can use an inbuilt length() method of the
Java string class
In Java, strings are objects created using the string class and the length() method is a
public member method of this class. So, any variable of type string can access this
method using the . (dot) operator.
Data type in java specifies the type of value a variable in java can store.
HashMap is a Map-based collection class that is used for storing Key & value pairs, it is
denoted as HashMap<Key, Value> or HashMap<K, V>. This class makes no
guarantees as to the order of the map. It is similar to the Hashtable class except that it
is unsynchronized and permits nulls(null values and null key).
Stream keeps the ordering of the elements the same as the ordering in the source. The
aggregate operations are operations that allow us to express common manipulations on
stream elements quickly and clearly.
}}
String replace(char oldChar, char newChar): It replaces all the occurrences of a oldChar
character with newChar character. For e.g. “pog pance”.replace(‘p’, ‘d’) would return
dog dance.
A lambda expression (lambda) describes a block of code (an anonymous function) that
can be passed to constructors or methods for subsequent execution. The constructor or
method receives the lambda as an argument. Consider the following example:
System.out.println(“Hello”)
This example identifies a lambda for outputting a message to the standard output
stream. From left to right, () identifies the lambda’s formal parameter list (there are no
parameters in the example), -> indicates that the expression is a lambda, and
System.out.println(“Hello”) is the code to be executed.
The recommended file extension for the source file of a JSP page is .jsp. The page can
be composed of a top file that includes other files that contain either a complete JSP
page or a fragment of a JSP page. The recommended extension for the source file of a
fragment of a JSP page is .jspf.
The JSP elements in a JSP page can be expressed in two syntaxes, standard and XML,
though any given file can use only one syntax. A JSP page in XML syntax is an XML
document and can be manipulated by tools and APIs for XML documents.
A constructor is a block of code that initializes the newly created object. A constructor
resembles an instance method in java but it’s not a method as it doesn’t have a return
type. In short constructor and method are different(More on this at the end of this
guide). People often refer constructor as special type of method in Java.
A constructor has same name as the class and looks like this in java code.
The best and easiest way to convert a List into an Array in Java is to use the .toArray()
method.
Likewise, we can convert back a List to Array using the Arrays.asList() method.
The examples below show how to convert List of String and List of Integers to their
Array equivalents.
for(String s : itemsArray)
System.out.println(s);
}
}"
Java 8 adds functional programming through what are called lambda expressions,
which is a simple way of describing a function as some operation on an arbitrary set of
supplied variables.
int i=int(d)
An empty interface in Java is known as a marker interface i.e. it does not contain any
methods or fields by implementing these interfaces a class will exhibit a special
behaviour with respect to the interface implemented. If you look carefully on marker
interface in Java e.g. Serializable, Cloneable and Remote it looks they are used to
indicate something to compiler or JVM. So if JVM sees a Class is Serializable it done
some special operation on it, similar way if JVM sees one Class is implement Clonnable
it performs some operation to support cloning. Same is true for RMI and Remote
interface. In simplest Marker interface indicate, signal or a command to Compiler or
JVM.
–> Practically we can create an interface like a marker interface with no method
declaration in it but it is not a marker interface at all since it is not instructing something
to JVM that provides some special behaviour to the class when our program is going to
execute.
class MyClass {
public static void main(String[ ] args) {
Scanner a = new Scanner(System.in);
//Scanner b = new Scanner(System.in);
System.out.println (a.nextLine());
System.out.println(a.nextLine());
}
}
}}
62. What is type casting in java?
The process of converting the value of one data type (int, float, double, etc.) to another
data type is known as typecasting.
import java.util.Arrays;
import java.util.*;
class Inp
{
public static void main(String[] args)
{
Scanner sc= new Scanner(System.in); //System.in is a standard
input stream
System.out.print(""Enter a string: "");
String str= sc.nextLine(); //reads string
System.out.print(""You have entered: ""+str);
}
}
65. How to import scanner in java?
import java.utils.Scanner
class New
{
public static void main(String args[])
{
String str= ""This#string%contains^special*characters&."";
str = str.replaceAll(""[^a-zA-Z0-9]"", "" "");
System.out.println(str);
}
To figure the length of a string in Java, you can utilize an inbuilt length() technique for
the Java string class.
In Java, strings are objects made utilizing the string class and the length() strategy is an
open part technique for this class. Along these lines, any factor of type string can get to
this strategy utilizing the . (dot) administrator.
import java.util.*;
public class ScannerExample {
public static void main(String args[]){
Scanner in = new Scanner(System.in);
System.out.print(""Enter your name: "");
String name = in.nextLine();
System.out.println(""Name is: "" + name);
in.close();
In case one wants a different sorting order then he can implement comparator and
define its own way of comparing two instances. If sorting of objects needs to be based
on natural order then use Comparable whereas if your sorting needs to be done on
attributes of different objects, then use Comparator in Java.
The basic format of the command for creating a JAR file is:
jar-file is the name that you want the resulting JAR file to have. You can use any
filename for a JAR file. By convention, JAR filenames are given a .jar extension, though
this is not required.
The input-file(s) argument is a space-separated list of one or more files that you want to
include in your JAR file. The input-file(s) argument can contain the wildcard * symbol. If
any of the “input-files” are directories, the contents of those directories are added to the
JAR archive recursively.
The c and f options can appear in either order, but there must not be any space
between them.
To call a method in Java, write the method’s name followed by two parentheses () and a
semicolon; The process of method calling is simple. When a program invokes a method,
the program control gets transferred to the called method.
next() can read the input only till space. It can’t read two words separated by space.
Also, next() places the cursor in the same line after reading the input. nextLine() reads
input including space between the words (that is, it reads till the end of line \n).
String a = ""one"";
String b = ""two"";
a = a + b;
b = a.substring(0, (a.length() - b.length()));
a = a.substring(b.length());
import java.io.*;
The case of Aggregation is Student in School class when School shut, Student despite
everything exists and afterwards can join another School or something like that. In UML
documentation, a structure is signified by a filled precious stone, while conglomeration
is indicated by an unfilled jewel, which shows their undeniable distinction regarding the
quality of the relationship.
int amount = 9;
switch(amount) {
case 0 : System.out.println(""amount is 0""); break;
case 5 : System.out.println(""amount is 5""); break;
case 10 : System.out.println(""amount is 10""); break;
default : System.out.println(""amount is something
else"");
Recursion is simply the strategy of settling on a capacity decision itself. This method
gives an approach to separate entangled issues into straightforward issues which are
simpler to settle.
System.out.println(Arrays.toString(a));
Method Overloading is a feature that allows a class to have more than one method
having the same name if their argument lists are different. It is similar to constructor
overloading in Java, that allows a class to have more than one constructor having
different argument lists.
One way to initialize the array of objects is by using the constructors. When you create
actual objects, you can assign initial values to each of the objects by passing values to
the constructor. You can also have a separate member method in a class that will
assign data to the objects.
Java provides four types of access specifiers that we can use with classes and other
entities.
#1) Default: Whenever a specific access level is not specified, then it is assumed to be
‘default’. The scope of the default level is within the package.
#2) Public: This is the most common access level and whenever the public access
specifier is used with an entity, that particular entity is accessible throughout from within
or outside the class, within or outside the package, etc.
#3) Protected: The protected access level has a scope that is within the package. A
protected entity is also accessible outside the package through inherited class or child
class.
#4) Private: When an entity is private, then this entity cannot be accessed outside the
class. A private entity can only be accessible from within the class.
Singleton class means you can create only one object for the given class. You can
create a singleton class by making its constructor as private so that you can restrict the
creation of the object. Provide a static method to get an instance of the object, wherein
you can handle the object creation inside the class only. In this example, we are
creating an object by using a static block.
static{
myObj = new MySingleton();
}
private MySingleton(){
Exception class inherits from the Throwable class in java. Java has a try-catch
mechanism for handling exceptions without them being generated as errors.
Whenever there is a need for random access of elements in java we use ArrayList. Get
and set methods provide really fast access to the elements using the array list.
Generics allow classes and interfaces to be a type for the definition of new classes in
java which enables stronger type checking. It also nullifies the probability of type
mismatch of data while insertion.
1. Enumeration Iterator
2. List Iterator
Hashmap is a collection framework functionality which is used for storing data into key-
value pairs. To access data we need the key. A hashmap uses linked lists internally for
supporting the storage functionality.
Treemap is a navigable map interpretation in java which is built around the concepts of
red and black trees. The keys of a treemap are sorted in ascending order by their keys.
A vector is an ArrayList like data structure in java whose size increases as per the
demands. Moreover, it also supports some legacy functions not supported by
collections.
You should also know that a vector is more suitable to work with threads, unlike
collection objects.
An ArrayList is not suitable for working in a thread based environment. A vector is built
for thread-based executions. ArrayList does not support legacy functions whereas a
vector has support for legacy functions.
import java.util.Scanner;
System.out.println(fact);
import java.util.Scanner;
public class star {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int count=0;
for (int i=1;i<=n;i++)
{
if (n%i==0)
count++;
}
if (count==2)
System.out.println("Prime");
else
System.out.println("Not Prime");
}
import java.util.Scanner;
class star
{
public static void main(String arg[])
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a decimal number");
int n=sc.nextInt();
int bin[]=new int[100];
int i = 0;
while(n > 0)
{
bin[i++] = n%2;
n = n/2;
}
System.out.print("Binary number is : ");
for(int j = i-1;j >= 0;j--)
{
System.out.print(bin[j]);
}
}
import java.util.Scanner;
class star
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =sc.nextInt();
String octal = Integer.toOctalString(num);
System.out.println("Decimal to octal: " + octal);
}
}
107. Which utility function can be used to extract
characters at a specific location in a string?
The charAt() utility function can be used to achieve the above-written functionality.
This is one of the really tricky questions and can be answered only if your concepts are
very clear. The short answer is false because some floating-point numbers can not be
represented exactly.
import java.util.Scanner;
class star
{
public static void main(String args[])
{
int arr[] =new int [10];
Scanner sc = new Scanner( System.in );
System.out.println("Enter size of array");
int n=sc.nextInt();
System.out.print("Enter an arry : ");
for (int i=0;i<n;i++)
arr[i]=sc.nextInt();
for (int i=0;i<n;i++)
{
for (int j=0;j<n-i-1;j++)
{
if (arr[j]>arr[j+1])
{
int t=arr[j];
arr[j]=arr[j+1];
arr[j+1]=t;
}
}
}
for (int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
**
****
*****
******
****
***
**
import java.util.Scanner;
System.out.println("Enter a string:");
str = sc.nextLine();
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");
Java’s built-in sort function utilizes the two pivot quicksort mechanism. Quicksort works
best in most real-life scenarios and has no extra space requirements.
To remove an element from an array we have to delete the element first and then the
array elements lying to the right of the element are shifted left by one place.
The += operator implicitly cast the result of addition into the type of the variable used to
hold the result. When you add two integral variables e.g. variable of type byte, short, or
int then they are first promoted to int and them addition happens. If the result of the
addition is more than the maximum value of a then a + b will give a compile-time error
but a += b will be ok as shown below
byte a = 127;
byte b = 127;
b += a; // ok
Java OOPS Interview Questions
In the real world, you often have many objects of the same kind. For example, your
bicycle is just one of many bicycles in the world. Using object-oriented terminology, we
say that your bicycle object is an instance (in the glossary) of the class of objects known
as bicycles. Bicycles have some state (current gear, current cadence, two wheels) and
behaviour (change gears, brake) in common. However, each bicycle’s state is
independent of and can be different from that of other bicycles.
When building bicycles, manufacturers take advantage of the fact that bicycles share
characteristics, building many bicycles from the same blueprint. It would be very
inefficient to produce a new blueprint for every individual bicycle manufactured.
In object-oriented software, it’s also possible to have many objects of the same kind that
share characteristics: rectangles, employee records, video clips, and so on. Like the
bicycle manufacturers, you can take advantage of the fact that objects of the same kind
are similar and you can create a blueprint for those objects. A software blueprint for
objects is called a class (in the glossary).
Example
Create a constructor:
// Outputs 5
You can represent real-world objects using software objects. You might want to
represent real-world dogs as software objects in an animation program or a real-world
bicycle as a software object within an electronic exercise bike. However, you can also
use software objects to model abstract concepts. For example, an event is a common
object used in GUI window systems to represent the action of a user pressing a mouse
button or a key on the keyboard.
● Declaration: The code set in bold are all variable declarations that associate a
variable name with an object type.
● Instantiation: The new keyword is a Java operator that creates the object.
● Initialization: The new operator is followed by a call to a constructor, which
initializes the new object.
Bytecode is the compiled format for Java programs. Once a Java program has been
converted to bytecode, it can be transferred across a network and executed by Java
Virtual Machine (JVM).
Java has no concept of pointers. Hence java is secure. Java does not provide access to
actual memory locations.
Java supports multiple inheritance through interfaces only. A class can implement any
number of interfaces but can extend only one class.
Multiple inheritance is not supported because it leads to a deadly diamond problem.
However, it can be solved but it leads to a complex system so multiple inheritance has
been dropped by Java founders.
Java supports multiple inheritance through interfaces only. A class can implement any
number of interfaces but can extend only one class. Multiple inheritance is not
supported because it leads to a deadly diamond problem.
When a class has multiple constructors with different function definitions or different
parameters it is called constructor overloading.
import java.io.*;
import java.lang.*;
public class constructor_overloading {
double sum;
constructor_overloading(){
sum=0;
}
constructor_overloading(int x,int y){
sum=x+y;
}
constructor_overloading(double x,double y){
sum=x+y;
}
void print_sum(){
System.out.println(sum);
}
public static void main(String args[]){
constructor_overloading c=new constructor_overloading();
c.print_sum();
constructor_overloading c1=new
constructor_overloading(10,20);
c1.print_sum();
constructor_overloading c2=new
constructor_overloading(10.11,20.11);
c2.print_sum();
}
Single, multiple, multilevel, hybrid and hierarchical inheritance are possible in java.
Hybrid inheritance and hierarchical inheritance are only possible through interfaces.
– Parameterized Constructors
– Copy constructor
A singleton class is a class in Java that can at most have one instance of it in an
application. If new instances are created for the same class they point to the first
instance created and thus have the same values for all attributes and properties.
Singleton classes are created to create global points of access to objects. Singleton
classes find their primary usages in caching, logging, device drivers which are all
entities for universal access.
Finalize() is used for garbage collection. It’s called by the Java run environment by
default to clear out unused objects. This is done for memory management and clearing
out the heap.
Encapsulation is the process of wrapping variables and functions together into a single
unit in order to hide the unnecessary details. The wrapped up entities are called classes
in java. Encapsulation is also known as data hiding because it hides the underlying
intricacies.
Abstraction is the process of revealing the essential information and hiding the trivial
details across units in java. Java has abstract classes and methods through which it
does data abstraction.
Constructors are not properties of a class. Hence they cannot be inherited. If one can
inherit constructors then it would also mean that a child class can be created with the
constructor of a parent class which can later cause referencing error when the child
class is instantiated. Hence in order to avoid such complications, constructors cannot be
inherited. The child class can invoke the parent class constructor by using the super
keyword.
Encapsulation is achieved by wrapping up data and code into simple wrappers called
classes. Objects instantiate the class to get a copy of the class data.
An abstract class is a class that can only be inherited and it cannot be used for object
creation. It’s a type of restricted class with limited functionality.
If we make the constructors final then the class variables initialized inside the
constructor will become unusable. Their state cannot be changed.
Multithreading in Java is a feature that allows concurrent execution of two or more parts
of a program for maximum utilization of CPU. Each part of such a program is called a
thread. So, threads are light-weight processes within a process.
Thread-safety or thread-safe code in Java refers to code which can safely be used or
shared in concurrent or multi-threading environment and they will behave as expected.
any code, class, or object which can behave differently from its contract on the
concurrent environment is not thread-safe.
Volatile keyword is used to modify the value of a variable by different threads. It is also
used to make classes thread-safe. It means that multiple threads can use a method and
instance of the classes at the same time without any problem.
5. How to generate random numbers in java within range?
import java.util.concurrent.ThreadLocalRandom;
When objects are cloned using the assignment operator, both objects share the same
reference. Changes made to the data by one object would also be reflected in the other
object.
Once a thread is started, it can never be started again. Doing so will throw an
IllegalThreadStateException
This brings us to the end of the Java Interview Questions. Glad to see you are now
better equipped to face an interview.
There is no fixed method through which you can prepare for your upcoming Java
Interview. However, understanding the basic concepts of Java is important for you to do
well. The next step would be to take up a Java Beginners Course that will help you
understand the concepts well, or read the top books for self-learning. Apart from
learning the basic concepts through courses, books, and blogs, you can also work on
projects that will help you gain a hands-on experience.
String is immutable in Java to ensure that the value of the string does not change. Java
uses string literals, if there are multiple variables that refer to one object and the value
of the object is changed, it would affect all reference variables. Hence, strings are
immutable in Java.
Java doesn’t allow using pointers. Pointers are not used in Java to ensure that it is more
secure and robust.
No. Java is not a 100% object oriented language. It follows some principles of object
oriented language, but not all.
Any method of learning that suits you and your learning style should be considered as
the best way to learn. Different people learn well through different methods. Some
individuals may prefer taking up online courses, reading books or blogs, watching
YouTube videos to self-learn. And some people may also learn through practice and
hands-on experience. Choose what works best for you!
In Java, API stands for Application Programming Interface. It is a software that allows
two applications to talk to each other. It is a list of classes that is part of a JDK or Java
Development Kit and includes interfaces, packages, classes, fields, methods and
constructors.