Java - tutorial - 04/13 - operators

revision:


Java - operators

Operators are used to perform operations on variables and values.

the + operator is often used to add together two values, but it can also be used to >add together a variable and a value, or a variable and another variable.

example: "+" operator

      public class Main {
        public static void main(String[] args) {
          int x = 100 + 50;
          System.out.println(x); //150
        }
      }
    
      public class Main {
        public static void main(String[] args) {
          int sum1 = 100 + 50;
          int sum2 = sum1 + 250;
          int sum3 = sum2 + sum2;
          System.out.println(sum1); //150
          System.out.println(sum2); //400
          System.out.println(sum3);  // 800
        }
      }
    

Java divides the operators into the following groups:

arithmetic operators

assignment operators

comparison operators

logical operators

bitwise operators

arithmetic operators are used to perform common mathematical operations.

operator: + ; name: addition; description: adds together two values; example: x + y .

operator: - ; name: subtraction; description: subtracts one value from another ; example: x - y.

operator: * ; name: multiplication; description: multiplies two values; example: x * y .

operator: / ; name: division; description: divides one value by another; example: x / y .

operator: % ; name: modulus; description: returns the division remainder; example: x % y .

operator: ++ ; name: increment; description: increases the value of a variable by 1; example: ++x .

operator: --; name: decrement; description: decreases the value of a variable by 1; example: --x .

assignment operators are used to assign values to variables.

operator: = ; example: x = 5; same as: x = 5 .

operator: += ; example: x += 5; same as: x = x + 5 .

operator: -= ; example: x -= 5; same as: x = x - 5 .

operator: *= ; example: x *= 5; same as: x = x * 5 .

operator: /= ; example: x /= 5; same as: x = x / 5 .

operator: %= ; example: x %= 5; same as: x = x % 5 .

operator: &= ; example: x &= 5; same as: x = x & 5 .

operator: |= ; example: x |= 5; same as: x = x | 5 .

operator: ^= ; example: x ^= 5; same as: x = x ^ 5 .

operator: >>=; example: x >>= 5; same as: x = x >> 5 .

operator: <<= ; example: x <<= 5; same as: x = x << 5 .

example: assigmnent operator (=) assigns a value to a variable

      public class Main {
        public static void main(String[] args) {
          int x = 10;
          System.out.println(x); // 10
        }
      }
    

example: addition assigmnent operator (+=) assigns a value to a variable

      public class Main {
        public static void main(String[] args) {
          int x = 10;
          x += 5;
          System.out.println(x); // 15
        }
      }
    

comparison operators are used to compare two values.

operator: == ; name: equal to; example: x == y .

operator: != ; name: not equal; example: x != y .

operator: > ; name: greater than; example: x > y .

operator: < ; name: less than; example: x < y .

operator: >= ; name: greater than or equal to; example: x >= y .

operator: <= ; name: less than or equal to; example: x <= y .

logical operators are used to determine the logic between variables or values.

operator: && ; name: logical and ; description: returns true if both statements are true; example: x < 5 && x < 10 .

operator: || ; name: logical or ; description: returns true if one of the statements is true; example: x < 5 || x < 4 .

operator: ! ; name: logical not ; description: reverse the result; returns false if the result is true; example : !(x < 5 && x < 10) .


strings

strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes (" ").

example:

      public class Main {
        public static void main(String[] args) {
          String greeting = "Hello";
          System.out.println(greeting); // Hello
        }
      }
    

A String in Java is actually an object, which contain methods that can perform certain operations on strings.

The length of a string can be found with the length() method.

example:

      public class Main {
        public static void main(String[] args) {
          String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
          System.out.println("The length of the txt string is: " + txt.length()); // The length of the txt string is: 26
        }
      }
    

toUpperCase() method and toLowerCase() method.

example:

      public class Main {
        public static void main(String[] args) {
          String txt = "Hello World";
          System.out.println(txt.toUpperCase()); // HELLO WORLD
          System.out.println(txt.toLowerCase()); // hello world
        }
      }
    

the indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace).

example:

      public class Main {
        public static void main(String[] args) {
          String txt = "Please locate where 'locate' occurs!";
          System.out.println(txt.indexOf("locate")); // 7
        }
      }
    

String concatenation is done by using the + operator between strings to combine them. You can also use the concat() method to concatenate two strings.

example:

      public class Main {
        public static void main(String args[]) {
          String firstName = "Eric";
          String lastName = "Walbers";
          System.out.println(firstName + " " + lastName); //Eric Walbers
        }
      }
    

example:

      public class Main {
        public static void main(String args[]) {
          String firstName = "Eric";
          String lastName = "Walbers";
          System.out.println(firstName.concat(lastName)); //Eric Walbers
        }
      }
    

special characters - backslash escape characters: the backslash (\) escape character turns special characters into string characters:

escape character \' ; result: '; description: single quote.

escape character \" ; result: "; description: double quote.

escape character \\ ; result: \; description: backslash.

The sequence \" inserts a double quote in a string; the sequence \' inserts a single quote in a string; the sequence \\ inserts a single backslash in a string.

other escape sequences:

code: \n ; result: new line.

code: \r ; result: carriage return.

code: \t ; result: tab.

code: \b ; result: backspace.

code: \f ; result: form feed.

adding numbers and strings: the + operator

If you add two numbers, the result will be a number.
If you add two strings, the result will be a string concatenation.
If you add a number and a string, the result will be a string concatenation.


booleans

Java has a boolean data type, which can take the values true or false.

A boolean type is declared with the boolean keyword and can only take the values true or false.

example:

      public class Main {
        public static void main(String[] args) {
          boolean isJavaFun = true;
          boolean isFishTasty = false;    
          System.out.println(isJavaFun); // true
          System.out.println(isFishTasty); // false
        }
      }
   

A Boolean expression is a Java expression that returns a Boolean value: true or false. You can use a comparison operator, such as the greater than (>) operator to find out if an expression (or a variable) is true:

example:

      public class Main {
        public static void main(String[] args) {
          int x = 10;
          int y = 9;
          System.out.println(x > y); // returns true, because 10 is higher than 9  
        }
      }
   

The >equal to (==) operator an also be used to evaluate an expression.

example:

      public class Main {
        public static void main(String[] args) {
          System.out.println(15 == 10); // returns false, because 10 is not equal to 15
        }
      }
   

All String methods

Method Description Return Type
charAt(): Returns the character at the specified index (position); return type: char
codePointAt(): Returns the Unicode of the character at the specified index; return type: int
codePointBefore(): Returns the Unicode of the character before the specified index; return type: int
codePointCount(): Returns the number of Unicode values found in a string.; return type: int
compareTo(): Compares two strings lexicographically; return type: int
compareToIgnoreCase(): Compares two strings lexicographically, ignoring case differences; return type: int
concat(): Appends a string to the end of another string; return type: String
contains(): Checks whether a string contains a sequence of characters; return type: boolean
contentEquals(): Checks whether a string contains the exact same sequence of characters of the specified CharSequence or StringBuffer; return type: boolean
copyValueOf(): Returns a String that represents the characters of the character array; return type: String
endsWith(): Checks whether a string ends with the specified character(s); return type: boolean
equals(): Compares two strings. Returns true if the strings are equal, and false if not; return type: boolean
equalsIgnoreCase(): Compares two strings, ignoring case considerations; return type: boolean
format(): Returns a formatted string using the specified locale, format string, and arguments; return type: String
getBytes(): Encodes this String into a sequence of bytes using the named charset, storing the result into a new byte array; return type: byte[]
getChars(): Copies characters from a string to an array of chars; return type: void
hashCode(): Returns the hash code of a string; return type: int
indexOf(): Returns the position of the first found occurrence of specified characters in a string; return type: int
intern(): Returns the canonical representation for the string object; return type: String
isEmpty(): Checks whether a string is empty or not; return type: boolean
lastIndexOf(): Returns the position of the last found occurrence of specified characters in a string; return type: int
length(): Returns the length of a specified string; return type: int
matches(): Searches a string for a match against a regular expression, and returns the matches; return type: boolean
offsetByCodePoints(): Returns the index within this String that is offset from the given index by codePointOffset code points; return type: int
regionMatches(): Tests if two string regions are equal; return type: boolean
replace(): Searches a string for a specified value, and returns a new string where the specified values are replaced; return type: String
replaceFirst(): Replaces the first occurrence of a substring that matches the given regular expression with the given replacement; return type: String
replaceAll(): Replaces each substring of this string that matches the given regular expression with the given replacement; return type: String
split(): Splits a string into an array of substrings; return type: String[]
startsWith(): Checks whether a string starts with specified characters; return type: boolean
subSequence(): Returns a new character sequence that is a subsequence of this sequence; return type: CharSequence
substring(): Returns a new string which is the substring of a specified string; return type: String
toCharArray(): Converts this string to a new character array; return type: char[]
toLowerCase(): Converts a string to lower case letters; return type: String
toString(): Returns the value of a String object; return type: String
toUpperCase(): Converts a string to upper case letters; return type: String
trim(): Removes whitespace from both ends of a string; return type: String
valueOf(): Returns the string representation of the specified value; return type: String