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.
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
Assignment Statement
Computation and Assignment Statement
Output Statement of Variable
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
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
, andchar
Non-primitive data type are also called Object references, Reference variables, and Reference data types (e.g.,
String
,Arrays
andClasses
)
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
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
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
}
}
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
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 “:,”
Equivalent to
Floating-Point Arithmetic
Calculations involving floating-point numbers are approximated because these numbers cannot be stored with perfect precision. For example:
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
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.
Basic Example
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