Java Questions Part1 - Basic Questions


Other Important Questions and Answers:

1. What is Java?

Answer:  Java is a programming language and computing platform first released by Sun Microsystems in 1995. There are lots of applications and websites that will not work unless you have Java installed, and more are created every day. Java is fast, secure, and reliable. From laptops to datacenters, game consoles to scientific supercomputers, cell phones to the Internet, Java is everywhere!
Java is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers “write once, run anywhere” (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation.
For example, you can write and compile a Java program on UNIX and run it on Microsoft Windows, Macintosh, or UNIX machine without any modifications to the source code.
The Oracle implementation is packaged into two different distributions:
Java Runtime Environment (JRE) which contains the parts of the Java SE platform required to run Java programs and is intended for end users.
Java Development Kit (JDK) which is intended for software developers and includes development tools such as the Java compiler, Javadoc, Jar, and a debugger.

2. Additional features in Java 8?

Answer:  “Java Platform, Standard Edition 8 (Java SE 8)” is released on 18th March 2014. Along with the Java SE 8 platform, the product that implements the platform, “Java SE Development Kit 8 (JDK 8)” and “Java SE Runtime Environment 8 (JRE 8)” is also released.
Some of the important Java 8 features are;
forEach() method in Iterable interface
default and static methods in Interfaces
Functional Interfaces and Lambda Expressions
Java Stream API for Bulk Data Operations on Collections
Java Time API
Collection API improvements
Concurrency API improvements
Java IO improvements
Miscellaneous Core API improvements

3. Is Java a pure 100% Object Oriented Programming language?

Answer:  Java is not fully object oriented because it supports primitive data type like it, byte, long etc., which are not objects. Because in JAVA we use data types like int, float, double etc which are not object oriented, and of course is what opposite of OOP is. That is why JAVA is not 100% objected oriented.

4. What is the parent or base class of all the classes in Java? 

Answer: java.lang.Object class is the super base class of all Java classes. Every other Java classes descends from Object.

5. What is a Package in Java?

Answer:  Package in Java is a mechanism to encapsulate a group of classes, sub packages and interfaces. Packages are used for: Preventing naming conflicts. A default member (without any access specifier) is accessible by classes in the same package only. Packages can also be considered as data encapsulation (or data-hiding).

6. What is a class?

Answer:  A class is a user defined blueprint or prototype from which objects are created.  It represents the set of properties or methods that are common to all objects of one type. In general, class declarations can include these components, in order:
Modifiers : A class can be public or has default access (Refer this for details).
Class name: The name should begin with a initial letter (capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass), if any, preceded by the keyword extends. A class can only extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces implemented by the class, if any, preceded by the keyword implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.

7. What is class file?

Answer:  A Java class file is a file containing Java bytecode and having .class extension that can be executed by JVM. A Java class file is created by a Java compiler from .java files as a result of successful compilation. As we know that a single Java programming language source file (or we can say .java file) may contain one class or more than one class. So if a .java file has more than one class then each class will compile into a separate class files.
For Example: Save this below code as Test.java on your system.
class Sample 
{   
// Class Declaration-- 
class Student 
// Class Declaration-- 
class Test 
       public static void main(String[] args)    
       { 
           System.out.println("Class File"); 
       } 
}  
For Compiling:
After compilation there will be 3 class files in corresponding folder named as:
Sample.class
Student.class
Test.class

8. What is byte code?

Answer:  Java bytecode is the instruction set for the Java Virtual Machine. It acts similar to an assembler which is an alias representation of a C++ code. As soon as a java program is compiled, java bytecode is generated. In others words, java bytecode is the machine code in the form of a .class file. With the help of java bytecode we achieve platform independence in java.

9. What is nested Class?

Answer:  In java, it is possible to define a class within another class, such classes are known as nested classes. They enable you to logically group classes that are only used in one place, thus this increases the use of encapsulation, and create more readable and maintainable code.
The scope of a nested class is bounded by the scope of its enclosing class.
A nested class has access to the members, including private members, of the class in which it is nested. However, reverse is not true i.e. the enclosing class does not have access to the members of the nested class.
A nested class is also a member of its enclosing class.
As a member of its enclosing class, a nested class can be declared private, public, protected, or package private(default).
Nested classes are divided into two categories:
static nested class : Nested classes that are declared static are called static nested classes.
inner class : An inner class is a non-static nested class.

Syntax:
class OuterClass
{
...
    class NestedClass
    {
        ...
    }
}

10. What are the different access specifiers in Java?

Answer: There are 4 types of access modifiers in Java:
Private
Public
Default
Protected
1) Private
If a variable is declared as private, then it can be accessed within the class. This variable won’t be available outside the class. So, the outside members cannot access the private members.
Note: Classes and interfaces cannot be private.
2) Public
Methods/variables with public access modifiers can be accessed by all the other classes in the project.
3) Protected
If a variable is declared as protected, then it can be accessed within the same package classes and sub-class of any other packages.
Note: Protected access modifier cannot be used for class and interfaces.
4) Default Access Modifier
If a variable/method is defined without any access modifier keyword, then that will have a default modifier access.

11. Explain stack and heap in Java for memory management?

Answer:  Stack is used for static memory allocation and Heap for dynamic memory allocation, both stored in the computer's RAM.
The main difference between heap and stack is that stack memory is used to store local variables and function call while heap memory is used to store objects in Java.
What is Stack Memory?
Stack in java is a section of memory which contains methods, local variables, and reference variables. Stack memory is always referenced in Last-In-First-Out order. Local variables are created in the stack.
What is Heap Memory?
Heap is a section of memory which contains Objects and may also contain reference variables. Instance variables are created in the heap
The JVM divided the memory into following sections.
Heap
Stack
Code
Static
The code section contains your bytecode.
The Stack section of memory contains methods, local variables, and reference variables.
The Heap section contains Objects (may also contain reference variables).
The Static section contains Static data/methods.

12. What’s Singleton class?

Answer:  In object-oriented programming, a singleton class is a class that can have only one object (an instance of the class) at a time.
After first time, if we try to instantiate the Singleton class, the new variable also points to the first instance created. So whatever modifications we do to any variable inside the class through any instance, it affects the variable of the single instance created and is visible if we access that variable through any variable of that class type defined.
To design a singleton class:
Make constructor as private.
Write a static method that has return type object of this singleton class. Here, the concept of Lazy initialization in used to write this static method.
Normal class vs Singleton class: Difference in normal and singleton class in terms of instantiation is that, For normal class we use constructor, whereas for singleton class we use getInstance() method. In general, to avoid confusion we may also use the class name as method name while defining this method.

13. Explain SingletonDesign pattern in Java?

14. What is the use of static keyword in Main()?

Answer:  Java program's main method has to be declared static because keyword static allows main to be called without creating an object of the class in which the main method is defined.

15. What is the difference between Java and JavaScript?

Answer: JavaScript is a lightweight programming language(“scripting language”) and used to make web pages interactive. It can insert dynamic text into HTML.JavaScript is also known as browser’s language.
JavaScript(JS) is not similar or related to Java. Both the languages have a C like a syntax and are widely used in client-side Web applications, but there are few similarities only.
Java is an object-oriented programming language and have virtual machine platform that allows you to create compiled programs that run on nearly every platform. Java promised, “Write Once, Run Anywhere”.
Here are the differences:
The JavaScript programming language is developed by Netscape, Inc and not part of the Java platform.
Java applications are run in a virtual machine or web browser while JavaScript is run on a web browser.
Java code is compiled whereas while JavaScript code is in text and in a web page.
JavaScript is an OOP scripting language, whereas Java is an OOP programming language.

16. Is null a keyword in Java?

Answer:  It is simply a value that indicates that the object reference is not currently referring to an object. The null type has one value, the null reference, represented by the null literal null, which is formed from ASCII characters. A null literal is always of the null type.

17. Why String is non primitive?

Answer:  Strings has its own feature that they are immutable. ... Primitive data types has limitation that they have fixed size and can hold data of that type only but String can vary in size and it can hold any type of data using its wrapper classes and it is one of reason why STRING IS NON-PRIMITIVE data type.

18. what is JIT (just in time compiler)

Answer:  The Just-In-Time (JIT) compiler is a an essential part of the JRE i.e. Java Runtime Environment, that is responsible for performance optimization of java based applications at run time. Compiler is one of the key aspects in deciding performance of an application for both parties i.e. the end user and the application developer.

19. What is Autoboxing and un-boxing?

Answer:  Autoboxing: Converting a primitive value into an object of the corresponding wrapper class is called autoboxing. For example, converting int to Integer class. The Java compiler applies autoboxing when a primitive value is:
Passed as a parameter to a method that expects an object of the corresponding wrapper class.
Assigned to a variable of the corresponding wrapper class.
Unboxing: Converting an object of a wrapper type to its corresponding primitive value is called unboxing. For example conversion of Integer to int. The Java compiler applies unboxing when an object of a wrapper class is:

Passed as a parameter to a method that expects a value of the corresponding primitive type.
Assigned to a variable of the corresponding primitive type.

20. How do you write custom class which is immutable?

Answer: To create an immutable class in java, you have to do following steps.
Declare the class as final so it can’t be extended.
Make all fields private so that direct access is not allowed.
Don’t provide setter methods for variables
Make all mutable fields final so that it’s value can be assigned only once.
Initialize all the fields via a constructor performing deep copy.
Perform cloning of objects in the getter methods to return a copy rather than returning the actual object reference.

21. Can we create private access specifier inside interface?

Answer:  Java 9 onward, you are allowed to include private methods in interfaces. Using private methods, now encapsulation is possible in interfaces as well.
Interfaces till Java 7
In Java 7 and all earlier versions, interfaces were very simple. They could only contain public abstract methods. These interface methods MUST be implemented by classes which choose to implement the interface.
From Java 8, apart from public abstract methods, you can have public static methods and public default methods.

22. Do you have any idea on Enumeration?

Answer:  Enumeration means a list of named constant. In Java, enumeration defines a class type. An Enumeration can have constructors, methods and instance variables. It is created using enum keyword. Each enumeration constant is public, static and final by default.

enum WeekDays

{ sun, mon, tues, wed, thurs, fri, sat }

class Test

{

 public static void main(String args[])

 {

  WeekDays wk; //wk is an enumeration variable of type WeekDays

  wk = WeekDays.sun; //wk can be assigned only the constants defined under enum type Weekdays

  System.out.println("Today is "+wk);

 }

}

Output:

Today is sun

23. Assert is an abstract or static method?

24. Difference between Instantiate and Initialize in Java?

Answer:  Initialization-Assigning a value to a variable i.e a=0,setting the initial values. 
Instantiation- Creating the object i.e when u r referencing a variable to an object with new operator.

25. Difference between == and =.?

Answer:  = is an Assignment Operator it is used to assign the value of variable or expression, while == is an Equal to Operator and it is a relation operator used for comparison (to compare value of both left and right side operands).

26. What is the difference between equals() and == operator?

Answer:  In general both equals() and “==” operator in Java are used to compare objects to check equality but here are some of the differences between the two:
Main difference between .equals() method and == operator is that one is method and other is operator.
We can use == operators for reference comparison (address comparison) and .equals() method for content comparison. In simple words, == checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects.
public class Test { 

    public static void main(String[] args) 

    { 
        String s1 = new String("HELLO"); 

        String s2 = new String("HELLO"); 

        System.out.println(s1 == s2); 

        System.out.println(s1.equals(s2)); 

    } 

} 

Output:
false
true

27. Can we create an object for an abstract class?

Answer: you can't create object of abstract class because there is an abstract method which has nothing so you can call that abstract method too. If we will create an object of the abstract class and calls the method having no body(as the method is pure virtual) it will give an error.

28. What is reflection in Java?

Answer:  Reflection is an API which is used to examine or modify the behavior of methods, classes, interfaces at runtime.
The required classes for reflection are provided under java.lang.reflect package.
Reflection gives us information about the class to which an object belongs and also the methods of that class which can be executed by using the object.
Through reflection we can invoke methods at runtime irrespective of the access specifier used with them.
Reflection can be used to get information about –
Class The getClass() method is used to get the name of the class to which an object belongs.
Constructors The getConstructors() method is used to get the public constructors of the class to which an object belongs.
Methods The getMethods() method is used to get the public methods of the class to which an objects belongs.

29. What is up casting and down casting in Java? How will you use it in Selenium with an example?

Answer:  Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but downcasting involves a type check and can throw a ClassCastException . ... Basically what you're doing is telling the compiler that you know what the runtime type of the object really is.
We can create Object of a class FirefoxDriver by taking reference of an interface (WebDriver). In this case, we can call implemented methods of WebDriver interface. ... Every browser driver class implements WebDriver interface and we can get all the methods. It helps you when you do testing on multiple browsers

30. How will you call a protected method in a nested class?

Answer:  

31. Why java developer decided to keep object class as super most class in java hierarchy.

Answer: Following could be the reasons for this design decision,
By having the Object as the super class of all Java classes, without knowing the type we can pass around objects using the Object declaration.
Before generics was introduced, imagine the state of heterogeneous Java collections. A collection class like ArrayList allows to store any type of classes. It was made possible only by Object class hierarchy.
The other reason would be to bring a common blueprint for all classes and have some list of functions same among them. I am referring to methods like hashCode(), clone(), toString() and methods for threading which is defined in Object class.

32. What is the difference between instance variable and local variable?

Answer:  What is a Local Variable?
A local variable in Java is typically used in a method, constructor, or bloc and has only local scope. So, you can use the variable only within the scope of a block. Other methods in the class aren't even aware that the variable exists.

if(x > 50) {
    String testLocal = "some value";
}
In the above case, you cannot use testLocal outside of that if block.
What is an Instance Variable?
An instance variable is a variable that's bound to the object itself. Instance variables are declared in a class , but outside a method. And every instance of that class (object) has it's own copy of that variable. Changes made to the variable don't reflect in other instances of that class. Instance variables are available to any method bound to an object instance . As a practical matter, this generally gives it scope within some instantiated class object. When an object is allocated in the heap , there is a slot in it for each instance variable value. Therefore an instance variable is created when an object is created and destroyed when the object is destroyed.
class TestClass{
     public String StudentName;
     public int age;
}
What is a Class/Static Variable
Class variables are declared with keyword static, but outside a method. So, they are also known as static member variables and there's only one copy of that variable is shared with all instances of that class. If changes are made to that variable, all other instances will see the effect of the changes.
public class Product {
    public static int Barcode;
}
Class Variables are stored in static memory. It is rare to use static variables other than declared final and used as either public or private constants.

33. To exit the system from the current execution what command is used in java?

Answer:  The java.lang.System.exit() method exits current program by terminating running Java virtual machine. This method takes a status code. A non-zero value of status code is generally used to indicate abnormal termination. This is similar exit in C/C++.
Following is the declaration for java.lang.System.exit() method:
public static void exit(int status)

34. Difference between for and foreach loops in java and use of it?

Answer: The biggest differences are that a foreach loop processes an instance of each element in a collection in turn, while a for loop can work with any data and is not restricted to collection elements alone.

35. Difference between Break and Continue?

Answer: The break keyword is used to breaks(stopping) a loop execution, which may be a for loop, while loop, do while or for each loop. The continue keyword is used to skip the particular recursion only in a loop execution, which may be a for loop, while loop, do while or for each loop.
class BreakAndContinue

{
    public static void main(String args[])

    {
        // Example of break statement (execution stops when value of i becomes to 4.)

        System.out.println("Break Statement\n....................");

        for(int i=1;i<=5;i++)

        {

            if(i==4) break;

            System.out.println(i);

        }
        // Example of continue statement (execution skipped when value of i becomes to 1.)

        System.out.println("Continue Statement\n....................");
        for(int i=1;i<=5;i++)

        {

            if(i==1) continue;

            System.out.println(i);

        }

    }

}

Output:
Break Statement
....................
1
2
3
Continue Statement
....................
2
3
4
5

36. What is the difference between Call by Value and Call by Reference?

Answer:  Call by Value means calling a method with a parameter as value. Through this, the argument value is passed to the parameter.

While Call by Reference means calling a method with a parameter as a reference. Through this, the argument reference is passed to the parameter.

Call By Value:
public class Tester{

   public static void main(String[] args){

      int a = 30;

      int b = 45;

      System.out.println("Before swapping, a = " + a + " and b = " + b);

      // Invoke the swap method

      swapFunction(a, b);

      System.out.println("\n**Now, Before and After swapping values will be same here**:");

      System.out.println("After swapping, a = " + a + " and b is " + b);

   }

   public static void swapFunction(int a, int b) {

      System.out.println("Before swapping(Inside), a = " + a + " b = " + b);

      // Swap n1 with n2

      int c = a;

      a = b;

      b = c;

      System.out.println("After swapping(Inside), a = " + a + " b = " + b);

   }

}

Output:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45

Call By Reference:
public class JavaTester {

   public static void main(String[] args) {

      IntWrapper a = new IntWrapper(30);

      IntWrapper b = new IntWrapper(45);

      System.out.println("Before swapping, a = " + a.a + " and b = " + b.a);

      // Invoke the swap method

      swapFunction(a, b);

      System.out.println("\n**Now, Before and After swapping values will be different here**:");

      System.out.println("After swapping, a = " + a.a + " and b is " + b.a);

   }

   public static void swapFunction(IntWrapper a, IntWrapper b) {

      System.out.println("Before swapping(Inside), a = " + a.a + " b = " + b.a);

      // Swap n1 with n2

      IntWrapper c = new IntWrapper(a.a);

      a.a = b.a;

      b.a = c.a;

      System.out.println("After swapping(Inside), a = " + a.a + " b = " + b.a);

   }

}

class IntWrapper {

   public int a;

   public IntWrapper(int a){ this.a = a;}

}

Output:
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be different here**:
After swapping, a = 45 and b is 30

37. Is there any way to deallocate memory in JAVA?

Answer:  Java uses managed memory, so the only way you can allocate memory is by using the new operator, and the only way you can deallocate memory is by relying on the garbage collector. ... You can also call System.gc() to suggest that the garbage collector run immediately

38. What is Final, Finally, Finalize?

Answer:
final:
final is used to apply restrictions on class, method and variable. Final class can't be inherited, final method can't be overridden and final variable value can't be changed.
class FinalExample{  

public static void main(String[] args){  

final int x=100;  

x=200;//Compile Time Error  

}}  

finally:
Finally is used to place important code, it will be executed whether exception is handled or not.
class FinallyExample{  

public static void main(String[] args){  

try{  

int x=300;  

}catch(Exception e){System.out.println(e);}  

finally{System.out.println("finally block is executed");}  

}}  

Output:
finally block is executed

finalize:
Finalize is used to perform clean up processing just before object is garbage collected.
class FinalizeExample{  

public void finalize(){System.out.println("finalize called");}  

public static void main(String[] args){  

FinalizeExample f1=new FinalizeExample();  

FinalizeExample f2=new FinalizeExample();  

f1=null;  

f2=null;  

System.gc();  

}}  

Output:
finalize called
finalize called

39. What is done in finally block?

Answer: Please refer above question.

40. what are the methods in object class

Answer:  Following methods are available
public final Class getClass()
public int hashCode()
public boolean equals(Object obj)
protected Object clone() throws CloneNotSupportedException
public String toString()
public final void notify()
public final void notifyAll()
public final void wait(long timeout)throws InterruptedException
public final void wait(long timeout,int nanos)throws InterruptedException
public final void wait()throws InterruptedException
protected void finalize()throws Throwable

41. Why Strings are immutable in Java?

Answer: In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
class Testimmutablestring{  

 public static void main(String args[]){  

   String s="Virat";  

   s.concat("Kohli");//concat() method appends the string at the end  

   System.out.println(s);//will print Virat because strings are immutable objects  

 }  

}  

Output:
Virat

Why string objects are immutable in java?
Because java uses the concept of string literal.Suppose there are 5 reference variables,all referes to one object "Virat".If one reference variable changes the value of the object, it will be affected to all the reference variables. That is why string objects are immutable in java.

42. Difference between String, StringBuilder And StringBuffer?
Answer:  String vs StringBuffer vs StringBuilder
String is immutable whereas StringBuffer and StringBuider are mutable classes.
StringBuffer is thread safe and synchronized whereas StringBuilder is not, thats why StringBuilder is more faster than StringBuffer.
String concat + operator internally uses StringBuffer or StringBuilder class.
For String manipulations in non-multi threaded environment, we should use StringBuilder else use StringBuffer class.

43. What is the purpose of using Wrapper classes in Java?
Answer:  They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). The classes in java.util package handles only objects and hence wrapper classes help in this case also.

44. Can we use private and protect access modifiers inside an Interface?

Answer:  Interface members are always public because the purpose of an interface is to enable other types to access a class or struct. No access modifiers can be applied to interface members

45. What happens when we specify the final non-access modifier with variables and methods in Java?

46. Can we have multiple public classes inside a single class in Java?

Answer:  there can only be one public class per .java file, as public classes must have the same name as the source file. One Java file can consist of multiple classes with the restriction that only one of them can be public.

47. Why main() is declared as static?

Answer:  Main() is declared as static as it is directly call by the JVM without creating an object of the class in which the it is declared. When java runtime starts,there is no object of class present.Thats why main method has to be static,so JVM can load the class into memory and call the main method.

48. What is Garbage Collection in Java and how exactly it is done?

Answer:  In java, garbage means unreferenced objects.
Garbage Collection is process of reclaiming the runtime unused memory automatically. In other words, it is a way to destroy the unused objects.
To do so, we were using free () function in C language and delete() in C++. But, in java it is performed automatically. So, java provides better memory management.
Advantages:
It makes java memory efficient because garbage collector removes the unreferenced objects from heap memory.
It is automatically done by the garbage collector(a part of JVM) so we don't need to make extra efforts.
There are many ways object be unreferenced:
1. By nulling a reference:
Employee e=new Employee();  
e=null;  

2. By assigning a reference to another:
Employee e1=new Employee();  
Employee e2=new Employee();  
e1=e2;//now the first object referred by e1 is available for garbage collection
3. By anonymous object:
new Employee();
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize(){}  
gc() method
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc() is found in System and Runtime classes.

public static void gc(){}  
Example of garbage collection in java
public class TestGarbage1{  
 public void finalize(){System.out.println("object is garbage collected");}  
 public static void main(String args[]){  
  TestGarbage1 s1=new TestGarbage1();  
  TestGarbage1 s2=new TestGarbage1();  
  s1=null;  
  s2=null;  
  System.gc();  
 }  
}  

49. How to execute Java program from the command prompt?

Answer:  
Open a command prompt window and go to the directory where you saved the java program (MyFirstJavaProgram.java). ...
Type 'javac MyFirstJavaProgram.java' and press enter to compile your code. ...
Now, type ' java MyFirstJavaProgram ' to run your program.
You will be able to see the result printed on the window.

50. What’s the difference between plug-ins and dependencies?

Answer: Both plugins and dependencies are Jar files. But the difference between them is, most of the work in maven is done using plugins; whereas dependency is just a Jar file which will be added to the classpath while executing the tasks. For example, you use a compiler-plugin to compile the java files.

51. How to assign different types of values say integer, character, string, decimal and boolean into the same array? 

Answer:  we cannot store multiple datatype in an Array, we can store similar datatype only in an Array. You can create an array with elements of different data types when declare the array as Object. Since System.Object is the base class of all other types, an item in an array of Objects can have a reference to any other type of object.
object[] mixedArray = new object[4];
mixedArray[0]=10;
mixedArray[1]="Jack";
mixedArray[2]=true;
mixedArray[3]=System.DateTime.Now;
In order to retrieve different data types from an Object array, you can convert an element to the appropriate data type.
int id = int.Parse(mixedArray(0));
DateTime admissionDate = DateTime.Parse(mixedArray(3));

52. In public static void main(String arr[])… what if i replace public with private

Answer: Consider following Java program:
class AutomationtestingInsider{ 

    public static void main(String args[]) 

    { 

        System.out.println("AutomationTestingInsider"); 

    } 

} 

Output:
AutomationTestingInsider

Explanation:
1)public: It is an access specifier which allows the JVM(Java Virtual Machine) to access the main method from anywhere.
2)static: static keyword allows the JVM to access the main method without any instance(object).
3)void: It specifies that the main method doesn’t return anything.
4)main: name of the method(function) configured in JVM.
5)String args[]: Command line arguments.
Now, if we replace ‘public’ with ‘private’ in “public static void main”, the above code becomes:

class ATI { 
    private static void main(String args[]) 
    { 
        System.out.println("AutomationTestingInsider"); 
    } 
}

The above code will be compiled successfully, but will throw a runtime error as follows:
Error: Main method not found in class ATI, please define the main method as:
   public static void main(String[] args)
or a JavaFX application class must extend javafx.application.Application.


No comments:

Post a Comment