2

This question is actually one of two I have asked regarding Java, and I don't understand this syntax enough to understand what to ask, but here is something I see in coding:

HibernateUtil hibUtil = new HibernateUtil(ORDB_CFG, AS400_CFG);

I know where the class HibernateUtil is located.

What I don't understand is, why is it also specified before the var hibUtil in the expression? What is the different if I do or do not?

2
  • 2
    Specifying the type for the variable is part of how you declare a variable in Java. You may want to start with pretty much any introductory Java tutorial, the syntax for declaring a variable will be covered. Commented Dec 18, 2015 at 22:19
  • That's what Java syntax looks like. You are declaring a variable named hibUtil of type HibernateUtil, and assign to it (using =) a new instance object of type HibernateUtil that you instantiate it (using new keyword) by invoking its constructor that takes 2 arguments. Commented Dec 18, 2015 at 22:19

2 Answers 2

7

This is a variable declaration and initialisation.

In java you need to declare the type of a variable.

HibernateUtil hibUtil = new HibernateUtil(ORDB_CFG, AS400_CFG);

The first HibernateUtil declares the type of a variable/an object.

In your case its a variable of class HibernateUtil named hibUtil. After the = a new object is created and assigned to the previously declared variable.

Depending on your class structure you can also declare an interface or super class as variable and assign an object of a sub class to it.

Sign up to request clarification or add additional context in comments.

1 Comment

As I now understand this is because Java is a "strongly typed" language vs. PHP which I have started on years ago :)
3

As an example of when you might not see the repeated syntax, supposes we have subclasses of HibernateUtil called MyHibernateUtil and YourHibernateUtil. Then you might see an array of HibernateUtil's containing one of each of the subclasses:

HibernateUtil[] h = { new MyHybernateUtil(...), new YourHibernateUtil(...)};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.