1. What is Java?
Java is a general-purpose programming language that is class-based, object-oriented
and is very popular. It’s one of the most popular programming languages in the world.
Hello World in Java:
public class FileName {
public static void main(String args[]) {
System.out.println("Hello World!");
}
}
2. How to install Java?
Install Java through command prompt so that it can generate necessary log files to
troubleshoot the issue.
Go to java.com and click on the Free Java Download button.
Click on the Save button and save Java software on the Desktop
Verify that Java software is saved on the desktop.
Open Windows Command Prompt window.
Windows XP: Click Start -> Run -> Type: cmd
Windows Vista and Windows 7: Click Start -> Type: cmd in the Start Search field.
cd <Java download directory> (for example Downloads or Desktop etc.)
IRun the installer and follow onscreen instructions.
3. How to reverse a string in Java?
"String str = ""Hello"";
String reverse(String str){
StringBuilder sb = new StringBuilder();
sb.append(str);
sb.reverse();
return sb.toString();
}"
4. What is the thread in Java?
Threads allow a program to operate more efficiently by doing multiple things at the
same time.
Threads can be used to perform complicated tasks in the background without
interrupting the main program.
It can be created by extending the Thread class and overriding its run() method:
Extend Syntax
public class MyClass extends Thread {
public void run() {
System.out.println("This code is running in a
thread");
}
}
5. How to take input in Java?
"Scanner in = new Scanner(System.in);
System.out.print(""Please enter hour 1: "");
int hour1 = in.nextInt();
System.out.print(""Please enter hour 2: "");
int hour2 = in.nextInt();
System.out.print(""Please enter minute 1: "");
int min1 = in.nextInt();
System.out.print(""Please enter minute 2: "");
int min2 = in.nextInt();"
6. How to set path in Java?
Windows 10 and Windows 8
● In Search, search for and then select: System (Control Panel)
● Click the Advanced system settings link.
● Click Environment Variables. In the section System Variables, find the PATH
environment variable and select it. Click Edit. If the PATH environment
variable does not exist, click New.
● In the Edit System Variable (or New System Variable) window, specify the
value of the PATH environment variable. Click OK. Close all remaining
windows by clicking OK.
● Reopen Command prompt window, and run your java code.
Mac OS X
To run a different version of Java, either specify the full path or use the java_home tool:
% /usr/libexec/java_home -v 1.8.0_73 –exec javac -version
Solaris and Linux
To find out if the path is properly set:
In a terminal windows, enter:
% 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
In a terminal window, enter:
% which java
7. What is enumeration in Java?
Enumeration means a list of named constants. In Java, enumeration defines a class
type. An Enumeration can have constructors, methods, and instance variables. It is
created using the enum keyword. Each enumeration constant is public, static, and final by
default. Even though enumeration defines a class type and has constructors, you do
not instantiate an enum using new. Enumeration variables are used and declared in
much the same way as you do a primitive variable.
8. What is inheritance in 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 the 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, subclass
or derived class.
Parent Class:
The class whose properties and functionalities are used(inherited) by another class is
known as a parent class, superclass or Base class.
9. How to compare two strings in Java?
"// These two have the same value
new String(""test"").equals(""test"") // --> true
// ... but they are not the same object
new String(""test"") == ""test"" // --> false
// ... neither are these
new String(""test"") == new String(""test"") // --> false
// ... but these are because literals are interned by
// the compiler and thus refer to the same object
""test"" == ""test"" // --> true "
10. What is an abstraction in Java?
Objects are the building blocks of Object-Oriented Programming. An object contains
some properties and methods. We can hide them from the outer world through access
modifiers. We can provide access only for required functions and properties to the other
programs. This is the general procedure to implement abstraction in OOPS.
520
Created by Sushil
JAVA QUIZ
Assess yourself by giving a quiz now!
11. What is encapsulation in java?
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.
12. What is a collection in java?
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 a few Collection classes – Vector, Stack, Hashtable, Array.
13. What is API in java?
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.
14. How to initialize an array in java?
"int[] arr = new int[5]; // integer array of size 5 you can
also change data type
String[] cars = {""Volvo"", ""BMW"", ""Ford"", ""Mazda""};"
15. How to take input from users in java?
"import java.util.Scanner;
Scanner console = new Scanner(System.in);
int num = console.nextInt();
console.nextLine() // to take in the enter after the nextInt()
String str = console.nextLine();"
16. What is static in java?
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.
17. What is a package in java?
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 better maintainable
code. Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
18. How to sort an array in java?
"import java. util. Arrays;
Arrays. sort(array);"
19. What is an abstract class in java?
A class that is declared using the “abstract” keyword is known as an abstract class. It can
have abstract methods(methods without body) as well as concrete methods (regular
methods with the body). A normal class(non-abstract class) cannot have abstract methods.
20. What is a method in java?
A method is a block of code that 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.
21. How to check the java version?
Execute java -version on a command prompt/terminal.
22. What is a class in java?
A class–the basic building block of an object-oriented language such as Java–is a
template that describes the data and behavior associated with instances of that class.
When you instantiate a class you create an object that looks and feels like other
instances of the same class. The data associated with a class or object is stored in
variables; the behavior associated with a class or object is implemented with methods.
23. What is core java?
“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.
24. How to enable java in chrome?
● In the Java Control Panel, click the Security tab
● Select the option Enable Java content in the browser
● Click Apply and then OK to confirm the changes
● Restart the browser to enable the changes
25. What is a string in java?
The string is a sequence of characters, e.g. “Hello” is a string of 5 characters. In java,
the string is an immutable object which means it is constant and cannot be changed once it
has been created.
26. What is an exception in java?
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.
27. Why multiple inheritance is not supported in java?
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.
28. How to take string input in java?
"import java.util.Scanner; // Import the Scanner class
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
}
}"
29. What is singleton class in java?
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.
30. What is array in java?
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.
Illustration of an array as 10 boxes numbered 0 through 9; an index of 0 indicates the
first element in the array.
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.
31. What is garbage collection in java?
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.
32. Why we need encapsulation in java?
Encapsulation in Java is a mechanism of wrapping the code and data (variables)acting
on the data (methods) together as a single unit. In encapsulation, the variables of a
class will be hidden from other classes and can be accessed only through the methods
of their current class.
33. What is jvm in java?
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.
34. What is java programming?
Java is a powerful general-purpose programming language. It is used to develop
desktop and mobile applications, big data processing, embedded systems, and so on.
According to Oracle, the company that owns Java, Java runs on 3 billion devices
worldwide, which makes Java one of the most popular programming languages.
35. How hashmap works internally in java?
HashMap in Java works on hashing principles. It is a data structure which allows us to
store object and retrieve it in constant time O(1) provided we know the key. In hashing,
hash functions are used to link key and value in HashMap.
36. Who invented java?
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.
Now, type ‘ HelloWorld ‘ to run your program.
You will be able to see the result printed on the window.
38. How to get input from user in java?
"import java.util.Scanner; // Import the Scanner class
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
}
}"
39. What is bytecode in java?
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.
40. How to set classpath in java?
● Select Start, select Control Panel, double click System, and select the
Advanced tab.
● Click Environment Variables. In the section System Variables, find the PATH
environment variable and select it.
● In the Edit System Variable (or New System Variable) window, specify the
value of the PATH environment variable. Click OK.
41. How to connect database in java?
● Install or locate the database you want to access.
● Include the JDBC library.
● Ensure the JDBC driver you need is on your classpath.
● Use the JDBC library to obtain a connection to the database.
● Use the connection to issue SQL commands.
42. What is enum in java?
An enum is a special “class” that represents a group of constants (unchangeable
variables, like final variables). To create an enum, use the enum keyword (instead of
class or interface), and separate the constants with a comma.
43. How to uninstall java?
● 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
44. How to find duplicate characters in a string in java?
"public class Example {
public static void main(String argu[]) {
String str = ""beautiful beach"";
char[] carray = str.toCharArray();
System.out.println(""The string is:"" + str);
System.out.print(""Duplicate Characters in above string
are: "");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (carray[i] == carray[j]) {
System.out.print(carray[j] + "" "");
break;
}
}
}
}
}"
45. How to take character input in java?
"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);
}
} "
46. how to read string in java?
"import java.util.Scanner; // Import the Scanner class
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
}
}"
47. How to round off numbers in java?
"import java.lang.Math; // Needed to use Math.round()
class Program {
public static void main( String args[] ) {
double num1 = 74.65;
System.out.println(Math.round(num1));
float num2 = 1337.345523f;
System.out.println(Math.round(num2));
}
}"
48. How to get current date in java?
"DateFormat df = new SimpleDateFormat(""dd/MM/yy HH:mm:ss"");
Date dateobj = new Date();
System.out.println(df.format(dateobj));"
49. What is dao in java?
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?
The Abstract Window Toolkit (AWT) is Java’s original platform-dependent windowing,
graphics, and user-interface widget toolkit, preceding Swing. The AWT is part of the
Java Foundation Classes (JFC) — the standard API for providing a graphical user
interface (GUI) for a Java program. AWT is also the GUI toolkit for a number of Java ME
profiles. For example, Connected Device Configuration profiles require Java runtimes
on mobile telephones to support the Abstract Window Toolkit.
51. What is framework 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.
52. How to update java?
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.
53. How to run java program in command prompt?
execute java <programName.java>
54. What is variable in java?
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.
55. What is the difference between java and javascript?
The main differences between JavaScript and Java are:
1. JavaScript is used for Front End development while java is used for Back End
Development. i.e.
JavaScript is responsible for the dynamic behaviour of a webpage. Mainly, JavaScript
handles events, cookies, ajax (Asynchronous JavaScript and XML), etc. in a website.
JavaScript is the heart of a Dynamic User Interface of a Web Page while Java is the
best programming language for software engineers and can be used with JSP (Java
Server pages) for handling back end.
2. Java Script is dynamically typed language and Java is Statically typed language: i.e
In JavaScript, datatype of one variable can be changed:
var string = “hello world”;
string = 4;
document.write(string); //OUTPUT IS 4
document.write( ) will now print ‘4′ on the browser.
But in Java, the datatype of one variable cannot be changed and Java shows the error.
int number = 45;
number = “hello world”; //ERROR!!!!!!!
3. JavaScript is a scripting language while Java is a programming language:
Like other languages, Java also needs a compiler for building and running the programs
while JavaScript scripts are read and manipulated by the browser.
4. Java and JavaScript are very different in their SYNTAX.
For example:
Hello World Program in JAVA:
public class hello
{
public static void main(String[] args)
{
System.out.println("Hello World");
}
}
Hello World Program in JavaScript:
<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.
56. How to count the number of occurrences of a character
in a string in java?
"import java.util.HashMap;
public class EachCharCountInString
{
private static void characterCount(String inputString)
{
//Creating a HashMap containing char as a key and
occurrences as a value
HashMap<Character, Integer> charCountMap = new
HashMap<Character, Integer>();
//Converting given string to char array
char[] strArray = inputString.toCharArray();
//checking each char of strArray
for (char c : strArray)
{
if(charCountMap.containsKey(c))
{
//If char 'c' is present in charCountMap,
incrementing it's count by 1
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);
}
}
//Printing inputString and charCountMap
System.out.println(inputString+"" : ""+charCountMap);
}
public static void main(String[] args)
{
characterCount(""Java J2EE Java JSP J2EE"");
characterCount(""All Is Well"");
characterCount(""Done And Gone"");
}
}"
57. how to read excel file in java?
"FileInputStream fis = new FileInputStream(new
File(""WriteSheet.xlsx""));
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet spreadsheet = workbook.getSheetAt(0);
Iterator < Row > rowIterator = spreadsheet.iterator();
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();"
58. What is a method in java?
Functions are also known as methods in java.
59. How to read csv file in java?
"public static void readDataLineByLine(String file)
{
try {
// Create an object of filereader
// class with CSV file as a parameter.
FileReader filereader = new FileReader(file);
// create csvReader object passing
// file reader as a parameter
CSVReader csvReader = new CSVReader(filereader);
String[] nextRecord;
// we are going to read data line by line
while ((nextRecord = csvReader.readNext()) != null) {
for (String cell : nextRecord) {
System.out.print(cell + ""\t"");
}
System.out.println();
}
}
catch (Exception e) {
e.printStackTrace();
}
} "
60. How to check java version in windows?
type java -version on command prompt.
61. What is public static void main in java?
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.
62. Why we use interface in java?
It is used to achieve total abstraction. Since java does not support multiple inheritance
in the 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.
63. What is the purpose of serialization in java?
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.
64. What is functional interface in java?
A functional interface in Java is an interface that contains only a single abstract
(unimplemented) method. A functional interface can contain default and static methods
which do have an implementation, in addition to the single unimplemented method.
65. What is this keyword in java?
The this keyword refers to the current object in a method or constructor. The most
common use of the this keyword is to eliminate the confusion between class attributes
and parameters with the same name (because a class attribute is shadowed by a
method or constructor parameter).
66. How was java initially named?
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.
67. How to remove duplicate elements from array in java?
"public class Change
{
public static int removeDuplicate(int[] arrNumbers, int num)
{
if(num == 0 || num == 1)
{
return num;
}
int[] arrTemporary = new int[num];
int b = 0;
for(int a = 0; a < num - 1; a++)
{
if(arrNumbers[a] != arrNumbers[a + 1])
{
arrTemporary[b++] = arrNumbers[a];
}
}
arrTemporary[b++] = arrNumbers[num - 1];
for(int a = 0; a < b; a++)
{
arrNumbers[a] = arrTemporary[a];
}
return b;
}
public static void main(String[] args)
{
int[] arrInput = {1, 2, 3, 3, 4, 5, 5, 6, 7, 8};
int len = arrInput.length;
len = removeDuplicate(arrInput, len);
// printing elements
for(int a = 0; a < len; a++)
{
System.out.print(arrInput[a] + "" "");
}
}
}
"
68. What is difference between throw and throws in java?
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.
69. What is classpath in java?
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.)
70. Why is Java Platform Independent?
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.
71. What is Method overloading? Why is it used in Java?
Method overriding is a process in which methods inherited by child classes from parent
classes are modified as per requirement by the child class. It’s helpful in hierarchical
system design where objects share common properties.
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");
}
}
class Dog extends Animal{
void sound(){
System.out.println("Bark");
}
}
public class OverRide{
public static void main(String args[]){
Cat c=new Cat();
c.sound();
Dog d=new Dog();
d.sound();
}
}
72. What is Method overloading? Why is it used in Java?
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:
println() prints any data type passed to it as a string.
public class Add_Overload {
void add(int x, int y){
System.out.println(x+y);
}
void add(double x, double y){
System.out.println(x+y);
}
void add(double x, int y){
System.out.println(x+y);
}
public static void main(String args[]){
Add_Overload a= new Add_Overload();
a.add(10,20);
a.add(20.11,11.22);
a.add(20.11,2);
}
73. Why is Java Robust?
Java is termed as robust because of the following features:
– 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 has strong memory management.
– Java supports dynamic linking.
74. Why is Java Secure?
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.
75. What is the difference between JDK, JRE, and JVM?
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.
76. What are the features of Java?
Java is a pure Object Oriented Programming Language with the following features:
– High Performance
– Platform Independent
– Robust
– Multi-threaded
– Simple
– Secure
77. Does Java Support Pointers?
Pointers are not supported in java to make it more secure.
You can also go through this Java Tutorial to understand better.
78. Why are Static variables used in Java?
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.
public class static_variable {
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();
}
}
79. What are static methods, static variables, and static
blocks?
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.
80. What’s the use of static methods?
Static methods are used when there is no requirement of instantiating a class. If a
method is not going to change or overridden then it can be made static.
81. What’s the use of static variables?
Static variables are used for maintaining a common state of certain data which is
modifiable and accessible by all instances of a class.
82. What are the interfaces?
An interface is a collection of constants, static methods, abstract methods, and default
methods. Methods in an interface do not have a body.
83. How is Abstraction achieved in Java?
Abstraction is achieved in Java by the use of abstract class and abstract methods.
84. Why are strings immutable in Java?
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.
85. What are wrapper classes in Java?
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.
87. Are static methods allowed in a Java interface?
Yes, static methods are allowed in java interfaces. They are treated as default methods
so they need not be implemented.
88. How is garbage collection done in Java?
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.
89. Can there be two main methods in a 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.
90. Can private variables be inherited?
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.
91. Can the size of an array be increased after declaration?
The size of a java array cannot be increased after declaration. This is a limitation of
Java arrays.
92. What is the size of the below array in memory?
int a[]=new int[10];
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.
93. How many data types does java support?
Java supports 8 primitive data types, namely byte, short, int, long, float, double, char,
boolean.
94. How to find out the ASCII value of a character in java?
int c=char(‘A’) would give the ASCII value of A in java.
95. How to get a string as user input from the console?
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.
96. How to check the size of strings?
The size of strings in java can be checked by using the length() function.
97. How can we sort a list of elements in Java?
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.
98. If we sort a list of strings how would be the strings
arranged? The strings would be arranged alphabetically in
ascending order.
99. The difference between throw and throws in Java?
Throw is used to actually throw an instance of java.lang.Throwable class, which means
you can throw both Error and Exception using throw keyword e.g.
throw new IllegalArgumentException("size must be multiple of 2")
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.
100. Can we make an array volatile in Java?
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.
.
0 Comments