DEV Community

Cover image for A Beginner's Guide to Java Basics
Isah Jacob
Isah Jacob

Posted on

A Beginner's Guide to Java Basics

Java is a popular programming language that is widely used for developing various applications such as web applications, mobile applications, desktop applications, and more. Understanding the basics of Java is essential for anyone who wants to start programming in Java. This article covers the fundamental concepts of Java, including syntax and structure, data types and variables, operators, and control statements.

Java Syntax and Structure

Java is a case-sensitive programming language, which means that uppercase and lowercase letters are treated differently; the same is true of quotation marks. "" is not the same as ''. Java programs are written in plain text files and saved with the .java file extension. 

A Java program starts with a class definition that includes the keyword "class," followed by the name of the class, and the opening and closing curly braces.

public class ClassName{ 
}
Enter fullscreen mode Exit fullscreen mode

The braces { } above indicate the scope of the structure involved, like a class.

If you want your Java file to do something, then you should place a main method inside that class. The main method is where your code is executed.The code below shows you the appropriate syntax for a simple Java program.

The class, as well as the file, is called Classes in Java.

public class ClassName 
{
  //The main method;
  public static void main(String[] args)
{
  //This is a comment, ignored by Java.
  //Place statements here.
 }
}
Enter fullscreen mode Exit fullscreen mode

Print Statement in Java

For you to print out to the console in Java, you will make use of the command below. Inside the main method, you can place two types of print statements.

System.out.print()
Enter fullscreen mode Exit fullscreen mode

Prints a message in the console.

System.out.println()
Enter fullscreen mode Exit fullscreen mode

Prints a message in the console, then ends the line.

After every command, like the one above, you must place a semicolon ; at the end of the line. A semicolon is compulsory in Java. See examples below:

public class PrintingStatements
{   
   public static void main(String[] args)
{      
   System.out.println("I am learning Java");      
   System.out.print("Java is interesting");   
  }
}
Enter fullscreen mode Exit fullscreen mode

Data Types and Variables

In Java, there are eight primitive data types: byte, short, int, long, float, double, char, and boolean. These data types are used to define the type of data that a variable can hold.

A variable is a storage location that holds a value of a specific data type. To declare a variable in Java, you need to specify its data type, followed by its name and an optional value.

It is possible to save information inside a Java program. To do so, you must first tell Java what type of data it contains. The most commonly used data types are:

  • int to store "integers," that is, numbers without decimal digits.
  • double to store numbers with decimal digits.
  • boolean to store true or false values.
  • string to save literal messages.

The syntax to declare a variable is

<data type> <variable name>;
Enter fullscreen mode Exit fullscreen mode
int age;
Enter fullscreen mode Exit fullscreen mode

After being declared,you can set the variable's value:

<variable name> = <variable value>;
Enter fullscreen mode Exit fullscreen mode
age = 36;
Enter fullscreen mode Exit fullscreen mode

You can initialize and declare a variable at the same time:

<data type> <variable name> = <variable value>;
Enter fullscreen mode Exit fullscreen mode
int age = 36;
Enter fullscreen mode Exit fullscreen mode

Let's see a simple Java program:

public class ClassVariable 
{   
   public static void main(String[] args)
{          
   double amount = 3000.00;      
   boolean male;      
   String programmingLanguage;
   int hoursInADay = 24;
   male = true;
   programmingLanguage = "Java";
   
   System.out.println("Hours in a day: " + hoursInADay);     System.out.println("The amount is " + amount);      
   System.out.println("Is Jacob male?: " + male);      
   System.out.print("The programming language we're learning is " + programmingLanguage);   
  }
}
Enter fullscreen mode Exit fullscreen mode
Output:
Hours in a day: 24
The amount is 3000.0
Is Jacob male?: true
The programming language we're learning is Java.
Enter fullscreen mode Exit fullscreen mode

Operators

Operators are used to perform operations on variables and values in Java. Java has several types of operators, including arithmetic, assignment, relational, logical, and bitwise operators.

Arithmetic operators are used to perform basic mathematical operations such as addition, subtraction, multiplication, and division. Example:

 

int a = 7 `+` 3; addition
int b = 7 `-` 3; subtraction
int c = 21 `/` 3; division
int d = 7 `*` 3; multiplication
Enter fullscreen mode Exit fullscreen mode
  • Assignment operators are used to assign values to variables.
  • Relational operators are used to compare two values.
  • Logical operators are used to perform logical operations such as AND, OR, and NOT.
  • Bitwise operators are used to perform operations on the bits of binary numbers. Let's see example:

Assignment operators

int a = 7;
int b = 3;
b += a; // equivalent to b = b + a, b is now 10
Enter fullscreen mode Exit fullscreen mode

In the above code, we've used assignment operator (=) to assign a value to a variable (a = 7, b = 3).

Relational operators

if (a < b) {
  printf("b is less than a");
}
Enter fullscreen mode Exit fullscreen mode

In the above code, we've also used relational operator (<) to compare two values (a < b).

Logical operators

in c = 20
if ((a < b) && (b < c)) {
  printf("b is less than a and b is less than c");
}
Enter fullscreen mode Exit fullscreen mode

we've also used Logical operator (&&) in the above code to combine multiple conditions ((a < b) && (b < c)).

Bitwise operators

unsigned int x = 0x0F; // binary 00001111
unsigned int y = 0xF0; // binary 11110000
unsigned int z = x & y; // binary 00000000
Enter fullscreen mode Exit fullscreen mode

In the above code, we've used the following Bitwise operator (&) to perform bitwise AND operation (x & y).

Control statements (if, while, and loops)

Control statements are used to control the flow of a program in Java. Java has several types of control statements, including if statements, while, and loops.

If Statement

If statements are used to perform different actions based on different conditions,You can select the way a program develops depending on the value of some variable or an input. After an if, there must be a pair of parentheses enclosing a condition that simplifies into a single boolean value. When the code reaches a conditional statement, if the condition is equivalent to true, the block of code enclosed by braces after it will be executed. Let's see example:

if (condition) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode
System.out.print("Enter a number: ");
int num = input.nextInt();
if (num % 2 == 0) 
{
   System.out.println("The number is even.");
} else {
   System.out.println("The number is odd.");
 }
Enter fullscreen mode Exit fullscreen mode

While-loop

A while loop is a control statement used to execute a block of code repeatedly while a certain condition is true. The syntax of a while loop is as follows:

while (condition) {
    // code to be executed
}

Enter fullscreen mode Exit fullscreen mode
int i = 1;
while (i <= 10)
{
  System.out.println(i);
  i++;
}
Enter fullscreen mode Exit fullscreen mode

In the example above, the condition i <= 10 is checked before each iteration of the loop. As long as i is less than or equal to 10, the code inside the loop is executed, which prints the value of i and increments its value by 1. This process continues until i becomes 11, at which point the condition becomes false and the loop terminates.

for Loop

In Java, a for loop is a control statement used to execute a block of code repeatedly for a fixed number of times. The syntax of a for loop is as follows:

for (initialization; condition; update) {
    // code to be executed
}
Enter fullscreen mode Exit fullscreen mode

The initialization part is executed once before the loop starts and is used to initialize the loop counter variable. The condition is a boolean expression that is checked before each iteration of the loop. If the condition is true, the code inside the loop is executed. The update part is executed after each iteration of the loop and is used to update the loop counter variable.

Here's an example of a programme that prints the first 10 positive square numbers:

for (int i = 1; i <= 10; i++) 
{
    int square = i * i;
    System.out.println(square);
}
Enter fullscreen mode Exit fullscreen mode

Do-while Loop

In Java, a do-while loop is a control statement used to execute a block of code at least once and then repeatedly as long as a certain condition is true. The syntax of a do-while loop is as follows:

do {
    // code to be executed
} while (condition);
Enter fullscreen mode Exit fullscreen mode

The code inside the do block is executed once before the condition is checked. If the condition is true, the code inside the do block is executed again. This process continues until the condition becomes false, at each point the loop is terminated and the program continues with the next statement after the loop.

Here's an example of a do-while loop in Java that prompts the user to enter a positive integer and repeats the prompt until a valid input is entered:

int number;
do {
    System.out.print("Enter a positive integer: ");
    number = input.nextInt();
 } 
    while (number <= 0);
    System.out.println("You entered " + number);
   }
}
Enter fullscreen mode Exit fullscreen mode

In this example, the do block prompts the user to enter a positive integer and reads the input from the console.

The while condition checks whether the input is less than or equal to 0. If the input is not valid (i.e., less than or equal to 0), the loop repeats the prompt. This process continues until the user enters a valid input (i.e., a positive integer), at which point the loop terminates and the program continues with the next statement after the loop.

To learn more about Java iterations, you can check my previous article here

Wrapping-Up

Understanding Java basics is essential for anyone who wants to start programming in Java. In this article I have been able to cover the fundamental concepts of Java, including syntax and structure, data types and variables, operators, and control statements. By understanding these concepts, you will be able to write basic Java programs and build a strong foundation for your Java programming skills.

Your feedback is highly appreciated.
you can follow me on twitter and linkedIn

Top comments (0)