├── JavaCheatSheet ├── JavaCheatSheet.pdf ├── JavaCheatSheet.docx └── CheatSheet.md └── README.md /JavaCheatSheet/JavaCheatSheet.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fletchy95/Java-Cheat-Sheet/HEAD/JavaCheatSheet/JavaCheatSheet.pdf -------------------------------------------------------------------------------- /JavaCheatSheet/JavaCheatSheet.docx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fletchy95/Java-Cheat-Sheet/HEAD/JavaCheatSheet/JavaCheatSheet.docx -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Java-Cheat-Sheet 2 | I built this cheat sheet for an entry level Java interview. I built it to the standards of my job description. 3 | Therefore it its important to review your job descripiton for the role your applying for and then use mine, or 4 | alter it depending on your needs. Feel free to fork it to make adjustments to fit your needs. Perhaps I'll make 5 | more Cheat Sheets in the future for other languages if I find the time! 6 | 7 | There is a .md verison of the cheat sheet, as well as a PDF and .docx verison! However the word version would be 8 | the best version to start with becuase you can adjust it to your needs! Enjoy! 9 | -------------------------------------------------------------------------------- /JavaCheatSheet/CheatSheet.md: -------------------------------------------------------------------------------- 1 | # Java-Cheat-Sheet 2 | Java Cheat Sheet 3 | 4 | Object oriented programming concepts 5 | - **Encapsulation** – this is concerned with hiding the implementation details and only exposing 6 | the methods. The main purpose of encapsulation is to; Reduce software development 7 | complexity – by hiding the implementation details and only exposing the operations, using a 8 | class becomes easy. Protect the internal state of an object – access to the class variables is via 9 | methods such as get and set, this makes the class flexible and easy to maintain. The internal 10 | implementation of the class can be changed without worrying about breaking the code that 11 | uses the class. 12 | - **Inheritance** – this is concerned with the relationship between classes. The relationship takes 13 | the form of a parent and child. The child uses the methods defined in the parent class. The 14 | main purpose of inheritance is; Re-usability– a number of children, can inherit from the same 15 | parent. This is very useful when we have to provide common functionality such as adding, 16 | updating and deleting data from the database. 17 | - **Polymorphism** – this is concerned with having a single form but many different 18 | implementation ways. The main purpose of polymorphism is; Simplify maintaining 19 | applications and making them more extendable. 20 | 21 | Interface vs. Abstract Classes 22 | - Interfaces are implicitly abstract and cannot have implementations out side the 23 | implementing class. Abstract classes can have instance methods that implement a default 24 | behavior 25 | - Variables in an interface by default are final. An abstract class may contain non-final 26 | variables. 27 | - Java interfaces are public by default meanwhile abstract class has can use the usual 28 | private, protected, public 29 | - Interface gets implemented, abstract classes get extended 30 | - Possible to have non abstract methods in an interface (you can have static and default) 31 | 32 | Constructors 33 | - No return type 34 | - They are the skeleton of an object, they allow you to create and object 35 | - When new instance of a class is called, the constructor is called to build the object 36 | - May have input values 37 | 38 | Serialization and File I/O 39 | - Serialization is a way to transform objects in to byte sequences and back (deserialization). 40 | It allows us to transmit serializable objects over the network and store them into files 41 | - File I/O streams are for storing/reading any kind of data to/from files 42 | 43 | List, Map, Set – Collections 44 | - All are interfaces in java 45 | - List 46 | o Provides ordered and indexed collection which may contain duplicates 47 | o Most popular would be ArrayList and LinkedList 48 | o Ordered Collection, maintains insertion order 49 | o Nulls allowed (can have several) 50 | o When to use 51 | ▪ Frequent access via index. If you know the index ArrayList provides quick access 52 | ▪ If you need to maintain an order on how they are inserted then go List again 53 | - Set 54 | o Interface provides an unordered collection of unique objects (no duplicates) 55 | o Most popular would be LinkedHashSet, TreeSet and HashSet 56 | o Unordered collection, no guarantee on which order element will be stored (Some 57 | may maintain order, but it is not a requirement by a Set 58 | o Only one null allowed 59 | o When to use 60 | ▪ Collection of unique elements, use Set as no duplicates are allowed 61 | ▪ Items stored on a TreeSet can be sorted easily when using a comparator so 62 | it is possible to maintain an order. However generally they do not 63 | maintain order 64 | - Map 65 | o Map provides a data structure based on key-value pair and hashing 66 | o Most popular would be HashMap, Hashtable, LinkedHashMap 67 | o May contain duplicates but each value is sent in with a (key, and value) so each 68 | piece of data does have an unique key 69 | o Can have null values, and at most ONE null key 70 | o When to use 71 | ▪ If you need to store data associated with a specific key then a Map is the 72 | way to go. For every value that goes in to a MAP a unique key also does 73 | which is used to access that value 74 | 75 | Access Modifiers 76 | - Important for Encapsulation, force the need for setters and getters 77 | - Default – only the same package 78 | - Private – only the same class 79 | - Protected – only the same package and sub classes in a different package 80 | - Public – Everywhere 81 | o Should be avoided, except for constants 82 | 83 | Checked vs. Unchecked Exceptions 84 | - Checked 85 | o Checked exceptions are checked at compile time 86 | o Checked exceptions must be thrown at method declaration, or placed in a try-catch 87 | - Unchecked exceptions are not checked. Error and RuntimeException are unchecked exceptions, 88 | everything else under throwable is checked. 89 | - Things should be checked if a client can reasonably be expected to recover from the exception. 90 | If a client cannot do anything, or it is unreasonable then make it an unchecked exception 91 | 92 | Generics 93 | - Allows type to be a parameter to methods, classes and interfaces. 94 | - ArrayList, HashSet, HashMap, etc do this very well 95 | - Ex. ArrayList arrayList = new ArrayList(); 96 | o The generic is , a requirement for being in this list is that the value must be an 97 | integer 98 | - Cannot use primitive types (int, double, char, etc) Must use the Object/Class version (Integer, 99 | Double, etc) 100 | 101 | Java Keywords 102 | - Final – variables are constants (cannot be changed), final methods cannot be overridden, final 103 | classes cannot be sub classed 104 | - Static – Indicates that a variable or method, is a class method 105 | - Volatile – indicates a variable may change asynchronously 106 | - Synchronized – specifies critical sections or methods in multithreaded code 107 | o Synchronized is attached to some object which will only allow one thread at a time to 108 | access that object 109 | - Transient – specifies that a variable is not part of an objects persistent state 110 | o Used in serialization 111 | o Used if we don’t want to save the value of a variable 112 | o The JVM it will ignore the original value of the variable and save it in its default state 113 | (typically 0) 114 | o Great for password security 115 | o Cannot be static (volatile keyword can be static) 116 | 117 | JVM and Memory Management 118 | - The JVM has very intuitive memory management so it is not always needed by the programming 119 | o Ex. The garbage collector will come around and auto delete unused variables 120 | - Some items are not handled automatically by the JVM and garbage collector forcing the 121 | programmer to get involved 122 | o Ex. Closing your scanner to ensure all resources are freed up 123 | - Heap 124 | o Shared runtime data area, stores the actual object in memory. Instantiated during VM 125 | startup 126 | o Allocated for all class instances and array, can be fixed or dynamic size depending on 127 | system configuration 128 | o Only one heap for a running JVM process, never more 129 | - Method Area 130 | o Logical part of the heap area, created on VM startup 131 | o Memory allocated for class structures, method data and constructor field data. Also for 132 | interfaces, can be fixed or dynamic size. 133 | - JVM Stacks 134 | o Stack is created same time a thread is created. Used to store data and partial results 135 | which is needed while returning value for method and performing dynamic linking 136 | o Fixed or dynamic, stack size can be chosen independently when created 137 | - Native Method Stacks 138 | o Not written in the Java language 139 | o Known as C stacks, memory allocated for each thread when its created, can be fixed or 140 | dynamic 141 | - Program Counter (PC) Registers 142 | o Each JVM thread that has a task is associated with a PC Register. 143 | o It stores the address of the available JVM instruction 144 | 145 | Multithreading and Synchronization 146 | - Best to look at deadlock code to explain synchronization 147 | - Multithreading 148 | o Using Threads allows you to concurrent execution of two or more parts of a program 149 | o Allows maximum utilization of the CPU 150 | o Threads are light-weight processes within a process 151 | o Achieved by extending thread class or implementing the runnable interface 152 | ▪ Both require usage of the run method 153 | o If you extend thread class we cannot extend any other class b/c java does not support 154 | multiple inheritance 155 | o If you implement the runnable interface, our class can still extend other base classes 156 | - Synchronized – specifies critical sections or methods in multithreaded code 157 | o Synchronized is attached to some object which will only allow one thread at a time to 158 | access that object 159 | o Be careful of DEADLOCKS, they can occur if two threads access synchronized methods in 160 | opposite order 161 | o Should always build in the same order of locks A->B always; never A->B AND B->A 162 | 163 | Design Patterns 164 | - Creational 165 | o All about class instantiation or object creation. 166 | o Great for Factory method, abstract factory, builder, singleton, object pool and prototype 167 | - Structural 168 | o All about organizing different classes and objects to form larger structures and provide 169 | new functionality 170 | o Great for adapter, bridge, composite, decorator, façade, flyweight, private class data 171 | and proxy 172 | - Behavioral 173 | o All about identifying common communication patterns between objects and realize 174 | these patterns 175 | o Great for chain of responsibility, command, interpreter, iterator, mediator, memento, 176 | null object, observer, state, strategy, template method, visitor 177 | 178 | Sockets 179 | - Socket socket = new Socket( IP , Port); 180 | - Streams are used in both input and output of the data 181 | - Sockets are needed to connect to another machine 182 | - Think of the java chat program you built with Nicole 183 | 184 | Remote Method Invocation RMI 185 | - Is an API which allows an object to invoke a method on an object that exists in another address 186 | space on the same machine or on a remote machine. 187 | - Through RMI an object on the client side can invoke methods on an object present in another 188 | JVM on the server side. 189 | - How it works: 190 | o Stub object 191 | ▪ Client machine builds an information block and sends this info to the server 192 | ▪ The information contains: an identifier of the remote object, method name to be invoked, and parameters to the remote JVM 193 | o Skeleton Object 194 | ▪ This object passes the request from the stub object to the remote object 195 | ▪ It preforms tasks like calling the desired method on the real object (present on server), forwards parameters received from the stub object to the method 196 | - Steps to implement interface 197 | o Define a remote interface 198 | o Implement the remote interface 199 | o Creating Stub and Skeleton objects from the implementation class using rmic (rmi 200 | compiler) 201 | o Start the rmiregsitry 202 | o Create and execute the server application program 203 | o Create and execute the client application program 204 | 205 | ORMs 206 | - EJB (Session Beans, Entity Beans, MDBS) 207 | o Session bean stores data of a particular user for a single session. 208 | o Entity Beans represent persistent data storage. Data can be saved to database via entity 209 | beans and later on retrieved 210 | o Message Driven Bean are used in context of Java messaging service. Consumes JMS 211 | messages from external entities and acts based on those messages 212 | - Hibernate 213 | o Used to overcome limitations of JDBC 214 | o It is open source and usable by anyone 215 | o Can modify the code to our need, very versatile 216 | o Most implementations are done for us, CRUD (create, read, update, delete) operations 217 | taken care of 218 | o First Level Cache vs. Second level Cache 219 | ▪ 1 st level came with Hibernate 1.0 where 2nd level came with Hibernate 3. 220 | ▪ 1 st level is session specific (local) while 2nd level is shared by sessions (global) 221 | 222 | Database Knowledge 223 | 224 | Database Drivers 225 | - Java Database Connectivity (JDBC) 226 | - Type 1 driver 227 | o JDBC-ODBC bridge driver 228 | o Not written in java so its not portable 229 | - Type 2 driver 230 | o Native API driver, converts JDBC method calls into native calls of the database API. 231 | o Allows interaction with different databases, data transfer is much more secure then 232 | type 1 233 | - Type 3 Driver 234 | o Network protocol driver uses middle ware that converts JDBC calls directly or indirectly 235 | into the vendor-specific database protocol 236 | o Written fully in java, therefore portable 237 | o No client side library is required, b/c application server can preform tasks like auditing, 238 | load balancing and logging 239 | o Maintenance is costly because it requires database-specific coding to be done in middle 240 | tier 241 | - Type 4 driver 242 | o Native Protocol driver interacts directly with database. 243 | o Known as Thin Driver b/c it does not require any native database library 244 | o Written fully in java, therefore portable 245 | - Which to use? 246 | o Accessing one type of databse like Oracle, preferred driver is type 4 247 | o Multiple types of databases at the same time then use type 3 248 | o Type 2 drivers are useful in situations where T3/4 are not available yet for your database 249 | o Type 1 driver is not considered a deployment0level driver, only really used for 250 | development and testing purposes 251 | 252 | Normalization and Denormalization 253 | - Normalization 254 | o Organizing the attributes of database to reduce or eliminate data redundancy 255 | o Data redundancy will increase the size of the database, inconsistency problems also 256 | arise during insert deletion and update queries 257 | - Denormalization 258 | o Optimization technique where we add redundant data to one or more tables. 259 | o Helps avoid costly joins in a relational database 260 | o This dos not mean not doing normalization, denormalization is an optimizing technique 261 | used after normalization the database 262 | - Pros and Cons of denormalization 263 | o Denormalization helps us retrieve data quicker, we need to do fewer joins 264 | o Denormalization queries to retrieve can be more simple since we only need to look at 265 | few tables 266 | o Cons: updates and inserts are more expensive, denormalization will make update/insert 267 | code harder to write, data may be inconsistent, increases amount of storage 268 | 269 | Stored Procedures 270 | - It is like a function that contains a set of operations compiled together. 271 | - Set of SQL statements with an assigned name, which are stored in a relational database 272 | management system as a group so it can be reused and shred by multiple programs 273 | - It provides and important layer of security between the user interface and the database. 274 | Supports security through data access controls because end users may enter or change 275 | 276 | Triggers 277 | - A database object that is associated with a table 278 | - It will be activated when a defined action is executed for the table 279 | o It can be activated if you run a insert, update or delete and it can be invoked before or 280 | after the event 281 | - Need SUPERUSER privileges to run MySQL triggers 282 | - Ex. CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age < 0 283 | THEN SET NEW.age = 0 ; END IF; 284 | 285 | Cursor 286 | - A cursor is read-only (cannot write to it), non-scrollable(can only fetch rows determined by the 287 | select statement), and asensitive 288 | - Asensitive 289 | o Asensitive cursor 290 | ▪ Points to actual data 291 | ▪ Faster than insensitive 292 | o Insensitive cursor 293 | ▪ Uses a temporary copy of the data 294 | ▪ Creates a copy and is safer to use an update command 295 | 296 | Waterfall Process 297 | 298 | Stages 299 | - Requirement gathering and documentation. Phase 1 300 | o Gather comprehensive information about what the project requires. 301 | o Gather information through interviews, questionnaires, interactive brainstorming 302 | o By the end of this phase requirements should be clear, and a requirements document 303 | should be distributed to the entire team 304 | - System Design. Phase 2 305 | o Using the requirements, the team designs the system. 306 | o No coding yet, specifications are proposed here, like programming language(s), 307 | software, hardware requirements 308 | - Implementation. Phase 3 309 | o Coding takes place 310 | o Take information from previous steps and build a functional product 311 | o Implement in small pieces, which are integrated at the end of this phase and/or 312 | beginning of the next 313 | - Testing. Phase 4 314 | o Test product in real (safe) environment 315 | o If problems arise team may need to return to phase 1 for reevaluation 316 | - Delivery/deployment. Phase 5 317 | o Product is complete 318 | o Deploy product to client 319 | - Maintenance. Phase 6 320 | o As issues arise you should be in contact with client to troubleshoot issues on 1st, 2nd, or 321 | 3 rd, level. 322 | o Send patch updates 323 | o Major issues may require return to phase 1 324 | 325 | Waterfall Facts 326 | - Keeps training simple 327 | o Ensures success even if unanticipated changes in bandwidth occur 328 | - Shows progress 329 | o You will see what stage you are at what is being completed, and what needs to be done 330 | still 331 | o Eliminates guesswork in project timeline because it does not allow to return to prior 332 | phase 333 | - Makes project easy to manage 334 | o Know where project is, where it should be 335 | o Unexpected delays/changes in personnel allow team to quickly get back on track 336 | - Saves time and money 337 | o Taking proper time to plan and design allows us to save time and money down the line 338 | in implementation and testing 339 | - When to use 340 | o When requirements are clear and specific. They do not change for the most part 341 | o Use agile if project requirements could change drastically 342 | 343 | Common Questions 344 | 345 | Difference between == and .equals() 346 | - X.equals(y) means the references x and y are holding objects that are equal 347 | - X==y means that references x and y are referencing the same object 348 | 349 | Common use of “this” keyword 350 | - Refer to instance variable when local variable is the same name 351 | - When passing itself to another method 352 | - Calling another constructor in constrictor chaining 353 | 354 | Lambda Expression 355 | - Useful to write shorthand code, saves effort of writing lengthy code 356 | - Should promote developer productivity, which in turn creates better more reliable code 357 | 358 | Different types of classes 359 | - Access – public, protected, default, private 360 | - Packaging – System, library, user defined 361 | - Structure – Outer or Inner 362 | - Object Derivation – abstract class or concrete class 363 | - Object creation – normal, singleton, doubleton, immutable, or enum 364 | - Functionality – String, Util, Stream etc. 365 | 366 | Final vs. Finally vs. Finalize() 367 | - Final 368 | o Final variables are constants, will never change. 369 | o Final Methods cannot be overridden 370 | o Final Classes cannot be sub classed 371 | - Finally 372 | o Used after the catch portion of try catch block 373 | o Used to “clean up” no matter what happens in try block, it will always execute 374 | o Commonly used to close files, or close database connections 375 | - Finalize() 376 | o Invoked before garbage collection, allowing it to clean up its state 377 | 378 | ArrayList vs LinkedList 379 | - If you need to get data in a sequential order then use LinkedList 380 | - If you need to insert elements anywhere at anytime use linked list 381 | - Linkedlist does not support most optimized searches like binary search so use ArrayList 382 | - If you know the size of your data ArrayList could be better, if you don’t then use LinkedList because it allows for expansion 383 | 384 | String vs StringBuffer vs StringBuilder 385 | - String – Use if string will stay the same 386 | o Immutable, one created cannot be changed, if value is changed a new object is created 387 | o Strings are stored in the Constant String Pool 388 | o String cannot be used by two threads simultaneously 389 | - StringBuffer – Use if it will change and be needed to run concurrently 390 | o Mutable which means we can change the value of the object 391 | o Stored in the heap 392 | o Same methods as StringBuilder, BUT StringBuffer methods as synchronized, therefore 393 | thread safe. However StringBuffer is slower than StringBuilder because of this 394 | - StringBuilder – Use if it will change and will not be used concurrently 395 | o Basically, the same as StringBuffer except it is not thread safe, making it faster 396 | 397 | Rules and differences of Overloading and overriding 398 | - Overloading 399 | o Method signature must be different, different types,/amount of parameters 400 | o If you only change the return type it should return an error 401 | o You can overload a static method 402 | - Overriding 403 | o Name and return type must be the same 404 | o Method signature should also be the same 405 | o Must be overridden in a subclass 406 | o Cannot increase security level, can only keep the same or reduce 407 | ▪ Protected to private not allowed protected to protected allowed protected to 408 | public allowed 409 | o Cannot override: Private, static or final methods 410 | - Differences 411 | o Overloading is during compile time, overriding is during runtime 412 | o Can overload in the same class, can only override a method in its subclass 413 | o Overloaded methods are fast compared to overridden methods in java 414 | 415 | ClassLoader 416 | - When you run a java program it gets converted in to a .class file which is basically byte code of 417 | the .java file. The ClassLoader is responsible to load that class file from the file system (or where 418 | ever its located). 419 | o Three types of class loaders: Bootstrap, Extension, and System class loader 420 | 421 | What is double checked locking in Singleton 422 | - Singleton means we can only create one instance of that class 423 | - Double Checked Locking is how java ensures that that at any cost only one instance is created 424 | o If in a multi-threaded environment DCL may not be reliable so be sure to use 425 | synchronized keyword in this scenario 426 | 427 | --------------------------------------------------------------------------------