Java Flashcards

1
Q

What is Java? / Explain some features of Java

A

Java is an OOP language that supports different programming paradigms such as functional programming(using only functions to complete tasks). It’s is a portable and independent platform due to the JVM.

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

What is JRE / JDK / JVM?

A

JDK(Java Development Kit)
Provides an environment to develop and execute a Java Program
Contains the compiler, tools for development
Contains the JRE and JVM
JRE(Java Runtime Environment)
All that’s needed to RUN an application
Contains the JVM
Contains the core libraries for Java
JVM(Java Virtual Machine)
Takes the COMPILED code (bytecode) and executes it from the main method

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

What is the difference between an object and a class?

A

A Class is a blueprint for an object that define variables and methods. Where as Objects are representations of real life objects that can be interacted with in Java.

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

What is the root class from which every class extends?

A

Object class, it contains the toString(), hashcode(), and .equals()

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

What are the primitive data types in Java?

A
Primitives - are stored in the stack:
Int
Long
Double
Short
Byte
Boolean
Char
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Where are Strings stored?

A

Strings in Java are arrays of characters that are immutable. Strings are stored in the string pool within the heap that allow you to reuse the same String object for repeated instances. You can make it so a string isn’t in the string pool by declaring a string using the new keyword.

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

Explain stack vs heap

A

Stack:

  • Data Structure that follows a LIFO pattern (Last In First Out) which is naturally managed
  • Holds primitives and reference variables
  • Once the scope of the method is over, the variable “pop” off

Heap:

  • Object storage
  • String Pool for string literals
  • Managed by the Garbage collector
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Are variable references stored on the stack or heap? What about the objects they refer to?

A

Reference variables are stored on the stack but the objects they refer to reside in the heap

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

What are annotations?

A

A form metadata that can be added to Java code that provide additional information about the program

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

Why are strings immutable in java? How would you make your own objects immutable?

A
Strings are immutabile in Java because caching, security, easy reuse without replication. 
You can make objects immutable by Declaring class final, Make fields private, or not use setters/getters.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the difference between String, StringBuilder, and StringBuffer?

A

String:

  • arrays of characters that are stored in the string pool within the heap
  • immutable: the value of strings cannot be changed

StringBuffer:

  • Mutable, alternatives that allow for manipulation
  • Thread safe, slower

StringBuilder:

  • Mutable, alternatives that allow for manipulation
  • Not thread safe, faster
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are the different variable scopes in Java?

A

Variable scope refers to the lifetime of a variable some types of variable scopes are:

  • Class Level
  • Method Level
  • Block Level
  • Instance Level - lifetime of an obj
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

What are the access modifiers in Java? Explain them.

A

public - least restrictive, all of the classes within the application have access

protected - all of the classes within the same package and all of the
subclasses/children have access

default - all of the classes within the same package have access, absence of an access modifier

private - only the class itself has access

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

What are the non-access modifiers in Java?

A
abstract
- that cannot be used to create objects (to access it, it must be inherited from another class
static
- static members do not require an instance and are initialized when the class is loaded into memory

default
- allows to provide a default implementation to an interface

final

  • prevents the class from being extended, cannot be inherited
  • for variables cannot be Reassigned once initialized
  • for methods cannot be overridden by a child class
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What is the difference between static and final variables?

A

Static is used to define a class member that can be used independently of any object of the class

Final is used to declare a constant variable or method that cannot be overridden

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

What are the default values for all data types in Java?

A
Boolean - false
Char  - \u0000
byte - 0
short - 0 
Int - 0
long - 0L
float - 0.0f
double - 0,0d
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What makes a class immutable?

A
Do not write setter functions
Include all-argument constructor
Make a class final
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What data types are supported in switch statements?

A
Data types supported:
Byte
Short
Char
Int
String
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to pass multiple values with a single parameter into a method?

A

Creating an array with multiple values and pass that into your method

Var args: allows methods to support an arbitrary number of parameters of one type (must be at the end of the argument list)

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

What methods are available in the Object class?

A

toString(): Returns the string representation of this object

equals(): Compares the given object to this object

hashcode(): Returns the hashcode number for this object

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

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

A

“==” checks if both objects point to the same memory location whereas .equals() evaluates to the comparison of values in the objects

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

What is an enhanced for loop?

A

a simpler way to iterate through all the elements of a Collection

for (int i = 0; i < myArray.length; i++) {

to:

for (int myValue : myArray)

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

What are the 3 usages of the “super” keyword?

A

super keyword in java is used to refer parent class objects

  1. Use of super with variables:
  2. Use of super with methods: This is used when we want to call parent class method
  3. Use of super with constructors: super keyword can also be used to access the parent class constructor.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is the first line of any constructor?

A

The first line in any constructor is a call to the parent’s constructor: super();

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

How would you perform constructor chaining?

A

Can be done using the this(). To chain constructors you utilize the same signature or argument structure as the methods you are trying to chain.

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

What happens if you don’t define a constructor for a class? Can you still instantiate it?

A

the compiler creates a default constructor(with no arguments) for the class and yes you can instantiate it.

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

What are the four pillars of OOP

A

Abstraction
Encapsulation
Inheritance
Polymorphism

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

What is Abstraction

A

Abstraction

Process of only showing the essential/necessary features of an entity/object to the outside world and hiding irrelevant information. And having users use an interface to interact with your program.

Let’s say you have an abstract class called Animal and inside of it you have an abstract method called animal sound. Since you cannot create a new object of the Animal class, you can extend those methods to a child class dog. Then fill in that abstract animal sound method with what a dog says: bark.

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

Encapsulation

A

The ability for an object to protect its states and behavior

- can achieve by defining the accessibility of class members using access modifiers
set variables to private, only the class itself has access 
- setters/getters methods to interact with the property

Ex:
If you have a Private String called name, you can make a getter function called public String getName() returning name and a setter function called public void setName(having one argument newName){} and the function will use the this keyword .name = newName; that way you can acquire what name is and set the value to something different.

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

Inheritance

A

when subclasses classes adopt the states/behaviors from its parent class, using the extends keyword
deriving classes allows for code reusability or the DRY concept

this/ super
this(used for constructor chaining) is a reference to the instance
super is a reference to the parent

Ex: if you have a class vehicle and it contains a string variable containing the brand of a car, for example ford. Then you can utilize inheritance via the extend keyword in the car class that contains a string variable model name

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

Polymorphism- “many forms”

A

the ability of objects and methods to adapt their behaviors in different contexts. This can be done with method overloading/ overriding and upcasting/ downcasting.

Ex:
Let’s say you have two separate employee objs. Which have the same id and name. If we were to compare each of these objs using the .equals method currently it would return false. This is where the concept of polymorphism comes in, we need to override the .equals method if we want to check the objects based on the properties bc currently only the references to the same object will return true. After overriding the method it would return true.

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

What is the difference between an abstract class and an interface?

A

Abstract class:
Allows you to create functionality that sub-classes can implement or override.

Interface:
Only allows you to define functionality, not implement it.

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

Can abstract classes have concrete methods? Can concrete (non-abstract) classes have abstract methods?

A

Concrete classes cannot have abstract methods

Abstract class can have no abstract methods

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

Can static methods access instance variables? Can non-static methods access static variables?

A

Static methods can’t access instance methods and instance variables directly

non-static methods can access any static method and static variable

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

What are the implicit modifiers for interface variables? Methods?

A

Variables have to be public static and final

Methods are implicitly abstract, default, and static

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

What is the difference between method overloading and overriding? What are the rules for changing the method signature of overloaded methods?

A

method overloading is creating multiple methods in the same class with the same method name but different number and/or types of parameters.

  • Have different return types.
  • Have different access modifiers.
  • Throw different checked or unchecked exceptions.

While method overriding is writing a method in a subclass with the same method signature as the parent class but different implementation

ie: the .equals() method It needs to be overridden if we want to check the objects based on the property.

37
Q

What are covariant return types? What rules apply to return types for overridden methods?

A

covariant return types are returns types of overrided methods

the new return type has to be a child/sub-type of the original type

38
Q

When do you use extends or implements keywords?

A

You use the extends keyword when you want another class to inherit all the classes and methods of the parent class. While the Implements keyword is used to designate an interface being used.

classes IMPLEMENT interfaces; Classes EXTEND other classes

39
Q

Exceptions

A

Is a condition that prevents a method from completing successfully, which inherits the Throwable class

Divided into checked(chked by the compiler)/ unchecked(runtime/not accnted by the compiler) exceptions

40
Q

What is the difference between final, .finalize(), and finally?

A

Final: is the access modifier
Finally: is the block in exception handling
Finalize: is the method of the object class
used to close resources

41
Q

Explain throw vs throws vs Throwable

A

Throw: is a keyword to throw an exception manually. Also known as”pass the buck”

Throws: is used in the method signature to indicate that the method can throw such exceptions if triggered.

Throwable: is a super class for all types of errors and exceptions

42
Q

Do you need a catch block? Can you have more than 1? Is there an order to follow?

A

No you dont always need a catch block
Can be followed by one or more try/catch blocks.
Each must contain a different exception handler.
Order from most to least specific other most generic exception will catch all

43
Q

What is base class of all exceptions? What interface do they all implement?

A
All exception and error types are subclasses of the Throwable class
They all implement the Serializable interface
44
Q

What is base class of all exceptions? What interface do they all implement?

A
All exception and error types are subclasses of the Throwable class
They all implement the Serializable interface(exceptions)
45
Q

List some checked and unchecked exceptions?

A

Checked:

  • IOException
  • SQLException
  • ClassNotFoundException
Unchecked:
- ArithmeticException
- ClassCastException
- NullPointerException
I- llegalArgumentsException
46
Q

Multi-catch block - can you catch more than one exception in a single catch block?

A

After Java SE7, a catch block supports multiple exceptions for code readability.

47
Q

What is JUnit?

A

What is JUnit?

  • JUnit is a Java Unit testing(refers to testing an individual unit of functionality) framework(JUnit5)
  • It includes a lot of annotations and classes in order to write automated unit tests
  • it leverages “assert” methods to check for a particular condition to determine if a test passes
48
Q

What is TDD?

A

TDD or Test driven development: the process of writing your tests to fail first to establish the functionality of your application, THEN writing the code to pass your tests

49
Q

What are the annotations in JUnit? Order of execution?

A
Annotations: enforce tests to run in a specific order.
@BeforeAll
@BeforeEach
@AfterAll
@AfterEach
@Test
@Ignore
@Order
50
Q

Give an example of a test case

A
@Test
    public void addOneAndTwo() {
        double expected = 3;
        double actual = calc.add(1, 2);
        assertEquals(expected, actual, "Adding one and two should be 3");
    }
51
Q

How would you prevent a test from being run without commenting it out?

A

The @Ignore annotation

52
Q

How would you test that a specific exception is thrown?

A

You would create a class with the specific exception that extends the RuntimeException superclass and use the assertThrows method to throw that exception.

53
Q

What is Maven?

A

Project management tool and build automation tool that handles dependencies for developers and allows for easily shared project configurations across teams:

54
Q

What is the default Maven build lifecycle?

A

3 build lifecycles
clean - removes/clean previous artifacts (.jar, .war)
default - test/package your application
site - documentation

55
Q

Where / when does Maven retrieve dependencies from? Where are they stored locally?

A

Maven retrieves dependencies from the maven repository and utilizes them only when working on projects. They are stored stored locally in the user’s home directory in the .m2 folder

56
Q

What is the POM and what is the pom.xml?

A

POM is Project Object Model which utilizes the pom.xml files to:

metadata about the project configuration, dependencies, build details

allows for easy shared project configuration across teams

57
Q

What defines Maven project coordinates?

A

groupId
artifactId
version

58
Q

What is version control?

A

Version control is the practice of tracking and managing changes to software code.

Specifically to git, it facilitates the construction of different versions of an application and ensures the quality of your software is maintained as features evolve over time

59
Q

What is the difference between git and GitHub?

A

Git is a SCM(Software Configuration Management), Git is a version control system that lets you manage and keep track of your source code history

Github is a cloud-based hosting service that lets you manage Git repositories. Where you store your code remotely, whereas git is just a tool

60
Q

List the git commands you know and what they do

A
Cd: change directory
ls(list all items) -a flag to show hidden items
git clone
git init
git add
git restore
git status
git commit -m
git branch
git checkout
61
Q

How would you prevent a file from being tracked by git?

A

Must be added to the .gitignore file

62
Q

What is a branch? What are some common branching strategies?

A

A branch is an independent line of development

Its main advantage the ability to separate when working on new features or bug fixes because it isolates your work from others

63
Q

What is a merge conflict? How do you prevent these and resolve them if it happens?

A

A merge conflict is when your current branch and the branch you want to merge into are in conflict with one another. You can resolve a merge conflict by pulling from the most recent source from the main repo, switching back into your branch, adding/editing your code to fix the conflict, then re-committing and pushing it back to the repo.

Prevent Merge Conflicts:
Best practices
    - commit regularly
    - provide detailed commit messages
    - communicate with your team
64
Q

What is a GitHub pull request?

A

Pull requests let you tell others about changes you’ve pushed to a branch in a repository on GitHub

65
Q

What is the git workflow for editing code and saving changes?

A

Git Workflow

- create/retrieve repository
- add/remove changes to/from the staging area

    - git add [filename] (git add . => for everything in this directory)

- visualize the state of the repository
    - git status

- create a commit locally
    - git commit -m "insightful message about the commit"
- push commit to remote repository
    - git push
66
Q

What is a commit?

A

Commits are snapshots of your repository at specific times and tell a story of the history of your repository and how it came to be the way it is currently

67
Q

How would you go back in your commit history if you make a mistake?

A

Every commit is given and id and can be seen on github as well as pulled up in the git bash client using:
git checkout

68
Q

What is a Github issue?

A

Lets you track your work, errors, and things in progress in your repo. The issue’s timeline allows you to cross-reference between commits, pull requests, etc so that you can keep track

69
Q

Where are the root and home directories located? How to get to each?

A
  • The root directory is the highest level in a file system, denoted by a “/” slash
  • The home directory is sub-directory of root and is denoted by the “ ~ ” tilde
70
Q

What Linux command would you use to:

  1. Navigate your file hierarchy on the command line?
  2. List files? What about hidden files?
  3. Edit a file from the terminal
A
  1. The “cd” command
  2. ls to list files, ls with the -a flag to show hidden files as well
  3. to edit a file from the terminal, you would use the command for your chosen text editor, ie: “code” for vscode, or the native text editor “nano” and then the filename. Ex: nano readme.txt
71
Q

What are the advantages to using a logging library?

A

Logging consists in capturing and persisting information regarding the state of an application

making it available at a later time for analysis

72
Q

What is log4j?

A

Log4j is a Java logging framework that contains:

Loggers
responsible for recording log events and forwarding them to the appropriate appender
by default, a root logger is provided
class specific loggers are preferred

Appenders
responsible for delivering the log event to their destination target
formatting of the event is delegated to the layouts

Layouts
responsible for returning a byte array to be turned into a String using the appropriate layout

73
Q

What are the logging levels of log4j?

A
Trace
Debug
Info
Warning
Error
Fatal
74
Q

What is Javalin?

A

lightweight framework for Java (and Kotlin) to handle HTTP requests and responses

runs on an embedded web server (Jetty)

75
Q

What is Jetty? What is the relationship between Jetty and Javalin?

A

an open source Java web server, as well as a servlet container, that provides an application
with the features required to launch and run an application servlet or API

Javalin leverages Jetty to handle HTTP requests and responses

76
Q

What are Servlets and how are they related to Javalin?

A

A servlet is simply a class which responds to a particular type of network request - most commonly an HTTP request. Basically servlets are usually used to implement web applications - but there are also various frameworks like Javalin which operate on top of servlets

77
Q

What is Object Mapping(JSON Marshalling)? What is Jackson?

A

Object mapping is converting Java Objects in our case specifically to JSON (Mapping for data exchange)

Jackson: is an obj mapper leveraged by Javalin and it provides us with a way to convert Java to JSON and vice versa

78
Q

How does Javalin convert JSON data to Java objects? And the other way around?

A

Jackson - databind is leveraged by Javalin and it allows us to convert Java objects to JSON and vice versa

79
Q

How do you set up a Javalin application?

A

Javelin app = Javalin.create(lambda function)

app.start();

80
Q

What are HTTP Handlers in Javalin?

A

HTTP handlers are functional interfaces that takes the Context object as a parameter and is used to specify a behavior to handle a request at a particular endpoint

81
Q

What are different ways to set them up?

A

app. get

app. post

82
Q

What are Handler groups?

A

You can group your endpoints (making them easier to configure)by using the routes() and path() methods. routes() creates a temporary static instance of Javalin so you can skip the app. prefix before your handlers.

83
Q

What is the Context object? What is it an abstraction of?

A

The context obj provides you with everything you need to handle http-requests. It contains the underlying servlet-request and servlet-response, as well as getters and setters.

HTTP requests and responses

84
Q

How would you handle path params?

A

pathParam(“name”)

85
Q

How would you retrieve the request body

A

bodyAsClass(clazz)

body()

86
Q

How would you handle query params?

A

queryParam(“name”)

87
Q

How would you map an endpoint?

A

you can map and endpoint using the context object and the app.get or app.post methods.

app. verb (url path, ctx->
extract param from url
)

88
Q

How would you return information in the response body?

A

The method: body() // request body as string

89
Q

How would you set a status code for a response?

A

ctx.status(201); method