Name some classes present in java.util.regex package.
“There are the following classes and interfaces present in java.util.regex package.
Match Result Interface
Matcher class
Pattern class
PatternSyntaxException class”
How the metacharacters are different from the ordinary characters?
Metacharacters have the special meaning to the regular expression engine. The metacharacters are ^, $, ., *, +, etc. The regular expression engine does not consider them as the regular characters. To enable the regular expression engine treating the metacharacters as ordinary characters, we need to escape the metacharacters with the backslash.
What is the output of the following Java program?
“import java.util.regex.*;
class RegexExample2{
public static void main(String args[]){
System.out.println(Pattern.matches(“”.s””, “”as””)); //line 4
System.out.println(Pattern.matches(“”.s””, “”mk””)); //line 5
System.out.println(Pattern.matches(“”.s””, “”mst””)); //line 6
System.out.println(Pattern.matches(“”.s””, “”amms””)); //line 7
System.out.println(Pattern.matches(“”..s””, “”mas””)); //line 8
}}
Output
true
false
false
false
true
Explanation
line 4 prints true since the second character of string is s, line 5 prints false since the second character is not s, line 6 prints false since there are more than 3 characters in the string, line 7 prints false since there are more than 2 characters in the string, and it contains more than 2 characters as well, line 8 prints true since the third character of the string is s.”
Java Interview Questions
What are the advantages of Java inner classes?
“There are two types of advantages of Java inner classes.
Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of the outer class including private.
Nested classes are used to develop a more readable and maintainable code because it logically groups classes and interfaces in one place only.
Code Optimization: It requires less code to write.”
What is a nested class?
“The nested class can be defined as the class which is defined inside another class or interface. We use the nested class to logically group classes and interfaces in one place so that it can be more readable and maintainable. A nested class can access all the data members of the outer class including private data members and methods. The syntax of the nested class is defined below.
class Java_Outer_class{
//code
class Java_Nested_class{
//code
}
}
There are two types of nested classes, static nested class, and non-static nested class. The non-static nested class can also be called as inner-class
How many class files are created on compiling the Outer Class in the following program?
“public class Person {
String name, age, address;
class Employee{
float salary=10000;
}
class BusinessMen{
final String gstin=””£4433drt3$””;
}
public static void main (String args[])
{
Person p = new Person();
}
}
3 class-files will be created named as Person.class, Person$BusinessMen.class, and Person$Employee.class.”
Advance Java Interview Questions
What are anonymous inner classes?
“Anonymous inner classes are the classes that are automatically declared and instantiated within an expression. We cannot apply different access modifiers to them. Anonymous class cannot be static, and cannot define any static fields, method, or class. In other words, we can say that it a class without the name and can have only one object that is created by its definition. Consider the following example.
abstract class Person{
abstract void eat();
}
class TestAnonymousInner{
public static void main(String args[]){
Person p=new Person(){
void eat(){System.out.println(“”nice fruits””);}
};
p.eat();
}
}
Test it Now
Output:
nice fruits
Consider the following example for the working of the anonymous class using interface.
interface Eatable{
void eat();
}
class TestAnnonymousInner1{
public static void main(String args[]){
Eatable e=new Eatable(){
public void eat(){System.out.println(“”nice fruits””);}
};
e.eat();
}
}
Test it Now
Output:
nice fruits”
What is the nested interface?
“An Interface that is declared inside the interface or class is known as the nested interface. It is static by default. The nested interfaces are used to group related interfaces so that they can be easy to maintain. The external interface or class must refer to the nested interface. It can’t be accessed directly. The nested interface must be public if it is declared inside the interface but it can have any access modifier if declared within the class. The syntax of the nested interface is given as follows.
interface interface_name{
…
interface nested_interface_name{
…
}
} “
What is Garbage Collection?
Garbage collection is a process of reclaiming the unused runtime objects. It is performed for memory management. In other words, we can say that It is the process of removing unused objects from the memory to free up space and make this space available for Java Virtual Machine. Due to garbage collection java gives 0 as output to a variable whose value is not set, i.e., the variable has been defined but not initialized. For this purpose, we were using free() function in the C language and delete() in C++. In Java, it is performed automatically. So, java provides better memory management.
Java Interview Questions
What is gc()?
“The gc() method is used to invoke the garbage collector for cleanup processing. This method is found in System and Runtime classes. This function explicitly makes the Java Virtual Machine free up the space occupied by the unused objects so that it can be utilized or reused. Consider the following example for the better understanding of how the gc() method invoke the garbage collector.
public class TestGarbage1{
public void finalize(){System.out.println(“”object is garbage collected””);}
public static void main(String args[]){
TestGarbage1 s1=new TestGarbage1();
TestGarbage1 s2=new TestGarbage1();
s1=null;
s2=null;
System.gc();
}
}
Test it Now
object is garbage collected
object is garbage collected”
How is garbage collection controlled?
Garbage collection is managed by JVM. It is performed when there is not enough space in the memory and memory is running low. We can externally call the System.gc() for the garbage collection. However, it depends upon the JVM whether to perform it or not.
How can an object be unreferenced?
“There are many ways:
By nulling the reference
By assigning a reference to another
By anonymous object etc.
Java Garbage Collection Scenario
1) By nulling a reference:
Employee e=new Employee();
e=null;
2) By assigning a reference to another:
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection
3) By anonymous object:
new Employee(); “
Advance Java Interview Questions
What is the purpose of the finalize() method?
“The finalize() method is invoked just before the object is garbage collected. It is used to perform cleanup processing. The Garbage collector of JVM collects only those objects that are created by new keyword. So if you have created an object without new, you can use the finalize method to perform cleanup processing (destroying remaining objects). The cleanup processing is the process to free up all the resources, network which was previously used and no longer needed. It is essential to remember that it is not a reserved keyword, finalize method is present in the object class hence it is available in every class as object class is the superclass of every class in java. Here, we must note that neither finalization nor garbage collection is guaranteed. Consider the following example.
public class FinalizeTest {
int j=12;
void add()
{
j=j+12;
System.out.println(“”J=””+j);
}
public void finalize()
{
System.out.println(“”Object is garbage collected””);
}
public static void main(String[] args) {
new FinalizeTest().add();
System.gc();
new FinalizeTest().add();
}
} “
What is the purpose of the Runtime class?
“Java Runtime class is used to interact with a java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory, etc. There is only one instance of java.lang.Runtime class is available for one java application. The Runtime.getRuntime() method returns the singleton instance of Runtime class.
How will you invoke any external process in Java?
“By Runtime.getRuntime().exec(?) method. Consider the following example.
public class Runtime1{
public static void main(String args[])throws Exception{
Runtime.getRuntime().exec(“”notepad””);//will open a new notepad
}
} “
Java Interview Questions
What do you understand by an IO stream?
“The stream is a sequence of data that flows from source to destination. It is composed of bytes. In Java, three streams are created for us automatically.
System.out: standard output stream
System.in: standard input stream
System.err: standard error stream”
What are the super most classes for all the streams?
All the stream classes can be divided into two types of classes that are ByteStream classes and CharacterStream Classes. The ByteStream classes are further divided into InputStream classes and OutputStream classes. CharacterStream classes are also divided into Reader classes and Writer classes. The SuperMost classes for all the InputStream classes is java.io.InputStream and for all the output stream classes is java.io.OutPutStream. Similarly, for all the reader classes, the super-most class is java.io.Reader, and for all the writer classes, it is java.io.Writer.
What are the FileInputStream and FileOutputStream?
“Java FileOutputStream is an output stream used for writing data to a file. If you have some primitive values to write into a file, use FileOutputStream class. You can write byte-oriented as well as character-oriented data through the FileOutputStream class. However, for character-oriented data, it is preferred to use FileWriter than FileOutputStream. Consider the following example of writing a byte into a file.
import java.io.FileOutputStream;
public class FileOutputStreamExample {
public static void main(String args[]){
try{
FileOutputStream fout=new FileOutputStream(“”D:\testout.txt””);
fout.write(65);
fout.close();
System.out.println(“”success…””);
}catch(Exception e){System.out.println(e);}
}
}
Java FileInputStream class obtains input bytes from a file. It is used for reading byte-oriented data (streams of raw bytes) such as image data, audio, video, etc. You can also read character-stream data. However, for reading streams of characters, it is recommended to use FileReader class. Consider the following example for reading bytes from a file.
import java.io.FileInputStream;
public class DataStreamExample {
public static void main(String args[]){
try{
FileInputStream fin=new FileInputStream(“”D:\testout.txt””);
int i=fin.read();
System.out.print((char)i);
fin.close();
}catch(Exception e){System.out.println(e);}
}
} "
Advance Java Interview Questions
How to set the Permissions to a file in Java?
“In Java, File Permission class is used to alter the permissions set on a file. Java File Permission class contains the permission related to a directory or file. All the permissions are related to the path. The path can be of two types:
D:\IO\-: It indicates that the permission is associated with all subdirectories and files recursively.
D:\IO\*: It indicates that the permission is associated with all directory and files within this directory excluding subdirectories.
Let’s see the simple example in which permission of a directory path is granted with read permission and a file of this directory is granted for write permission.
package com.javatpoint;
import java.io.*;
import java.security.PermissionCollection;
public class FilePermissionExample{
public static void main(String[] args) throws IOException {
String srg = “”D:\IO Package\java.txt””;
FilePermission file1 = new FilePermission(“”D:\IO Package\-“”, “”read””);
PermissionCollection permission = file1.newPermissionCollection();
permission.add(file1);
FilePermission file2 = new FilePermission(srg, “”write””);
permission.add(file2);
if(permission.implies(new FilePermission(srg, “”read,write””))) {
System.out.println(“”Read, Write permission is granted for the path “”+srg );
}else {
System.out.println(“”No Read, Write permission is granted for the path “”+srg); }
}
}
What are Filter Streams?
Filter Stream classes are used to add additional functionalities to the other stream classes. Filter Stream classes act like an interface which read the data from a stream, filters it, and pass the filtered data to the caller. The Filter Stream classes provide extra functionalities like adding line numbers to the destination file, etc.
What is an I/O filter?
An I/O filter is an object that reads from one stream and writes to another, usually altering the data in some way as it is passed from one stream to another. Many Filter classes that allow a user to make a chain using multiple input streams. It generates a combined effect on several filters.
What is serialization?
Serialization in Java is a mechanism of writing the state of an object into a byte stream. It is used primarily in Hibernate, RMI, JPA, EJB and JMS technologies. It is mainly used to travel object’s state on the network (which is known as marshaling). Serializable interface is used to perform serialization. It is helpful when you require to save the state of a program to storage such as the file. At a later point of time, the content of this file can be restored using deserialization. It is also required to implement RMI(Remote Method Invocation). With the help of RMI, it is possible to invoke the method of a Java object on one machine to another machine.
Java Interview Questions
Can a Serialized object be transferred via network?
Yes, we can transfer a serialized object via network because the serialized object is stored in the memory in the form of bytes and can be transmitted over the network. We can also write the serialized object to the disk or the database.
What is Deserialization?
“Deserialization is the process of reconstructing the object from the serialized state. It is the reverse operation of serialization. An Object Input Stream deserializes objects and primitive data written using an Object Output Stream.
import java.io.*;
class Depersist{
public static void main(String args[])throws Exception{
ObjectInputStream in=new ObjectInputStream(new FileInputStream(“”f.txt””));
Student s=(Student)in.readObject();
System.out.println(s.id+”” “”+s.name);
in.close();
}
} “
What is the transient keyword?
If you define any data member as transient, it will not be serialized. By determining transient keyword, the value of variable need not persist when it is restored.
Advance Java Interview Questions
What is Externalizable?
The Externalizable interface is used to write the state of an object into a byte stream in a compressed format. It is not a marker interface.
Give a brief description of Java socket programming?
“Java Socket programming is used for communication between the applications running on different JRE. Java Socket programming can be connection-oriented or connectionless. Socket and Server Socket classes are used for connection-oriented socket programming and Datagram Socket, and Datagram Packet classes are used for connectionless socket programming. The client in socket programming must know two information:
IP address of the server
port number”
What is Socket?
A socket is simply an endpoint for communications between the machines. It provides the connection mechanism to connect the two computers using TCP. The Socket class can be used to create a socket.
Java Interview Questions
What are the steps that are followed when two computers connect through TCP?
“There are the following steps that are performed when two computers connect through TCP.
The Server Socket object is instantiated by the server which denotes the port number to which, the connection will be made.
After instantiating the Server Socket object, the server invokes accept() method of Server Socket class which makes server wait until the client attempts to connect to the server on the given port.
Meanwhile, the server is waiting, a socket is created by the client by instantiating Socket class. The socket class constructor accepts the server port number and server name.
The Socket class constructor attempts to connect with the server on the specified name. If the connection is established, the client will have a socket object that can communicate with the server.
The accept() method invoked by the server returns a reference to the new socket on the server that is connected with the server.”
Write a program in Java to establish a connection between client and server?
“Consider the following program where the connection between the client and server is established.
File: MyServer.java
import java.io.; import java.net.;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println(“”message= “”+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}
File: MyClient.java
import java.io.; import java.net.;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket(“”localhost””,6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF(“”Hello Server””);
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
} “
What is the reflection?
“Reflection is the process of examining or modifying the runtime behavior of a class at runtime. The java.lang.Class class provides various methods that can be used to get metadata, examine and change the runtime behavior of a class. The java.lang and java.lang.reflect packages provide classes for java reflection. It is used in:
IDE (Integrated Development Environment), e.g., Eclipse, MyEclipse, NetBeans.
Debugger
Test Tools, etc.”
Advance Java Interview Questions
What is the purpose of using java.lang.Class class?
“The java.lang.Class class performs mainly two tasks:
Provides methods to get the metadata of a class at runtime.
Provides methods to examine and change the runtime behavior of a class.”
What are the ways to instantiate the Class class?
“There are three ways to instantiate the Class class.
for Name() method of Class class: The for Name() method is used to load the class dynamically. It returns the instance of Class class. It should be used if you know the fully qualified name of the class. This cannot be used for primitive types.
get Class() method of Object class: It returns the instance of Class class. It should be used if you know the type. Moreover, it can be used with primitives.
the .class syntax: If a type is available, but there is no instance then it is possible to obtain a Class by appending “”.class”” to the name of the type. It can be used for primitive data type also.”
What is the output of the following Java program?
“class Simple{
public Simple()
{
System.out.println(“”Constructor of Simple class is invoked””);
}
void message(){System.out.println(“”Hello Java””);}
}
class Test1{
public static void main(String args[]){
try{
Class c=Class.forName(“”Simple””);
Simple s=(Simple)c.newInstance();
s.message();
}catch(Exception e){System.out.println(e);}
}
}
Output
Constructor of Simple class is invoked
Hello Java
Explanation
The newInstance() method of the Class class is used to invoke the constructor at runtime. In this program, the instance of the Simple class is created.
Java Interview Questions
What is the purpose of using javap?
“The javap command disassembles a class file. The javap command displays information about the fields, constructors and methods present in a class file.
Syntax
javap fully_class_name”
What are autoboxing and unboxing? When does it occur?
“The autoboxing is the process of converting primitive data type to the corresponding wrapper class object, eg., int to Integer. The unboxing is the process of converting wrapper class object to primitive data type. For eg., integer to int. Unboxing and autoboxing occur automatically in Java. However, we can externally convert one into another by using the methods like value Of() or xxxValue().
It can occur whenever a wrapper class object is expected, and primitive data type is provided or vice versa.
Adding primitive types into Collection like ArrayList in Java.
Creating an instance of parameterized classes ,e.g., ThreadLocal which expect Type.
Java automatically converts primitive to object whenever one is required and another is provided in the method calling.
When a primitive type is assigned to an object type.”
What is the output of the below Java program?
“public class Test1
{
public static void main(String[] args) {
Integer i = new Integer(201);
Integer j = new Integer(201);
if(i == j)
{
System.out.println(“”hello””);
}
else
{
System.out.println(“”bye””);
}
}
}
Output
bye
Explanation
The Integer class caches integer values from -127 to 127. Therefore, the Integer objects can only be created in the range -128 to 127. The operator == will not work for the value greater than 127; thus bye is printed.”
protected Object clone() throws CloneNotSupportedException”
Advance Java Interview Questions
What are the advantages and disadvantages of object cloning?
“Advantage of Object Cloning
You don’t need to write lengthy and repetitive codes. Just use an abstract class with a 4- or 5-line long clone() method.
It is the easiest and most efficient way of copying objects, especially if we are applying it to an already developed or an old project. Just define a parent class, implement Cloneable in it, provide the definition of the clone() method and the task will be done.
Clone() is the fastest way to copy the array.
Disadvantage of Object Cloning
To use the Object.clone() method, we have to change many syntaxes to our code, like implementing a Cloneable interface, defining the clone() method and handling CloneNotSupportedException, and finally, calling Object.clone(), etc.
We have to implement the Cloneable interface while it does not have any methods in it. We have to use it to tell the JVM that we can perform a clone() on our object.
Object.clone() is protected, so we have to provide our own clone() and indirectly call Object.clone() from it.
Object.clone() does not invoke any constructor, so we do not have any control over object construction.
If you want to write a clone method in a child class, then all of its superclasses should define the clone() method in them or inherit it from another parent class. Otherwise, the super.clone() chain will fail.
Object.clone() supports only shallow copying, but we will need to override it if we need deep cloning.”
A native method is a method that is implemented in a language other than Java. Natives methods are sometimes also referred to as foreign methods.
What is the purpose of the strictfp keyword?
Java strict keyword ensures that you will get the same result on every platform if you perform operations in the floating-point variable. The precision may differ from platform to platform that is why java programming language has provided the strictfp keyword so that you get the same result on every platform. So, now you have better control over the floating-point arithmetic.
What is the purpose of the System class?
“The purpose of the System class is to provide access to system resources such as standard input and output. It cannot be instantiated. Facilities provided by System class are given below.
Standard input
Error output streams
Standard output
utility method to copy the portion of an array
utilities to load files and libraries
There are the three fields of Java System class, i.e., static printstream err, static inputstream in, and standard output stream.”
Java Interview Questions
What is a singleton class?
“Singleton class is the class which can not be instantiated more than once. To make a class singleton, we either make its constructor private or use the static get Instance method. Consider the following example.
class Singleton{
private static Singleton single_instance = null;
int i;
private Singleton ()
{
i=90;
}
public static Singleton getInstance()
{
if(single_instance == null)
{
single_instance = new Singleton();
}
return single_instance;
}
}
public class Main
{
public static void main (String args[])
{
Singleton first = Singleton.getInstance();
System.out.println(“”First instance integer value:””+first.i);
first.i=first.i+90;
Singleton second = Singleton.getInstance();
System.out.println(“”Second instance integer value:””+second.i);
}
} “
Write a Java program that prints all the values given at command-line.
“Program
class A{
public static void main(String args[]){
for(int i=0;i<args.length;i++)
System.out.println(args[i]);
}
}
compile by > javac A.java
run by > java A sonoo jaiswal 1 3 abc
Output
sonoo
jaiswal
1
3
abc “
What are peerless components?
The lightweight component of Swing is called peerless components. Spring has its libraries, so it does not use resources from the Operating System, and hence it has lightweight components.
Advance Java Interview Questions
What is a lightweight component?
Lightweight components are the one which does not go with the native call to obtain the graphical units. They share their parent component graphical units to render them. For example, Swing components, and JavaFX Components.
What is a heavyweight component?
The portable elements provided by the operating system are called heavyweight components. AWT is limited to the graphical classes provided by the operating system and therefore, It implements only the minimal subset of screen elements supported by all platforms. The Operating system dependent UI discovery tools are called heavyweight components.
What is an applet?
“An applet is a small java program that runs inside the browser and generates dynamic content. It is embedded in the webpage and runs on the client side. It is secured and takes less response time. It can be executed by browsers running under many platforms, including Linux, Windows, Mac Os, etc. However, the plugins are required at the client browser to execute the applet. The following image shows the architecture of Applet.
hierarchy of applet
When an applet is created, the following methods are invoked in order.
init()
start()
paint()
When an applet is destroyed, the following functions are invoked in order.
stop()
destroy()”
Java Interview Questions
What is Locale?
“A Locale object represents a specific geographical, political, or cultural region. This object can be used to get the locale-specific information such as country name, language, variant, etc.
import java.util.*;
public class LocaleExample {
public static void main(String[] args) {
Locale locale=Locale.getDefault();
//Locale locale=new Locale(“”fr””,””fr””);//for the specific locale
System.out.println(locale.getDisplayCountry());
System.out.println(locale.getDisplayLanguage());
System.out.println(locale.getDisplayName());
System.out.println(locale.getISO3Country());
System.out.println(locale.getISO3Language());
System.out.println(locale.getLanguage());
System.out.println(locale.getCountry());
}
}
Output:
United States
English
English (United States)
USA
eng
en
US”
What is a JavaBean?
“JavaBean is a reusable software component written in the Java programming language, designed to be manipulated visually by a software development environment, like JBuilder or VisualAge for Java. t. A JavaBean encapsulates many objects into one object so that we can access this object from multiple places. Moreover, it provides the easy maintenance. Consider the following example to create a JavaBean class.
//Employee.java
package mypack;
public class Employee implements java.io.Serializable{
private int id;
private String name;
public Employee(){}
public void setId(int id){this.id=id;}
public int getId(){return id;}
public void setName(String name){this.name=name;}
public String getName(){return name;}
} “