Question
stringlengths
1
113
Answer
stringlengths
22
6.98k
What is Interface in Java?
An interface in Java is a blueprint of a class. It has static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables. It cannot have a method body. Java Interface also represents the IS-A relationship. It cannot be instantiated just like the abstract class. Since Java 8, we can have default and static methods in an interface. Since Java 9, we can have private methods in an interface.
Why use Java interface?
There are mainly three reasons to use interface. They are given below. -It is used to achieve abstraction. -By interface, we can support the functionality of multiple inheritance. -It can be used to achieve loose coupling.
How to declare an interface?
An interface is declared by using the interface keyword. It provides total abstraction; means all the methods in an interface are declared with the empty body, and all the fields are public, static and final by default. A class that implements an interface must implement all the methods declared in the interface.
Can you provide Java Interface Example?
In this example, the Printable interface has only one method, and its implementation is provided in the A6 class. interface printable{ void print(); } class A6 implements printable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ A6 obj = new A6(); obj.print(); } } Output: Hello
Can you provide Java Interface Example: Drawable?
In this example, the Drawable interface has only one method. Its implementation is provided by Rectangle and Circle classes. In a real scenario, an interface is defined by someone else, but its implementation is provided by different implementation providers. Moreover, it is used by someone else. The implementation part is hidden by the user who uses the interface. File: TestInterface1.java //Interface declaration: by first user interface Drawable{ void draw(); } //Implementation: by second user class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class Circle implements Drawable{ public void draw(){System.out.println("drawing circle");} } //Using interface: by third user class TestInterface1{ public static void main(String args[]){ Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable() d.draw(); }} Output: drawing circle
Can you provide Java Interface Example: Bank?
Let's see another example of java interface which provides the implementation of Bank interface. File: TestInterface2.java interface Bank{ float rateOfInterest(); } class SBI implements Bank{ public float rateOfInterest(){return 9.15f;} } class PNB implements Bank{ public float rateOfInterest(){return 9.7f;} } class TestInterface2{ public static void main(String[] args){ Bank b=new SBI(); System.out.println("ROI: "+b.rateOfInterest()); }} Output: ROI: 9.15
Multiple inheritance is not supported through class in java, but it is possible by an interface, why?
As we have explained in the inheritance chapter, multiple inheritance is not supported in the case of class because of ambiguity. However, it is supported in case of an interface because there is no ambiguity. It is because its implementation is provided by the implementation class. For example: interface Printable{ void print(); } interface Showable{ void print(); } class TestInterface3 implements Printable, Showable{ public void print(){System.out.println("Hello");} public static void main(String args[]){ TestInterface3 obj = new TestInterface3(); obj.print(); } } Output: Hello
What is Interface inheritance?
A class implements an interface, but one interface extends another interface.
Can you provide Java 8 Default Method in Interface?
Since Java 8, we can have method body in interface. But we need to make it default method. Let's see an example: interface Drawable{ void draw(); default void msg(){System.out.println("default method");} } class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class TestInterfaceDefault{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); d.msg(); }} interface Drawable{ void draw(); default void msg(){System.out.println("default method");} } class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class TestInterfaceDefault{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); d.msg(); }} Output: drawing rectangle default method
Can you provide Java 8 Static Method in Interface?
ince Java 8, we can have static method in interface. Let's see an example: interface Drawable{ void draw(); static int cube(int x){return x*x*x;} } class Rectangle implements Drawable{ public void draw(){System.out.println("drawing rectangle");} } class TestInterfaceStatic{ public static void main(String args[]){ Drawable d=new Rectangle(); d.draw(); System.out.println(Drawable.cube(3)); }} Output: drawing rectangle 27
What is marker or tagged interface?
An interface which has no member is known as a marker or tagged interface, for example, Serializable, Cloneable, Remote, etc. They are used to provide some essential information to the JVM so that JVM may perform some useful operation. //How Serializable interface is written? public interface Serializable{ }
What is Nested Interface in Java?
Note: An interface can have another interface which is known as a nested interface. We will learn it in detail in the nested classes chapter. For example: interface printable{ void print(); interface MessagePrintable{ void msg(); } }
Can you provide an Example of abstract class and interface in Java?
Let's see a simple example where we are using interface and abstract class both. //Creating interface that has 4 methods interface A{ void a();//bydefault, public and abstract void b(); void c(); void d(); } //Creating abstract class that provides the implementation of one method of A interface abstract class B implements A{ public void c(){System.out.println("I am C");} } //Creating subclass of abstract class, now we need to provide the implementation of rest of the methods class M extends B{ public void a(){System.out.println("I am a");} public void b(){System.out.println("I am b");} public void d(){System.out.println("I am d");} } //Creating a test class that calls the methods of A interface class Test5{ public static void main(String args[]){ A a=new M(); a.a(); a.b(); a.c(); a.d(); }} Output: I am a I am b I am c I am d
What is Java Package?
A java package is a group of similar types of classes, interfaces and sub-packages. Package in java can be categorized in two form, built-in package and user-defined package. There are many built-in packages such as java, lang, awt, javax, swing, net, io, util, sql etc.
What is the Advantage of Java Package?
1) Java package is used to categorize the classes and interfaces so that they can be easily maintained. 2) Java package provides access protection. 3) Java package removes naming collision.
Can you provide Simple example of java package?
The package keyword is used to create a package in java. //save as Simple.java package mypack; public class Simple{ public static void main(String args[]){ System.out.println("Welcome to package"); } }
How to access package from another package?
There are three ways to access the package from outside the package. 1.import package.*; 2.import package.classname; 3.fully qualified name.
What is Using packagename?
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.
Can you provide an Example of package that import the packagename?
//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
What is Using packagename.classname?
If you import package.classname then only declared class of this package will be accessible.
Can you provide an Example of package by import package.classname?
//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
How the Using fully qualified name work?
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.
Can you provide an Example of package by import fully qualified name?
//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
What is Subpackage in java?
Package inside the package is called the subpackage. It should be created to categorize the package further.
Can you provide an Example of Subpackage?
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
What are the Ways to load the class files or jar files?
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.
How to put two public classes in a package?
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{}
What is Access Modifiers in Java?
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.
What is Private?
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 } }
What is Default?
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 } }
What is Protected?
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
What is Public?
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
Can you provide an example of Java Access Modifiers with Method Overriding?
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(); } }
What is Encapsulation in Java?
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.
What is the Advantage of Encapsulation in Java?
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.
Can you provide Simple Example of Encapsulation in Java?
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 } }
What is Read-Only class?
//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; } }
What is Write-Only class?
//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; } }
Can you provide Another Example of Encapsulation in Java?
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
What is Java Arrays?
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
What are the Types of Array in java?
There are two types of array. -Single Dimensional Array -Multidimensional Array
WHat is Single Dimensional Array in Java?
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];
Can you provide an Example of Java Array?
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
Can you provide an example of Declaration, Instantiation and Initialization of Java Array?
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
Can you provide the For-each Loop for Java Array?
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
Can you provide the Passing Array to a Method in Java?
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
Can you provide the Anonymous Array in Java?
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
Can you provide the Returning Array from the Method?
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
Can you provide the ArrayIndexOutOfBoundsException?
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
What is Multidimensional Array in Java?
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;
Can you provide an Example of Multidimensional Java Array?
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;
What is Jagged Array in Java?
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
What is the class name of Java array?
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
Can you provide the Copying a Java Array?
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 )
What is the Example of Copying an Array in Java?
//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
Can you provide the Cloning an Array in Java?
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
What is Addition of 2 Matrices in Java?
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
Can you provide the Multiplication of 2 Matrices in Java?
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
What is Object class in Java?
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.
What are the Methods of Object class?
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.
What is Object Cloning in Java?
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.
Why use clone() method ?
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.
What is the Advantage of Object cloning?
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.
What is the Disadvantage of Object cloning?
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.
Can you provide an Example of clone() method (Object cloning)?
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.
What is Java Math class?
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.
Can you provide the Java Math Methods?
The java.lang.Math class contains various methods for performing basic numeric operations such as the logarithm, cube root, and trigonometric functions etc.
Can you provide the Basic Math methods?
Basic Math methods Method: Math.abs() Description: It will return the Absolute value of the given value. Method:Math.max() Description: It returns the Largest of two values. Method:Math.min() Description: It is used to return the Smallest of two values. Method:Math.round() Description: It is used to round of the decimal numbers to the nearest value. Method:Math.sqrt() Description: It is used to return the square root of a number. Method:Math.cbrt() Description: It is used to return the cube root of a number. Method:Math.pow() Description: It returns the value of first argument raised to the power to second argument. Method:Math.signum() Description: It is used to find the sign of a given value. Method:Math.ceil() Description: It is used to find the smallest integer value that is greater than or equal to the argument or mathematical integer. Method:Math.copySign() Description: It is used to find the Absolute value of first argument along with sign specified in second argument. Method:Math.nextAfter() Description: It is used to return the floating-point number adjacent to the first argument in the direction of the second argument. Method:Math.nextUp() Description: It returns the floating-point value adjacent to d in the direction of positive infinity. Method:Math.nextDown() Description: It returns the floating-point value adjacent to d in the direction of negative infinity. Method:Math.floor() Description: It is used to find the largest integer value which is less than or equal to the argument and is equal to the mathematical integer of a double value. Method:Math.floorDiv() Description: It is used to find the largest integer value that is less than or equal to the algebraic quotient. Method:Math.random() Description: It returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Method:Math.rint() Description: It returns the double value that is closest to the given argument and equal to mathematical integer. Method:Math.hypot() Description: It returns sqrt(x2 +y2) without intermediate overflow or underflow. Method:Math.ulp() Description: It returns the size of an ulp of the argument. Method:Math.getExponent() Description: It is used to return the unbiased exponent used in the representation of a value. Method:Math.IEEEremainder() Description: It is used to calculate the remainder operation on two arguments as prescribed by the IEEE 754 standard and returns value. Method: Math.addExact() Description: It is used to return the sum of its arguments, throwing an exception if the result overflows an int or long. Method:Math.subtractExact() Description: It returns the difference of the arguments, throwing an exception if the result overflows an int. Method: Math.multiplyExact() Description: It is used to return the product of the arguments, throwing an exception if the result overflows an int or long. Method: Math.incrementExact() Description: It returns the argument incremented by one, throwing an exception if the result overflows an int. Method:Math.decrementExact() Description: It is used to return the argument decremented by one, throwing an exception if the result overflows an int or long. Method:Math.negateExact() Description: It is used to return the negation of the argument, throwing an exception if the result overflows an int or long. Method:Math.toIntExact() Description: It returns the value of the long argument, throwing an exception if the value overflows an int.
Can you provide the Logarithmic Math Methods?
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.
Can you provide the Trigonometric Math Methods?
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.
Can you provide the Hyperbolic Math Methods?
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.
Can you provide the Angular Math Methods?
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.
What is Wrapper classes in Java?
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.
What is the Use of Wrapper classes in Java?
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.
What is Autoboxing?
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.
Can you provide the Wrapper class Example: Primitive to Wrapper?
//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
What is Unboxing?
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
Can you Wrapper class Example: Wrapper to Primitive?
//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
Can you provide the Java Wrapper classes Example?
//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
Can you provide the Custom Wrapper class in Java?
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
What is Recursion in Java?
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 }
Can you provide the Java Recursion Example 1: Infinite times?
public class RecursionExample1 { static void p(){ System.out.println("hello"); p(); } public static void main(String[] args) { p(); } } Output:hello hello ... java.lang.StackOverflowError
Can you provide the Java Recursion Example 2: Finite times?
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
Can you provide the Java Recursion Example 3: Factorial Number?
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
Can you provide the Java Recursion Example 4: Fibonacci Series?
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
What is Call by Value and Call by Reference in Java?
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.
Can you provide an Example of call by value in java?
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
What is Java Strictfp Keyword?
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.
What is Legal code for strictfp keyword?
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 }
What is Illegal code for strictfp keyword?
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 }
What is Creating API Document | javadoc tool?
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.
What is Java Command Line Arguments?
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.
Can you provide Simple example of command-line argument in java?
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
Can you provide an Example of command-line argument that prints all the values?
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
What are the Difference between object and class?
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
Can you provide Java Method Overloading example?
class OverloadingExample{ static int add(int a,int b){return a+b;} static int add(int a,int b,int c){return a+b+c;} }
Can you provide Java Method Overriding example?
class Animal{ void eat(){System.out.println("eating...");} } class Dog extends Animal{ void eat(){System.out.println("eating bread...");} }
What is Java String?
n Java, string is basically an object that represents sequence of char values. An array of characters works same as Java string. For example: char[] ch={'j','a','v','a','t','p','o','i','n','t'}; String s=new String(ch); is same as: String s="javatpoint"; Java String class provides a lot of methods to perform operations on strings such as compare(), concat(), equals(), split(), length(), replace(), compareTo(), intern(), substring() etc. The java.lang.String class implements Serializable, Comparable and CharSequence interfaces.
CharSequence Interface
The CharSequence interface is used to represent the sequence of characters. String, StringBuffer and StringBuilder classes implement it. It means, we can create strings in Java by using these three classes. The Java String is immutable which means it cannot be changed. Whenever we change any string, a new instance is created. For mutable strings, you can use StringBuffer and StringBuilder classes. We will discuss immutable string later. Let's first understand what String in Java is and how to create the String object.
What is String in Java?
Generally, String is a sequence of characters. But in Java, string is an object that represents a sequence of characters. The java.lang.String class is used to create a string object.