JavaInterview Flashcards

2
Q

What do you understand by a variable?

A

Variable is a named memory location that can be easily referred in the program. A variable is just a container for holding data and is accesible through a reference.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the Java API?

A

The Java API(Application Programming Interface) is the set of classes included with the Java Development Environment. These classes are written using the Java language and run on the JVM.

The Java API includes everything from collection classes to GUI classes

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is JVM,JRE, JDK?

A

The Java Virtual Machine(JVM) is the software that can be ported onto various hardware-based platforms.The JVM executes instructions that a Java compiler generates.

The JRE is the Java Runtime Environment consisting of the JVM, the Java libraries, and all other components necessary to run Java applications and applets, but does not contain any development tools such as a compiler or a debugger JDK contains software development tools which are used to compile and run the Java program.

Both JDK and JRE contains the JVM.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What if the main method is declared as private?

A

The program compiles properly but at runtime it will give “Main method not public” error message.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What if the static modifier is removed from the signature of the main method?

A

Program compiles.But at runtime throws an error “NoSuchMethodError

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What if I do not provide the String array as the argument to the method?

A

The program works fine.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is meant by pass by reference and pass by value in Java?

A

Pass by reference means, passing the address itself(like pointers) rather than passing the value.

Pass by value means passing a copy of the value.

Java uses pass by value.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

If you’re overriding the method equals() of an object, which other method you might also consider?

A

hashCode()

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is Byte Code?

A

All Java programs are compiled into class files that contain bytecodes.

Java bytecode is produced by the Java compiler and executed by the JVM.

Bytecode is the intermediate representation of Java programs just as assembly code is the intermediate representation of C or C++ programs

Java bytecode is one of the things that make it possible for Java code to run on many different platforms.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Expain the reason for each keyword of public static void main(String args[])?

A

public main(..) is the first method called by java environment when a program is executed so it has to accessible from java environment. Hence the access specifier has to be public.

static: Java environment should be able to call this method without creating an instance of the class , so this method must be declared as static.

void: main does not return anything so the return type must be void

String args[] The argument String indicates the argument type which is given at the command line and args is an array for string given during command line.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the differences between == and .equals()?

A

The == operator compares two objects to determine if they are present in the same memory location. It is possible for two String objects to have the same value, but located in different areas of memory.

== compares references while .equals compares contents.

The method public boolean equals(Object obj) is provided by the Object class and can be overridden.

The default implementation uses the equality operator == to compare the object.

String, BitSet, Date, and File override the equals() method.

For two String objects, value equality means that they contain the same character sequence.

Example:

public static void main(String[] args) { String s1 = "abc"; String s2 = s1; String s5 = "abc"; String s3 = new String("abc"); String s4 = new String("abc"); System.out.println("== comparison : " + (s1 == s5)); System.out.println("== comparison : "" + (s1 == s2)); System.out.println("Using equals method : " + s1.equals(s2)); System.out.println("== comparison : "" + s3 == s4); System.out.println("Using equals method : " + s3.equals(s4)); }

Output

== comparison : true == comparison : true Using equals method : true == comparison : false Using equals method : true
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What is final, finalize() and finally? What does it mean that a class or member is final?

A

final - Variables defined in an interface are implicitly final.

A final class can’t be extended i.e., final class may not be subclassed. This is done for security reasons with basic classes like String and Integer. It also allows the compiler to make some optimizations, and makes thread safety a little easier to achieve.

A final method can’t be overridden when its class is inherited. You can’t change value of a final variable (is a constant)

finally - a key word used in exception handling and will be executed whether or not an exception is thrown. For example, closing of open connections is done in the finally method.

finalize - helps in garbage collection. finalize() method is used just before an object is destroyed and garbage collected

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Why there are no global variables in Java?

A

Global variables are globally accessible. Java encapsulates data and makes it available through methods. Every variable in Java must be declared within a class.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to convert String to Number in java program?

A

The valueOf() function of Integer class is is used to convert string to Number. Here is the code

Eg:

String numString = "1000"; int id = Integer.valueOf(numString).intValue();
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What is the difference between a while statement and a do statement?

A

A while statement (pre test) checks at the beginning of a loop to see whether the next loop iteration should occur. A do while statement (post test) checks at the end of a loop.

The do statement will always execute the loop body at least once.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Describe the principles of OOPS.

A

There are three main principles:

  • Polymorphism
  • Inheritance
  • Encapsulation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Explain the Inheritance principle.

A

Inheritance is the process by which one object acquires the properties and behaviour of another object. Inheritance allows well-tested methods to be reused and enables changes to be made once and have effect in all relevant places.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What do you understand by casting in java language? What are the types of casting?

A

The process of converting one data type to another is called Casting. There are two types of casting in Java; these are implicit casting and explicit casting.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is implicit and explicit casting?

A

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Explicit casting in the process in which the complier are specifically informed about transforming the object.

Implicit casting is the process of simply assigning one entity to another without any transformation guidance to the compiler. This type of casting is not permitted in all kinds of transformations and may not work for all scenarios.

Explicit casting in the process in which the complier are specifically informed about transforming the object.

Eg:

int i = 1000, k =100.20; long j = i; //Implicit int j = (int) i; //Explicit
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

What do you understand by downcasting?

A

The process of Downcasting refers to the casting from a general to a more specific type, i.e. casting down the hierarchy.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Is sizeof a keyword in java?

A

The sizeof method is not a keyword.

23
Q

What is a native method?

A

A native method is a method that is implemented in a language other than Java.

24
Q

In System.out.println(), what is System, out and println?

A

System is a predefined final class, out is a PrintStream object and println is a built-in overloaded method in the out object.

25
Q

Explain Polymorphism? Explain the different forms of Polymorphism.

A

Polymorphism simply means one name many forms.

Polymorphism enables one entity to be used as a general category for different types of actions. The specific action is determined by the exact nature of the situation.

In java there are two type of polymorphism:

  • compile time polymorphism (overloading)
  • runtime polymorphism (overriding).

Polymorphism exists in three distinct forms in Java:

  • Method overloading
  • Method overriding through inheritance
  • Method overriding through the Java interface
26
Q

Explain Encapsulation.

A

Encapsulation is a process of binding or wrapping the variables and the method that operates on them into a single entity. This keeps the data safe from outside interface and misuse. Objects allow methods to be encapsulated with their data to reduce potential interference.

Encapsulation may be used by creating ‘get’ and ‘set’ methods in a class which are used to access the fields of the object. Typically the fields are made private while the get and set methods are public.

Encapsulation provides data security by data hiding.

27
Q

What are Java Access modifiers? What is the difference between public, private, protected and default Access Specifiers?

A

Access specifiers are keywords that determine the type of access to the member of a class. These keywords are for allowing privileges to parts of a program such as methods and variables.

These are:

  • Public : accessible to all classes
  • Protected : accessible to the classes within the same package and any subclasses.
  • Private : accessible only to the class to which they belong
  • Default : accessible to the class to which they belong and to subclasses within the same package
28
Q

Which class is the superclass of every class?

A

Object.

29
Q

Name primitive Java types.

A

The 8 primitive types are byte, char, short, int, long, float, double, and boolean.

30
Q

What is the purpose of static variable and method?

A

A static variable is associated with the class as a whole rather than with specific instances of a class. Each object has only one copy per class, no matter how many objects are created from it.

A static method is a method that belongs to the class rather than any object of the class and doesn’t apply to an object or even require that any objects of the class have been instantiated.

Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.

A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final.

However, you can’t override a static method with a non-static method. In other words, you can’t change a static method into an instance method in a subclass.

31
Q

What is the difference between the boolean & operator and the && operator?

A

If an expression involving the boolean & operator is evaluated, both operands are evaluated, whereas the && operator is a short circuit operator.

When an expression involving the && operator is evaluated, the first operand is evaluated.

  • If the first operand returns a value of true then the second operand is evaluated.
  • If the first operand evaluates to false, the evaluation of the second operand is skipped.
32
Q

How does Java handle integer overflows and underflows?

A

Java does not give any explicit notifications of arithmetic underflow or overflow. For example,integer operations will just wrap around if you let the operands get too big.

Floating-point operations will not wrap around, but they won’t throw an exception either. If a floating point operation overflows, the result value is floating-point infinity.

Similarly, if it underflows,then the result will be 0.0.

33
Q

What is the difference between declaring a variable and defining a variable?

A

In declaration we only mention the type of the variable and its name without initializing it.

Defining means declaration + initialization.

E.g.

String s; //is just a declaration while String s = new String ("bob"); //is a definition.
34
Q

What type of parameter passing does Java support?

A

In Java the arguments (primitives and objects) are always passed by value.

With objects, the object reference itself is passed by value and so both the original reference and parameter copy both refer to the same object.

35
Q

What do you understand by numeric promotion?

A

The Numeric promotion is the conversion of a smaller numeric type to a larger numeric type, so that integral and floating-point operations may take place.

In the numerical promotion process the byte, char, and short values are converted to int values.

The int values are also converted to long values, if necessary.

The long and float values are converted to double values, as required.

36
Q

When is static variable and static block loaded in Java?

A

Static variable are loaded when classloader brings the class to the JVM. It is not necessary that an object has to be created. Static variables will be allocated memory space when they have been loaded.

The code in a static block is loaded/executed only once i.e. when the class is first initialized. A class can have any number of static blocks.

Static block is not member of a class, they do not have a return statement and they cannot be called directly and Cannot contain this or super. They are primarily used to initialize static fields.

37
Q

Explain working of Java Virtual Machine (JVM)?

A

Java compiler first converts .java file into .class byte code file.

Java Virtual Machine interprets the byte code into the machine code depending upon the underlying operating system and hardware combination. It is responsible for all the things like garbage collection, array bounds checking, etc.

The JVM is called “virtual” because it provides a machine interface that does not depend on the underlying operating system and machine hardware architecture.

This independence from hardware and operating system is a cornerstone of the write-once run-anywhere value of Java programs

38
Q

How can I swap two variables without using a third variable?

A

Method 1 :

  • Add two variables and assign the value into First variable.
  • Subtract the Second value with the result Value. and assign to Second variable.
  • Subtract the Result of First Variable With Result of Second Variable and Assign to First Variable
int a=5,b=10; a=a+b; b=a-b; a=a-b;

Method 2 :

  • use an XOR swap.
int a = 5; int b = 10; a = a ^ b; b = a ^ b; a = a ^ b;
39
Q

What is reflection API? How are they implemented?

A

Reflection is the process of introspecting the features and state of a class at runtime. This is supported using Reflection API with built-in classes like Class, Method, Fields, Constructors etc.

Eg: Using Java Reflection API we can get the class name, by using the getName method.

40
Q

Does JVM maintain a cache by itself?

A

Yes, the JVM maintains a cache by itself.

It creates the Objects on the heap, but references to those objects are on the STACK.

41
Q

What is phantom memory?

A

Phantom memory is false memory. Memory that does not exist in reality.

42
Q

Can a method be static and synchronized?

A

A static method can be synchronized.

If you do so, the JVM will obtain a lock on the java.lang.Class instance associated with the object. It is similar to saying:

synchronized(XYZ.class) { }
43
Q

What is difference between String and StringTokenizer?

A

A StringTokenizer is utility class used to break up string.

String is immutable while StringTokenizer is not

Eg:

StringTokenizer st = null; st = new StringTokenizer("Hello World"); while (st.hasMoreTokens()) { System.out.println(st.nextToken()); }

Output:

Hello World
44
Q

Does java support multiple interitance? Why?

A

Java doesnt support multiple inheritance but it provide a way through which it can enact it.

Consider the scenario is C++

Class A { public void add(){ // some text } } Class B { public void add(){ // some text } } Class C extends A,B { public static void main(String arg[]) { C objC = new C(); objC.add(); //problem, compiler gets confused //and cant decide to call Class A or B method. } }

This problem is called Diamond problem.

This problem in java is taken care with the use of interfaces In Java similar problem would look like:

interface A{ add(); } interface B{ add(); } class C implements A,B { add() { // doesn't matter which interface it belong to } }
45
Q

What is difference between instanceof and isInstance(Object obj)?

A

Differences are as follows:

  • instanceof is a reserved word of Java, but isInstance(Object obj) is a method of java.lang.Class.
  • instanceof method is used to check the type of an object which are known at compile time and isInstance() could only be called on class, say instance of java.lang.Class.
if (obj instanceof MyType) { ... } else if (MyType.class.isInstance(obj)) { ... }
  • instanceof is used of identify whether the object is type of a particular class or its subclass but isInstance(obj) is used to identify object of a particular class.
46
Q

Explain how Java supports pass by value?

A

Java passes the references by value just like any other parameter.

This means the references passed to the method are actually copies of the original references. Thus method manipulation will alter the objects, since the references point to the original objects. However setting the object reference to null or any other objectreference in the method will not be affected once it exits it as the object is passed by value.

Eg:

public void tricky(Point arg1, Point arg2) { arg1.x = 100; arg1.y = 100; Point temp = arg1; arg1 = arg2; arg2 = temp; } public static void main(String [] args) { Point pnt1 = new Point(0,0); Point pnt2 = new Point(0,0); S.o.p("X: " + pnt1.x + " Y: " + pnt1.y); S.o.p("X: " + pnt2.x + " Y: " + pnt2.y); S.o.p(" "); tricky(pnt1,pnt2); S.o.p("X: " + pnt1.x + " Y:" + pnt1.y); S.o.p("X: " + pnt2.x + " Y:" + pnt2.y); }

Output:

X: 0 Y: 0 X: 0 Y: 0 X: 100 Y: 100 X: 0 Y: 0

The method successfully alters the value of pnt1, even though it is passed by value; however, a swap of pnt1 and pnt2 fails! This is the major source of confusion.

In the main() method, pnt1 and pnt2 are nothing more than object references. When you pass pnt1 and pnt2 to the tricky() method, Java passes the references by value just like any other parameter. This means the references passed to the method are actually copies of the original references.

47
Q

What is memory leak?

A

A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesnt get garbage collected.

48
Q

How to find the size of an object?

A

The heap size of objects can be found using :

Runtime.totalMemory()-Runtime.freeMemory()
49
Q

What if I write static public void instead of public static void?

A

Program compiles and runs properly.

50
Q

What is the GregorianCalendar, ResourceBundle, Locale class?

A

The GregorianCalendar provides support for traditional Western calendars.

The ResourceBundle class is used to store locale-specific resources that can be loaded by a program to tailor the program’s appearance to the particular locale in which it is being run.

The Locale class is used to tailor a program output to the conventions of a particular geographic, political, or cultural region.

51
Q

What is the first argument of the String array in main method?

How can one prove that the array is not null but empty?

A

The String array is empty. It does not have any element.

This is unlike C/C++ where the first element by default is the program name. If we do not provide any arguments on the command line, then the String array of main method will be empty but not null.

Print array.length. It will print 0. That means it is empty.

But if it would have been null then it would have thrown a NullPointerException on attempting to print array.length.

52
Q

Can an application have multiple classes having main method?

A

Yes. While starting the application we mention the class name to be run. The JVM will look for the main method only in the class whose name you have mentioned. Hence there is not conflict amongst the multiple classes having main method.

53
Q

Can I have multiple main methods in the same class?

A

We can have multiple overloaded main methods but there can be only one main method with the following signature : public static void main(String[] args) {}

No the program fails to compile.

The compiler says that the main method is already defined in the class.