Using Objects in a similar way to Variables in Java - java

Can i use the following code? It's not throwing any error at the Object but at obj.i. Is this a legal way of using an object? Also, how many ways can i create an object other than using the normal syntax obj s = new obj();
public class Test {
static int i;
static Test obj;
obj.i = 10; //am getting a compilation error here "Syntax error on token "i", VariableDeclaratorId expected after this token"
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}

You need to place a static block around the obj.i assignment statement for this to work:
public class Test {
static int i;
static Test obj;
static { obj.i = 10; }
public static void main(String[] args) {
System.out.println(i+" "+ obj);
}
}

This is not, you didn't initialize. Furthermore you might not want to use static.
public static void main(String [] args) {
int i = 10;
Test obj = new Test();
obj.setI(i);
System.out.println("my objects I = "+ obj.getI());
}
now in your Test object
public class Test {
private int i;
public void setI(int i) {
this.i = i;
}
public int getI() {
return this.i;
}
}

Related

Is there any flaw in the below design ? My intention is whenever an object is created, unique id has to be generated

public class Test {
private static int counter = 1;
int uniqueId;
public Test() {
uniqueId = counter++;
}
public int getUniqueId() {
return uniqueId;
}
}
public class TestSub {
public static void main(String args[]) {
Test a = new Test();
Test b = new Test();
}
}
Assuming that:
the scope of int is large enough for your needs
you will not work with more than one thread at a time
you do not need randomness (for security reasons)
it should do exactly what you're describing.

Increment a variable without using static keyword

Here I am using static keyword to instantiate a variable And I am calling the variable using two different Objects.I want to print the result as 1 and 2 without using the static keyword.Thanks in advance.
public class Test {
static int a = 1;
public void meth() {
System.out.println(a);
a = a + 1;
}
public static void main(String[] args) {
Test a = new Test();
Test b = new Test();
a.meth(); //prints 1
b.meth(); //prints 2
}
}
If you remove the static keyword, you need to share an int variable in your two instances of Test.
For example, using AtomicInteger as a mutable wrapper for int and providing the object when constructing Test:
public class Test {
private final AtomicInteger a;
// + constructor setting a + getter
public void increment() {
a.incrementAndGet();
}
}
public class Main {
public static void main(String[] args) {
AtomicInteger i = new AtomicInteger()
Test a = new Test(i);
Test b = new Test(i);
System.out.println(i.get()); // prints 0
a.increment();
System.out.println(i.get()); // prints 1
b.increment();
System.out.println(i.get()); // prints 2
}
}

is it possible to print static method?

class DuckPrivate
{
private static int size;
public static void main(String [] args)
{
Duck d=new Duck();
d.setSize(25);
d.getSize();
System.out.println("size of duck is "+size);
}
public static void setSize(int s)
{
size=s;
}
public static int getSize()
{
return size;
}
}
I am getting the error cannot find the symbol getSize(),why i am getting this error,is it possible to print the static method.
Duck d = new Duck(); you are calling set/getSize method of Duck not DuckPrivate and note d.getSize(); if exist will return the value which you need to store.In DuckPrivate you can simply call setSize(25); as it's static and just print size.

Declaration for an array being called into main from a method (Java)

I am fairly new to java, and am having what I assume is a simple problem with my program.
For the method arrayTest2, I cannot import it into main due to an error on compilation:
"Cannot find symbol, symbol: variable dataStorage".
I have tried also tried the declarations:
arrayTest2(dataStorage[][])
and
arrayTest2(dataStorage[5][5])`
but they don't work.
Any help would be greatly appreciated.
Cheers
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
The problem here is the scope: Something defined in one function is not visible in another. What you will normally do to solve this is to return the value. Something like this:
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
int[][] dataStorage = arrayTest();
arrayTest2(dataStorage);
}
public static int[][] arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
return dataStorage;
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
Alternatively you could have your dataStorage field as a global variable, this is however potentially very confusing. To do that you'd define
public class TrialArray
{
private static int[][] dataStorage;
// ...
public static void arrayTest() {
dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
// ...
}
on this line
arrayTest2(dataStorage);
You are passing parameter to method, that has one argument "dataStorage", but you don't declare it.
You try to pass dataStorage to your arrayTest-function, but dataStorage is not a field of the class, neither is it a local variable of main (aka dataStorage does not exist in main).
public static void main(String [] args) {
arrayTest();
arrayTest2(dataStorage); //<------- What is dataStorage?
}
Here is a little tutorial on variable scopes in Java. You probably want to return the array you created in arrayTest() and use it, but I am just guessing what you want to do.
You cant access variables in declared inside other methods.
To make it work, you would have to do this:
public class TrialArray
{
int[][] dataStorage;
public static void main(String [] args)
{
dataStorage = new int[5][5];
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}

Represent a Java type as a varargs

Is it possible to do something like this using Java features?
class myClass {int i; String s;}
static void myMethod(myClass... args)
{
...
}
main()
{
myMethod(2,"two",3,"three");
}
It is not possible. Perhaps you could create a static helper method which makes creating your objects as easy as possible.
static myClass mc(int i, String s) {
return new myClass(i, s);
}
myMethod(mc(2, "two"), mc(3, "three"));
No, but you can make a constructor of MyClass and invoke:
myMethod(new MyClass(2, "two"), new Myclass(3, "three"));
For the sake of brevity you can make a statically-imported factory method:
public class MyClass {
public MyClass create(String s, int i) {
return new MyClass(s, i);
}
}
and use:
myMethod(create(2, "two"), create(3, "three"));
You could do it with a wrapper class:
class MyWrapper {
private int i;
private String s;
public MyWrapper(int _i, String _s) {
i = _i;
s = _s;
}
}
class Test {
static void myMethod(MyWrapper... args) {
//do work
}
public static void main(String[] args) {
myMethod(new MyWrapper(2, "two"), new MyWrapper(3, "three"));
}
}
Yes, sortof. You need a constructor of your class...
public class MyClass{
int i
String s;
public MyClass(int i, String s){
this.i = i;
this.s = s;
}
}
public static void myMethod(MyClass... instances){
.....
}
public static void myMethod(Object... args){
MyClass[] instances = new MyClass[args.length / 2];
for (int i=0; i<args.length / 2; i++){
instances[i] = new MyClass((Integer)args[i * 2], (String)args[(i*2) + 1]);
}
myMethod(instances);
}
You would need to add error checking to ensure that args has an even number of elements and there is not a method to enforce that every i * 2 element is an Integer and every i * 2 + 1 is a String. But it is possible.
Given all of the above, I will say... this is very non-standard programming and I would not recommend it. But as you see, it is possible.

Categories

Resources