Java Flashcards
What is Java Development Kit & what does it include?
In order to start writing the code in Java, we need to install Java Dev. Kit
JDK includes:
- Compiler - will compile for Java a source code into java-byte code, which isn’t unique machine code & will be executed by Java Virtual Machine (JVM)
- Java Runtime Environment (JRE) contains JVM & core java libraries
- Tools for Java development (archiver, docs generator, etc.)
What is a method?
A method is a set of codes which is referred to by name & runs when it’s called. Each method has its own name. We need method to reuse the code: define the code once & use it many times
What is a main method?
Main method is a special method that actually runs the program. Everything in the main method will be executed when we run the program from top to bottom
What is a constructor?
It’s a special method to create an object
What’s a default constructor?
If we don’t define any constructors by ourselves java will provide one default (empty) constructor.
What is the difference between the constructor & the method?
- Constructor doesn’t have a return type & its name must be the same as a class name
- Java provides the default constructor if we don’t define it
- Constructor isn’t inherited by child class
- Method has a return & its name may or may not be the same as a class name
- Method isn’t provided buy Java
- Methods are inherited by child class
What is the difference between local & instance variables?
- Local variables are declared in methods, constructors, or blocks.
- Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.
- Access modifiers cannot be used for local variables.
- Local variables are visible only within the declared method, constructor, or block.
- Instance variables are declared in a class, but outside a method, constructor or any block.
- Instance variables hold values that must be referenced by more than one method, constructor or block
- Instance variables can be declared in class level before or after use.
- Access modifiers can be given for instance variables.
What are the OOP concepts in Java you know?
Object Oriented Programming. In Java, we have 4 concepts:
Encapsulation, Inheritance, Abstraction, Polymorphism.
What’s an encapsulation in java and how do we achieve it?
It’s data protection(hiding) mechanism from the client code. We make instance variables as private and we provide public getters and setters. use pojo class
What’s inheritance in java?
Can you give an example of using the inheritance in your project?
It is a process where one class can inherit visible properties and methods from another class. Parent-child relationship (super class - subclass relationship). Inheritance is used for not creating the object. Using extends keyword
What’s abstraction in java?
When we focus on what object does instead of how it does it by hidding implementation details. We achvieve abstraction by using abstract method.
What’s polymorphism in java?
Polymorphism is the ability of the object to take many different forms.
List list = new ArrayList<>();
list = newLinkedList<>();
What’s POJO?
Plain Old Java Object. Usually, encapsulated objects referred as POJO.
What’s super class?
It’s parent class in inheritance.
What’s the class which every class will inherit from? Why?
java.lang.Object. To give generic behaviors for every object. For example, equals, hashCode, toString.
How many classes we can extend at once?
Just one because java supports only single type inheritance.
*** Java doesn’t support multiple inheritance.
Why Java doesn’t support multiple inheritance?
Java doesn’t support multiple inheritance in classes because of “Diamond Problem”.
Due to this Java does not support multiple inheritance i.e., you cannot extend more than one other class
What’s the difference between method overriding and method overloading?
- Overloading is when we have multiple methods with the same name but different arguments
- Overriding is when we override the parent class or interface method in the child class.
- Most of the method signatures should be the same
- Child class access modifier should be the same or more visible
- Return type should be the same or covariant
- Child class cannot declare bigger exception than parent class
What does ‘this’ and ‘super’ keyword mean in java?
- ‘super’ is used to access the parent class properties and methods.
- ’ this’ is used to access current object properties and methods.
Access modifiers
- public - the member accessible from anywhere in the project
- protected - accessible within the same package & inside subclasses
- default - accessible within the same package only
- private - accessible within the same class only
Method Arguments
Arguments are used to provide the data to the method.
Methods can have multiple arguments with different types
What is variable?
Variable is a container that can hold piece of information. There are different type of variables for different data types in Java.
What kind of logical operators do you know? And how do they work?
Logical operators are used to check whether an expression is true or false. They are used in decision making.
&& (Logical AND) expression1 && expression2
true only if both expression1 and expression2 are true
|| (Logical OR) expression1 || expression2
true if either expression1 or expression2 is true
! (Logical NOT) !expression
true if expression is false and vice versa
What’s a static keyword in Java?
- Static variables and methods belong to the class, not to a specific object.
- We don’t need to create an object to call them, we use them by class name.
public FileHelper {
public static String path = “ABC”;
public static String readContent() {
…
return
What is final keyword in Java?
- final variable cannot be changed (reassinged)
- final class cannot be inherited
- final method cannot be overridden
How to prevent your method to be ever overridden?
- make it final
What is static block in Java?
Block of code that will be executed one time when this class is used
static {
. . .
. . .
}
What is initializer block?
Block of code that run before constructor
What is the relationship between parent class and child class?
Child class inherits visible variables and methods from the parent class
Can one class extend multiple classes at the same time in Java?
No, we cannot
Can one class implement multiple interfaces at the same time?
Yes, we can
What is difference between abstract class and interface?
- Interface can have only abstract methods (except static and default) and abstract class can have abstract and regular methods and properties
- We can extend one abstract class and implement multiple interfaces
- Abstract class can have abstract and non-abstract methods.
- Interface can have only abstract methods. Since Java 8, it can have default and static methods also.
- Abstract class doesn’t support multiple inheritance. - Interface supports multiple inheritance.
-Abstract class can have final, non-final, static and non-static variables.
- Interface has only static and final variables.
- Abstract class can provide the implementation of interface. - Interface can’t provide the implementation of abstract class.
- The abstract keyword is used to declare abstract class. - The interface keyword is used to declare interface.
- An abstract class can extend another Java class and implement multiple Java interfaces.
- An interface can extend another Java interface only.
- An abstract class can be extended using keyword “extends”.
- An interface can be implemented using keyword “implements”.
- A Java abstract class can have class members like private, protected, etc.
- Members of a Java interface are public by default.
Example: Example:
public abstract class Shape{ public interface rawable{
public abstract void draw(); void draw();
} }
An Interface in Java programming language is defined as an abstract type used to specify the behavior of a class. An interface in Java is a blueprint of a class. A Java interface contains static constants and abstract methods. The interface in Java is a mechanism to achieve abstraction
https://www.javatpoint.com/difference-between-abstract-class-and-interface
Can you give me an example of using abstraction in your project?
- I don’t use abstraction
or - I use abstract templates to locate elements in my framework and we implement them in my steps class
Can you give me an example of using polymorphism in your project?
WebDriver driver = new ChromeDriver();
WebDriver driver = new FirefoxDriver();
What is the helper class for array and collection (for sorting, and searching)?
Arrays is a helper class for arrays
Arrays.sort();
How to get number of elements in the array?
.length -> without parentheses
int[] nums = {1, 2, 3, 4, 5, 6};
System.out.println(nums.length);
What is collection framework in Java?
It is framework provided by Java to work with collection of data
List, Set, Queue, Map (it is not part of the framework)
How does ArrayList work internally?
ArrayList works internally with array
What is the initial capacity (size of internal array) of ArrayList?
10
What is Set in Java?
It is unique collection of data, doesn’t allow duplicates
The List is an ordered collection of objects and the List can contain duplicate values
SetTable synchronized doesn’t maintain insertion order
What is Map in Java?
Key value data collection and keys are unique in map put()
How do you iterate over the map?
We can iterate over the map by using keySet() method that returns all keys. Once we have keys we can easily find out values
What is the difference between HashMap and HashTable?
hashTable doesn’t allow null key and null value, synchronized, doesn’t maintain insertion order, thread-safe
HashMap allows one null key and multiple null values,
What is TreeMap? What is LinkedHashMap?
TreeMap - sorted by keys implementation of the map
LinkedHashMap - maintains insertion order
What is Queue data structure?
FIFO - First In, First Out data structure
What is the helper class for collection framework in Java (for sorting, searching)?
Collections is a helper class for collection framework
What is Stack data structure?
LIFO - Last In, First Out data structure
Could you explain about upcasting vs downcasting?
Person <- Student
// downcasting
Person obj = new Student();
Student student = (Student)obj;
Student.study();
// upcasting
Student obj2 = new Student();
Person person = obj2;
How to handle exceptions in Java?
By using try catch statement
try {
…
…
} catch (TypeOfException e) {
// handle it
}
When do you get NullPointerException?
When object is null and we try to use some of the property or method to this project
String str = null;
System.out.println(str); // NullPointerException
if (str == null) {
}
What is the difference between runtime and checked exceptions?
- we must handle checked exceptions but it is optional to handle runtime exceptions
- all checked exceptions extend from Exception class (except RuntimeException)
What does finally block do?
- it always runs (if there is exception or not) after try catch
- usually it is used to close resources
Can you catch multiple exceptions in the same try statement?
Yes, we can
try {
} catch (NullPointerException e) {
} catch (RuntimeException e1) {
}
What is Error? Do you handle or throw errors in your project?
Error is system level failure. Errors are thrown by Java Virtual Machine and they should not be handles in application level
final vs finally vs finalize()
- Final:
- final is a keyword, it is used to apply restrictions on class method and variable
- if a class is marked as final then this class can not be inherited by any other class
- finally:
- finally is a block that is used for exception handling along with try and catch blocks
- Finalize:
- finalize() method is protected method of java.lang.object class, it is inherited to every class you create in java & it is used to perform some clean-up operations on an object before it is removed from memory
What is a StringPool?
It is a memory for String objects in the heap. Java will reuse the same String values from StringPool to save memory.
String vs StringBuilder vs StringBuffer
STRING STRINGBUFFER STRINGBUILDER
Storage constant HEAP Heap
Area String pool
Modifiable no(immutable) YES(mutable) YES(mutable)
Thread Safe YES YES NO
Performance FAST VERY SLOW FAST
Immutable means values can not be changed once it’s created:
Most common Java Exceptions
NullPointerException.
ArrayIndexOutOfBoundsException.
IllegalStateException.
ClassCastException.
ArithmeticException.
IllegalArgumentException.
What are the wrapper classes in Java?
Object representations of the primitives in Java
byte -> Byte
short -> Short
int -> Integer
long -> Long
float -> Float
double -> Double
char -> Character
boolean -> Boolean
String str = “123”;
int num = Integer.parseInt(str);
When do you use while loop? And when do you use for loop?
We use while loop when we don’t know number of iterations in advance
We use for loop when we know number of iterations in advance
What is the difference between Array and ArrayList?
- Array is fixed size and ArrayList is resizable
- Array can work with primitives and Objects but ArrayList works only with Objects
What is Varags in Java?
- By using Varags we can create a method that can take dynamic number of arguments
- it works inside the method exactly as Array
- varag can be used in method argument only and only one varag per method
public int sum(int . . . nums) {
int sum = 0;
for (int num : nums) {
sum += num;
}
return sum;
}