I have following code
class Demo {
static int a = 0;
static int b = 1;
static {
a = ++b;
}
void gam(int x) {
a = a * x;
b = b * x;
}
}
class Test {
public static void main(String[] args) {
Demo d1 = new Demo();
Demo d2 = new Demo();
d1.a++;
d2.a--;
System.out.println(d1.a + " " + d1.b + " " + d2.a + " " + d2.b);
}
}
But I can't figure out why d1.a is 2. Shouldn't it be 3? Since a=++b makes it 2 and d1.a++ makes it 3?
The variable a is static, so there is only one a for all instances of Demo. It starts off as 0, and the static initializer sets it to ++b, or 2. Then, d1.a++ increments it to 3, but d2.a-- decrements the same a back down to 2.
d1.a is a static member field, so it should be accessed not via the instance. It should accessed via: Demo.a.
And by the way, d1.a and d2.a refer to the same static member field, so the increment of a in d1.a++ is "roll-backed" with the decrement: d2.a--.
Related
There are two programs here . I am not able to understand the explanation of the problems as they have very contrasting explanations.
//Question1
What will be the output of the program?
class Test
{
static int s;
public static void main(String [] args)
{
Test p = new Test();
p.start();
System.out.println(s);
}
void start()
{
int x = 7;
twice(x);
System.out.print(x + " ");
}
void twice(int x)
{
x = x*2;
s = x;
}
}
ans: 7 14
explanation: The int x in the twice() method is not the same int x as in the start() method. Start()'s x is not affected by the twice() method. The instance variable s is updated by twice()'s x, which is 14.
//ANOTHER QUESTION
```
class Two
{
byte x;
}
class PassO
{
public static void main(String [] args)
{
PassO p = new PassO();
p.start();
}
void start()
{
Two t = new Two();
System.out.print(t.x + " ");
Two t2 = fix(t);
System.out.println(t.x + " " + t2.x);
}
Two fix(Two tt)
{
tt.x = 42;
return tt;
}
}
```
ans= 0 42 42
explanation:
In the fix() method, the reference variable tt refers to the same object (class Two) as the t reference variable. Updating tt.x in the fix() method updates t.x (they are one in the same object). Remember also that the instance variable x in the Two class is initialized to 0.
What is the internal reason due to which within method local inner class we can only access final or effectively final local variables of the method in which that inner class is declared?
Please see below example.
class Test{
int i = 10;
static int j = 20;
public void m1(){
int k = 30;
//k=40;
final int m = 40;
class Inner{
public void m2(){
System.out.println("value of i = " + i + " value of j = " + j + " value of k = " + k + " value of m = " + m);
}
}
Inner i = new Inner();
i.m2();
}
public static void main(String[] args){
Test t = new Test();
t.m1();
}
}
If I try to change the value of variable k (line commented in source code), then there will be compiler error stating "local variables referenced from an inner class must be final or effectively final"
Also in java versions lower than 1.8, local variables must be explicitly defined as final if you want to access that variable within method local inner class.
I'm in a beginning programming class, and a lot of this had made sense to me up until this point, where we've started working with methods and I'm not entirely sure I understand the "static," "void," and "return" statements.
For this assignment in particular, I thought I had it all figured out, but it says it "can not find symbol histogram" on the line in the main method, although I'm clearly returning it from another method. Anyone able to help me out?
Assignment: "You see that you may need histograms often in writing your programs so you decide for this program to use your program 310a2 Histograms. You may add to this program or use it as a class. You will also write a class (or method) that will generate random number in various ranges. You may want to have the asterisks represent different values (1, 100, or 1000 units). You may also wish to use a character other than the asterisk such as the $ to represent the units of your graph. Run the program sufficient number of times to illustrate the programs various abilities.
Statements Required: output, loop control, decision making, class (optional), methods.
Sample Output:
Sales for October
Day Daily Sales Graph
2 37081 *************************************
3 28355 ****************************
4 39158 ***************************************
5 24904 ************************
6 28879 ****************************
7 13348 *************
"
Here's what I have:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public String histogram (int randomNum) //creates the histogram string
{
String histogram = "";
int roundedRandom = (randomNum/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
randInt(randomNum);
System.out.print(randomNum + " ");
histogram (randomNum);
System.out.print(histogram + "\n");
}
}
}
Edit: Thanks to you guys, now I've figured out what static means. Now I have a new problem; the program runs, but histogram is returning as empty. Can someone help me understand why? New Code:
import java.util.Random;
public class prog310t
{
public static int randInt(int randomNum) //determines the random value for the day
{
Random rand = new Random();
randomNum = rand.nextInt((40000 - 1000) + 1) + 10000;
return randomNum;
}
public static String histogram (int marketValue) //creates the histogram string
{
String histogram = "";
int roundedRandom = (marketValue/1000);
int ceiling = roundedRandom;
for (int k = 1; k < ceiling; k++)
{
histogram = histogram + "*";
}
return histogram;
}
public static void main(String[] Args)
{
System.out.println("Sales for October\n");
System.out.println("Day Daily Sales Graph");
for (int k = 2; k < 31; k++)
{
if (k == 8 || k == 15 || k == 22 || k == 29)
{
k++;
}
System.out.print(k + " ");
int randomNum = 0;
int marketValue = randInt(randomNum);
System.out.print(marketValue + " ");
String newHistogram = histogram (randomNum);
System.out.print(newHistogram + "\n");
}
}
}
You're correct that your issues are rooted in not understanding static. There are many resources on this, but suffice to say here that something static belongs to a Class whereas something that isn't static belogns to a specific instance. That means that
public class A{
public static int b;
public int x;
public int doStuff(){
return x;
}
public static void main(String[] args){
System.out.println(b); //Valid. Who's b? A (the class we are in)'s b.
System.out.println(x); //Error. Who's x? no instance provided, so we don't know.
doStuff(); //Error. Who are we calling doStuff() on? Which instance?
A a = new A();
System.out.println(a.x); //Valid. Who's x? a (an instance of A)'s x.
}
}
So related to that your method histogram isn't static, so you need an instance to call it. You shouldn't need an instance though; just make the method static:
Change public String histogram(int randomNum) to public static String histogram(int randomNum).
With that done, the line histogram(randomNum); becomes valid. However, you'll still get an error on System.out.print(histogram + "\n");, because histogram as defined here is a function, not a variable. This is related to the return statement. When something says return x (for any value of x), it is saying to terminate the current method call and yield the value x to whoever called the method.
For example, consider the expression 2 + 3. If you were to say int x = 2 + 3, you would expect x to have value 5 afterwards. Now consider a method:
public static int plus(int a, int b){
return a + b;
}
And the statement: int x = plus(2, 3);. Same here, we would expect x to have value 5 afterwards. The computation is done, and whoever is waiting on that value (of type int) receives and uses the value however a single value of that type would be used in place of it. For example:
int x = plus(plus(1,2),plus(3,plus(4,1)); -> x has value 11.
Back to your example: you need to assign a variable to the String value returned from histogram(randomNum);, as such:
Change histogram(randomNum) to String s = histogram(randomNum).
This will make it all compile, but you'll hit one final roadblock: The thing won't run! This is because a runnable main method needs to be static. So change your main method to have the signature:
public static void main(String[] args){...}
Then hit the green button!
For starters your main method should be static:
public static void main(String[] Args)
Instance methods can not be called without an instance of the class they belong to where static methods can be called without an instance. So if you want to call your other methods inside the main method they must also be static unless you create an object of type prog310t then use the object to call the methods example:
public static void main(String[] Args)
{
prog310t test = new prog310t();
test.histogram(1);
}
But in your case you probably want to do:
public static String histogram (int randomNum)
public static void main(String[] Args)
{
histogram(1);
}
Also you are not catching the return of histogram() method in your main method you should do like this:
System.out.print(histogram(randomNum) + "\n");
Or
String test = histogram(randomNum);
System.out.print(test + "\n");
Static methods are part of a class and can be called without an instance but instance methods can only be called from an instance example:
public class Test
{
public static void main(String[] args)
{
getNothingStatic();// this is ok
getNothing(); // THIS IS NOT OK IT WON'T WORK NEEDS AN INSTANCE
Test test = new Test();
test.getNothing(); // this is ok
getString(); // this is ok but you are not capturing the return value
String myString = getString(); // now the return string is stored in myString for later use
}
public void getNothing()
{
}
public static void getNothingStatic()
{
}
public static String getString()
{
return "hello";
}
}
Void means the method is not returning anything it is just doing some processing. You can return primitive or Object types in place of void but in your method you must specify a return if you don't use void.
Before calling histogrom (randomNum) you need to either make histogram static or declare the object that has histogram as a method
e.g
prog310t myClass = new prog310t();
myClass.histogram()
I'm learning, I'm newbie
but I wanted to know what I do to get "run" it.
this happening a error:
Static Error: This class does not have a static void main method accepting String[].
This is the code:
/**
* #author "LionH"
*/
public class Caneirinho {
public static void contar() {
int i = 1;
String a = " Carneirinho",
b = " pulando a cerca.",
c = "s";
for (i = 1; i <= 100; i++) {
if (i == 1) {
System.out.println(i + a + b);
} else {
System.out.println(i + a + c + b);
}
}
}
} // Carneirinho
Any Java class that you run directly must have a main method, which is the entry point, i.e., where the program starts when you execute the code.
public static void main(String args[])
Just rename your method contar() to main(String args[]) and it should work.
Alternate to #mellamokb Answer
public class Caneirinho{
public static void contar(){
int i = 1;
String a = " Carneirinho",
b = " pulando a cerca.",
c = "s";
for(i=1; i<=100; i++){
if(i==1){
System.out.println( i + a + b );
} else {
System.out.println( i + a + c + b );
Thread.sleep(1000); // thread wais for 1 sec ie 1000 milisecond
}
}
}
public static void main(String[] args){
contar(); // call contar() from main method
}
}//Carneirinho
If you write a java program, it can have a number of classes but for all the classes to run we should have a main class which is used to implement the classes which we defined. You created a class without main in it. The program will start its execution from main.
I need a refresher on moving classes from one file into two files. My sample code is in one file called "external_class_file_main". The program runs fine and the code is shown below:
Public class external_class_file_main {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
I move the get_a_random_number class to a separate file called "external_class_file". When I do this, I get the following error:
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method get_a_random_number(int, int) is undefined for the type
external_class_file_main
at external_class_file_main.main(external_class_file_main.java:20)
The "external_class_file_main" now contains:
public class external_class_file_main {
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
The "external_class_file" now contains:
public class external_class_file {
public static int get_a_random_number (int min, int max) {
int n;
n = (int)(Math.random() * (max - min +1)) + min;
return (n);
}
}
You need to refer t get_a_random_number via the class external_class_file. E.g.:
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
You should definitely stick to Java naming conventions though.
Here the solution:
public class external_class_file_main {
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
}
But, please, take a look into Java naming conventions.
You no longer have access to the get_a_random_number method from the external_class_file_main class. As the method you need is static you can just refer directly to it as follows:
public static void main(String[] args) {
int r;
System.out.println("Program starting...");
r = external_class_file.get_a_random_number (1, 5);
System.out.println("random number = " + r);
System.out.println("Program ending...");
}
PS you will find it a lot easier to code and for people reading your questions if you use proper Java naming conventions for your methods and classes e.g. no underscores and start classes with a capital letter. http://en.wikipedia.org/wiki/Naming_convention_%28programming%29