Preview only show first 10 pages with watermark. For full document please download
Document 94595
-
Rating
-
Date
January 2018 -
Size
5.7MB -
Views
2,338 -
Categories
Transcript
® Java Programming Interviews Exposed Noel Markham Java® Programming Interviews Exposed Published by John Wiley & Sons, Inc. 10475 Crosspoint Boulevard Indianapolis, IN 46256 www.wiley.com Copyright © 2014 by John Wiley & Sons, Inc., Indianapolis, Indiana Published simultaneously in Canada ISBN: 978-1-118-72286-2 ISBN: 978-1-118-72292-3 (ebk) ISBN: 978-1-118-72288-6 (ebk) Manufactured in the United States of America 10 9 8 7 6 5 4 3 2 1 No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior written permission of the Publisher, or authorization through payment of the appropriate per-copy fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax (978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax (201) 748-6008, or online at http://www.wiley.com/go/permissions. Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or warranties with respect to the accuracy or completeness of the contents of this work and specifically disclaim all warranties, including without limitation warranties of fitness for a particular purpose. No warranty may be created or extended by sales or promotional materials. The advice and strategies contained herein may not be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in rendering legal, accounting, or other professional services. If professional assistance is required, the services of a competent professional person should be sought. Neither the publisher nor the author shall be liable for damages arising herefrom. The fact that an organization or Web site is referred to in this work as a citation and/or a potential source of further information does not mean that the author or the publisher endorses the information the organization or website may provide or recommendations it may make. Further, readers should be aware that Internet websites listed in this work may have changed or disappeared between when this work was written and when it is read. For general information on our other products and services please contact our Customer Care Department within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002. Wiley publishes in a variety of print and electronic formats and by print-on-demand. Some material included with standard print versions of this book may not be included in e-books or in print-on-demand. If this book refers to media such as a CD or DVD that is not included in the version you purchased, you may download this material at http://booksupport .wiley.com. For more information about Wiley products, visit www.wiley.com. Library of Congress Control Number: 2013958289 Trademarks: Wiley and the Wiley logo are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affiliates, in the United States and other countries, and may not be used without written permission. Java is a registered trademark of Oracle America, Inc. All other trademarks are the property of their respective owners. John Wiley & Sons, Inc. is not associated with any product or vendor mentioned in this book. For my wife and best friend, Rebecca. About the Author Noel Markham is a developer with almost 15 years’ experience using Java across financial, tech- nology, and gaming industries. Most recently, he has been working for startups in social gaming and digital entertainment. He has hosted interviews for all experienced levels of developer, from graduates to technical leaders, and has set up assessment centers in the UK and overseas to set up full development teams. About the Contributing Author Greg Milette is a programmer, author, consultant and entrepreneur who loves implementing great ideas. He’s been developing Android apps since 2009 when he released a voice controlled recipe app called Digital Recipe Sidekick. In between chatting with his Android device in the kitchen, Greg co-authored Professional Android Sensor Programming in 2012. Currently, he is the founder of Gradison Technologies, Inc, where he continues to develop great apps. About the Technical Editors Ivar Abrahamsen is a Software Engineer/Architect with over 15 years of experience working mostly with Java and more recently with Scala. He has worked for small and very large banks, telecoms, and consultancy companies in several countries. Ivar is currently a passionate and opinionated Tech Lead at a startup in Shoreditch, London. For more see flurdy.com. Rheese Burgess is a Technical Lead, working closely with recruitment to fill positions in his current workplace. He has worked with a number of languages and technologies, and has experience working in social, gaming, and financial products, ranging from startups to investment banks. Credits Executive Editor Business Manager Robert Elliott Amy Knies Project Editor Vice President and Executive Group Publisher Ed Connor Richard Swadley Technical Editors Ivar Abrahamsen Rheese Burgess Associate Publisher Senior Production Editor Project Coordinator, Cover Kathleen Wisor Todd Klemme Copy Editor Compositor Kim Cofer Maureen Forys, Happenstance Type-O-Rama Jim Minatel Editorial Manager Mary Beth Wakefield Proofreader Nancy Carrasco Freelancer Editorial Manager Rosemarie Graham Indexer Robert Swanson Associate Director of Marketing David Mayhew Cover Image ©iStockphoto.com/RapidEye Marketing Manager Ashley Zurcher Cover Designer Wiley Acknowledgments Thank you to James Summerfield for putting me in touch with Wiley to make this book happen. The team at Wiley has been so encouraging and supportive all through the writing process: Thank you to editors Ed Connor and Robert Elliott, and to the many others behind the scenes. Thank you to Greg Milette for writing the Android chapter. Thanks to my colleagues Rheese Burgess and Ivar Abrahamsen for taking the time to edit and review the book. Thank you to many of my other colleagues at Mind Candy, who have helped in some way: Sean Parsons, Olivia Goodman, Amanda Cowie, and to my good friend, Luca Cannas. My family: I thank my parents for their unending help and support with everything I’ve ever done. Finally, my wife, Rebecca: Thank you for putting up with seeing so little of me for these last few months, and for bringing me all of those cups of tea and other little treats, always smiling. Quite simply, it wouldn’t have happened without you. Contents Introduction xi Part I: Navigating the Interview Process Chapter 1: Dissecting Interview Types 3 Looking at the Phone Screening Process 4 Reviewing Technical Tests 5 Handling Face-to-Face Interviews 7 Making the Decision 8 Summary 9 Chapter 2: Writing a Noticeable Resume 11 How to Write a Resume and Cover Letter 11 Writing a Cover Letter 14 Summary 15 Chapter 3: Technical Test and Interview Basics 17 Technical Written Tests 17 At-Computer Tests 18 Face-to-Face Technical Interviews 19 Summary 21 Chapter 4: Writing Core Algorithms 23 Looking at Big O Notation 23 Sorting Lists 24 Searching Lists 32 Summary 33 Chapter 5: Data Structures 35 Lists 35 The Relationship between Arrays and Lists 36 Trees 39 Maps 45 Sets 48 Summary 49 CONTENTS Chapter 6: Design Patterns 51 Investigating Example Patterns 51 Commonly Used Patterns 60 Summary 64 Chapter 7: Implementing Popular Interview Algorithms 65 Implementing FizzBuzz 65 Demonstrating the Fibonacci Sequence 67 Demonstrating Factorials 71 Implementing Library Functionality 72 Using Generics 80 Summary 83 Part II: Core Java Chapter 8: Java Basics The Primitive Types Using Objects Java’s Arrays Working with Strings Understanding Generics Autoboxing and Unboxing Using Annotations Naming Conventions 87 88 91 98 98 101 107 109 111 Classes 111 Variables and Methods 111 Constants 111 Handling Exceptions 112 Using the Standard Java Library 115 Looking Forward to Java 8 119 Summary 120 Chapter 9: Testing with JUnit 123 The JUnit Test Life Cycle 125 Best Practices for Using JUnit 127 Eliminating Dependencies with Mocks 138 Creating System Tests with Behavior-Driven Development 143 Summary 146 viii CONTENTS Chapter 10: Understanding the Java Virtual Machine 147 Garbage Collection 147 Memory Tuning 149 Interoperability between the JVM and the Java Language 152 Summary 157 Chapter 11: Concurrency 159 Using Threads 159 Working with Concurrency 165 Actors 169 Summary 174 Part III: Components and Frameworks Chapter 12: Integrating Java Applications with Databases 177 SQL: An Introduction 177 JDBC: Combining Java and the Database 191 Testing with In-Memory Databases 198 Summary 199 Chapter 13: Creating Web Applications 201 Tomcat and the Servlet API 201 Jetty 207 Play Framework 213 Summary 218 Chapter 14: Using HTTP and REST 221 The HTTP Methods 221 HTTP Clients 224 Creating HTTP Services Using REST 226 Summary 230 Chapter 15: Serialization 231 Reading and Writing Java Objects 231 Using XML 234 JSON 240 Summary 243 ix CONTENTS Chapter 16: The Spring Framework 245 Core Spring and the Application Context 245 Spring JDBC 255 Integration Testing 259 Spring MVC 262 Summary 269 Chapter 17: Using Hibernate 271 Using Hibernate Summary 284 Chapter 18: Useful Libraries 287 Removing Boilerplate Code with Apache Commons 287 Developing with Guava Collections 290 Using Joda Time 296 Summary 300 Chapter 19: Developing with Build Tools 301 Building Applications with Maven 301 Ant 309 Summary 311 Chapter 20: Android 313 Basics 314 Components 314 Intents 315 Activities 318 BroadcastReceivers 321 Services 322 User Interface 326 Persistence 333 Android Hardware 336 Summary 340 Appendix: Introducing Scala 341 Index 353 x Introduction Interviews can be overwhelming for some, especially when you are being examined, one to one, on your technical abilities. This book has been designed to give you guidance and preparation for finding your next job as a Java developer. It has been written to help you overcome any sense of fear or worry around Java programming interviews by giving you enough material to practice with so that you can feel confident about any questions you might be asked. Overview of the Book and Technology This book is based on Java SE 7. If you are an experienced Java developer, but not up to date with Java 7, following are some new language features and APIs that have been introduced. The Diamond Operator Where possible, the compiler can infer the type of a generic instance. This means you can write List", parameterName, Arrays.asList(parameterMap.get(parameterName)))); } IOUtils.write(output, response.getOutputStream()); If you were to send a request with the query string a=123&b=asdf&a=456, then this would produce the output: b: [asdf]
a: [123, 456]
Notice how the values for the a key were collated, as that key appeared more than once. As this functionality is part of the Servlet API, it is available to any application container that supports the Servlet API. This includes Tomcat, and Jetty. Jetty Jetty has been designed to be lightweight and easy to use. You can even create and run servers purely in Java code, with no configuration. How can you create a running web application inside a Java class? You can configure Jetty to run in several lines of code. Listing 13-4 shows two classes: one to start a server and the other to define how that server responds to requests. Listing 13-4: Defining a Jetty server in code public class JettyExample { public static void main(String args[]) throws Exception { final Server jettyServer = new Server(8080); jettyServer.setHandler(new EchoHandler()); jettyServer.start(); continues 208 ❘ CHAPTER 13 Creating Web Applications Listing 13-4 (continued) jettyServer.join(); } } class EchoHandler extends AbstractHandler { @Override public void handle(String target, Request baseRequest, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); baseRequest.setHandled(true); final ServletInputStream requestInputStream = request.getInputStream(); final ServletOutputStream responseOutputStream = response.getOutputStream(); IOUtils.copy(requestInputStream, responseOutputStream); } } This code configures a server to respond to any client with the same body of the request. The HTTP POST and PUT methods have bodies, so requests with these methods will respond appropriately. Performing HTTP Requests A web browser is fine for performing requests, but to make a POST, PUT, or anything other than a GET request will require you to write a small amount of HTML, and perhaps use the help of a JavaScript library such as JQuery. You will find that using a dedicated HTTP client will make it easier to create and debug HTTP requests. UNIX operating systems (including Mac OS X) ship with the command-line client curl. The following line demonstrates its use for the server created in Listing 13-4: > curl -X PUT -d "Hello World" http://localhost:8080 This will respond with the same “Hello World.” It will not have a trailing newline. For a graphical HTTP client, the Google Chrome plug-in called Postman has a rich feature set and an intuitive user interface. Chapter 14 covers using HTTP clients within Java code, and also looks at the HTTP methods. Jetty ❘ 209 The final line of the handle method in the EchoHandler is a utility method from the Apache Commons IO library for connecting InputStreams to OutputStreams. The Apache Commons library is covered in Chapter 18. Extending the AbstractHandler class is a Jetty-specific implementation, and though this may be fine for your needs, it also ties your code to the Jetty platform. Rather than using Jetty’s handlers, you can implement your specific behavior as a servlet. Listing 13-5 shows two classes: the Jetty configuration in code and the implementation of the HttpServlet class. Listing 13-5: Using Jetty with the Servlet API public class JettyServletExample { public static void main(String[] args) throws Exception { final Server jettyServer = new Server(8080); final ServletHandler servletHandler = new ServletHandler(); jettyServer.setHandler(servletHandler); servletHandler.addServletWithMapping(EchoServlet.class, "/*"); jettyServer.start(); jettyServer.join(); } } public class EchoServlet extends HttpServlet { @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/plain"); response.setStatus(HttpServletResponse.SC_OK); final ServletInputStream requestInputStream = request.getInputStream(); final ServletOutputStream responseOutputStream = response.getOutputStream(); IOUtils.copy(requestInputStream, responseOutputStream); } } Jetty’s API has a specific handler for dealing with servlets. This means that it is possible to use both Jetty-specific handlers and servlet implementations in the same code. The following snippet shows an example: final HandlerList handlers = new HandlerList(); handlers.setHandlers(new Handler[] { jettyHandler, servletHandler }); jettyServer.setHandler(handlers); Note that this implementation of the same functionality is more restricted than the implementation using only Jetty’s handlers: it will only respond to POST requests. To perform the same action for another method, say PUT, the doPut method should be overridden too: 210 ❘ CHAPTER 13 Creating Web Applications @Override protected void doPut(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } You can see from the main method that different servlets can be mapped to different contexts, much like you would do inside a web.xml deployment descriptor: servletHandler.addServletWithMapping(AppServlet.class, "/app"); servletHandler.addServletWithMapping(AdminServlet.class, "/admin"); How can you perform integration tests against a running web server? The simplicity and flexibility of Jetty and its capability to configure and run within Java code makes it an ideal candidate as a server for use within integration tests, even if your production servlet container is different. Listing 13-6 is a JUnit test running against the EchoServlet defined in Listing 13-5. Listing 13-6: Testing servlets with Jetty and JUnit public class JettyJUnitTest { private static Server jettyServer; @BeforeClass public static void startJetty() throws Exception { jettyServer = new Server(8080); final ServletHandler servletHandler = new ServletHandler(); jettyServer.setHandler(servletHandler); servletHandler.addServletWithMapping(EchoServlet.class, "/echo/*"); jettyServer.start(); } @Test public void postRequestWithData() throws IOException { final HttpClient httpClient = new DefaultHttpClient(); final HttpPost post = new HttpPost("http://localhost:8080/echo/"); final String requestBody = "Hello World"; post.setEntity(new StringEntity(requestBody)); final HttpResponse response = httpClient.execute(post); final int statusCode = response.getStatusLine().getStatusCode(); final InputStream responseBodyStream = response.getEntity().getContent(); final StringWriter stringWriter = new StringWriter(); IOUtils.copy(responseBodyStream, stringWriter); final String receivedBody = stringWriter.toString(); assertEquals(200, statusCode); Jetty ❘ 211 assertEquals(requestBody, receivedBody); } @AfterClass public static void stopJetty() throws Exception { jettyServer.stop(); } } A new server is started when this test suite is created, and the server is stopped once all the tests are run. For this implementation, the server holds no state, so it is not necessary to create a new server for each test run. Should you require a new server for each test run, the server could be started in a @Before annotated method. Note that inside the test method, there are no references to Jetty, nor any code related to the server implementation; this is only testing the behavior of the server over the HTTP protocol. Apache’s HTTP client API is used here, and again, Apache’s Commons IO API simplifies reading the response InputStream and converting to a string. Although only one test has been defined here, you can certainly think of more test cases for this servlet, such as different HTTP methods, or making requests with no data. How can you perform active development against a local application server? Jetty has a Maven plug-in, which allows for easy running of web applications built from a Maven project. You can set the Maven Jetty plug-in for the project by adding the plug-in to the project’s POM:
The request parameters for this page:
- @for((param, values) <- queryString) {
- @param : @for(value <- values) { @value } }