java Flashcards

1
Q

what is void?

A

Used at method declaration and definition to specify that the method does not return any type, the method returns void

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

what is the ‘main’ function?

A

it is the entry point of the class

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

what is an access modifier

A

keywords for other classes and methods that shows they can use these methods

example:
public, private

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

what is a class

A

a container for related methods

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

what is byte code when talking about java programs

A

the platform independent code that gets turned into native code for the platform (Mac, windows, etc) that you are running by the java virtual machine (software component of java runtime environment, which you need to download on your system)

written as Name.class

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

what is the equivalent of comma in numbers in java. how would you write 123,456,789?

A

123_456_789

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

How do you write a type long?

A

add an L at the end.

example: 3_123_456_789L

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

How do you write a type float?

A

ad an F at the end

10.99F

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

does a char use single or double quotes

A

single

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

are strings mutable in java

A

no they are immutable

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

are arrays fixed length in java

A

yes

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

How does Java code run?

A

COMPILE TIME
JavaFile.java (java code)
- this is the file that contains our java code

compiler
- this converts the java code to byte code

JavaFile.class (byte code)

  • byte code is able to be read by the java virtual machine
----------
RUN TIME EXECUTION
class loader 
- loads the byte code into memory
- part of JVM that loads the  the byte code

byte code verifier

  • checks if everything is written correctly in the byte code
  • checks the loaded byte code is valid and does not violate any rules of security

interpreter
- reads the byte code and executes the program

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

What does capitalized data type represent in java

A

Capitalized data types are non-primitive

Lowercase data types are primitive types

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

What value represents a variable that is not initialized yet

A

null

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

Why won’t this compile?

int n = null;

A

primitive types cannot be initialized to null

a variable of a reference type can refer to a special null value that represents the fact that it is not initialized yet or doesn’t have a value.

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

What is does the keyword final do?

A

Such variables are known as constants. Java provides a special keyword called final to declare them. The only difference between a regular variable and a final variable is that we cannot modify the value of a final variable once assigned. Hence final variables must be used only for the values that we want to remain constant throughout the execution of the program.

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

How doo final variables work similar to const in javascript?

A

Yes

Important, that it is always possible to change the internal state of an object point by a final reference object, i.e. the constant is only the variable itself (the reference), not the object to which it refers.

final StringBuilder builder = new StringBuilder(); // ""
builder.append("Hello!"); // it works
System.out.println(builder.toString()); // Hello!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

You can you initialize a final variable without a value. But what must you do to prevent the compiler from throwing an error?

A

You have to set a value to the final variable before you use it.

final boolean FALSE;
System.out.println(FALSE); // error line

final boolean FALSE; // not initialized
FALSE = false; // initialized
System.out.println(FALSE); // no errors here

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

Why use getters and setters?

A

To prevent unwanted actions on our classes

example:
dog.height = 0;
// we never want dog height to be 0
// so we create a setter that prevents this from happening
public void setHeight(int h) {
if(h > 0) {
height = h;
}
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

What is encapsulation?

A

refers to the bundling of data with the methods that operate on that data, or the restricting of direct access to some of an object’s components.[1] Encapsulation is used to hide the values or state of a structured data object inside a class, preventing unauthorized parties’ direct access to them. Publicly accessible methods are generally provided in the class (so-called “getters” and “setters”) to access the values, and other client classes call these methods to retrieve and modify the values within the object.

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

What are the default values of Number primitives, booleans, and objects

A

0, false, null

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

What is the difference between .equals and ==

A

Use == to compare two primitives, or to see if two references refer to the same object.

Use the equals() method to see if two different objects are equal.

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

True or false?

int a = 3;
byte b = 3;
a == b

A

true

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

How do you declare an array?Instantiate and initalize? Most general way to Instantiate and initalize an array?

A

To declare an array we must use two special characters [] after the name of the type of elements in the array:

int[] array; // declaration’s form 1

or after the name of an array variable:

int array[]; // declaration’s form 2: less used in practice

The most general way to create an array is to use the special keyword new and specify the necessary number of elements:

int n = …; // n is a length of an array
int[] numbers = new int[n];

int[] numbers = { 1, 2, 3, 4 }; // instantiating and initializing an array of 1, 2, 3, 4

It’s possible to separate declaration and instantiation in two lines:

int[] numbers; // declaration
numbers = new int[n]; // instantiation and initialization with default values
Also, we can write the keyword new and enumerate all elements of an array:

float[] floatNumbers; // declaration
floatNumbers = new float[] { 1.02f, 0.03f, 4f }; // instantiation and initialization

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

What happens if you try to access a non-existing element by an index in an array?

A

If we try to access a non-existing element by an index then a runtime exception happens.

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

How do you convert an array to a string?

A

Arrays.toString(array)

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

How do you fill an array with values?

A

java.util.Arrays.fill() method is in java.util.Arrays class. This method assigns the specified data type value to each element of the specified range of the specified array.

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

What does StringBuilder do?

A

used to create mutable string objects

An object of this class is similar to a regular string, except that it can be modified.

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

What is the difference between length and capacity on the StringBuilder class?

A

The length returns the actual number of characters when capacity returns the amount of storage available for newly inserted characters, beyond which an allocation will occur. The capacity is a part of the internal representation of StringBuilder and its value will dynamically change.

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

When we need a lot of concatenations what will work faster StringBuilder or a String?

A

StringBuilder

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

Use 2 different methods to create a two dimensional array of integers

A
// two-dim array - the array of arrays
int[][] twoDimArray = {
        {1, 2, 3, 1}, // first array of int
        {3, 4, 1, 2}, // second array of int
        {4, 4, 1, 0}  // third array of int
};
// another way
int[][][] twoDimArray = new int[3][4];
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
32
Q

How do you look over a 2 dimensional array in a 3 dimensional array called cubic using a for each loop?

A
// For each loop
for (int[][] dim2Array : cubic) {
    for (int[] vector : dim2Array) {
        System.out.println(Arrays.toString(vector));
    }
    System.out.println();
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
33
Q

How would you write a isAnagram method?

A

static boolean isAnagram(String a, String b) {
if(a.length() != b.length()) return false;
int c[] = new int[26], d[] = new int[26] ;
a = a.toUpperCase();
b = b.toUpperCase();
for(int i=0; i

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

What is an exception?

A

errors detected during the program execution (at runtime)

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

Implement depth first search

A

bfs(root) {
let result = [];
let queue = [];

queue.push(root);

  while(queue.length) {
    let curr = queue.shift();
    result.push(curr.value)
    if (curr.left) {
      queue.push(curr.left)
    }
    if (curr.right) {
      queue.push(curr.right)
    }
  }

return result;
}

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

What is an interface?

A

A special kind of a class that can’t be instantiated. Often (but not always) it contains only abstract methods that you can implement in the subclasses.

An interface can’t contain fields (only constants), constructors and non-public abstract methods.

An interface can contain:

  • public constants;
  • abstract methods without an implementation (the keyword abstract is not required here);
  • default methods with implementation since Java 8 (the keyword default is required);
  • static methods with implementation (the keyword static is required).
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
37
Q

Declare an interface with a constant, an instance method, a static method, and a default method

A

Let’s take a closer look at this interface. The variable INT_CONSTANT is not a field here, it’s a static final constant. Two methods instanceMethod1() and instanceMethod2() are abstract methods. The staticMethod() is just a regular static method. The default method defaultMethod() has an implementation but it can be overridden in subclasses.

interface Interface {

int INT_CONSTANT = 0; // it's a constant, the same as public static final INT_FIELD = 0

void instanceMethod1();

void instanceMethod2();

static void staticMethod() {
    System.out.println("Interface: static method");
}

default void defaultMethod() {
    System.out.println("Interface: default method. It can be overridden");
} }
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
38
Q

What are marker or tagged interfaces?

A

An interface can have no members at all.

public interface Serializable{
}

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

How would you implement an interface with 2 instance methods? Each instance method should print out it’s method name.

Interface to implement:
interface Interface {

int INT_CONSTANT = 0; // it's a constant, the same as public static final INT_FIELD = 0

void instanceMethod1();

void instanceMethod2();

static void staticMethod() {
    System.out.println("Interface: static method");
}

default void defaultMethod() {
    System.out.println("Interface: default method. It can be overridden");
} }
A

class Class implements Interface {

@Override
public void instanceMethod1() {
    System.out.println("Class: instance method1");
}
    @Override
    public void instanceMethod2() {
        System.out.println("Class: instance method2");
    }
}

Interface instance = new Class();

instance. instanceMethod1(); // it prints “Class: instance method1”
instance. instanceMethod2(); // it prints “Class: instance method2”
instance. defaultMethod(); // it prints “Interface: default method. It can be overridden”

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

What is multiple inheritance when dealing with interfaces?

A

A class can implement multiple interfaces:

interface A { }

interface B { }

interface C { }

class D implements A, B, C { }
An interface can extend one or more other interfaces using the keyword extends:

interface A { }

interface B { }

interface C { }

interface E extends A, B, C { }
A class can also extend another class and implement multiple interfaces:

class A { }

interface B { }

interface C { }

class D extends A implements B, C { }
All the examples above do not pose any problems.

Multiple inheritance of interfaces is often used in the Java standard class library. The class String, for example, implements three interfaces at once:

public final class String 
    implements java.io.Serializable, Comparable, CharSequence {
// ...
}
41
Q

Why use interfaces?

A

interfaces help to abstract from specific classes and emphasize the common functionality. It makes software design more usable and clear.

interface Pencil {
    void draw(Curve curve);
}

GraphitePencil is an ordinary graphite pencil:

class GraphitePencil implements Pencil {
    ...
    void draw(Curve curve) {...}
}
ColoredPencil is the class that is intended for any colored pencil:
class ColoredPencil implements Pencil {
    ...
    void draw(Curve curve) {...}
}
StilusPencil is a pencil for electronic devices:
class StilusPencil implements Pencil {
    ...
    void draw(Curve curve) {...}
}
42
Q

What are annotations and what are 3 ways annotations are used?

A

They are a kind of metadata that provide information about a program. They can mark classes, methods, fields, variables, and other elements of a program.

Annotations can be used for different purposes:

to provide information for the compiler;
to provide information for development tools to generate code, XML files and so forth;
to provide information for frameworks and libraries at runtime.

43
Q

What does the @Deprecated annotation signify?

A

Indicates that the marked element (class, method, field and so on) is deprecated and should no longer be used. This annotation causes a compile warning if the element is used.

44
Q

What is polymorphism? What are the 2 main types of polymorphism in java?

A

means that something (an object or another entity) has many forms

-static (compile-time) and dynamic (run-time) polymorphism. The first one is achieved by method overloading, the second one is based on inheritance and method overriding.

45
Q

What is method overriding?

A

when a subclass redefines a method of the superclass with the same name.

Overriding is done so that a child class can give its own implementation to a method which is already provided by the parent class

46
Q

What is method overloading?

A

Means there are several methods present in a class having the same name but different types/order/number of parameters

47
Q

What is the standard input?

A

It is a stream of data going into a program.

Simple way of reading data going into java program.

Actually, not all programs need to use the standard input. But we will often use it here to help you master your programming skills! The typical way to solve programming problems is the following:

Read data from the standard input (System.in);
Process data to obtain a result;
Output the result to the standard output (System.out).

48
Q

input stream

A

reads data from a source

49
Q

output stream

A

writes data to a specified destination

50
Q

byte streams

A

used to read and write data in bytes

51
Q

char streams

A

used to read and write data in characters according to the 16-bit Unicode format

52
Q

What type of stream between byte and char is easier to work with?

A

Char streams make processing text data much easier for programmers. In comparison with them, byte streams are quite low-level but can work with data of any type including multimedia.

53
Q

buffer stream

A

Some streams use a temporary memory location. At first, such streams read or write data to a temporary location and then data is moved on to a source or destination from it. This temporary location is typically a byte or character array called buffer, and the whole process is called buffering

54
Q

Why would you use a buffer?

A

The reason why an intermediate memory location is introduced is that appealing to some sources or destinations takes substantial time interval. So buffering is a kind of optimization that minimizes the number of interactions with them.

55
Q

why do we use streams?

A

Streams allow Java applications to send/receive data from different sources

56
Q

when would you use an abstract class?

A

Sometimes you have a set of fields and methods that you need to reuse in all classes within a hierarchy. It is possible to put all the common members to a special base class and then declare subclasses which can access these members. At the same time, you do not need to create objects of the base class.

57
Q

What is the builder pattern?

A

a creational design pattern used to separate complex object construction from its representation. It can be used to create objects with a specified structure step-by-step. The main benefit is that you can avoid the so-called constructor pollution.

58
Q

What are the 4 components of the builder pattern?

A

Builder interface describes the steps of product construction. Each complex object requires the service of a Builder class to generate object instances.

ConcreteBuilder implements Builder to make the required representation of the product. It will construct and assemble the parts of the final product and provide the interface to retrieve it. This is the main component that keeps track of the specific representation of the product.

Director manages the object creation process using the Builder class, and it will not directly create and assemble the final complex object.

Product is the complex object constructed using the concrete builder class which contains the final user-requested representation.

59
Q

How do you create a generic object?

A

It is important, that a type argument must be a reference type. It is impossible to use a primitive type like int or double as a type argument.

GenericType obj1 = new GenericType(10);

GenericType obj2 = new GenericType(“abc”);

Since Java 7, it has been possible to replace the type arguments required to invoke the constructor of a generic class with an empty set of type arguments, as long as the compiler can infer the type arguments from the context.

GenericType obj1 = new GenericType<>(10);

GenericType obj2 = new GenericType<>(“abc”);

60
Q

When dealing with generics what is the pair of angle brackets <> is informally called?

A

diamond operator.

61
Q

What is a benefit of using generics?

A

generics allow you to use the same class and methods for processing different types.

They enable types to be parameters when defining classes (or interfaces) and methods. Parameterized types make it possible to re-use the same code while processing different concrete types.

62
Q

What are wrapper classes?

A

Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects.

63
Q

What are 3 different situations when you would use wrapper classes?

A
  1. when a variable can be null (absence of a value);
  2. when you need to store values in generic collections;
  3. when you want to use special methods of these classes.
64
Q

What is boxing and unboxing?

A

Boxing is the conversion of primitive types to objects of corresponding wrapper classes. Unboxing is the reverse process. The following code illustrates both processes:

int primitive = 100;
Integer reference = Integer.valueOf(primitive); // boxing
int anotherPrimitive = reference.intValue(); // unboxing

Autoboxing and auto-unboxing are automatic conversions performed by the Java compiler.

double primitiveDouble = 10.8;
Double wrapperDouble = primitiveDouble; // autoboxing
double anotherPrimitiveDouble = wrapperDouble; // auto-unboxing
You can mix both automatic and manual boxing/unboxing processes in your programs.

Autoboxing works only when the left and the right parts of an assignment have the same type. In other cases, you will get a compilation error.
Long n1 = 10L; // OK, assigning long to Long
Integer n2 = 10; // OK, assigning int to Integer

Long n3 = 10; // WRONG, assigning int to Long
Integer n4 = 10L; // WRONG assigning long to Integer

65
Q

What is faster to process, primitive types or wrapper objects;

A

primitive types

66
Q

Can wrapper classes and primitive types be used in standard collections?

A

primitive types cannot be used in standard collections (like lists, sets, or others), but wrappers can.

when you need to store values in generic collections, use wrapper classes

67
Q

What is the result of the following code execution?

Long longReference = null;
long longValue = longReference;

A

NullPointerException

If the wrapper object is null, the unpacking throws NullPointerException.

68
Q

How do you handle a NullPointerException when boxing and unboxing?

A

To fix it, we can add a conditional statement that produces a default value:

long unboxed = val != null ? val : 0; // No NPE here
This code does not throw an exception.

Another example is arithmetic operations on Integer, Long, Double and other numeric wrapper types. They may cause an NPE since there is auto-unboxing involved.

Integer n1 = 50;
Integer n2 = null;
Integer result = n1 / n2; // It throws NPE

69
Q

How do you declare a class field as an Object type?

A

private Object val;

70
Q

What is the purpose of declaring a class field as Object type?

A

Now we can create an instance of this type string by passing in a value. works for other value types as well. example: Integer and Character

NonGenericClass instance2 = new NonGenericClass(“abc”);

71
Q
If there is a generic class with an object type instance and a get method that returns that object, how to we invoke the get method so there is not a runtime error?
class NonGenericClass {
private Object val;
    public NonGenericClass(Object val) {
        this.val = val;
    }
public Object get() {
    return val;
} }
A

you must performa a type cast

After an invocation of the method get() we obtain an Object, not a String or an Integer. We cannot get a string directly from the method.

NonGenericClass instance2 = new NonGenericClass("abc");
String str = instance2.get(); // Compile-time error: Incompatible types
To get the string back, we should perform an explicit type-casting to the String class.

String str = (String) instance2.get(); // “abc”
Of course, it works, but what if the instance does not store a string at all? Since it is declared as an Object, the field value can keep any type. If this is the case, the code throws an exception.

72
Q

What is the advantage of using generics over Object types?

A

Both generics and Object allows you to write a generalized code. Using Object , however, may need explicit type-casting that is error-prone. Generics provide type-safety by shifting more type checking responsibilities to the Java compiler.

73
Q

Consider the following generic class:

class MyClass {

private T t;
    public MyClass(T t) {
        this.t = t;
    }
    public T get() {
        return t;
    }
}
What will happen if you create an instance, but don't specify type argument?

MyClass instance = new MyClass(“Hello!”);

A

The field t of the created instance will store a value of Object

74
Q

What is the parent of all standard classes and your custom classes by default.

A

Object

75
Q

When you declare a class, what class is does your newly declared class implicitly extended?

A

Object

76
Q

The Object class provides some common methods to all subclasses. How Many and what are they?

A

It has nine instance methods (excluding overloaded methods) which can be divided into four groups:

threads synchronization: wait, notify, notifyAll;
object identity: hashCode, equals;
object management: finalize, clone, getClass;
human-readable representation: toString;
This way of grouping methods isn’t supposed to be perfect, but it can help you remember them. Here’s a more detailed explanation of the methods:

  • The first group of methods (wait, notify, notifyAll) are for working in multithreaded applications.
  • The method hashCode returns a hash code value for the object.
  • The method equals indicates whether some other object is “equal to” this particular one.
  • The method finalize is called by the garbage collector (GC) on an object when the GC wants to clean it up. (Note: this method has been deprecated as of JDK 9).
  • The method clone creates and returns a copy of the object.
  • The method getClass returns an instance of Class, which has information about the runtime class.
  • The method toString returns a string representation of the object.
77
Q

What is Spring Boot

A

a framework that simplifies the configuration of Spring applications

78
Q

What does the build.gradle file do?

A

describes how to build and manage the dependencies of the project when using gradle as a dependency manager

79
Q

What are member variables?

A

variables defined outside of any methods but inside the class and are used in different methods

80
Q

Generic static methods are methods that …

A

introduce their own type parameters

81
Q

Can we use the class’s type parameters inside a generic method?

A

Yes, if this method is not static

82
Q

How do we declare a method that contains some logic and uses the type parameters that is passed to it as arguments, but does not return anything?

A

public void method(T t) { }

83
Q

There is a naming convention that restricts type parameter name choices to single uppercase letters. Without this, it would be difficult to tell the difference between a type variable and an ordinary class name.

What are the most commonly used type parameter names?

A
T – Type
S, U, V etc. – 2nd, 3rd, 4th types
E – Element (used extensively by different collections)
K – Key
V – Value
N – Number
84
Q

Given the following example

class Storage {
    private T nameOfElements;
    //other methods
}
Let us create three classes:
public class Books { }
public class Brochures extends Books { }
public class Computers { }

which of these classes will not compile?

A

Storage storage1 = new Storage<>(); //no problem
Storage storage2 = new Storage<>(); //no problem
Storage storage3 = new Storage<>(); //a compile-time error

Two first lines will compile without problems unlike the third one: there we will get the Type parameter ‘Computers’ is not within its bound; should extend ‘Books’ error

85
Q

What class under the hood is implicitly type bound in generic types?

A

object

86
Q

What are bounded type parameters?

A

They restrict the kinds of types that are allowed to be passed to a type parameter.

87
Q

functional interface

A

The functional interface is another way to model functions using object-oriented programming instead of methods.

It is an interface (not a class or enum) with a single abstract method (SAM type). Static and default methods are allowed here.

88
Q

What are packages?

A

provide a mechanism for grouping classes together in the same module (package). A package can contain other packages, and the whole structure resembles directories in a file system

89
Q

What dos a controller do?

A

Handles API requests

90
Q

What does the RestController annotation do?

A

It declares that a class will provide the exact endpoints (URLs you request for) to access the REST methods.

91
Q

What does IoC stand for? And what does IOC mean?

A

Inversion of Control

an object gives the control of its fields’ lifecycles to a container or inverses it.

92
Q

What are beans?

A

A commonly used object used through out the application

Beans are objects of any class that Spring Boot creates on a startup and provides to any other bean’s constructor.

93
Q

What annotation on a class’s method or constructor do you use to show that this bean needs other beans.?

A

Autowired

94
Q

What annotation do you use to show that a class creates a host bean?

A

Component

95
Q

Inversion of control means that the … takes control over beans lifecycle instead of a hosting object

A

container

96
Q

What are collections?

A

set of containers for grouping elements into a single unit.

97
Q

Can collections store primitive values (int, long, char, double and so on)?

A

No

You should use one of the wrapper classes (Integer, Long, Character, Double or another one) instead.

98
Q

What is an ArrayList

A

a resizable array of objects of a specified type