I don't know what's wrong with my code. I want to display the value of b (10) in my info() method, but when I run this code, the value of b is 0. Why does this happen?
class Alpha {
public int a = 5;
public void info() {
System.out.println("a = " + a);
Beta3 betaku;
betaku = new Beta3();
System.out.println("b = " + betaku.perolehB());
System.out.println("Dipanggil pada " + this.getClass().getName());
System.out.println("----------");
}
}
Here's the main class:
class Beta3 extends Alpha {
private int b;
public void isiB(int b){
this.b=b;
}
public int perolehB(){
return b;
}
public static void main(String[] args) {
Beta3 varobjBeta;
varobjBeta = new Beta3();
varobjBeta.isiB(10);
varobjBeta.info();
Alpha varobjAlpha;
varobjAlpha = new Alpha();
varobjAlpha.info();
}
}
That will never work, in the info method you wrote this:
Beta3 betaku;
betaku = new Beta3();
System.out.println("b = " + betaku.perolehB());
And ever will display 0(Because b is not initialized in the betaku instance, so the default is 0), you should delete that line, and pass the b value in some way, or override the info method in Beta3 class.
class Beta3 extends Alpha
{
//Another code
public void info()
{
// super.info(); if you wanna show the a value too
System.out.println("b=" + this.b);
}
//Some other code
}
Or if you need to access that value from Alpha class:
class Alpha
{
public void info(Beta3 aux)
{
this.info();
aux.info();
}
}
Then in main you can do something like this:
public static void main(String[] args)
{
Beta3 varobjBeta;
varobjBeta = new Beta3();
varobjBeta.isiB(10);
Alpha varobjAlpha;
varobjAlpha = new Alpha();
varobjAlpha.info(varobjBeta);
}
Make line 4 of your main() method, beta_ku.info();. Your other calls to .info aren't working because you haven't called isiB and they're defaulting to 0.
Every time you write new Beta3, a new object of type Beta3 is created, with a new pair of attributes. If you want the value of an attribute you set in a previous object, just pass the reference of that object to the method and fetch the value from it.
That's because you are asking for the value of an instance of Beta3, which never initializes its value anyways and Java automatically initializes ints to 0 (for some reason).
beta_ku should print out 10 correctly, but varobjBeta does not set its b value.
The instance of Beta3 in your info call to Alpha does not have its b value set. Therefore, it is initialized at instantiation to 0.
The real reason this happens is due to the way initial values are established, per the JLS:
Each class variable, instance variable, or array component is initialized with a default value when it is created. ...
...which in general, means that all primitives are initialized to some form of zero, and all objects are initialized to null.
How would you get around this? Either create an instance by hand of Beta3 and pass that to the instance of Alpha, or just use Beta3 to print its own info.
Observe that beta_ku would work fine, if you were calling info - for that instance, b is defined to 10.
betake = new Beta3();
When you instantiate the betake it just assign the default values to the attributes of the class Beta3. Here the attribute of the class Beta3 is b.
Below is a table of default values of class variables by type:
Type default
--------------------------------------------------------
boolean false
int 0
float 0.0
char /u0000
reference type null
So in you class Beta3 b is int so the it gets the default value of 0. You need to call isiB(int b) to set the intended value to b or you have to write a parameterized con structure to set the value of b i.e.
public Beta3(int bb){
this.b= bb;
}
EDIT
Beta3 betaku;
betake = new Beta3();
betake.isiB(10);
System.out.println("b = " + betaku.perolehB());
Hope it helps.
Related
I want to build a method that when it is called in main, automatically increment the value of variable.If first value is 0 when its called increment it to 1 , when I call for second time from 1 to be incremented at 2 and so on.
Notes: The method is part of a class and it called via object in main.
you can use the static variables. Static variables are initialized only once, at the start of the execution. These variables will be initialized first, before the initialization of any instance variables.
Create a static variable whose value can be updated in a function.
let this be your class
class Student {
static int b; //initialized to zero only when class is loaded not for each object created.
public void update(){
//incrementing static variable b
b++;
}
public void showData(){
System.out.println("Value of b = "+b);
}
}
and this be your main class
public class Demo{
public static void main(String args[]){
Student s1 = new Student();
s1.update();
s1.showData();
Student s2 = new Student();
s2.update();
s1.showData();
}
}
output:
Value of b = 1
Value of b = 2
Well, you kinda left a lot up for interpretation here, assuming the "value of variable" is part of the object the code would be something like this:
public class MyClass {
public int myVariable = 0;
public MyClass() {}
public void incrementMyVariable() {
myVariable++;
}
}
How you would handle this depends on where the variable your referring to is located ie. main method, object variable, etc... Additionally, if the variable needs to be kept constant across all the objects created for the class you would need it to be static.
I have very silly doubt that why we use return statement in method . Without using return statement in method we can also get required value
as example
package testing;
public class ReturnMethod {
static int a = 10;
static int b = 5;
static int c;
static int d;
public static void add() {
c = a + b;
}
public static int returnAddValue() {
d = a + b;
return d;
}
public static void main(String[] args) {
add();
System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In above example in both the cases i am getting output
c: 15
value: 15
So i am having doubt when to use return statement and why is neccessary
With return statement, the return value is not necessary to be saved in any global, external or member variable.
However, without return statement you have to prepare kind of outer variable value to track that.
If you assign the result of a method to a static variable (and, indeed, pass in the "parameters" of the method by setting static variables), you have problems when that method is called by two threads concurrently, since the variables are shared for all invocations of the method:
Thread t1 = new Thread(() -> {a = 1; b = 2; add(); }); t1.start();
Thread t2 = new Thread(() -> {a = 3; b = 4; add(); }); t2.start();
t1.join(); t2.join();
You don't know which of these threads run first, or even if they run at the same time; so you don't know what the value of a or b is when you call add(), and nor do you know whether the value in c afterwards is the result of the invocation in the first or second thread (or a mixture of the two).
The value stored in c afterwards could be any of 3, 5 or 7 (or any other value, if there is another thread which is also invoking add() concurrently outside this code.
This problem of thread interference just completely goes away if you keep values localized to the stack, by passing a and b as method parameters, and receiving the result as a return value.
Even if your code is single-threaded, it's simply ugly to have to write:
a = 1;
b = 2;
add();
int result = c;
rather than
int result = add(1, 2);
You should use a return statement, when you need the method to return a value.
In your case, both methods work.
But you can, and should use returning methods, when you don't want a field of your class to be changed by another class.
For example, you want money to be only seen, and not changed, when you are making a bank-account related software. So, you make money private, and make a method which returns the money. In this way, other classes can only see money, but not change it.
First, your functions are different, as you see
public static **void** add()
public static **int** returnAddValue()
First one does not return anything, because it has void as return type and the second one has int as return type.
First one works, because c is a global variable.
You typically would use return when you don't store the result in a (static) variable of your class.
public class ReturnMethod {
static int a = 10;
static int b = 5;
public static void add() {
int c = a + b;
}
public static int returnAddValue() {
int d = a + b;
return d;
}
public static void main(String[] args) {
add();
//not possible to access c here
//System.out.println("c: " + c);
int value = returnAddValue();
System.out.println("value: " + value);
}
}
In that modified example, there would be no way for you to access the result of the add() method.
You should probably read about Scopes in Java.
You have a class variable c & d. These variables are associated with the class and stored in heap. If you assign a value back to it and you can access it without a explicit return statement. But if you have declared d inside the method then return statement is required to give the value back to the caller.
The reason that you are able to access the value of class variable c is that it has been initialized as static. Had this not been the case the information in the c variable would be lost as soon as the add method ends. The reason methods have return value is that they user can get the updated value , if there are any manipulation in the object data. In this case there is a very small, what if there is series of manipulation with the data. In that case the final value has to be returned to the calling object which without return statement is not possible.
Its totally depends upon our requirement whether to return a value from our method or update instance variable. Some time we just want to process a value and get back the result in and result will be used in different manner, in this case we need to return value from method.
For example
java.lang.Math.sqrt(double a) method return a value and we use returned value as per our need OR requirement. Can you think if this method does not returned any value then what it should update, I think this method useless if it does not returned any value.
The variable C in your code snippet is accessed in the class throughout, and will stay until the object of the class exists. So you can print the value of Variable C outside the method.
However, if you had declared a local variable in the method add(), then print statement System.out.println("c: " + c); will print the default value for variable c. That is zero in this case.
I was just trying some sample code for checking class variable overriding behavior in Java. Below is the code:
class A{
int i=0;
void sayHi(){
System.out.println("Hi From A");
}
}
class B extends A{
int i=2;
void sayHi(){
System.out.println("Hi From B");
}
}
public class HelloWorld {
public static void main(String[] args) {
A a= new B();
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
a.sayHi(); // method from B gets called since object is of type B
}
}
I am not able to understand whats happening at these two lines below
System.out.println("i->"+a.i); // this prints 0, which is from A
System.out.println("i->"+((B)a).i); // this prints 2, which is from B
Why does a.i print 0 even if the object is of type B? And why does it print 2 after casting it to B?
i is not a method - it's a data member. Data members don't override, they hide. So even though your instance is a B, it has two data members - i from A and i from B. When you reference it through an A reference you will get the former and when you use a B reference (e.g., by explicitly casting it), you'll get the latter.
Instance methods, on the other hand, behave differently. Regardless of the the type of the reference, since the instance is a B instance, you'll get the polymorphic behavior and get the string "Hi From B" printed.
Even though A is initialized as new B(), the variable is an A. if you say
B a = new B();
you won't have that problem.
Based on my reference, primitive types have default values and Objects are null. I tested a piece of code.
public class Main {
public static void main(String[] args) {
int a;
System.out.println(a);
}
}
The line System.out.println(a); will be an error pointing at the variable a that says variable a might not have been initialized whereas in the given reference, integer will have 0 as a default value. However, with the given code below, it will actually print 0.
public class Main {
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
What could possibly go wrong with the first code? Do class variables behave different from local variables?
In the first code sample, a is a main method local variable. Method local variables need to be initialized before using them.
In the second code sample, a is class member variable, hence it will be initialized to the default value.
Read your reference more carefully:
Default Values
It's not always necessary to assign a value when a field is declared.
Fields that are declared but not initialized will be set to a
reasonable default by the compiler. Generally speaking, this default
will be zero or null, depending on the data type. Relying on such
default values, however, is generally considered bad programming
style.
The following chart summarizes the default values for the above data
types.
. . .
Local variables are slightly different; the compiler never assigns a
default value to an uninitialized local variable. If you cannot
initialize your local variable where it is declared, make sure to
assign it a value before you attempt to use it. Accessing an
uninitialized local variable will result in a compile-time error.
These are the main factors involved:
member variable (default OK)
static variable (default OK)
final member variable (not initialized, must set on constructor)
final static variable (not initialized, must set on a static block {})
local variable (not initialized)
Note 1: you must initialize final member variables on every implemented constructor!
Note 2: you must initialize final member variables inside the block of the constructor itself, not calling another method that initializes them. For instance, this is not valid:
private final int memberVar;
public Foo() {
// Invalid initialization of a final member
init();
}
private void init() {
memberVar = 10;
}
Note 3: arrays are Objects in Java, even if they store primitives.
Note 4: when you initialize an array, all of its items are set to default, independently of being a member or a local array.
I am attaching a code example, presenting the aforementioned cases:
public class Foo {
// Static and member variables are initialized to default values
// Primitives
private int a; // Default 0
private static int b; // Default 0
// Objects
private Object c; // Default NULL
private static Object d; // Default NULL
// Arrays (note: they are objects too, even if they store primitives)
private int[] e; // Default NULL
private static int[] f; // Default NULL
// What if declared as final?
// Primitives
private final int g; // Not initialized. MUST set in the constructor
private final static int h; // Not initialized. MUST set in a static {}
// Objects
private final Object i; // Not initialized. MUST set in constructor
private final static Object j; // Not initialized. MUST set in a static {}
// Arrays
private final int[] k; // Not initialized. MUST set in constructor
private final static int[] l; // Not initialized. MUST set in a static {}
// Initialize final statics
static {
h = 5;
j = new Object();
l = new int[5]; // Elements of l are initialized to 0
}
// Initialize final member variables
public Foo() {
g = 10;
i = new Object();
k = new int[10]; // Elements of k are initialized to 0
}
// A second example constructor
// You have to initialize final member variables to every constructor!
public Foo(boolean aBoolean) {
g = 15;
i = new Object();
k = new int[15]; // Elements of k are initialized to 0
}
public static void main(String[] args) {
// Local variables are not initialized
int m; // Not initialized
Object n; // Not initialized
int[] o; // Not initialized
// We must initialize them before use
m = 20;
n = new Object();
o = new int[20]; // Elements of o are initialized to 0
}
}
There are a few things to keep in mind while declaring primitive type values.
They are:
Values declared inside a method will not be assigned a default value.
Values declared as instance variables or a static variable will have default values assigned which is 0.
So in your code:
public class Main {
int instanceVariable;
static int staticVariable;
public static void main(String[] args) {
Main mainInstance = new Main()
int localVariable;
int localVariableTwo = 2;
System.out.println(mainInstance.instanceVariable);
System.out.println(staticVariable);
// System.out.println(localVariable); // Will throw a compilation error
System.out.println(localVariableTwo);
}
}
Yes, an instance variable will be initialized to a default value. For a local variable, you need to initialize before use:
public class Main {
int instaceVariable; // An instance variable will be initialized to the default value
public static void main(String[] args) {
int localVariable = 0; // A local variable needs to be initialized before use
}
}
Local variables do not get default values. Their initial values are undefined without assigning values by some means. Before you can use local variables they must be initialized.
There is a big difference when you declare a variable at class level (as a member, i.e., as a field) and at the method level.
If you declare a field at the class level they get default values according to their type. If you declare a variable at the method level or as a block (means any code inside {}) do not get any values and remain undefined until somehow they get some starting values, i.e., some values assigned to them.
All member variables have to load into the heap, so they have to be initialized with default values when an instance of class is created.
In case of local variables, they don't get loaded into the heap. They are stored on the stack until they are being used. This is before Java 7, so we need to explicitly initialize them.
In Java, the default initialization is applicable for only instance variable of class member.
It isn't applicable for local variables.
In the first case you are declaring "int a" as a local variable(as declared inside a method) and local varible do not get default value.
But instance variable are given default value both for static and non-static.
Default value for instance variable:
int = 0
float,double = 0.0
reference variable = null
char = 0 (space character)
boolean = false
I wrote following function to return a default representation 0 or false of a primitive or Number:
/**
* Retrieves the default value 0 / false for any primitive representative or
* {#link Number} type.
*
* #param type
*
* #return
*/
#SuppressWarnings("unchecked")
public static <T> T getDefault(final Class<T> type)
{
if (type.equals(Long.class) || type.equals(Long.TYPE))
return (T) new Long(0);
else if (type.equals(Integer.class) || type.equals(Integer.TYPE))
return (T) new Integer(0);
else if (type.equals(Double.class) || type.equals(Double.TYPE))
return (T) new Double(0);
else if (type.equals(Float.class) || type.equals(Float.TYPE))
return (T) new Float(0);
else if (type.equals(Short.class) || type.equals(Short.TYPE))
return (T) new Short((short) 0);
else if (type.equals(Byte.class) || type.equals(Byte.TYPE))
return (T) new Byte((byte) 0);
else if (type.equals(Character.class) || type.equals(Character.TYPE))
return (T) new Character((char) 0);
else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
return (T) new Boolean(false);
else if (type.equals(BigDecimal.class))
return (T) BigDecimal.ZERO;
else if (type.equals(BigInteger.class))
return (T) BigInteger.ZERO;
else if (type.equals(AtomicInteger.class))
return (T) new AtomicInteger();
else if (type.equals(AtomicLong.class))
return (T) new AtomicLong();
else if (type.equals(DoubleAdder.class))
return (T) new DoubleAdder();
else
return null;
}
I use it in hibernate ORM projection queries when the underlying SQL query returns null instead of 0.
/**
* Retrieves the unique result or zero, <code>false</code> if it is
* <code>null</code> and represents a number
*
* #param criteria
*
* #return zero if result is <code>null</code>
*/
public static <T> T getUniqueResultDefault(final Class<T> type, final Criteria criteria)
{
final T result = (T) criteria.uniqueResult();
if (result != null)
return result;
else
return Utils.getDefault(type);
}
One of the many unnecessary complex things about Java making it unintuitive to use. Why instance variables are initialized with default 0 but local are not is not logical. Similar why enums dont have built in flag support and many more options. Java lambda is a nightmare compared to C# and not allowing class extension methods is also a big problem.
Java ecosystem comes up with excuses why its not possible but me as the user / developer i dont care about their excuses. I want easy approach and if they dont fix those things they will loose big in the future since C# and other languages are not waiting to make life of developers more simple. Its just sad to see the decline in the last 10 years since i work daily with Java.
I have commented between codes:
public class Main {
public static void main(String[] args) {
// This is local variable.
// Look! you have declared it within the "body of a method".
// Local variables must be initialized.
int a;
System.out.println(a);
}
}
Now the next one
public class Main {
//This is NOT a local variable. It is NOT in a method body!
//Look! you have defined it as class member ( or a property).
//Java is more generous with local variables and initiates them.
//(ex: int with 0, boolean with false, String(or any object) with null, ...)
static int a;
public static void main(String[] args) {
System.out.println(a);
}
}
How to initialize the values in constructor that the values cannot be passed by object and that we could pass them from main method?
class ex
{
int a,b;
ex()
{
this.a=b;
}
public static void main(String args[])
{
//here we pass the values to that consructor ex
ex obj=new ex();
}
}
make an overloaded constructor which accepts two arguments.
public ex(int a, int b) {
this.a = a;
this.b = b;
}
public static void main(String...args){
ex obj = new ex(1,2)
}
values canntot be passed by object we should pass from main method
If i understand correctly, you want to pass arguments from the main method and nitialize them in your constructor, the only was to do is by passing them to the constuctor while object creation
You can call setter method from constructor if don't want to display initialization values while declaring new object.
Please see code below for reference :
class Testcl {
int a,b;
Testcl(){
setValues(1,2);
}
private void setValues(int a, int b){
this.a=a;
this.b=b;
}
public static void main(String [] args){
Testcl test = new Testcl();
System.out.println("a : " + test.a + " b : " + test.b);
}}
The first thing to say is that this does actually "work" ... in the sense that it compiles and executes without any errors.
int a,b; // default initialized to 'zero'
ex() {
this.a=b; // assigns 'zsro' to a.
}
But of course, it doesn't achieve anything ... because a is already zero at that point.
Now the main method could assign something to the a and/or b fields after the constructor returns. But there is no way (in pure Java1) to get some non-zero value into b before the constructor is called ... if that is what you are asking.
The practical solution is to just to add a and b arguments to the constructor.
1 - a non-pure Java solution might be to "monkey around" with the bytecodes of the constructor so that it does what you "need" to do. But that's pretty horrible, and horrible solutions have a tendency of coming back to bite you.