HowToDoInJava

  • Java 8
  • Regex
  • Concurrency
  • Best Practices
  • Spring Boot
  • JUnit5
  • Interview Questions
  • Dark Mode

Core Java Interview Questions – Part 1

By Lokesh Gupta | Filed Under: Interview Questions

Are you planning to learn core java? Or an interview is scheduled in coming days? Do not worry and read all interview questions given below to refresh your concepts and possibly have some new added in your best of java list.

Interview Questions List

How to create a immutable object in Java? Count all benefits?
Is Java Pass by Reference or Pass by Value?
What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?
Why there are two Date classes; one in java.util package and another in java.sql?
What is Marker interface?
Why main() in java is declared as public static void main?
What is the difference between creating String as new() and literal?
How does substring() inside String works?
Explain the working of HashMap.
Difference between interfaces and abstract classes?
When do you override hashCode and equals()?

How to create a immutable object in Java? Count all benefits?

An immutable class is one whose state can not be changed once created. Here, state of object essentially means the values stored in instance variable in class whether they are primitive types or reference types.

To make a class immutable, below steps needs to be followed:

  1. Don’t provide “setter” methods or methods that modify fields or objects referred to by fields. Setter methods are meant to change the state of object and this is what we want to prevent here.
  2. Make all fields final and private. Fields declared private will not be accessible outside the class and making them final will ensure the even accidentally you can not change them.
  3. Don’t allow subclasses to override methods. The simplest way to do this is to declare the class as final. Final classes in java can not be overridden.
  4. Always remember that your instance variables will be either mutable or immutable. Identify them and return new objects with copied content for all mutable objects (object references). Immutable variables (primitive types) can be returned safely without extra effort.

Also, you should memorize following benefits of immutable class. You might need them during interview. Immutable classes –

  • are simple to construct, test, and use
  • are automatically thread-safe and have no synchronization issues
  • do not need a copy constructor
  • do not need an implementation of clone
  • allow hashCode to use lazy initialization, and to cache its return value
  • do not need to be copied defensively when used as a field
  • make good Map keys and Set elements (these objects must not change state while in the collection)
  • have their class invariant established once upon construction, and it never needs to be checked again
  • always have “failure atomicity” (a term used by Joshua Bloch) : if an immutable object throws an exception, it’s never left in an undesirable or indeterminate state.

Take a look an example written in this post.

Is Java Pass by Reference or Pass by Value?

The Java Spec says that everything in Java is pass-by-value. There is no such thing as “pass-by-reference” in Java. These terms are associated with method calling and passing variables as method parameters. Well, primitive types are always pass by value without any confusion. But, the concept should be understood in context of method parameter of complex types.

In java, when we pass a reference of complex types as any method parameters, always the memory address is copied to new reference variable bit by bit. See in below picture:

pass-by-value

In above example, address bits of first instance are copied to another reference variable, thus resulting both references to point a single memory location where actual object is stored. Remember, making another reference to null will not make first reference also null. But, changing state from either reference variable have impact seen in other reference also.

Read in detail here: Java Pass by Value or Reference?

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

The finally block always executes when the try block exits. This ensures that the finally block is executed even if an unexpected exception occurs. But finally is useful for more than just exception handling — it allows having cleanup code accidentally bypassed by a return, continue, or break. Putting cleanup code in a finally block is always a good practice, even when no exceptions are anticipated.

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. Likewise, if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

Why there are two Date classes; one in java.util package and another in java.sql?

A java.util.Date represents date and time of day, a java.sql.Date only represents a date. The complement of java.sql.Date is java.sql.Time, which only represents a time of day.
The java.sql.Date is a subclass (an extension) of java.util.Date. So, what changed in java.sql.Date:

– toString() generates a different string representation: yyyy-mm-dd
– a static valueOf(String) methods to create a date from a string with above representation
– the getters and setter for hours, minutes and seconds are deprecated

The java.sql.Date class is used with JDBC and it was intended to not have a time part, that is, hours, minutes, seconds, and milliseconds should be zero… but this is not enforced by the class.

Explain marker interfaces?

The marker interface pattern is a design pattern in computer science, used with languages that provide run-time type information about objects. It provides a means to associate metadata with a class where the language does not have explicit support for such metadata. In java, it is used as interfaces with no method specified.

A good example of use of marker interface in java is Serializable interface. A class implements this interface to indicate that its non-transient data members can be written to a byte steam or file system.

A major problem with marker interfaces is that an interface defines a contract for implementing classes, and that contract is inherited by all subclasses. This means that you cannot “un-implement” a marker. In the example given, if you create a subclass that you do not want to serialize (perhaps because it depends on transient state), you must resort to explicitly throwing NotSerializableException.

Why main() in java is declared as public static void?

Why public? main method is public so that it can be accessible everywhere and to every object which may desire to use it for launching the application. Here, i am not saying that JDK/JRE had similar reasons because java.exe or javaw.exe (for windows) use Java Native Interface (JNI) calls to invoke method, so they can have invoked it either way irrespective of any access modifier.

Why static? Lets suppose we do not have main method as static. Now, to invoke any method you need an instance of it. Right? Java can have overloaded constructors, we all know. Now, which one should be used and from where the parameters for overloaded constructors will come.

Why void? Then there is no use of returning any value to JVM, who actually invokes this method. The only thing application would like to communicate to invoking process is: normal or abnormal termination. This is already possible using System.exit(int). A non-zero value means abnormal termination otherwise everything was fine.

What is the difference between creating String as new() and literal?

When we create String with new() it’s created in heap and also added into string pool, while String created using literal are created in String pool only which exists in Perm area of heap.

Well you really need to know the concept of string pool very deeply to answer this question or similar questions. My advise.. “Study Hard” about string class and string pool.

How does substring () inside String works?

String in java are like any other programming language, a sequence of characters. This is more like a utility class to work on that char sequence. This char sequence is maintained in following variable:

/** The value is used for character storage. */
private final char value[];

To access this array in different scenarios, following variables are used:

/** The offset is the first index of the storage that is used. */
private final int offset;

/** The count is the number of characters in the String. */
private final int count;

Whenever we create a substring from any existing string instance, substring() method only set’s the new values of offset and count variables. The internal char array is unchanged. This is a possible source of memory leak if substring() method is used without care. Read more here

Explain the working of HashMap. How duplicate collision is resolved?

Most of you will agree that HashMap is most favorite topic for discussion in interviews now-a-days. If anybody asks me to describe “How HashMap works?”, I simply answer: “On principles of Hashing“. As simple as it is.

Now, Hashing in its simplest form, is a way to assigning a unique code for any variable/object after applying any formula/ algorithm on its properties.

A map by definition is : “An object that maps keys to values”. Very easy.. right? So, HashMap has an inner class Entry, which looks like this:

static class Entry<k ,V> implements Map.Entry<k ,V>
{
final K key;
V value;
Entry<k ,V> next;
final int hash;
...//More code goes here
}

When, someone tries to store a key value pair in a HashMap, following things happen:

  • First of all, key object is checked for null. If key is null, value is stored in table[0] position. Because hash code for null is always 0.
  • Then on next step, a hash value is calculated using key’s hash code by calling its hashCode() method. This hash value is used to calculate index in array for storing Entry object. JDK designers well assumed that there might be some poorly written hashCode() functions that can return very high or low hash code value. To solve this issue, they introduced another hash() function, and passed the object’s hash code to this hash() function to bring hash value in range of array index size.
  • Now indexFor(hash, table.length) function is called to calculate exact index position for storing the Entry object.
  • Here comes the main part. Now, as we know that two unequal objects can have same hash code value, how two different objects will be stored in same array location [called bucket]. Answer is LinkedList. If you remember, Entry class had an attribute “next”. This attribute always points to next object in chain. This is exactly the behavior of LinkedList.

    So, in case of collision, Entry objects are stored in LinkedList form. When an Entry object needs to be stored in particular index, HashMap checks whether there is already an entry?? If there is no entry already present, Entry object is stored in this location.

    If there is already an object sitting on calculated index, its next attribute is checked. If it is null, and current Entry object becomes next node in LinkedList. If next variable is not null, procedure is followed until next is evaluated as null.

    What if we add the another value object with same key as entered before. Logically, it should replace the old value. How it is done? Well, after determining the index position of Entry object, while iterating over LinkedList on calculated index, HashMap calls equals() method on key object for each Entry object. All these Entry objects in LinkedList will have similar hash code but equals() method will test for true equality. If key.equals(k) will be true then both keys are treated as same key object. This will cause the replacing of value object inside Entry object only.

In this way, HashMap ensure the uniqueness of keys.

Difference between interfaces and abstract classes?

This is very common question if you are appearing interview for junior level programmer. Well, most noticeable differences are as below:

  • Variables declared in a Java interface is by default final. An abstract class may contain non-final variables.
  • Java interface are implicitly abstract and cannot have implementations. A Java abstract class can have instance methods that implements a default behavior.
  • Members of a Java interface are public by default. A Java abstract class can have the usual flavors of class members like private or abstract etc.
  • Java interface should be implemented using keyword “implements“; A Java abstract class should be extended using keyword “extends“.
  • A Java class can implement multiple interfaces but it can extend only one abstract class.
  • Interface is absolutely abstract and cannot be instantiated; A Java abstract class also cannot be instantiated, but can be invoked if a main() exists. Since Java 8, you can define default methods in interfaces.
  • Abstract class are slightly faster than interface because interface involves a search before calling any overridden method in Java. This is not a significant difference in most of cases but if you are writing a time critical application than you may not want to leave any stone unturned.

When do you override hashCode() and equals()?

hashCode() and equals() methods have been defined in Object class which is parent class for java objects. For this reason, all java objects inherit a default implementation of these methods.

hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.

Note that it is generally necessary to override the hashCode method whenever this method is overridden, so as to maintain the general contract for the hashCode() method, which states that equal objects must have equal hash codes.

  • equals() must define an equality relation (it must be reflexive, symmetric and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.
  • hashCode() must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b) then a.hashCode() must be same as b.hashCode().

Happy Learning !!

TwitterFacebookLinkedinRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

52
Leave a Reply

This comment form is under antispam protection
27 Comment threads
25 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
27 Comment authors
This comment form is under antispam protection
  Subscribe  
newest oldest most voted
Notify of
Rakesh

Hi Lokesh,

Can you update this page for the below question.

Difference between interfaces and abstract classes?
“A Java abstract class can have the usual flavors of class members like private, abstract.”

There is no use of declaring the abstract class method as private and only you can declare data members as private.

Please check once

Thanks for the information.

Vote Up0Vote Down  Reply
5 months ago
Lokesh Gupta

There is comma between private and abstract for this reason. Anyway, I updated the text so it does not create this confusion to others. Thanks for your comment.

Vote Up0Vote Down  Reply
5 months ago
Mohit

Superb content. thanks to Lokesh for share valuable information to with us.

Vote Up0Vote Down  Reply
6 months ago
Raj Srivastava

This is the best material i have ever read about java in my entire 4 years of career. I feel so fortunate that i got this sort of straight to the point explanation for my revision.

Vote Up0Vote Down  Reply
1 year ago
Lokesh Gupta

I am glad you find it useful.

Vote Up0Vote Down  Reply
1 year ago
arun singh

Thanks,
beautiful article

Vote Up0Vote Down  Reply
1 year ago
pranit

very helpful and useful list of core java interview question will be good to prepare for interview. I have an interview next week as java developer and i can predict what they will ask or what type of question will ask from this list. Thanks a lot!

Vote Up0Vote Down  Reply
1 year ago
Slava

You have some problems with English

Vote Up0Vote Down  Reply
2 years ago
Lokesh Gupta

I also realize it. And I am working on it. Thanks for the feedback. Much appreciated.

Vote Up0Vote Down  Reply
2 years ago
Tushar Singh Bora

I beg to differ on the point where you say in question
What is the difference between creating String as new() and literal?
“When we create String with new() it’s created in heap and also added into string pool” The thing is when I create a String object using new only one object is created in the Heap and is still not placed in the String Pool. In order to place it in the String Pool, you need to call String.Intern() method on it. this will put the String the String Pool.

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Hi Tushar, I must say it’s some how confusing for me too – till date. Let me put my logic:

String s = new String("abc");

Here, we both agree that one new object will be created in heap – so let’s leave that discussion. Coming to main point, the argument "abc" is a string literal and before passing it to String class’s constructor, JVM must somehow interpret it and that is done by placing it inside string pool.

Your logic??

Vote Up0Vote Down  Reply
3 years ago
Parag

This is from Java Doc-
public String intern()

Returns a canonical representation for the string object.

A pool of strings, initially empty, is maintained privately by the class String.

When the intern method is invoked, if the pool already contains a string equal to this String object as determined by the equals(Object) method, then the string from the pool is returned. Otherwise, this String object is added to the pool and a reference to this String object is returned.

It follows that for any two strings s and t, s.intern() == t.intern() is true if and only if s.equals(t) is true.

Returns:
a string that has the same contents as this string, but is guaranteed to be from a pool of unique strings.

Here they didn’t mention anything about Heap

Vote Up0Vote Down  Reply
2 years ago
Himansu

Explain the working of HashMap. How duplicate collision is resolved?

while iterating over LinkedList on calculated index, HashMap calls equals() method on key object for each Entry object…

Just to add one more imp thing here i.e. after rehashing the key the new hascode is saved in the Entry object together with key and value. While iterating over linkedlist, Hashmap together with reference equality and object equality it also check for the hashcode match too.

if(e.hash == hash && ((k = e.key) == key || key.equals(k))){...}
Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Please refer: https://howtodoinjava.com/java/collections/how-hashmap-works-in-java/

Vote Up0Vote Down  Reply
3 years ago
Himansu

What is the use of the finally block? Is finally block in Java guaranteed to be called? When finally block is NOT called?

if the thread executing the try or catch code is interrupted…

I wrote a test for the above case but unable to reproduce. Could you highlight when this is possible.

Test Code

 
package core.thread.interrupt;

public class InterruptThread implements Runnable {

    @Override
    public void run() {
        try {
            Thread.sleep(10000);
        } catch (InterruptedException intException) {
            intException.printStackTrace();
        } finally {
            System.out.println("finally executed");
        }
    }
}


package core.thread.interrupt;

public class InterruptThreadMain {
    public static void main(String...args) {
        Thread thread = new Thread(new InterruptThread());
        thread.start();
        thread.interrupt();
    }
}

o/p : 
java.lang.InterruptedException: sleep interrupted
finally executed
and the stack frame dump 

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

You may use the method setDaemon(boolean status) which is used to mark the current thread as daemon thread or user thread and exit the JVM as and when required. This will enable you exit the JVM before finally{} is executed.

public class InterruptThreadMain {
    public static void main(String...args) throws InterruptedException {
        Thread thread = new Thread(new InterruptThread());
        thread.setDaemon(true);
        thread.start();
        //Let the thread start - at least
        Thread.sleep(1000);
        thread.interrupt();
    }
}

class InterruptThread implements Runnable {
	 
    @Override
    public void run() {
        try {
        	System.out.println("Thread Start");
            Thread.sleep(10000);
        } catch (InterruptedException intException) {
            intException.printStackTrace();
        } finally {
            System.out.println("finally executed");
        }
    }
}
Output:
Thread Start
Vote Up0Vote Down  Reply
3 years ago
Sidharth

Hi Lokesh,

When I executed the above snippet as you have mentioned here, the output is something else. The finally block is getting executed.

Vote Up0Vote Down  Reply
3 years ago
Jana

Hi Lokesh

Greetings!!!

What is the internal functionality of below code?

String strObj = new String(null); – Exception at Compile time
StringBuilder d = new StringBuilder(null); – Exception at Runtime

Please clarify.

Vote Up0Vote Down  Reply
3 years ago
Jana

Hi Lokesh,

Why the Singleton classes are in JVM level not in application level? Please clarify.

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

This is tricky question. Usually when we talk about singleton, we assume that only one instance of application is running in one JVM. A singleton is always tied to classloader hirarchy for application. In case of single instance of application running on JVM, there can be only one class loaded by classloaders.

What if we deploy two instances of same application in same JVM/server instance? Here the location of singleton class will decide the number of instances created for singleton class. E.g. if class belongs to any shared lib (any j2se class or tomcat lib class) then both applications ( sharing same parent class loader for java and tomcat ) will have only one singleton instance. BUT, if class belongs to application specific lib folder, then both application will end up having their separate instances of same singleton because classloader for both application is separate.

You can find more detailed discussion of StackOverFlow thread1 and thread2.

Vote Up0Vote Down  Reply
3 years ago
Jana

Thanks Lokesh. Can you please explain Abstraction with some real time example?

Vote Up0Vote Down  Reply
3 years ago
Jana

Hi Lokesh

import java.io.*;
import java.util.*;

public class HelloWorld {

     public static void main(String []args) throws IOException,ClassNotFoundException {
         
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Newfile.txt"));
        out.writeObject(new Child());
        
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("Newfile.txt"));
        System.out.print(in.readObject());
        System.out.println();
     }
}

class Parent {
    protected transient String hello = "Hello!";
}

class Child extends Parent implements Serializable{
    int age = 11;
    
    public String toString() {
        return "age="+age+" hello="+hello;
    }
}

Actual Result of above snippet : age=11 hello=Hello!

My doubt is, hello string should print null because it is declared as transient. How come the value got serialized?

Please clarify.

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

I slightly modified your code to make it more clear:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
 
public class HelloWorld {
 
     public static void main(String []args) throws IOException,ClassNotFoundException {
          
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("Newfile.txt"));
        out.writeObject(new Child());
        out.close();
         
        ObjectInputStream in = new ObjectInputStream(new FileInputStream("Newfile.txt"));
        Child c = (Child)in.readObject();
        in.close();
        
        //parent
        System.out.println(c.hello);
        
        //child
        System.out.println(c.age);
        System.out.println(c.world);
     }
}
 
class Parent {
    protected transient String hello = "Hello!";
}
 
class Child extends Parent implements Serializable{
    int age = 11;
    protected transient String world = "World";
     
    public String toString() {
        return "age="+age+" hello="+hello+" world="+world;
    }
}
Output:
Hello!

11
null

As per java docs:

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

So essentially, only Child class is part of serialization and de-serialization. Parent class is created by calling it’s default constructor and normal initialization process, so value is set for hello field.

Effect of serialization is visible in new transient field added in Child class.

Vote Up0Vote Down  Reply
3 years ago
Jana

Thanks Lokesh. So, there will not be any impact by using transient declaration in non-serializable classes. Right?

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Yes, in relation to serialization.

Vote Up0Vote Down  Reply
3 years ago
Jana

Excellent work. Please keep it up.. 🙂

Vote Up0Vote Down  Reply
3 years ago
Sharique

Hi Lokesh,

The memory leak with string that you mentioned here have been fixed in 1.7 right ?

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Yes.

Vote Up0Vote Down  Reply
3 years ago
Shilpa

Thank you Lokesh! Important, clear and helpful questions!

Vote Up0Vote Down  Reply
3 years ago
Raj Sharma

Hi,

This is great website which explain most critical topics in detail, I love the way you explained HashMap and HashSet concept, waiting for your book in market for Java details interview preparation for experience candidate, because in so many websites they just highlighted the concept but you explained them really well.
wish you all the best.

Regards,
Raj Sharma

Vote Up0Vote Down  Reply
3 years ago
Bastin

Hi Lokesh,

Excellent website. I always come back here to brush up my knowledge.

One doubt from a question on this page.

For the question “Why main() in java is declared as public static void?”, you say that irrespective of the access modifiers, java.exe or javac.exe can invoke the main method. But, when I try to run a test program which does not have ‘public’ access modifier for main(), it gives me the below error. Has the behavior changed lately?

Error: Main method not found in class TestJavaMain, please define the main method as:
public static void main(String[] args)

Vote Up0Vote Down  Reply
4 years ago
Lokesh Gupta

Bastin, java.exe file is written in native code and uses C++ like instructions to verify the syntax and execute main() method. Infact, error “does not have ‘public’ access modifier” is itself thrown from inside java.exe file sourcecode, when syntax does not match.

Vote Up0Vote Down  Reply
4 years ago
Bastin

But, I get this error when running the program from command line using java.exe. If it doesn’t have such a restriction, then it should work fine.

Error: Main method not found in class TestJavaMain, please define the main method as:
public static void main(String[] args)
Vote Up0Vote Down  Reply
4 years ago
Vijay

Hi Lokesh,

Well explained theoritically.

If you provide programs for each concept will be more easier to understand the internals of java.

Please do it.

Vote Up0Vote Down  Reply
4 years ago
Vijay

Why can’t you provide with examples

Vote Up0Vote Down  Reply
4 years ago
pankaj

thanks this helped lot.

Vote Up0Vote Down  Reply
5 years ago
venkata

Hi Lokesh,

One of the interview, they asked me how to do sort in ascending order on String of characters after converting them into Ascii values and I answered in below mentioned way but he does not satisfied with my answer.Could you please tell me other way to do this.

I have coded like this.

public static String convert_String_To_Ascii(String numStr){

char ch[] = numStr.toCharArray();
int first=0;
int last=0;
StringBuffer asn=new StringBuffer();
for(int i=0;i<ch.length;i++)
{
first=(int) ch[i];
for(int j=i;jlast)
{
char temp=(char)first;
first=last;
ch[i]=(char)last;
ch[j]=temp;

}

}

}
return new String(ch);
}

Vote Up0Vote Down  Reply
5 years ago
Lokesh Gupta

What about below?

String s = “some-string-here”;
byte[] bytes = s.getBytes(“US-ASCII”);
Arrays.sort(bytes);

It’s sort and easy to read. Your’s is also correct.

Vote Up0Vote Down  Reply
5 years ago
Arun

Veri Nice Post.

Vote Up0Vote Down  Reply
5 years ago
Sumeet Singh

In this page you mentioned:
When we create string with new () it’s created in heap and not added into string pool

and in https://howtodoinjava.com/java/string/interview-stuff-about-string-class-in-java/ you have mentioned:
==================================
2) Using new keyword
String str = new String(“abc”);
This version end up creating two objects in memory. One object in string pool having char sequence “abc” and second in heap memory referred by variable str and having same char sequence as “abc”.
==================================

Isn’t it contradictory to each other?

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Hey Sumeet, Good catch. It was a typo (sometimes happen when you type so much text). Thanks for pointing out and I have corrected that.
To put more focus on topic, When you use new keyword and pass a String parameter then that parameter is actually a String literal and string literal in string pool gets created even before your String() constructor is called. So, on runtime when constructor is called, you get your second object in heap area.
“Compile-time constant expressions of type String are always “interned” so as to share unique instances, using the method String.intern”
Source: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.28

Vote Up0Vote Down  Reply
6 years ago
Heul français

Hi, thank you for your post, very nice!

At the question: “Why there are two Date classes; one in java.util package and another in java.sql?”
When you say : “So, what changed in java.sql.Date: […] the getters and setter for hours, minutes and seconds are deprecated” I feel it’s a bit misleading, because in the original java.util.Date class, those methods are already deprecated, but it’s just not for the same reasons.
https://docs.oracle.com/javase/7/docs/api/index.html?java/util/Date.html

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

You caught me on wrong foot.- 🙂 OK, it can be misleading. So let’s me clarify again.

Methods in java.util.Date were gone deprecated because of Calendar class was considered recommended approach. So, util’s Date class’s multiple methods were marked as deprecated.

e.g. setMinutes(int minutes) :: Deprecated. As of JDK version 1.1, replaced by Calendar.set(Calendar.MINUTE, int minutes).

But, in java.sql.Date class it was deprecated because they are (though not enforced) conceptually discouraged.

e.g. setMinutes(int i) :: Deprecated. This method is deprecated and should not be used because SQL Date values do not have a time component.

Vote Up0Vote Down  Reply
6 years ago
Heul français

I like this answer 😉 Thx!

Vote Up0Vote Down  Reply
6 years ago
Abey

Great list dude. Keep it up the writing.

Vote Up0Vote Down  Reply
6 years ago
Vivek

Thanks for sharing it.

Vote Up0Vote Down  Reply
6 years ago
Manohar

public class FinallyReturnVariableAlter
{
public static void main(String[] args)
{
System.out.println(test());
}
public static int test()
{
int i=0;
try
{
return i;
}
finally
{
i+=100;
}
}
}

why the return value is 0 instead of 100?

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Manohar, This is really good question and most fail to answer it correctly. Let me put my reasoning.

Every function call in java leads to creation of extra memory space created where return value is stored for reference after function execution completes and execution return to caller function back.

At that time, that special memory address where return value is stored, if referenced back as return value of function.

Here, trick is, the memory slot store the value of returned value, not its reference. So, once any return statement is encountered its value is copied in memory slot. That’s why if you change the value of “i” in finally, return value does not change because its already copied to memory slot.

We any other return statement is encountered (e.g. in finally block), its value will be overwritten again. So, it you want to return 100, use return statement in finally also.;

Vote Up0Vote Down  Reply
6 years ago
rifaie

Hi Lokesh,

does the finally block executes if we have a return statement in try block if it works fine without throwing an exception?

Vote Up0Vote Down  Reply
3 years ago
Lokesh Gupta

Yes.

Vote Up0Vote Down  Reply
3 years ago
Rajendra Joshi

Hi Lokesh

certainly I will go thr’ questions but tell me java code to connect to
hsqldb .I am getting user lacks privilege or object not found: EMPLOYEEDETAILS exception

pl help me

Vote Up0Vote Down  Reply
6 years ago
Lokesh Gupta

Are you using hibernate.. match your properties..

http://docs.jboss.org/hibernate/orm/4.1/devguide/en-US/html_single/#d5e54

Vote Up0Vote Down  Reply
6 years ago

Search Tutorials

Interview Questions

  • Java Interview Questions List
  • Java Puzzles List
  • Java String Interview Questions
  • Core Java Interview Questions – 1
  • Core Java Interview Questions – 2
  • Core Java Interview Questions – 3
  • Collection Interview Questions
  • Spring Interview Questions
  • Spring AOP Interview Questions
  • Spring Boot Interview Questions
  • Spring MVC Interview Questions
  • Mid-level Developer Interview
  • Oracle Interview Questions
  • HashMap Interview Questions

Popular Tutorials

  • Java 8 Tutorial
  • Core Java Tutorial
  • Collections in Java
  • Java Concurrency
  • Spring Boot Tutorial
  • Spring AOP Tutorial
  • Spring MVC Tutorial
  • Spring Security Tutorial
  • Hibernate Tutorial
  • Python Tutorial
  • Jersey Tutorial
  • Maven Tutorial
  • Log4j Tutorial
  • Regex Tutorial

Meta Links

  • Advertise
  • Contact Us
  • Privacy policy
  • About Me

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2016 · HowToDoInjava.com · All Rights Reserved. | Sitemap

wpDiscuz