[Personal memo] Frequently used Java grammar updated from time to time

Self-introduction

This is my first year as a member of society who has just studied Java. It summarizes Java grammar like a memo. As for the grammar, it feels like "I'm having trouble finding it" and "I'm having trouble remembering it", so it's a completely personal memo.

We are looking for advice on Java.

String split

Example


String str = new String("Minami Hoshino,Asuka Saito,Miona Hori");
String[] oshi = str.split(",");

//output
for (int i=0; i < oshi.length; i++) {
  System.out.println(oshi[i]);
}

output


Minami Hoshino
Asuka Saito
Miona Hori

String comparison

Example


String str1 = "Minami Hoshino";
String str2 = "Minami Hoshino";
String str3 = "Ranze Terada";

//Comparison
//str1 and str2
if (str1.equals(str2)) {
  System.out.println("equal");
} else {
  System.out.println("Not equal");
}

//Comparison
//str1 and str3
if (str1.equals(str3)) {
  System.out.println("equal");
} else {
  System.out.println("Not equal");
}

output


equal
Not equal

Regular expressions

date Determine if the date stored in the string ymd is in the form YYYY / MM / DD.

Example


Pattern p = Pattern.compile("^[0-9]{4}/[0-9]{2}/[0-9]{2}$");
Matcher m = p.matcher(ymd);
m.find(); //True if matched,False if not matched

time Judge whether the time stored in the character string time is in the form of HH: mm.

Example


Pattern p = Pattern.compile("^[0-9]{2}:[0-9]{2}$");
Matcher m = p.matcher(time);
m.find(); //True if matched,False if not matched

** Other regular expressions **

Example


// URL
Pattern p = Pattern.compile("^https?://([\w-]+\.)+[\w-]+(/[\w-./?%&=]*)?$");

//Domain name
Pattern p = Pattern.compile("^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z-]{2,}$");

//Landline number
Pattern p = Pattern.compile("^0\d(-\d{4}|\d-\d{3}|\d\d-\d\d|\d{3}-\d)-\d{4}$");

//cell phone number
Pattern p = Pattern.compile("^0[789]0-\d{4}-\d{4}$");

//Free dial
Pattern p = Pattern.compile("^(0120|0800)-\d{3}-\d{3}$");

//Postal code
Pattern p = Pattern.compile("^\d{3}-\d{4}$");

Date and time format specification

Example


SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd (E)", Locale.JAPANESE);
SimpleDateFormat de = new SimpleDateFormat("yyyy/MM/dd");
SimpleDateFormat dd = new SimpleDateFormat("HH:mm");
SimpleDateFormat dc = new SimpleDateFormat("HH:mm:ss");

Get the current date and time

Get the current date and time and store it in ** Today **

Example


SimpleDateFormat de = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");

//Get the current date
Date today = new Date();
today.toString();
String Today = de.format(today);

Date comparison (equal (), after (), before ())

Example


public void dateTodate() throws ParseException {
  SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
  Date date1 = sdf.parse("2020/04/01");
  Date date2 = sdf.parse("2020/04/30");
  Date date3 = sdf.parse("2020/04/01");

  if (date1.equals(date3)) {
    System.out.println("date1 and date3 are the same day");
  }

  if (date1.before(date2)) {
    System.out.println("date1 is past compared to date2");
  }

  if (date2.after(date1)) {
    System.out.println("date2 is the future compared to date1");
  }
}

output


date1 and date3 are the same day
date1 is past compared to date2
date2 is the future compared to date1

Leap year judgment

Determine if the variable ymd_YYY (year) is a leap year.

Example


//Leap year judgment
if (Integer.parseInt(ymd_YYYY) % 4 == 0) {
	if ((Integer.parseInt(ymd_YYYY) % 100) == 0) {
		if ((Integer.parseInt(ymd_YYYY) % 400) == 0) {
			//leap year
		}
	} else {
		//leap year
	}
}

Copy of 2D array

Example


String[][] oshi = { {"Minami Hoshino", "Asuka Saito", "Miona Hori"}, {"South", "Asuka", "Miona"}, {"Chiba", "Tokyo", "Gifu Prefecture"}};
String[][] oshi_copy = new String[oshi.length][];

for (int i=0; i < oshi.length; i++) {
	oshi_copy[i] = new String[oshi[i].length];
	
	for (int j=0; j < oshi[i].length; j++) {
		oshi_copy[i][j] = oshi[i][j];
	}
}

//output
for (int i=0; i < oshi_copy.length; i++) {
	for (int j=0; j < oshi_copy[i].length; j++) {
		System.out.println(oshi_copy[i][j]);
    }
}

output


Minami Hoshino
Asuka Saito
Miona Hori
South
Asuka
Miona
Chiba
Tokyo
Gifu Prefecture

for statement (for, extension for, foreach)

Example


// for
//Standard
for (int i=0; i < 10; i++) {
  //processing
}

//Extension for
//Used when processing all elements of an array or list in order
for (String str : Array) {
  //processing
}

// forEach
//Can be written more concisely than the top two(I don't fully understand...)
str.forEach( i -> //processing);

in conclusion

If you have any Java grammar that you often use, we are looking for it in the comment section.

Recommended Posts

[Personal memo] Frequently used Java grammar updated from time to time
I translated the grammar of R and Java [Updated from time to time]
From Java to VB.NET-Writing Contrast Memo-
Memorandum Poem (updated from time to time)
Convert from java UTC time to JST time
Memo for migration from java to kotlin
[Reverse lookup] Spring Security (updated from time to time)
SpringBoot useful site collection (updated from time to time)
[Updated from time to time] Links that are indebted
Touch all Spring "Guides" (updated from time to time)
Changes from Java 8 to Java 11
Sum from Java_1 to 100
Frequently used Java generics
From Java to Ruby !!
[Updated from time to time] Ruby on Rails Convenient methods
[Eclipse] Summary of environment settings * Updated from time to time
Learning memo when learning Java for the first time (personal learning memo)
Migration from Cobol to JAVA
New features from Java7 to Java8
Connect from Java to PostgreSQL
How to store a string from ArrayList to String in Java (Personal)
Personally recommended Intellij IDEA initial settings (updated from time to time)
Time taken to acquire Java SE11 Silver, teaching materials used
A concise summary of Java 8 date / time APIs that are likely to be used frequently
I'll forget to look it up, so I've put together a list of frequently used Docker commands [updated from time to time]
From Ineffective Java to Effective Java
Java HashMap, entrySet [Personal memo]
Design patterns to enjoy with frequently used Java libraries --Factory pattern
Summary of results of research on object orientation [Updated from time to time]
How to convert param to hash with Rails controller (updated from time to time)
git flow Frequently used commands Memo
Personal memo: Metaprogramming with Java reflection
Java to be involved from today
Java, interface to start from beginner
The road from JavaScript to Java
[Java] Conversion from array to List
[Java] Processing time measurement method memo
Introduction to Docker (1) Frequently used commands
[Personal memo] How to interact with a random number generator in Java
Introduction to java for the first time # 2
[Personal notes] Frequently used IntelliJ IDEA shortcuts
[Personal memo] Java data type is annoying
[Java] How to measure program execution time
Connect from Java to MySQL using Eclipse
[Java] How to set the Date time to 00:00:00
Java 8 to start now ~ Date time API ~
From installing Eclipse to executing Java (PHP)
Post to Slack from Play Framework 2.8 (Java)
Java: How to send values from Servlet to Servlet
[Java] Flow from source code to execution
Introduction to monitoring from Java Touching Prometheus
Precautions when migrating from VB6.0 to JAVA
[Personal memo] Java development environment is ready
Type conversion from java BigDecimal type to String type
Display message dialog in java (personal memo)
Points I stumbled upon when creating an Android application [Updated from time to time]
Git commands that new engineers should look back on [updated from time to time]