Technical Interview
What is agile methodology? What about SCRUM?
- Iterative and incremental development - Adaptive planning rather than predictive planning - Flexible response to changes - Software delivery is the measure of progress Scrum is a subset of Agile.
13. toString() and hashCode() in String class
.toString is what will be called when you print the method. Hashcode is used in conjunction with .equals(). A hash code is an integer value that is associated with each object in Java. Its main purpose is to facilitate hashing in hash tables, which are used by data structures like HashMap. Same object should always have same hash value. Hashing is simply passing some data through a formula that produces a result, called a hash. That hash is usually a string of characters and the hashes generated by a formula are always the same length, regardless of how much data you feed into it.
18. What are the steps to connect to Database in Java?
7 steps: 1. import the package (java.sql.*) 2. load the driver (download the jar mysql.connector.. in dependencies) and register it (for mysql it's class.forName("com.mysql.jdbc.Driver")) 3. establish the connection (instantiate Connection interface) 4. create the statement (create a Statement, PreparedStatement, or CallableStatement object) 5. execute the query 6. process results 7. close the connection and statement
9. Exception handling - checked and unchecked exceptions, try/catch and finally.
A checked exception is caught at compile time (ex. IO exception if you use FileReader) - you will be forced to handle it. An unchecked exception is not caught at compile time and is discovered at runtime (ex. Null Pointer exception) - not forced to handle it, but you should. TO HANDLE: 1. you can use throws keyword before the method body OR 2. try / catch(only runs if specified exception occurs) to surround the part that's causing the exception Finally is what it will do afterwards regardless of whether there is an exception and regardless of whether it was handled properly at that time or not.
What is an inner class?
A class within a class. To access it, you must create an instance of the outer class and then an instance of the inner class. It is used to organize code. Also they can access attributes & methods of the outer class. An inner class can be private or protected (unlike normal classes) Ex. OuterClass myOuter = new OuterClass(); OuterClass.InnerClass myInner = myOuter.new InnerClass();
2. What is a constructor?
A constructor is a special method which contains the instructions for how to initialize an object. Its' name must match the class name exactly and it has no return type. It is called whenever an object is created. If you don't write a constructor, the compiler will create on with no-args and empty body. We can have multiple constructors with different parameters (overloaded constructors). For example, my student class could have a no-arg constructor that initializes the tuition variable to $7000. I can also have a parameterized constructor where we will pass in firstName, lastName and tuition.
What is Spring Boot?
A java framework for Spring that does a lot of the configuration for you. Use Spring initializer.. just select Maven/Gradle, War/Jar, some dependencies, etc. You don't need to setup a Tomcat server to run your web application. You can just write code and run it as Java application because it comes with an embedded Tomcat server.
What are lambda expressions?
A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.
What is recursion?
A programming technique that causes a method to call itself in order to compute a result. must have a halting condition ex. def factorials(n): if n == 1: return 1 else: return n * factorial(n-1)
What is a servlet?
A servlet is a class that extends HttpServlet. Use @WebServlet annotations with URI. need to complete doGet and/or doPost methods which have request and response parameters. Often you will add things to the HttpSession (which can be accessed by the jsp). session.setAttribute("vehiclesFromSearch", vehiclesFromSearch) request dispatcher... send a jsp.
What are variable arguments?
Allows an undefined number of arguments. use ... Ex. public int sum(int... numbers) {blah} example.sum() example.sum(1,2,3); example.sum(1,2,3,4); Inside the method, you basically use it like an array. for (int number : numbers) { sum += number; }
6. Describe some of the data structures you used along with advantages/disadvantages of each. (Lists, Maps, trees etc)
ArrayList as opposed to Array -ArrayList is resizeable while array is not (so you have to create a new one to add something) -can't use ArrayList w/ primitive types.. so have to convert them to use wrapper classes -ArrayList has add, remove, get, set, clear, size, contains -Can use Collections.sort(myNumbers); to put in order cars.get(0); LinkedList is similar but can only add, get, or remove from front and back contains HashMap - key/value pairs You can access items with their key instead of a random index .put(key, value).. .get(key).. .remove(key).. .clear().. .size() containsKey() containsValue() Loop through the items of a HashMap with a for-each loop. Use the keySet() method if you only want the keys, and use the values() method if you only want the values: HashSet - every item is unique .add() .contains() .remove() .clear() .size() no .get (sets don't have this) -for all of these, can't use ArrayList w/ primitive types.. so have to convert them to use wrapper classes Stack - last-in-first-out Queue - first-in-first-out
8. Distinguish between abstract classes and interfaces.
Both are abstract and cannot be instantiated. An interface talks about actions that the classes can confirm (ex. Runnable). Abstract classes represent an object and so have noun names. Use abstract class when you have a parent class that is "not complete".. has abstract methods. Constructors - Abstract classes have constructors that can be implemented using super keyword. Interfaces do not have constructors. Methods - Abstract classes can have abstract methods or concrete methods (w/ body implementation). Interfaces have only "empty"(abstract) methods.. classes then implement the interface.. classes that implement the interface must implement all the methods from the interface (meaning, write their bodies). Fields - An abstract class may contain instance variables or constant/final variables. Interface can only use constant variables, using static final. Keywords to use - extend vs. implement Mutliple Implementation - Classes can extend only 1 abstract class (hierarchical), but can implement multiple interfaces. Implementation: Abstract class can provide the implementation of interface. Interface can't provide the implementation of abstract class. An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. WHY WOULD YOU USED EACH ONE? Objects of classes that implement an interface can be treated as that interface type (and assigned to interface variables). This sounds like the same as abstract classes. IS THIS CONSIDERED POLYMORPHISM? Then with interface, you could have a method that has that interface type as a parameter.. it could be used with anything that implements that interface. (see pdf).. seems same as with abstract class EXAMPLE: Created a TokenVerifier interface and GoogleTokenVerifier... that way in the future I can also implement this interface if I integrate this app with other platforms besides Google in the future.
1. Define classes and objects.
Class - Is a blueprint from which objects of that type are created. It includes all the attributes (fields) and behavior (methods) all objects of that type will have, as well as constructor(s) which explain how to initialize a new object of that type. For example you could have a student class with a ID field and getGPA method. Every class is a different .java file (src) and compiled into a .CLASS file. Object - Is an instance of a class. It has identity(name), attributes/state(instance variables), and behaviors(methods). You create it using the keyword new which directs it to the constructor. Has instance variables and methods. An example would be a student object that I store in a variable called Lucy. Arrays are also objects.
4 Explain inheritance.
DEFINE: Inheritance can be defined as the process where one class acquires the methods and fields of another. Represents the IS-A relationship - child is a parent - UsedVehicle is a Vehicle. EXPLAIN: The class which inherits the properties of other is known as subclass (derived class, child class) and the class whose properties are inherited is known as superclass (base class, parent class). For common properties that will be reused again and again (so you're not writing repetitive code). EXAMPLE with syntax: We use the "extends" keyword to inherit the properties of a class. For example my NewVehicle extended Vehicle so that it inherited the fields & methods from it. Default child constructor will run parent constructor, Use the super keyword to inherit the constructor. Single (1P, 1C), Mulitlevel (1 GP, 1P, 1C), Hierarchical (1P, 2+ C). MULTIPLE inheritance is only posssible with interfaces. Buyer & Employee extend Person (firstName, lastName, email, phoneNumber... compareTo, equals are concrete methods while toString and formatData are abstract) Employee has additional fields that are not inherited (employeeId & password) NewVehicle & UsedVehicle extend Vehicle (id, year, make, model, askingPrice, priceSold, etc, etc. ... isEligibleForBid, equals, hashcode). Several methods such as toString will be overridden by one child class and not the other. UsedVehicle also has KBBCondition and miles.
What is object-oriented programming?
DEFINE: OOP is where the most important things are classes which are blueprints for objects. EXPLAIN: Objects contain both fields and methods. The fields and methods will belong to (be specific to) object, unless we use the static modifier in which case it will belong to class. EXAMPLE: Student class with field grades, int[] and method calculateGPA, double. Student object, Gina & student object Julio will each have their own individual grades and calculateGPA method which may come up with different results.
4 Explain polymorphism.
DEFINE: Same code, different behavior. Achieved through overloading and overriding. EXPLAIN: So there are two types, compile-time and runtime, but usually people are talking about runtime polymorphism. Dynamic/Runtime - Multiple children with same parent can override the method of the parent and have different implementations for it. Animal.makeSound() esp in an array.. the cat will say meow and the dog will say ruff We also have: Static/Compile Time... method overloading.. method name is same but arguments different and unique (in number and/or return type). Return type does not matter while overloading a method. ... The only way Java can know which method to call is by differentiating the types of the argument list. In my car dealership app: .toString and formatData for Buyer & Employee which extend person... they each provide their own implementation of these 2 abstract methods.
4 Explain abstraction.
DEFINE: Separate FUNCTIONALITY from IMPLEMENTATION. Hiding the complexity so you just use the functionality. Basically not having to worry about what's under the hood. EXPLAIN: Achieved through interfaces (100% abstraction) and abstract classes (0-100% abstraction - b/c can put in final methods). If we know that a class extends or implements one of these, we know that it will have certain functionality. But you don't might not understand how this method is implemented and which kinds of actions it has to perform to create the expected result. EXAMPLE with syntax: I know anything that implements the Collections interface has .size() method or .isEmpty(). Anything with DAO interface will have a .save method. I created a TokenVerifier interface with verify method and then GoogleTokenVerifier... that way in the future I can also implement this interface if I integrate this app with other platforms besides Google in the future. The token verifier to verify the OAuth token sent by Google and uses it to get the "payload" user info to create a new TeachSmart account or pull up the old one. TokenVerifier is what we're acting on, so later it could be a FacebookTokenVerifier or a GoogleTokenVerifier
Single Responsibility Principle
Define: A class should have only one job to do. Therefore there should never be more than one reason for a class to change. Explain: Everything in the class should be related to that single purpose, i.e. be cohesive. Example: Instead of having one class, Logger, that collects and stores log. We should have two classes, Logger collects logs, and LogStorage stores them.
What is an anonymous class?
Define: A class without a name. Explain: Use this whenever you're only going to use this class once Example: Comparator<String> reverseComparator = new Comparator<String>() {...}
What's the difference between an array and arrayList?
Define: Array is a fixed length data structure whereas ArrayList is a part of collection framework and is dynamic. Explain: We cannot change length of array once created in Java but ArrayList can be changed. We cannot store primitives in ArrayList, it can only store objects. But array can contain both primitives and objects in Java. Example: I use an ArrayList when I need flexibility in size (adding and removing items). I use Array for primitive types (int or boolean). Array is also faster and takes less memory (but it doesn't really matter).
4 Explain encapsulation.
Define: It describes the idea of bundling data and methods that work on that data within one unit - the class. It's used to protect or hide the values or state of a structured data object inside a class, preventing unauthorized parties' direct access to them. Can only modify the fields directly from that class... not from outside classes. Explain: bundle it with methods that provide read or write access to it, then you can hide specific information and control access to the internal state of the object. Declaring all the variables in the class as private and writing public methods in the class to set and/or get the values of variables. Example with syntax: Ex. Student class with firstName, lastName, studentID. If each of these were variables were public, we could access them even from outside the class by student.lastName... but instead, we'll make them private. Getters & setters , but id only has getter. Other methods that act on those variables could include printFullName. Encapsulation... provide getters and setters to access the private fields of Person, Vehicle, etc.
Interface Segregation Principle
Define: The Interface Segregation Principle (ISP) states that clients should not be forced to depend upon interface members they do not use. When we have non-cohesive interfaces, the ISP guides us to create multiple, smaller, cohesive interfaces. Explain: Many client-specific interfaces are better than one general purpose interface Example:
Open-Closed Principle
Define: classes should be open for extension but closed for modification. "Open to extension" means that you should design your classes so that new functionality can be added as new requirements are generated. "Closed for modification" means that once you have developed a class you should never modify it, except to correct bugs. Explain: Modifying the original source code can cause new bugs. Rather than changing an existing class/Interface, we should extend that class/Interface in a new class to add new features. Example:
19. What is a DriverManager class?
DriverManager is a static class in the Java™ 2 Plaform, Standard Edition (J2SE) and Java SE Development Kit (JDK). DriverManager manages the set of Java Database Connectivity (JDBC) drivers that are available for an application to use. Applications can use multiple JDBC drivers concurrently if necessary.
Difference between error and exception?
Exceptions are expected to be provided for (happen due to your program.. ex. null pointer).. not errors (happen due to the system.. ex. out of memory).
What is XML?
Extensible Markup Language Used for storing and exchanging data as text. pom.xml HTTP Requests
Explain some of the HTTP codes
HTTP is Hyper Text Transfer Protocol... to communicate/deliver info between web clients and web servers on the www 400 - bad request - the request could not be understood by the server (probably formatted incorrectly) 401 - unauthorized - request requires user authentication (need authorization header or have expired token) 404 - not found - server has not found anything matching the Request-URI (example there is not jsp) 500 - internal server error - server encountered an unexpected condition which prevented it from fulfilling the request (generic)
25. What is a MultipartResolver and when it's used?
In Spring Framework, MultipartResolver interface is used for uploading files
Functional Programming
In declarative programming, there are no statements. Instead, programmers use expressions to tell the computer what needs to be done, but not how to accomplish the task. If you are familiar with SQL or regular expressions, then you have some experience with the declarative style
What are the primary interfaces and objects in java util package?
Includes Collections Framework: Set, HashSet, SortedSet, And Maps Interface: HashMap, Hashtable, Queue, List (ArrayList, LinkedList) There are also scanner & iterator
22. What is dependency Injection? Why use it?
Instead of having our object create it's dependencies using the new keyword (tight coupling), we are using an external service (container) to create this dependency and then inject it in your object. B/c loosecoupling.. one is not completely dependent on other @Component makes it a dependency (or @Controller, @Service, @Repository) @Autowired where we want it injected ex. class Laptop { @Autowired HardDrive obj1; } @Component class HitachiHD implements HardDrive { }
17. What is JDBC?
JDBC - Java Data Base Connectivity. To connect a java application with a database. I used JPA & Hibernate. The Java Persistence API (JPA) is a standard API for accessing databases from within Java applications.
What is JSON?
JSON: JavaScript Object Notation - a syntax for storing and exchanging data as text. Can be used to exchange data between between a browser and a server. We can work with the data as JavaScript objects, with no complicated parsing. var myObj = {name: "John", age: 31, city: "New York"};var myJSON = JSON.stringify(myObj); Better than XML b/c XML is much more difficult to parse than JSON. JSON is parsed into a ready-to-use JavaScript object.
11. Generic and collections - definition and use.
Java has type safety because you have to declare it at compile time. Typically Collections framework doesn't provide type safety List value = new ArrayList(); .. you could add anything to this if you put List<Integer> = new ArrayList<Integer>(); this is using generics.. so it ensure everything that you put in is of the same type... so you won't have errors when processing it inheritance is not supported in generic type parameters.. me: that's why we have to use the wild card... method with paramenter of ArrayList<Object> won't accept ArrayList<Student> as a parameter The difference is that the inputs to formal parameters are values, while the inputs to type parameters are types. example class Test<T, U> { T obj1; // An object of type T U obj2; // An object of type U // constructor Test(T obj1, U obj2) { this.obj1 = obj1; this.obj2 = obj2; } }
Pass by value vs. pass by reference
Java is always pass-by-value. Unfortunately, when we pass the value of an object, we are passing the pointer (not the actual memory address) to it. x = 5; y = x; y += 2; now x=5 & y=7 (x does not equal 7). Class test { int x; } static void main { Test test1 = new Test(); test1.x = 5; Test test2 = test1; test2.x += 2; } Now test1.x & test2.x = 7 because test1 & test2 are the exact same object Pass by value = primitives and immutable object. String & all wrapper classes are immutable so they will be pass by value (because a new one is getting made each time... the values are not getting changed). Pass by reference = mutable objects.
What is an enum?
Like a class but group of constants (unchangeable variables, like final variables) It can only be one. Example: clothingSize.SMALL clothingSize.MEDIUM clothingSize.LARGE Months, colors, etc Can have also methods. Cannot be used to create objects, and it cannot extend other classes (but it can implement interfaces).
20. How do we store images in database?
Look at project... I think we used file... I've also just stored URL strings
Maven
Maven is a build tool that helps in project management. It helps in building and managing the project. A build tool - generates source code, generates documentation from the source code, compiles the source code, packages the compiled code into JAR files, and installs the packaged code in your local repository. Based on the Project Object Model - an XML file that has all the info regarding project and configuration details. Maven looks for the POM in the current directory whenever it has to execute a task. Helps in downloading dependencies (libraries/JAR files) used in the project. Helps to create the right project structure which is essential for execution. Builds and deploys the project so that it will work properly.
21. What is Spring MVC framework?
Model View Controller
SQL
MySQL is a relational database management system Inner Join Full Outer Join Left Outer Join Right Outer Left Join
What is the difference of Java from C++?
No pointers, so cannot access an object by referencing it's memory location. Java is a put OOL - classes only. Has garbage collection, so we don't need to manage memory. Java doesn't support multiple inheritance (only implementing multiple interfaces).
Hibernate
Object model for code. Relational model for database. To connect the software objects with the database relations we need Object Relational Mapping concept.. so we came up with the implementations ORM tools (like Hibernate). Classes/fields/objects.... Tables/columns/rows
4. What are the 4 fundamentals of OOP? Why is OOP good?
PIEA - Polymorphism, Inheritance, Encapsulation, Abstraction Can model everything after the "domain" (target subject of a computer program). Ex. car dealership application: Dealership, Buyer, Employee, Vehicle, UsedVehicle, NewVehicle. Reuse (classes to make many different object and the methods.. also inheritance, etc)
Why is Java so good/popular?
Platform independent & pure Object Oriented (everything is a class... can only write OOP programs)- easy to maintain
What are the primitive & nonprimitive data types?
Primitive data types - includes byte, short, int, long, float, double, boolean and char... specifies the amt of memory allocated. Cannot be null. Have no methods (that's why there's the special classes... Integer, Character, etc) Non-primitive/reference/object data types - such as String, Arrays and Classes. Can be null. Can use their methods. All have the same size.
Explain SOLID design principles.
READ THIS: https://www.baeldung.com/solid-principles Purpose: Our software must be able to keep up with the changing needs of your customer in order to keep the secondary value high. important to write code that's easy to extend and maintain. Easier for other developers to deal with down the line. 5 OODesign principles: Single Responsibility Principle Open-Closed Principle Liskov Substitution Principle Interface Segregation Principle Dependency Inversion Principle
What are RESTful webservices?
RESTful web services are loosely coupled, lightweight web services that are particularly well suited for creating APIs for clients. In REST architecture, a REST Server simply provides access to resources and REST client accesses and modifies the resources. A RESTful web service usually defines a URI, resource representation such as JSON and set of HTTP Methods. Use HTTP Methods: GET − Provides a read only access to a resource. POST − Used to create a new resource. DELETE − Used to remove a resource. PUT − Used to update a existing resource or create a new resource.
16. What is 'This' keyword in Java?
Refers to the object that this method belongs to.
7. What is interface, why do we use it?
Represents commons functionality/actions that multiple classes will share. All methods are abstract... all attributes are static final. if implement an interface, must provide bodies for all its' methods Blueprint for classes to follow... contains a set of related methods with empty bodies... classes must write the bodies to fit their needs.. so must provide functionality, but how they do it is up to them An interface in Java is a collection of abstract methods and static constants. As you might know in an interface, each method is public and abstract but it does not contain any constructor. Along with abstraction, the interface also helps to achieve multiple inheritance in Java.Note: You can achieve 100% abstraction using interfaces. Notes on Interfaces: Like abstract classes, interfaces cannot be used to create objects (in the example above, it is not possible to create an "Animal" object in the MyMainClass) Interface methods do not have a body - the body is provided by the "implement" class On implementation of an interface, you must override all of its methods Interface methods are by default abstract and public Interface attributes are by default public, static and final An interface cannot contain a constructor (as it cannot be used to create objects) Why And When To Use Interfaces? 1) To achieve security - hide certain details and only show the important details of an object (interface). 2) Java does not support "multiple inheritance" (a class can only inherit from one superclass). However, it can be achieved with interfaces, because the class can implement multiple interfaces. Note: To implement multiple interfaces, separate them with a comma (see example below). If we know that a class extends or implements one of these, we know that it will have certain functionality... but we don't know exactly how. Ex. I know anything that implements the Collections interface has .size() method or .isEmpty(). Anything with DAO interface will have a .save method. An interface can extend another interface in the same way that a class can extend another class. The extends keyword is used to extend an interface, and the child interface inherits the methods of the parent interface. ONLY a class can implement the interface. Can also have static methods and default methods (more for functional programming) EXAMPLE: Created a TokenVerifier interface and GoogleTokenVerifier... that way in the future I can also implement this interface if I integrate this app with other platforms besides Google in the future. Created a TokenVerifier interface (and my own IdToken class) with verify method and then GoogleTokenVerifier... that way in the future I can also implement this interface if I integrate this app with other platforms besides Google in the future. The token verifier to verify the OAuth token sent by Google and uses it to get the "payload" user info to create a new TeachSmart account or pull up the old one Also CoursesService interface and GoogleClassroomService implementation... currently CoursesService is actually coupled with Google Client Library because I've had trouble parsing those items... in future I want the CoursesService to correspond with my classes TSClass and TSAssignment
Functional Interface
SAM - Single Abstract Method.. can only have one abstract method, but can have additional non-abstract methods can use lambda expressions We have a functional interface and call it through Lamba expression. Without implementing it somewhere. All lambda expressions will fail if you add another abstract method. Would fail at runtime. Instead you can add an annotation @FunctionalInterface above the class so that others can see and compiler will catch it.
23. What is DispatcherServlet and ContextLoaderListener?
Spring - The DispatcherServlet is one of the important components of the Spring MVC web framework and acts as a Front Controller. ... The DispatcherServlet is a front controller like it provides a single entry point for a client request to Spring MVC web application and forwards request to Spring MVC controllers for processing. Spring - ContextLoaderListner is a Servlet listener that loads all the different configuration files (service layer configuration, persistence layer configuration etc) into single spring application context. This helps to split spring configurations across multiple XML files.
24. What is the ViewResolver class?
Spring Framework - The ViewResolver provides a mapping between view names and actual views.
15. What is the difference between Static method and instance method?
Static methods are called on the class. Instance methods are called on the object.
12. Difference between string, stringBuffer and stringBuilder.
String is immutable meaning the value cannot be changed. It will create a new String object each time you change that variable. StringBuffer & StringBuilder are mutable. Therefore they have better performance if you're looping through and changing the something b/c it reuses existing objects. StringBuilder is not synchronized so it's bad if we have multiple threads. StringBuffer is good for multiple threads.
Liskov Substitution Principle
THIS ONE IS STILL HARD FOR ME TO UNDERSTAND... I NEED TO DO SOME PRACTICE Define: you should design your classes so that client dependencies can be substituted with subclasses without the client knowing about the change. Explain: All subclasses must, therefore, operate in the same manner as their base classes. The specific functionality of the subclass may be different but must conform to the expected behaviour of the base class. Wherever we use class A in our program we should be able to replace it with its subtype class B. The following are the conditions to avoid LSP violation. Method signatures must match and accept equal no of the parameter as the base type The return type of the method should match to a base type Exception types must match to a base class Example: example that violates LSP is a Square class that derives from a Rectangle class. The Square class always assumes that the width is equal with the height. If a Square object is used in a context where a Rectangle is expected, unexpected behaviour may occur because the dimensions of a Square cannot (or rather should not) be modified independently.
3. What is static variable/method and block?
Technical - Static members belong to the class instead of a specific instance. Explain - That means it's one member shared b/t all objects. Therefore you can access a static member without creating an object (we can simply get that from memory). Example - min is a static method belonging to the Math class so we can call it as Math.min(10, 20). I've use path as a static variable(and set it as final so it can't be modified). Extra: Static members are common for all the instances(objects) of the class but non-static members are separate (and possibly unique) for each instance of class. Static variables can be accessed via the class or the object. This is not recommended though. we can use statics for constants as in static final. It's recommended not to use too many static variables or methods because they're not out there Static block is executed once at the time of class-loading (so it always runs BEFORE the main method if it's in that class) & initialisation by JVM (whereas constructor is called at the every time of creating instance of that class). Non-static members cannot be accessed from static context like in a method... b/c can't get that info unless you have a specific object Why? Static block - is especially good for something more complicated than doing Private static final path = "/" Static variable - is shared b/t all, so memory allocation for such variables only happens once when the class is loaded in the memory... if one object updates it, then it's updated for all (so it's good to make it final)... Use static variables if they should be shared among all objects, e.g. a variable to keep track the number of instances, a constant, etc. Static method - Any method that doesn't use the instance variables could be static (i.e. it's hard coded or only uses parameters)...Use static methods if they do not depend on states of any objects, e.g. utility methods that do calculation.
5. What's the difference between overloading and overriding?
Technical: Overloading is when two or more methods have the same name but different parameters (can occur in same class or parent/child relationship)... can use either. Explain: This often happens so that you can have one no-arg constructor (for use by JPA/hibernate), but also have a parameterized constructor. Example: A method that is often overloaded is the constructor.. Student() {} and Student(String firstName, String lastName) {} Technical: Overriding means the child class has a method with the same exact name and parameters (i.e., method signature is entirely same) as the parent class... child can only use the child one (can't use the parent one anymore) Explain: This is done to customize, define specific behavior for the child. It is required if the method is abstract (b/c an abstract method has no body). Example w/ syntax: toString() for Object class returns the hashcode which is the memory location. I usually override this (public String toString()) and have it print my fields. If you change the return type... it is NOT overriding or overloading. ven if you have a different return type, but everything else it the same, you can't do this... The only way Java can know which method to call is by differentiating the types of the argument list.
Java API
The Java Applications Programming Interface that specifies the wide variety of classes that come with the Java platform. can import classes (ex. import java.util.Scanner) or packages (ex. import java.util*;) using the import keyword
Types of loops and when/how to use them?
The while loop loops through a block of code as long as a specified condition is true.... good if you don't know how many times you'll need to go through int i = 0; while (i < 5) { System.out.println(i); i++; } //remember you still need to iterate I've used while loop for user input with an escape key Used for reading input while scanner has next line The do/while loop is a variant of the while loop. This loop will execute the code block once, before checking if the condition is true, then it will repeat the loop as long as the condition is true. When you know exactly how many times you want to loop through a block of code, use the for loop instead of a while loop often for arrays when you're going to do something based on the index value for-each" loop, which is used exclusively to loop through elements in an array
What are threads?
Threads allows a program to operate more efficiently by doing multiple things at the same time. Threads can be used to perform complicated tasks in the background without interrupting the main program. There are two ways to CREATE a thread. 1. It can be created by extending the Thread class and overriding its run() method. 2. implement the Runnable interface. Then you must run the thread... The major difference is that when a class extends the Thread class, you cannot extend any other class, but by implementing the Runnable interface, it is possible to extend from another class as well, like: class MyClass extends OtherClass implements Runnable. Concurrency problems: Because threads run at the same time as other parts of the program, there is no way to know in which order the code will run. When the threads and main program are reading and writing the same variables, the values are unpredictable.
10. Difference between throw and throws
Throw is when you actually create the exception in the method body. Throws is used to declare an exception.. a required specification when something in your program may cause an exception... you put it write before the method body.
What is UML?
Unified Modeling Language. This is a graphical notation specifically for drawing diagrams of an object-oriented system. The Unified Modeling Language is a general-purpose, developmental, modeling language in the field of software engineering that is intended to provide a standard way to visualize the design of a system.
What is JUnit? What are some assertions?
Unit Testing Framework.. library. Ensure code meets design and behaves as it should. Regression testing. TDD. setUpClass() setUp() testMethodName() tearDown() tearDownClass() assertions: assertEquals assertNotEquals assertTrue assertFalse assertNull assertNotNull
What's the difference between Linux and Windows?
Unix environment (w/o Linux) will not have a GUI.. so will be using Command Line. File system is different - Unix/Linux uses tree-like hierarchical file system. Everything is a file with Unix - even hard drives, printers, etc. Files are case sensitive so you can have a file Blah and blah in the same directory. Linux & Mac both use Unix.
What are some conditional statements and when/how to use them?
Use if to specify a block of code to be executed, if a specified condition is true Use else to specify a block of code to be executed, if the same condition is false Use else if to specify a new condition to test, if the first condition is false Use switch to specify many alternative blocks of code to be executed Short Hand If...Else (Ternary Operator): variable = (condition) ? expressionTrue : expressionFalse;
What are packages?
Used to group related classes. Like a folder/file directory. two categories: Built-in Packages (packages from the Java API) User-defined Packages (create your own packages)
Dependency Inversion Principle
VERY CONFUSED BY THIS ONE
14. What is a wrapper class, name some you have used
Wrapper class in Java. ... The eight primitive data types byte, short, int, long, float, double, char and boolean are not objects. Wrapper classes provide a way to use primitive data types (int, boolean, etc..) as objects. like int to Integer. Written w/ a capital letter I've used Integer and Double to parse those types from strings. I've also used Integer quite often for ArrayLists. I've used Character to Character.getNumericValue(thisChar); especially to transpose an array
What is platform independence?
Write the java program once and compile it and then you can run it anywhere. You just need to install a version of JVM for your operating system. Your program will run on JVM. Can run the .class or .jar file on any computer. Older languages like C & C++ are not platform independent. Will need to change some things in the code, compile it, build it, then run it on MacOS.
What are the access modifiers?
Written before the type and name ex. public String getName() Control access level of the class, attribute, method, or constructor For classes: 1. public (accessible by any other class) & 2. default (only accessible in the same package) For attributes, methods and constructors: 1. public 2. default 3. private (only within this class) 4. protected (in the same package and subclasses)
What is an iterator used for and how do you use it?
an object that can be used to loop through collections to loop using an iterator Iterator<String> it = cars.iterator(); while(it.hasNext()) { System.out.println(it.next()); } Trying to remove items using a for loop or a for-each loop would not work correctly because the collection is changing size at the same time that the code is trying to loop.
garbage collection
automatic reclamation of memory occupied by objects that are no longer referenced finalize() is called by the garbage collector on an object when garbage collection determines that there are no more references to the object. Generally avoid using finalize but could be used to close a scanner or something of the sort
What are some useful methods in java.lang.object?
clone, equals, toString, HashCode, finalize
" What are the Non-Access Modifiers?
do not control access level, but provides other functionality For classes: 1. Final - class cannot be inherited by other classes 2. Abstract - class cannot be used to create objects For attributes and methods: 1. Final - cannot be overridden or modified 2. Abstract - only for methods in an abstract class. The method does not have a body... the body will be written in the subclass. 3. Static - belongs to the class not the object (can be accessed without creating an object) 4. Transient - skipped when serializing the object containing them. ex. when storing in database or sending info 5. Synchronized 6. Volatile
How is the final modifier used?
final is something that can't be modified or overridden variable - value can't be changed method - can't be overridden class - can't be extended
Casting
int myInt = 9; double myDouble = myInt; // widening casting: done automatically double myDouble = 9.78; int myInt = (int) myDouble; //narrowing casting - manual
Where are all the java data / time stuff? How do you access the current date or current time?
java.time To display the current date, import the java.time.LocalDate class, and use its now() method: To display the current time (hour, minute, second, and nanoseconds), import the java.time.LocalTime class, and use its now() method: To display the current date and time, import the java.time.LocalDateTime class, and use its now() method:
" JDK vs JRE vs JVM
smallest to largest The JVM executes a computer program which has been compiled into Java bytecode. Java Runtime Environment (JRE) holds the JVM and provides the libraries. The Java Development Toolkit (JDK) is a software development environment. It encompasses JRE and the Dev Tools, compiler, and documentation.