CoreJava Tricky
CoreJava Tricky
Home › Quick Prep Java Interview › 300+ Java Interview FAQs 📌 › Java FAQs - 03: Core Java 📌 › 00: Top
50+ Core Java interview questions & answers for 1 to 3 years experience
experience
150+ Java Architect FAQs
100+ Java code quality Q&As
150+ Java coding Q&As
Posted on June 24, 2024
comparing the two object references to see if they point to the same
object. When you use “equals(…)”, which is a “deep comparison” that
compares the actual string values. For example: Key Areas & Companion
Techs FAQs
String Pool Caches and you create a String object as a literal without the “new” keyword for caching
In Java 7 – the string pool was relocated to the heap. So, you are not
restricted by the limited size.
String class
Q2. Can you explain how Strings are interned in Java?
A2. String class is designed with the Flyweight design pattern in
mind. Flyweight is all about re-usability without having to create too
many objects in memory.
to this object is returned. For any two given strings s1 & s2,
s1.intern( ) == s2.intern( ) only if s1.equals(s2) is true.
Two String objects are created by the code shown below. Hence s1
== s2 returns false.
1 //Two new objects are created. Not interned and not recommende
2 String s1 = new String("A");
3 String s2 = new String("A");
4
1 String s1 = "A";
2 String s2 = "A";
3
read only objects. They can easily be shared among multiple threads
for better scalability.
If you use a char[] instead, you can override it with some dummy
values once done with it, and also logging the char[] like
“[C@5829428e” is not as bad as logging it as String “password123”.
1
2 public class Person {
3
4 //instance variables
5 private String name;
6 private int age;
7
8 //constructor
9 public Person(String name, int age) {
10 this.name = name;
11 this.age = age;
12 }
13
14 public static void main(String[] args) {
15 Person p1 = new Person("John", 25); // "p1" is object
16 String greeting = "Hello"; // "greeting" is a
17 p1.addOneAndPrint(greeting);
18 }
19
20 public void addOneAndPrint(String param) {
21 int valToAdd = 1; // local pri
22
23
this.age = this.age + valToAdd; // instance
System.out.println(param + "! " + this); // calls toS
https://www.java-success.com/50-core-java-interview-questions-answers/ 4/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
24 }
25
26 @Override
27 public String toString() {
28 return name + " you are now " + age;
29 }
30 }
31
32
A4. The above code outputs “Hello! John you are now 26”. The
following diagram depicts how the different variable references &
actual objects get stored.
Stack: is where local variables both primitives like int, float, etc &
references to objects in the heap and method parameters are stored
as shown in the above diagram.
Heap: is where objects are stored. For example, an instance of
“Person” with name=”John” and age=25. Strings will be stored in
String Pool within the heap.
//Pre Java 7
1 BufferedReader br = null;
2 try {
3 File f = new File("c://temp/simple.txt");
4 InputStream is = new FileInputStream(f);
5 InputStreamReader isr = new InputStreamReader(is);
6 br = new BufferedReader(isr);
7
8 String read;
9
10 while ((read = br.readLine()) != null) {
11 System.out.println(read);
12 }
13 } catch (IOException ioe) {
14 ioe.printStackTrace();
15 } finally {
16 //Hmmm another try catch. unsightly
17 try {
18 if (br != null) {
19 br.close();
20 }
21 } catch (IOException ex) {
22 ex.printStackTrace();
23 }
24 }
25
“try” can now have multiple statements in the parenthesis and each
statement should create an object which implements the new
java.lang.AutoClosable interface. The AutoClosable interface
consists of just one method. void close() throws Exception {}. Each
AutoClosable resource created in the try statement will be
automatically closed without requiring a finally block. If an exception
is thrown in the try block and another Exception is thrown while
closing the resource, the first Exception is the one eventually thrown
to the caller. Think of the close( ) method as implicitly being called
as the last line in the try block. If using Java 7 or later editions, use
AutoCloseable statements within the try block for more concise &
readable code.
So, final and finally are used very frequently in your Java code, but
the modifier finalize is hardly or never used.
It has been deprecated from Java 9 onwards.
1
2 import java.util.concurrent.TimeUnit;
3
4 class Counter extends Thread {
5
6 //instance variable
7 Integer count = 0;
8
9 // method where the thread execution will start
10 public void run() {
11 int fixed = 6; //local variable
12
13 for (int i = 0; i < 3; i++) {
14 System.out.println(Thread.currentThread().getName
15 + performCount(fixed));
16 try {
17 TimeUnit.SECONDS.sleep(1);
18 } catch (InterruptedException e) {
19 e.printStackTrace();
20 }
21 }
22 }
23
24 // let’s see how to start the threads
25 public static void main(String[] args) {
26 System.out.println(Thread.currentThread().getName() +
27 Counter counter = new Counter();
28
29 //5 threads
30 for (int i = 0; i < 5; i++) {
31 Thread t = new Thread(counter);
32 t.start();
33 }
34
35 }
36
37 //multiple threads can access me concurrently
38 private int performCount(int fixed) {
https://www.java-success.com/50-core-java-interview-questions-answers/ 8/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
39 return (fixed + ++count);
40 }
41 }
42
If you do the wrong thing, you will get “compile-time” errors. Also,
note that you can’t use wildcards on the RHS when assigning and
Java 8 supports empty “<>” on the RHS.
When you are using wildcard List<? super Dog>, means assignable
from anything of type Dog, or any superclasses of type Dog. You can
add any subclasses of type Dog because of polymorphism where a
parent type reference can hold its subclass types.
When you are using wildcard List<? extends Dog>, means assignable
from anything of type Dog, or any subclasses of type Dog. This is
read only, and can’t add anything to this collection.
https://www.java-success.com/50-core-java-interview-questions-answers/ 9/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
In summary:
Java OO concepts
Q8. Can you describe “method overloading” versus “method
overriding”? Does it happen at compile time or runtime?
A8. Overloading deals with multiple methods in the same class with
the same name but different method signatures. Both the below
methods have the same method names but different method
signatures, which mean the methods are overloaded.
1 public class {
2 public static void evaluate(String param1); // overloaded
3 public static void evaluate(int param1); // overloaded
4 }
5
It could see that the argument was a “string” literal, and generates
byte code that called method #1.
1 evaluate(5);
2
https://www.java-success.com/50-core-java-interview-questions-answers/ 10/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
It could see that the argument was an “int”, and generates byte code
that called method #2.
Overloading lets you define the same operation in different ways for
different data.
Overriding deals with two methods, one in the parent class and the
other one in the child class and has the same name and same
signatures. Both the below methods have the same method names
and the signatures but the method in the subclass “B” overrides the
method in the superclass (aka the parent class) “A”.
Parent class
1 public class A {
2 public int compute(int input) { //method #3
3 return 3 * input;
4 }
5 }
6
Child class
The compiler would not know whether the input argument ‘reference‘
is of type “A” or type “B”. This must be determined during runtime
whether to call method #3 or method #4 depending on what type of
https://www.java-success.com/50-core-java-interview-questions-answers/ 11/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
1 A obj1 = new B( );
2 A obj2 = new A( );
3 evaluate(obj1, 5); // 4 * 5 = 20. method #4 is invoked as sto
4 evaluate(obj2, 5); // 3 * 5 = 15. method #3 is invoked as sto
5
Overriding lets you define the same operation in different ways for
different object types. It is determined by the “stored” object type,
and NOT by the “referenced” object type.
https://www.java-success.com/50-core-java-interview-questions-answers/ 12/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
1 class MyClass {
2 public static void main(String args[]) {
3 Car c = new Car( );
4 }
5 }
6
https://www.java-success.com/50-core-java-interview-questions-answers/ 13/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
The above static method “forName” & the below instance (i.e. non-
static method) “loadClass”
return the class object associated with the class name.Once the
class is dynamically loaded the following method returns an
instance of the loaded class. It’s just like creating a class object with
no arguments.
1
2 public void process(String classNameSupplied) {
3 Object vehicle = Class.forName (classNameSupplied).newInsta
4 //......
5 }
6
1 Class.forName("com.SomeClass");
and
1 classLoader.loadClass("com.SomeClass");
A.
https://www.java-success.com/50-core-java-interview-questions-answers/ 14/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
Class.forName(“com.SomeClass”)
— Uses the caller’s classloader and initializes the class (runs static
intitializers, etc.)
classLoader.loadClass(“com.SomeClass
”)
— Uses the “supplied class loader”, and initializes the class lazily (i.e.
on first use). So, if you use this way to load a JDBC driver, it won’t get
registered, and you won’t be able to use JDBC.
1
2 forName(String name, boolean initialize, ClassLoader loader)
3
So, invoking
1 Class.forName("com.SomeClass")
is same as invoking
1
2 ClassLoader classLoader = Thread.currentThread().getContextCla
3 ClassLoader classLoader = MyClass.class.getClassLoader();
4 ClassLoader classLoader = getClass().getClassLoader();
5
1
2 final Properties properties = new Properties();
https://www.java-success.com/50-core-java-interview-questions-answers/ 15/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
3 try (final InputStream stream = this.getClass().getResourceAsS
4 properties.load(stream);
5 /* or properties.loadFromXML(...) */
6 }
7
1
2 final Properties properties = new Properties();
3 final String dir = System.getProperty("user.dir");
4
5 try (final InputStream stream = new FileInputStream(dir + "/m
6 properties.load(stream);
7 }
8
As the above code is NOT portable, you must document very clearly
in the installation or deployment document as to where the
.properties file is loaded from because if you deploy your “jar” file to
another location, it might not already have the path “myapp”
configured.
https://www.java-success.com/50-core-java-interview-questions-answers/ 16/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
New to Java?
If you are new to Java you can look at: Core Java interview Q&As for
freshers and 17 Java Beginner Interview Questions and Answers.
‹ 27: 50+ SQL scenarios based interview Q&As – identifying consecutive records – job status
repetition
12: PySpark working with SQL syntax Interview Q&As with tutorials ›
Arulkumaran Kumaraswamipillai
Mechanical Engineer to self-taught Java engineer in 1999. Contracting since 2002 as a Java Engineer &
Architect and since 2016 as a Big Data Engineer & Architect. Preparation & key know-hows empowered me
to attend 150+ job interviews, choose from 130+ job offers & negotiate better contract rates. Author of the
book "Java/J2EE job interview companion", which sold 35K+ copies & superseded by this site with 3.5K+
registered users Amazon.com profile | Reviews | LinkedIn | LinkedIn Group | YouTube Email: java-
interview@hotmail.com
"You are paid to read & write lots of code & solve business problems in a
collaborative environment"
100+ Free Java Interview FAQs
100+ Free Big Data Interview FAQs
https://www.java-success.com/50-core-java-interview-questions-answers/ 17/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
Don't be overwhelmed by the number of Q&As. Job interviews are not technical contests to see who gets most number of questions right.
Nobody knows everything. The Clarity of the answers you give with real-life examples will go a long way in getting you multiple job offers.
It pays to brush-up & choose from 2-6 job offers. Experienced interviewers can easily judge your real experience from a few open-ended
questions & the answers you provide.
1. Feeling stagnated?
2. How to earn more?
3. Freelancing Vs contracting?
4. Self-taught professional?
5. Job Interview Tips
6. Resume Writing Tips
300+ Big Data Interview Q&As with code, scenarios & FAQs
100+ SQL Interview Q&As 01. 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code? 02.…
(2,400)
00: Top 50+ Core Java interview questions & answers for 1 to 3 years experience
Top 50 core Java interview questions covering core Java concepts with diagrams, code, examples, and scenarios. If you don't get…
(1,946)
Java 8 String streams and finding the first non repeated character with functional programming
Q1.Find the first non repeated character in a given string input using Java 8 or later? A1.Extends Find the first…
(1,647)
Membership Levels
Membership prices listed below are in Australian Dollars (A$). If you purchase in other currencies like Indian rupees, the equivalent…
(702)
The SAR (Situation-Action-Result) technique is very useful to tackle open-ended questions like: 1. What were some of the challenges you…
(504)
https://www.java-success.com/50-core-java-interview-questions-answers/ 18/19
06/12/2024, 19:05 Top 50+ Core Java interview questions & answers
0: 50+ SQL scenarios based interview Q&As – What is wrong with this SQL code?
This extends 18+ SQL best practices & optimisation interview Q&As. You can practice these SQLs by setting up the data…
(365)
Disclaimer
The contents in this Java-Success are copyrighted and from EmpoweringTech pty ltd. The EmpoweringTech pty ltd has the right to correct or enhance the current content without
any prior notice. These are general advice only, and one needs to take his/her own circumstances into consideration. The EmpoweringTech pty ltd will not be held liable for any
damages caused or alleged to be caused either directly or indirectly by these materials and resources. Any trademarked names or labels used in this blog remain the property of
their respective trademark owners. Links to external sites do not imply endorsement of the linked-to sites. Privacy Policy
© 2024 800+ Big Data & Java Interview FAQs Responsive WordPress Theme powered by CyberChimps
Top
https://www.java-success.com/50-core-java-interview-questions-answers/ 19/19