Java Definition II

Introduction

Java Definitions II

Contents

  1. String in Java
  2. Casting in Java
  3. Convert Data Type in Java
  4. Ternary Operator in Java
  5. Abbreviation Operators in Java

1. String in Java

Strings are a data type in Java, which is not a primitive type. It is actually a Class.

Strings are a sequence of characters. and Strings can contain a sequence of characters.

public class String_Example {
    public static void main(String[] args) {

        String p = "This is unicode U0070: ";
        String unicode = "\u0070";
        System.out.println(p + unicode);
    }
}
This is unicode U0070: p
  • Strings in Java are Immutable
    • You can not change a String after it is created. Instead, what happens is a new String is created.
    • As a result a Sting being created, appending values is inefficient and not recommended.

2. Casting in Java

Casting means to treat or convert a number from one type to another.

(byte) (maxByte /2);

public class Primitive {
    public static void main(String[] args) {

        byte maxByte = Byte.MAX_VALUE;
        byte a = (byte) (maxByte / 2);
        System.out.println(a);
    }
}
63

3. Convert Data Type in Java

Parsing value from a String

public class ConvertDataType {
    public static void main(String[] args) {
        
        String num = "1.4324";
        double realNum = Double.parseDouble(num);
        System.out.println(++realNum);
    }
}
2.4324
  • A String in Java is a nonprimitive data type, because it refers to an object.

4. Ternary Operator in Java

The ternary operator is a shortcut to assigning one of two values to a variable depending on a given condition.

It is a shortcut of the if-then-else statement.

public class Ternary {
    public static void main(String[] args) {

        boolean trueValue = true;

        boolean factCheck_trueValue = trueValue ? true : false;
        
        System.out.println("trueValue is " + factCheck_trueValue);
    }
}
trueValue is true

boolean factCheck_trueValue = trueValue ? true : false;

  • If trueValue is true, factCheck_trueValue define as true.
  • If trueValue is false, factCheck_trueValue define as false.

5. Abbreviation Operators in Java

Abbreviation Operators are shorthand operator in Java.

What is Operators?

Operators are constructs defined within programming languages which behave generally like functions, but which differ syntactically or semantically.

public class Abbreviating {
    public static void main(String[] args) {

        int answer = 0;
        answer++;
        System.out.println(answer);
        answer--;
        System.out.println(answer);
        System.out.println(answer+=3);
        System.out.println(answer*=10);
        System.out.println(answer/=3);
        System.out.println(answer-=3);
        System.out.println(answer%=5);
    }
}
1
0
3
30
10
7
2

Leave a Reply

Your email address will not be published.

ANOTE.DEV