JAVA Sample Codes…
Click Here to find sample codes

Operators in java

Operator in java is a symbol that is used to perform operations. For example: +, -, *, / etc.

There are many types of operators in java which are given below:

  • Unary Operator,
  • Arithmetic Operator,
  • Shift Operator,
  • Relational Operator,
  • Bitwise Operator,
  • Logical Operator,
  • Ternary Operator and
  • Assignment Operator.
Operator Type Category Precedence
Unary postfix expr++ expr--
prefix ++expr --expr +expr -expr ~ !
Arithmetic multiplicative * / %
additive + -
Shift shift << >> >>>
Relational comparison < > <= >= instanceof
equality == !=
Bitwise bitwise AND &
bitwise exclusive OR ^
bitwise inclusive OR |
Logical logical AND &&
logical OR ||
Ternary ternary ? :
Assignment assignment = += -= *= /= %= &= ^= |= <<= >>= >>>=

Java Unary Operator

The Java unary operators require only one operand. Unary operators are used to perform various operations i.e.:

  • incrementing/decrementing a value by one
  • negating an expression
  • inverting the value of a boolean

Java Unary Operator Example: ++ and —

class OperatorExample{  
public static void main(String args[]){  
System.out.println(x++);//10 (11)  
System.out.println(++x);//12  
System.out.println(x--);//12 (11)  
System.out.println(--x);//10  
}}

Output

10
12
12
10

Java Unary Operator Example 2: ++ and —

class OperatorExample{ 
public static void main(String args[]){  
int a=10;  
int b=10;  
System.out.println(a++ + ++a);//10+12=22  
System.out.println(b++ + b++);//10+11=21  
}}
 

Output:

22
21

Java Unary Operator Example: ~ and !

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=-10;  
boolean c=true;  
boolean d=false;  
System.out.println(~a);//-11 (minus of total positive value which starts from 0)  
System.out.println(~b);//9 (positive of total minus, positive starts from 0)  
System.out.println(!c);//false (opposite of boolean value)  
System.out.println(!d);//true  
}}

Output:

-11
9
false
true

Java Arithmetic Operators

Java arithmatic operators are used to perform addition, subtraction, multiplication, and division. They act as basic mathematical operations.

Java Arithmetic Operator Example

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
System.out.println(a+b);//15  
System.out.println(a-b);//5  
System.out.println(a*b);//50  
System.out.println(a/b);//2  
System.out.println(a%b);//0  
}}

Output:

15
5
50
2
0

Java Arithmetic Operator Example: Expression

class OperatorExample{  
public static void main(String args[]){  
System.out.println(10*10/5+3-1*4/2);  
}}

Output:

21

Java Left Shift Operator

The Java left shift operator << is used to shift all of the bits in a value to the left side of a specified number of times.

Java Left Shift Operator Example

class OperatorExample{  
public static void main(String args[]){  
System.out.println(10<<2);//10*2^2=10*4=40  
System.out.println(10<<3);//10*2^3=10*8=80  
System.out.println(20<<2);//20*2^2=20*4=80  
System.out.println(15<<4);//15*2^4=15*16=240  
}}

Output:

40
80
80
240

Java Right Shift Operator

The Java right shift operator >> is used to move left operands value to right by the number of bits specified by the right operand.

Java Right Shift Operator Example

class OperatorExample{  
public static void main(String args[]){  
System.out.println(10>>2);//10/2^2=10/4=2  
System.out.println(20>>2);//20/2^2=20/4=5  
System.out.println(20>>3);//20/2^3=20/8=2  
}}

Output:

2
5
2

Java Shift Operator Example: >> vs >>>

class OperatorExample{  
public static void main(String args[]){  
    //For positive number, >> and >>> works same  
    System.out.println(20>>2);  
    System.out.println(20>>>2);  
    //For negative number, >>> changes parity bit (MSB) to 0  
    System.out.println(-20>>2);  
    System.out.println(-20>>>2);  
}}

Output:

5
5
-5
1073741819

Java AND Operator Example: Logical && and Bitwise &

The logical && operator doesn’t check second condition if first condition is false. It checks second condition only if first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false.

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a<b&&a<c);//false && true = false  
System.out.println(a<b&a<c);//false & true = false  
}}

Output:

false
false

Java AND Operator Example: Logical && vs Bitwise &

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a<b&&a++<c);//false && true = false  
System.out.println(a);//10 because second condition is not checked  
System.out.println(a<b&a++<c);//false && true = false  
System.out.println(a);//11 because second condition is checked  
}}

Output:

false
10
false
11

Java OR Operator Example: Logical || and Bitwise |

The logical || operator doesn’t check second condition if first condition is true. It checks second condition only if first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false.

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int c=20;  
System.out.println(a>b||a<c);//true || true = true  
System.out.println(a>b|a<c);//true | true = true  
//|| vs |  
System.out.println(a>b||a++<c);//true || true = true  
System.out.println(a);//10 because second condition is not checked  
System.out.println(a>b|a++<c);//true | true = true  
System.out.println(a);//11 because second condition is checked  
}}

Output:

true
true
true
10
true
11

Java Ternary Operator

Java Ternary operator is used as one liner replacement for if-then-else statement and used a lot in java programming. it is the only conditional operator which takes three operands.

Java Ternary Operator Example

class OperatorExample{  
public static void main(String args[]){  
int a=2;  
int b=5;  
int min=(a<b)?a:b;  
System.out.println(min);  
}}

Output:

2

Another Example:

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=5;  
int min=(a<b)?a:b;  
System.out.println(min);  
}}

Output:

5

Java Assignment Operator

Java assignment operator is one of the most common operator. It is used to assign the value on its right to the operand on its left.

Java Assignment Operator Example

class OperatorExample{  
public static void main(String args[]){  
int a=10;  
int b=20;  
a+=4;//a=a+4 (a=10+4)  
b-=4;//b=b-4 (b=20-4)  
System.out.println(a);  
System.out.println(b);  
}}

Output:

14
16

Java Assignment Operator Example

class OperatorExample{  
public static void main(String[] args){  
int a=10;  
a+=3;//10+3  
System.out.println(a);  
a-=4;//13-4  
System.out.println(a);  
a*=2;//9*2  
System.out.println(a);  
a/=2;//18/2  
System.out.println(a);  
}}

Output:

13
9
18
9

Java Assignment Operator Example: Adding short

class OperatorExample{  
public static void main(String args[]){  
short a=10;  
short b=10;  
//a+=b;//a=a+b internally so fine  
a=a+b;//Compile time error because 10+10=20 now int  
System.out.println(a);  
}}

Output:

Compile time error

After type cast:

class OperatorExample{  
public static void main(String args[]){  
short a=10;  
short b=10;  
a=(short)(a+b);//20 which is int now converted to short  
System.out.println(a);  
}}

Output:

20

Jackson JSON field mapping capitalization?

Send capital letters in json body java

If you really want a capital letter use the @JsonProperty annotation on the setter (or - for serialization - on the getter) like this:

@JsonProperty("Feedback")
public void setFeedback(List<FeedbackDto> Feedback){
this.Feedback = Feedback;
}

Specifying an http proxy with spring-boot

java -Dhttp.proxyHost=10.0.0.0 -Dhttp.proxyPort=8080 -Dhttps.proxyHost=10.0.0.0 -Dhttps.proxyPort=8080 -jar vrm-0.0.1-SNAPSHOT.jar

How to get Current Directory in Linux/Windows

System.getProperty("user.dir")

public class app {
    public static void main(String[] args) {
        System.out.println("Working Directory = " +
                System.getProperty("user.dir"));
    }
}

/*
OUTPUT
Working Directory = C:\Users\learninginz\Projects\App
*/

Binary Tree

/**
 *
 * @author Usman Mughal
 */
public class BinaryTree { 
    static class Node {    
    int value; 
        Node left, right; 
          
        Node(int value){ 
            this.value = value; 
            left = null; 
            right = null; 
        } 
    } 
       
    public void insert(Node node, int value) {
        if (value < node.value) { if (node.left != null) {
			insert(node.left, value); 
			}
		else { 
		System.out.println(" Inserted " + value + " to left of " + node.value);
		node.left = new Node(value); 
		} 
		} 
		else if (value > node.value) {
          if (node.right != null) {
            insert(node.right, value);
          } else {
            System.out.println("  Inserted " + value + " to right of " + node.value);
            node.right = new Node(value);
          }
        }
      }
     public void traverseInOrder(Node node) {
        if (node != null) {
            traverseInOrder(node.left);
            System.out.print(" " + node.value);
            traverseInOrder(node.right);
        }
     }
     
     public static void main(String args[]) 
    { 
    BinaryTree tree = new BinaryTree();
                Node root = new Node(5);
                System.out.println("Binary Tree Example");
                System.out.println("Building tree with root value " + root.value);
                tree.insert(root, 2);
                tree.insert(root, 4);
                tree.insert(root, 8);
                tree.insert(root, 6);
                tree.insert(root, 7);
                tree.insert(root, 3);
                tree.insert(root, 9);
                System.out.println("Traversing tree in order");
                tree.traverseInOrder(root);
                
              }
}

stringManipulations – How to get names matches with given String only
{“cat”, “bt”, “hat”, “tree”}, “atach”

/**
 *
 * @author Usman Mughal
 */
public class stringManipulations {

    public static void main(String args[]) {
        stringManipulations mn = new stringManipulations();

        mn.showCharactersInString(new String[]{"cat", "bt", "hat", "tree"}, "atach");
    }

    public static void countVowels() {
        int count = 0;
        String str = "Usman Mughal";
        String vowels = "aeiou"; // or a set!
        StringBuilder strB = new StringBuilder();

        for (char data : str.toCharArray()) {
            if (vowels.contains(Character.toString(data))) {
                count++;
                strB.append(Character.toString(data));
            }
        }
        System.out.println("Count are : " + count);
        System.out.println("Vowels are : " + strB);
    }

    public static String reverse() {
        String str = "Usman";
        String reversed = "";
        for (int i = str.length() - 1; i >= 0; i--) {
            reversed += str.charAt(i);
        }
        return reversed;
    }

    public static String removeDuplicates() {
        String str = "Usmaan";
        StringBuilder output = new StringBuilder();
        Set<Character> seen = new HashSet<>();
        for (char ch : str.toCharArray()) {
            if (!seen.contains(ch)) {
                seen.add(ch);
            }
            output.append(ch);
        }
        return output.toString();
    }

    public int countCharacters(String[] words, String chars) {

        int[] countArray = new int[26];
        for (char c : chars.toCharArray()) {
            countArray[c - 'a']++;
        }

        int sum = 0;
        int[] array = new int[26];
        char[] ch = null;
        boolean isGood = false;
        for (String word : words) {

            Arrays.fill(array, 0);
            ch = word.toCharArray();
            isGood = true;
            for (int i = 0; i < ch.length; i++) {
                array[ch[i] - 'a']++;
                if (countArray[ch[i] - 'a'] - array[ch[i] - 'a'] < 0) {
                    isGood = false;
                    break;
                }
            }

            if (isGood) {
                sum = sum + word.length();
            }
        }
        return sum;
    }

    public String[] showCharactersInString(String[] words, String chars) {
        //{"cat", "bt", "hat", "tree"}, "atach"
        StringBuilder res = new StringBuilder();
        StringBuilder res1 = new StringBuilder();
        String[] data = new String[6];
        char[] rec = chars.toCharArray();
        for (int i = 0; i < words.length; i++) {

            System.out.println("Result a = " + words[i]);
            char[] ar = words[i].toCharArray();
//            System.out.println("Result aasd = " + res.append(words[i]));

            for (int z = 0; z < ar.length; z++) {

                for (int q = 0; q < rec.length; q++) {

                    if (ar[z] == rec[q]) {
                        res.append(ar[z]);
                        System.out.println("Outttttt = " + res);
                        break;

                    }
                    

                }
                

            }

            System.out.println("res.toString() " + res);
                System.out.println("words[i]  " + words[i]);
                if(!res.toString().equals(words[i])){
                    
                        res = new StringBuilder();
                    }
                
            res1.append(res);
            data[0] = res1.toString();
            System.out.println("finallll aaaaa = " + res1);
        }

        return data;
    }

    public static int[] returnArray() {

        int[] i = {1, 2, 3, 4, 5};
        return i;
    }

    public static String[] returnStringArray() {

        String[] i = {"usman", "mughal"};
        return i;
    }
}

import java.util.Random;

How can you generate random integers between 0 and 9 in Java?
/**
*

  • @author usman
    */
    public class RandomInt { public static void main(String args[]) { Random rand = new Random(); // Generate random integers in range 0 to 9 int rand_int = rand.nextInt(2); System.out.println("Random Integers: " + rand_int); //System.out.print(“The generated random integer between 0 and 9 = “, randomNumber); }

}