When are initializer blocks used in java? [duplicate] - java

This question already has answers here:
What is an initialization block?
(10 answers)
Closed 7 years ago.
I read that an initializer block is "an unnamed code block that contains th code that initializes the class?
For example :
class A {
final int x;
final int y;
final String n;
{
x = 10;
y = 20;
}
public A(String name ) {
/* etc... etc */
I have never seen this type of code used, so I was wondering where it may be helpful. Why don't we just initialize variables in constructor ?
thanks

I think it can sometimes be helpful to initialize a variable immediately when it is defined.
public class Stooges {
private ArrayList<String> stooges = new ArrayList<>();
{ stooges.add("Lary"); stooges.add("Curly"); stooges.add("Moe"); }
// ... etc. other methods.
}
That initializer is now common to all constructors, so it avoids code duplication. You could use a private method and call similar code from within all constructors, but this way avoid even remembering to insert a method call. Less maintenance!
There could be other examples. If the initializer code calls a method that throws an exception, then you can't just assign it. You have to catch the exception.

A common use for this is the static initializer block:
class A {
static boolean verbose;
final int x;
final int y;
final String n;
static {
verbose = doSomethingToGetThisValue();
}
public A(String name ) {
/* etc... etc */
This is useful because your static variables might be used by a static method before an instance of the class is ever created (and therefore before your constructor is ever called).
See also this SO answer.

Related

When Should You Use Get Methods vs Call Variables Directly? [duplicate]

This question already has answers here:
Why use getters and setters/accessors?
(37 answers)
Closed 4 years ago.
ok so i just found out that if you have a class with global variables you can call it in another class just by saying class.variable and now i'm very confused as to why getVariable and setVariable methods exist ever when they're already accessible
so let's say we have these two classes
public class MyClass {
public int num;
public String str;
public MyClass (int num, String str) {
this.num = num;
this.str = str;
}
public int getNum () {
return num;
}
public String getStr () {
return str;
}
}
public class test {
public static void main (String[] args) {
MyClass x = new MyClass (3, "string");
System.out.println(x.num);
System.out.println(x.str);
System.out.println(x.getNum());
System.out.println(x.getStr());
x.num = 4;
System.out.println(x.num);
}
}
Both ways, it accesses the same data from the object and outputs the same thing. Is one way better practice than the other or are there certain cases where one of the ways won't work?
Short answer: encapsulation.
A major benefit is to prevent other classes or modules, especially ones you don't write, from abusing the fields of the class you created.
Say for example you can an instance variable int which gets used as the denominator in one of your class methods. You know when you write your code to never assign this variable a value of 0, and you might even do some checking in the constructor. The problem is that some else might instantiate your class and later assign the instance variable a value of 0, thereby throwing an exception when they later invoke the method that uses this variable as a denominator (you cannot divide by 0).
Using a setter, you write code that guarantees the value of this variable will never be 0.
Another advantage is if you want to make instance variables read only after instantiating the class then you can make the variables private and define only getter methods and no setters.

static interface variables getting inherited ......... why? [duplicate]

This question already has answers here:
Are static variables inherited
(4 answers)
Closed 4 years ago.
I am learning interfaces in java and the source from which i am learning clearly says that static variables do not get inherited. But for some reason, I am able to access that static variable without adding the interface name before it. I want to know why is this happening and an in depth explanation of whats going on !!!? plzz help
class StaticMethods {
public static void main(String [] com) {
TourClient t = new TourClient(); // i made this a class variable in place of interface variable just for demonstration
t.check();
}
}
interface Tour {
///This stuff is just for display, doesn't play a role
static float minimalCost = 50000;
static float maximumCost = 1000000;
static float recommendedRating = 3.9f;
static int minimumVisitingPlaces = 4;
}
interface DubaiTour extends Tour {
static float Rating = 4.4f;
}
class TourClient implements DubaiTour{
void check() {
System.out.println(Rating); // This is not giving me any errors!!
}
}
NOTE :- I found a stack overflow page Does static variable inherited?
, but this does not explain in depth why is this happening, which doesn't help me
Static variables are inherited.
Once again - static variables are inherited - BUT you shouldn't use them. The reason why is, if you build your program. For optimization, your TourClient class variables get substituted with the constants. The line System.out.println(Rating) gets replaced with System.out.println(4.4) - all is well. If you edit your interface and change a variable to, say, 5.5, it won't get updated in your TourClient class. It will probably still print 4.4. When you use static variables in an interface, you need to recompile EVERYTHING. Not just the files you change.

scope of variable inside main in Java? [duplicate]

This question already has answers here:
Why does Java not have block-scoped variable declarations?
(6 answers)
Closed 9 years ago.
Am I correct that a block inside main() doesn't have separate scope?
For example, if I do the following, I will get compile error:
static int i = 1;
public static void main(String[] args) {
int i = 2;
{
int i = 3;
}
}
Why is this?
When I try to compile this, I get this message:
error: variable i is already defined in method main(String[])
This means that the static int i = 1; does not cause the error. The scope of the first i in main is for the whole main, so when you try to make another one, in the code block, you get an error.
Note that if you declared the i in a block:
public static void main(String[] args){
{
int i = 2;
}
{
int i = 3;
}
}
You don't get a compile error (see here).
The static int can be accessed in one of two ways: this.i (not recommended) or ClassName.i (recommended for accessing of a static variable)
Java does not allow obfuscation of stack (ie. local variables). You can obfuscate an instance or class variable because there are other ways to access them (ie. this.i for instance, or MainClass.i for static).

how to declare a helper method in java, to be used locally being able to reference variables

I have a class with several methods. Now I would like to define a helper method that should be only visible to method A, like good old "sub-functions" .
public class MyClass {
public methodA() {
int visibleVariable=10;
int result;
//here somehow declare the helperMethod which can access the visibleVariable and just
//adds the passed in parameter
result = helperMethod(1);
result = helperMethod(2);
}
}
The helperMethod is only used by MethodA and should access MethodA's declared variables - avoiding passing in explicitly many parameters which are already declared within methodA.
Is that possible?
EDIT:
The helper mehod is just used to avoid repeating some 20 lines of code which differ in only 1 place. And this 1 place could easily be parameterized while all the other variables in methodA remain unchanged in these 2 cases
Well you could declare a local class and put the method in there:
public class Test {
public static void main(String[] args) {
final int x = 10;
class Local {
int addToX(int value) {
return x + value;
}
}
Local local = new Local();
int result1 = local.addToX(1);
int result2 = local.addToX(2);
System.out.println(result1);
System.out.println(result2);
}
}
But that would be a very unusual code. Usually this suggests that you need to take a step back and look at your design again. Do you actually have a different type that you should be creating?
(If another type (or interface) already provided the right signature, you could use an anonymous inner class instead. That wouldn't be much better...)
Given the variables you declare at the top of your method can be marked as final (meaning they don't change after being initialized) You can define your helper method inside a helper class like below. All the variables at the top could be passed via the constructor.
public class HelperClass() {
private final int value1;
private final int value2;
public HelperClass(int value1, int value2) {
this.value1 = value1;
this.value2 = value2;
}
public int helperMethod(int valuex) {
int result = -1;
// do calculation
return result;
}
}
you can create an instance of HelperClass and use it inside the method
It is not possible. It is also not good design. Violating the rules of variable scope is a sure-fire way to make your code buggy, unreadable and unreliable. If you really have so many related variables, consider putting them into their own class and giving a method to that class.
If what you mean is more akin to a lambda expression, then no, this is not possible in Java at this time (but hopefully in Java 8).
No, it is not possible.
I would advise you create a private method in your class that does the work. As you are author of the code, you are in control of which other methods access the private method. Moreover, private methods will not be accessible from the outside.
In my experience, methods should not declare a load of variables. If they do, there is a good chance that your design is flawed. Think about constants and if you couldn't declare some of those as private final variables in your class. Alternatively, thinking OO, you could be missing an object to carry those variables and offer you some functionality related to the processing of those variables.
methodA() is not a method, it's missing a return type.
You can't access variables declared in a method from another method directly.
You either has to pass them as arguments or declare methodA in its own class together with the helpermethods.
This is probably the best way to do it:
public class MyClass {
public void methodA() {
int visibleVariable=10;
int result;
result = helperMethod(1, visibleVariable);
result = helperMethod(2, visibleVariable);
}
public int helperMethod(int index, int visibleVariable) {
// do something with visibleVariable
return 0;
}
}

difference between final int and final static int [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
java: is using a final static int = 1 better than just a normal 1?
Well I'd like to know what difference between:
final int a=10;
and
final static int a=10;
when they're the member variables of a class, they both hold the same value and cannot be changed anytime during the execution.
Is there any other difference than that the static variable is shared by all the objects and a copy is created in case of non-static variable?
There is no practical difference if you initialize the variable when you declare it.
If the variable is initialized in a constructor, it makes a big difference.
See the example below:
/**
* If you do this, it will make almost no
* difference whether someInt is static or
* not.
*
* This is because the value of someInt is
* set immediately (not in a constructor).
*/
class Foo {
private final int someInt = 4;
}
/**
* If you initialize someInt in a constructor,
* it makes a big difference.
*
* Every instance of Foo can now have its own
* value for someInt. This value can only be
* set from a constructor. This would not be
* possible if someInt is static.
*/
class Foo {
private final int someInt;
public Foo() {
someInt = 0;
}
public Foo(int n) {
someInt = n;
}
}
A static variable is accessible via the dot separator outside of it's class definition.
So if you have a class called myClass and inside it you have static int x = 5;
then you can refer to it with myClass.x;
The final keyword means you are not allowed to change the value of x after it has been defined. The compiler will stop with an error if you attempt to do so.
As a static variable, you don't need an instance of the class to access the value. The only other difference is that the static field is not serialized (if the class is serializable). It's also possible that all references to it in compiled code are optimized away.
The difference doesn't show up if you're only using ints. However, as an example of how it's different:
class PrintsSomething {
PrintsSomething(String msg) {
System.out.println(msg);
}
}
class Foo {
public static final PrintsSomething myStaticObject = new PrintsSomething("this is static");
public final PrintsSomething myLocalObject = new PrintsSomething("this is not");
}
When we run this:
new Foo();
new Foo();
...the output is this:
this is static
this is not
this is not
I would point out, that the static modifier should only be used with explicit needs, and the final only for constants.

Categories