abstract | assert | boolean | break | byte |
case | catch | char | class | const |
continue | default | do | double | else |
enum | extends | final | finally | float |
for | goto | if | implements | import |
instanceof | int | interface | long | native |
new | package | private | protected | public |
return | short | static | strictfp | super |
switch | synchrnized | this | throw | throws |
transient | try | void | volatile | while |
_ |
abstract
abstract method name(argument, argument, ...);
abstract class AbstractClass {
abstract public void method();
}
class ConcreteClass extends AbstractClass{
public void method(){
//Implementation details
}
}
AbstractClass c = new AbstractClass(); //Compile error
AbstractClass c = new ConcreteClass(); //Yes
ConcreteClass c = new ConcreteClass(); //Yes
assert
private int divide(int x, int y) {
assert y != 0 : y +“Must be a number greater than 0”;
return x / y;
}
boolean
//In the case of if statement
public class Main {
public static void main(String[] args) throws Exception {
boolean bool1 = false;
if(bool1) {
System.out.println("The value of bool1 is true");
} else {
System.out.println("The value of bool1 is false");
}
int number = 100;
boolean isResult = number < 200;
if(isResult) {
System.out.println("The value of isResult is true");
} else {
System.out.println("The value of isResult is false");
}
}
}
//Execution result
The value of bool1 is false
The value of isResult is true
//For while statement
public class Main {
public static void main(String[] args) throws Exception {
boolean bool = true; //Initial value setting
int count = 1; //Initial value setting
while(bool) {
System.out.println("The value of count is" + count + "is.");
if(count == 5) {
bool = false; //Processing to be executed when the value of count reaches 5.
}
count++; //Add 1 to the value of the variable "count".
}
}
}
//Execution result
The value of count is 1.
The value of count is 2.
The value of count is 3.
The value of count is 4.
The value of count is 5.
//For Boolean type
public class Main {
public static void main(String[] args) throws Exception {
Boolean bool = null;
if(bool == null) {
System.out.println("The value of bool is null");
} else if(bool) {
System.out.println("The value of bool is true");
} else {
System.out.println("The value of bool is false");
}
}
}
//Execution result
The value of bool is null
break
//For switch statements
public static void main(String[] args) {
int num = 3;
switch(num) {
case 1:
System.out.println("It's 1");
break;
case 2:
System.out.println("It's 2");
break;
case 3:
System.out.println("It's 3");
break;
case 4:
System.out.println("It's 4");
break;
default:
System.out.println("It's default");
}
}
//Execution result
It's 3
//For statement
public static void main(String[] args) {
for (int i = 1; i <= 5; i++) {
if (i == 3) {
break;
}
System.out.println(i + "Time");
}
System.out.println("It's done");
}
//Execution result
First time
Second time
It's done
//For while statement
public static void main(String[] args) {
int num = 1;
while(true) {
if (num == 3) {
break;
}
System.out.println(num + "This is the second time");
num++;
}
System.out.println("It's done");
}
//Execution result
It's the first time
It's the second time
It's done
//For double loop
loop1: for(Initialization formula;Conditional expression;Change formula){//Specify the name of the for statement in loop1
for(Initialization formula;Conditional expression;Change formula){
if(Conditional expression when exiting the for loop) break loop1;//Specify the for statement to exit in loop1
Processing content
}
}
//Execution result
When the condition is met, exit the loop1 process
byte
//Declaration of byte type variable and assignment of initial value
byte b = 100;
//Declaration of byte type array and assignment of value to each index
byte[] byteArray1 = new byte[3];
byteArray1[0] = 11;
byteArray1[1] = 12;
byteArray1[2] = 13;
//Declaration of byte type array and initialization at the same time
byte[] byteArray2 = { -128, 0, 127 };
switch
public class Main {
public static void main(String[] args) {
int num = 3;
switch(num) {
case 1:
System.out.println("Variable num is 1");
break;
case 2:
System.out.println("The variable num is 2");
break;
case 3:
System.out.println("Variable num is 3");
break;
case 4:
System.out.println("Variable num is 4");
break;
default:
System.out.println("The variable num is not an integer from 1 to 4");
}
}
}
//Execution result
Variable num is 3
case
public class Main {
public static void main(String[] args) {
int num = 3;
switch(num) {
case 1:
System.out.println("Variable num is 1");
break;
case 2:
System.out.println("The variable num is 2");
break;
case 3:
System.out.println("Variable num is 3");
break;
case 4:
System.out.println("Variable num is 4");
break;
default:
System.out.println("The variable num is not an integer from 1 to 4");
}
}
}
//Execution result
Variable num is 3
default
public class Main {
public static void main(String[] args) {
int num = 5;
switch(num) {
case 1:
System.out.println("Variable num is 1");
break;
case 2:
System.out.println("The variable num is 2");
break;
case 3:
System.out.println("Variable num is 3");
break;
case 4:
System.out.println("Variable num is 4");
break;
default:
System.out.println("The variable num is not an integer from 1 to 4");
}
}
}
//Execution result
The variable num is not an integer from 1 to 4
//For interface
interface Foo{
void print(String s);
default void twice(String s){
print(s);
print(s);
}
}
try
public class Main {
public static void main(String[] args) {
int result;
result = div(5, 0);
System.out.println("Return value= " + result);
}
public static int div(int num1, int num2) {
try {
int result = num1 / num2;
return result;
} catch (ArithmeticException e) {
System.out.println("Exception occured.");
System.out.println(e);
return 0;
}
}
}
catch
catch(Exception class variable name) {
Exception handling;
}
public class Main {
public static void main(String[] args) {
int result;
result = div(5, 0);
System.out.println("Return value= " + result);
}
public static int div(int num1, int num2) {
try {
int result = num1 / num2;
return result;
} catch (ArithmeticException e) {
System.out.println("Exception occured.");
System.out.println(e);
return 0;
}
}
}
//Execution result
Exception occured.
java.lang.ArithmeticException: / by zero
Return value= 0
finally
int n[] = {18, 29, 36};
System.out.println("start");
try{
for (int i = 0; i < 4; i++){
System.out.println(n[i]);
}
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Beyond the range of the array");
}
finally{
System.out.println("Finished outputting the array");
}
System.out.println("Finished");
throw
public class Main {
public static void main(String[] args) {
int result;
result = div(5, 0);
System.out.println("Return value= " + result);
}
public static int div(int num1, int num2) {
try {
if (num2 == 0) {
throw new ArithmeticException("Raise an exception when divided by 0");
}
int result = num1 / num2;
return result;
} catch (Exception e) {
System.out.println("Exception occured.");
System.out.println(e);
return 0;
}
}
}
//Execution result
Exception occured.
java.lang.ArithmeticException:Raise an exception when divided by 0
Return value= 0
throws
public static void main(String[] args) {
int num = 10;
math(num);
math(int i) {
int i += 100;
}
}
public class Main {
public static void main(String[] args) {
int result = 0;
try {
result = div(5, 0);
} catch (Exception e) {
System.out.println("Exception occured.");
System.out.println(e);
}
System.out.println("Return value= " + result);
}
public static int div(int num1, int num2) throws ArithmeticException {
int result = num1 / num2;
return result;
}
}
//Execution result
Exception occured.
java.lang.ArithmeticException: / by zero
Return value= 0
for
for(Initialization formula;Conditional expression;Change formula){
Process to be executed
}
for (Type variable name:Array name or collection name){
Process to be executed
}
public class sample {
public static void main (String[] args){
int sum = 0;//[1]
for (int number = 1; number <= 10; number++) {//[2]
sum += number;//[3]
}
System.out.println("sum:" + sum);//[4]
}
}
//Execution result
sum:55
continue
class sample{
public static void main(String args[]){
for (int i = 1; i < 10; i++){
if (i % 2 == 0){//In this case, only when the value of i is even(1)Will be skipped
continue;
}
System.out.println("i = " + i);//(1)
}
}
}
//Execution result
i = 1
i = 3
i = 5
i = 7
i = 9
if
//In case of 1
public class Main{
public static void main(String[] args){
int number = 80;
if (number > 90) {
System.out.println("Great result!");
} else if (number > 60) {
System.out.println("It's a good result.");
} else {
System.out.println("Let's do our best.");
}
}
}
//Execution result
It's a good result.
//In case of 2
public class Main{
public static void main(String[] args){
int number = 10;
if (number < 20) {
System.out.println(number + "Is less than 20");
}
}
}
//Execution result
10 is less than 20
//In case of 3
public class Main{
public static void main(String[] args){
int number = 10;
if ((number < 20) || (number >= 10)) {
System.out.println(number + "Is a value greater than or equal to 10 or less than 20");
}
}
}
//Execution result
10 is a value greater than or equal to 10 or less than 20
//In case of 4
public class Main {
public static void main(String[] args) {
int number = 10;
String str = (number == 5) ? "number is 5" : "number is not 5";
System.out.println(str);
}
}
//Execution result
number is not 5
//In case of 5
public class Main {
public static void main(String[] args) {
String str1 = "Pote bread";
if(str1 == "Pote bread") {
System.out.println("str1 matches the string "potepan"");
} else {
System.out.println("str1 does not match the string "potepan"");
}
}
}
//Effective result
str1 matches the string "potepan"
else
class sample {
public static void main (String[] args){
int number = 200;//[1]
if (number >= 1 && number <= 9){//[2]
System.out.println("[3] number : 1 - 9");
} else if (number >= 10 && number <= 99) {//[4]
System.out.println("[5] number : 10 - 99");
} else {//[6]
System.out.println("[7] number >= 100");
}
}
}
//Execution result
[7] number >= 100
char
class sample {
public static void main(String[] args) {
char chrHensu1 = 'A'; //Substitute A as it is
char chrHensu2 = 0x0041; //Specify 0x0041
char chrHensu3 = 65; //Specify 65
System.out.println(chrHensu1);
System.out.println(chrHensu2);
System.out.println(chrHensu3);
}
}
//Execution result
A
A
A
class
class class name{
Execution processing...
}
const
do
public class sample {
public static void main(String[] args) {
int i = 0;
do {
System.out.println((i + 1) + "This is the second process");
i++;
} while (i < 3);
System.out.println("Processing is finished");
}
}
//Execution result
This is the first process
This is the second process
This is the third process
Processing is finished
double
//Decimal numbers with a decimal point and integers in binary, octal, and hexadecimal numbers
double d1 = 12345; //Decimal number(integer)
double d2 = 1.2345; //Decimal number(There is a decimal point)
double d3 = -123_456.789_012; //Decimal number, with delimiter
double d4 = 0b0101; //Binary integer
double d5 = 012345; //Integer integer
double d6 = 0x12345; //Hexian integer
//Decimal and hexadecimal exponential notation
double d1 = 1.23e4; //Decimal exponential notation(1.23 × 10 4) → 12300
double d2 = -1.23e-4; //Decimal exponential notation(-1.23x10-4th power) → -0.000123
double d3 = 0x1.23p4; //Hexagonal exponential notation(0x1.23 x 2 to the 4th power) → 18.1875
double d4 = -0x1.23p-4; //Hexagonal exponential notation(-0x1.23x2-4th power) → -0.071044921875
//D as a suffix/If you add a D, the literal will be treated as a double
double d1 = 5 / 10; //→ 0, int 5 is divided by int 10 so the calculation result is int 0
double d2 = 5 / 10d; // → 0.Since 5 of 5 and int is divided by 10 of double, 5 also becomes double, and the calculation result is 0 of double..Become 5
enum
Access modifier enum enum{Enumerator 1,Enumerator 2,・ ・ ・};
When using a switch statement
public class Main {
public static void main(String[] args) {
Fruit fruit_type = Fruit.Orange;
switch(fruit_type) {
case Orange:
System.out.println("Delicious oranges");
break;
case Apple:
System.out.println("I want to eat apples");
break;
case Melon:
System.out.println("Melon is everything");
break;
}
}
protected enum Fruit {
Orange,
Apple,
Melon
};
}
//Execution result
Delicious oranges
When defining fields and methods
public class sample {
public static void main(String[] args) {
for(Fruit frt : Fruit.values()) {
System.out.println(frt.ordinal() + ":" + frt.name() + "," + frt.getValue());
}
}
protected enum Fruit {
Orange("Ehime"),
Apple("Aomori"),
Melon("Ibaraki");
//Define field
private String name;
//Define constructor
private Fruit(String name) {
this.name = name;
}
//Method
public String getValue() {
return this.name;
}
}
}
//Execution result
0:Orange,Ehime
1:Apple,Aomori
2:Melon,Ibaraki
extends
public class Student{
String name;
int id;
attend(){}
}
public class School extends Student{
test(){}
}
interface
//Creating an interface
interface Calc {
int NUM1 = 1;
int NUM2 = 2;
void calc();
}
//Implement the interface and create a class to add
class Add implements Calc {
public void calc() {
System.out.println(NUM1 + NUM2);
}
}
//Implement the interface and create a class to subtract
class Sub implements Calc {
public void calc() {
System.out.println(NUM1 - NUM2);
}
}
//Create a class that executes the class that implements the interface
public class sample {
public static void main(String[] args) {
Add add = new Add();
add.calc();
Sub sub = new Sub();
sub.calc();
}
}
//Execution result
3
-1
implements
public class Sample implements interface name{}
private
class PublicClass {
private String fieldVariable = "PublicClass field variable.";
public void publicMethod() {
System.out.println(fieldVariable + "Output from publicMethod.");
}
}
public class sample {
public static void main(String[] args) {
PublicClass pc = new PublicClass();
pc.publicMethod();
}
}
//Execution result
PublicClass field variable.Output from publicMethod.
protected
//When referencing from a subclass
class SuperClass {
protected String str = "Variables in SuperClass";
}
public class sample extends SuperClass {
public static void main(String[] args) {
sample sc = new sample();
System.out.println(sc.str);
}
}
//Execution result
Variables in SuperClass
//When referencing from the same class
public class sample{
public static void main(String[] args) {
method();
}
protected static void method() {
System.out.println("Methods with protected");
}
}
//Execution result
Methods with protected
//If you cannot access
class SuperClass {
protected String str = "Variables in SuperClass";
}
class SubClass_NG {
public static void main(String[] args) {
SubClass_NG sc = new SubClass_NG();
System.out.println(sc.str);
}
}
//Execution result
sample.java:9:error:Can't find symbol
public
class PublicClass {
public String fieldVariable = "PublicClass field variable.";
public void publicMethod() {
System.out.println(fieldVariable + "Output from publicMethod.");
}
}
public class sample {
public static void main(String[] args) {
PublicClass pc = new PublicClass();
System.out.println(pc.fieldVariable);
}
}
//Execution result
PublicClass field variable.
package
package lang.java.hello;
public class HelloJava {
public HelloJava() {
System.out.println("Hello Java!");
}
}
package lang.cpp.hello;
public class HelloCpp {
public HelloCpp() {
System.out.println("Hello C++!");
}
}
import
import package name.Class name you want to import;
import lang.cpp.hello.HelloCpp;
import lang.java.hello.HelloJava;
public class Main {
public static void main(String[] args) {
HelloJava hello1 = new HelloJava();
HelloCpp hello2 = new HelloCpp();
}
}
while
public class sample {
public static void main(String[] args) {
int num = 0;
while (num < 3) {
System.out.println(num);
num++;
}
}
}
//Execution result
0
1
2
goto
void
public class sample {
static String sampleMethod() {
//Return the string
return "The sample method was called";
}
public static void main(String[] args) {
//Call sampleMethod and assign the result to a String variable named str
String str = sampleMethod();
//Output the contents of the str variable
System.out.println(str);
}
}
//Execution result
The sample method was called
return
//In case of 2
public class sample {
public static void main(String[] args) {
num(0, 2);
}
private static void num(int num1, int num2) {
if (num1 == 0) {
System.out.println("Return to the caller.");
return;
}
int addAns = num1 + num2;
System.out.println("The answer is" + addAns + "is.");
}
}
//Execution result
The answer is 2.
//If there is no return in the same source code
public class sample {
public static void main(String[] args) {
num(0, 2);
}
private static void num(int num1, int num2) {
if (num1 == 0) {
System.out.println("Return to the caller.");
}
int addAns = num1 + num2;
System.out.println("The answer is" + addAns + "is.");
}
}
//Execution result
Return to the caller.
The answer is 2.
//Commentary
Since there is no return, the next processing of the if statement was performed.
new
public class main class name{
public static void main(String[] args) {
//Instance generation
Class name Variable name=new class name();
}
}
class class name{
//Constructor (executed when instantiating)
public class name(){
Initialization process, etc.
}
}
static
class ClassSample {
private int val1 = 0; //Non-static variables(Instance variables)
private static int val2 = 0; //static variable(Class variables)
//Add 1 to the variable each time the constructor class is instantiated
public ClassSample(int val1, int val2) {
this.val1 += val1;
ClassSample.val2 += val2; //"name of the class.Declare a static variable with "variable name"
}
//Show variable value
public void print(){
System.out.println("val1 = " + val1 + ", val2 = " + val2);
}
}
public class sample {
public static void main(String[] args) {
for (int i = 0; i < 3; i++){
ClassSample cs = new ClassSample(1, 1);
cs.print();
}
}
}
//Execution result
val1 = 1, val2 = 1
val1 = 1, val2 = 2
val1 = 1, val2 = 3
final
//For variables
int x = 0; //Ordinary variable declaration, with initial value
x = 1; //Change the value of a variable
final int y = 10; //Variable is declared as final, with initial value
y = 100; //Variables set as final cannot be changed and compile error!!
String s = "A"; //Ordinary reference type variable declaration, with initial value
s = "B"; //Change the reference destination of the reference type variable
final String s2 = "C"; //Reference type variable is declared as final, with initial value
s2 = "D"; //Variables set as final cannot be changed and compile error!!
//For class
final class FinalSample {
}
class ChildFinalSample extends FinalSample { //Compile error!!final classes cannot be inherited
}
//For methods
class FinalSample {
final void method() { //final instance method
}
}
class ChildFinalSample extends FinalSample { //Since it is not a final class, it can be inherited.
void method() { //Compile error!!Final instance methods cannot be overridden
}
}
_
float
public class sample {
public static void main(String[] args) {
float f = 1.25f;
int num = 10;
float addNum = num + f;
System.out.println(num + " + " + f + " = " + addNum);
}
}
//Execution result
10 + 1.25 = 11.25
int
int i1 = 123456789; //Decimal number
int i2 = 0b1010101; //Binary number
int i3 = 012345670; //8 base
int i4 = 0x123ABCDE; //Hexadecimal
int i5 = 123_456_789; //Digit separator(Every 3 digits)
int i6 = 0b1111_1010_0101; //Digit separator(Every 4 bits)
long
public class sample {
public static void main(String [] args) {
int m = 2147483647;
System.out.println(m);
m += 1;
System.out.println(m);
long n = 2147483647;
System.out.println(n);
n += 1;
System.out.println(n);
}
}
//Execution result
2147483647
-2147483648
2147483647
2147483648
short
public class sample {
short a=100;
short b=10;
short c=0;
c = a + d;
System.out.println("c =" + c );
}
//Execution result
sample.java:6:error: <identifier>there is not
instanceof
//When referring to the data type
public class sample {
public static void main(String[] args) {
Object obj = "samurai";
System.out.println(obj instanceof String);
System.out.println(obj instanceof Integer);
}
}
//Execution result
true
false
//To determine if a subclass inherits a spar class
public class sample {
public static void main(String[] args) {
SubClass sub = new SubClass();
System.out.println(sub instanceof SubClass);
System.out.println(sub instanceof SuperClass);
}
}
class SuperClass {}
class SubClass extends SuperClass{}
//Execution result
true
true
//To determine if an interface is implemented
public class sample {
public static void main(String[] args) {
SubClass sub = new SubClass();
System.out.println(sub instanceof SubClass);
System.out.println(sub instanceof Interface);
}
}
interface Interface {}
class SuperClass implements Interface {}
class SubClass extends SuperClass {}
//Execution result
true
true
this
//When referencing methods and variables of the same class
public class sample {
//Sample class variable
String animal = "Rabbits";
public void printAnimal() {
//Local variables
String animal = "Cat";
System.out.println("Local variable animal:" + animal);
System.out.println("Class variable animal:" + this.animal);
}
public static void main(String[] args) {
sample s = new sample();
s.printAnimal();
}
}
//Effective result
Local variable animal:Cat
Class variable animal:Rabbits
//When calling another constructor
class ThisSample8 {
String name;
int amount;
//① Default constructor
ThisSample8() {
this("Anonymous Gonbei", 10); //Call ③ with the default value
}
//② Overloaded constructor(Part 1)
ThisSample8(String name) {
this(name, 20); //Call ③ while using arguments
}
//③ Overloaded constructor(Part 2)
ThisSample8(String name, int amount) {
//Field initialization is done only with this constructor
this.name = name;
this.amount = amount;
}
void printProperty() {
System.out.println(String.format("my name is%s. The money you have%It is d yen.", name, amount));
}
public static void sample(String[] args) {
ThisSample8 sample1 = new ThisSample8();
sample1.printProperty(); //→ Anonymous Gonbei, 10 yen
ThisSample8 sample2 = new ThisSample8("Yamada Taro");
sample2.printProperty(); //→ Taro Yamada, 20 yen
ThisSample8 sample3 = new ThisSample8("Jiro Suzuki", 1000);
sample3.printProperty(); //→ Jiro Suzuki, 1000 yen
}
}
//Execution result
My name is Anonymous Gonbei. The money you have is 10 yen.
My name is Taro Yamada. The money you have is 20 yen.
My name is Jiro Suzuki. The money you have is 1000 yen.
super
//When calling the superclass constructor
public class sample {
public static void main(String[] args) throws Exception {
SubClass sub = new SubClass();
}
}
class SuperClass {
public SuperClass(){
System.out.println("Super_Const");
}
public SuperClass(String str){
System.out.println("str : " + str);
}
public SuperClass(int num){
System.out.println("num : " + num);
}
}
class SubClass extends SuperClass {
public SubClass(){
super("apple");
}
}
//Execution result
str : apple
//When calling the method before overriding
class SuperClassSample {
String str = "SuperClass";
public String getSrt() {
return str;
}
}
class SubClassSample extends SuperClassSample {
String str = "SubClass";
public String getSrt() {
return str;
}
public void print() {
System.out.println("super.str = " + super.str);
System.out.println("str = " + str);
System.out.println("super.getSrt() = " + super.getSrt());
System.out.println("getSrt() = " + getSrt());
}
}
public class sample {
public static void main(String[] args) {
SubClassSample scs = new SubClassSample();
scs.print();
}
}
//Execution result
super.str = SuperClass
str = SubClass
super.getSrt() = SuperClass
getSrt() = SubClass
native
//Java file
pablic native boolean isCameraMute();
//c file
JNIEXPORT jboolean JNICALL prefix_isCameraMute();
return isCsmeraMute();
strictfp
public class sample {
public static void main(String args[]) {
new sample();
}
//Constructor generation
public sample() {
this.strictfpTest();
}
strictfp public void strictfpTest() {
double a = 0.01;
double b = 0.02;
double c = 0.0001;
System.out.println(a * b * c);
}
}
//Execution result
2.0E-8
synchronized
//When not using synchronized
public class sample{
public static void main(String[] args) {
Bathroom bathroom = new Bathroom();
FamilyTread father = new FamilyTread(bathroom, "father");
FamilyTread mother = new FamilyTread(bathroom, "mother");
FamilyTread sister = new FamilyTread(bathroom, "sister");
FamilyTread me = new FamilyTread(bathroom, "I");
father.start();
mother.start();
sister.start();
me.start();
}
}
class FamilyTread extends Thread {
private Bathroom mBathroom;
private String mName;
FamilyTread(Bathroom bathroom, String name) {
this.mBathroom = bathroom;
this.mName = name;
}
public void run() {
mBathroom.openDoor(mName);
}
}
class Bathroom {
void openDoor(String name) {
System.out.println(name + ""I'll take a bath!"");
for (int count = 0; count < 100000; count++) {
if (count == 1000) {
System.out.println(name + ""I took a bath."");
}
}
System.out.println(name + ""I got out of the bath!"");
}
}
//Execution result
Father "I'll take a bath!"
Mother "I'll take a bath!"
Father "I took a bath."
My sister "I'll take a bath!"
I "take a bath!"
Mother "I took a bath."
I "I took a bath."
My sister "I took a bath."
Father "I got out of the bath!"
My sister "I got out of the bath!"
I "I got out of the bath!"
Mother "I got out of the bath!"
//When synchronized is used for class Bathroom
class Bathroom {
synchronized void openDoor(String name) {
System.out.println(name + ""I'll take a bath!"");
for (int count = 0; count < 100000; count++) {
if (count == 1000) {
System.out.println(name + ""I took a bath."");
}
}
System.out.println(name + ""I got out of the bath!"");
}
//Execution result
Father "I'll take a bath!"
Father "I took a bath."
Father "I got out of the bath!"
I "take a bath!"
I "I took a bath."
I "I got out of the bath!"
Mother "I'll take a bath!"
Mother "I took a bath."
Mother "I got out of the bath!"
My sister "I'll take a bath!"
My sister "I took a bath."
My sister "I got out of the bath!"
transient
//Main.java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Main {
public static void main(String[] args) throws Exception {
Player player = new Player(new Badminton());
player.play(); System.out.println();
Player clonePlayer = deepCopy(player);
clonePlayer.play();
System.out.println();
System.out.print("Same instance of Player:");
System.out.println(player == clonePlayer);
System.out.print("Same instance of Badminton:");
System.out.println(player.getSports() == clonePlayer.getSports());
}
@SuppressWarnings("unchecked")
public static <T extends Serializable> T deepCopy(T t) throws Exception {
if (t == null) {
return null;
}
ByteArrayOutputStream byteOut = null;
ObjectOutputStream objectOut = null;
try {
byteOut = new ByteArrayOutputStream();
objectOut = new ObjectOutputStream(byteOut);
objectOut.writeObject(t);
} finally {
objectOut.close();
}
ObjectInputStream objectin = null;
T copy = null;
try {
objectin = new ObjectInputStream(new ByteArrayInputStream
(byteOut.toByteArray()));
copy = (T) objectin.readObject();
} finally {
objectin.close();
}
return copy;
}
}
//Sports.java
public interface Sports {
void play();
}
class Badminton implements Sports {
@Override
public void play() {
System.out.println("Play badminton.");
}
}
//Player.java
import java.io.Serializable;
@SuppressWarnings("serial")
public class Player implements Serializable {
private transient Sports sports;
public Player(Sports sports) {
this.sports = sports;
System.out.println("It is a constructor.");
}
public Sports getSports() {
return sports;
}
public void play() {
System.out.println("Warm up.");
sports.play();
System.out.println("Cool down");
}
}
volatile
public class VolatileSample {
private static volatile int count = 0;
//private static int count = 0;
public static void main(String[] args) {
new MultiThread1().start();
new MultiThread2().start();
}
static class MultiThread1 extends Thread {
public void run() {
int val = count;
while(count < 3) {
if (val != count) {
String message = getName() + ": val = " + val + ", count = " + count;
System.out.println(message + "update");
val = count;
}
}
}
}
static class MultiThread2 extends Thread {
public void run() {
int val = count;
while(count < 3) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
String message = getName() + ": val = " + val + ", count = " + count;
System.out.println(message);
count = ++val;
}
}
}
}
//Execution result
Thread-1: val = 0, count = 0
Thread-0: val = 0, count =1 update
Thread-1: val = 1, count = 1
Thread-0: val = 1, count =2 update
Thread-1: val = 2, count = 2
Recommended Posts