Show List

Java syntax, data types, and variables

Java syntax refers to the set of rules that govern how Java code is written and structured. Some examples of Java syntax include:

  1. Statement

    : A statement is a single line of code that performs an action. For example:
 int x = 10;
  1. Expression

    : An expression is a combination of values, variables, and operators that evaluates to a single value. For example:
 int x = 10 + 20;
  1. Control structure

    : Control structures, such as if-else statements, for loops, and while loops, control the flow of execution in a Java program. For example:
if (x > 10) {
   System.out.println("x is greater than 10");
} else {
   System.out.println("x is not greater than 10");
}

Data Types in Java

Java has a number of built-in data types that are used to store values in variables. Some of the most common data types in Java include:

  1. int: An integer data type used to store whole numbers. For example:
int x = 10;
  1. float: A floating-point data type used to store numbers with fractional values. Below is one example. The "f" suffix after the value of 10.5 indicates that it is a float literal, which is necessary because decimal literals are interpreted as doubles by default, and assigning a double to a float variable without an explicit cast can result in a loss of precision.
float y = 10.5f;
  1. double: A double-precision floating-point data type used to store numbers with larger fractional values. For example:
double z = 20.347352467236;
  1. boolean: A boolean data type used to store a true or false value. For example:
boolean flag = true;
  1. char: A character data type used to store a single character. Below is one example. The char keyword specifies that the variable has a character data type, which means it can store a single character. If we use double quotes for the value assignment e.g. "A", it will result in a compile-time error, because it attempts to assign a string literal to a character variable.
char c = 'A';
Variables are used to store values in Java. A variable has a name and a data type, and it must be declared before it can be used in a program. For example:
int x;
x = 10;
In this example, x is a variable of type int and it is assigned a value of 10.

    Leave a Comment


  • captcha text