Basic grammars of java for beginners

7 minute read

Running Environment

# run with encoding
java -Dfile.encoding=UTF-8 … com.x.Main
java -Dfile.encoding=EUC-KR … com.x.Main

#########################
# run.sh
#########################
for i in ../lib/*.jar; do
    CLASSPATH="$CLASSPATH":"$i"
done

# Not using package
java -classpath $CLASSPATH:. TestSender

# Using package (class or jar)
java -Xdiag -classpath $CLASSPATH:./test.jar:. com.test.TestSender -f/app/inf/java/cfg/test.json -l/app/inf/java/lib

# Using charset
# java -Dsun.jnu.encoding=UTF-8 -Dfile.encoding=UTF-8 ...
  • -Dfile.encoding=UTF-8 : change the default character set to UTF-8

https://www.programmersought.com/article/95251457972/

System.out.println("file.encoding:"+System.getProperty("file.encoding"));  
        System.out.println("sun.jnu.encoding:"+System.getProperty("sun.jnu.encoding")); 

sun.jnu.encoding refers to the default encoding of the operating system, file.encoding refers to the encoding of JAVA files (remember, not class files, all class files are encoded in UTF-8), so, in the same The JAVA application running on the operating system has the same sun.jnu.encoding, and the file.encoding can be encoded differently even in the same JAVA application.

Basic grammar

Expressions

// switch/case
switch(expression) {
  case x:
    // code block
    break;
  case y:
    // code block
    break;
  default:
    // code block
}

// for
String[] temp = { "aa", "bb", "cc" };
for (int i = 0; i < temp .length; i++) { 
    System.out.println(temp[i]);
}

// foreach
String[] temp = { "aa", "bb", "cc" };
for (String el : temp) {
    System.out.println(el);
}

Data Types

Java Primitive Data Types

  • boolean : 1bit
  • byte : 1byte
  • short : 2bytes
  • int : 4bytes
  • long : 8bytes
  • float : 4bytes, Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits
  • double : 8bytes, Stores fractional numbers. Sufficient for storing 15 decimal digits
  • char : 2bytes, Stores a single character/letter or ASCII values

boolean (Boolean)

// String ---> Boolean(Wrapper class), boolean(native)
Boolean boolean1 = Boolean.valueOf("true");
boolean b = Boolean.valueOf("true");
// cf. boolean b = string.equalsIgnoreCase("true");
// boolean ---> String
boolean b = true;
String str = String.valueOf(b)

byte array

// declaration byte array
byte[] bTrCode = new byte[9];
byte[] bArray = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 };

// String to byte array
byte[] textBytes = str.getBytes();
byte[] textBytes = str.getBytes(Charset.forName("UTF-8"));
byte[] textBytes = str.getBytes("UTF-8");

// String to byte[]
byte[] bytes = "hello".getBytes();

// Initialize
Arrays.fill(bytes, 0, recvBuff.length, (byte) 0x00); // Null

// byte[] to String
String s = new String(bytes, StandardCharsets.UTF_8);

//----------------------------------
// byte array to String
//----------------------------------
// public String(byte bytes[], Charset charset) 
// public String(byte bytes[], int offset, int length, Charset charset) 
String msg = new String(bArray, StandardCharsets.ISO_8859_1);


// Appending a byte[] to the end of another byte[] [duplicate]
// create a destination array that is the size of the two arrays
byte[] destination = new byte[ciphertext.length + mac.length];

// copy ciphertext into start of destination 
// (from pos 0, copy ciphertext.length bytes)
System.arraycopy(ciphertext, 0, destination, 0, ciphertext.length);

// copy mac into end of destination 
// (from pos ciphertext.length, copy mac.length bytes)
System.arraycopy(mac, 0, destination, ciphertext.length, mac.length);

// Copy of byte array
byte[] bTrCode = new byte[9];
String str = "test";
byte[] barray = str.getBytes();
System.arraycopy(barray, 0, bTrCode, 0, bTrCode.length);

ByteBuffer

import java.io.*;
import java.nio.ByteBuffer;

// put(byte[]), put(byte[], offset, length), ...
ByteBuffer bb = ByteBuffer.allocate(a.length + b.length + c.length);
bb.put(a);
bb.put(b);
bb.put(c);
byte[] result = bb.array();

// or using method chaining:

byte[] result = ByteBuffer
        .allocate(a.length + b.length + c.length)
        .put(a).put(b).put(c)
        .array();

// Put data into the index
		buf.put(2, (byte)22);
		buf.put(3, (byte)23);
		buf.put(4, (byte)24);

ByteBuffer dynamic allocation performance test

Difference between capacity() and limit()

  • In Write Mode, Capacity and Limit are Same.
  • But in Read mode Limit means the limit of how much data you can read from the data
import java.nio.ByteBuffer;

public class ByteBufferTest {
    static int INIT_ALLOC = 1024;
    static int MORE_ALLOC = 1024;
    static int TEST_CNT = 1000000;

    public static void main(String args[]) throws Exception {
        testByteArr();

        System.out.println("----------------------------------");

        testByteBuffer();
    }

    static void testByteArr() {
        byte[] curbytes = new byte[INIT_ALLOC];
        int idx;

        System.out.println(String.format("Byte Array LEN:%d", curbytes.length));

        long ctime = System.currentTimeMillis();

        try {
            for (idx = 0; idx < TEST_CNT; idx++) {
                if (idx >= curbytes.length) {
                    byte[] tmpbytes = new byte[curbytes.length + MORE_ALLOC];
                    for (int jdx = 0; jdx < curbytes.length; jdx++) {
                        tmpbytes[jdx] = curbytes[jdx];
                    }
                    curbytes = null;
                    curbytes = tmpbytes;
//                    System.out.println(String.format("-------------------New allocation[%d][%d]", curbytes.length, MORE_ALLOC));
                }

                curbytes[idx] = (byte)('a'+(idx%26));
//                System.out.println(String.format("LEN: %d [%d][%c]", curbytes.length, idx, (char)curbytes[idx]));
            }
            if (idx > 0)
                System.out.println(String.format("---> LEN: [%d] DATA: [%d][%c]", curbytes.length, idx-1, (char)curbytes[idx-1]));
        } catch (Exception e) {
            System.out.println("ERROR: " + e.getMessage());
        }
        long elsp = System.currentTimeMillis() - ctime;
        if (elsp > 0)
            System.out.println(String.format("Elapsed time: [%d][%d] TPS:%d", TEST_CNT, elsp, (int) TEST_CNT *1000/elsp));
        else
            System.out.println(String.format("Elapsed time: [%d][%d]", TEST_CNT, elsp));
    }

    static void testByteBuffer() {
        int idx;
        ByteBuffer buftmp;
        ByteBuffer buffer = ByteBuffer.allocate(INIT_ALLOC);
        System.out.println(String.format("ByteBuffer capacity:%d limit:%d pos:%d", buffer.capacity(), buffer.limit(), buffer.position()));

        long ctime = System.currentTimeMillis();

        try {
            for (idx = 0; idx < TEST_CNT; idx++) {
                if (buffer.position() >= buffer.capacity()) {
                    buftmp = ByteBuffer.allocate(buffer.capacity() + MORE_ALLOC);
                    buffer.flip(); // 포지션을 0 으로 설정하고, 리미트를 현재 내용의 마지막 위치로 압축
                    buftmp.put(buffer);
                    buffer.clear();
                    buffer = buftmp;
//                    System.out.println(String.format("-------------------New allocation[%d][%d]", buffer.capacity(), MORE_ALLOC));
                }

                buffer.put((byte)('a'+(idx%26)));
//                System.out.println(String.format("capacity:%d limit:%d pos:%d idx:[%d][%c]", buffer.capacity(), buffer.limit(), buffer.position(), idx, (char)buffer.get(idx)));
            }
            if (idx > 0)
                System.out.println(String.format("---> LEN: [%d] DATA: [%d][%c]", buffer.capacity(), idx-1, (char)buffer.get(idx-1)));
        } catch (Exception e) {
            System.out.println("ERROR: " + e.getMessage());
        }
        long elsp = System.currentTimeMillis() - ctime;
        if (elsp > 0)
            System.out.println(String.format("Elapsed time: [%d][%d] TPS:%d", TEST_CNT, elsp, (int) TEST_CNT *1000/elsp));
        else
            System.out.println(String.format("Elapsed time: [%d][%d]", TEST_CNT, elsp));
    }
}
  • Result
    Byte Array LEN:1024
    ---> LEN: [1000448] DATA: [999999][n]
    Elapsed time: [1000000][241] TPS:4149377
    ----------------------------------
    ByteBuffer capacity:1024 limit:1024 pos:0
    ---> LEN: [1000448] DATA: [999999][n]
    Elapsed time: [1000000][242] TPS:4132231
    

ByteArrayOutputStream

byte[] aa = new byte[9];
byte[] bb = new byte[9];

// merge
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
outputStream.write(aa);
outputStream.write(bb);
byte[] barr = outputStream.toByteArray();

char array

// char array to String
har[] charArray = { 'H', 'e', 'l', 'l', 'o', 'W', 'o', 'r', 'l', 'd' };
String str = new String(charArray);

short, int, long (Short, Integer, Long)

// Interger ---> int
Integer intObj = new Integer(i);

// int ---> String
int from = 123;
String to = Integer.toString(from);

// String ---> int
String from = "123";
int to = Integer.parseInt(from);

float vs double (Float vs Double)

  • float : 32 bits
  • double : 64 bits
float num3 = 1.23456789f;
double num4 = 1.23456789;

System.out.println("float : " + num3);
System.out.println("double : " + num4);
float : 1.2345679
double : 1.23456789

JSON

// JSON
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;

// String to JSONObject
JSONParser parser = new JSONParser();
JSONObject jobj = (JSONObject)parser.parse(new String(data, "UTF-8"));

// JSONArray
JSONArray jarr = (JSONArray)jobj.get("fileList");

// loop array
JSONArray msg = (JSONArray) jsonObject.get("messages");
Iterator<String> iterator = msg.iterator();
while (iterator.hasNext()) {
	System.out.println(iterator.next());
}

Difference between Integer.valueOf and Integer.parseInt

  • Integer.valueOf(String str) : returns new Integer()
  • Integer.parseInt(String str) : returns primitive int

String format

String.format(Locale.US,"[%d]%s", position, getItem(position).title);

Split, Tokenize

spaces are used to separate words

  1. java.util.StringTokenizer : Not used these days
  2. java.util.Scanner
  3. String[] String.split
String phrase = "the music made   it   hard      to        concentrate";
String delims = "[ ]+";
String[] tokens = phrase.split(delims);

for (int i = 0; i < tokens.length; i++)
  System.out.println(tokens[i]);

Java Exception

try
{
  parseTask.execute(result); // Now we start the task to parse the xml
} catch(Exception ex) {
  Log.e("Exception Message: ", ex.getMessage());
}

URL functions

toString() : Full URL string
getProtocol() : Protocol(scheme) information such as http
getHost() : Host information
getPort() : Port
getPath() : Path (Starts with '/')
getQuery() : Parameter information
getFile() : path + query
getAuthority() : host + port
getRef()

File exist

// if the file does not exist, it occurs FileNotFoundException...
try {
  File file = new File("filename");
  if (file.exist()) {

  } else {
    // when ???
  }
} catch (FileNotFoundException e) {
  // File Not Found
} catch (Exception e) {

}

Delete File

try {
  File file = new File(C.MenuFilePath, C.MenuFileName);
  if(file.exists())
  {
    boolean result = file.delete();
    Log.i(TAG, "File is deleted " + C.MenuFilePath + "/" + C.MenuFileName + " " + result);
    finish();
  }
  else
  {
    Log.e(TAG, "Failed to delete file " + C.MenuFilePath + "/" + C.MenuFileName);
  }
} catch (Exception e) {
  Log.e(TAG, "ERROR:" + e.getMessage());
}

Get hostname

String hname = Runtime.getRuntime().exec("hostname");

// This can be failed. it depends on /etc/hosts
InetAddress.getLocalHost().getHostName();

Remove file path

String fname = "/tmp/test.txt";
int idx = fname.lastIndexOf(File.separator);
String _fileName = fname.substring(idx + 1); // Remove path

Run external programs

    // mv example
    Process process = new ProcessBuilder("mv", filename, targetfile).start();

    /**
     * Gets a string representing the pid of this program - Java VM
     */
    public static String getPid() throws IOException, InterruptedException {

        Vector<String> commands = new Vector<String>();
        commands.add("/bin/bash");
        commands.add("-c");
        commands.add("echo $PPID");
        ProcessBuilder pb = new ProcessBuilder(commands);

        Process pr = pb.start();
        pr.waitFor();
        if (pr.exitValue() == 0) {
            BufferedReader outReader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
            return outReader.readLine().trim();
        } else {
            System.out.println("Error while getting PID");
            return "";
        }
    }

Tags:

Categories:

Updated:

Leave a comment