Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

Java Basics Interview Prep Questions with Answers, Exams of Computer Security

Java Basics Interview Prep Questions with Answers

Typology: Exams

2024/2025

Available from 11/22/2024

mariebless0
mariebless0 šŸ‡ŗšŸ‡ø

3.4

(5)

1.4K documents

1 / 25

Toggle sidebar

Related documents


Partial preview of the text

Download Java Basics Interview Prep Questions with Answers and more Exams Computer Security in PDF only on Docsity!

1 / 25

Java Basics Interview Prep Questions with Answers

  1. What is a variable?: A data container that can be named and assigned a data type. Each variable name is given a memory location that can be called within the variables scope.
  2. What is a variable's scope?: The segments in a program in which a variable can be used.
  3. What is a literal? Give examples.: A literal is a source code representation of a fixed value. They are represented directly in the code without any computation. int count = 0; A literal '0' represents the value zero.
  4. What are variable naming conventions? (Reference/Primitive types; Meth- ods; Enums; Imports): Reference and primitive types: use lower camel case for names with no spaces. Variables cannot have the same name unless you are reassigning the value of a previously declared variable. Method names: camelCase, can overload method names Enums use all caps snake case: LETTERS_LETTERS Imports: java.util.package
  5. What happens if you define a variable without assigning a value, and then use the variable?: You will have the ability to assign it later, but a value is necessary if the variable's value is being evaluated before the assignment. If you try to use it, then it will give you an error.
  6. What is a type?: A data type determines what kind of value an object or variable is allowed to hold. Example: an int holds a number with a limited length, and a String holds multiple character values such as words or number combinations.
  7. Distinguish between value types and reference types.: Value Type holds the data within its own memory allocation: Predefined datatypes, structures, enums Reference Type contains a pointer to another memory location that holds the real data: Objects, Classes, Arrays, Interfaces

2 / 25

  1. What is a primitive(or simple) type?: A primitive type is a data type that directly holds the data within that variable. Examples are int, Boolean, char, long.
  2. How many bits in a byte?: 8 bits
  3. How many bytes in char: 1 byte
  4. How many bytes in a short?: 2 bytes
  5. How many bytes in an int?: 4 bytes
  6. How many bytes in a long?: 8 bytes
  7. How many bytes in a boolean?: 1 byte
  8. How many bytes in a float?: 4 bytes
  9. How many bytes in a double?: 8 bytes
  10. How many bytes in a string?: 4 bytes
  11. How do ints and doubles differ?: A double takes twice the memory space to store data and accepts decimal values. Ints only use whole numbers.
  12. What is a static type system?: Static types expect variables values to be instantiated before the variables can be used.
  13. Is Big Decimal a value or reference type? How about LocalDate?: Big Deci- mal is a reference type. LocalDate is a temporal type.
  14. Which value type is safe for financial math?: BigDecimal is the safest for financial math because floats and doubles cannot represent every value in a very large value. Big Decimal takes up much more memory and is slower, but it also accurately represents every number in the calculation.
  15. Why include numeric types that don't work for financial math?: Int, long, double, and float are useful for quick calculations that don't require as much accu- racy.
  16. Conceptually, what is a String?: It is a sequence of characters. The program interprets them literally, and the index of the string is numbered.
  17. What is a character?: A primitive data type that represents a single letter or number
  18. Can I alter a String? How?: Strings are immutable, but you can alter it by reconstructing it and pulling out characters or ranges of characters.
  19. How do I concatenate Strings?: You concatenate strings by "string" + "string". This is appending one string to the end of the other string. (use add '+' operand)

3 / 25

  1. What is an expression?: a sequence of variables, literal values, and operators that produce a value.
  2. What is a statement: one or more lines of code that do NOT produce a value; it may trigger an action such as printing to a console or variable declaration.
  3. What is a code block? What syntax denotes a block?: A code block is a section of the program is a grouping of two or more statements and it is denoted by curly brackets.
  4. What goes inside of "if" statement's parentheses?: Boolean and conditional statements.

4 / 25

  1. What goes inside an else statement's parentheses?: Nothing, because this would be the only other alternative of the if statement. An if else statement would require an alternative to the if statement.
  2. Where is an else in an 'if statement' valid?: Beneath the if statement where the boolean returns false.
  3. How deep can ifs and elses be nested?: Forever potentially, but this would be poor practice, and it is better to limit the nesting because it complicates the program and slows everything down.
  4. Does a switch require a default case?: No, but it useful for catching any unforeseen values.
  5. Can we "fall through" (execute all cases after a match) a switch?: Yes, if you exclude the break keyword, all cases will initiate
  6. Can we switch on a String value?: Yes, you can use a string value for each case in a switch statement
  7. What can a while loop compute that a for loop can't?: While loops can continue until the condition of the loop is proven wrong, so the number of iterations is essentially unlimited. A for loop is useful when you know the limit of the number of loops being made. A while loop checks the condition before each iteration.
  8. The do/while loop seems unnecessary. Is it?: A do while loop is useful when you want to run the loop at least once. The while loop checks the condition before each iteration, and the do while loop check the condition after each iteration.
  9. What is an enhanced for loop? What can it operate on?: The enhanced for loop iterates over each element in a collection, it cannot decrement. A normal for loop can iterate forwards and backwards.
  10. How do I designate a method's inputs?: Setting the parameters for the method next to the method name. Calling the method with the defined data types included: E.g. method Name(String, int)
  11. How do I designate a method's outputs?: Return statement if the method is not void. If the method is void, it depends on the structure of the method and the connected classes.
  12. Where can a method call go in your source code? Can calls be nested?: -

5 / 25 Methods can be called anywhere as long as the class calling it has access to the

6 / 25 class holding the method. They can only be nested indirectly.

  1. How many things can a method return? (How many types?): Only one type
  2. How do I return several things from a method?: You can return multiple values if you return an array or a list.
  3. How many return statements are allowed in a method?: Infinite return state- ments as long as you have conditional statements.
  4. What is the ideal length for a method?: Try to keep it as concise as possible, but try to limit it so 25. (subjective)
  5. Can a method call itself?: Yes, this is called recursion.
  6. What is the difference between a static and non-static method?: A Static method is a class method which cannot be overridden and can only access other static methods without having to create an instance of that class. A non-static method belongs to an instance of a class and can access other non static methods and is compiled at run time.
  7. How do I indicate a method is non-static?: It lacks the keyword 'static'
  8. What is method overriding?: This happens when a subclass has the same method as a parent class and the subclass is creating a specific instance of that method.
  9. What is method overloading?: Overloading a method means defining the same method but with a different set of parameters (defining the same method but with a different method signature).
  10. What does an array represent?: A collection of values
  11. Is it a value type or reference type?: Reference type
  12. How do I know how many elements are in an array?: Array.size() You can instantiate the literal size of the array, which would be the limit to the number of things in the array, or you can loop through the array and count the size, or get the index -1.
  13. How do I know how many elements an array could hold?: The amount of elements an array can hold is specified when the array is declared
  14. How do I access an element in an array?: Array.getIndex(i); You can loop through the elements or you can directly retrieve a specific element in the array if you know its index

7 / 25

  1. If an array holds ten elements, what happens if I try to access the 12th element?: An error will occur because Java will be unable to read beyond the length of an array
  2. Array elements are value or reference types?: They can be either value or reference types
  3. True or false?: a class definition requires a code block.: False
  4. What is a constructor?: A call to an app class (like a method) that allows the use of parameters to set the values of the fields in the class.
  5. How can you tell something is a constructor? (Which syntax gives it away?): The call (method) has the same name as the class
  6. Does A class require a constructor?: A constructor is not needed to use a class. If a constructor is created for a class, an empty constructor is also required to call the class without parameters.
  7. Can a class contain multiple constructors?: Yes
  8. What problem does an interface solve that isn't solved by a class?: In- terfaces allow for polymorphism - allows the use of those same methods but the methods can be used by objects from different classes Classes: a single class will have methods exclusive to objects from that specific class
  9. What is the naming convention for classes?: Start with an uppercase letter for every individual word in the name
  10. What is the maximum number of methods a class should contain?: Howev- er many methods it takes to accurately represent and manipulate an object's fields
  11. What are getters and setters? What problem do they solve?: Getters retrieve an object's field values while setters will set their field's values. Getters and setters prevent direct access to a field which protects its value - the value will not change with a getter, and in order to change the value of the field, the developer must specify that is their intention with a setter.
  12. Are getters and setters different from other methods? If so, how?: No, getters and setters are blocks of code that return or change a value, just like other methods.
  13. Where can I assign a default value to a class variable when an object

8 / 25 is created?: With the use of a constructor or class declarations. Setting a parameter within a class constructor will set the field's values without individually setting each field.

9 / 25

  1. What is the relationship between a class and object?: A class defines an object while the object belongs to the class. A class defines the values an object will hold, the object instantiated will hold those defined values.
  2. Pillars of OOP?: Encapsulation Inheritance Polymorphis m Abstraction
  3. Encapsulation (OOP): the process of isolating your code to prevent sets of code with different purposes from unintentionally affecting each other.
  4. Inheritance (OOP): the reuse of code throughout the program to reduce com- plexity (extend/implements)
  5. Polymorphism (OOP): allowing methods to have different uses for different classes - it is a way to reuse code but permit different behavior
  6. Abstraction (OOP): the act of hiding the smaller details of your code from the broader scope of the program. This is done to reduce complexity.
  7. What is inheritance? How does it work?: Inheritance is the reuse of methods for a variety of different classes through an interface. These classes will import the interface's methods and will have to be individually defined
  8. How do I call a parent class's constructor from a child class?: Within the child's constructor, call the keyword 'super'
  9. Tell me about the keyword: this. What does it mean? What does it do?: 'this' refers to the fields in a class. It is called within the class itself and it allows the developer to make a change to the field 'this' refers to For example: this.lastName = lastName
  10. Is it possible to return "this" from a method?: Yes, for example you can call return this.hostCity and it will return the value of the field 'hostCity'
  11. What is the maximum number of classes you can extend (inherit)?: You can only extend one class
  12. What is the maximum number of interfaces you can implement?: Any number of classes can be implemented in an interface

10 / 25

  1. Can one class both extend a parent and implement an interface?: Yes, a class can extend a parent and implement an interface; Extend first then implement

11 / 25

  1. What is state? How does OOP manage it?: State refers to the variables that an object holds. OOP manages this through abstraction - these minor details are hidden away from the coding context
  2. What is a unit test? What is a unit?: Tests that are run to ensure that parts of an application functions. Units refer to these sections being tested.
  3. Talk a bit about JUnit. How does it work?: JUnit is an open-source testing library that allow for unit testing to function. This is implemented through dependen- cies in a project.
  4. What are the three A's (AAA) of unit testing? Give concrete examples.: - Arrange/Act/Assert Say you were testing a calculator method: Arrange - create the object (insert parameters if it requires them) Act - call the method and store the value in a variable Assert - assert an equality or a truth to compare an expected value with the actual value (stored value from act)
  5. How does a stateful unit test differ from a stateless test?: Stateful Unit Tests test methods that rely on the values of an object. The methods belong to a class which uses variables from its own class to make calculations. Stateless Unit Tests test methods that do not rely on any specified value. These methods can be defined outside of a class.
  6. What is a setup method? Why might you use it?: A set-up method provides the test with a 'known good state' which means the file or values being tested is set at each test to ensure they are all testing the same file/values
  7. What is a tear-down method? Why might you use it?: A tear-down method is executed after each test which deletes test data generated during the test execution. This deletion removes data that may otherwise affect the next test.
  8. True or false?: each unit test should contain one and only one assert.: - False.

12 / 25 Additional assertions can ensure you have the exact value you expect to output.

  1. Is it possible to run multiple scenarios per test method? How?: Yes You can make multiple scenarios by creating additional arrangements, each having a different set of parameters in their methods and making assertions to each scenario.

13 / 25

  1. What is a generic type?: A class type that accepts any data type for its object. Ex: Result - the can be a String, Integer, Double, etc. And the object can be created as whatever data type is placed inside those brackets.
  2. What is a generic method?: It is a method like any other, but the parameter can be any data type used in the parameter so long as the executable code within the method is compatible with that data type.
  3. Have you used a generic method? When?: Yes, in the service domain in an MVC setup, instead of creating a result for each individual service, a generic result class was used to accept any data type and was used universally across all service classes.
  4. True or false?: a generic type can accept any type as its type parameter.- : False, it cannot accept int, double, float, etc. These can be used only if they are placed in a wrapper class.
  5. True or false?: a generic type can have one and only one type parameter.- : False, a generic type can have many parameters and each argument is allowed to be their own generic type
  6. What is a collection? Why is it necessary since we already have arrays?: A collection is a broader type that includes arrays, arraylists, hashmaps, queues, etc. We use these other collections because each one has unique abilities and can be more flexible than an array.
  7. Which collection(s) should I avoid if the order of elements matters?: Sets and hashmaps are unordered and should be avoided if order matters.
  8. Which collection guarantees its elements are unique?: Sets/Hashsets
  9. If you're not sure which collection to use, but you know you need a collection, what is a sensible collection to start with?: A list. A list is a collection that can be turned into an array or a hashmap later using a stream.
  10. Why would I use a Map<K,V>? Share a concrete example.: You would use a map for large data sets where it would be a waste of resources to loop through the entire collection. Example: assigning an email with a username - instead of looping through the entire collection to find someone's username, entering in

14 / 25 their email (if that is the key for the map) would return their username - immediately finding the username and omitting the need to cycle through every username.

  1. What is the difference between Map and HashMap?: A map is an interface while HashMap is a framework.

15 / 25 Both contain key-pair sets, but HashMaps are unordered and can contain more than one null value; maps only allow for one null value and they are ordered by insertion

  1. Did you use a List during training? For what?: Yes, this was used many times during our training to create lists of values/objects.
  2. What data type should I use if I want to make a collection grow?: An array list is a good choice for a growing collection
  3. Name three collection types and their uses.: ArrayList - ordered collection of values with a specified index; used for collecting information like data sets HashSet - unordered collection of values that ensures no duplicate values exist; used for collecting unique values HashMap - unordered collection of values that can be accessed with a key-value system; used for large data sets that can be easily accessed by referencing a key
  4. Why does Java need exceptions?: Java needs exceptions because things can go wrong with our code, and it is important to let developers know what is causing the issue.
  5. How are exceptions modeled?: Termination Model - encounter exception -> method is terminated and control is transferred to catch block Resumptive Model - encounter exception -> exception handler does something to stable the situation, and then the faulting method is retried
  6. Talk about the keyword try: Try keyword attempts a block of code and is found in a try/catch statement
  7. Talk about the keyword catch: Catch keyword is used to deal with an excep- tion that the 'try' block may potentially pass
  8. What is throwing an exception?: Throw keyword explicitly casts out an exception, this is typically used with custom exceptions; methods that throw an exception typically uses the 'throws' keyword in conjunction. Each method that calls to this method must also use 'throws' to the same exception.
  9. Is it possible to execute two catch blocks from one exception in a try/catch declaration?: Yes, each catch block can have their own

16 / 25 exception to find.

  1. Does Java require us to eventually catch exceptions if they might be thrown?: Yes, otherwise the program will crash if they aren't dealt with.
  2. What is a checked exception?: A checked exception is an exception that is found at compile time - when throwing this kind of exception in a specified method, the program will warn the developer of subsequent methods that call to this method.

17 / 25

  1. If I call a method that might throw a checked exception and I don't want to catch it, what must I do?: The method itself and any other method that calls to this method must use the 'throws' keyword as part of the method signature that references the exception being thrown.
  2. What is an enum? What problem do they solve?: An enum is an object that is created at compile-time rather than run-time. This grants immediacy of evaluating information rather than waiting for the program to run and then create the object to evaluate at run-time.
  3. What is the naming convention for declaring an enum?: Every letter is capitalized for an enum, under scores replace spaces
  4. What is an Enum, and what is the naming convention?: Enums can hold a variety of values, but are fixed throughout the program. All Caps snake case.
  5. Can I explicitly define the values of an enum?: Yes, these values must be declared within the class and placed in a constructor.
  6. public, protected, private - What do these do?: These affect classes, fields, and methods; each of these keywords affect whether other classes will have access to them:
  7. public keyword: Public - any class can have access to methods/fields
  8. private keyword: Private - only the class has access to its own elements (methods, fields)
  9. protected keyword: the protected keyword limits the access of a class mem- ber to only those classes which reside within the same package
  10. static keyword: Means the static method/field can stand on its own - it does not depend on the instantiation of an object to be called upon Is used to declare members that do not belong to individual objects but to a class itself.
  11. final keyword: Used to denote a variable whose value is constant- can also be used in method declaration to assert that the method cannot be overridden by subclasses
  12. abstract keyword: Abstract class is restricted and cannot be used to create objects (accessed by being inherited from another class)

18 / 25 denotes a class that cannot be instantiated and provides no implementation for its member methods and fields - used to define certain behaviors and properties of subclasses

  1. super keyword: Calls to a parent class

19 / 25 Used to pass data from the subclass into the superclass through the superclass's constructor

  1. this keyword: Calls to a field (variable) within the class the keyword is being used in
  2. new keyword: Used to create a new instance of an object
  3. What is lambda? What are some examples?: A lambda is a method that is unnamed and has the ability to be used as a parameter to another method: List
    addresses = find All Addresses(); List
    lasVegas = filter(addresses, a -> a.getCity().equals Ignore Case("Las Vegas")); Public List
    filter(addresses, Predicate
    test) The output of the lambda in this example will take the place of the predicate argument in the 'filter' method.
  4. True or false?: a lambda must return a value.: True, a lambda acts in place of a value; instead it is a method that returns a value based on what information the lambda requests
  5. If you take away the special syntax, what is a lambda under the hood?: A method like any other. The first part of the lambda is the parameter for the unnamed method while the code that follows is the code block for the method.
  6. What is the stream API? What problem does it solve?: It is a method that turns a list into a stream. This allows for filtering, sorting, mapping, and other functions to be enacted upon the list. This is allows for a more convenient iteration method comparing to a traditional loop.
  7. Which types have stream methods?: All collections can be turned into streams
  8. What type is returned by a stream's .filter(predicate)?: Another stream that only takes elements that are specified by the filter function
  9. How do I grab one item inside of a Stream? Is there more than one way?: You can use the limit function; find First; and .collect with a specific criteria to extract a single element
  10. What type is returned by a stream's .collect(Collectors. grouping By(se- lector))?: The grouping By depends on two arguments that are

20 / 25 each used as a key-value pair: a map

  1. What is a terminal operation?: An operation called during a stream that prevents the stream from being broken down any further: the stream cannot be

21 / 25 expanded further. forEach, collect, and .get terminates a stream

  1. What is Maven? What problem does it solve?: Maven is a java application that installs third-party libraries, defines a project structure, builds and executes our project in different modes and bundles our project to be shared and deployed
  2. How do you configure Spring?: Add spring as a dependency to the project and the you have two methods for injecting dependencies: Annotation: uses a keyword for each class to seamlessly connect them together Xml file: manually specify each class and which class to each other in an xml document
  3. What is dependency injection? What problem does it solve?: Dependency injection is the act of slotting class parameters for classes that require the use of those classes methods. This is accomplished by placing class objects within the parameters of a class's constructor or using a dependency injection method such as Spring.
  4. Name three types of dependency injection.: Constructor dependency injec- tion XML dependency injection Annotation dependency injection
  5. What is the DRY principle?: Don't Repeat Yourself - limit the amount of repeated code as much as possible
  6. What is loose coupling?: Loose coupling follows the concept of encapsula- tion: approach to interconnecting the components in a system or network so that those components depend on each other to the least extent possible
  7. What are common logical application layers?: The UI, domain, data access layer, and the models
  8. What is the MVC pattern?: The model-view-controller pattern is a three layer architecture that is composed of the controller, view, and the model with the interac- tion between the view and the model

22 / 25 occurring within the controller.

  1. What is a design pattern? Name one other than MVC.: Design patterns are solutions to general problems that software developers face during software development. They describe how classes are laid out to efficiently solve a problem

23 / 25

  1. Where can a method definition go in your source code? Can definitions be nested?: Methods just need to be defined in a class. Methods cannot be directly nested.
  2. What is a static method?: Access: A static method can access only static members and can not access non-static members. Binding: Static method uses compile time binding or early binding. Overriding: A static method cannot be overridden. Memory: Static method occupies less space and memory allocation happens once. Keyword: A static method is declared using static keyword.
  3. What is a non-static method?: Access: A non-static method can access both static as well as non-static members Binding: Non-static method uses run time binding or dynamic binding. Overriding: A non-static method can be overridden being dynamic binding. Memory: A non-static method may occupy more space. Memory allocation happens when method is invoked and memory is deallocated once method is executed completely. Keyword: none
  4. Can I create my own custom exception?: Yes, custom exceptions can be made like the Data Access Exception that is frequently used throughout our projects to catch any and all exceptions or errors.
  5. Why do we throw exceptions?: Throwing warns developers about the ex- ception being thrown. Developers can then decide when and how to deal with that exception later in the program using a try/catch block.
  6. What does the finally keyword do in a try/catch?: Finally keyword is an optional keyword at the end of a try/catch block that will execute regardless of whether an exception was caught or not.
  7. What is an unchecked exception?: An unchecked exception is an

24 / 25 exception that is found at run-time. Any exception classes that extend Runtime Exception are the unchecked exceptions

  1. Explain how each part of the MVC pattern is connected.: Controller and view lies in the UI, while the models have their own package, but the communication

25 / 25 between the view and the model occurs in the domain layer which also has access to the data layer.

  1. What is the JVM?: JVM is specifically responsible for converting bytecode to machine-specific code and is necessary in both JDK and JRE. It is also platform-de- pendent and performs many functions, including memory management and security. Inner Most of the 3 Class Loader Runtime Memory/Data Area Execution Engine
  2. What is the JDK?: The JDK is the Java Development Kit which contains all tools necessary to create and compile Java programs.
  3. What is the JRE?: The JRE is the Java Runtime Environment which provides the classes and runtime libraries to run a Java program.
  4. How are the JRE, JDK, and JVM connected?: JVM is a subset of JRE and converts bytecode to machine-specific code. The JRE executes programs and includes the JVM. The JDK is the outer most layer that includes the JRE, a debugger, and more.
  5. When would you use a temporal type?: Use temporal data types to store date, time, and time-interval information. Although you can store this data in char- acter strings, it is better to use temporal types for consistency and validation.