Java学習8日目
【八日目】Java学習
1. 練習問題
public class Main {
int x = 3;
static int y = 2;
public static void main(String[] args) {
int x = 10;
int y = 10;
Main obj = new Main();
obj.printIt();
obj.printIt(y);
}
Main() {x = x+1;}
static{y += y;}
void printIt() {
System.out.print(++x);
}
void printIt(int y) {
System.out.print(" " + ++y);
}
}
実行結果:>java Main.java
5 11
public class Main {
void x(int num) {
num += 30;
}
public static void main(String[] args) {
int num = 10;
Main obj = new Main();
obj.x(num);
System.out.print(num);
}
}
実行結果:java Main.java
10
public class Main {
void x(int[] num) {
num[0] += 30;
}
public static void main(String[] args) {
int[] num = {10};
Main obj = new Main();
obj.x(num);
System.out.print(num[0]);
}
}
実行結果:>java Main.java
40
class Boo{
private String msg;
public Boo(String m) { msg = m; }
public void setMsg(String m) { msg = m; }
public String getMsg() { return msg; }
public Goo useGoo(Goo g) {
setMsg(g.getMsg());
return g;
}
}
class Goo {
private String msg;
public Goo(String m) { msg = m; }
public void setMsg(String m) { msg = m; }
public String getMsg() { return msg; }
}
public class Main {
public static void main(String[] args){
Boo b = new Boo("Boo");
Goo g = new Goo("Goo");
b.useGoo(g);
System.out.println(b.getMsg() + " : " + g.getMsg());
}
}
実行結果:java Main
Goo : Goo
public class Main {
public static void main(String[] args){
Main ojb1 = new Main();
Main ojb2 = new Main();
System.out.print(ojb1 == ojb2);
ojb2 = operate(ojb1,ojb2);
System.out.print(" " + (ojb1 == ojb2));
}
static Main operate(Main ojb1, Main ojb2) {
Main ojb3 = ojb1;
ojb1 = ojb2;
return ojb3;
}
}
実行結果:java Main.java
false true
class Foo{
int x;
Foo(int a) {x = a;}
void setX(int a) {x = a;}
int getX() {return x;}
}
public class Main {
public static void main(String[] args) {
Foo f1 = new Foo(500);
System.out.print(" 1 : " + f1.getX());
Main obj = new Main();
Foo f2 = obj.toObj(f1);
System.out.print(" 2 : " + f2.getX());
}
Foo toObj(Foo f1) {
Foo f2 = new Foo(100);
System.out.print(" 3 : " + f1.getX());
return f2;
}
}
実行結果:>java Main
1 : 500 3 : 500 2 : 100
public class Main {
int val;
static void x(int val) {
val = 9;
System.out.print(val + " ");
}
public static void main(String[] args) {
Main obj = new Main();
obj.val = 8;
int val = 10;
System.out.print(val + " ");
x(val);
System.out.print(val + " ");
System.out.print(obj.val + " ");
}
}
実行結果:>java Main.java
10 9 10 8
public class Main {
static int x = 1;
int y = 1;
public static void main(String[] args) {
Main obj1 = new Main();
Main obj2 = new Main();
obj1.x = 5;
obj1.y = 6;
obj2.x = 7;
obj2.y = 8;
System.out.print("ans:" + obj1.x + obj1.y + obj2.x + obj2.y);
}
}
実行結果:java Main.java
ans:7678