Java Programming Fundamentals

  • Overview of Java Variable and Data Types

    • As the name suggests, the word “variable” is made of up two words: “vary” and “able.” This means that the value of variables can change.

    • A Java variable is a memory location that can contain a Value. A variable therefore, has a data type. Data types are broken down into two groups:

      • Primitive data types.

      • Object references/reference variables.

    • A variable takes up a certain amount of space in memory. How much memory a variable takes depends on its data type.

// A variable is a memory location - where we save stuff
// small number:
byte smallNumber;
// A middle sized number:
short alittleBiggerNumber;
// A little bit bigger: int aLittleBitBiggerNumber;
// long number:
long longerNumber;
// Decimal value (floating point numbers):
double decimalNumber;
float smallerDecimalNumber;
// Strings (sequence of characters):
String name;
String address;
String password;
String username;
// What if I just want to save like true/false - yes/no: boolean winOrLose; boolean yesOrNo;
boolean flag = true;
//Single character:
char letterA;
char ampersand;
  • Let’s understand variable by using an example:

    • Problem: We need to compute the area of a circle.

      • The example on the next slide will show us how to compute the area of a circle.

  • Variable Declaration/Memory Allocation

double radius;
double area;
  • Assignment Statement

radius = 20;
  • Computation and Assignment Statement

//Compute area - assigning the values of radius (x 2 ) × 3.14:
area = radius * radius * 3.14159;
  • Output Statement of Variable

//Display results:
System.out.println("The area for the circle of radius " + radius + " is " + area);
//Declaration of our variables 
double radius;
double area;
//Assign a radius:
radius = 20;
//Compute area - assigning the values of radius (x 2 ) × 3.14:
area = radius * radius * 3.14159;
//Display results:
System.out.println("The area for the circle of radius " + radius + " is " + area);
  • Declare Names of Variables (Identifiers)

    • An identifier is needed to name a variable, and an identifier is a sequence of characters that consist of letters, digits, underscores (_), and dollar signs ($).

    • Java imposes the following rules on identifiers:

      • An identifier must start with a letter, underscore (_), or dollar sign ($).

        • Identifiers cannot start with a digit.

    • An identifier cannot be a reserved word.

    • An identifier cannot be the words, true, false, or null.

    • An identifier can be any number of characters in length.

    • Identifiers are case-sensitive. “A rose is NOT a Rose, and is NOT a ROSE."

  • Final Variable (Named Constants) in Java

    • Constants are non-modifiable (immutable) variables, declared with a keyword final.

    • Once we declare a variable with the final keyword, we cannot change the variable’s value. If we attempt to change the value (final keyword), we will get a compilation error.

    • It is used to define constants

      • The syntax is: final datatype CONSTANTNAME = expression;

      • It is a common practice to use ALL_CAPS for named constants

final double PI = 3.14159; 
final int SIZE = 32;
final double RADIUS = SIZE*SIZE*PI; 
  • Java is Statically Typed

    • Java is a Statically Typed language. Every variable used in a Java program has a distinct data type

      • Variables cannot hold values inconsistent with their data type

        • A variable declared as int cannot be assigned a floating-point value.

        • A variable declared as Boolean cannot hold a character value.

        • A variable declared as Scanner cannot be assigned a numeric value.

      • In contrast, many languages, such as Python and Javascript are dynamically typed, which means that any variable can take on any value. These languages are generally interpreted, not compiled.

      • In exchange for the restrictions imposed by static typing, a compiler can make programs run more efficiently and with fewer runtime errors.

    • Java Data Types

      • Java has data types:

        • Primitive data types - includes byte, short, int, long, float, double, boolean, and char

        • Non-primitive data type are also called Object references, Reference variables, and Reference data types (e.g., String, Arrays and Classes)

    • Primitive Data Types

      • A primitive data type variable contains the value of the variable directly in the memory allocated to the variable.

      • Data uses a small fixed amount of memory.

      • Primitive data types are built into the Java language. Java has eight built-in primitive data types.

        • boolean byte char double float int long short

        • Numeric integer types (4): byte, short, int, and long.

        • Floating-point numeric types (2): float and double.

        • Non-numeric types (2): boolean and char.

      • Primitive Data Types - Integer Data Types

        • The simplest numeric types hold a number with no fractional part: integers

        • When we store an integer, we can opt to use one, two, four, or eight bytes

          • The smaller the amount of storage, the smaller the numerical range we can use

        • The standard Java integer data types are

          • Data Type

            Default Value

            Storage Size

            Value Range

            Example

            byte

            0

            1 byte

            (8 bits)

            -128 to 127

            byte b = 10;

            short

            0

            2 bytes

            (16 bits)

            -32,768 to 32,767

            short s = 10;

            int

            0

            4 bytes

            (32 bits)

            -2,147,483,648 to 2,147,483,647

            int i = 10;

            long

            0L

            8 bytes

            (64 bits)

            -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

            long l = 12345678910L;

      • Primitive Data Types - Floating-Point Data Types

        • If we need to perform exact financial calculations, we need to use more advanced data types, such as the BigDecimal class. These are not primitive data types but classes that implement more sophisticated ways of representing and storing numbers

        • Often, we need to represent numbers with a fractional part

        • The term “floating-point” means that a number’s decimal point can occur anywhere within the digits that represent the number. This allows a computer to represent a wide range of values, from the very tiny to the very large

        • Java provides two built-in, floating-point types

          • Data Type

            Default Value

            Storage Size

            Example

            float

            0.0f

            4 bytes

            (32 bit floating point value)

            float f = 1.001f;

            double

            0.0

            8 bytes

            (64 bit floating point value)

            double d = 1.001;

      • Additional Primitive Data Types

        • Java has two additional Primitive data types; both of which are non-numeric: boolean and char

          • boolean type

            • Represents one bit of information.

            • There are only two possible values: true and false.

            • Is used for simple flags that track true/false conditions.

              • Default value is false.

                • Example: boolean flag = true;

          • char type

            • Is a single 16-bit unicode character.

            • Minimum value is '\u0000' (or 0).

            • Maximum value is '\uffff' (or 65,535).

            • Is used to store any character.

              • Example: char letterA = ‘A’;

            • Can often be used in integer arithmetic expressions. This is valid Java:

              • char letterB = letterA + 1;

      • Example - Primitive Data type

        • In this example, you will demonstrate how to declare variables with Primitive Data types

public class datatypedemo {
   public static void main(String[] args) {
       byte num;   // This can hold whole number between -128 and 127.
       num = 113;
       System.out.println(num);


       short snum;
       snum = 150;
       System.out.println(snum);


       long lnum = -12332252626L;
       System.out.println(lnum);


       double dnum = -42937737.9d;
       System.out.println(dnum);


       float fnum = 19.98f;
       System.out.println(fnum);


       boolean b = false;
       System.out.println(b);


       char ch = 'Z';
       System.out.println(ch);
   }
}
  • Non-Primitive Data Types

    • Non-primitive data types are also called Object references, Reference variables, and Reference data types.

      • We can extend the Java type system by defining classes.

      • Once defined, a class can serve as a template for creating objects with capabilities and behaviors that go far beyond the built-in types.

      • While non-primitive types have exact memory requirements, the memory needed for class-based types depends on the class definition.

      • Memory to store objects is allocated in a memory area called the heap. Reference variables reference, or point to this memory location.

    • The new keyword is used to create objects.

    • When objects are created, special methods called constructors run to initialize the object.

    • The default value of any reference variable is null, which means that there is nothing there.

  • Introduction to Java Literal

    • A literal is a number, text, or other information that directly represents a value.

      • A literal is not a value of any type that we read from the console, a file, or any other information source.

    • Literal is a programming term that essentially means that what we type is what we get. The following assignment statement uses a literal:

      • int radius = 20;

    • The literal is 20, because it directly represents the integer value 20.

    • Numbers, characters, and strings can all be represented as literals.

  • Integer Literals

    • An integer (int) literal can be assigned to an integer variable, provided it is within the range of the variable’s type.

      • An integer literal is assumed to be an int, whose value is between -2^31 (-2,147,483,648) to 2^31–1 (2,147,483,647).

        • To denote a long literal, append it with the letter “L.” Lowercase “l” is allowed, but is strongly discouraged because it is easily be confused with “1” (the digit).

  • Floating-Point Literals

    • Floating-Point Literals use a period character (.) for the decimal point. The following statement uses a literal to initialize a double variable:

      • double length = 1.5;

    • All floating-point literals are considered type double.

    • To specify a literal of float, append the letter F (or f) to the literal:

      • float pi = 3.1415927F;

    • Floating point literals can be written using scientific notation.

      • double avogadrosNumber = 6.022e23;

      • double plancksConstant = 6.626e-34;

    • The ‘e’ may be either lower- or upper-case.

  • Character Literals

    • Character (char) literals are enclosed in single quotation mark. Any printable character, except for the backslash (), can be specified this way.

      • char a = ‘A’, nine = ‘9’, plus = ‘+’, tilde = ‘~’;

    • Alternatively, we can specify a char literal as an integer literal. This code is identical to the code above:

      • char a = 0101, nine = 57, plus = 0x2b, tilde = 126;

    • The integer can be specified using either decimal, octal, or hexadecimal forms.

    • The allowed range is 0 to 65535.

  • Character Literals - Escape Sequences

    • A character preceded by a backslash (\) is an escape sequence and has special meaning to the compiler.

    • The table on the right lists the Java escape sequences.

    • Examples:

    • Result

    • Escape Sequence

      Description

      \t

      Tab character.

      \b

      Backspace character.

      \n

      Newline character.

      \r

      Carriage-return character.

      \f

      Form feed character.

      \'

      Single-quote character.

      \''

      Double-quote character.

      \\

      Backslash character.

  • Character Literals - Unicode Characters

    • We can specify char literals in Unicode representation (“\uxxxx”) where xxxx represents four hexadecimal digits.

      • char ch = '\u0061'; // /u0061 represents ‘a’

    • Unicode is not especially useful in console/terminal applications because terminals do not render characters outside of the standard ASCII character set.

    • Unicode characters written into text files and displayed by GUI (Graphical User Interface) applications can take advantage of the full Unicode character set.

  • String Literals

    • A string in Java is an Object, not a Primitive. Any sequence of characters within double quotes is treated as a String literal:

      • String username = “popcorn”;

      • String password = “123456”;

    • String literals are first-class objects. They have access to all of the methods defined by the String class:

      • String username = “pop”.concat(“corn”);

    • String literals are stored in the String Constant pool.

  • Boolean Literals

    • Only two values are allowed for boolean literals: true and false.

      • boolean t = true;

      • boolean f = false;

  • Introduction to Java Scanner Class

    • Scanner Class

      • Reading input From the Console

        • Let’s return to the Scanner Class and look at it in more detail

          • Accepting input from a console, terminal, or file is a common task.

          • Java has various ways to read input from various sources. The Scanner Class is one of them.

            • The Scanner class is used to parse string and primitive types from text input (int, double, etc. and strings, input streams, users, files, etc.).

            • The Scanner Class provides a variety of methods that perform these read operations.

      • To use Scanner Class, include near the top of your Java file: import java.util.Scanner;.

      • Before a Java program can read input from the keyboard, the program must instantiate a Scanner object.

      • The System.in parameter is used to take input from the standard input. It works just like taking inputs from the keyboard.

        • Scanner input = new Scanner(System.in); //System.in represents the keyboard; input is an identifier

        • int radius = input.nextInt(); // Instead of hard-coding a radius

        • Method

          Description

          nextLine()

          Reads an entire line of input as a string and advances to the next line.

          nextByte()

          Reads an integer of the byte type.

          nextShort()

          Reads an integer of the short type/

          nextInt()

          Reads an integer of the int type.

          nextLong()

          Reads an integer of the long type.

          nextDouble()

          Reads a number of the double type.

          nextFloat()

          Reads a number of the float type.

          next()

          next() method reads input up to the whitespace character. Once the whitespace is encountered, it returns the string (excluding the whitespace).

    • Popular Scanner Class Objects in Java

// read input from the input stream
Scanner sc1 = new Scanner(System.in);

// read input from files
Scanner sc2 = new Scanner(new File("myFile"));

// read input from a string
Scanner sc3 = new Scanner(new String("Hello"));
import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    // create an Object of Scanner class
    Scanner input = new Scanner(System.in);
    System.out.print("Enter your name: ");
    // read input(line of text) from the keyboard
    String name = input.nextLine();
    // prints the name
    System.out.println("My name is " + name);
    // closes the scanner
    input.close();
  } 
}
  • Overview of Operators

    • Operators are used to manipulate primitive data types. For example: To calculate an area, we used the expression.

      • area = radius * radius * 3.14159;

    • Here, we are performing successive multiplications, and then assigning the result to a variable.

      • The symbol * is an arithmetic (type: multiplication) operator.

      • The symbol = is an assignment operator.

  • Arithmetic Operators

    • Arithmetic operators are used with numeric values to perform common mathematical operations:

    • Operator

      Description

      Example

      (Assume a,b,v are double)

      + Addition

      Adds values on each side of the operator.

      v = a + b;

      - Subtract

      Subtracts right-hand operand from left-hand operand.

      v = a – b;

      * Multiplication

      Multiplies values on each side of the operator.

      v = a * b

      / Division

      Divides left-hand operand by right-hand operand.

      v = a / b;

      % Modulus

      Divides left-hand operand by right-hand operand and returns the remainder.

      v = b % a;

  • Relational Operators

    • Java has seven relational operators that compare two numbers and return a boolean value.

    • Careful: Do not confuse the assignment operator = with the equality operator ==.

    • Operator

      Description

      Example (assume a=3, b=4, r is boolean)

      ==

      (equal to)

      If the values of two operands are equal, then the condition becomes true.

      r = (a == b); // false

      !=

      (not equal to)

      If values of two operands are not equal, then condition becomes true.

      r = (a != b); // true

      >

      (greater than)

      If the value of left-hand operand is greater than the value of right-hand operand, then condition becomes true.

      r = (a > b); // false

      <

      (less than)

      If the value of the left-hand operand is less than the value of the right-hand operand, then condition becomes true.

      r = (a < b); // true

      >=

      (greater than or equal to)

      If the value of the left-hand operand is greater than or equal to the value of right-hand operand, then condition becomes true.

      r = (a >= b); // false

      <=

      (less than or equal to)

      If the value of the left-hand operand is less than or equal to the value of the right-hand operand, then condition becomes true.

      r = (a <= b); // true

      instanceOf

      Test whether the object is an instance of the specified type (class or subclass or interface).

      class Student{

      public static void main(String args[]){

      Student s = new Student();

      System.out.println(s instanceof Student); //true

      }

      }

int a = 3, b=4;
boolean r;
r = (a == b);
System.out.println(r);
r = (a != b);
System.out.println(r);
r = (a > b);
System.out.printIn(r);
r = (a < b);
System.out.println(r);
r = (a >= b);
System.out.printIn(r);
r = (a <= b);
System.out.printIn(r);
  • Conditional Operators

    • Conditional operators are used to combine conditional statements and return a boolean value. These operators short circuit as described here:

    • Operator

      Description

      Example (a=3, b=4)

      && Logical AND

      The conditional && operator does not check the second condition if the first condition is false. It checks the second condition only if the first one is true.

      System.out.print (a<b && b<a);

      // true && false = false

      System.out.print (a>b && a<b);

      //false && true = false

      || Logical OR

      The conditional || operator does not check the second condition if the first condition is true. It checks second condition only if the first one is false.

      System.out.print (a<b || b<a);

      // true || false = true

      System.out.print (a>b || a<b);

      // false || true = true

System.out.println(a‹b && b<a);
System.out.println(a>b && a<b);
System.out.println(a‹b| b<a);
System.out.println(a>b| a<b);
  • Assignment Operators

    • Assignment operators are used in Java to assign the result of an operation on a variable back to the same variable:

    • Operator

      Example

      Equivalent

      += Addition Assignment

      x += 5

      x = x + 5

      -= Subtraction Assignment

      x -= 5

      x = x - 5

      *= Multiplication Assignment

      x *= 5

      x = x * 5

      /= Division Assignment

      x /= 5

      x = x / 5

      %= Remainder Assignment

      x %= 5

      x = x / 5

      <<= Left Shift Assignment

      x <<= 5

      x = x << 5

      >>= Right Shift Assignment

      x >>= 5

      x = x >> 5

      &= Bitwise AND Assignment

      x &= 5

      x = x & 5

      ^= Bitwise XOR Assignment

      x ^= 5

      x = x ^ 5

      |= Bitwise OR Assignment

      x |= 5

      x = x | 5

  • Unary Operators

    • Unary operators need only one operand. They are used to increment, decrement, or negate a value:

    • Operator

      Description

      Example

      (a = 20, b = 10, c = 0, d = 20, e = 40, f = 30)

      - Unary Minus

      Used for negating the values.

      int result = -a; // result is now -20

      System.out.println(result); //-20

      + Unary Plus

      Used to retain the current sign. This operator has no effect on a value.

      int result = +a; // result is now 20

      System.out.println(result); //20

      ++ Increment Operator

      Used to incrementing a value by 1.

      c = b++;

      System.out.println("Value of c (b++) = " + c);

      //Value of c (b++) = 10

      c = ++a;

      System.out.println("Value of c (++a) = " + c);

      //Value of c (++a) = 21

      Postfix-Increment: Value is first used for computing a result and then incremented.

      Prefix-Increment: Value is incremented first, and then result is computed.

      -- Decrement Operator

      Used for decrementing the value by 1.

      c = e--;

      System.out.println("Value of c (e--) = " + c);

      //Value of c (e--) = 40

      c = --d;

      System.out.println("Value of c (--d) = " + c);

      //Value of c (--d) = 19

      Postfix-Decrement: Value is first used for computing the result and then decremented.

      Prefix-Decrement: Value is decremented first and then result is computed.

      ! Logical Not Operator

      Used for inverting a boolean value.

      boolean condition = true;

      System.out.println("Value of !condition = " + !condition);

      //Value of !condition = false

    • Bitwise and Bit Shift Operators

      • Bitwise and Bit Shift operators work on bits and perform bit-by-bit operations. Unlike the Conditional Operators, both operands are evaluated before an operator is applied.

    • Bitwise and Bit Shift Operators

      • Operator

        Description

        Example (a=3, b=4)

        | Bitwise OR

        Compares corresponding bits of two operands. If either of the bits is 1, it gives 1. If not, it gives 0.

        System.out.println(a|b); //7

        00000011 | 00000100 = 00000111 = 7

        & Bitwise AND

        Compares corresponding bits of two operands. If both bits are 1, it gives 1. If either of the bits is not 1, it gives 0.

        System.out.println(a&b); //7

        00000011 | 00000100 = 00000000 = 0

        ~ Bitwise Complement

        It is an unary operator (works on only one operand); inverts the bit pattern; makes every 0 to 1, and every 1 to 0.

        System.out.println(~b); //-5

        ~00000100 = 11111011 = -5 (Two’s Complement)

        ^ Bitwise XOR

        Compares corresponding bits of two operands. If corresponding bits are different, it gives 1. If corresponding bits are same, it gives 0.

        System.out.println(a^b); //7

        00000011 | 00000100 = 00000111 = 7

      • To convert the decimal number 75 to binary, you can use the division-by-2 method as follows:

        • Divide 75 by 2. The quotient is 37 and the remainder is 1.

        • Divide 37 by 2. The quotient is 18 and the remainder is 1.

        • Divide 18 by 2. The quotient is 9 and the remainder is 0.

        • Divide 9 by 2. The quotient is 4 and the remainder is 1.

        • Divide 4 by 2. The quotient is 2 and the remainder is 0.

        • Divide 2 by 2. The quotient is 1 and the remainder is 0.

        • Divide 1 by 2. The quotient is 0 and the remainder is 1.

        • Therefore, the binary representation of 75 is 1001011

      • To convert the binary number 00000110 to decimal, you can use the positional notation system. Each digit in a binary number represents a power of 2, with the rightmost digit being 2^0 (1), the next digit being 2^1 (2), and so on. To convert the binary number to decimal, you need to multiply each digit by its corresponding power of 2, and then add up the results.

        • For 00000110, the leftmost digit is 0 and represents 0 × 2^7 = 0, the next digit is also 0 and represents 0 × 2^6 = 0, the third digit from the left is 0 and represents 0 × 2^5 = 0, the fourth digit is 0 and represents 0 × 2^4 = 0, the fifth digit is 0 and represents 0 × 2^3 = 0, the sixth digit is 1 and represents 1 × 2^2 = 4, and the rightmost digit is 1 and represents 1 × 2^1 = 2.

        • Therefore, the binary number 00000110 is equal to the decimal number 6

    • The Ternary Operator

      • The Ternary operator is a shorthand version of the if-else statement. It has three operands; hence the name ternary. General format: condition ? exprTrue : exprFalse;

      • The above statement means that if the condition evaluates to true, then execute the expression after the “?,” else, execute the expression after the “:,”

int age = 18;
String result;
if(age < 100){
   result =Less than 100”;
}else {
   result =Greater than 100”;
}
System.out.println(result);
  • Equivalent to

int age = 18;
String result = age < 100 ? 
     "Less than 100" : "Greater than 100";
System.out.println(result); //Less than 100
  • Floating-Point Arithmetic

    • Calculations involving floating-point numbers are approximated because these numbers cannot be stored with perfect precision. For example:

System.out.println(1.0 - 0.1 - 0.1 - 0.1 - 0.1 - 0.1); 
//displays 0.5000000000000001, not 0.5
System.out.println(1.0 - 0.9); 
//displays 0.09999999999999998, not 0.1
  • Integers are stored exactly. Therefore, calculations with integers yield an exact integer result.

  • Operator Precedence and Associativity

    • The expression in the parentheses is evaluated first. Parentheses can be nested; in which case, the expression in the innermost parentheses is executed first.

    • When evaluating an expression without (or within) parentheses, the operators are applied according to the precedence rule and the associativity rule.

    • If operators with the same precedence are next to each other, their associativity determines the order of evaluation. All binary operators, except assignment operators, are left-associative.

  • Example: Operator Precedence and Associativity

    • Applying the operator precedence and associativity rule, the expression

      3 + 4 * 4 > 5 * (4 + 3) - 1 is evaluated as follows.

  • Division and Modulus

    • Integer Division:

      • 5 / 2 yields an integer 2.

    • Floating-point Division:

      • 5.0 / 2 yields an floating-point 2.5.

    • Integer Modulus:

      • 5 % 2 yields 1 (the remainder of the division).

    • Floating-point Modulus:

      • 3.6 % 0.55 yields 0.1 (the remainder of the division).

    • Remainder is very useful in programming. For example, an even number % 2 is always 0 and an odd number % 2 is always 1. So you can use this property to determine whether a number is even or odd. Because odd, negative numbers return a negative remainder, always use the 0 test:

      • boolean isEven = (myValue % 2) == 0;

    • Suppose today is Saturday and you and your friends are going to meet in 10 days. What day is it in 10 days? You can find that the day is Tuesday using the following expression:

    • Write a Java program to convert a total amount of seconds to the hour, minute, and seconds.

      • Example case:

        • Input seconds: 86399

        • Output: 23:59:59

public static void main(String args[]) {
int seconds = 86399;
int p1 = seconds % 60;
int p2 = seconds / 60;
int p3 = p2 % 60;
p2 = p2 / 60;
System.out.print( p2 + ":" + p3 + ":" + p1);
System.out.print("\n");
}
  • Introduction to Type Casting

    • Assigning a value of one type to a variable of another type is known as Type Casting.

    • Here, we discuss four types of Type Casting in Java:

      • Implicit Type Casting, Widening, or Automatic Type Conversion.

      • Explicit Type Casting or Narrowing.

      • Automatic Type Promotion in Expressions.

      • Explicit Type Casting in Expressions.

  • Explicit Type Casting

    • If we want to assign a value of a larger data type with a smaller range, we perform explicit type casting. This kind of conversion is also known as narrowing conversion in Java.

      • The explicit cast operation has syntax: (target-type)value;

      • Let’s review an example to better understand the concept of Java explicit type casting.

int x;
double y = 9.99;
x = (int)y;   // It will compile in Java and the resulting value will simply be 9.
  • Basic Example

public static void main(String args[]) {
   byte i = 40;
   // No casting needed for below conversion
   short j = i;
   int k = j;
   long l = k;
   float m = l;
   double n = m;
   System.out.println("byte value : "+i);
   System.out.println("short value : "+j);
   System.out.println("int value : "+k);
   System.out.println("long value : "+l);
   System.out.println("float value : "+m);
   System.out.println("double value : "+n);
     s =  short(k);  // Not Allowed - narrowing
     c = (char)(k); // Not Allowed - narrowing
   float f = 1.5e3f;
   k = (int)f; // Explicit - ok
   k = f // Not Allowed - narrowing
  • Implicit Type Casting

    • Implicit type casting takes place when two data types are automatically converted by Java compiler internally. This happens when:

      • The two data types are compatible.

      • We assign value of a smaller data type to a bigger data type.

    • It is also called Widening or Automatic Type Conversion.

    • The Java numeric data types are compatible with each other and with char.

    • Boolean is not compatible with any other types.

  • Automatic Type Promotion in Expressions

    • Implicit (automatic) type conversions may occur in arithmetic in expressions.

    • In an expression, the range required of an intermediate value will sometimes exceed the range of either operand.

    • For example, consider the following statements:

    • The result of a * b exceeds the range of byte. To handle this, the compiler automatically promotes each byte, short or char operand to int.

    • a * b is performed using integers.

  • Type-Promotion Rules

    • All byte, short, and char values are promoted.

    • Promotion to int is the default behavior, except:

      • If any operand is a long, the whole expression is promoted to long.

      • If any operand is a float, the entire expression is promoted to float.

      • If any of the operands is double, the result is double.

  • Explicit Type Casting in Expressions

    • Automatic promotions can cause confusing compile-time errors. For example, this seemingly correct code causes a problem:

      • The code is attempting to store 50*2, a perfectly valid byte value, back into a byte variable.

      • However, because the operands were automatically promoted to int when the expression was evaluated, the result has also been promoted to int.

      • The result cannot be assigned to a byte without the use of a cast.

      • This explicit cast solves the problem:

  • Common Errors and Pitfalls in Java Program

    • Undeclared/Uninitialized Variables

      • Attempting to use an undeclared or uninitialized variable is a compiler error:

      • Undeclared Variable

      • Uninitialized Variable

    • Redundant/Unused Variables

      • The first code example asks the compiler to allocate stack space for a redundant variable, y.

      • This is not a critical error because it is neither a compiler error nor a logic error.

      • As your coding skills improve, it is important to develop awareness of even minor errors like this.

  • Knowledge Check

    • What are primitive data types?

    • What are the primitive data types supported by Java programming language?

    • What are Primitive Literals?

    • What is Primitive Casting in Java programming language?

    • What is the default value stored in Local Variables?

    • Why do we use Scanner Class in Java?

    • What is the difference between ++x and x++ under increment operators?

Last updated