Mastering Static in Java: Top Interview Questions and Answers

If you’re interviewing for a Java programming role, then your coding skills will probably be tested. This article has some common Java interview questions and answers that can help you get ready, no matter how much you know about the language.

There is no reverse() utility method in the String class. You can, however, turn the string into a character array and then read it from beginning to end. You can append the characters to a string builder and finally return the reversed string.

Bonus points for adding null check in the method and using StringBuilder for appending the characters. Note that the indexing in Java starts from 0, so you need to start at chars. length – 1 in the for loop.

Swapping numbers without using a third variable is a three-step process that’s better visualized in code:

The following example code shows how to use a regular expression to check whether the string contains vowels:

You can make a program that takes the given number n, divides it by any number from 2 to n/2, and then checks the result. If the remainder is 0, then it’s not a prime number. The following example code shows one way to check if a given number is a Prime number:

Although this program works, it’s not very memory and time-efficient. There is a prime number M between 2 and ∢N (square root of N) that divides a given number N evenly. This means that N is not a prime number.

A Fibonacci sequence is one in which each number is the sum of the two previous numbers. In this example, the sequence begins with 0 and 1. The following example code shows how to use a for loop to print a Fibonacci sequence:

You can also print a Fibonacci sequence with recursion, since the Fibonacci number is made by adding the two numbers that came before it:

You can use recursion to figure out a 10-number Fibonacci sequence in the following example class:

If the list is long, you can use parallel stream to process it faster, as shown in the code below:

Go to Wikipedia and look up the modulo operation to learn more about the math behind finding out if an integer is odd.

A palindrome string is the same string backwards or forwards. Check for a palindrome by putting the string backwards and seeing if the result is the same as the string you put in. The following example code shows how to use the String charAt(int index) method to check for palindrome strings:

The following example code shows one way to remove spaces from a string using with the Character.isWhitespace() method:

The String class contains two methods to remove leading and trailing whitespaces: trim() and strip(). The strip() method was added to the String class in Java 11. The strip() method uses the Character. isWhitespace() method to check if the character is a whitespace. This method works with Unicode code points, while the trim() method sees as a whitespace character any character whose codepoint value is less than or equal to U 0020.

The strip() method is the recommended way to remove whitespaces because it uses the Unicode standard. The following example code shows how to use the strip() method to remove whitespaces:

The Arrays utility class has many overloaded sort() methods to sort primitive and to object arrays. If you are sorting a primitive array in the natural order, then you can use the Arrays. sort() method, as shown in the following example:

However, if you want to sort an array of objects, then the object must implement the Comparable interface. If you want to specify the sorting criteria, then you can pass the Comparator for the sorting logic. Learn more about Comparable and Comparator in Java.

Deadlock is a scenario in a multi-threaded Java environment where two or more threads are blocked forever. The deadlock situation arises with at two or more threads. The following example code creates a deadlock scenario:

All three threads will be able to acquire a lock on the first object. They are, however, using shared resources and are set up in a way that means they will never be able to get the lock on the second object. You can use the Java thread dump to detect the deadlocks. Learn more about deadlock in Java.

The factorial of an integer is calculated by multiplying all the numbers from 1 to the given number:

The following example code shows how to use recursion to find the factorial of an integer:

LinkedList descendingIterator() returns an iterator that iterates over the element in reverse order. This iterator can be used to make a new Linked List with elements listed in the opposite order, as shown in the code below:

The array elements must be sorted to implement binary search. The binary search algorithm is based on the following conditions:

Merge sort is one of the most efficient sorting algorithms. It works on the principle of “divide and conquer”. It works by splitting a list into smaller lists until each list only has one item, then joining those smaller lists together in a way that makes the main list sorted. The following example code shows one way to use merge sort:

Pattern programs are a very popular interview topic. This type of question is used to understand the logical thinking abilities of the interviewee. Refer to Pyramid Pattern Programs in Java for examples of different ways to create pyramid patterns.

To find out if two arrays have the same elements, you must first make a set of elements from each array. Then, you must compare these sets to see if there is an element that is missing from both sets. The following example code shows how to check if two arrays only contain common elements:

Here’s how to use a for loop to go through the elements of an array and add them all up:

There are many ways to solve this problem. You can sort the array in natural ascending order and take the second last value. However, sorting is an expensive operation. You can also use two variables together to find the second biggest number in a single loop, as this example shows:

The code below shows how to use the Random class to mix up the elements and make random index numbers:

To read the file’s contents line by line with the Scanner class, use the code below. Then, use the String contains() method to see if the string is in the file:

Keep in mind that the code example assumes that the string you’re looking for in the file doesn’t have any newline characters in it.

The following example code shows how to use the SimpleDateFormat class to format the date string:

The following example code shows how to use the addAll() method to merge multiple lists in Java:

HashMap is not an ordered collection. Here’s some code that sorts the entries by value and stores them in a LinkedHashMap that remembers the order in which they were added:

The String class doesn’t have a method to remove characters. The code below shows how to use the replace() method to make a new string that doesn’t have the given character:

String is immutable in Java. All methods that work with strings return a new string, which is why you need to link it to another variable. Learn more about removing characters from a string in Java.

You can create the character array from the string. Then iterate over it and create a HashMap with the character as key and their count as value. The following example code shows how to extract and count the characters of a string:

The code below shows how to show that a String object can’t be changed, and the comments in the code explain each step:

The code below shows how to use the keyword “extends” to make a child class of the Animal class. The Animal class’s variable is passed on to the new Cat class, which also adds some code that is unique to Cat.

The diamond problem happens when a class inherits from more than one class, and ambiguity happens when it’s not clear which class’s method to run. Java doesn’t allow extending multiple classes to avoid the diamond problem illustrated by the following example:

As of Java 7, you can also catch more than one exception in the same catch block, as this example shows. It’s useful when you have the same code in all the catch blocks.

A NullPointerException will be thrown if you call a function on null, as shown in the code below:

You should have null check in place for early validation, as shown in the following example code:

Records was added as a standard feature in Java 16. Records enable you to create a POJO class with minimal code. Records automatically generates hashCode(), equals(), getter methods, and toString() method code for the class. Records are final and implicitly extend the java. lang. Record class. The following example code shows one way to cerate a record:

Learn more about records in Java. For details about POJO, refer to Plain old Java object on Wikipedia.

Java 15 added the text blocks feature. You can create multiline strings using text blocks. That’s right, the multiline string needs to be written between two triple-double quotes, like this:

The switch expressions were added as a standard feature in Java 14. The following examples show switch expressions as well as multi-label case statements:

In newer versions, the java command will also compile the program even if the class file is missing. If the class is in a package, such as com. example, then it should be inside the folder com/example. The command to compile and run is:

If your class requires some additional JARs to compile and run, you can use the java -cp option. For example:

ThreadStates is the enum with fixed constants fields START, RUNNING, WAITING, and DEAD. All enums implicitly extend the java. lang. Enum class and implement the Serializable and Comparable interfaces. Enum can have methods also. Learn more about enums in Java.

The forEach() method provides a shortcut to perform an action on all the elements of an iterable. The following example code shows how to iterate over the list elements and print them:

To make the code smaller, you can use the forEach() method with a lambda expression, like in the code below:

Java 8 introduced default and static methods in interfaces. This bridged the gap between interfaces and abstract classes. The following example code shows one way to write an interface with the default and static method:

An interface with exactly one abstract method is called a functional interface. The best thing about functional interfaces is that you don’t have to use big anonymous classes to set them up; instead, you can use lambda expressions. The @FunctionalInterface annotation indicates a functional interface, as shown in the following example code:

Runnable is an excellent example of a functional interface. You can use lambda expressions to create a runnable, as shown in the following example code:

When a class has two or more methods with the same name, they are called overloaded methods. The following example code shows as overloaded method called print:

When a superclass method is also implemented in the child class, it’s called overriding. The following example code shows how to annotate the printname() method that’s implemented in both classes:

The given statement’s result is false because the operator comes before the == operator. So the given expression is evaluated to “s1 == s2 is:abc” == “abc”, which is false.

The output of the given statement is ourn. The first character is automatically type cast to int. Then, since the first character index is 0, it will start from o and print until n. Keep in mind that the String substring method makes a substring that starts at index start and goes to index end -1.

The size of the shortSet is 100. Because Java has autoboxing, the expression i, which has the primitive type short, turns into a Short object. Similarly, the expression i – 1 has the primitive type int and is autoboxed to an Integer object. Since there is no Integer object in the HashSet, nothing is removed and the size is 100.

No output. If the flag is true, this code will create an endless loop. If the flag is false, the program will run. The finally block will never be reached.

The given print statement will throw a java. lang. NullPointerException because the OR logical operator evaluates both the literals before returning the result. Since str is null, the . equals() method will throw an exception. It is always best to use short-circuit logical operators like || and In this case, since the first literal would return true, it would skip the second literal evaluation.

The x. concat(y) creates a new string but is not assigned to x, so the value of x is not changed.

It might look like this question is about the order in which the math operators are run, but it’s really about noticing that the main method wasn’t declared static.

This code results in a compile time error. The exception IOException is already caught by the alternative Exception.

You can use this list of 50 Java programming interview questions, which range from easy to hard, to help you prepare for your interview.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Static is one of the fundamental concepts in Java that every developer should understand thoroughly. It comes up frequently in Java interviews across all levels. Having a solid grasp of static will help you ace those tough technical interviews and demonstrate your depth of knowledge.

In this comprehensive guide, we will explore the ins and outs of static in Java along with some common interview questions and detailed answers. Let’s get started!

What Does Static Mean in Java?

The static keyword in Java indicates that a member belongs to a class itself rather than instances of that class. Static members include static variables, static methods, static blocks, and static nested classes.

Some key properties of static members

  • They are associated with the class rather than individual objects
  • A single copy is shared across all instances
  • They can be accessed without creating an instance of the class
  • Static methods can only directly access other static members

Understanding this central concept will help you reason through many nuances around using static in Java.

Top 10 Static Interview Questions and Answers

Here are some of the most frequently asked Java interview questions on static along with detailed explanations

Q1. Can you explain the purpose of the static keyword in Java?

The static keyword serves two main purposes in Java:

  1. It allows defining class members that are shared across all instances of the class. There is only one copy of the static member rather than each instance having its own copy

  2. It allows accessing static members without requiring an instance of the class. This is because they belong to the class itself.

Q2. What is a static variable in Java?

A static variable, also called a class variable, is a variable that is declared with the static keyword inside a class but outside any method. It belongs to the class rather than individual objects.

Some key properties:

  • A single copy exists per class regardless of how many objects are created
  • It is created and initialized when the class is loaded
  • All instances share the same static variable
  • Can be accessed via the class name rather than a particular object

Q3. What is a static method in Java?

A static method is a method declared with the static keyword in a class. Some important facts:

  • Belongs to the class rather than any instance
  • Can be called without creating an instance of the class
  • Cannot access instance members directly and vice versa
  • Cannot be overridden, but can be overloaded
  • Useful for utility or helper methods not tied to a particular object

Q4. What is a static block in Java?

A static block is a block of code inside a class marked with the static keyword. It contains code that needs to be executed when the class is loaded into memory by the JVM.

Key properties of static blocks:

  • Executed before the main method when the class is loaded
  • Used to initialize static variables or perform other one-time setup
  • Since it is static, cannot access instance members directly
  • Can have multiple static blocks per class executing in order

Q5. Can you differentiate between a static block and a constructor in Java?

While both are used for initialization, there are some key differences:

  • Static block runs when the class is loaded while constructor runs when an object is instantiated.
  • Static block can access only static members directly while constructor can access both static and non-static members.
  • Static block executes before constructor when loading a class into memory.
  • We can have multiple static blocks but only one constructor per class in Java.

Q6. Can you create a static inner class in Java?

Yes, we can declare an inner class as static in Java. A static inner class is tied to the outer class and can access static members of the outer class directly.

Some key properties of static inner classes:

  • Does not require an instance of outer class to be created
  • Cannot access non-static (instance) members of the outer class directly
  • Useful for defining utility classes encapsulated within another class
  • Commonly used for implementation classes in the Singleton pattern

Q7. Why do we use static keywords in Java?

Some common reasons for using static in Java include:

  • To define class-level constants e.g. final static PI = 3.14 that are shared across all instances
  • To group utility methods that don’t require any state e.g. Math.max()
  • Avoiding the cost of creating duplicate copies across instances when not required
  • One-time initialization of resources or state for the class
  • Accessing class members without needing an object instance
  • Implementing Singleton patterns where only one instance of a class can exist

Q8. Can static methods be overridden in Java?

No, static methods cannot be overridden in Java. Method overriding only applies to instance methods.

Since static methods belong to the class itself, the method called is decided at compile time based on the reference type rather than dynamic polymorphism at runtime.

Q9. Is it possible to access static members using an instance of the class?

Yes, it is possible to call static members using an instance of the class. However, doing so is considered bad practice and against conventions.

The recommended way is using the class name rather than an instance to access statics since they belong to the class itself.

Q10. Can interfaces have static methods in Java?

Yes, interfaces can have static methods from Java 8 onwards. They are defined with the static keyword just like in a class.

Some key facts about static methods in interfaces:

  • Cannot be overridden, only overloaded
  • Implementing classes do not inherit the static methods
  • Commonly used for providing utility methods related to the interface

Static in Java – Key Takeaways

  • Static indicates a class member rather than instance member
  • Single copy exists for the entire class
  • Accessed via class name without requiring an instance
  • Static context can only directly access other static members
  • Commonly used for constants, utility methods, initialization blocks

Having a solid grasp of static will help you design classes better and master Java interviews on this topic. Use these questions to benchmark your knowledge and identify any areas that need more focus.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Please complete your information!

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Top 10 Static & Instance Block Based Interview Questions || Tricky Java Interview Questions

FAQ

What is static in programming?

What does static mean? When you declare a variable or a method as static, it belongs to the class, rather than a specific instance. This means that only one instance of a static member exists, even if you create multiple objects of the class, or if you don’t create any. It will be shared by all objects.

What is the static keyword in Java interview questions?

The static keyword in Java is used for memory management mainly. We can apply static keyword with variables, methods, blocks and nested classes. The static keyword belongs to the class than an instance of the class.

What is static method in programming?

A static method is a method that belongs to the class itself, not to any specific instance of the class. This means that you can call a static method without creating an object of the class first. A static method can access only static variables and other static methods of the class, not instance variables or methods.

What is static in C# interview questions?

The static constructor of a class is called before any instance of the class is created. The static constructor called here initializes the TestValue variable first.

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *