0%

Backwards Compatibility

Java is almost unique in being able to run code from 25 years ago on a modern version of Java. The language developers take backwards compatibility very seriously, and because of this many organisations are happy to make Java their primary development platform, knowing that the code will still run on the JVM for years to come.

Maturity

There are plenty of advantages to having been around for a long time. For the last 25 years, developers have been writing applications in Java for a huge range of industries and business types, and for different platforms. Meanwhile, over these 25 years, developers have been learning Java in schools, universities, boot camps, and on the job. This has created a large ecosystem that has had time to learn from experience and continues to grow. Java, and the problems it can solve, is well documented and well supported by vendors and non-profit organisations and individuals. Very importantly for developers like us, the maturity and broad adoption of Java means there are plenty of jobs for developers who want to code in Java!

Constant Improvement

In contrast to backwards compatibility and maturity, is the evolution of the platform and the language. Since 2017 (Java 9) there’s been a new release every six months, which has enabled a steady stream of changes and improvements to the language. Combined with Preview Features, the language is able to experiment with new syntax, get feedback from developers, and then standardise new features that really work well for those who use the language.

Balance

Java has a difficult balance to strike between backwards compatibility and embracing the future. The current approach of valuing backwards compatibility and releasing every six months, but with a Long Term Support release every three years, seems to strike the right balance. The language is able to evolve by providing warnings for deprecated features that will be removed, and by having replacements for anything that might go away.

Those who wish for extra stability can stay on a Long Term Support release. To reduce their risk when it does come time to upgrade, they could be regularly testing against every new release. Those who are happy to upgrade every six months can update to the latest version of Java every time it comes out. Developers who want to try out new syntax even before it’s standardised can enable preview features, and those who want to do so as soon as possible can even use the Early Access release of a version that’s not out. Teams using modern versions of Java really can have the best of all worlds.

Standards

Standards might not be as exciting to a developer as language features, but having standards for Java, for Java EE and Jakarta EE, and for common use-cases that developers run into, does make a developer’s life easier. Understanding how to use JDBC to talk to a database means that we don’t have to care about how the database driver is implemented, the way we interact with it is always the same. The JCP is one of the processes used to determine standards for Java.

The Java Language Specification covers what Java-the-language looks like and how the compiler should work. It includes the Java Memory Model, which can help us to predict how an application might behave, regardless of JVM or hardware. The Java Virtual Machine Specification covers the lower-level details down in the JVM. These specifications enable JDKs distributed by different vendors, running on different platforms, to behave in specified, predictable ways. Which leads us to…

Write Once Run Anywhere

WORA was one of the original ideas behind Java, which seems so obvious these days that we might not even realise how ground-breaking it was. I remember working for a very, very large organisation who, back in 2002, switched from their previous technology stack to Java simply because they had a lot of different hardware lying around, and being able to run new Java applications on it instead of having to buy specific hardware for applications was one of the main reasons they moved all their development to Java. In this day and age of Cloud this might seem less relevant, but in fact just because we don’t always see WORA in action does not mean we’re not still taking advantage of it. And of course, if you’re using IntelliJ IDEA (or NetBeans) you’re taking advantage of WORA on the desktop.

Performance

It sometimes comes as a surprise to those who are less familiar with Java, but Java is a very high-performance language. It’s a mature platform that has 25 years of performance improvements; numerous garbage collectors with different performance profiles; and the JVM optimises our code at runtime for our real production use-cases far better than most human developers ever could. Java is used extensively in the finance world, for example, which depends on low-latency transactions and predictable performance.

Memory Management and Garbage Collection

Automatic Garbage Collection is something else that, 25 years on, we generally take for granted. We don’t have to think about how memory is allocated in our applications, or how to free it. Each JVM has one or more different GC algorithms, so we can pick one that works well for our application without having to concern ourselves too much with the internals, we can just get on with writing the business logic for our applications.

Observability and Management

If we are interested in what’s going on while our application is running, there are a huge number of tools available to us. Many of them are even free, particularly since Java Flight Recorder and Mission Control are now part of OpenJDK (since Java 11). Tools like JMX even allow us to dynamically manage our applications too.

The Java Virtual Machine (JVM)

Many of the features we’ve just mentioned are features of the JVM, but we specifically want to call out the JVM, and the fact that it’s separate from Java-the-language. There are many reasons to love the JVM, including some of the things we’ve already covered: WORA, runtime optimisations, performance, vendor choice, etc., much of which is made possible because of standards and specifications. It’s important that the JVM is separate from Java-the-language, too. It means different languages can be built upon the platform, taking advantage of all the great features of the JVM we’ve just mentioned while providing different types of syntax and language features.

Other JVM Languages

One of the reasons Java survived, even thrived, in those quiet years between Java 6 and 8 (Java 7 has some great features but it didn’t feel like a big release for Java developers) is because of the other JVM languages. At JetBrains of course our favourite is Kotlin, but the JVM is a platform for other popular languages like Groovy, Scala, Clojure and JRuby, and a huge number of other new and re-implemented languages. In many cases, interoperability between these languages and classic Java helps us to embrace and leverage this variety.

Libraries and Frameworks

One of the most compelling arguments is the huge amount of choice of libraries and frameworks we have, many of which are Open Source and free to use. Popular frameworks like Spring, and Spring Boot in particular, make it easy to create anything from small services to large and complex enterprise applications. Standards mean that often it’s not hard to understand and use a library when we’ve been using something similar in another context. The maturity of Java, and the community’s early adoption of open source, means that there’s usually an existing solution for standard problems; there’s no need to re-invent the wheel. It also means that since many of these solutions have been around, and in use, for a long time: they’re well tested, well understood, and well documented.

Build Tools and Dependency Management

Long gone are the days when a poor developer had to search on the internet for some unknown JAR file containing some class that the code they are trying to run apparently requires. Maven and Gradle, in particular, made it easy to build and deploy an application, of course, but also to set up a project in a standard way with all the required dependencies. It’s straightforward to start coding in either a new or existing project. Public repositories like Maven Central and Bintray give us well-known places to find (and publish) libraries.

JUnit and Automated Testing

JUnit was created in 1997 so is nearly as old as Java itself! It is by far the most common automated testing framework in the Java world, and both JUnit and TestNG are shipped with IntelliJ IDEA since it’s assumed a testing framework will be needed with any new Java project. It’s likely that modern testing frameworks for a whole range of languages are based on the ideas we now take for granted from JUnit. The Java community’s culture of automated testing owes a lot to this one library.

IDEs

This is the IntelliJ IDEA blog, we weren’t going to forget this one! Whether you believe the verbosity of Java requires an IDE, or that actually Java can really leverage an IDE because of its static typing, the fact is that Java developers love their IDEs (and we love you!). Learning to use an IDE effectively (whether it’s IntelliJ IDEA, Eclipse, or NetBeans) can significantly improve a developer’s productivity, via: code completion and generation, running tests, debugging, navigation, and a bunch of other features. Java developers are usually extremely enthusiastic about the benefits an IDE brings.

Community

The Java Community is a large, mature, vibrant, and welcoming community. There are Java User Groups in many cities worldwide, and a Virtual Java User Group if you can’t get to a physical meetup. The Java Champions are recognised technical leaders in the Java world who became known for sharing things that are useful or interesting for Java and JVM developers. Java has a huge Open Source community, including the JDK itself via OpenJDK. The Java Community values learning, teaching, and constant improvement, cares about standards and “best practice”, and is pragmatic about how to apply these in a real-world environment.

People

The Community is made up of people, of course, but when I asked what developers value most about Java, many of them specifically called out individuals in the Java world who had impacted them. These range from colleagues and teachers, to people like Brian Goetz, Angie Jones, Georges Saab, Mala Gupta, Venkat Subramaniam. Some people even mentioned me. Personally, I came to Java because I learnt it at university and there were plenty of jobs, but I stayed because I love the people and the help and support I’ve had from them.

Javadoc and Documentation

Java makes API documentation a key part of the language via Javadoc. The three different types of comments (Javadoc, block and line) clearly indicates what sort of commentary a developer is leaving. Javadoc specifically encourages developers to leave helpful documentation for other developers who call a method, or use a class or package. If a developer cannot find detailed tutorial information on a library or piece of code, there’s usually Javadoc that can help point them in the right direction.

In addition, the Java ecosystem generally seems to expect (and provide) good quality documentation for developers. Prospective committers to open source projects are encouraged to submit pull request of Javadoc comments or other documentation, and developers all over the world ask and answer questions on StackOverflow, or blog about solutions to specific problems.

Open Source

Not only did the Java community embrace open source early on, but now the JDK itself is open source too via OpenJDK. Open source makes it easier for multiple vendors, and individuals, to be involved and collaborate. It’s also fascinating to be able to look at the code of Java itself. Open source code provides a great opportunity for developers like us to learn from people who have already done all the hard work thinking about and solving complicated problems.

Free

The Java platform and many of the most popular tools used in the Java ecosystem don’t require a developer (or often even a profit-making organisation) to pay money to use them. Even after Oracle changed its licensing and support in Java 11 they (and many other vendors) still provided a way to use the language for free in production. The open source projects, build tools, and IDEs already mentioned in this article are all either free or have a free option. This makes Java appealing for developers getting started with coding, and for organisations of all sizes who need to build software while keeping an eye on the budget.

Object-Oriented

Object-oriented programming is not the only game in town, of course, and every paradigm has its advantages and disadvantages. Java was designed as an OO language right from the start, and many examples of design patterns and other coding best practice for OO are demonstrated in Java. If you want an object-oriented programming language, Java should be high on your list of ones to try.

Evolution and Adaptation

Java was, and still is, an object-oriented programming language. But it has also successfully adopted some concepts from functional programming (like lambda expressions and immutable data structures) and made them work nicely within the OO paradigm. Type inference (for example var) allows us to still have the benefits of a statically typed language, but with less boilerplate. Computer science is still a relatively young discipline, yet as we learn things they can be applied to our existing tools. Java (the language and the whole ecosystem) is constantly evolving according to new trends and new “best practices”, and also as a result of seeing how things work out in the real world.

Java also gets to benefit from syntax and ideas from other JVM languages, to see what works and what perhaps might not fit in a classic Java world. Even the processes and tools that Java uses to evolve and grow, such as the JCP and OpenJDK, are also adapting themselves to stay relevant in this constant evolution. This evolution and adaptation is part of the careful balance Java has to strike.

Focus on Readability

Java code is often readable, even for non-Java programmers. The language leans towards being more verbose rather than over-concise, which makes it easier to reason about Java code when we’re reading it. The language developers have not implemented features like operator overloading, as they feel it’s important to not be surprised by unexpected custom behaviour. There’s a tendency to avoid “magic” in the language and the frameworks – although some frameworks will use things like Convention over configuration to do things without a developer having to be imperative about it. There’s definitely been a move away from,for example, doing lots of AOP with annotations, and more towards using annotations for documentation and static analysis checks. The community and ecosystem tend to like standards and “best practice”, so Java code often follows similar sorts of rules even on very different projects.

Language Features

We’ve covered 23 Things We Like About Java but haven’t mentioned a single feature! To be honest, it’s because limiting ourselves to just 25 features seemed extremely difficult, and also because lots of the things we love about Java are not about the syntax or features. We’d like to give an honourable shout out to some of developers’ favourite features:

  • Collections API: it’s been with us a long time and served us well!
  • Convenience factory methods for collections: makes creating unmodifiable collections so much easier.
  • Streams API: a very nice addition to the collections API, and great to see it evolving even since Java 8. Parallel streams added a new way to utilise modern hardware.
  • Lambda Expressions: particularly useful with the Streams API, but very handy in its own right.
  • Optional: a nice way to express that a method might not give you something (and stops us having to protect against NullPointerExceptions!). Really nice to see each improvement to Optional since Java 8 as well.
  • java.time: the latest API for working with date and time is a welcome improvement
  • Checked exceptions: people are divided on checked vs runtime exceptions, but at least checked exceptions are there for those who wish to use them.
  • Annotations: annotations are like (among other things) documentation that the compiler can check, or notes for a framework to do some heavy lifting.
  • JShell: now we can play with Java in a REPL
  • var: type inference helps reduce code noise if used sensibly
  • Access modifiers and modularity: Java makes it easy (even more so since Java 9) to be explicit about which code can access which fields, methods, classes, and modules.
  • Switch expressions: now if we use switch it’s a lot less ugly!
  • Helpful NullPointerExceptions: who doesn’t love a good NullPointerException? Now the exceptions give developers much more useful information about what was null.
  • Preview features: we love preview features! We’re very excited about Records; Pattern matching for instanceof; and Text Blocks.

Workout Routine for Category I

The goal of category I is to work up to 16 miles per week of running. Then—and only then—you can continue on to the category II exercise. Category I is a nine-week buildup program.

Running Schedule Category I

  • Weeks 1 and 2: 2 miles per day, 8:30 pace, Monday, Wednesday and Friday (6 miles total for the week)
  • Week 3: No running as there is a high risk of stress fractures
  • Week 4: 3 miles per day,Monday, Wednesday and Friday (9 miles total for the week)
  • Week 5 and 6: Monday 2 miles, Tuesday 3 miles, Thursday 4 miles, Friday 2 miles (11 miles total for the week)
  • Weeks 7, 8, and 9: Monday 4 miles, Tuesday 4 miles, Thursday 5 miles, Friday 3 miles (16 miles total for the week)

Physical Training (PT) Schedule Category I

Perform these exercises Monday, Wednesday, and Friday

Week 1

  • Pushups: Four sets of 15 repetitions
  • Situps: Four sets of 20 repetitions
  • Pullups: Three sets of three repetitions

Week 2

  • Pushups: Five sets of 20 repetitions
  • Situps: Five sets of 20 repetitions
  • Pullups: Three sets of three repetitions

Weeks 3 and 4

  • Pushups: Five sets of 25 repetitions
  • Situps: Five sets of 25 repetitions
  • Pullups: Three sets of four repetitions

Weeks 5 and 6

  • Pushups: Six sets of 25 repetitions
  • Situps: Six sets of 25 repetitions
  • Pullups: Two sets of eight repetitions

Weeks 7 and 8

  • Pushups: Six sets of 30 repetitions
  • Situps: Six sets of 30 repetitions
  • Pullups: Two sets of 10 repetitions

Week 9

  • Pushups: Six sets of 30 repetitions
  • Situps: Six sets of 30 repetitions
  • Pullups: Three sets of 10 repetitions

For best results, alternate exercises. Do a set of pushups, then a set of situps, followed by a set of pull ups, immediately with no rest. Then progress again with the next sets of each exercise.

Swimming Schedule Category I

Sidestroke with no fins four to five days a week

  • Weeks 1 and 2: Swim continuously for 15 minutes
  • Weeks 3 and 4: Swim continuously for 20 minutes
  • Weeks 5 and 6: Swim continuously for 25 minutes
  • Weeks 7 and 8: Swim continuously for 30 minutes
  • Week 9: Swim continuously for 35 minutes

If you have no access to a pool, ride a bicycle for twice as long as you would swim. If you do have access to a pool, swim every day available. Swim four to five days a week for 200 meters in one session as your initial workup goal. Also, you want to develop your sidestroke on both the left and the right side. Try to swim 50 meters in one minute or less.

Workout Routine for Category II (Advanced Level) Navy Seals

The Navy SEALs Category II workout routine is a more intense workout designed for those who have been involved with a routine physical fitness training program or those who have completed the requirements of category I workout routine. Do not attempt this workout unless you can complete week 9 of category I workout.

Running Schedule Category II

Run the stated number of miles Monday, Tuesday, Thursday, Friday, and Saturday.

  • Weeks 1 and 2: (3/5/4/5/2) miles (19 miles per week total)
  • Weeks 3 and 4: (4/5/6/4/3) miles (22 miles per week total)
  • Week 5: (5/5/6/4/4) miles (24 miles per week total)
  • Week 6: (5/6/6/6/4) miles (27 miles per week total)
  • Week 7: (6/6/6/6/6) miles (30 miles per week total)

For weeks 8 and 9 and beyond, it is not necessary to increase the distance of the runs; work on the speed of your 6-mile runs and try to get them down to 7:30 per mile or lower. If you wish to increase the distance of your runs, do it gradually—no more than 1 mile per day increase for every week beyond week 9.

Physical Training Schedule Category II

Complete these sets and repetitions Monday, Wednesday, and Friday

Weeks 1 and 2

  • Pushups: Six sets of 30 repetitions
  • Situps: Six sets of 35 repetitions
  • Pullups: Three sets of 10 repetitions
  • Dips: Three sets of 20 repetitions

Weeks 3 and 4

  • Pushups: 10 sets of 20 repetitions
  • Situps: 10 sets of 25 repetitions
  • Pullups: Four sets of 10 repetitions
  • Dips: 10 sets of 15 repetitions

Week 5

  • Pushups: 15 sets of 20 repetitions
  • Situps: 15 sets of 25 repetitions
  • Pullups: Four sets of 12 repetitions
  • Dips: 15 sets of 15 repetitions

Week 6

  • Pushups: 20 sets of 20 repetitions
  • Situps: 20 sets of 25 repetitions
  • Pullups: Five sets of 12 repetitions
  • Dips: 20 sets of 15 repetitions

These workouts are designed for long-distance muscle endurance. Muscle fatigue will gradually take a longer and longer time to develop doing high repetition workouts. For best results, alternate exercises each set, in order to rest that muscle group for a short time.

Pyramid Workouts

After you have reached your Category I and II standards, you can do a pyramid workout with any exercise to vary your workout. The object is to slowly build up to a goal, then build back down to the beginning of the workout. For instance, pullups, situps, pushups, and dips can be alternated as in the above workouts, but this time choose a number to be your goal and build up to that number. Each number counts as a set. Work your way up and down the pyramid.

For example, if your goal is five repetitons, the number of repetitions you would do for each exercise would be:

  • Pullups: 1,2,3,4,5,4,3,2,1
  • Pushups: 2,4,6,8,10,8,6,4,2 (two times the number of pullups)
  • Situps: 3,6,9,12,15,12,9,6,3 (three times the number of pullups)
  • Dips: Same as pushups

Swimming Workouts Category II

Swim four to five days per week

  • Weeks 1 and 2: Swim continuously for 35 minutes.
  • Weeks 3 and 4: Swim continuously for 45 minutes with fins.
  • Week 5: Swim continuously for 60 minutes with fins.
  • Week 6: Swim continuously for 75 minutes with fins.

At first, to reduce initial stress on your foot muscles when starting with fins, alternate swimming 1000 meters with fins and 1000 meters without them. Your goal should be to swim 50 meters in 45 seconds or less.

Stretching and Physical Training
Since Monday, Wednesday, and Friday are devoted to PT, it is wise to devote at least 20 minutes on Tuesday, Thursday, and Saturday to stretching. You can stretch for 15 minutes before a workout, after warming up, stretch after a workout, or do stretching as its own separate activity. A good way to do stretching is to start at the top and go to the bottom. Stretch to tightness, not to pain; hold for 10 to 15 seconds. Do not bounce. Stretch every muscle in your body from the neck to the calves, concentrating on your thighs, hamstrings, chest, back, and shoulders.

作者是书籍质量的一个主要保证。《人月神话》的作者:Frederick Phillips Brooks(以下简称 Brooks)。这位老兄最牛X的成就是在60年代(那时他才【29岁】)主持并完成了一个同样很牛X的IBM 360系统的开发。
  IBM 360后来被誉为是人类从原子能时代进入信息时代的标志。该项目不光具有历史意义,而且在软件工程方面非常有代表性(因为其规模和复杂度)。为了给大伙儿加深印象,列举该项目的几个数据如下:
--------------------------------
软件人员总数  2000  四十年后,微软的Windows 2003团队也就5000人
软件总费用   5亿$  发明第一个原子弹的曼哈顿工程也不过才花20亿$
开发周期    4年
--------------------------------
  注意,上述仅仅是软件方面的统计。

  最终,IBM 360项目并没有完成全部的预定目标,但是对于这个史无前例的项目,居然没有中途夭折,本身已经算是奇迹了。后来,Brooks 在1975年(距今已30多年)把他所写的一些软件工程方面的随笔(很多都与 IBM 的360项目有关)整理出版,也就是我们今天点评的《人月神话》。

★本书的结构

  前面已经说了,Brooks 当年是把他写过的一些随笔整理出书的,所以书中的各个章节相对来说比较独立。因此你不一定按照排版的顺序来阅读。比如俺每次重读这本书都只是挑选其中一两个章节来看。

★本书的看点

  虽然本书的每个章节都称得上是经典,但限于篇幅,只把俺印象最深刻的几章介绍一下。

◇第2章 关于【人月】的误导性

  这是本书最有名气的章节。在本章,Brooks明确反对使用“人月”这个极具欺骗性的度量单位。因为“人月”这个称谓暗示着“人”和“月”是可以互换的。
  即使到今天为止,还是有大量的编程人员、测试人员、项目经理和软件公司老板在【错误地】使用“人月”来衡量软件开发的工作量,实际上,当某人宣称某工作量是6个人月时,这句话本身是没有太大意义的。一般来说,1个人干6个月的工作,6个人在1个月内几乎很难完成。所以俺在沟通工作量时,都会明确地讲清楚,需要几个人干几个月。
  另外,Brooks 根据人月的不可互换推导出一个怪论:向进度落后的项目增加人手会导致项目更加落后。这个怪论是如此出名,以至于后来被称为“Brooks 法则”。这个法则蛮有用滴,每当有上级领导企图通过增加人手来赶进度时(往往在项目后期),俺都会搬出这个法则来拒绝这种企图。

◇第3章 关于团队的组成

  为了解决前几章中提到的大型团队的种种困难,Brooks 提出了一种新的解决方案:把大型团队拆分为若干个类似于外科手术式的小团队。
  每个小团队有一名主程序员(类似于主刀医生),所有的问题分解和功能定义都通过主程序员来完成,以此来降低沟通成本。并且,每个主程序员配备若干个平庸的人帮他/她打下手,也很符合现实情况(还记得“二八原理系列”中提到的优秀人员和平庸人员的比例吗?)。具体的角色职责我就不细说了,书上都有。

◇第16、17章 关于【没有银弹】的真知灼见

  实际上第16章“没有银弹”的内容来自于作者在1986年作的报告,后来才加入书中。第17章“再论没有银弹”是20周年版加入的。
  据作者在本书的“20周年纪念版”中宣称,“没有银弹”是引发最多争议的章节。不过我个人认为:虽然引发最多争议,但是这两章却是全书最重要、最深刻且最有价值的章节。即使你从事的工作和软件工程无关,你也应该认真阅读它。
  Brooks 在第16章分析了软件开发的【根本性困难】(复杂性、非一致性、易变性和不可见性)和【次要性困难】。分析完根本性困难和次要性困难之后,作者断言:未来十年内,【不可能】有某种技术突破(银弹)能够彻底解决“根本性困难”,从而导致软件开发效率有数量级的提高。
  现在,时间已经过去了远远不止十年。在“没有银弹”发表之后,软件界冒出了数不清的新玩意儿(比如面向对象、组件技术、设计模式、CMM、UML、敏捷开发、RAD、等等),很多新玩意儿的创造者都号称他们发明了银弹。但实际上没有哪个新技术能够经受住时间的考验并真正获得银弹的称号。

★俺的建议

  啰嗦了这么多,最后来说说俺的几点建议:

  1. 如果你从来没有看过本书,那赶紧去找一本来,并全部读一遍(不一定要按顺序看)。
  2. 如果你以前看的是老版本,那赶紧去找来新版(20周年纪念版),并重点看看增补的4个章节。
  3. 如果你已经把新版全部看完,今后可以考虑定期(例如每隔一两年)再拿出来翻一翻。

What is Python?

Python is a high-level, interpreted, interactive and object-oriented scripting language. Python is designed to be highly readable. It uses English keywords frequently where as other languages use punctuation, and it has fewer syntactical constructions than other languages.

Name some of the features of Python.

Following are some of the salient features of python −

  • It supports functional and structured programming methods as well as OOP.
  • It can be used as a scripting language or can be compiled to byte-code for building large applications.
  • It provides very high-level dynamic data types and supports dynamic type checking.
  • It supports automatic garbage collection.
  • It can be easily integrated with C, C++, COM, ActiveX, CORBA, and Java.

What is the purpose of PYTHONPATH environment variable?

PYTHONPATH - It has a role similar to PATH. This variable tells the Python interpreter where to locate the module files imported into a program. It should include the Python source library directory and the directories containing Python source code. PYTHONPATH is sometimes preset by the Python installer.

What is the purpose of PYTHONSTARTUP environment variable?

PYTHONSTARTUP - It contains the path of an initialization file containing Python source code. It is executed every time you start the interpreter. It is named as .pythonrc.py in Unix and it contains commands that load utilities or modify PYTHONPATH.

What is the purpose of PYTHONCASEOK environment variable?

PYTHONCASEOK − It is used in Windows to instruct Python to find the first case-insensitive match in an import statement. Set this variable to any value to activate it.

What is the purpose of PYTHONHOME environment variable?

PYTHONHOME − It is an alternative module search path. It is usually embedded in the PYTHONSTARTUP or PYTHONPATH directories to make switching module libraries easy.

Is python a case sensitive language?

Yes! Python is a case sensitive programming language.

What are the supported data types in Python?

Python has five standard data types −

  • Numbers
  • String
  • List
  • Tuple
  • Dictionary

What is the output of print str if str = ‘Hello World!’?

It will print complete string. Output would be Hello World!.

What is the output of print str[0] if str = ‘Hello World!’?

It will print first character of the string. Output would be H.

What is the output of print str[2:5] if str = ‘Hello World!’?

It will print characters starting from 3rd to 5th. Output would be llo.

What is the output of print str[2:] if str = ‘Hello World!’?

It will print characters starting from 3rd character. Output would be llo World!.

What is the output of print str * 2 if str = ‘Hello World!’?

It will print string two times. Output would be Hello World!Hello World!.

What is the output of print str + “TEST” if str = ‘Hello World!’?

It will print concatenated string. Output would be Hello World!TEST.

What is the output of print list if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

It will print complete list. Output would be [‘abcd’, 786, 2.23, ‘john’, 70.200000000000003].

What is the output of print list[0] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

It will print first element of the list. Output would be abcd.

What is the output of print list[1:3] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

It will print elements starting from 2nd till 3rd. Output would be [786, 2.23].

What is the output of print list[2:] if list = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ]?

It will print elements starting from 3rd element. Output would be [2.23, ‘john’, 70.200000000000003].

What is the output of print tinylist * 2 if tinylist = [123, ‘john’]?

It will print list two times. Output would be [123, ‘john’, 123, ‘john’].

What is the output of print list1 + list2, if list1 = [ ‘abcd’, 786 , 2.23, ‘john’, 70.2 ] and ist2 = [123, ‘john’]?

It will print concatenated lists. Output would be [‘abcd’, 786, 2.23, ‘john’, 70.2, 123, ‘john’]

What are tuples in Python?

A tuple is another sequence data type that is similar to the list. A tuple consists of a number of values separated by commas. Unlike lists, however, tuples are enclosed within parentheses.

What is the difference between tuples and lists in Python?

The main differences between lists and tuples are − Lists are enclosed in brackets ( [ ] ) and their elements and size can be changed, while tuples are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be thought of as read-only lists.

What is the output of print tuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print complete tuple. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003).

What is the output of print tuple[0] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print first element of the tuple. Output would be abcd.

What is the output of print tuple[1:3] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print elements starting from 2nd till 3rd. Output would be (786, 2.23).

What is the output of print tuple[2:] if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 )?

It will print elements starting from 3rd element. Output would be (2.23, ‘john’, 70.200000000000003).

What is the output of print tinytuple * 2 if tinytuple = (123, ‘john’)?

It will print tuple two times. Output would be (123, ‘john’, 123, ‘john’).

What is the output of print tuple + tinytuple if tuple = ( ‘abcd’, 786 , 2.23, ‘john’, 70.2 ) and tinytuple = (123, ‘john’)?

It will print concatenated tuples. Output would be (‘abcd’, 786, 2.23, ‘john’, 70.200000000000003, 123, ‘john’).

What are Python’s dictionaries?

Python’s dictionaries are kind of hash table type. They work like associative arrays or hashes found in Perl and consist of key-value pairs. A dictionary key can be almost any Python type, but are usually numbers or strings. Values, on the other hand, can be any arbitrary Python object.

How will you create a dictionary in python?

Dictionaries are enclosed by curly braces ({ }) and values can be assigned and accessed using square braces ([]).

1
2
3
4
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}

How will you get all the keys from the dictionary?

Using dictionary.keys() function, we can get all the keys from the dictionary object.

1
print dict.keys()   # Prints all the keys

How will you get all the values from the dictionary?

Using dictionary.values() function, we can get all the values from the dictionary object.

1
print dict.values()   # Prints all the values

How will you convert a string to an int in python?

int(x [,base]) - Converts x to an integer. base specifies the base if x is a string.

How will you convert a string to a long in python?

long(x [,base] ) - Converts x to a long integer. base specifies the base if x is a string.

How will you convert a string to a float in python?

float(x) − Converts x to a floating-point number.

How will you convert a object to a string in python?

str(x) − Converts object x to a string representation.

How will you convert a object to a regular expression in python?

repr(x) − Converts object x to an expression string.

How will you convert a String to an object in python?

eval(str) − Evaluates a string and returns an object.

How will you convert a string to a tuple in python?

tuple(s) − Converts s to a tuple.

How will you convert a string to a list in python?

list(s) − Converts s to a list.

How will you convert a string to a set in python?

set(s) − Converts s to a set.

How will you create a dictionary using tuples in python?

dict(d) − Creates a dictionary. d must be a sequence of (key,value) tuples.

How will you convert a string to a frozen set in python?

frozenset(s) − Converts s to a frozen set.

How will you convert an integer to a character in python?

chr(x) − Converts an integer to a character.

How will you convert an integer to an unicode character in python?

unichr(x) − Converts an integer to a Unicode character.

How will you convert a single character to its integer value in python?

ord(x) − Converts a single character to its integer value.

How will you convert an integer to hexadecimal string in python?

hex(x) − Converts an integer to a hexadecimal string.

How will you convert an integer to octal string in python?

oct(x) − Converts an integer to an octal string.

What is the purpose of ** operator?

** Exponent − Performs exponential (power) calculation on operators. a**b = 10 to the power 20 if a = 10 and b = 20.

What is the purpose of // operator?

// Floor Division − The division of operands where the result is the quotient in which the digits after the decimal point are removed.

What is the purpose of is operator?

is − Evaluates to true if the variables on either side of the operator point to the same object and false otherwise. x is y, here is results in 1 if id(x) equals id(y).

What is the purpose of not in operator?

not in − Evaluates to true if it does not finds a variable in the specified sequence and false otherwise. x not in y, here not in results in a 1 if x is not a member of sequence y.

What is the purpose break statement in python?

break statement − Terminates the loop statement and transfers execution to the statement immediately following the loop.

What is the purpose continue statement in python?

continue statement − Causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating.

What is the purpose pass statement in python?

pass statement − The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.

How can you pick a random item from a list or tuple?

choice(seq) − Returns a random item from a list, tuple, or string.

How can you pick a random item from a range?

randrange ([start,] stop [,step]) − returns a randomly selected element from range(start, stop, step).

How can you get a random number in python?

random() − returns a random float r, such that 0 is less than or equal to r and r is less than 1.

How will you set the starting value in generating random numbers?

seed([x]) − Sets the integer starting value used in generating random numbers. Call this function before calling any other random module function. Returns None.

How will you randomizes the items of a list in place?

shuffle(lst) − Randomizes the items of a list in place. Returns None.

How will you capitalizes first letter of string?

capitalize() − Capitalizes first letter of string.

How will you check in a string that all characters are alphanumeric?

isalnum() − Returns true if string has at least 1 character and all characters are alphanumeric and false otherwise.

How will you check in a string that all characters are digits?

isdigit() − Returns true if string contains only digits and false otherwise.

How will you check in a string that all characters are in lowercase?

islower() − Returns true if string has at least 1 cased character and all cased characters are in lowercase and false otherwise.

How will you check in a string that all characters are numerics?

isnumeric() − Returns true if a unicode string contains only numeric characters and false otherwise.

How will you check in a string that all characters are whitespaces?

isspace() − Returns true if string contains only whitespace characters and false otherwise.

How will you check in a string that it is properly titlecased?

istitle() − Returns true if string is properly “titlecased” and false otherwise.

How will you check in a string that all characters are in uppercase?

isupper() − Returns true if string has at least one cased character and all cased characters are in uppercase and false otherwise.

How will you merge elements in a sequence?

join(seq) − Merges (concatenates) the string representations of elements in sequence seq into a string, with separator string.

How will you get the length of the string?

len(string) − Returns the length of the string.

How will you get a space-padded string with the original string left-justified to a total of width columns?

ljust(width[, fillchar]) − Returns a space-padded string with the original string left-justified to a total of width columns.

How will you convert a string to all lowercase?

lower() − Converts all uppercase letters in string to lowercase.

How will you remove all leading whitespace in string?

lstrip() − Removes all leading whitespace in string.

How will you get the max alphabetical character from the string?

max(str) − Returns the max alphabetical character from the string str.

How will you get the min alphabetical character from the string?

min(str) − Returns the min alphabetical character from the string str.

How will you replaces all occurrences of old substring in string with new string?

replace(old, new [, max]) − Replaces all occurrences of old in string with new or at most max occurrences if max given.

How will you remove all leading and trailing whitespace in string?

strip([chars]) − Performs both lstrip() and rstrip() on string.

How will you change case for all letters in string?

swapcase() − Inverts case for all letters in string.

How will you get titlecased version of string?

title() − Returns “titlecased” version of string, that is, all words begin with uppercase and the rest are lowercase.

How will you convert a string to all uppercase?

upper() − Converts all lowercase letters in string to uppercase.

How will you check in a string that all characters are decimal?

isdecimal() − Returns true if a unicode string contains only decimal characters and false otherwise.

What is the difference between del() and remove() methods of list?

To remove a list element, you can use either the del statement if you know exactly which element(s) you are deleting or the remove() method if you do not know.

What is the output of len([1, 2, 3])?

3.

What is the output of [1, 2, 3] + [4, 5, 6]?

[1, 2, 3, 4, 5, 6]

What is the output of [‘Hi!’] * 4?

[‘Hi!’, ‘Hi!’, ‘Hi!’, ‘Hi!’]

What is the output of 3 in [1, 2, 3]?

True

What is the output of for x in [1, 2, 3]: print x?

1
2
3
1
2
3

What is the output of L[2] if L = [1,2,3]?

3, Offsets start at zero.

What is the output of L[-2] if L = [1,2,3]?

1, Negative: count from the right.

What is the output of L[1:] if L = [1,2,3]?

2, 3, Slicing fetches sections.

How will you compare two lists?

cmp(list1, list2) − Compares elements of both lists.

How will you get the length of a list?

len(list) − Gives the total length of the list.

How will you get the max valued item of a list?

max(list) − Returns item from the list with max value.

How will you get the min valued item of a list?

min(list) − Returns item from the list with min value.

How will you get the index of an object in a list?

list.index(obj) − Returns the lowest index in list that obj appears.

How will you insert an object at given index in a list?

list.insert(index, obj) − Inserts object obj into list at offset index.

How will you remove last object from a list?

list.pop(obj=list[-1]) − Removes and returns last object or obj from list.

How will you remove an object from a list?

list.remove(obj) − Removes object obj from list.

How will you reverse a list?

list.reverse() − Reverses objects of list in place.

How will you sort a list?

list.sort([func]) − Sorts objects of list, use compare func if given.

What is lambda function in python?

‘lambda’ is a keyword in python which creates an anonymous function. Lambda does not contain block of statements. It does not contain return statements.

What we call a function which is incomplete version of a function?

Stub.

When a function is defined then the system stores parameters and local variables in an area of memory. What this memory is known as?

Stack.

A canvas can have a foreground color? (Yes/No)

Yes.

Is Python platform independent?

No

There are some modules and functions in python that can only run on certain platforms.

Do you think Python has a complier?

Yes

Yes it has a complier which works automatically so we don’t notice the compiler of python.

What are the applications of Python?

  1. Django (Web framework of Python).

  2. Micro Frame work such as Flask and Bottle.

  3. Plone and Django CMS for advanced content Management.

What is the basic difference between Python version 2 and Python version 3?

Table below explains the difference between Python version 2 and Python version 3.

S.No Section Python Version2 Python Version3
1. Print Function Print command can be used without parentheses. Python 3 needs parentheses to print any string. It will raise error without parentheses.
2. Unicode ASCII str() types and separate Unicode() but there is no byte type code in Python 2. Unicode (utf-8) and it has two byte classes −ByteBytearray S.
3. Exceptions Python 2 accepts both new and old notations of syntax. Python 3 raises a SyntaxError in turn when we don’t enclose the exception argument in parentheses.
4. Comparing Unorderable It does not raise any error. It raises ‘TypeError’ as warning if we try to compare unorderable types.

Which programming Language is an implementation of Python programming language designed to run on Java Platform?

Jython

(Jython is successor of Jpython.)

Is there any double data type in Python?

No

Is String in Python are immutable? (Yes/No)

Yes.

Can True = False be possible in Python?

No.

OS.

When does a new block begin in python?

A block begins when the line is intended by 4 spaces.

Write a function in python which detects whether the given two strings are anagrams or not.

1
2
3
4
5
6
7
8
def check(a,b):
if(len(a)!=len(b)):
return False
else:
if(sorted(list(a)) == sorted(list(b))):
return True
else:
return False

Name the python Library used for Machine learning.

Scikit-learn python Library used for Machine learning

What does pass operation do?

Pass indicates that nothing is to be done i.e. it signifies a no operation.

Name the tools which python uses to find bugs (if any).

Pylint and pychecker.

Write a function to give the sum of all the numbers in list?

Sample list − (100, 200, 300, 400, 0, 500)

Expected output − 1500

Program for sum of all the numbers in list is −

1
2
3
4
5
6
def sum(numbers):
total = 0
for num in numbers:
total+=num
print(''Sum of the numbers: '', total)
sum((100, 200, 300, 400, 0, 500))

We define a function ‘sum’ with numbers as parameter. The in for loop we store the sum of all the values of list.

Write a program in Python to reverse a string without using inbuilt function reverse string?

Program to reverse a string in given below −

1
2
3
4
5
6
7
8
9
10
def string_reverse(str1):

rev_str = ' '
index = len(str1) #defining index as length of string.
while(index>0):
rev_str = rev_str + str1[index-1]
index = index-1
return(rev_str)

print(string_reverse('1tniop'))

First we declare a variable to store the reverse string. Then using while loop and indexing of string (index is calculated by string length) we reverse the string. While loop starts when index is greater than zero. Index is reduced to value 1 each time. When index reaches zero we obtain the reverse of string.

Write a program to test whether the number is in the defined range or not?

Program is −

1
2
3
4
5
def test_range(num):
if num in range(0, 101):
print(''%s is in range''%str(num))
else:
print(''%s is not in range''%str(num))

Output −

test_range(101)

101 is not in the range

To test any number in a particular range we make use of the method ‘if..in’ and else condition.

Write a program to calculate number of upper case letters and number of lower case letters?

Test on String: ‘’Tutorials POINT’’

Program is −

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def string_test(s):

a = { ''Lower_Case'':0 , ''Upper_Case'':0} #intiail count of lower and upper
for ch in s: #for loop
if(ch.islower()): #if-elif-else condition
a[''Lower_Case''] = a[''Lower_Case''] + 1
elif(ch.isupper()):
a[''Upper_Case''] = a [''Upper_Case''] + 1
else:
pass

print(''String in testing is: '',s) #printing the statements.
print(''Number of Lower Case characters in String: '',a[''Lower_Case''])
print(''Number of Upper Case characters in String: '',a[''Upper_Case''])

Output −

string_test(‘’Tutorials POINT’’)

String in testing is: Tutorials POINT

Number of Lower Case characters in String: 8

Number of Upper Case characters in String: 6

We make use of the methods .islower() and .isupper(). We initialise the count for lower and upper. Using if and else condition we calculate total number of lower and upper case characters.

1. Overview

Before we get started with the implementation, it’s important to point out that the primary List and Set collection interfaces extend Collection but Map does not.

Simply put, the HashMap stores values by key and provides APIs for adding, retrieving and manipulating stored data in various ways. The implementation is based on the the principles of a hashtable, which sounds a little complex at first but is actually very easy to understand.

Key-value pairs are stored in what is known as buckets which together make up what is called a table, which is actually an internal array.

Once we know the key under which an object is stored or is to be stored, storage and retrieval operations occur in constant time, O(1) in a well-dimensioned hash map.

To understand how hash maps work under the hood, one needs to understand the storage and retrieval mechanism employed by the HashMap. We’ll focus a lot on these.

Finally, HashMap\ related questions are quite common in interviews, so this is a solid way to either prepare an interview or prepare for it.

2. The put() API

To store a value in a hash map, we call the put API which takes two parameters; a key and the corresponding value:

1
V put(K key, V value);

When a value is added to the map under a key, the hashCode() API of the key object is called to retrieve what is known as the initial hash value.

To see this in action, let us create an object that will act as a key. We will only create a single attribute to use as a hash code to simulate the first phase of hashing:

1
2
3
4
5
6
7
8
9
10
11
public class MyKey {
private int id;

@Override
public int hashCode() {
System.out.println("Calling hashCode()");
return id;
}

// constructor, setters and getters
}

We can now use this object to map a value in the hash map:

1
2
3
4
5
6
@Test
public void whenHashCodeIsCalledOnPut_thenCorrect() {
MyKey key = new MyKey(1);
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
}

Nothing much happening in the above code, but pay attention to the console output. Indeed the hashCode method gets invoked:

1
Calling hashCode()

Next, the hash() API of the hash map is called internally to compute the final hash value using the initial hash value.

This final hash value ultimately boils down to an index in the internal array or what we call a bucket location.

The hash function of HashMap looks like this:

1
2
3
4
static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

What we should note here is only the use of the hash code from the key object to compute a final hash value.

While inside the put function, the final hash value is used like this:

1
2
3
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

Notice that an internal putVal function is called and given the final hash value as the first parameter.

One may wonder why the key is again used inside this function since we have already used it to compute the hash value.

The reason is that hash maps store both key and value in the bucket location as a *Map.Entry* object.

As discussed before, all Java collections framework interfaces extend Collection interface but Map does not. Compare the declaration of Map interface we saw earlier to that of Set interface:

1
public interface Set<E> extends Collection<E>

The reason is that maps do not exactly store single elements as do other collections but rather a collection of key-value pairs.

So the generic methods of Collection interface such as add, toArray do not make sense when it comes to Map.

The concept we have covered in the last three paragraphs makes for one of the most popular Java Collections Framework interview questions. So, it’s worth understanding.

One special attribute with the hash map is that it accepts null values and null keys:

1
2
3
4
5
@Test
public void givenNullKeyAndVal_whenAccepts_thenCorrect(){
Map<String, String> map = new HashMap<>();
map.put(null, null);
}

When a null key is encountered during a *put* operation, it is automatically assigned a final hash value of *0*, which means it becomes the first element of the underlying array.

This also means that when the key is null, there is no hashing operation and therefore, the hashCode API of the key is not invoked, ultimately avoiding a null pointer exception.

During a put operation, when we use a key that was already used previously to store a value, it returns the previous value associated with the key:

1
2
3
4
5
6
7
8
9
@Test
public void givenExistingKey_whenPutReturnsPrevValue_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key1", "val1");

String rtnVal = map.put("key1", "val2");

assertEquals("val1", rtnVal);
}

otherwise, it returns null:

1
2
3
4
5
6
7
8
@Test
public void givenNewKey_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.put("key1", "val1");

assertNull(rtnVal);
}

When put returns null, it could also mean that the previous value associated with the key is null, not necessarily that it’s a new key-value mapping:

1
2
3
4
5
6
7
8
@Test
public void givenNullVal_whenPutReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.put("key1", null);

assertNull(rtnVal);
}

The containsKey API can be used to distinguish between such scenarios as we will see in the next subsection.

3. The get API

To retrieve an object already stored in the hash map, we must know the key under which it was stored. We call the get API and pass to it the key object:

1
2
3
4
5
6
7
8
9
@Test
public void whenGetWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", "val");

String val = map.get("key");

assertEquals("val", val);
}

Internally, the same hashing principle is used. The hashCode() API of the key object is called to obtain the initial hash value:

1
2
3
4
5
6
7
@Test
public void whenHashCodeIsCalledOnGet_thenCorrect() {
MyKey key = new MyKey(1);
Map<MyKey, String> map = new HashMap<>();
map.put(key, "val");
map.get(key);
}

This time, the hashCode API of MyKey is called twice; once for put and once for get:

1
2
Calling hashCode()
Calling hashCode()

This value is then rehashed by calling the internal hash() API to obtain the final hash value.

As we saw in the previous section, this final hash value ultimately boils down to a bucket location or an index of the internal array.

The value object stored in that location is then retrieved and returned to the calling function.

When the returned value is null, it could mean that the key object is not associated with any value in the hash map:

1
2
3
4
5
6
7
8
@Test
public void givenUnmappedKey_whenGetReturnsNull_thenCorrect() {
Map<String, String> map = new HashMap<>();

String rtnVal = map.get("key1");

assertNull(rtnVal);
}

Or it could simply mean that the key was explicitly mapped to a null instance:

1
2
3
4
5
6
7
8
9
@Test
public void givenNullVal_whenRetrieves_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("key", null);

String val=map.get("key");

assertNull(val);
}

To distinguish between the two scenarios, we can use the containsKey API, to which we pass the key and it returns true if and only if a mapping was created for the specified key in the hash map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
@Test
public void whenContainsDistinguishesNullValues_thenCorrect() {
Map<String, String> map = new HashMap<>();

String val1 = map.get("key");
boolean valPresent = map.containsKey("key");

assertNull(val1);
assertFalse(valPresent);

map.put("key", null);
String val = map.get("key");
valPresent = map.containsKey("key");

assertNull(val);
assertTrue(valPresent);
}

For both cases in the above test, the return value of the get API call is null but we are able to distinguish which one is which.

4. Collection Views in HashMap

HashMap offers three views that enable us to treat its keys and values as another collection. We can get a set of all keys of the map:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void givenHashMap_whenRetrievesKeyset_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();

assertEquals(2, keys.size());
assertTrue(keys.contains("name"));
assertTrue(keys.contains("type"));
}

The set is backed by the map itself. So any change made to the set is reflected in the map:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test
public void givenKeySet_whenChangeReflectsInMap_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

assertEquals(2, map.size());

Set<String> keys = map.keySet();
keys.remove("name");

assertEquals(1, map.size());
}

We can also obtain a collection view of the values:

1
2
3
4
5
6
7
8
9
10
11
12
@Test
public void givenHashMap_whenRetrievesValues_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "baeldung");
map.put("type", "blog");

Collection<String> values = map.values();

assertEquals(2, values.size());
assertTrue(values.contains("yc"));
assertTrue(values.contains("blog"));
}

Just like the key set, any changes made in this collection will be reflected in the underlying map.

Finally, we can obtain a set view of all entries in the map:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Test
public void givenHashMap_whenRetrievesEntries_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<Entry<String, String>> entries = map.entrySet();

assertEquals(2, entries.size());
for (Entry<String, String> e : entries) {
String key = e.getKey();
String val = e.getValue();
assertTrue(key.equals("name") || key.equals("type"));
assertTrue(val.equals("yc") || val.equals("blog"));
}
}

Remember that a hash map specifically contains unordered elements, therefore we assume any order when testing the keys and values of entries in the for each loop.

Many times, you will use the collection views in a loop as in the last example, and more specifically using their iterators.

Just remember that the iterators for all the above views are *fail-fast*.

If any structural modification is made on the map, after the iterator has been created, a concurrent modification exception will be thrown:

1
2
3
4
5
6
7
8
9
10
11
12
13
@Test(expected = ConcurrentModificationException.class)
public void givenIterator_whenFailsFastOnModification_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
map.remove("type");
while (it.hasNext()) {
String key = it.next();
}
}

The only allowed structural modification is a *remove* operation performed through the iterator itself:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public void givenIterator_whenRemoveWorks_thenCorrect() {
Map<String, String> map = new HashMap<>();
map.put("name", "yc");
map.put("type", "blog");

Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();

while (it.hasNext()) {
it.next();
it.remove();
}

assertEquals(0, map.size());
}

The final thing to remember about these collection views is the performance of iterations. This is where a hash map performs quite poorly compared with its counterparts linked hash map and tree map.

Iteration over a hash map happens in worst case O(n) where n is the sum of its capacity and the number of entries.

5. HashMap Performance

The performance of a hash map is affected by two parameters: Initial Capacity and Load Factor. The capacity is the number of buckets or the underlying array length and the initial capacity is simply the capacity during creation.

The load factor or LF, in short, is a measure of how full the hash map should be after adding some values before it is resized.

The default initial capacity is 16 and default load factor is 0.75. We can create a hash map with custom values for initial capacity and LF:

1
2
Map<String,String> hashMapWithCapacity=new HashMap<>(32);
Map<String,String> hashMapWithCapacityAndLF=new HashMap<>(32, 0.5f);

The default values set by the Java team are well optimized for most cases. However, if you need to use your own values, which is very okay, you need to understand the performance implications so that you know what you are doing.

When the number of hash map entries exceeds the product of LF and capacity, then rehashing occurs i.e. another internal array is created with twice the size of the initial one and all entries are moved over to new bucket locations in the new array.

A low initial capacity reduces space cost but increases the frequency of rehashing. Rehashing is obviously a very expensive process. So as a rule, if you anticipate many entries, you should set a considerably high initial capacity.

On the flip side, if you set the initial capacity too high, you will pay the cost in iteration time. As we saw in the previous section.

So a high initial capacity is good for a large number of entries coupled with little to no iteration.

A low initial capacity is good for few entries with a lot of iteration.

*6. Collisions in the HashMap

A collision, or more specifically, a hash code collision in a HashMap, is a situation where two or more key objects produce the same final hash value and hence point to the same bucket location or array index.

This scenario can occur because according to the equals and hashCode contract, two unequal objects in Java can have the same hash code.

It can also happen because of the finite size of the underlying array, that is, before resizing. The smaller this array, the higher the chances of collision.

That said, it’s worth mentioning that Java implements a hash code collision resolution technique which we will see using an example.

Keep in mind that it’s the hash value of the key that determines the bucket the object will be stored in. And so, if the hash codes of any two keys collide, their entries will still be stored in the same bucket.

And by default, the implementation uses a linked list as the bucket implementation.

The initially constant time O(1) put and get operations will occur in linear time O(n) in the case of a collision. This is because after finding the bucket location with the final hash value, each of the keys at this location will be compared with the provided key object using the equals API.

To simulate this collision resolution technique, let’s modify our earlier key object a little:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class MyKey {
private String name;
private int id;

public MyKey(int id, String name) {
this.id = id;
this.name = name;
}

// standard getters and setters

@Override
public int hashCode() {
System.out.println("Calling hashCode()");
return id;
}

// toString override for pretty logging

@Override
public boolean equals(Object obj) {
System.out.println("Calling equals() for key: " + obj);
// generated implementation
}

}

Notice how we’re simply returning the id attribute as the hash code – and thus force a collision to occur.

Also, note that we’ve added log statements in our equals and hashCode implementations – so that we know exactly when the logic is called.

Let’s now go ahead to store and retrieve some objects that collide at some point:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
@Test
public void whenCallsEqualsOnCollision_thenCorrect() {
HashMap<MyKey, String> map = new HashMap<>();
MyKey k1 = new MyKey(1, "firstKey");
MyKey k2 = new MyKey(2, "secondKey");
MyKey k3 = new MyKey(2, "thirdKey");

System.out.println("storing value for k1");
map.put(k1, "firstValue");
System.out.println("storing value for k2");
map.put(k2, "secondValue");
System.out.println("storing value for k3");
map.put(k3, "thirdValue");

System.out.println("retrieving value for k1");
String v1 = map.get(k1);
System.out.println("retrieving value for k2");
String v2 = map.get(k2);
System.out.println("retrieving value for k3");
String v3 = map.get(k3);

assertEquals("firstValue", v1);
assertEquals("secondValue", v2);
assertEquals("thirdValue", v3);
}

In the above test, we create three different keys – one has a unique id and the other two have the same id. Since we use id as the initial hash value, there will definitely be a collision during both storage and retrieval of data with these keys.

In addition to that, thanks to the collision resolution technique we saw earlier, we expect each of our stored values to be retrieved correctly, hence the assertions in the last three lines.

When we run the test, it should pass, indicating that collisions were resolved and we will use the logging produced to confirm that the collisions indeed occurred:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
storing value for k1
Calling hashCode()
storing value for k2
Calling hashCode()
storing value for k3
Calling hashCode()
Calling equals() for key: MyKey [name=secondKey, id=2]
retrieving value for k1
Calling hashCode()
retrieving value for k2
Calling hashCode()
retrieving value for k3
Calling hashCode()
Calling equals() for key: MyKey [name=secondKey, id=2]

Notice that during storage operations, k1 and k2 were successfully mapped to their values using only the hash code.

However, storage of k3 was not so simple, the system detected that its bucket location already contained a mapping for k2. Therefore, equals comparison was used to distinguish them and a linked list was created to contain both mappings.

Any other subsequent mapping whose key hashes to the same bucket location will follow the same route and end up replacing one of the nodes in the linked list or be added to the head of the list if equals comparison returns false for all existing nodes.

Likewise, during retrieval, k3 and k2 were equals-compared to identify the correct key whose value should be retrieved.

On a final note, from Java 8, the linked lists are dynamically replaced with balanced binary search trees in collision resolution after the number of collisions in a given bucket location exceed a certain threshold.

This change offers a performance boost, since, in the case of a collision, storage and retrieval happen in O(log n).

This section is very common in technical interviews, especially after the basic storage and retrieval questions.

Spring Interview Questions And Answers

Q1) What is Spring?

Spring is an open-source development framework for Enterprise Java. The core features of the Spring Framework can be used in developing any Java application, but there are extensions for building web applications on top of the Java EE platform. Spring framework targets to make Java EE development easier to use and promote good programming practice by enabling a POJO-based programming model.

Q2) What are benefits of Spring Framework?

  1. Lightweight: Spring is lightweight when it comes to size and transparency. The basic version of the spring framework is around 2MB.
  2. Inversion of control (IOC): Loose coupling is achieved in Spring, with the Inversion of Control technique. The objects give their dependencies instead of creating or looking for dependent objects.
  3. Aspect oriented (AOP): Spring supports Aspect oriented programming and separates application business logic from system services.
  4. Container: Spring contains and manages the life cycle and configuration of application objects.
  5. MVC Framework: Spring’s web framework is a well-designed web MVC framework, which provides a great alternative to web frameworks.
  6. Transaction Management: Spring provides a consistent transaction management interface that can scale down to a local transaction and scale up to global transactions (JTA).
  7. Exception Handling: Spring provides a convenient API to translate technology-specific exceptions (thrown by JDBC, Hibernate, or JDO) into consistent, unchecked exceptions.

Q3) Which are the Spring framework modules?

The basic modules of the Spring framework are :

  1. Core module
  2. Bean module
  3. Context module
  4. Expression Language module
  5. JDBC module
  6. ORM module
  7. OXM module
  8. Java Messaging Service(JMS) module
  9. Transaction module
  10. Web module
  11. Web-Servlet module
  12. Web-Struts module
  13. Web-Portlet module

Q4) Explain the Core Container (Application context) module

This is the basic Spring module, which provides the fundamental functionality of the Spring framework. BeanFactory is the heart of any spring-based application. Spring framework was built on the top of this module, which makes the Spring container.

Q5) What is BeanFactory – BeanFactory implementation example

A BeanFactory is an implementation of the factory pattern that applies Inversion of Control to separate the application’s configuration and dependencies from the actual application code.
The most commonly used BeanFactory implementation is the XmlBeanFactory class.

Q6) XMLBeanFactory

The most useful one is org.springframework.beans.factory.xml.XmlBeanFactory, which loads its beans based on the definitions contained in an XML file. This container reads the configuration metadata from an XML file and uses it to create a fully configured system or application.

Q7) Explain the AOP module

The AOP module is used for developing aspects for our Spring-enabled application. Much of the support has been provided by the AOP Alliance in order to ensure the interoperability between Spring and other AOP frameworks. This module also introduces metadata programming to Spring.

Q8) Explain the JDBC abstraction and DAO module

With the JDBC abstraction and DAO module we can be sure that we keep up the database code clean and simple, and prevent problems that result from a failure to close database resources. It provides a layer of meaningful exceptions on top of the error messages given by several database servers. It also makes use of Spring’s AOP module to provide transaction management services for objects in a Spring application.

Q9) Explain the object/relational mapping integration module

Spring also supports for using of an object/relational mapping (ORM) tool over straight JDBC by providing the ORM module. Spring provides support to tie into several popular ORM frameworks, including Hibernate, JDO, and iBATIS SQL Maps. Spring’s transaction management supports each of these ORM frameworks as well as JDBC.

Q10) Explain the web module

The Spring web module is built on the application context module, providing a context that is appropriate for web-based applications. This module also contains support for several web-oriented tasks such as transparently handling multipart requests for file uploads and programmatic binding of request parameters to your business objects. It also contains integration support with Jakarta Struts.

Q11) Explain the Spring MVC module

MVC framework is provided by Spring for building web applications. Spring can easily be integrated with other MVC frameworks, but Spring’s MVC framework is a better choice, since it uses IoC to provide for a clean separation of controller logic from business objects. With Spring MVC you can declaratively bind request parameters to your business objects.

Q12) Spring configuration file

Spring configuration file is an XML file. This file contains the classes information and describes how these classes are configured and introduced to each other.

Q13) What is Spring IoC container?

The Spring IoC is responsible for creating the objects,managing them (with dependency injection (DI)), wiring them together, configuring them, as also managing their complete lifecycle.

Q14) What are the benefits of IOC?

IOC or dependency injection minimizes the amount of code in an application. It makes easy to test applications, since no singletons or JNDI lookup mechanisms are required in unit tests. Loose coupling is promoted with minimal effort and least intrusive mechanism. IOC containers support eager instantiation and lazy loading of services.

Q15) What are the common implementations of the ApplicationContext?

The FileSystemXmlApplicationContext container loads the definitions of the beans from an XML file. The full path of the XML bean configuration file must be provided to the constructor.

The ClassPathXmlApplicationContext container also loads the definitions of the beans from an XML file. Here, you need to set CLASSPATH properly because this container will look bean configuration XML file in CLASSPATH.

The WebXmlApplicationContext: container loads the XML file with definitions of all beans from within a web application.

Q16) What is the difference between Bean Factory and ApplicationContext?

Application contexts provide a means for resolving text messages, a generic way to load file resources (such as images), they can publish events to beans that are registered as listeners. In addition, operations on the container or beans in the container, which have to be handled in a programmatic fashion with a bean factory, can be handled declaratively in an application context. The application context implements MessageSource, an interface used to obtain localized messages, with the actual implementation being pluggable.

Q17) What does a Spring application look like?

  1. An interface that defines the functions.
  2. The implementation that contains properties, its setter and getter methods, functions etc.,
  3. Spring AOP
  4. The Spring configuration XML file.
  5. Client program that uses the function

Q18) What is Dependency Injection in Spring?

Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept, and it can be expressed in many different ways.This concept says that you do not create your objects but describe how they should be created. You don’t directly connect your components and services together in code but describe which services are needed by which components in a configuration file. A container (the IOC container) is then responsible for hooking it all up.

Q19) What are the different types of IoC (dependency injection)?

  1. Constructor-based dependency injection: Constructor-based DI is accomplished when the container invokes a class constructor with a number of arguments, each representing a dependency on other class.
  2. Setter-based dependency injection: Setter-based DI is accomplished by the container calling setter methods on your beans after invoking a no-argument constructor or no-argument static factory method to instantiate your bean.

Q20) Which DI would you suggest Constructor-based or setter-based DI?

You can use both Constructor-based and Setter-based Dependency Injection. The best solution is using constructor arguments for mandatory dependencies and setters for optional dependencies.

Q21) What are Spring beans?

Spring beans scope interview questions - The Spring Beans are Java Objects that form the backbone of a Spring application. They are instantiated, assembled, and managed by the Spring IoC container. These beans are created with the configuration metadata that is supplied to the container, for example, in the form of XML definitions.

Beans defined in spring framework are singleton beans. There is an attribute in bean tag named “singleton” if specified true then bean becomes singleton and if set to false then the bean becomes a prototype bean. By default it is set to true. So, all the beans in spring framework are by default singleton beans.

Q22) What does a Spring Bean definition contain?

A Spring Bean definition contains all configuration metadata which is needed for the container to know how to create a bean, its lifecycle details and its dependencies.

Q23) How do you provide configuration metadata to the Spring Container?

There are three important methods to provide configuration metadata to the Spring Container:

  1. XML based configuration file.
  2. Annotation-based configuration
  3. Java-based configuration

Q24) How do you define the scope of a bean?

When defining a in Spring, we can also declare a scope for the bean. It can be defined through the scope attribute in the bean definition. For example, when Spring has to produce a new bean instance each time one is needed, the bean’sscope attribute to be prototype. On the other hand, when the same instance of a bean must be returned by Spring every time it is needed, the the bean scope attribute must be set to singleton.

Q25) Explain the bean scopes supported by Spring

There are five scoped provided by the Spring Framework supports following five scopes:

  1. In singlet on scope, Spring scopes the bean definition to a single instance per Spring IoC container.
  2. In prototype scope, a single bean definition has any number of object instances.
  3. In request scope, a bean is defined to an HTTP request. This scope is valid only in a web-aware Spring ApplicationContext.
  4. In session scope, a bean definition is scoped to an HTTP session. This scope is also valid only in a web-aware Spring ApplicationContext.
  5. In global-session scope, a bean definition is scoped to a global HTTP session. This is also a case used in a web-aware Spring ApplicationContext.

The default scope of a Spring Bean is Singleton.

Q26) Are Singleton beans thread safe in Spring Framework?

No, singleton beans are not thread-safe in Spring framework.

Q27) Explain Bean lifecycle in Spring framework

  1. The spring container finds the bean’s definition from the XML file and instantiates the bean.
  2. Spring populates all of the properties as specified in the bean definition (DI).
  3. If the bean implementsBeanNameAware interface, spring passes the bean’s id to setBeanName()
  4. If Bean implementsBeanFactoryAware interface, spring passes the beanfactory to setBeanFactory()
  5. If there are any beanBeanPostProcessors associated with the bean, Spring calls postProcesserBeforeInitialization()
  6. If the bean implementsIntializingBean, its afterPropertySet() method is called. If the bean has init method declaration, the specified initialization method is called.
  7. If there are any BeanPostProcessors associated with the bean, their postProcessAfterInitialization() methods will be called.
  8. If the bean implementsDisposableBean, it will call the destroy()

Q28) Which are the important beans lifecycle methods? Can you override them?

There are two important bean lifecycle methods. The first one is setup which is called when the bean is loaded in to the container. The second method is the teardown method which is called when the bean is unloaded from the container.

The bean tag has two important attributes (init-method and destroy-method) with which you can define your own custom initialization and destroy methods. There are also the correspondive annotations(@PostConstruct and @PreDestroy).

Q29) What are inner beans in Spring?

When a bean is only used as a property of another bean it can be declared as an inner bean. Spring’s XML-based configuration metadata provides the use of element inside the or elements of a bean definition, in order to define the so-called inner bean. Inner beans are always anonymous and they are always scoped as prototypes.

Q30) How can you inject a Java Collection in Spring?

Spring offers the following types of collection configuration elements:

  1. The type is used for injecting a list of values, in the case that duplicates are allowed.
  2. The type is used for wiring a set of values but without any duplicates.
  3. The type is used to inject a collection of name-value pairs where name and value can be of any type.
  4. The type can be used to inject a collection of name-value pairs where the name and value are both Strings.

Q31) What is bean wiring?

Wiring, or else bean wiring is the case when beans are combined together within the Spring container. When wiring beans, the Spring container needs to know what beans are needed and how the container should use dependency injection to tie them together.

Q32) What is bean auto wiring?

The Spring container is able to autowire relationships between collaborating beans. This means that it is possible to automatically let Spring resolve collaborators (other beans) for a bean by inspecting the contents of the BeanFactorywithout using and elements.

Q33) Explain different modes of auto wiring?

The autowiring functionality has five modes which can be used to instruct Spring container to use autowiring for dependency injection:

  1. no: This is default setting. Explicit bean reference should be used for wiring.
  2. byName: When autowiring byName, the Spring container looks at the properties of the beans on which autowireattribute is set to byName in the XML configuration file. It then tries to match and wire its properties with the beans defined by the same names in the configuration file.
  3. byType: When autowiring by datatype, the Spring container looks at the properties of the beans on which autowireattribute is set to byType in the XML configuration file. It then tries to match and wire a property if its type matches with exactly one of the beans name in configuration file. If more than one such beans exist, a fatal exception is thrown.
  4. constructor:This mode is similar to byType, but type applies to constructor arguments. If there is not exactly one bean of the constructor argument type in the container, a fatal error is raised.
  5. autodetect: Spring first tries to wire using autowire by constructor, if it does not work, Spring tries to autowire bybyType.

Q34) Are there limitations with autowiring?

Limitations of autowiring are:

  1. Overriding: You can still specify dependencies using and settings which will always override autowiring.
  2. Primitive data types: You cannot autowire simple properties such as primitives, Strings, and Classes.
  3. Confusing nature: Autowiring is less exact than explicit wiring, so if possible prefer using explicit wiring.

Q35) Can you inject null and empty string values in Spring?

Yes, you can.

Q36) What is Spring Java-Based Configuration? Give some annotation example.

Java based configuration option enables you to write most of your Spring configuration without XML but with the help of few Java-based annotations.

An example is a @Configuration annotation, that indicates that the class can be used by the Spring IoC container as a source of bean definitions. Another example is the@Bean annotated method that will return an object that should be registered as a bean in the Spring application context.

Q36) What is Annotation-based container configuration?

An alternative to XML setups is provided by an annotation-based configuration which relies on the bytecode metadata for wiring up components instead of angle-bracket declarations. Instead of using XML to describe a bean wiring, the developer moves the configuration into the component class itself by using annotations on the relevant class, method, or field declaration.

Q37) How do you turn on annotation wiring?

Annotation wiring is not turned on in the Spring container by default. In order to use annotation based wiring, we must enable it in our Spring configuration file by configuring element.

Q38) @Required annotation

This annotation simply indicates that the affected bean property must be populated at configuration time, through an explicit property value in a bean definition or through autowiring. The container throws BeanInitializationException if the affected bean property has not been populated.

Q39) @Autowired annotation

The @Autowired annotation provides more fine-grained control over where and how autowiring should be accomplished. It can be used to autowire bean on the setter method just like @Required annotation, on the constructor, on a property or pn methods with arbitrary names and/or multiple arguments.

Q40) @Qualifier annotation

When there are more than one beans of the same type and only one is needed to be wired with a property, the@Qualifier annotation is used along with @Autowired annotation to remove the confusion by specifying which exact bean will be wired.

Q41) How can JDBC be used more efficiently in the Spring framework?

When using the Spring JDBC framework the burden of resource management and error handling is reduced. So developers only need to write the statements and queries to get the data to and from the database. JDBC can be used more efficiently with the help of a template class provided by Spring framework, which is the JdbcTemplate

Q42) JdbcTemplate

JdbcTemplate class provides many convenience methods for doing things such as converting database data into primitives or objects, executing prepared and callable statements, and providing custom database error handling.

Q43) Spring DAO support

The Data Access Object (DAO) support in Spring is aimed at making it easy to work with data access technologies like JDBC, Hibernate or JDO in a consistent way. This allows us to switch between the persistence technologies fairly easily and to code without worrying about catching exceptions that are specific to each technology.

Q44) What are the ways to access Hibernate by using Spring?

There are two ways to access Hibernate with Spring:

  1. Inversion of Control with a Hibernate Template and Callback.
  2. ExtendingHibernateDAOSupport and Applying an AOP Interceptor node.

Q45) ORM’s Spring support

Spring supports the following ORM’s:

  1. Hibernate
  2. iBatis
  3. JPA (Java Persistence API)
  4. TopLink
  5. JDO (Java Data Objects)
  6. OJB

Q46) How can we integrate Spring and Hibernate using HibernateDaoSupport?

Use Spring’s SessionFactory called LocalSessionFactory. The integration process is of 3 steps:

  1. Configure the Hibernate SessionFactory
  2. Extend a DAO Implementation fromHibernateDaoSupport
  3. Wire in Transaction Support with AOP

Q47) Types of the transaction management Spring support

Spring supports two types of transaction management:

  1. Programmatic transaction management: This means that you have managed the transaction with the help of programming. That gives you extreme flexibility, but it is difficult to maintain.
  2. Declarative transaction management: This means you separate transaction management from the business code. You only use annotations or XML based configuration to manage the transactions.

Q48) What are the benefits of the Spring Framework’s transaction management?

  1. It provides a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO.
  2. It provides a simpler API for programmatic transaction management than a number of complex transaction APIs such as JTA.
  3. It supports declarative transaction management.
  4. It integrates very well with Spring’s various data access abstractions.

Q49) Which Transaction management type is more preferable?

Most users of the Spring Framework choose declarative transaction management because it is the option with the least impact on application code, and hence is most consistent with the ideals of a non-invasive lightweight container. Declarative transaction management is preferable over programmatic transaction management though it is less flexible than programmatic transaction management, which allows you to control transactions through your code.

Q50) Explain AOP

Aspect-oriented programming, or AOP, is a programming technique that allows programmers to modularize crosscutting concerns or behavior that cuts across the typical divisions of responsibility, such as logging and transaction management.

Q51) Aspect

The core construct of AOP is the aspect, which encapsulates behaviors affecting multiple classes into reusable modules. It ia a module which has a set of APIs providing cross-cutting requirements. For example, a logging module would be called AOP aspect for logging. An application can have any number of aspects depending on the requirement. In Spring AOP, aspects are implemented using regular classes annotated with the @Aspect annotation (@AspectJ style).

Q52) What is the difference between concern and cross-cutting concern in Spring AOP

The Concern is behavior we want to have in a module of an application. A Concern may be defined as a functionality we want to implement.

The cross-cutting concern is a concern which is applicable throughout the application and it affects the entire application. For example, logging, security and data transfer are the concerns which are needed in almost every module of an application, hence they are cross-cutting concerns.

Q53) Joinpoint

The join point represents a point in an application where we can plug-in an AOP aspect. It is the actual place in the application where an action will be taken using Spring AOP framework.

Q54) Advice

The advice is the actual action that will be taken either before or after the method execution. This is an actual piece of code that is invoked during the program execution by the Spring AOP framework.
Spring aspects can work with five kinds of advice:

  1. before: Run advice before the method execution.
  2. after: Run advice after the method execution regardless of its outcome.
  3. after-returning: Run advice after the method execution only if method completes successfully.
  4. after-throwing: Run advice after the method execution only if a method exits by throwing an exception.
  5. around: Run advice before and after the advised method is invoked.

Q55) Pointcut

The pointcut is a set of one or more joinpoints where an advice should be executed. You can specify pointcuts using expressions or patterns.

Q56) What is Introduction?

An Introduction allows us to add new methods or attributes to existing classes.

Q57) What is Target object?

A target object is an object being advised by one or more aspects. It will always be a proxy object. It is also referred to as the advised object.

Q58) What is a Proxy?

A proxy is an object that is created by applying advice to a target object. When you think of client objects the target object and the proxy object are the same.

Q59) What are the different types of AutoProxying?

  1. BeanNameAutoProxyCreator
  2. DefaultAdvisorAutoProxyCreator
  3. Metadata autoproxying

Q60) What is Weaving? What are the different points where weaving can be applied?

Weaving is the process of linking aspects with other application types or objects to create an advised object.

Weaving can be done at compile time, at load time, or at runtime.

Q61) Explain XML Schema-based aspect implementation?

In this implementation case, aspects are implemented using regular classes along with XML based configuration.

Q62) Explain annotation-based (@AspectJ based) aspect implementation

This implementation case (@AspectJ based implementation) refers to a style of declaring aspects as regular Java classes annotated with Java 5 annotations.

Q63) What is Spring MVC framework?

Spring comes with a full-featured MVC framework for building web applications. Although Spring can easily be integrated with other MVC frameworks, such as Struts, Spring’s MVC framework uses IoC to provide a clean separation of controller logic from business objects. It also allows to declaratively bind request parameters to business objects.

Q64) DispatcherServlet

The Spring Web MVC framework is designed around a DispatcherServlet that handles all the HTTP requests and responses.

Q65) WebApplicationContext

The WebApplicationContext is an extension of the plain ApplicationContext that has some extra features necessary for web applications. It differs from a normal ApplicationContext in that it is capable of resolving themes, and that it knows which servlet it is associated with.

Q66) What is Controller in Spring MVC framework?

Controllers provide access to the application behavior that you typically define through a service interface. Controllers interpret user input and transform it into a model that is represented to the user by the view. Spring implements a controller in a very abstract way, which enables you to create a wide variety of controllers.

Q67) @Controller annotation

The @Controller annotation indicates that a particular class serves the role of a controller. Spring does not require you to extend any controller base class or reference the Servlet API.

In this article, you will learn about why is programming skills important, what are its uses in technology, and how it impacts business and career. The programming skill is important for learning to innovate, create eco-friendly solutions for global problems. Programming is important in our daily life to enhance and increase the power of computers and the internet.

Programming is important for speeding up the input and output processes in a machine. Programming is important to automate, collect, manage, calculate, analyze the processing of data and information accurately.

Programming is important to create software and applications that help computer and mobile users in daily life. Due to all these reasons, it’s really important to learn how to use programming languages in our daily life.

Java, javascript, C#, C++, PHP, Python, Swift, SQL, Ruby, etc. programming languages are the reasons behind the innovations in information technologies. If today we are seeing robots, artificial intelligence, machine learning, bitcoins, blockchain, IoT (Internet of Things), Cloud Computing, etc. new technology and products in the IT industry, then it’s because of programming languages.

The group of programs is called software. Programming languages are the way to create software that performs various or specific tasks in a systematic manner. Software development is like a Marriage event.

A programming language is a method to communicate with machines in a systematic format. To understand programming languages first we need to start from programs.

What is a program?

A program is a group of logical, mathematical, systematical, and managed functions grouped together to perform a specific task. Just like there are various programs in the marriage such as Shanti, Barat Prasthan, Lagan, Vadhu Pravesh, reception, Dham, etc.

What is a function?

Groups of classes are called a function. A function requires specific classes. For example, if you want to create a function to play songs then you need to create specific classes under these programs in which play, pause, stop and etc. are the classes. Now in a marriage example, the Shanti program contains various functions such as mama swagat, batna lepan, lok sangit, sehra bandi are various functions inside the Shanti program. That’s why small and big functions are important in a programming language to create software.

What is class?

Now each class contains a group of instruction and commands. There are variables, integers, decimals, symbols, loops, if/else, logical methods, and certain leaders in the class. All that is aimed to perform a specific task on the computer and the internet automatically. Similarly, in Sehra Bandhi, the Sehra is given by Mama’s to the bridegroom, it’s placed by parents and pandit pronounce the certain mantras. Now, this process takes time and all things go smoothly. Now I think you must have got a clear idea, how the classes are created or programmed using programming languages. That’s why classes are so much important in a programming language to create functions.

I want to take you a little deeper into the programming languages so that you automatically understand why it is important. As you learned above in the last point about the classes and group of instruction and commands.

Now, What is instruction or command?

Instruction or commands are the systematic methods to operate certain machines. Just as we give instructions to the computer using a keyboard and mouse. Similarly, during sehra bandi, vadhu pravesh, lagna we use certain objects such as dhoop, chawal, kusha, water, haldi, and other religious products to perform that specific action.

So to perform certain tasks on the computer we use input devices and in the same methods, we instruct computers and machines in the classes, functions, programs, and software to perform those tasks. So that we don’t need to do the task again and again. Instead, the software can do it automatically with high speed and accuracy. And we use a programming language to create software that performs and receives inputs.
Each event contains different smaller programs. Such as Retirement programs contain different smaller functions and even birthday parties contain different programs, functions, and classes.

Similarly, each software contains different programs, functions, classes, and instruction. So for Android programs, functions and classes are different than Mac Os programs. For the same example, we have adobe photoshop software programs, classes, libraries, and functions, which are different than Microsoft office 360.

Similarly, the Facebook website is an application in which programs, functions, classes are different than the WordPress website.

All web applications and software are created using programming languages and the languages can be similar or different or many languages in a single class. It’s not about how many programming languages you use in a single class. It’s just about doing this in a way so that the language is acceptable, instructional, and logical to automate the process.

Similarly, in a marriage function in a class in which ‘Lagan’ is going on and Pundit pronounces mantras in Sanskrit language only, but in other countries the similar process of Lagana is different and the language can be English and prayer or blessings are done by a priest in a church.

In this way with the example of marriage, you will be able to understand the importance of programming language. As marriage is important in our life programming is important to create and run software and information technology.

Now the above example helped you to understand what is a programming language and its importance. Now it’s important that you also understand a different perspective of the importance of programming languages in this article, we always want our readers will get maximum information and knowledge. So that’s why we not only write in creative and technical methods but also write with variety.

Now from a career perspective, the importance of learning programming languages is bigger and higher than any other IT subject for students. As you learned above that to innovate and to create software it’s important to use programming language.

Now if kids, school, and college students learn programming languages as early as possible, it will greatly help them to create next big things like WhatsApp, Facebook, Google, and many other applications that are in the race to influence and change the world.

Even if students don’t want to create their own applications and next viral apps they can easily get a job in the city. Almost every IT company requires skilled programmers. Small companies require an array of wider programming skills whereas big companies require very specific skills with predefined targets.

Now the software development has many parts as I discussed above with the marriage example. When we look for a career in software development or programming field, we need to differentiate our skill and programming training in a way so that it remains relevant and specific for the job.

So if we take Marriage as an analogy of software, then it’s important to know if you want to become Pundit, tent and decoration supplier, event manager, DJ, or the whole event planner.

Similarly, in software and web development it requires planning, execution, management, inventory, support, sales, and marketing. So it’s important when you look for a career you need to have expertise in the skills. Such as an expert in Javascript, Expert in Python web development, an expert in SQL Lite, etc. So the demand of programmers in the IT field and the various industry is big, so it’s not a doubt that learning programming languages will provide you a high return on time, effort, and financial investment.

While there are other reasons behind why one should learn programming languages, we conclude in a short paragraph. We can say that programming languages are important to create software and programming languages are important to create and implement certain functionality in machines. Programming languages are important to create solutions that are environmentally friendly and support the highest level of living standards for humans.

It’s also important to program a world that helps to reduce corruption, improves transparency and happiness in everyone’s life. Programming languages are now a part of our life. Learning can never be wrong, but purposeful learning helps in a great way for students, businesses and all human beings. It’s should be done to support nature not to disturb it.

1. Introduction

In this article, we’re going to look at some of the most common Spring-related questions that might pop up during a job interview.

2. Spring Core

Q1. What Is Spring Framework?

Spring is the most broadly used framework for the development of Java Enterprise Edition applications. The core features of Spring can be used in developing any Java application.

We can use its extensions for building various web applications on top of the Jakarta EE platform, or we may just use its dependency injection provisions in simple standalone applications.

Q2. What Are the Benefits of Using Spring?

Spring targets to make Jakarta EE development easier. Here are the advantages of using it:

  • Lightweight: there is a slight overhead of using the framework in development
  • Inversion of Control (IoC): Spring container takes care of wiring dependencies of various objects, instead of creating or looking for dependent objects
  • Aspect Oriented Programming (AOP): Spring supports AOP to separate business logic from system services
  • IoC container: it manages Spring Bean life cycle and project specific configurations
  • MVC framework: that is used to create web applications or RESTful web services, capable of returning XML/JSON responses
  • Transaction management: reduces the amount of boiler-plate code in JDBC operations, file uploading, etc., either by using Java annotations or by Spring Bean XML configuration file
  • Exception Handling: Spring provides a convenient API for translating technology-specific exceptions into unchecked exceptions

Q3. What Spring Sub-Projects Do You Know? Describe Them Briefly.

  • Core – a key module that provides fundamental parts of the framework, like IoC or DI
  • JDBC – this module enables a JDBC-abstraction layer that removes the need to do JDBC coding for specific vendor databases
  • ORM integration – provides integration layers for popular object-relational mapping APIs, such as JPA, JDO, and Hibernate
  • Web – a web-oriented integration module, providing multipart file upload, Servlet listeners, and web-oriented application context functionalities
  • MVC framework – a web module implementing the Model View Controller design pattern
  • AOP module – aspect-oriented programming implementation allowing the definition of clean method-interceptors and pointcuts

Q4. What Is Dependency Injection?

Dependency Injection, an aspect of Inversion of Control (IoC), is a general concept stating that you do not create your objects manually but instead describe how they should be created. An IoC container will instantiate required classes if needed.

For more details, please refer here.

Q5. How Can We Inject Beans in Spring?

A few different options exist:

  • Setter Injection
  • Constructor Injection
  • Field Injection

The configuration can be done using XML files or annotations.

For more details, check this article.

Q6. Which Is the Best Way of Injecting Beans and Why?

The recommended approach is to use constructor arguments for mandatory dependencies and setters for optional ones. Constructor injection allows injecting values to immutable fields and makes testing easier.

Q7. What Is the Difference Between Beanfactory and Applicationcontext?

BeanFactory is an interface representing a container that provides and manages bean instances. The default implementation instantiates beans lazily when getBean() is called.

ApplicationContext is an interface representing a container holding all information, metadata, and beans in the application. It also extends the BeanFactory interface but the default implementation instantiates beans eagerly when the application starts. This behavior can be overridden for individual beans.

Q8. What Is a Spring Bean?

The Spring Beans are Java Objects that are initialized by the Spring IoC container.

Q9. What Is the Default Bean Scope in Spring Framework?

By default, a Spring Bean is initialized as a singleton.

Q10. How to Define the Scope of a Bean?

To set Spring Bean’s scope, we can use @Scope annotation or “scope” attribute in XML configuration files. There are five supported scopes:

  • singleton
  • prototype
  • request
  • session
  • global-session

For differences, please refer here.

Q11. Are Singleton Beans Thread-Safe?

No, singleton beans are not thread-safe, as thread safety is about execution, whereas the singleton is a design pattern focusing on creation. Thread safety depends only on the bean implementation itself.

Q12. What Does the Spring Bean Lifecycle Look Like?

First, a Spring bean needs to be instantiated, based on Java or XML bean definition. It may also be required to perform some initialization to get it into a usable state. After that, when the bean is no longer required, it will be removed from the IoC container.

Q13. What Is the Spring Java-Based Configuration?

It’s one of the ways of configuring Spring-based applications in a type-safe manner. It’s an alternative to the XML-based configuration.

Q14. Can We Have Multiple Spring Configuration Files in One Project?

Yes, in large projects, having multiple Spring configurations is recommended to increase maintainability and modularity.

You can load multiple Java-based configuration files:

1
2
3
@Configuration
@Import({MainConfig.class, SchedulerConfig.class})
public class AppConfig {

Or load one XML file that will contain all other configs:

1
ApplicationContext context = new ClassPathXmlApplicationContext("spring-all.xml");

And inside this XML file you’ll have:

1
2
<import resource="main.xml"/>
<import resource="scheduler.xml"/>

Q15. What Is Spring Security?

Spring Security is a separate module of the Spring framework that focuses on providing authentication and authorization methods in Java applications. It also takes care of most of the common security vulnerabilities such as CSRF attacks.

To use Spring Security in web applications, you can get started with a simple annotation: @EnableWebSecurity.

Q16. What Is Spring Boot?

Spring Boot is a project that provides a pre-configured set of frameworks to reduce boilerplate configuration so that you can have a Spring application up and running with the smallest amount of code.

Q17. Name Some of the Design Patterns Used in the Spring Framework?

  • Singleton Pattern: Singleton-scoped beans
  • Factory Pattern: Bean Factory classes
  • Prototype Pattern: Prototype-scoped beans
  • Adapter Pattern: Spring Web and Spring MVC
  • Proxy Pattern: Spring Aspect Oriented Programming support
  • Template Method Pattern: JdbcTemplate, HibernateTemplate, etc.
  • Front Controller: Spring MVC DispatcherServlet
  • Data Access Object: Spring DAO support
  • Model View Controller: Spring MVC

Q18. How Does the Scope Prototype Work?

Scope prototype means that every time you call for an instance of the Bean, Spring will create a new instance and return it. This differs from the default singleton scope, where a single object instance is instantiated once per Spring IoC container.

3. Spring Web MVC

Q19. How to Get *ServletContext* and *ServletConfig* Objects in a Spring Bean?

You can do either by:

  1. Implementing Spring-aware interfaces.
  2. Using @Autowired annotation on those beans:
1
2
3
4
5
@Autowired
ServletContext servletContext;

@Autowired
ServletConfig servletConfig;

Q20. What Is a Controller in Spring Mvc?

Simply put, all the requests processed by the DispatcherServlet are directed to classes annotated with @Controller. Each controller class maps one or more requests to methods that process and execute the requests with provided inputs.

Q21. How Does the @Requestmapping Annotation Work?

The @RequestMapping annotation is used to map web requests to Spring Controller methods. In addition to simple use cases, we can use it for mapping of HTTP headers, binding parts of the URI with @PathVariable, and working with URI parameters and the @RequestParam annotation.

4. Spring Data Access

Q22. What Is Spring Jdbctemplate Class and How to Use It?

The Spring JDBC template is the primary API through which we can access database operations logic that we’re interested in:

  • creation and closing of connections
  • executing statements and stored procedure calls
  • iterating over the ResultSet and returning results

To use it, we’ll need to define the simple configuration of DataSource:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
@Configuration
@ComponentScan("org.baeldung.jdbc")
public class SpringJdbcConfig {
@Bean
public DataSource mysqlDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/springjdbc");
dataSource.setUsername("guest_user");
dataSource.setPassword("guest_password");

return dataSource;
}
}

Q23. How Would You Enable Transactions in Spring and What Are Their Benefits?

There are two distinct ways to configure Transactions – with annotations or by using Aspect Oriented Programming (AOP) – each with their advantages.

The benefits of using Spring Transactions, according to the official docs, are:

  • Provide a consistent programming model across different transaction APIs such as JTA, JDBC, Hibernate, JPA, and JDO
  • Support declarative transaction management
  • Provide a simpler API for programmatic transaction management than some complex transaction APIs such as JTA
  • Integrate very well with Spring’s various data access abstractions

Q24. What Is Spring Dao?

Spring Data Access Object is Spring’s support provided to work with data access technologies like JDBC, Hibernate, and JPA in a consistent and easy way.

5. Spring Aspect-Oriented Programming (AOP)

Q25. What Is Aspect-Oriented Programming?

Aspects enable the modularization of cross-cutting concerns such as transaction management that span multiple types and objects by adding extra behavior to already existing code without modifying affected classes.

Q26. What Are Aspect, Advice, Pointcut, and Joinpoint in Aop?

  • Aspect: a class that implements cross-cutting concerns, such as transaction management
  • Advice\: the methods that get executed when a specific JoinPoint with matching Pointcut is reached in the application
  • Pointcut: a set of regular expressions that are matched with JoinPoint to determine whether Advice needs to be executed or not
  • JoinPoint: a point during the execution of a program, such as the execution of a method or the handling of an exception

Q27. What Is Weaving?

According to the official docs, weaving is a process that links aspects with other application types or objects to create an advised object. This can be done at compile time, load time, or at runtime. Spring AOP, like other pure Java AOP frameworks, performs weaving at runtime.

6. Spring 5

Q28. What Is Reactive Programming?

Reactive programming is about non-blocking, event-driven applications that scale with a small number of threads, with back pressure being a key ingredient that aims to ensure producers don’t overwhelm consumers.

The primary benefits of reactive programming are:

  • increased utilization of computing resources on multicore and multi-CPU hardware
  • and increased performance by reducing serialization

Reactive programming is generally event-driven, in contrast to reactive systems, which are message-driven. Thus, using reactive programming does not mean we’re building a reactive system, which is an architectural style.

However, reactive programming may be used as a means to implement reactive systems if we follow the Reactive Manifesto, which is quite vital to understand.

Based on this, reactive systems have four important characteristics:

  • Responsive: the system should respond in a timely manner
  • Resilient: in case the system faces any failure, it should stay responsive
  • Elastic: reactive systems can react to changes and stay responsive under varying workload
  • Message-driven: reactive systems need to establish a boundary between components by relying on asynchronous message passing

Q29. What Is Spring Webflux?

Spring WebFlux is Spring’s reactive-stack web framework, and it’s an alternative to Spring MVC.

Q30. What Are the Mono and Flux Types?

The WebFlux framework in Spring Framework 5 uses Reactor as its async foundation.

This project provides two core types: Mono to represent a single async value, and Flux to represent a stream of async values. They both implement the Publisher interface defined in the Reactive Streams specification.

Mono implements Publisher and returns 0 or 1 elements:

1
public abstract class Mono<T> implements Publisher<T> {...}

Also, Flux implements Publisher and returns N elements:

1
public abstract class Flux<T> implements Publisher<T> {...}

By definition, the two types represent streams, hence they’re both lazy, which means nothing is executed until we consume the stream using the subscribe() method. Both types are immutable, therefore calling any method will return a new instance of Flux or Mono.

Q31. What Is the Use of Webclient and Webtestclient?

WebClient is a component in the new Web Reactive framework that can act as a reactive client for performing non-blocking HTTP requests. Being a reactive client, it can handle reactive streams with back pressure, and it can take full advantage of Java 8 lambdas. It can also handle both sync and async scenarios.

On the other hand, the WebTestClient is a similar class that we can use in tests. Basically, it’s a thin shell around the WebClient. It can connect to any server over an HTTP connection. It can also bind directly to WebFlux applications using mock request and response objects, without the need for an HTTP server.

Q32. What Are the Disadvantages of Using Reactive Streams?

The major disadvantages of using reactive streams are:

  • Troubleshooting a Reactive application is a bit difficult;
  • There is limited support for reactive data stores, as traditional relational data stores have yet to embrace the reactive paradigm
  • There’s an extra learning curve when implementing

Q33. Is Spring 5 Compatible With Older Versions of Java?

In order to take advantage of Java 8 features, the Spring codebase has been revamped. This means older versions of Java cannot be used. Hence, the framework requires a minimum of Java 8.

Q34. How Does Spring 5 Integrate With Jdk 9 Modularity?

In Spring 5, everything has been modularized, thus we won’t be forced to import jars that may not have the functionalities we’re looking for.

Let’s see an example to understand the new module functionality in Java 9 and how to organize a Spring 5 project based on this concept.

To start, let’s create a new class that contains a single method to return a String “HelloWorld”. We’ll place this within a new Java project – HelloWorldModule:

1
2
3
4
5
6
package com.hello;
public class HelloWorld {
public String sayHello(){
return "HelloWorld";
}
}

Then let’s create a new module:

1
2
3
module com.hello {
export com.hello;
}

Now, let’s create a new Java Project, HelloWorldClient, to consume the above module by defining a module:

1
2
3
module com.hello.client {
requires com.hello;
}

The above module will be available for testing now:

1
2
3
4
5
6
public class HelloWorldClient {
public static void main(String[] args) {
HelloWorld helloWorld = new HelloWorld();
log.info(helloWorld.sayHello());
}
}

Q35. Can We Use Both Web Mvc and Webflux in the Same Application?

As of now, Spring Boot will only allow either Spring MVC or Spring WebFlux, as Spring Boot tries to auto-configure the context depending on the dependencies that exist in its classpath.

Also, Spring MVC cannot run on Netty. Moreover, MVC is a blocking paradigm and WebFlux is a non-blocking style, therefore we shouldn’t be mixing both together, as they serve different purposes.

7. Conclusion

In this extensive article, we’ve explored some of the most important questions for a technical interview all about Spring.

We hope that this article will help you in your upcoming Spring interview. Good luck!

The Most Common Behavioral Interview Questions and Answers

Unlike traditional interview questions, behavior job interview techniques look for concrete examples of skills and experiences that relate to the position. Your answers to these questions should provide a brief story that illustrates your skills and strengths as an employee. For each answer, give the interviewer the background to the story briefly, specific actions you took and the results.

Tips for answering behavioral interview questions

Here are some tips you can use as you answer behavioral interview questions:

  • Prepare ahead of time: While you may be asked a few uncommon questions, most interviewers ask many of the same interview questions, which is why it’s helpful to review common behavioral interview questions in advance and practice your responses. This will ensure you have thoughtful anecdotes ready in advance. Another way to feel fully prepared with anecdotes is to think of examples for every responsibility or challenge listed on the job description. Keep in mind that they don’t have to be direct examples. For example, if you’re applying for a manager job but have never been a supervisor, talk about how you were the go-to person on your team for training new employees and were widely known as a problem-solver.
  • Take your time answering: After a question is asked, give yourself a moment to think of an appropriate story before answering. Take a breath, pause or even take a drink of water to calm any nerves before responding.
  • Be positive: While behavioral interview questions require you to think of a failure or problem at work, don’t focus on that part of your story. Describe the background enough so that the interviewer understands the situation and then quickly move on to how you solved the problem and the results you achieved.
  • Follow the STAR method: Use the STAR method to answer any question. STAR stands for situation, task, action and result. For Situation, briefly share context and relevant details for the challenge or problem you were facing. For Task, describe your role in overcoming the challenge or handling the situation. For Action, explain what action was taken by you or your team, although it’s important to focus on the role you played, specifically. For Result, share the successful outcome. If possible, provide quantifiable results or concrete examples of the effect of your effort.

Sample interview questions and answers

Here are some common behavioral interview questions and suggestions for how to answer them. Remember that the interviewer is trying to gauge not only how successfully you solved problems but also the strategies and skills you used to do so.

  1. Tell me about a time when you handled a challenging situation.
  2. Tell me about a time when you made a mistake. What did you do to correct it?
  3. Tell me about a time when you were in conflict with a peer and how the situation was resolved.
  4. Tell me about how you work under pressure.
  5. Give me an example of how you set goals.
  6. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.
  7. Share an example of how you were able to motivate a coworker, your peers or your team.
  8. Tell me about a goal you set and reached and how you achieved it.
  9. Tell me about the last time your workday ended before you were able to get everything done.
  10. Tell me about a goal you failed to achieve.

1. Tell me about a time when you handled a challenging situation.

With this question, the interviewer wants to see how you handle challenging situations when they arise. A great example is one where you successfully problem-solved to overcome the challenge. It could also be an example of a time you made mistakes in handling the challenge but learned from the experience and know what you would do differently next time.

Example: *”*My manager left town unexpectedly when we in the middle of pitching large sponsors for an upcoming conference. I was tasked with putting together the slide decks for the presentations to secure these sponsors but all I had was a few notes left behind by my manager. Because he was unavailable, I called a meeting with members of our team and we generated a list of the biggest selling points that would be most impactful with potential sponsors. After creating the slide deck, I presented the presentation successfully and we got the sponsorship. I’m incredibly proud of the results we achieved when we worked together.”

2. Tell me about a time when you made a mistake. What did you do to correct it?

The interviewer understands that everyone makes mistakes. What they want to know, with this question, is how you handle mistakes. A great response to this question is one in which you take full responsibility for the mistake, worked hard to correct it and took steps to minimize the likelihood that it would happen again.

Example: “When I was working at a printing company, I misquoted the fees for a particular job. I realized the mistake, I went directly to my manager and explained what happened. He said he appreciated my honesty and suggested that we waive the setup fee for the job as an apology to the customer. I spoke to the customer directly and explained what happened and that the quoted price was actually higher than my original estimate, but that we would be happy to waive the setup fee. The customer understood and appreciated the effort to make the situation right. After that happened, I printed our price sheet to have it quickly at hand and implemented a new process for quoting estimates, one in which I double-check the final estimate before sending it.”*

3. Tell me about a time when you were in conflict with a peer and how the situation was resolved.

In workplaces where there are a large number of people with different personality types and communication styles, conflicts can occur. The interviewer wants to see, with this question, how you handle conflicts in the workplace and what your conflict resolution strategy is. A great answer is one where you demonstrate a specific strategy that you used to resolve a problem and find a mutually agreeable resolution.

Example: *”I had a sales manager who was great about stepping in to help when members of our team were struggling with meeting goals. However, she had a single approach that didn’t work for everyone and members of our team were getting frustrated and felt they were being micro-managed. I suggested that I sit down one-on-one with our manager, having heard the frustrations of the team. I avoided us all sitting down because I didn’t want her to feel ganged up on and become defensive. After talking, we decided that she would let team members know her door was open if they needed help but that she would let them be in charge of the strategy they used to meet their goals. We also implemented a monthly, optional training program where we had different team members present what was working for them in order to offer a variety of approaches.”*

4. Tell me about how you work under pressure.

The interviewer is using this question to see how well you work under pressure and what strategies you have used in the past to handle the pressure. This question is especially important if you’re interviewing for a high-stress job. A great answer will give a specific example of how you managed a high-pressure situation successfully. It could also include what you would have done differently, looking back.

Example: *”I had been working on a large project that my team committed to turning around for the client in 60 days. My manager came to me and said that the client wanted it back in 45 days and that we would need to speed up our work without losing momentum on our other projects. I met with our team and we reviewed the calendar. We eliminated team meetings and shifted lower-priority tasks until the end of the 45-day period to add extra hours to our workweeks. I challenged my team to complete the project in 45 days or left and as a reward promised two days of extra PTO time. Our team got the job done in 42 days.”*

5. Give me an example of how you set goals.

This question is designed to show the interviewer how well you plan and set goals. A great answer is one where you discuss an ambitious goal you set for yourself and how you came up with a plan for success.

Example: *”Within a few weeks of beginning my job as a server at a restaurant, I knew I wanted to work in the foodservice industry as a chef. I decided I would learn all I could in my current position until an opening became available in the kitchen, even for less pay. I wanted the experience of working in a restaurant kitchen environment. I also started saving up money at that time to go to the culinary academy. I knew that by the time I finished school, I would have been working in the kitchen for a number of years and would be highly competitive as a candidate for chef roles.”*

6. Give me an example of a time you made a decision that was unpopular and explain how you handled implementing it.

Managers sometimes have to make difficult decisions that aren’t popular with all employees. The interviewer wants to know how you handle this situation and how you implemented the new policy or plan. A great answer is one where you show you moved forward with the decision but communicated your reasoning to garner the support of more of the employees.

Example: *”I took over management of a gym where the trainers were allowed to cover one another’s shifts without the knowledge or approval of management. I didn’t like the uncertainty involved, because if someone failed to show up for a class, there was no way to know which trainerwas supposed to be there. I implemented a new policy that required trainers to go through management to make schedule changes. I also explained the problem with the previous approach and how this would resolve any possible issues.”*

7. Share an example of how you were able to motivate a coworker, your peers or your team.

With this question, the interviewer is evaluating your ability and willingness to lead, even informally. A great answer is one that shows you provided encouragement and offered help in some way. This could mean you offered to help with some work if they’ve fallen behind or that you suggested helping them with strategies to move through their work more quickly and efficiently.

Example: *”I noticed that one of my coworkers was having a hard time meeting her sales quotas each month. I told her that not every sales technique works for every personality and that it can take time to figure out what will work best for her. I suggested we find time over the next day or two and I would show her some techniques I was using that I found highly effective. And it worked! After a couple of weeks of practice and trial and error, she was consistently hitting her quota.”*

8. Tell me about a goal you set and reached and how you achieved it.

For this question, the interviewer wants to see how you plan to achieve a goal. A good answer is one where you were given a goal, created a plan and followed the necessary steps to achieve it. A great answer is one where you set your own goal, especially a large goal, and took the necessary steps to reach it.

Example: “

9. Tell me about the last time your workday ended before you were able to get everything done.

This question is designed to evaluate your commitment, work ethic, prioritization skills and ability to communicate. While the interviewer doesn’t expect heroic efforts daily, they do want to see a level of dedication to getting your job done. A great answer is that you either stayed late to finish your work, came in early the next day or prioritized differently. It’s also important to emphasize that you communicated to others that you might miss a deadline in case changes need to be made or clients need to be contacted.

Example: *”We had a client wanted us to deliver new social media content to them by Wednesday of each week to get it scheduled for the following week. One week they requested double the content in order to increase their online activity in advance of a big launch. I decided to stay late the night before the deliverable was due. I also let the manager know that we might be a few hours behind for our content that week. A coworker and I went in early the next morning, together, made our deadline.”*

10. Tell me about a goal you failed to achieve.

With this question, the interviewer is evaluating how you handle disappointment and failure. They also want to see how you decide when it’s time to give up, accept that something didn’t work and move forward. A great response is one where you set a huge goal, didn’t achieve it, took responsibility and learned from the experience. Some examples of things you could learn from it are what you would do differently next time, something about yourself, what motivates you or what is truly important to you.

Example: *”I was working on a start-up where our goal was to create content that would educate parents about why it’s important to spend time as a family around the dinner table. Unfortunately, we were never able to figure out a way to monetize the business. We polled our audience and tried many different ideas, but after a year we had to move on. However, I learned so much from the process. I developed numerous skills and realized I’m incredibly good at shifting direction when something isn’t working. I realized I don’t let defeats discourage me for long. Each time something didn’t work, I picked myself back up and moved forward.”*

The Standard of Code Review

The primary purpose of code review is to make sure that the overall code health of Google’s code base is improving over time. All of the tools and processes of code review are designed to this end.

In order to accomplish this, a series of trade-offs have to be balanced.

First, developers must be able to make progress on their tasks. If you never submit an improvement to the codebase, then the codebase never improves. Also, if a reviewer makes it very difficult for any change to go in, then developers are disincentivized to make improvements in the future.

On the other hand, it is the duty of the reviewer to make sure that each CL is of such a quality that the overall code health of their codebase is not decreasing as time goes on. This can be tricky, because often, codebases degrade through small decreases in code health over time, especially when a team is under significant time constraints and they feel that they have to take shortcuts in order to accomplish their goals.

Also, a reviewer has ownership and responsibility over the code they are reviewing. They want to ensure that the codebase stays consistent, maintainable, and all of the other things mentioned in “What to look for in a code review.”

Thus, we get the following rule as the standard we expect in code reviews:

In general, reviewers should favor approving a CL once it is in a state where it definitely improves the overall code health of the system being worked on, even if the CL isn’t perfect.

That is the senior principle among all of the code review guidelines.

There are limitations to this, of course. For example, if a CL adds a feature that the reviewer doesn’t want in their system, then the reviewer can certainly deny approval even if the code is well-designed.

A key point here is that there is no such thing as “perfect” code—there is only better code. Reviewers should not require the author to polish every tiny piece of a CL before granting approval. Rather, the reviewer should balance out the need to make forward progress compared to the importance of the changes they are suggesting. Instead of seeking perfection, what a reviewer should seek is continuous improvement. A CL that, as a whole, improves the maintainability, readability, and understandability of the system shouldn’t be delayed for days or weeks because it isn’t “perfect.”

Reviewers should always feel free to leave comments expressing that something could be better, but if it’s not very important, prefix it with something like “Nit: “ to let the author know that it’s just a point of polish that they could choose to ignore.

Note: Nothing in this document justifies checking in CLs that definitely worsen the overall code health of the system. The only time you would do that would be in an emergency.

Mentoring

Code review can have an important function of teaching developers something new about a language, a framework, or general software design principles. It’s always fine to leave comments that help a developer learn something new. Sharing knowledge is part of improving the code health of a system over time. Just keep in mind that if your comment is purely educational, but not critical to meeting the standards described in this document, prefix it with “Nit: “ or otherwise indicate that it’s not mandatory for the author to resolve it in this CL.

Principles

  • Technical facts and data overrule opinions and personal preferences.
  • On matters of style, the style guide is the absolute authority. Any purely style point (whitespace, etc.) that is not in the style guide is a matter of personal preference. The style should be consistent with what is there. If there is no previous style, accept the author’s.
  • Aspects of software design are almost never a pure style issue or just a personal preference. They are based on underlying principles and should be weighed on those principles, not simply by personal opinion. Sometimes there are a few valid options. If the author can demonstrate (either through data or based on solid engineering principles) that several approaches are equally valid, then the reviewer should accept the preference of the author. Otherwise the choice is dictated by standard principles of software design.
  • If no other rule applies, then the reviewer may ask the author to be consistent with what is in the current codebase, as long as that doesn’t worsen the overall code health of the system.

Resolving Conflicts

In any conflict on a code review, the first step should always be for the developer and reviewer to try to come to consensus, based on the contents of this document and the other documents in The CL Author’s Guide and this Reviewer Guide.

When coming to consensus becomes especially difficult, it can help to have a face-to-face meeting or a video conference between the reviewer and the author, instead of just trying to resolve the conflict through code review comments. (If you do this, though, make sure to record the results of the discussion as a comment on the CL, for future readers.)

If that doesn’t resolve the situation, the most common way to resolve it would be to escalate. Often the escalation path is to a broader team discussion, having a Technical Lead weigh in, asking for a decision from a maintainer of the code, or asking an Eng Manager to help out. Don’t let a CL sit around because the author and the reviewer can’t come to an agreement.