Basic grammars of java for beginners

4 minute read

Running Environment

# run with encoding
java -Dfile.encoding=UTF-8 … 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

Basic grammar

switch/case expression

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

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

// 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();

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()

# 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());
}
    /**
     * 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