DEV Community

Cover image for Introduction to Java for beginners
rachel
rachel

Posted on • Updated on

Introduction to Java for beginners

Overview

Java is a high level OOP language. It is one of the most popular languages due to its platform independent nature, which is especially important for softwares that are required to work on multiple operating systems. This is because Java code are compiled to bytecode that can be executed on any Java virtual machine(JVM) across different platforms without recompilation.

Java compilation process


Introduction to Java

Your first Java application: Hello World

// This is a comment

/* This is a 
multi-line comment */

/**
 * The HelloWorldApp class implements an application 
 * that prints the string "Hello World!" to the screen.
 */
class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}
Enter fullscreen mode Exit fullscreen mode
  • Every program in Java is enclosed within a class definition. In this case, the class name is HelloWorld and the class definition is class HelloWorld {...}.
  • The main method is the entry point of any Java program where the JVM will begin program execution.
  • Don't worry if you don't understand the meaning of class, public, static for now. It will be discussed in the OOP articles which will be posted in the future.

Java JDK, JRE, JVM
In short, we use the Java Development Kit(JDK) to build Java applications. When you download the JDK, it comes with a compiler, the Java Runtime Environment(JRE). The JRE provides a library of classes and the Java Virtual Machine(JVM) which is used to execute Java bytecode.

Java JDK, JRE, JVM


Java Variables

// Method 1 to declare variables
int num = 7;

// Method 2 to declare variables
int num;
num = 7;

// Assigning a new value
num = 10; // num is now 10

// To make this variable unchangeable, use the 'final' keyword
final int fixedNum = 1;
fixedNum = 2; // Generates an error
Enter fullscreen mode Exit fullscreen mode

Java Data Types
The data type should be specified during a variable declaration. Java data types can be categorised into 2 groups, namely primitive types and reference types.

  • Primitive data types:
Data Type Size(bits) Description
byte 8 Whole numbers from -128 to 127
short 16 Whole numbers from -32,768 to 32,767
int 32 Whole numbers from -231 to 231-1
long 64 Whole numbers from -263 to 263-1
float 32 Fractional numbers with 6-7 decimal digits precision
double 64 Fractional numbers with 15-16 decimal digits precision
boolean. 1 true or false values
char 16 a single Unicode character
  • Reference data types:

Primitive types are basic types that stores values. Non-primitive types, also known as reference types, store the address of dynamically created objects. They provide access to the objects stored in the memory. Say we have a class named Animal and we create an object cat, then the variable cat is considered a reference type. Some examples of reference types are String, Array, class, interface, etc.


Java Type Casting
Type casting is assigning a value of one primitive data type to another primitive data type. In Java, there are 2 types of casting:

  • Widening casting (implicit) - It happens automatically when we try to store a value of smaller size type to a larger size type.
  • Narrowing casting (explicit) - It is done manually when we want to convert a value of larger size type to a smaller size type.
// Example of widening casting: short(2 bytes) to int(4 bytes)
short x = 1; 
int y = x;

// Example of narrowing casting
int x = 1;
short y = (short) x;
Enter fullscreen mode Exit fullscreen mode

Java type casting


Java Input and Output

There are a few ways to display the ouput to the standard output(screen).

Method Description
print() prints string inside the quotes
println() prints string inside the quotes and inserts a new line
printf() print formatted strings according to format specifiers

Java also provides several ways to get user input. The most simple way is to create an object from the Scanner class as follows:

// Import java.util.Scanner package to use the Scanner class
import java.util.Scanner;

// Create an object of Scanner
Scanner input = new Scanner(System.in);

// Take input from the user
int number = input.nextInt();

// Print user input
System.out.println("You entered " + number);
Enter fullscreen mode Exit fullscreen mode

Java Flow Control

  • If-else statements:
if (condition) { 
    // statement
} else if (condition) {
    // statement
} else (condition) {
    // statement
}
Enter fullscreen mode Exit fullscreen mode
  • Ternary operator (shorthand for if-else statements):
// Syntax: (condition) ? Expression 1 : Expression 2

/* Example: If marks is more than 40, assign grade as "Pass", 
otherwise assign it as "Fail" */
String grade = (mark > 40) ? Pass : Fail;
Enter fullscreen mode Exit fullscreen mode
  • Switch statements:
/* Syntax: 
switch (expression) {
  case value1:
    // code
    break;
  case value2:
    // code
    break;
  ...
  default:
    // default statements
}
*/

// Example: 
char size = "M"

switch (size) {
      case "S":
        size = "small";
        break;

      case "M":
        size = "Medium";
        break;

      case "L":
        size = "Large";
        break;

      default:
        size = "Unknown";
        break;
}
Enter fullscreen mode Exit fullscreen mode

break statements are used to "jump out" of switch statements or loops and continue statements skip the current iteration of a loop if the specified condition is true.

  • While loops
// While loop syntax
while (condition) {
    // code block to be executed
}

// Do...while loop syntax
do {
  /* Code here will be executed once before checking if it
     it true or false, then it will repeat the loop as long as
     it satisfies the condition. 
  */
}
while (condition);
Enter fullscreen mode Exit fullscreen mode
  • For loops
// For loop syntax
for (statement 1; statement 2; statement 3) {
  // code block to be executed
}

// Example
int[] numbers = {1, 2, 3, 4};

for (int i = 0; i < numbers.length; i++) {
    System.out.println(numbers[i]);
}

// For...each loop syntax
for (type variableName : arrayName) {
  // code block to be executed
}

// Example
int[] numbers = {1, 2, 3, 4};

for (int number : numbers) {
    System.out.println(number);
}
Enter fullscreen mode Exit fullscreen mode

Java Arrays
Arrays are used to store a list of objects of the same type.

// Declaring an array to store marks
int[] marks;

// Allocate memory 
marks = new int[3]

// We can declare and allocate memory in one line
int[] marks = new int[3];

// Initialise the array
marks = { 75, 80, 90 }
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
lexiebkm profile image
Alexander B.K.

Much effort will be required when learning OOP elements like classes in more detail, like nested classes, inner classes, local classes, and the understanding of using lambda expression.
After having the fundamentals of OOP which includes interface and inheritance as well as annotations and generics, we can jump into Spring Boot to get started on creating a RESTful web backend, or turn to mobile dev that targets on Android platform.
Like you, I am still learning, though. Unfortunately, my time is now allocated more on learning C# and .Net, that I cannot learn Java intensively.

Collapse
 
rachelsarchive profile image
rachel

Thanks for the feedback, I agree that there is much more to learn. This article is aimed to help beginners with little exposure to Java get an overview of the langauge. I am planning to write about OOP concepts in greater detail in the future. Once again, thank you for taking the time to read the article. All the best for your learning journey!