hereral/Clara-Training-Data huggingface dataset:
Question: How to access package from another package?
Answer: There are three ways to access the package from outside the package.

1.import package.*;
2.import package.classname;
3.fully qualified name.
Question: What is Using packagename?
Answer: If you use package.* then all the classes and interfaces of this package will be accessible but not subpackages.

The import keyword is used to make the classes and interface of another package accessible to the current package.
Question: Can you provide an Example of package that import the packagename?
Answer: //save by A.java  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello
Question: What is Using packagename.classname?
Answer: If you import package.classname then only declared class of this package will be accessible.
Question: Can you provide an Example of package by import package.classname?
Answer: //save by A.java  
  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.A;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello
Question: How the Using fully qualified name work?
Answer: If you use fully qualified name then only declared class of this package will be accessible. Now there is no need to import. But you need to use fully qualified name every time when you are accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages contain Date class.
Question: Can you provide an Example of package by import fully qualified name?
Answer: //save by A.java  
package pack;  
public class A{  
  public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
class B{  
  public static void main(String args[]){  
   pack.A obj = new pack.A();//using fully qualified name  
   obj.msg();  
  }  
}  
Output:Hello
Question: What is Subpackage in java?
Answer: Package inside the package is called the subpackage. It should be created to categorize the package further.
Question: Can you provide an Example of Subpackage?
Answer: package com.javatpoint.core;  
class Simple{  
  public static void main(String args[]){  
   System.out.println("Hello subpackage");  
  }  
}  
To Compile: javac -d . Simple.java
To Run: java com.javatpoint.core.Simple
Output:Hello subpackage
Question: What are the Ways to load the class files or jar files?
Answer: There are two ways to load the class files temporary and permanent.
-Temporary
By setting the classpath in the command prompt
By -classpath switch
-Permanent
By setting the classpath in the environment variables
By creating the jar file, that contains all the class files, and copying the jar file in the jre/lib/ext folder.
Question: How to put two public classes in a package?
Answer: If you want to put two public classes in a package, have two java source files containing one public class, but keep the package name same. For example:
//save as A.java  
  
package javatpoint;  
public class A{}  
//save as B.java  
  
package javatpoint;  
public class B{}
Question: What is Access Modifiers in Java?
Answer: There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method, constructor, or class. We can change the access level of fields, constructors, methods, and class by applying the access modifier on it.
There are four types of Java access modifiers:

1.Private: The access level of a private modifier is only within the class. It cannot be accessed from outside the class.
2.Default: The access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.
3.Protected: The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.
4.Public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc. Here, we are going to learn the access modifiers only.
Question: What is Private?
Answer: The private access modifier is accessible only within the class.

Simple example of private access modifier

In this example, we have created two classes A and Simple. A class contains private data member and private method. We are accessing these private members from outside the class, so there is a compile-time error.

class A{  
private int data=40;  
private void msg(){System.out.println("Hello java");}  
}  
  
public class Simple{  
 public static void main(String args[]){  
   A obj=new A();  
   System.out.println(obj.data);//Compile Time Error  
   obj.msg();//Compile Time Error  
   }  
}
Question: What is Default?
Answer: If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package. It cannot be accessed from outside the package. It provides more accessibility than private. But, it is more restrictive than protected, and public.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

//save by A.java  
package pack;  
class A{  
  void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
class B{  
  public static void main(String args[]){  
   A obj = new A();//Compile Time Error  
   obj.msg();//Compile Time Error  
  }  
}
Question: What is Protected?
Answer: The protected access modifier is accessible within package and outside the package but through inheritance only.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.

It provides more accessibility than the default modifer.

Example of protected access modifier

In this example, we have created the two packages pack and mypack. The A class of pack package is public, so can be accessed from outside the package. But msg method of this package is declared as protected, so it can be accessed from outside the class only through inheritance.

//save by A.java  
package pack;  
public class A{  
protected void msg(){System.out.println("Hello");}  
}  
//save by B.java  
package mypack;  
import pack.*;  
  
class B extends A{  
  public static void main(String args[]){  
   B obj = new B();  
   obj.msg();  
  }  
}  
Output:Hello
Question: What is Public?
Answer: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.

Example of public access modifier

//save by A.java  
  
package pack;  
public class A{  
public void msg(){System.out.println("Hello");}  
}  
//save by B.java  
  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  
}  
Output:Hello
Question: Can you provide an example of Java Access Modifiers with Method Overriding?
Answer: If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A{  
protected void msg(){System.out.println("Hello java");}  
}  
  
public class Simple extends A{  
void msg(){System.out.println("Hello java");}//C.T.Error  
 public static void main(String args[]){  
   Simple obj=new Simple();  
   obj.msg();  
   }  
}
Question: What is Encapsulation in Java?
Answer: Encapsulation in Java is a process of wrapping code and data together into a single unit, for example, a capsule which is mixed of several medicines.

encapsulation in java
We can create a fully encapsulated class in Java by making all the data members of the class private. Now we can use setter and getter methods to set and get the data in it.

The Java Bean class is the example of a fully encapsulated class.
Question: What is the Advantage of Encapsulation in Java?
Answer: By providing only a setter or getter method, you can make the class read-only or write-only. In other words, you can skip the getter or setter methods.
It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.It provides you the control over the data. Suppose you want to set the value of id which should be greater than 100 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.

It is a way to achieve data hiding in Java because other class will not be able to access the data through the private data members.

The encapsulate class is easy to test. So, it is better for unit testing.

The standard IDE's are providing the facility to generate the getters and setters. So, it is easy and fast to create an encapsulated class in Java.
Question: Can you provide Simple Example of Encapsulation in Java?
Answer: Let's see the simple example of encapsulation that has only one field with its setter and getter methods.
//A Java class which is a fully encapsulated class.  
//It has a private data member and getter and setter methods.  
package com.javatpoint;  
public class Student{  
//private data member  
private String name;  
//getter method for name  
public String getName(){  
return name;  
}  
//A Java class to test the encapsulated class.  
package com.javatpoint;  
class Test{  
public static void main(String[] args){  
//creating instance of the encapsulated class  
Student s=new Student();  
//setting value in the name member  
s.setName("vijay");  
//getting value of the name member  
System.out.println(s.getName());  
}  
}  
Compile By: javac -d . Test.java
Run By: java com.javatpoint.Test
Output:

vijay
//setter method for name  
public void setName(String name){  
this.name=name  
}  
}
Question: What is Read-Only class?
Answer: //A Java class which has only getter methods.  
public class Student{  
//private data member  
private String college="AKG";  
//getter method for college  
public String getCollege(){  
return college;  
}  
}
Question: What is Write-Only class?
Answer: //A Java class which has only setter methods.  
public class Student{  
//private data member  
private String college;  
//getter method for college  
public void setCollege(String college){  
this.college=college;  
}  
}
Question: Can you provide Another Example of Encapsulation in Java?
Answer: Let's see another example of encapsulation that has only four fields with its setter and getter methods.
//A Account class which is a fully encapsulated class.  
//It has a private data member and getter and setter methods.  
class Account {  
//private data members  
private long acc_no;  
private String name,email;  
private float amount;  
//public getter and setter methods  
public long getAcc_no() {  
    return acc_no;  
}  
public void setAcc_no(long acc_no) {  
    this.acc_no = acc_no;  
}  
public String getName() {  
    return name;  
}  
public void setName(String name) {  
    this.name = name;  
}  
public String getEmail() {  
    return email;  
}  
public void setEmail(String email) {  
    this.email = email;  
}  
public float getAmount() {  
    return amount;  
}  
public void setAmount(float amount) {  
    this.amount = amount;  
}  
  
}  
//A Java class to test the encapsulated class Account.  
public class TestEncapsulation {  
public static void main(String[] args) {  
    //creating instance of Account class  
    Account acc=new Account();  
    //setting values through setter methods  
    acc.setAcc_no(7560504000L);  
    acc.setName("Sonoo Jaiswal");  
    acc.setEmail("sonoojaiswal@javatpoint.com");  
    acc.setAmount(500000f);  
    //getting values through getter methods  
    System.out.println(acc.getAcc_no()+" "+acc.getName()+" "+acc.getEmail()+" "+acc.getAmount());  
}  
}  
Output:

7560504000 Sonoo Jaiswal sonoojaiswal@javatpoint.com 500000.0
Question: What is Java Arrays?
Answer: Normally, an array is a collection of similar type of elements which has contiguous memory location.

Java array is an object which contains elements of a similar data type. Additionally, The elements of an array are stored in a contiguous memory location. It is a data structure where we store similar elements. We can store only a fixed set of elements in a Java array.

Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on.

Unlike C/C++, we can get the length of the array using the length member. In C/C++, we need to use the sizeof operator.

In Java, array is an object of a dynamically generated class. Java array inherits the Object class, and implements the Serializable as well as Cloneable interfaces. We can store primitive values or objects in an array in Java. Like C/C++, we can also create single dimentional or multidimentional arrays in Java.

Moreover, Java provides the feature of anonymous arrays which is not available in C/C++.

Advantages

-Code Optimization: It makes the code optimized, we can retrieve or sort the data efficiently.
-Random access: We can get any data located at an index position.
Disadvantages
-Size Limit: We can store only the fixed size of elements in the array. It doesn't grow its size at runtime. To solve this problem, collection framework is used
Question: What are the Types of Array in java?
Answer: There are two types of array.

-Single Dimensional Array
-Multidimensional Array
Question: WHat is Single Dimensional Array in Java?
Answer: 
Syntax to Declare an Array in Java

dataType[] arr; (or)  
dataType []arr; (or)  
dataType arr[];  

Instantiation of an Array in Java

arrayRefVar=new datatype[size];
Question: Can you provide an Example of Java Array?
Answer: Let's see the simple example of java array, where we are going to declare, instantiate, initialize and traverse an array.

//Java Program to illustrate how to declare, instantiate, initialize  
//and traverse the Java array.  
class Testarray{  
public static void main(String args[]){  
int a[]=new int[5];//declaration and instantiation  
a[0]=10;//initialization  
a[1]=20;  
a[2]=70;  
a[3]=40;  
a[4]=50;  
//traversing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
}}  

Output:
10
20
70
40
50
Question: Can you provide an example of Declaration, Instantiation and Initialization of Java Array?
Answer: We can declare, instantiate and initialize the java array together by:

int a[]={33,3,4,5};//declaration, instantiation and initialization  

Let's see the simple example to print this array.

//Java Program to illustrate the use of declaration, instantiation   
//and initialization of Java array in a single line  
class Testarray1{  
public static void main(String args[]){  
int a[]={33,3,4,5};//declaration, instantiation and initialization  
//printing array  
for(int i=0;i<a.length;i++)//length is the property of array  
System.out.println(a[i]);  
}}  

Output:
33
3
4
5
Question: Can you provide the For-each Loop for Java Array?
Answer: We can also print the Java array using for-each loop. The Java for-each loop prints the array elements one by one. It holds an array element in a variable, then executes the body of the loop.

The syntax of the for-each loop is given below:

for(data_type variable:array){  
//body of the loop  
}  

Let us see the example of print the elements of Java array using the for-each loop.

//Java Program to print the array elements using for-each loop  
class Testarray1{  
public static void main(String args[]){  
int arr[]={33,3,4,5};  
//printing array using for-each loop  
for(int i:arr)  
System.out.println(i);  
}}  

Output:
33
3
4
5
Question: Can you provide the Passing Array to a Method in Java?
Answer: We can pass the java array to method so that we can reuse the same logic on any array.

Let's see the simple example to get the minimum number of an array using a method.

//Java Program to demonstrate the way of passing an array  
//to method.  
class Testarray2{  
//creating a method which receives an array as a parameter  
static void min(int arr[]){  
int min=arr[0];  
for(int i=1;i<arr.length;i++)  
 if(min>arr[i])  
  min=arr[i];  
  
System.out.println(min);  
}  
  
public static void main(String args[]){  
int a[]={33,3,4,5};//declaring and initializing an array  
min(a);//passing array to method  
}}  

Output:

3
Question: Can you provide the Anonymous Array in Java?
Answer: Java supports the feature of an anonymous array, so you don't need to declare the array while passing an array to the method.

//Java Program to demonstrate the way of passing an anonymous array  
//to method.  
public class TestAnonymousArray{  
//creating a method which receives an array as a parameter  
static void printArray(int arr[]){  
for(int i=0;i<arr.length;i++)  
System.out.println(arr[i]);  
}  
  
public static void main(String args[]){  
printArray(new int[]{10,22,44,66});//passing anonymous array to method  
}}  

Output:
10
22
44
66
Question: Can you provide the Returning Array from the Method?
Answer: We can also return an array from the method in Java.

//Java Program to return an array from the method  
class TestReturnArray{  
//creating method which returns an array  
static int[] get(){  
return new int[]{10,30,50,90,60};  
}  
  
public static void main(String args[]){  
//calling method which returns an array  
int arr[]=get();  
//printing the values of an array  
for(int i=0;i<arr.length;i++)  
System.out.println(arr[i]);  
}}  

Output:
10
30
50
90
60
Question: Can you provide the ArrayIndexOutOfBoundsException?
Answer: The Java Virtual Machine (JVM) throws an ArrayIndexOutOfBoundsException if length of the array in negative, equal to the array size or greater than the array size while traversing the array.

//Java Program to demonstrate the case of   
//ArrayIndexOutOfBoundsException in a Java Array.  
public class TestArrayException{  
public static void main(String args[]){  
int arr[]={50,60,70,80};  
for(int i=0;i<=arr.length;i++){  
System.out.println(arr[i]);  
}  
}}  

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
        at TestArrayException.main(TestArrayException.java:5)
50
60
70
80
Question: What is Multidimensional Array in Java?
Answer: In such case, data is stored in row and column based index (also known as matrix form).

Syntax to Declare Multidimensional Array in Java
dataType[][] arrayRefVar; (or)  
dataType [][]arrayRefVar; (or)  
dataType arrayRefVar[][]; (or)  
dataType []arrayRefVar[];   

Example to instantiate Multidimensional Array in Java

int[][] arr=new int[3][3];//3 row and 3 column  

Example to initialize Multidimensional Array in Java

arr[0][0]=1;  
arr[0][1]=2;  
arr[0][2]=3;  
arr[1][0]=4;  
arr[1][1]=5;  
arr[1][2]=6;  
arr[2][0]=7;  
arr[2][1]=8;  
arr[2][2]=9;
Question: Can you provide an Example of Multidimensional Java Array?
Answer: arr[0][0]=1;  
arr[0][1]=2;  
arr[0][2]=3;  
arr[1][0]=4;  
arr[1][1]=5;  
arr[1][2]=6;  
arr[2][0]=7;  
arr[2][1]=8;  
arr[2][2]=9;
Question: What is Jagged Array in Java?
Answer: Let's see the simple example to declare, instantiate, initialize and print the 2Dimensional array.

//Java Program to illustrate the use of multidimensional array  
class Testarray3{  
public static void main(String args[]){  
//declaring and initializing 2D array  
int arr[][]={{1,2,3},{2,4,5},{4,4,5}};  
//printing 2D array  
for(int i=0;i<3;i++){  
 for(int j=0;j<3;j++){  
   System.out.print(arr[i][j]+" ");  
 }  
 System.out.println();  
}  
}}  

Output:
1 2 3
2 4 5
4 4 5
Question: What is the class name of Java array?
Answer: In Java, an array is an object. For array object, a proxy class is created whose name can be obtained by getClass().getName() method on the object.

//Java Program to get the class name of array in Java  
class Testarray4{  
public static void main(String args[]){  
//declaration and initialization of array  
int arr[]={4,4,5};  
//getting the class name of Java array  
Class c=arr.getClass();  
String name=c.getName();  
//printing the class name of Java array   
System.out.println(name);    
}}  

Output:
I
Question: Can you provide the Copying a Java Array?
Answer: We can copy an array to another by the arraycopy() method of System class.

Syntax of arraycopy method

public static void arraycopy(  
Object src, int srcPos,Object dest, int destPos, int length  
)
Question: What is the Example of Copying an Array in Java?
Answer: //Java Program to copy a source array into a destination array in Java  
class TestArrayCopyDemo {  
    public static void main(String[] args) {  
        //declaring a source array  
        char[] copyFrom = { 'd', 'e', 'c', 'a', 'f', 'f', 'e',  
                'i', 'n', 'a', 't', 'e', 'd' };  
        //declaring a destination array  
        char[] copyTo = new char[7];  
        //copying array using System.arraycopy() method  
        System.arraycopy(copyFrom, 2, copyTo, 0, 7);  
        //printing the destination array  
        System.out.println(String.valueOf(copyTo));  
    }  
}  

Output:
caffein
Question: Can you provide the Cloning an Array in Java?
Answer: Since, Java array implements the Cloneable interface, we can create the clone of the Java array. If we create the clone of a single-dimensional array, it creates the deep copy of the Java array. It means, it will copy the actual value. But, if we create the clone of a multidimensional array, it creates the shallow copy of the Java array which means it copies the references.

//Java Program to clone the array  
class Testarray1{  
public static void main(String args[]){  
int arr[]={33,3,4,5};  
System.out.println("Printing original array:");  
for(int i:arr)  
System.out.println(i);  
  
System.out.println("Printing clone of the array:");  
int carr[]=arr.clone();  
for(int i:carr)  
System.out.println(i);  
System.out.println("Are both equal?");  
System.out.println(arr==carr);  
  
}}  

Output:
Printing original array:
33
3
4
5
Printing clone of the array:
33
3
4
5
Are both equal?
false
Question: What is Addition of 2 Matrices in Java?
Answer: Let's see a simple example that adds two matrices.

//Java Program to demonstrate the addition of two matrices in Java  
class Testarray5{  
public static void main(String args[]){  
//creating two matrices  
int a[][]={{1,3,4},{3,4,5}};  
int b[][]={{1,3,4},{3,4,5}};  
  
//creating another matrix to store the sum of two matrices  
int c[][]=new int[2][3];  
  
//adding and printing addition of 2 matrices  
for(int i=0;i<2;i++){  
for(int j=0;j<3;j++){  
c[i][j]=a[i][j]+b[i][j];  
System.out.print(c[i][j]+" ");  
}  
System.out.println();//new line  
}  
  
}}  

Output:
2 6 8
6 8 10
Question: Can you provide the Multiplication of 2 Matrices in Java?
Answer: In the case of matrix multiplication, a one-row element of the first matrix is multiplied by all the columns of the second matrix.

Let's see a simple example to multiply two matrices of 3 rows and 3 columns.
//Java Program to multiply two matrices  
public class MatrixMultiplicationExample{  
public static void main(String args[]){  
//creating two matrices    
int a[][]={{1,1,1},{2,2,2},{3,3,3}};    
int b[][]={{1,1,1},{2,2,2},{3,3,3}};    
    
//creating another matrix to store the multiplication of two matrices    
int c[][]=new int[3][3];  //3 rows and 3 columns  
    
//multiplying and printing multiplication of 2 matrices    
for(int i=0;i<3;i++){    
for(int j=0;j<3;j++){    
c[i][j]=0;      
for(int k=0;k<3;k++)      
{      
c[i][j]+=a[i][k]*b[k][j];      
}//end of k loop  
System.out.print(c[i][j]+" ");  //printing matrix element  
}//end of j loop  
System.out.println();//new line    
}    
}}  

Output:
6 6 6 
12 12 12 
18 18 18
Question: What is Object class in Java?
Answer: The Object class is the parent class of all the classes in java by default. In other words, it is the topmost class of java.

The Object class is beneficial if you want to refer any object whose type you don't know. Notice that parent class reference variable can refer the child class object, know as upcasting.

Let's take an example, there is getObject() method that returns an object but it can be of any type like Employee,Student etc, we can use Object class reference to refer that object. For example:
Object obj=getObject();//we don't know what object will be returned from this method  

The Object class provides some common behaviors to all the objects such as object can be compared, object can be cloned, object can be notified etc.
Question: What are the Methods of Object class?
Answer: Methods of Object class
The Object class provides many methods. They are as follows:

Method: public final Class getClass()
Description: returns the Class class object of this object. The Class class can further be used to get the metadata of this class.

Method: public int hashCode()
Description: returns the hashcode number for this object.

Method: public boolean equals(Object obj)
Description: compares the given object to this object.

Method: protected Object clone() throws CloneNotSupportedException
creates and returns the exact copy (clone) of this object.

Method: public String toString()
Description: returns the string representation of this object.

Method: public final void notify()
Description: wakes up single thread, waiting on this object's monitor.

Method: public final void notifyAll()
Description: wakes up all the threads, waiting on this object's monitor.

Method: public final void wait(long timeout)throws InterruptedException
Description: causes the current thread to wait for the specified milliseconds, until another thread notifies (invokes notify() or notifyAll() method).

Method: public final void wait(long timeout,int nanos)throws InterruptedException
Description: causes the current thread to wait for the specified milliseconds and nanoseconds, until another thread notifies (invokes notify() or notifyAll() method).

Method: public final void wait()throws InterruptedException
Description: causes the current thread to wait, until another thread notifies (invokes notify() or notifyAll() method).

Method: protected void finalize()throws Throwable
Description: is invoked by the garbage collector before object is being garbage collected.
Question: What is Object Cloning in Java?
Answer: The object cloning is a way to create exact copy of an object. The clone() method of Object class is used to clone an object.

The java.lang.Cloneable interface must be implemented by the class whose object clone we want to create. If we don't implement Cloneable interface, clone() method generates CloneNotSupportedException.
Question: Why use clone() method ?
Answer: The clone() method saves the extra processing task for creating the exact copy of an object. If we perform it by using the new keyword, it will take a lot of processing time to be performed that is why we use object cloning.
Question: What is the Advantage of Object cloning?
Answer: Although Object.clone() has some design issues but it is still a popular and easy way of copying objects
. Following is a list of advantages of using clone() method:
-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 for 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 array.
Question: What is the Disadvantage of Object cloning?
Answer: Following is a list of some disadvantages of clone() method:

-To use the Object.clone() method, we have to change a lot of 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 cloneable interface while it doesn't have any methods in it. We just have to use it to tell the JVM that we can perform 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() doesn't invoke any constructor so we don't 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.
Question: Can you provide an Example of clone() method (Object cloning)?
Answer: Let's see the simple example of object cloning
class Student18 implements Cloneable{  
int rollno;  
String name;  
  
Student18(int rollno,String name){  
this.rollno=rollno;  
this.name=name;  
}  
  
public Object clone()throws CloneNotSupportedException{  
return super.clone();  
}  
  
public static void main(String args[]){  
try{  
Student18 s1=new Student18(101,"amit");  
  
Student18 s2=(Student18)s1.clone();  
  
System.out.println(s1.rollno+" "+s1.name);  
System.out.println(s2.rollno+" "+s2.name);  
  
}catch(CloneNotSupportedException c){}  
  
}  
}  
Output:101 amit
101 amit
As you can see in the above example, both reference variables have the same value. Thus, the clone() copies the values of an object to another. So we don't need to write explicit code to copy the value of an object to another.


If we create another object by new keyword and assign the values of another object to this one, it will require a lot of processing on this object. So to save the extra processing task we use clone() method.
Question: What is Java Math class?
Answer: Java Math class provides several methods to work on math calculations like min(), max(), avg(), sin(), cos(), tan(), round(), ceil(), floor(), abs() etc.

Unlike some of the StrictMath class numeric methods, all implementations of the equivalent function of Math class can't define to return the bit-for-bit same results. This relaxation permits implementation with better-performance where strict reproducibility is not required.

If the size is int or long and the results overflow the range of value, the methods addExact(), subtractExact(), multiplyExact(), and toIntExact() throw an ArithmeticException.

For other arithmetic operations like increment, decrement, divide, absolute value, and negation overflow occur only with a specific minimum or maximum value. It should be checked against the maximum and minimum value as appropriate.
Question: Can you provide the Java Math Methods?
Answer: The java.lang.Math class contains various methods for performing basic numeric operations such as the logarithm, cube root, and trigonometric functions etc.
Question: Can you provide the Logarithmic Math Methods?
Answer: Logarithmic Math Methods


Method: Math.log()
Description: It returns the natural logarithm of a double value.


Method: Math.log10()
Description: It is used to return the base 10 logarithm of a double value.


Method: Math.log1p()
Description: It returns the natural logarithm of the sum of the argument and 1.


Method:Math.exp()
Description: It returns E raised to the power of a double value, where E is Euler's number and it is approximately equal to 2.71828.


Method: Math.expm1()
Description: It is used to calculate the power of E and subtract one from it.
Question: Can you provide the Trigonometric Math Methods?
Answer: Trigonometric Math Methods

Method: Math.sin()
Description: It is used to return the trigonometric Sine value of a Given double value.


Method: Math.cos()
Description: It is used to return the trigonometric Cosine value of a Given double value.


Method: Math.tan()
Description: It is used to return the trigonometric Tangent value of a Given double value.


Method: Math.asin()
Description: It is used to return the trigonometric Arc Sine value of a Given double value


Method: Math.acos()
Description: It is used to return the trigonometric Arc Cosine value of a Given double value.


Method: Math.atan()
Description: It is used to return the trigonometric Arc Tangent value of a Given double value.
Question: Can you provide the Hyperbolic Math Methods?
Answer: Hyperbolic Math Methods
Method: Math.sinh()
Description: It is used to return the trigonometric Hyperbolic Cosine value of a Given double value.


Method: Math.cosh()
Description: It is used to return the trigonometric Hyperbolic Sine value of a Given double value.


Method: Math.tanh()
Description: It is used to return the trigonometric Hyperbolic Tangent value of a Given double value.
Question: Can you provide the Angular Math Methods?
Answer: Method:  Math.toDegrees
Description: It is used to convert the specified Radians angle to equivalent angle measured in Degrees.

Method: Math.toRadians
Description: It is used to convert the specified Degrees angle to equivalent angle measured in Radians.
Question: What is Wrapper classes in Java?
Answer: The wrapper class in Java provides the mechanism to convert primitive into object and object into primitive.

Since J2SE 5.0, autoboxing and unboxing feature convert primitives into objects and objects into primitives automatically. The automatic conversion of primitive into an object is known as autoboxing and vice-versa unboxing.
Question: What is the Use of Wrapper classes in Java?
Answer: Java is an object-oriented programming language, so we need to deal with objects many times like in Collections, Serialization, Synchronization, etc. Let us see the different scenarios, where we need to use the wrapper classes.
-Change the value in Method: Java supports only call by value. So, if we pass a primitive value, it will not change the original value. But, if we convert the primitive value in an object, it will change the original value.
-Serialization: We need to convert the objects into streams to perform the serialization. If we have a primitive value, we can convert it in objects through the wrapper classes.
-Synchronization: Java synchronization works with objects in Multithreading.
-java.util package: The java.util package provides the utility classes to deal with objects.
-Collection Framework: Java collection framework works with objects only. All classes of the collection framework (ArrayList, LinkedList, Vector, HashSet, LinkedHashSet, TreeSet, PriorityQueue, ArrayDeque, etc.) deal with objects only.
Question: What is Autoboxing?
Answer: The automatic conversion of primitive data type into its corresponding wrapper class is known as autoboxing, for example, byte to Byte, char to Character, int to Integer, long to Long, float to Float, boolean to Boolean, double to Double, and short to Short.
Since Java 5, we do not need to use the valueOf() method of wrapper classes to convert the primitive into objects.
Question: Can you provide the Wrapper class Example: Primitive to Wrapper?
Answer: //Java program to convert primitive into objects  
//Autoboxing example of int to Integer  
public class WrapperExample1{  
public static void main(String args[]){  
//Converting int into Integer  
int a=20;  
Integer i=Integer.valueOf(a);//converting int into Integer explicitly  
Integer j=a;//autoboxing, now compiler will write Integer.valueOf(a) internally  
  
System.out.println(a+" "+i+" "+j);  
}}  
Output:

20 20 20
Question: What is Unboxing?
Answer: The automatic conversion of wrapper type into its corresponding primitive type is known as unboxing. It is the reverse process of autoboxing. Since Java 5, we do not need to use the intValue() method of wrapper classes to convert the wrapper type into primitives
Question: Can you Wrapper class Example: Wrapper to Primitive?
Answer: //Java program to convert object into primitives  
//Unboxing example of Integer to int  
public class WrapperExample2{    
public static void main(String args[]){    
//Converting Integer to int    
Integer a=new Integer(3);    
int i=a.intValue();//converting Integer to int explicitly  
int j=a;//unboxing, now compiler will write a.intValue() internally    
    
System.out.println(a+" "+i+" "+j);    
}}    
Output:

3 3 3
Question: Can you provide the Java Wrapper classes Example?

Answer: //Java Program to convert all primitives into its corresponding   
//wrapper objects and vice-versa  
public class WrapperExample3{  
public static void main(String args[]){  
byte b=10;  
short s=20;  
int i=30;  
long l=40;  
float f=50.0F;  
double d=60.0D;  
char c='a';  
boolean b2=true;  
  
//Autoboxing: Converting primitives into objects  
Byte byteobj=b;  
Short shortobj=s;  
Integer intobj=i;  
Long longobj=l;  
Float floatobj=f;  
Double doubleobj=d;  
Character charobj=c;  
Boolean boolobj=b2;  
  
//Printing objects  
System.out.println("---Printing object values---");  
System.out.println("Byte object: "+byteobj);  
System.out.println("Short object: "+shortobj);  
System.out.println("Integer object: "+intobj);  
System.out.println("Long object: "+longobj);  
System.out.println("Float object: "+floatobj);  
System.out.println("Double object: "+doubleobj);  
System.out.println("Character object: "+charobj);  
System.out.println("Boolean object: "+boolobj);  
  
//Unboxing: Converting Objects to Primitives  
byte bytevalue=byteobj;  
short shortvalue=shortobj;  
int intvalue=intobj;  
long longvalue=longobj;  
float floatvalue=floatobj;  
double doublevalue=doubleobj;  
char charvalue=charobj;  
boolean boolvalue=boolobj;  
  
//Printing primitives  
System.out.println("---Printing primitive values---");  
System.out.println("byte value: "+bytevalue);  
System.out.println("short value: "+shortvalue);  
System.out.println("int value: "+intvalue);  
System.out.println("long value: "+longvalue);  
System.out.println("float value: "+floatvalue);  
System.out.println("double value: "+doublevalue);  
System.out.println("char value: "+charvalue);  
System.out.println("boolean value: "+boolvalue);  
}}  
Output:

---Printing object values---
Byte object: 10
Short object: 20
Integer object: 30
Long object: 40
Float object: 50.0
Double object: 60.0
Character object: a
Boolean object: true
---Printing primitive values---
byte value: 10
short value: 20
int value: 30
long value: 40
float value: 50.0
double value: 60.0
char value: a
boolean value: true
Question: Can you provide the Custom Wrapper class in Java?
Answer: Java Wrapper classes wrap the primitive data types, that is why it is known as wrapper classes. We can also create a class which wraps a primitive data type. So, we can create a custom wrapper class in Java.

//Creating the custom wrapper class  
class Javatpoint{  
private int i;  
Javatpoint(){}  
Javatpoint(int i){  
this.i=i;  
}  
public int getValue(){  
return i;  
}  
public void setValue(int i){  
this.i=i;  
}  
@Override  
public String toString() {  
  return Integer.toString(i);  
}  
}  
//Testing the custom wrapper class  
public class TestJavatpoint{  
public static void main(String[] args){  
Javatpoint j=new Javatpoint(10);  
System.out.println(j);  
}}  
Output:

10
Question: What is Recursion in Java?
Answer: Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

It makes the code compact but complex to understand.

Syntax:

returntype methodname(){  
//code to be executed  
methodname();//calling same method  
}
Question: Can you provide the Java Recursion Example 1: Infinite times?
Answer: public class RecursionExample1 {  
static void p(){  
System.out.println("hello");  
p();  
}  
  
public static void main(String[] args) {  
p();  
}  
}  Output:hello
hello
...
java.lang.StackOverflowError
Question: Can you provide the Java Recursion Example 2: Finite times?
Answer: public class RecursionExample2 {  
static int count=0;  
static void p(){  
count++;  
if(count<=5){  
System.out.println("hello "+count);  
p();  
}  
}  
public static void main(String[] args) {  
p();  
}  
}  
Output:

hello 1
hello 2
hello 3
hello 4
hello 5
Question: Can you provide the Java Recursion Example 3: Factorial Number?
Answer: public class RecursionExample3 {  
    static int factorial(int n){      
          if (n == 1)      
            return 1;      
          else      
            return(n * factorial(n-1));      
    }      
  
public static void main(String[] args) {  
System.out.println("Factorial of 5 is: "+factorial(5));  
}  
}  
Output:


Factorial of 5 is: 120
Working of above program:
factorial(5) 
   factorial(4) 
      factorial(3) 
         factorial(2) 
            factorial(1) 
               return 1 
            return 2*1 = 2 
         return 3*2 = 6 
      return 4*6 = 24 
   return 5*24 = 120
Question: Can you provide the Java Recursion Example 4: Fibonacci Series?
Answer: public class RecursionExample4 {  
    static int n1=0,n2=1,n3=0;      
     static void printFibo(int count){      
        if(count>0){      
             n3 = n1 + n2;      
             n1 = n2;      
             n2 = n3;      
             System.out.print(" "+n3);     
             printFibo(count-1);      
         }      
     }        
  
public static void main(String[] args) {  
    int count=15;      
      System.out.print(n1+" "+n2);//printing 0 and 1      
      printFibo(count-2);//n-2 because 2 numbers are already printed     
}  
}  
Output:

0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Question: What is Call by Value and Call by Reference in Java?
Answer: There is only call by value in java, not call by reference. If we call a method passing a value, it is known as call by value. The changes being done in the called method, is not affected in the calling method.
Question: Can you provide an Example of call by value in java?
Answer: class Operation{  
 int data=50;  
  
 void change(int data){  
 data=data+100;//changes will be in the local variable only  
 }  
     
 public static void main(String args[]){  
   Operation op=new Operation();  
  
   System.out.println("before change "+op.data);  
   op.change(500);  
   System.out.println("after change "+op.data);  
  
 }  
}  
Output:before change 50
       after change 50
Question: What is Java Strictfp Keyword?
Answer: Java strictfp 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 have provided the strictfp keyword, so that you get same result on every platform. So, now you have better control over the floating-point arithmetic.
Question: What is Legal code for strictfp keyword?
Answer: The strictfp keyword can be applied on methods, classes and interfaces.

strictfp class A{}//strictfp applied on class  
strictfp interface M{}//strictfp applied on interface  
class A{  
strictfp void m(){}//strictfp applied on method  
}
Question: What is Illegal code for strictfp keyword?
Answer: The strictfp keyword cannot be applied on abstract methods, variables or constructors.

class B{  
strictfp abstract void m();//Illegal combination of modifiers  
}  
class B{  
strictfp int data=10;//modifier strictfp not allowed here  
}  
class B{  
strictfp B(){}//modifier strictfp not allowed here  
}
Question: What is Creating API Document | javadoc tool?
Answer: We can create document api in java by the help of javadoc tool. In the java file, we must use the documentation comment /**... */ to post information for the class, method, constructor, fields etc.
Let's see the simple class that contains documentation comment.

package com.abc;  
/** This class is a user-defined class that contains one methods cube.*/  
public class M{  
  
/** The cube method prints cube of the given number */  
public static void  cube(int n){System.out.println(n*n*n);}  
}  
To create the document API, you need to use the javadoc tool followed by java file name. There is no need to compile the javafile.

On the command prompt, you need to write:
javadoc M.java
to generate the document api. Now, there will be created a lot of html files. Open the index.html file to get the information about the classes.
Question: What is Java Command Line Arguments?
Answer: The java command-line argument is an argument i.e. passed at the time of running the java program.

The arguments passed from the console can be received in the java program and it can be used as an input.

So, it provides a convenient way to check the behavior of the program for the different values. You can pass N (1,2,3 and so on) numbers of arguments from the command prompt.
Question: Can you provide Simple example of command-line argument in java?
Answer: In this example, we are receiving only one argument and printing it. To run this java program, you must pass at least one argument from the command prompt.
class CommandLineExample{  
public static void main(String args[]){  
System.out.println("Your first argument is: "+args[0]);  
}  
}  
compile by > javac CommandLineExample.java  
run by > java CommandLineExample sonoo  
Output: Your first argument is: sonoo
Question: Can you provide an Example of command-line argument that prints all the values?
Answer: In this example, we are printing all the arguments passed from the command-line. For this purpose, we have traversed the array using for loop.
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
Question: What are the Difference between object and class?
Answer: There are many differences between object and class. A list of differences between object and class are given below:

1)  Object is an instance of a class while Class is a blueprint or template from which objects are created
2) Object is a real world entity such as pen, laptop, mobile, bed, keyboard, mouse, chair etc. while Class is a group of similar objects
3) Object is a physical entity while Object is a physical entity.
4) Object is created through new keyword mainly e.g.
Student s1=new Student(); while Class is declared using class keyword e.g.
class Student{}
5) Object is created many times as per requirement while Class is declared once.
6) Object allocates memory when it is created while Class doesn't allocated memory when it is created.
7) There are many ways to create object in java such as new keyword, newInstance() method, clone() method, factory method and deserialization while there is only one way to define class in java using class keyword

Let's see some real life example of class and object in java to understand the difference well:

Class: Human Object: Man, Woman
Class: Fruit Object: Apple, Banana, Mango, Guava wtc.
Class: Mobile phone Object: iPhone, Samsung, Moto
Class: Food Object: Pizza, Burger, Samosa