Basic grammers for java

2 minute read

Variables

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

String msg = new String(bArray, StandardCharsets.UTF_8);

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

Data Types

Java Primitive Data Types

  • 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
  • boolean : 1bit
  • char : 2bytes, Stores a single character/letter or ASCII values

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

Type conversion

1. String to others

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

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

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

2. Change to string

// boolean ---> String
String.valueOf(b)

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

// double ---> String    
double f = Math.random();
rndNum.setText(String.valueOf(f));

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

// JSONObject ---> JSON String

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


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

3. Etc

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

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