Fundamental Programming Structure (Java)

Key points of Java

  1. In Java, all methods are declared in a class. You invoke a nonstatic method on an object of the class to which the method belongs.
  2. Static methods are not invoked on objects.
  3. Java has eight primitive types: five integral types, two floating-point types, and boolean.
  4. The Math class provides common mathematical functions.
  5. String objects are sequences of unicode code points in UTF-16 encoding. Or more precisely code units, the 16-bit quantities of  the UTF-16 encoding.
  6. With the System.out object, you can display output in a terminal window. A Scanner tied to System.in lets you read terminal input.
  7. Arrays and collections can be used to collect elements of the same type.

Method Calls

In java you can construct object with new operator.

Random generator = new Random();
int rand = generator.nextInt();

Primitive Types

Integer Types

  • int : 4 bytes
  • long : 8 bytes
  • short : 2 bytes
  • byte : 1 byte

Floating – Point Types

  • float : 4 bytes (6-7 significant decimal digits)
  • double : 8 bytes (15 significant decimal digits)

Other Type

  • char : 2 bytes
  • boolean: true/false
  • Constants : Use final. Value cannot be changed once created (but the creation can be delayed)
  • enum : Enumerated values of defined type

Arithmetic Operations

! ~ ++ -- + (unary) - (unary) () (cast) new  - right associativity
= += -= *= /= %= <<= >>= >>>= &= ^= |=   - right associativity

Other operations – left associativity

Mathematical Methods

  • A computation should yield same results no matter which virtual machine executes it. However, may modern processors use floating-point registers with more than 64 bit to add precision and reduce the risk of overflow in intermediate steps of computation. Java allows this optimization. For small set of users who care about this issue, there is strictfp modifier. When added to a method, all floating-point operations in the method are strictly portable
  • Math.pow(x, y) yields x ^ y
  • Math.sqrt(x) computes square root of x
  • Math.min and Math.max computes minimum and maximum of two values.
  • Math class provides trigonometric and logarithmic functions as well as the constants Math.PI and Math.E. For rounding Math.round(x)
  • Mathematical operators quietly return wrong results when a computation overflows. However, if you call Math.multiplyExact(1000000000, 3) instead, an exception is generated. There are also methods addExact, subtractExact, incrementExact, decrementExact, negateExact, toIntExact all with int and long parameters
  • If either of the operands is of type double, the other one is converted to double. Float to float, long to long or int to int.
  • Bitwise operators (&, |, ^) operate on the bit patterns of integers. E.g. 0xF has binary digits 0….01111, n & 0xF yields the lowest four bits in n, n= n | 0xF sets the lowest four bits to 1, and n = n ^ 0xF flips them. The ~ operator flips all the bits of the operand. There are two right shift operators: >>  fills the top bits with zero, and >>> extends the sign bit into the top bits. The right-hand side is reduced to modulo 32 if left hand side is an int, or modulo 64 if it is long. 1 << 35 is same as 1 << 3  (8) . 1 << 32 = 1. The & and | operators when applied to boolean values, force evaluation on both operands before combining the results. This usage is uncommon.
  • If the precision of the primitive integer and floating-point types is not sufficient, you can use BigInteger and BigDecimal classes in the java.math package. Objects of these classes represent numbers with an arbitrarily long sequence of digits.
BigInteger n = BigInteger.valueOf(38374495958560484L);
BigInteger k = new BigInteger(“39484398559384548595”);
BigInteger r = BigInteger.valueOf(5).multiply(n.add(k)); // r = 5 * (n + k)

The call BigDecimal.valueOf(n, e) returns a BigDecimal instance with value n x 10 ^ -e

BigDecimal.valueOf(2, 0).subtract(BigDecimal.valueOf(11,1)) //  is exactly 0.9

Strings

  • To combine several strings, separated with a delimiter, use the join  method: String names = String.join (“, “, “Peter”, “Paul”, “Mary”); // Sets names to “Peter, Paul, Mary”
  • To concatenate large no. of strings use StringBuilder’s append method.
  • “Hello, World!”.substring(7, 12); // “World” – Starts with index 7, doesn’t include index 12
  • String[] result = “Peter, Paul, Mary”.split(“, “); // Array containing [“Peter”, “Paul”, “Mary”]

Can use regular expression with split. E.g. input.split(“\\s+”) splits input at white space.

  • String comparison is done with equals location.equals(“World”).  The == operator may show true if they refer same object in virtual machine (but don’t use == for string comparison)
  • To compare two strings without regard to case use equalsIgnoreCase
  • The compareTo method tells you whether one string comes before another in dictionary order ( -ve if first comes before second, +ve if it comes after second, 0 otherwise). It usually returns difference of character order
  • To convert from int to string you can use Integer.toString(n) or “” + n

A variant of this method has a second parameter, a radix between 2 and 36

str = Integer.toString(n, 2) / Sets str to “101010”  // n = 42
  • To convert a string containing an integer to the number, use the Integer.parseInt method
n = Integer.parseInt(str); // Sets n to 101010
n = Integer.parseInt(str, 2); // Sets n to 42
    • For floating-point numbers, use Double.toString and Double.parseDouble.
  • startsWith(String str), endsWith(String str), contains(CharSequence str) checks whether a string starts with, ends with, or contains a given string
  • indexOf(String str), lastIndexOf(String str), indexOf(String str, int fromIndex), lastIndexOf(String str, int fromIndex) – gets the position of the first or last occurrence of str, searching the entire string or the substring starting at fromIndex. Returns -1 if not match is found
  • replace(CharSequence oldString, CharSequence newString) returns a string that is obtained by replacing all occurrences of oldString with newString.
  • toUpperCase, toLowerCase returns a string consisting of all characters of the original string converted to upper or lowercase.
  • trim returns a string obtained by removing all leading and trailing white space
  • To get the ith Unicode code point, call str.codePoint(str.offsetByCodePoints(0, i)). The total number of code points is str.codePointCount(0, str.length()), to get all code point values str.codePoints().toArray()

Input and Output

import java.util.Scanner;
Scanner in = new Scanner(System.in);
String name = in.nextLine();
String firstName = in.next();
if (in.hasNextInt()) {
   int age = in.nextInt();
}

// Reading password

Console terminal = System.console();
String username = terminal.readLine(“User name: “);
char[] password = terminal.readPassword(“Password: “);

To read input from file and write output to file

java package.MainClass < input.txt > output.txt

Formatted output

System.out.printf(“%8.2f”, 1000.0 / 3.0); // Field width of 8 with 2 digits of precision
// “_ _ 333.33”

Conversion Characters (Use %)

d: decimal, x or X: hexadecimal, o: octal, f: fixed floating-point, e or E: exponent floating point, g or G: general floating point (shorter of f or e), a or A: hexadecimal floating point, s or S : string, c or C: character, b or B: boolean, h or H: hash code, t or T: date and time (obsolete), % : percent symbol, n : platform dependent line separator

Flags for Formatted output

+: positive/negative sign, space: adjusts space between positive numbers, : left justified, 0: leading zeros, ( : Enclosing negative values in parenthesis, ,: group separator, # -> f : always includes decimal point, # -> x or o: adds 0x or 0 prefix, $: index of argument, < : previous format specification

javac -Xlint:fallthrough package/MainClass.java to warn fall through. Can be suppressed by @SuppressWarnings(“fallthrough”).

Arrays
int[] primes = {2, 3, 5, 7, 11, 13} // new array with values
primes = new int[] {17, 19, 23, 29, 31}  // reassign values to primes
BigInteger[] numbers = new BigIntegers[100]  // 100 null references
ArrayList<String> friends; // Variable length array
friends = new ArrayList<>(); // or new ArrayList<String>();
friends.add(“Paul”);
friends.remove(0);
friends.add(0, “Peter”);  // add value before index 0
String friend = friends.get(0);
int[] copiedPrimes = Arrays.copyOf(primes, primes.length);
String[] names = ….;
ArrayList<String> friends = new ArrayList<>(Arrays.asList(names)); // or
ArrayList<String> friends = new ArrayList<>(Arrays.asList("Peter", "Paul", "Mary"));
String[] names = friends.toArray(new String[0]);  

To convert between and int[] and ArrayList<Integer> you can use IntStream

Arrays.fill(numbers, 0);  // int[] array
Collections.fill(friends, ""); // ArrayList<String>

To sort an array or array list

Arrays.sort(names);
Collections.sort(friends);
System.out.println(Arrays.toString(primes));
String elements = friends.toString();   // "[Peter, Paul, Mary]"
Collections.reverse(names);
Collections.shuffle(names);

Pascall Tree

1
1 1
1 2 1
1 3 3 1
1 4 6 4 1

 

int[][] triangle = new int[n][];
for (int i = 0; i < n; i++) {
triangle[i] = new int[i + 1];
triangle[i][0] = 1;
triangle[i][i] = 1;
for (int j = 1; j < i; j++) {
    triangle[i][j] = triangle[i - 1][j - 1] + triangle[i - 1][j];
}

Varargs

public static double average(double… values) {    // values is array of double
double sum = 0;
for (double v : values) sum += v;
return values.length == 0 ? 0 : sum / values.length;
}

Date

import java.text.SimpleDateFormat;
import java.util.*;
SimpleDateFormat sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:m:ss Z");
Calendar calendar = new GregorianCalendar(2017, 0, 10, 04, 24, 02);
int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK);
System.out.println(sdf.format(calendar.getTime()));  // Tue, 10 Jan 2015 04:24:02 -0500
calendar.set(Calendar.DAY_OF_MONTH, 20);
calendar.add(Calendar.YEAR, 1);
calendar.add(Calendar.DAY_OF_MONTH, -5); // subtract

Calendar has YEAR, MONTH, DAY_OF_MONTH, HOUR, MINUTE, SECOND, DAY_OF_WEEK

Java Time

import java.time.*;
import java.time.format.TextStyle;
import java.util.Locale;

LocalDateTime localDateTime = LocalDateTime.now();
LocalDate localDate = localDateTime.toLocalDate();
LocalTime localTime = localDateTime.toLocalTime();
int year = localDateTime.getYear();
Month month = localDateTime.getMonth(); // MARCH
String monthJapan = month.getDisplayName(TextStyle.FULL, Locale.JAPANESE); // 3月
// See https://docs.oracle.com/javase/7/docs/api/java/util/Locale.html
int day = localDateTime.getDayOfMonth();
DayOfWeek dayOfWeek = localDateTime.getDayOfWeek();  // SUNDAY
String dayOfWeek = dayOfWeek.getDisplayName(TextStyle.FULL, Locale.ITALIAN); // domenica

LocalDateTime date2 = localDateTime.withDayOfMonth(15).withYear(2015); 
LocalDate ofEpochDay = LocalDate.ofEpochDay(20);  // 1970-01-21
LocalDateTime addedDateTime = localDateTime.plusYears(2).plusMonths(3).plusDays(12);
LocalDateTime subtractedDateTime = localDateTime.plusYears(-3).plusMinutes(30);

Sources

  1. Core Java for the Impatient – Cay S. Horstmann
  2. Java Date Examples
Advertisements

Leave a comment

Filed under Uncategorized

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s