Java Interview Questions

Q). What is Java?
A). Java is an Object oriented programming language and it is platform independent.

Q). What is the use of Java programming language?
A). Java is used to develop mobile apps, web apps, desktop apps, games and much more.

Q). Who has developed Java?
A). Java was developed by company called Sun Microsystems and developed by James Gosling, who is known as the father of Java.

Q).How many java application types we have and what are those?
A). There are 4 types of java applications those are:

  1. Standalone Application
  2. Web Application
  3. Enterprise Application
  4. Mobile Application

Q).List down the java editions?
A). There are 3 editions in java:

  1. J2SE (Java Standard Edition)
  2. Java EE (Java Enterprise Edition)
  3. Java ME (Java Micro Edition)

Q).What are the features of java?
A). Java features are:

  1. 1. Simple
  2. 2. Object-Oriented
  3. 3. Portable
  4. 4. Platform independent
  5. 5. Secured
  6. 6. Robust
  7. 7. Architecture neutral
  8. 8. Interpreted
  9. 9. High Performance
  10. 10. Multithreaded
  11. 11. Distributed
  12. 12. Dynamic

Q).Why java is platform independent?
A). Java is platform independent because we can write and compile a program in one operating system it will generate the byte code and this byte code can be executed into any other operating system.

Q).WORA stands for?
A). Write Once and Run Anywhere (WORA).

Q).Why java is secured?
A). Java is secured programming language because:

  1. 1. No explicit pointer
  2. 2. Java Programs run inside a virtual machine sandbox

Q).Why java is Robust?
A). Java is Robust because:

  1. 1. It uses strong memory management.
  2. 2. Java will not support pointers.
  3. 3. Java provides automatic garbage collection.
  4. 4. There are exception handling.

Q).Why java is Portable?
A). Java is portable because it facilitates to carry the Java bytecode to any platform.

Q).What is a Class in Java?
A). Class is a blueprint that is used to create objects and methods.

Q).What are the memory areas allocated by JVM?
A). There are totally five memory areas that are allocated by the JVM:

  1. 1. Class Area
  2. 2. Heap
  3. 3. Stack
  4. 4. Native Method Stack
  5. PC Register

Q).What is ClassLoader?
A). class loader is a subsystem of JVM which is used to load class files into JVM, there are mainly three types classloaders in JVM:

  1. 1. Application Classloader
  2. 2. Bootstrap Classloader
  3. 3. Extension Classloader

Q).What is JDK?
A). JDK stands for Java Development Kit. JDK is used as a standalone component to implement Java platform specifications, including class libraries and compiler.

Q).What is JRE?
A). JRE stands for Java Runtime Environment (JRE). JRE is a collection of software tools that are designed for the development of Java applications.

Q).What is the significant difference between JVM, JRE, and JDK?
A). The difference between JVM, JDK, and JRE is:

  1. JVM: stands for Java Virtual Machine which is the main part of Java programming, which provides platform independence. JRE and JDK both contain JVM in order to run our Java programs.
  2. JDK: stands for Java development kit which is mainly used for developing programs.
  3. JRE: stands for Java Runtime Environment which is mainly used for running Java programs.

Q).What is JIT compiler in Java?
A). JIT stands for Just In Time Compiler, JIT is the component of JRE, which is used to compile the bytecodes of the particular method into the native machine code.

Q).What are the different types of variables in Java?
A). There are mainly three different types of variables available in Java:

  1. Static Variables
  2. Local Variables
  3. Instance Variables

Q).What is mean by static variable?
A). A variable that is declared with the static keyword is called a static variable.

Q).What is mean by Local variable?
A). A variable that is declared inside the body of the method within the class is called a local variable.

Q).What is mean by Instance variable?
A). The variable declared outside the body of the method within the class is called a local variable.

Q).What happen if we write static public void instead of public static void?
A). The program compiles and runs correctly because the order of specifiers doesn't matter in Java.

Q).What are the advantages of Packages in Java?
A). There are various advantages of packages in Java.

  1. Packages avoid the name clashes.
  2. The Package provides easier access control.
  3. We can also have the hidden classes that are not visible outside and used by the package.

Q).What is the syntax to declare a variable in java?
A). The syntax to declare a variable is : datatype variablename;

Q).What is the syntax to initialize a variable in java?
A). The Syntax to initialize a variable is : datatype variablename = value;

Q).What is mean by datatype?
A). Data type is nothing but a type of data can be used to declare a variables.

Q).How many datatypes in Java?
A). In Java there are two types of datatypes

  1. Primitive data types
  2. Non-primitive data types:

Q).How many Primitive datatypes in Java?
A). In Java there are 8 Primitive datatypes:

  1. 1. byte
  2. 2. short
  3. 3. int
  4. 4. long
  5. 5. float
  6. 6. double
  7. 7. char
  8. 8. boolean

Q).1-byte is equals to how many bits in Java ?
A). In Java 1 byte is equals to 8 bits

Q).What is the size byte datatype?
A). byte datatype size is 1 byte or 8 bits

Q).What is the size short datatype?
A). short datatype size is 2 byte or 16 bits

Q).What is the size int datatype?
A). int datatype size is 4 byte or 32 bits

Q).What is the size long datatype?
A). long datatype size is 8 byte or 64 bits

Q).What is the size float datatype?
A). float datatype size is 4 byte or 32 bits

Q).What is the size double datatype?
A). double datatype size is 8 byte or 64 bits

Q).What is the size char datatype?
A). char datatype size is 2 byte or 16 bits

Q).What is the range of byte datatype?
A). byte datatype will accept values from -128 to 127

Q).What is the range of short datatype?
A). short datatype will accept values from -32,768 to 32,767

Q).What is the range of int datatype?
A). int datatype will accept values -231 to -231-1 or -2,147,483,648 to 2,147,483,647

Q).What is the range of long datatype?
A). long datatype will accept values -263 to -263-1 or -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

Q).What is the range of float datatype?
A). float datatype will Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits

Q).What is the range of double datatype?
A). double datatype will Stores fractional numbers. Sufficient for storing 15 decimal digits

Q).What is Java Type Casting?
A). Type casting is nothing but assigning a value of one primitive data type to another type.

Q).What is Widening Casting (automatically)?
A). Widening Casting is nothing but Converting a smaller size datatype to a larger datatype.

Q).What is Narrowing Casting (manually)?
A). Narrowing Casting is nothing but Converting a larger size datatype to a smaller datatype.

Q).How many types of Java comments?
A). Java comments are devided into three types

  1. Single-line Comments
  2. Multi-line Comments
  3. Document type Comments

Q).How to declare a single line comments in java?
A). Single-line comments start with two forward slashes (//). Any line starts with // java will ignore this line from the execution.

Q).How to declare a Multi-line Comments in java?
A). Multi-line comments start with /* and ends with */. Any text between /* and */ will be ignored by Java.

Q).How to declare a Document type Comments in java?
A). Document type comments start with /* and ends with */ and each line starts with *.

Q).What is mean by operator in Java?
A). Operators are used to perform operations on variables and values.

Q).How many types of operators in Java?
A). Java operators are devided into many types:

  1. 1. Arithmetic operators
  2. 2. Unary operators
  3. 3. Comparison/Relational operators
  4. 4. Logical operators
  5. 5. Assignment operators
  6. 6. Bitwise operator
  7. 7. Ternary operator

Q).What is mean by Arithmetic Operator and what are those?
A). Arithmetic operators are used to perform common mathematical operations.
Arithmetic operators are:

  1. 1. Addition (+)
  2. 2. Subtraction (-)
  3. 3. Multiplication (*)
  4. 4. Division (/)
  5. 5. Modulus (%)

Q).What is mean by Unary Operator and what are those?
A). The Java unary operators require only one operand. Unary operators are used to perform various operations:
Unary operators are below:

  1. 1. Increment operator (++)
  2. 2. Decrement operator (--)
  3. 33. Nagation (~)

Q).What is mean by Relational Operator and what are those?
A). Relational operators are used to compare two values:
Relational operators are below:

  1. 1. Equal To (==)
  2. 2. Not Equal To (!=)
  3. 3. Greater Than (>)
  4. 4. Less Than (<)
  5. 5. Greater Than Equal To (>=)
  6. 6. Less Than Equal To (<=)

Q).What is mean by Logical Operator and what are those?
A). Logical operators are used to perform the logic operations between variables or values. The logical operators doesn't check the second condition if the first condition is true. It checks the second condition only if the first one is false.
Logical operators are below:

  1. 1. Logical and (&&)
  2. 2. Logical or (||)
  3. 3. Logical not (!)

Q).What is mean by Assignment Operator?
A). Assignment operators are used to assign values to variables. = (equal) symbol is the assignment operator in java. We use the assignment operator (=) to assign the value 10 to a variable called x:
Example: int x = 10;

Q).What is mean by Bitwise Operator and what are those?
A). The bitwise operator is also use to perform the logical operations between variables or values. The bitwise operator always checks both conditions whether first condition is true or false.
Bitwise operators are below:

  1. 1. bitwise AND (&)
  2. 2. bitwise exclusive OR (^)
  3. 3. bitwise inclusive OR (|)

Q).What is mean by Ternary Operator?
A). Java ternary operator is the only conditional operator that takes three operands.

Q).What is syntax of Ternary Operator?
A). Ternary Operator syntax is: variable = Expression1 ? Expression2: Expression3.

Q).What is String?
A). In Java String is a class which is available in java.lang package. In java String represents sequence of characters.

Q).Is String immutable in java?
A). Yes, String class is immutable in java.

Q).What is mean by Immutable?
A). In Java Immutable means once the object is created, its value can not be changed.

Q).Is String a keyword in java ?
A). No, String is not a keyword it an Object in java.

Q).How to convert String to char Array?
A). In Java we can convert String to char Array using toCharArray() method with is available in String class.

Q).How many different ways you can create a String object?
A). Two ways we can create String object in java:

  1. 1. using String literal: if we create an object using String literal it will create an object in String Constant Pool area
    String str = "javahungry"; // String literal
  2. 2. using new operator if we create an object using new operator it will create the object in heap memory
    String str = new String("javahungry"); // using new operator

Q).Are String thread-safe in java?
A). Yes, String's are thread-safe because in Java String objects are immutable.

Q).Is String primitive type or object (derived) type in java?
A). String is an object type in java.

Q).Can we use String in switch statement?
A). Yes, we can use String in switch statement in java 7. this was not supported prior to java 7.

Q).What is the difference between String and StringBuffer in java?
A).

String StringBuffer
The String class is immutable. The StringBuffer class is mutable.
String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance. StringBuffer is fast and consumes less memory when we concatenate t strings.
String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method. StringBuffer class doesn't override the equals() method of Object class.
String class is slower while performing concatenation operation. StringBuffer class is faster while performing concatenation operation.
String class uses String constant pool. StringBuffer uses Heap memory

Q).What is the difference between StringBuilder and StringBuffer in java?
A).

StringBuffer StringBuilder
StringBuffer was introduced in Java 1.0. StringBuilder was introduced in Java 1.5.
StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.
StringBuffer is less efficient than StringBuilder. StringBuilder is more efficient than StringBuffer.

Q).Explain the difference between creation of a string using new operator and literal?
A).

  1. We can create the string using new operator String str = new String("abc");
    If we create the string using new operator, JVM will create one object in the heap memory. Another object in the String constant pool, if the object is not present. Otherwise,if present in the String constant pool ,it will return the reference to it.

  2. We can create the string using string literral String str = "abc";
    If we create the string using string literal, JVM checks for the string "abc" in the String constant pool. If the string is not present in the constant pool then it will create a new String object and stores it in pool.

Q).How many objects will be created for the following code:
String str1 = "abc";
String str2 = new String("abc");
A). Two objects are created. Object created using new operator will be stored in the heap memory (str2). Object created using String literal str1 will be stored in the string constant pool.

Q).How many objects will be created for the following code:
String str1 = "abc";
String str2 = "abc";
A). Only one object is created. String str1 will create a new object in String constant pool, while String str2 will create a reference to the String str1.

Q).How many objects will be created for the following code:
String str1 = new String("abc");
String str2 = new String("abc");
A). Three objects are created. For the first statement(str1) two objects are created one in String constant pool and one in heap memory. But for the second statement(str2), compulsory 1 new object is created in heap memory but no new object is created in string constant pool as it is already present.

Q).What are mutable and immutable objects in java?
A). Mutable objects value can be changed. StringBuilder and StringBuffer are the examples of the mutable objects. Immutable objects value can not be changed once created. String is an immutable class in java.

Q).Why is String immutable in java ?
A). There are various reasons to make String immutable in java.

  1. 1. Security : String is an immutable object which will help to increase the Security.
  2. 2. Class loading : String objects are used for Class loading.
  3. 3. Thread Safe : Immutable Strings are thread-safe.

Q).How will you create an immutable class in java?
A). We can create immutable class in java by implementing:

  1. 1. Make the class final so it can not be extended(inherited)
  2. 2. Make all fields private so one can not access them from outside the class.
  3. 3. Do not provide setter methods for the variables.
  4. 4. Declare all mutable fields as final so that it's value can be assigned only once.

Q).How will you create mutable String objects in java?
A). Using StringBuffer and StringBuilder objects.

Q).Why String is mostly used as a key in HashMap class?
A). String is mostly used as a key in HashMap class because it implements equals() and hashCode() methods which is required for an Object to be used as key in HashMap.

Q).Is it possible to call String class methods using String literals?
A). Yes, It is possible to call String class methods using String literals. For example
"javahungry".indexOf(u)
"javahungry".charAt(0)
"javahungry".compareTo("javahungry")

Q).How to Split String in java?
A). We can use split() method which is available in String class. This split() method is easy to use and it will accept regular expressions based on that we can perform split() operation.

Q).How do you compare two Strings in Java?
A). In Java we can compare strings using equals() method.

Q).Why String Constant Pool ?
A). String constant pool increases the reusability of the existing String objects. It also saves memory as no two objects with same content are created.

Q).What is Character encoding? Explain the difference between UTF-16 and UTF-8?
A). When you want to represent Character using bytes, character encoding is used.
The UTF-16 uses 2 bytes or 16 bits to represent a character while UTF-8 uses 1 byte or 8 bits to represent a character.

Q).Are Interned Strings Eligible for Garbage Collection in Java?
A). Yes, all Strings in the string pool are eligible for garbage collection if there are no references from the program.

Q).How Can We Compare Two Strings in Java? What’s the Difference Between str1 == str2 and str1.equals(str2)?
A). We can compare strings in two different ways: by using equal to operator ( == ) and by using the equals() method.
Both are quite different from each other:

  1. The operator (str1 == str2) checks for referential equality
  2. The method (str1.equals(str2)) checks for content equality

Q).What Is Stringjoiner?
A). StringJoiner is a class introduced in Java 8 for joining separate strings into one, like taking a list of colors and returning them as a comma-delimited string. We can supply a delimiter as well as a prefix and suffix:

Q).How Can We Convert String to Integer and Integer to String in Java?
A). The most straightforward approach to convert a String to an Integer is by using Integer.parseInt() method:
int num = Integer.parseInt("22");

To do the reverse, we can use Integer.toString():
String s = Integer.toString(num);

Q).How Can We Convert a String to Uppercase and Lowercase?
A). To convert a String into Uppercase then we need to use the toUpperCase() method and to convert a String into Lowercase then we need to use toLowerCase() method.

Q).Difference between String, StringBuffer, and StringBuilder in java?
A). String:

  1. Strings are Immutable.
  2. String is slow and consumes more memory when we concatenate too many strings because every time it creates new instance.
  3. String class overrides the equals() method of Object class. So you can compare the contents of two strings by equals() method.
  4. String class is slower while performing concatenation operation.
  5. String class uses String constant pool.
StringBuffer:
  1. StringBuffer was introduced in Java 1.0
  2. The StringBuffer class is mutable.
  3. StringBuffer is fast and consumes less memory when we concatenate t strings.
  4. StringBuffer class doesn't override the equals() method of Object class.
  5. StringBuffer class is faster while performing concatenation operation.
  6. StringBuffer is synchronized i.e. thread safe. It means two threads can't call the methods of StringBuffer simultaneously.
  7. StringBuffer is less efficient than StringBuilder.
StringBuilder:
  1. StringBuilder was introduced in Java 1.5
  2. The StringBuilder class is mutable.
  3. StringBuilder is more efficient than StringBuffer.
  4. StringBuilder is non-synchronized i.e. not thread safe. It means two threads can call the methods of StringBuilder simultaneously.

Q).Which of the two "StringBuilder" or "StringBuffer" is faster and Why ?
A). StringBuilder is not synchronized and hence faster than StringBuffer.

Q).What is Object class in Java programming language?
A). In Java Object class is present in java.lang package and it is superclass of all other classes defined in Java programming language.

Q).What are the Object class methods?
A). There are 9 object class methods in java those are clone(), toString(), equals(), hashcode(), finalize(), getClass(), wait(), notify(), notifyAll()

Q).Explain each Object class methods in java?
A).

  1. clone() - If a class implements cloneable interface, then calling clone() method on its object returns a copy of the object. If a class does not implement the cloneable interface, and clone() method is called on its object, then the method throws a CloneNotSupportedException exception.
  2. toString() - You can get a string representation of any Java object by calling its toString() method. The toString() method is defined in the Object class and is inherited by all Java classes. The toString() method is usually overridden so that it returns a meaningful string representation of the object.
  3. equals() - You can check if an object equals another object by calling its equals() method and passing another object as a parameter to compare for equality. The equals() method defined in the Object class uses the identity operator (==) to determine if two objects are equal. Hence this method returns correct result for primitive data types; but returns incorrect result for objects since the identity operator checks if the object references are equal instead of checking the logical equality of objects. Hence equals() method is usually overridden to compare the logical equality of objects rather than their references.
  4. hashcode() - You get the hash code of an object by calling its hashcode() method. An objects hash code determines its memory address. As a rule, if two objects are equal then their hash codes must also be equal. If you override equals() method, then you also have to override the hashcode() method to ensure that objects that are equal will have the same hash codes.
  5. finalize() - The Java garbage collector calls the finalize() method of an object just before the object is garbage collected. But you cannot control when, or if, an object is garbage collected. Hence, you should not rely on this method to perform critical tasks.
  6. getClass() - Calling getClass() method on an object returns a Class object which is a runtime class of this object. The Class class defines a number of methods which helps to find the metadata of a class - such as the class name, methods defined in the class, check if the class is an interface, check if the class is an interface etc.
  7. wait() - wait() is one of the three methods defined in Object class that facilitates thread to thread communication in multi-threaded Java programs. Calling wait() on an object of type Thread stops the execution of current thread until the processing of the other thread is complete.
  8. notify() - notify() is the second method defind in Java object class that facilitates thread to thread communication in multi-thread programming. notify() method will send an event notification or signal to a thread that is waiting in that object's waiting pool.
  9. notifyAll() - notifyAll() is the third method defind in Java object class that facilitates thread to thread communication in multi-thread programming. notifyAll() is similar to notify(), except that it sends notification to all threads that are waiting in that objects waiting pool

Q).How many types of control statements in Java?
A). In Java three types of control statements

  1. Decision making statements
  2. Looping statements
  3. Jump statements

Q).What is mean by Decision making statements in java?
A). Decision making statements are used to perform some decision based on the conditions, decision statements will be executed while execution of a java program. While execution of a program these statements will decide which statement to execute and when. Decision-making statements evaluate the Boolean expression and control the program flow depending upon the result of the condition provided.

Q).How many types of Decision making statements in Java?
A). Decision making statements are devided into 5 types:

  1. if statement
  2. if-else statement
  3. nested if-else statement
  4. if-else-if laddar statement
  5. switch statement

Q).Explain the if statement in Java?
A). if statement is the most simple decision-making statement. It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not.

Q).What is the syntax of if statement in Java?


                          if(condition) 
                          {
                            // Statements to execute if
                            // condition is true
                          }
                        

Q).Explain the if-else statement in Java?
A). if the condition is true then the code in if block is executed otherwise the else block is executed.

Q).What is the syntax of if statement in Java?


                            if (condition) {
                                // If block executed when the condition is true
                              }
                              else {
                                    // Else block executed when the condition is false
                              }
                        

Q).What is the syntax of if statement in Java?


                          if(condition) 
                          {
                            // Statements to execute if
                            // condition is true
                          }
                        

Q).Explain the nested if-else statement in Java?
A). Java allows us to nest if statements within if statements. Nested-if statements mean an if or if-else statement inside another if or else-if statement. It is similar to an if-else statement but they are defined inside another if-else statement.

Q).What is the syntax of if statement in Java?


                            if (condition1) {
                                // Executed when the condition1 is true
                                if (condition2) {
                                    // Executed when the condition2 is true
                                } 
                                else{
                                    // Executed when the condition2 is false
                                }
                              }   
                              else {
                                  // Executed when the condition1 is false
                              }
                        

Q).Explain the if-else-if laddar statement in Java?
A). If the condition is true, then it will execute the If block. Otherwise, it will execute the Else-If block. Again, if the condition is not met, then it will move to the else block.

Q).What is the syntax of if statement in Java?


                            if(Boolean_expression 1) {
                                // Executes when the Boolean expression 1 is true
                             }else if(Boolean_expression 2) {
                                // Executes when the Boolean expression 2 is true
                             }else if(Boolean_expression 3) {
                                // Executes when the Boolean expression 3 is true
                             }else {
                                // Executes when the none of the above condition is true.
                             }
                        

Q).Explain the switch statement in Java?
A). Switch statement allows program to select one action among multiple actions during the program execution. Switch statements are almost similar to the if-else-if ladder control statements in Java. It is a multi-branch statement. It is a bit easier than the if-else-if ladder and also more user-friendly and readable. The switch statements have an expression and based on the output of the expression, one or more blocks of codes are executed. These blocks are called cases. We may also provide a default block of code that can be executed when none of the cases are matched

Q).What are the importants to be remembered while using switch statement in Java?
A). There are certain points that one needs to be remembered while using switch statements:

  1. The expression can be of type string, short, byte, int, char, or an enumeration.
  2. We cannot have any duplicate case values.
  3. The default statement is optional.
  4. Usually, the break statement is used inside the switch to terminate a statement sequence.
  5. The break statement is optional. If we do not provide a break statement, execution will continue to the next case. This is known as the trailing case.

Q).What is the syntax of if statement in Java?


                            switch (expression) {
                                case value1:
                                    //code block of case with value1
                                    break;
                                case value2:
                                    //code block of case with value2
                                    break;
                                case valueN:
                                    //code block of case with valueN
                                    break;
                                default:
                                   //code block of default value
                              }
                        

Q).What is mean by looping statement in Java?
A). Looping statements are the statements which executes a block of code repeatedly until some condition meet to the criteria. Loops can be considered as repeating if statements.

Q).How many types of looping statement in Java?
A). There are 4 types of looping statements:

  1. while loop
  2. do-while loop
  3. for loop
  4. for-each loop

Q).Explain the while loop in Java?
A). While loop executes till the condition becomes false.

Q).What is the syntax of while loop in Java?


                            while (boolean condition)
                            {
                                // code block to be executed
                            }
                        

Q).Explain the do-while Loop in Java?
A). When you are using for or while, then it will execute the loop body only if the condition if true. In do-while loop, it will execute the loop first, then it checks the condition. So, it will execute the loop atleast once.

Q).What is the syntax of do-while Loop in Java?


                            do 
                            {
                                // code block to be executed
                            } while (boolean condition)
                        

Q).Explain the For Loop in Java?
A). It executes the code until condition is false. It is used when number of iterations are known. In a for loop statement, execution begins with the initialization of the looping variable, then it executes the condition, and then it increments or decrements the looping variable. If the condition results in true then the loop body is executed otherwise the for loop statement is terminated.

Q).What is the syntax of For Loop in Java?


                            for (initialization; termination condition; increment/decrement)
                            {
                                // code block to be executed
                            }
                        

Q).Explain the For-each Loop in Java?
A). The for-each loop statement provides an approach to traverse through elements of an array or a collection in Java. It executes the body of the loop for each element of the given array or collection. It is also known as the Enhanced for loop statement because it is easier to use than the for loop statement as you don’t have to increment the value. The major difference between the for and for-each loop is that whereas the for loop is a general-purpose loop that we can use for any use case, the for-each loop can only be used with collections or arrays. In for-each loop statement, you cannot skip any element of the given array or collection. Also, you cannot traverse the elements in reverse order using the for-each loop control statement in Java.

Q).What is the syntax of For Loop in Java?


                            for(dataType variableName : array | collection)
                            {
                                // code block to be executed   
                            } 
                        

Q).What is mean by Jump Statements in Java?
A). Jump statments in java are used to jump from a statement to another statement, thereby the transferring the flow of execution.

Q).How many types of Jump Statements in Java?
A). Jump statements are two types:

  1. Break Statement
  2. Continue Statement

Q).What is mean by Break Statement in Java?
A). The break statement as we can deduce from the name is used to break the current flow of the program. The break statement is commonly used in the following three situations:

  1. Terminate a case block in a switch statement as we saw in the example of the switch statement in the above section.
  2. To exit the loop explicitly, even if the loop condition is true.
The break statement cannot be used as a standalone statement in Java. It must be either inside a switch or a loop. If we try to use it outside a loop or a switch, JVM will give an error.

Q).What is the syntax of Jump statement in Java?


                            for(condition) {
                                //body of the loop
                                break;
                              }
                              while(loop) {
                                  //body of the loop
                                  break;
                              }
                        

Q).What is mean by Continue Statement in Java?
A). Sometimes there are situations where we just want to ignore the rest of the code in the loop body and continue from the next iteration. The continue statement in Java allows us to do just that. This is similar to the break statement in the sense that it bypasses every line in the loop body after itself, but instead of exiting the loop, it goes to the next iteration.

Q).What is the syntax of Jump statement in Java?


                            for(condition) {
                                //body of the loop
                                continue;
                                //the statements after this won't be executed
                              }
                              while(loop) {
                                //body of the loop
                                continue;
                                //the statements after this won't be executed
                              }
                        

Q).What is the difference between break and continue?
A). Break: It is a statement which transfers the control to outside of the loop. Continue: It is used to transfer the control to the beginning of the loop.

Q).What is an Array?
A). Array is a collection of similler data elements.

Q).What are the types of an array?
A). Arrays are generally categorized into two parts as described below:

  1. Single Dimensional Array
  2. Multi-Dimensional Array (2D and 3D arrays)

Q).How do you declare an Array in java?
A). We can declare an Array in java by the following way :

  1. dataType[] arrayVariableName = new dataType[arraySize];
    forExample: int[] temp = new int[256]

Q).What is the default value of Array for different data types?
A). We can declare an Array in java by the following way :

Data Type Default value
byte, short, int, long 0
float, double 0.0
boolean false
Any object null

Q).Can we change size of Array in java after creation?
A). We can not change the size of Array after creation. Although there are other data-structures which can change size after creation.

Q).Can we pass the negative number in Array size?
A). No, we can not pass the negative number as Array size. If you pass a negative number in Array size then you will not get the compiler error. Instead, you will get the NegativeArraySizeException at run time.

Q).Can you declare an Array without Array size?
A). No, we can not declare Array without Array size, will get compile time error.

Q).Where does Array stored in JVM memory ?
A). Array is an object in java. So, Array is stored in heap memory in JVM.

Q).What is ArrayStoreException ? When this exception is thrown ?
A). ArrayStoreException is a runtime exception. Array must contain the same data type elements. This exception is thrown to indicate that an attempt has been made to store the wrong type of object into an array of objects. In other words, if you want to store the integer Object in an Array of String you will get ArrayStoreException.

Q).What is the difference between ArrayStoreException and ArrayOutOfBoundsException ?
A). ArrayStoreException is thrown if you are trying to add incompatible data type. For example, if you try to add an integer object to String Array, then ArrayStoreException is thrown.

ArrayOutOfBoundsException is thrown when an attempt is made to access the Array with illegal index. For example, illegal index means if the index is either negative or greater than or equal to the size of the Array.

Q).What are the advantages of Array ?
A). We can sort multiple elements of Array at the same time. Using index, we can access the element of the Array in O(1) time.

Q).What are the disadvantages of Array?
A).

  1. To create an Array, contiguous memory is required. It is possible in JVM that the memory is available to accommodate Array but memory available is not contiguous.
  2. The Array is static data structure. It is of fixed size. We can not increase or decrease the size of the Array after creation.

Q).Can we use Generics with an Array?
A). No, we can not use generics with an Array.

Q).Which is legal int[] arr or int arr[] ?
A). Both are legal statements. It is preferred to write int[] arr instead of int arr[].

Q). What are jagged arrays in java?
A). Arrays containing arrays of different length is known as jagged arrays. Multidimensional arrays are also known as jagged arrays.