class F
{
static
{
i = 1;
}
static int i = 2;
public static void main(String[] args)
{
System.out.println(i);
}
}
The output of this execution is 2. Can someone explain why not 1? In which sequence variables are getting created and initialized and static block is executed?
http://docs.oracle.com/javase/tutorial/java/javaOO/initial.html
kindly check java documentation.
then clearly mentioned no matter how may static blocks are there they will be executed as a single block in the order they appear
So,
My understanding here is java is looking your code as
static{
i=1;
i=2;
}
static int i;
that is why you are getting output 2
hope this is helpful
Related
Why is it possible for a variable to call (initialise itself) a method that calls the same variable (seems a recursion)? I expected to see an endless recursion, but it compiles without errors. Any explanation?
class Forward {
static int test(){
return i;
}
static int i=test();
public static void main(String[] args) {
System.out.println(test()); //sout= 0
System.out.println(i); //sout =0
}
}
Another example. Why does referencing Backwards.j work while referencing j gives an error("illegal forward reference"):
class Backwards{
//static int i=j; //illegal forward reference;
static int i=Backwards.j; //reference through class works
static int j=i;
public static void main(String[] args) {
System.out.println(i);
System.out.println(j);
}
}
If you step through the code in your debugger you will see that i = test(); is only run once ever.
The previous value for i is 0 and that's the value test() returns before i has been initialised.
The java compiler can't detect every possible forward reference, only the simplest ones.
I am trying to print the number increment by 1 whenever i call the function, but i am not able to get the solution, below is my code
The blow is the function
public class Functions<var> {
int i=0;
public int value()
{
i++;
return i;
}
}
I am calling the above function here
import Java.Functions;
public class Increment {
public static void main(String[] args)
{
Functions EF = new Functions();
System.out.println(EF.value());
}
}
Whenever i run the program , i am getting only the output as 1 , but i want the output to be incremented by 1 . Could you please help. Thanks in Advance.
I believe your answer is with the scope of your variables and your understanding of them. You only call the method once in your given examples, so 1 is arguably the correct answer anyway. Below is a working example which will persist during runtime one variable and increment it every time a function is called. Your methods don't seem to follow the common Java patterns, so I'd recommend looking up some small example Hello, World snippets.
public class Example{
int persistedValue = 0; // Defined outside the scope of the method
public int increment(){
persistedValue++; // Increment the value by 1
return persistedValue; // Return the value of which you currently hold
// return persistedValue++;
}
}
This is due to the scope of "persistedValue". It exists within the class "Example" and so long as you hold that instance of "Example", it will hold a true value to your incremented value.
Test bases as follows:
public class TestBases {
static Example e; // Define the custom made class "Example"
public static void main(String[] args) {
e = new Example(); // Initialize "Example" with an instance of said class
System.out.println(e.increment()); // 1
System.out.println(e.increment()); // 2
System.out.println(e.increment()); // 3
}
}
If your desire is out of runtime persistence (the value persisting between application runs) then it would be best to investigate some method of file system saving (especially if this is for your Java practice!)
Your main problem is to increment the number value 1.
But you are calling your function only once. Even though you call the function many times you will get the value 1 only because it is not static variable so it will every time initialize to 0.
So please check below answer using static context.
Functions.java
public class Functions{
static int i=0;
public int value()
{
i++;
return i;
}
}
Increment.java
public class Increment{
public static void main(String []args){
Functions EF = new Functions();
System.out.println(EF.value());
System.out.println(EF.value());
System.out.println(EF.value());
}
}
Output:
1
2
3
If you design multi-threaded application, it will be better to use AtomicInteger.
The AtomicInteger class provides you an int variable which can be read and written atomically.
AtomicInteger atomicInteger = new AtomicInteger();
atomicInteger.incrementAndGet();
package ali;
public class test {
public static int n = 99;
public static test t1 = new test("t1");
public static test t2 = new test("t2");
public static int i = 0;
public static int j = i;
{
System.out.println("construct block");
}
static {
System.out.println("static construct block");
}
public test(String str){
System.out.println((++j) + ":" + " i="+ i + " n="+n+str);
n++;i++;
}
public static void main(String [] args){
test test1 = new test("initl");
}
}
after running:
construct block
1: i=0 n=99t1
construct block
2: i=1 n=100t2
static construct block
construct block
1: i=0 n=101initl
Who can tell me how it works?
why there is no "static construct block" when t1 and t2 ware created?
why i and j changed to the default ,but n still unchanged?
static variables/blocks are executed/initialized as they appear (usually).
your output and why? :
When the class is loaded and during its initialization, the following lines will be executed
public static test t1 = new test("t1");
public static test t2 = new test("t2");
which in-turn create new Test objects, but since the class is already under initialization, the above lines are not executed again.
So,
you get
construct block
1: i=0 n=99t1
construct block
2: i=1 n=100t2
Next, the static block executes
static construct block
Now when you create an object of Test in main(), you will have
construct block
1: i=0 n=101initl
When this class (which really should have a capitalized name) is loaded, the static initializers are invoked in the order in which they appear in the source code. This means that the new test("t?") object creations happen before the explicit static block.
I am new at programming and currently in our classes we are learning java. I am trying to create a routine in which I need to use String variables only. Below it is the code in which I am working with:
public static void main(String[] args) throws java.io.IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System. in ));
PrintStream out = System.out;
String hair.equals("damagedHair");
cutHair(marvin);
cleanHair(michelle);
for (int i = 0; i < 2; i++) {
static void cutHair(String marvin) {
String cabello;
marvin.equals(hair);
if (marvin.equals("damagedHair")) {
cabello.equals("newHaircut");
result(hair);
}
static void cleanHair(String michelle) {
String hair;
michelle.equals(hair);
if (michelle.equals(newHaircut)) {
hair.equals("putShampooAndConditioner");
result(hair);
}
static void result(String pHair) {;
PrintStream out = System.out;
out.println("=============");
out.println(pHair);
out.println("=============");
}
}
Jcreator is giving me an error that says Illegal start of expression and also java 50 error ';' expected.
I am not sure why is this coming up and I am a little confused as to whether I am doing something I am not supposed to and how to correct it. Sorry about the double posting, this is the right message. Need some help from you guys to figure this out.
Thanks in advanced!
This is in your main:
for(int i=0; i<2; i++)
{
static void cutHair(String marvin)
{
String cabello;
marvin.equals(hair);
if(marvin.equals("damagedHair"))
{
cabello.equals("newHaircut");
result(hair);
}
}
You cannot define methods inside of main. Also, hair is not in scope here, ie it's in your main, not your method. Additionally, you're constantly only declaring variables, and then using them without them ever having been initialized. For example, in the above method, you have:
cabello.equals("newHairCut")
but cabello was never initialized, this should give you a might not have been initialized warning. Or earlier in your code, you have:
String hair.equals("damagedHair");
Again, this doesn't make any sense. You just declared hair here, you cannot call methods on it until you initialize it. I suggest that you review some tutorials.
Whenever I try to test my code with JUnit, I receive a NullPointerException - even though I don't get that exception when I run the actual program. The line that gives me the exception is:
assertEquals(0.0, TweetClassification.tweetType[TweetClassification.SIGNIF_OTHER].likelihoodA);
The beginning of the TweetClassification class it's testing is as follows:
public class TweetClassification
{
// CONSTANTS =============================================
public static final int TCNUMBER = 5; // number of TweetCategories (including the null category)
// using constants to indicate the names of the TweetCategories, so that they could be renumbered
public static final int NULLTWEET = 0;
public static final int SIGNIF_OTHER = 1;
public static final int FRIENDS = 2;
public static final int WORK = 3;
public static final int FOOD = 4;
public static final TweetCategory[] tweetType = new TweetCategory[TCNUMBER];
...
(TweetCategory is another class that is defined separately within the package.) So I realize that this code initializes the array but not its members, and that's probably why I'm getting the exception(?) But the thing is, I do initialize the members of the array within the main method of TweetClassification, as follows:
for (int i=0; i<TCNUMBER; i++)
{
tweetType[i] = new TweetCategory();
}
But if I try to move this for loop outside the main method with the constants I get a syntax error - I presume you're not supposed to use a for loop outside of a method. So I'm not sure how to initialize the class properly for JUnit to work - either I do it outside the main method and get a syntax error, or I do it inside the main method and get a NullPointerException. Any ideas?
You need to move the init code into a static initializer block, like this:
public class TweetClassification
{
//...
public static final TweetCategory[] tweetType = new TweetCategory[TCNUMBER];
static
{
for (int i=0; i<TCNUMBER; i++)
{
tweetType[i] = new TweetCategory();
}
}
//...
}
This ensures that the static variable is initialized properly when the class is loaded (i.e. before it is first used anywhere within your program or tests).
Yo might find some use of the static initialzier block:
private static Integer arr[] = new Integer[2];
static {
for (int i = 0; i < 2; i++) {
arr[i] = 2;
}
}
public static void main(String[] args) {
System.out.println(arr[1]);
}
Ouputs:
2
This is proper java and is meant exactly for initializing static variables, though it is not very commonly used.