Secretly, studying Forget and google for yourself
final data type constant name=value
null There is no reference destination The empty ("") string is not null because there is an empty string at the reference destination. → Primitive types do not have a null state
On null, using the equals method raises an exception. (NullPointerException) Use the "==" operator.
Use the "isEmpty" method
Can be created by extending an existing class Subclasses inherit superclass fields and methods. Use the super keyword to access superclass methods Use the this keyword to access subclass methods. There is one superclass and multiple subclasses.
super.hoge();
Implement the matching parent method name, return value, and arguments in the child class It seems to be good to explicitly add "@Override".
//Child class
@Override
void hoge(){
}
Subclass methods take precedence over overridden methods.
Classes that cannot be instantiated
abstract class TestClass {
void test() {
System.out.println("TEST");
}
}
public class SampleProgram {
public static void main(String[] args) {
//Compile error: Unable to instantiate type TestClass
TestClass tc = new TestClass();
}
}
--A method that does not contain an instruction in the method --Abstract methods are defined in abstract classes --A subclass that inherits an abstract class remains an abstract class unless you override the abstract method (??)
abstract class TestClass {
//Ordinary method
void test() {
System.out.println("TEST");
}
//Abstract method
abstract void test2();
}
abstract class TestClass {
//Compile error: Abstract method does not specify body
abstract void test() {
System.out.println("TEST");
}
}
Even if you inherit an abstract class, if you define a subclass as an abstract class, you don't need to override it. ..
abstract class TestClass {
//Ordinary method
void test() {
System.out.println("TEST");
}
//Abstract method
abstract void test2();
}
//No compilation error
abstract class subClass extends TestClass {
}
//Compile error: Type subClass is an inherited abstract method TestClass.test2()Must be implemented
class subClass extends TestClass {
}
--Defining the methods that a class should have --Implement what is defined in the interface in the class --The class implements all the methods defined in the interface. --Like inheritance, not one-to-N. Multiple inheritance of N to N is possible. --Methods defined in the interface are implicitly treated with the "public abstract" qualifier, so be sure to add the "public" qualifier when implementing. --When implementing an interface in a class, separate the interface with "," --Not only methods but also constants can be defined Variables defined in interface fields are implicitly unqualified With "public static final", that is, it becomes a constant. --The interface can also inherit the interface.
interface testIf{
int test();
void test2(String msg);
}
interface testIf{
void test2(String msg);
}
//Compile error: type test is an inherited abstract method testIf.test2(String)Must be implemented
class test implements testIf{
}
//Compile error: Cannot reduce visibility of methods inherited from testIf
class test implements testIf{
void test2(String msg) {
System.out.println(msg);
}
}
//No compilation errors
class test implements testIf{
public void test2(String msg) {
System.out.println(msg);
}
}
interface testIf1{
void test1(String msg);
}
interface testIf2{
int test2();
}
class test implements testIf1, testIf2{
public void test1(String msg) {
System.out.println(msg);
}
public int test2() {
return 1;
}
}
interface testIf1{
int HOGE = 1;
public static final String HOGE2 = "constant";
}
class test implements testIf1{
int i = testIf1.HOGE;
//Compile error: final field testIf1.Cannot be assigned to HOGE
//testIf1.HOGE = 1;
void testPrint() {
System.out.println(testIf1.HOGE2);
}
}
public class SampleProgram {
public static void main(String[] args) {
test t = new test();
t.testPrint();
}
}
interface testIf1{
int HOGE = 1;
public static final String HOGE2 = "constant";
void test();
void test2();
}
//Interface inheritance
interface testIf2 extends testIf1{
void test();
}
//Compile error: type test is an inherited abstract method testIf1.test2()Must be implemented
class test implements testIf2{
@Override
public void test() {
//TODO auto-generated method stub
}
}
//No compilation errors
class test implements testIf2{
@Override
public void test() {
//TODO auto-generated method stub
}
@Override
public void test2() {
//TODO auto-generated method stub
}
}
Even if the parent interface and the child interface have the same method definition, it will not be treated as an error. .. It's going to be a source of confusion.
In Japanese, it means polymorphism (performs various movements).
--Subclass instances can be assigned to variables of superclass type --You can assign an instance of the class that implements the interface to a variable of the interface type. --When you call a method, the method referenced by the variable is executed regardless of the type of the variable. (difficult..)
import java.util.ArrayList;
import java.util.List;
interface TestIf{
public abstract void run();
}
class TestAAA implements TestIf{
String myClassName = "TestAAA";
@Override
public void run() {
//TODO auto-generated method stub
System.out.println(myClassName);
}
}
class TestBBB implements TestIf{
String myClassName = "TestBBB";
@Override
public void run() {
//TODO auto-generated method stub
System.out.println(myClassName);
}
}
public class SampleProgram {
public static void main(String[] args) {
//Interface type collections and arrays are available
List<TestIf> list = new ArrayList<TestIf>();
TestIf[] array = new TestIf[2];
//Set each instance in the collection
list.add(new TestAAA());
list.add(new TestBBB());
//Set each instance in the array
array[0] = new TestAAA();
array[1] = new TestBBB();
System.out.println("collection");
for(TestIf ti: list) {
ti.run();
}
System.out.println("Array");
for(int i = 0; i < array.length; i++) {
array[i].run();
}
}
}
array2 becomes a reference to array1. Rewriting the elements of array2 also affects array1. The reverse is also true.
int[] array1 = {1,2,3};
int[] array2 = array1;
You can copy the value using the clone method. The same applies to the collection.
int[] array2 = array1.clone();
Sometimes the clone method is not enough. If the element is an object type instead of a primitive type Since the object type is not a value but a reference destination as an element, the value at the reference destination is not copied. This is called a shallow copy. This means that multiple objects will share the same value. Deep copy to copy up to the referenced value. How much to copy depends on the program.
seems hard. ..
Specify to force the type by enclosing the type in "<" and ">" and noting it.
Only String type can be entered.
List<String> list = new ArrayList<String>();
A caution message appears on Eclipse, but it can be used. Since we don't specify the type of data, we can enter anything other than primitive types.
List list = new ArrayList();
--No need for explicit cast --Cast can slow down processing --Easy to understand what kind of data will be entered
List list = new ArrayList();
List<String> list2 = new ArrayList<String>();
//The cast is complicated
System.out.println(((String) list.get(0)).length());
//Can be used like a normal String type
System.out.println(list2.get(0).length());
Certainly, it may be easier to use Generics. Eclipse is excellent though.
Array name.length
public class SampleProgram {
public static void main(String[] args) {
int[] box = {0,1,2,3,4,5,6,7,8,9};
for(int i = 0; i < 10; i++) {
if(i == 5) {
System.out.println(i+1+":"+box[i]+"_continue");
continue;
}else if(i == 7) {
System.out.println(i+1+":"+box[i]+"_break");
break;
}
System.out.println(i+1+":"+box[i]);
}
}
}
//result
1:0
2:1
3:2
4:3
5:4
6:5_continue
7:6
8:7_break
public class SampleProgram {
public static void main(String[] args) {
int[] box = {0,1,2,3,4,5,6,7,8,9};
int i = 0;
while(i < 10) {
System.out.println(i+1+":"+box[i]);
i++;
}
}
}
public class SampleProgram {
public static void main(String[] args) {
int[] box = {0,1,2,3,4,5,6,7,8,9};
int i = 0;
do {
System.out.println(i+1+":"+box[i]);
i++;
}while(i < 10);
}
}
I haven't seen do ~ while in a long time ... As the number of subscripts increases, the stock of names runs out. ..
import java.util.HashSet;
import java.util.Set;
public class SampleProgram {
public static void main(String[] args) {
//Do not allow duplicate values
//There is no guarantee of order
Set<String> hs = new HashSet<String>();
hs.add("White");
hs.add("Red");
hs.add("White");
hs.add("Green");
int[] array = {1,2,3,1};
//HashSet has no get method
// for(int i = 0; i < hs.size(); i++) {
// System.out.println(hs.(i));
// }
//Extended for statement
for(String item : hs) {
System.out.println(item);
}
for(int i : array) {
System.out.println(i);
}
}
}
//result
Green
Red
White
1
2
3
1
Difficult ...
public class TestMain {
public static void main(String[] args) {
List<String> cities = new ArrayList<String>();
cities.add("Kyoto");
cities.add("Osaka");
cities.add("Aichi");
System.out.println("Loop 1");
for(int i = 0; i < cities.size(); i++) {
System.out.println(cities.get(i));
}
System.out.println("Loop 2");
for(Iterator<String> ite = cities.iterator(); ite.hasNext();) {
System.out.println(ite.next());
}
System.out.println("Loop 3: Extension for loop");
for(String city : cities) {
System.out.println(city);
}
System.out.println("Loop 4:");
cities.forEach(new Consumer<String>() {
public void accept(final String citiy) {
System.out.println(citiy);
}
});
System.out.println("Loop 5: Lambda expression");
cities.forEach((final String city) -> System.out.println(city));
System.out.println("Loop 6: Lambda expression");
cities.forEach(System.out::println);
}
}
map
import java.util.HashMap;
import java.util.Map;
public class SampleProgram {
public static void main(String[] args) {
Map<String, String> map = new HashMap<String, String>(){
{
put("001","Red");
put("002","Blue");
put("003","Green");
}
};
//value
for(String item : map.values()) {
System.out.println(item);
}
//Key
for(String item : map.keySet()) {
System.out.println(item);
}
}
}
Write the source code casually with Sakura Editor or Notepad
javac hoge.java
And casually compile I didn't realize that I was just popping a button on Eclipse. After manually compiling the source code created on Eclipse on DOS
//Source code
public class SampleProgram {
public static void main(String[] args) {
System.out.println("Hoge");
}
}
//result
C:\MyWork\>javac SampleProgram.java
SampleProgram.java:6:error:This character cannot be mapped to encoding MS932
System.out.println("縺 縺?");
^
1 error
C:\MyWork\>
This happens because the source file is "UTF-8" and the Windows default encoding is "MS932". If you do not specify the encoding when compiling with javac, it will be compiled with the default encoding of JVM (?). If the environment is Windows and the file encoding is "UTF-8"
javac -encoding utf8 SampleProgram.java
Then you can compile it safely.
import java.util.Properties;
import java.util.Enumeration;
class sampleEncoding{
public static void main(String args[]){
System.out.println(System.getProperty("file.encoding"));
}
}
The default encoding is a Java program and seems to have an effect on input and output. If you do not specify the encoding of the file when reading the file It seems that the default encoding is used In an environment where the default encoding is "utf8" If the file to be read is "euc", you have to specify the encoding Causes garbled characters.
If you change the default encoding in advance, you can modify the source code and input files. Even if you don't do it, the characters will not be garbled and you can compile it.
For REM windows
set JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8
C:\MyWork>javac SampleProgram.java
SampleProgram.java:6:error:This character cannot be mapped to encoding MS932
System.out.println("縺 縺?");
^
1 error
C:\MyWork>set JAVA_TOOL_OPTIONS=-Dfile.encoding=UTF8
C:\MyWork>javac SampleProgram.java
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF8
C:\MyWork>
There seems to be an error when it is internally converted to binary and calculated
It seems to use the BigDecimal class. It seems to calculate without converting to binary.
import java.math.BigDecimal;
public class SampleProgram {
public static void main(String[] args) {
double xx = 1.0;
double yy = 0.9;
System.out.println(xx - yy);
System.out.println(xx / yy);
BigDecimal x = new BigDecimal("1.0");
BigDecimal y = new BigDecimal("0.9");
System.out.println(x.subtract(y));
System.out.println(x.divide(y, 2, BigDecimal.ROUND_UP));
System.out.println(x.divide(y, 2, BigDecimal.ROUND_DOWN));
System.out.println(x.divide(y, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(x.divide(y, 3, BigDecimal.ROUND_HALF_DOWN));
System.out.println(x.divide(y, 2, BigDecimal.ROUND_HALF_UP));
System.out.println(x.divide(y, 3, BigDecimal.ROUND_HALF_DOWN));
}
}
//result
0.09999999999999998
1.1111111111111112
0.1
1.12
1.11
1.11
1.111
1.11
1.111
What is the difference between BigDecimal.ROUND_HALF_UP and BigDecimal.ROUND_HALF_DOWN? As a result of receiving comments and re-examining BigDecimal.ROUND_HALF_UP is rounded off BigDecimal.ROUND_HALF_DOWN is rounded off was. It's completely different. .. ..
import java.math.BigDecimal;
import java.text.DecimalFormat;
public class SampleProgram {
public static void main(String[] args) {
DecimalFormat format = new DecimalFormat("#.#");
BigDecimal x = new BigDecimal("10.55");
BigDecimal xx = x.setScale(1, BigDecimal.ROUND_HALF_UP);
System.out.println("Rounded to the first decimal place: " + format.format(xx));
BigDecimal xxx = x.setScale(1, BigDecimal.ROUND_HALF_DOWN);
System.out.println("Rounded to the first decimal place: " + format.format(xxx));
}
}
//result
Rounded to the first decimal place: 10.6
Rounded to the first decimal place: 10.5
By the way, if you specify only the number to divide by divide, the following exceptions will occur ... It seems that the cause is that the calculation result is a recurring decimal
System.out.println(x.divide(y));
//exception
Exception in thread "main" java.lang.ArithmeticException: Non-terminating decimal expansion; no exact representable decimal result.
at java.math.BigDecimal.divide(BigDecimal.java:1690)
at SampleProgram.main(SampleProgram.java:15)
It can be separated by "_". As a result of the display, the calculation is not affected. Hmm. .. .. Is it convenient to define constants?
int x = 1_000;
int x = 12;
int y = 5;
double ans = (double)x / (double)y;
--Primitive types --Same class inheritance source --The same interface is implemented
Use the String.valueOf method How to use Class name. Method name
int x = 1234;
String ss = String.valueOf(x);
Now that it's a string type, you can use the length method.
public class SampleProgram {
public static void main(String[] args) {
int x;
x = 123 * 234;
System.out.println(String.valueOf(x).length());
}
}
The method to call on the class
--Static method --static method --Class method
On the contrary, the method that calls the object (for the variable) It's called the instance method.
Is there a "static" way to tell?
Convert primitive types to objects using wrapper classes.
Primitive type | Wrapper class |
---|---|
boolean | Boolean |
char | Character |
byte | Byte |
short | Short |
int | Integer |
long | Long |
float | Float |
double | Double |
import java.io.IOException;
public class SampleProgram {
public static void main(String[] args) throws IOException {
String x = "123";
String xx = "12.45";
int y;
double yy;
//Primitive type cannot be assigned to String type
//y = x;
y = Integer.valueOf(x);
System.out.println(y);
yy = Double.valueOf(xx);
System.out.println(yy);
}
}
//result
123
12.45
--Primitive types are supported by cast (ex. (Double) i / (double) ii) --String type → Primitive type is supported by the method of String class --Primitive type → String type is supported by wrapper class
When I start working in various languages, I don't know how to write "else if". ..
if(Condition 1) {
}else if(Condition 2) {
}else {
}
operator | meaning |
---|---|
== | equal |
!= | different |
> | - |
>= | - |
< | - |
<= | - |
"==" Determines if the objects are the same, Use "equals" to see if the values are the same. "Equals" is included in types other than primitive types.
(Difference between reference type and base type. The base type stores the value, but the reference type stores the address of the object ... ??)
difficult. ..
public class SampleProgram {
public static void main(String[] args) {
String[] tell = {"090-1234-1234","1234-1234-1234","090-O123-1234"};
/*
*3 digit number-4-digit number-4-digit number
*/
for(int i = 0; i < tell.length; i++) {
System.out.println(tell[i]);
if(tell[i].matches("\\d{3}-\\d{4}-\\d{4}")) {
System.out.println("Correct answer");
}else {
System.out.println("Incorrect answer");
}
}
}
}
//result
090-1234-1234
Correct answer
1234-1234-1234
Incorrect answer
090-O123-1234
Incorrect answer
I wonder if finally isn't used much. ..
try{
}catch(Exception class variable name){
}finally{
}
When an exception occurs in a method, it can be thrown out of the method without catching it in the method. You have to catch the exception outside.
Return value method name(argument)throws exception type{
}
Is there a try-with-resources syntax? .. .. It seems to be a function from Java 7. ~~ Let's leave it for now. .. ~~ I was taught how to use it in the comments! It may be convenient.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SampleProgram {
public static void main(String[] args) {
String fileName1 = "C:\\test3.txt";
String fileName2 = "C:\\test4.txt";
//String fileName1 = null;
try (
FileReader fr = new FileReader(new File(fileName1));
BufferedReader bfr = new BufferedReader(fr);
FileReader fr2 = new FileReader(new File(fileName2));
BufferedReader bfr2 = new BufferedReader(fr2);
)
{
String ss = null;
while((ss = bfr.readLine()) != null) {
System.out.println(ss + "Loaded");
//throw new IOException();
}
}catch(IOException e) {
e.printStackTrace();
}
}
}
//Uninflected word
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SampleProgram {
public static void main(String[] args) {
try {
File file = new File("C:\\test3.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String ss = null;
while((ss = bfr.readLine()) != null) {
System.out.println(ss + "Loaded");
}
bfr.close();
}catch(IOException e) {
e.printStackTrace();
}
}
}
//result
java.io.FileNotFoundException: C:\test3.txt (The specified file could not be found.)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at SampleProgram.main(SampleProgram.java:12)
//Throw an exception out
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SampleProgram {
public static void main(String[] args) throws IOException {
File file = new File("C:\\test3.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String ss = null;
while((ss = bfr.readLine()) != null) {
System.out.println(ss + "Loaded");
}
bfr.close();
}
}
//result
Exception in thread "main" java.io.FileNotFoundException: C:\test3.txt (The specified file could not be found.)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at SampleProgram.main(SampleProgram.java:11)
What is thrown by throw is an instance of a class that inherits Throwable.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
public class SampleProgram {
public static void main(String[] args) throws IOException {
try {
File file = new File("C:\\test3.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String ss = null;
while((ss = bfr.readLine()) != null) {
System.out.println(ss + "Loaded");
}
bfr.close();
}catch(IOException e) {
IOException ee = new IOException("IOException has occurred! !!");
throw ee;
}
}
}
//result
Exception in thread "main" java.io.IOException:IOException has occurred! !!
at SampleProgram.main(SampleProgram.java:21)
If you want to create an exception that is not prepared by yourself, create an exception class that inherits the Exception class.
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
class myException extends Exception{
myException(String msg) {
super(msg);
}
}
public class SampleProgram {
public static void main(String[] args) throws Exception {
try {
File file = new File("C:\\test3.txt");
FileReader fr = new FileReader(file);
BufferedReader bfr = new BufferedReader(fr);
String ss = null;
while((ss = bfr.readLine()) != null) {
System.out.println(ss + "Loaded");
}
bfr.close();
}catch(Exception e) {
e.printStackTrace();
throw new myException("threw");
}
}
}
//result
java.io.FileNotFoundException: C:\test3.txt (The specified file could not be found.)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileReader.<init>(FileReader.java:72)
at SampleProgram.main(SampleProgram.java:19)
Exception in thread "main" myException:threw
at SampleProgram.main(SampleProgram.java:29)
Access modifier Class name(Argument type argument) {
//Something processing
}
The constructor is not inherited.
//Parent class
class p{
p(){
System.out.println("Parent constructor 1");
}
p(int x){
System.out.println("Parent constructor 2");
}
}
//Child class
class c extends p{
}
public class SampleProgram {
public static void main(String[] args) throws Exception {
c cc = new c(10);
c cc = new c();
}
}
c cc = new c(10);
If "Constructor c (int) is undefined" compile error
c cc = new c();
so "Parent constructor 1" is displayed Pretending that the parent constructor (with no arguments) is inherited It seems that the compiler automatically added the default constructor because nothing was declared in the child class.
I do not know on the source, but it seems that it is supposed to call the parent constructor like this
class c extends p{
c(){
super();
}
}
I tried to explicitly add a constructor to the child, but for some reason the parent's constructor was also called.
class p{
p(){
System.out.println("Parent constructor 1");
}
p(int x){
System.out.println("Parent constructor 2");
}
}
class c extends p{
c(){
System.out.println("Child constructor 1");
}
}
public class SampleProgram {
public static void main(String[] args) throws Exception {
c cc = new c();
}
}
//result
Parent constructor 1
Child constructor 1
After all, when the child class is instantiated, of course, the child class constructor is executed. However, it seems that the constructor without arguments of the parent class is called without permission before that. I can't see it on the source, but it seems like this.
class c extends p{
c(){
super();★ Can be attached by the compiler
System.out.println("Child constructor 1");
}
}
Hmmm. .. .. If you don't know it ..
A syntax that can be memorized or diverted by copying
import static java.lang.System.*;
public class SampleProgram{
public static void main(String[] args) {
out.println("hoge");
}
}
Hishidama's technical memo page →Java
Recommended Posts