Fundamentals of Java
Learn commonly used data types and operators in Java.
Data types in Java
Every variable in Java needs to be declared with the help of a data type. For example, whether a variable can store only numbers or can also store other symbols as its value.
Common data types
The following are the commonly used data types in Java:
int
: Integer values (5
,0
,-1
, etc.)char
: Character values (a
,0
,$
, etc.)double
: Floating-point values (2.33333
,-2500.001
,20.0
, etc.)boolean
: Boolean values (true
,false
)String
: String values (educative
,java
,k2
, etc.)
Variable declaration
The Java language requires the programmer to tell the data type of the variables used in a program. The following code demonstrates the declaration of variables to input their values with suitable prompts and to display them with suitable labels:
import java.util.Scanner; class Test { public static void main(String[] args) { Scanner myObj = new Scanner(System.in); String str; // Declaring a variable of type string int number; // Declaring a variable of type integer char alphabet='0'; double real; // Declaring a variable of type double boolean isTrue; // Declaring a variable of type bool System.out.println("Please input a word: "); str = myObj.nextLine(); System.out.println("Please input an alphabet: "); alphabet = myObj.nextLine().charAt(0); System.out.println("Please input an integer: "); number = myObj.nextInt(); System.out.println("Please input a real number: "); real = myObj.nextDouble(); System.out.println("Please input a boolean value true or false: "); isTrue = myObj.nextBoolean(); System.out.println("The value of each variable is enclosed in brackets: "); System.out.println("str (" + str + ")"); System.out.println("number (" + number + ")"); System.out.println("alphabet (" + alphabet + ")"); System.out.println("fraction (" + real + ")"); System.out.println("isTrue (" + isTrue + ")"); } }
Explanation
- Lines 7–11: In these lines, the variables are declared so that they can be used to store values input by the user. There are different types of variables that are declared:
str
is a variable of thestring
type.number
is a variable of theint
type.real
is a variable of thedouble
type.isTrue
is a variable of thebool
type.letter
is a variable of thechar
type.
- Lines 13–26: These lines output a prompt using
System.out.println()
and demand input from the user usingnextLine()
and then store them in the relevant variable. - Lines 28–33: These lines output the variable name as a label and print the value enclosed in a bracket.
The following code demonstrates the declaration of the variables without inputting their values from the user:
class Test{public static void main(String[] args){String str; // Declaring a variable of type stringint number; // Declaring a variable of type integerchar alphabet; // Declaring a variable of type chardouble real; // Declaring a variable of type doubleboolean isTrue; // Declaring a variable of type boolSystem.out.println("The value of each variable is enclosed in brackets: ");System.out.println("str (" + str + ")");System.out.println("number (" + number + ")");System.out.println("alphabet (" + alphabet + ")");System.out.println("fraction (" + real + ")");System.out.println("isTrue (" + isTrue + ")");}}
In the code above, lines 5–9 declare the variables str
, number
, alphabet
, real
, and isTrue
, with the String
, int
, char
, double
, and boolean
data types, respectively. When we execute the code, we see this error “variable might not have been initialized.” This shows that in Java programs, it is essential to assign some value to the variable before using it.
Variable initialization
Storing a value to a variable at the time of its declaration is called initialization. The following code demonstrates the initialization of the variables in Java:
class Test{public static void main(String[] args){int persons = 5; // Defining a variable of type int to store the number of personsdouble totalWeight = 350.6; //Defining a variable of type float to store the total weight of 5 personschar team = 'A'; // Defining a variable of type characterString status = "winner"; //Defining a variable of type str to store the team statusboolean flag = true; // Defining a variable of type booleanSystem.out.println("Total weight of " + persons + " persons of the " + status + " team " + team + " is: " + totalWeight + ", and" +" the value of flag is: " + flag);}}
In the code above, we have initialized all the variables to avoid the garbage values and to ensure that a known value is stored in them.
Operations depend on the data type
The data type also tells which operations are permissible on a specific piece of data and indicates the semantics (or meaning) of those operations. The following code demonstrates the semantics of the +
operation on various data types along with declaring two or more variables in a single statement:
class Test{public static void main(String args[]){int a = 5, b = 7, sum1 = 0; // Defining three variables on a single linesum1 = a + b; // Sum of a and bSystem.out.println("The sum of integers: " + sum1);double e = 3.2, f = 1.5; // Defining two variables on a single linedouble sum2 = e + f; // Sum of e and fSystem.out.println("The sum of doubles: " + sum2);String c = "5", d = "7"; // Defining two strings on a single lineString result = c + d; // Concatenates c and d, to store in resultSystem.out.println("The concatenation of strings: " + result);}}
We can declare multiple variables as a comma-separated list in a single statement, as shown in line 5. Each variable can have a separate initial value.
Operators in Java
Like any other programming language, Java supports several types of operators. We have already seen the assignment operator, =
, that assigns a value to a variable in our programs. The following are various forms of the assignment operator:
class Test{public static void main(String args[]){int a, b;a = b = 5; // Cascaded assignmentSystem.out.println("a = " + a + " \nb = " + b);}}
Explanation
- Line 5: We declare two variables,
a
andb
. - Line 6: We assign
5
to botha
andb
. This assignment syntax is called cascaded or chained assignment. - Line 7: We output a string,
a =
and then print the value stored in variablea
i.e.,5
. We output a stringb =
using\n
so that it printsb
on a new line and then the value stored in variableb
, i.e.,5
.
Commonly used operators
There are several other commonly used operators in Java, including:
-
Arithmetic operators: These are used for arithmetic operations (addition, subtraction, multiplication, etc.).
-
Comparison operators: These are used in conditional expressions (less than, greater than, etc.) .
-
Logical operators: These are used to combine conditional expressions (and, or, not).
-
Compound assignment operators: These are the combinations of arithmetic and assignment operators.
Arithmetic Operators
Operator | Description | Syntax | Results x=7 and y=4 |
+ | Addition: Adds two operands | x + y | 11 |
- | Subtraction: Subtracts two operands | x - y | 3 |
* | Multiplication: Multiplies two operands | x * y | 28 |
/ | Integer division: Divides the first operand by the second and gives an integer quotient because both operands are integers | x / y | 1 |
/ | Non-integer division: This divides the first operand by the second and gives a floating-point quotient. A quotient is a floating-point number when the dividend or the divisor, or both are floating-point numbers. | x / 4.0 | 1.75 |
% | Modulo: Returns the remainder when the first operand is divided by the second | x % y | 3 |
++ | Increment: Updates the variable with the value that is one more than the already stored value | x++ | 8 |
-- | Decrement: Updates the variable with the value that is one less than the already stored value | x-- | 6 |
Comparison Operators
Operator | Description | Syntax | Results x=7 and y=4 |
> | Greater than: True if the left operand is greater than the right | x > y | True |
< | Less than: True if the left operand is less than the right | x < y | False |
== | Equal to: True if both operands are equal | x == y | False |
!= | Not equal to: True if both operands are not equal | x != y | True |
>= | Greater than or equal to: True if the left operand is greater than or equal to the right | x >= y | True |
<= | Less than or equal to: True if the left operand is less than or equal to the right | x <= y | False |
Logical Operators
Operator | Description | Syntax | Results x=7 and y=4 |
&& | Logical AND: True if both the operands are true | x > 4 && y > 4 | False |
|| | Logical OR: True if either of the operands is true | x > 4 || y > 4 | True |
! | Logical NOT: True if the operand is false | ! (x > 4) | False |
Compound Assignment Operators
Operator | Description | Syntax | Results x=7 and y=4 |
+= | Add and assign: Add the right-side operand with the left-side operand and then assign the result to the left operand (x = x + y) | x += y | x = 11 |
-= | Subtract and assign: Subtract the right-side operand from the left-side operand, and then assign the result to the left operand (x = x - y) | x -= y | x = 3 |
*= | Multiply and assign: Multiply the right-side operand with the left-side operand, and then assign the result to the left operand (x = x * y) | x *= y | x = 28 |
/= | Divide and assign: Divide the left operand with the right operand, and then assign it to the left operand (x = x / y) | x /= y | x = 1 |
%= | Modulo and assign: Take modulo after dividing the left operand with the right operand and, then assign the result to the left operand (x = x % y) | x %= y | x = 3 |
Square root and power
There are some operations in mathematics that are difficult to replicate in Java programs by using symbols, for example, calculating the power or the square root of a number. In math, the power of is represented as and the square root is represented as . However, Java enables its users to perform these operations in the following way:
class Test{public static void main(String args[]){double a, b;a = Math.pow(25, 2);b = Math.sqrt(25);System.out.println("a = " + a);System.out.println("b = " + b);}}
Note: We have to add
Math
at line 6–7 to allow the use ofMath
operations,pow()
andsqrt()
.
Explanation:
-
Line 5: We declare two variables of the
double
type. -
Line 6: We performs the
pow()
operation and store as the result ina
. -
Line 7: We performs the
sqrt()
operation and store the square root of as the result inb
. -
Line 8: We output the string,
a =
, and then print the value stored in variablea
, i.e.,625
. -
Line 9: We output the string,
b =
, and then print the value stored in the variableb
, i.e.,5
.
Get hands-on with 1300+ tech skills courses.