Java Introduction, Java Installation, Java Syntax, Java Variables, Java data types, Java Comments, Java Operators, Java Strings

Java is a programming language introduced by Sun micro systems.

Java is used to develop mobile apps, web apps, desktop apps, games and much more.

What is Java?

Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

Initial name of Java is Oak.

The main success is platform independency is respective operating system, a Java program will be executed without trivial modifications.

It is used for:

  • Mobile applications (specially Android apps)
  • Desktop applications
  • Web applications
  • Web servers and application servers
  • Games
  • Database connection
  • And much, much more!

Java Install

Some PCs might have Java already installed.

To check if you have Java installed on a Windows PC, search in the start bar for Java or type the following in Command Prompt (cmd.exe):

C:\Users\Your Name>java -version

If Java is installed, you will see something like this (depending on version):

java version "1.8.0_261"
Java(TM) SE Runtime Environment (build 1.8.0_261-b12)
Java HotSpot(TM) 64-Bit Server VM (build 25.261-b12, mixed mode)

If you do not have Java installed on your computer, you can download it for free at oracle.com.

Setup for Windows

To install Java on Windows:

  1. Go to “System Properties” (Can be found on Control Panel > System and Security > System > Advanced System Settings)
  2. Click on the “Environment variables” button under the “Advanced” tab
  3. Then, select the “Path” variable in System variables and click on the “Edit” button
  4. Click on the “New” button and add the path where Java is installed, followed by \bin. By default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when you installed it). In that case, You will have to add a new path with: C:\Program Files\Java\jdk-11.0.1\bin
    Then, click “OK”, and save the settings
  5. At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on your machine

Show how to install Java step-by-step with images »Step 2 »Step 3 »Step 4 »Step 5 »

Structure of Java Program

[Package Section]
<import section>
public class <Classname>{
public static void main(string[] args){
Local variable
//body of main
}
[other method definations]
}
[other class definations]

Usage of Java:

In Java, every application begins with a class name, and that class must match the filename.

Let’s create our first Java file, called MyClass.java, which can be done in any text editor (like Notepad).

The file should contain a “Hello World” message, which is written with the following code:

MyClass.java

public class MyClass {
public static void main(String[] args) {
System.out.println("Hello World");
}
}

Save the code in Notepad as “MyClass.java”. Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type

C:\Users\Your Name>javac MyClass.java

This will compile your code. If there are no errors in the code, the command prompt will take you to the next line. Now, type “java MyClass” to run the file:

C:\Users\Your Name>java MyClass

The output should read:

Hello World

Java Syntax

Explanation of Myclass.java

Every line of code that runs in Java must be inside a class. In our example, we named the class MyClass. A class should always start with an uppercase first letter.

Note: Java is case-sensitive: “MyClass” and “myclass” has different meaning.

The name of the java file must match the class name. When saving the file, save it using the class name and add “.java” to the end of the filename. To run the example above on your computer, make sure that Java is properly installed.

The main Method

The main() method is required and you will see it in every Java program:

public static void main(String[] args)

Any code inside the main() method will be executed.

System.out.println()

Inside the main() method, we can use the println() method to print a line of text to the screen.

Java Comments

Comments can be used to explain Java code, and to make it more readable. It can also be used to prevent execution when testing alternative code.

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by Java (will not be executed).

This example uses a single-line comment before a line of code:

// This is a comment
System.out.println("Hello World");

This example uses a single-line comment at the end of a line of code:

System.out.println("Hello World"); // This is a comment

Java Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the code:

/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");

Java Variables

Variables are containers for storing data values.

In Java, there are different types of variables, for example:

  • String - stores text, such as "Hello". String values are surrounded by double quotes
  • int - stores integers (whole numbers), without decimals, such as 123 or -123
  • float - stores floating point numbers, with decimals, such as 19.99 or -19.99
  • char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
  • boolean - stores values with two states: true or false

Declaring (Creating) Variables

To create a variable, you must specify the type and assign it a value:

Where type is one of Java’s types (such as int or String), and variable is the name of the variable (such as x or name). The equal sign is used to assign values to the variable.

To create a variable that should store text, look at the following example:

//Create a variable called name of type String and assign it the //value "John":String name = "John";
System.out.println(name);
//To create a variable that should store a numberint myNum = 15;
System.out.println(myNum);
//Change the value of myNum from 15 to 20:
int myNum = 15;
myNum = 20; // myNum is now 20
System.out.println(myNum);

Final Variables

However, you can add the final keyword if you don't want others (or yourself) to overwrite existing values (this will declare the variable as "final" or "constant", which means unchangeable and read-only):

final int myNum = 15;
myNum = 20;//Generates an error: cannot assign a value to a final variable

Display Variables

The println() method is often used to display variables.

To combine both text and a variable, use the + character:

String name = "John";
System.out.println("Hello " + name);
//can also use the + character to add a variable to another //variable:
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
//For numeric values, the + character works as a mathematical operator
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y

Java Identifiers

All Java variables must be identified with unique names.

These unique names are called identifiers.

Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).

// Good
int minutesPerHour = 60;

// OK, but not so easy to understand what m actually is
int m = 60;

The general rules for constructing names for variables (unique identifiers) are:

  • Names can contain letters, digits, underscores, and dollar signs
  • Names must begin with a letter
  • Names should start with a lowercase letter and it cannot contain whitespace
  • Names can also begin with $ and _ (but we will not use it in this tutorial)
  • Names are case sensitive (“myVar” and “myvar” are different variables)
  • Reserved words (like Java keywords, such as int or boolean) cannot be used as names

Java Data Types

As already discussed, we need to define a variable using data type.

int myNum = 5;               // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // Boolean
String myText = "Hello"; // String

Data types are divided into two groups:

  • Primitive data types — includes byte, short, int, long, float, double, boolean and char
  • Non-primitive data types — such as strings,arrays,classes.

Java Type Casting

Type cating can be both

  • Automatic
  • Manual

Automatically can be done as shown below,

public class MyClass {
public static void main(String[] args) {
int myInt = 9;
double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt); // Outputs 9
System.out.println(myDouble); // Outputs 9.0
}
}

Manually is done as shown below,

public class MyClass {
public static void main(String[] args) {
double myDouble = 9.78;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}
}

Java Buzzwords

  1. Simple and Secured.
  2. Robust is about regarding errors.
  3. Architecture is neutral.
  4. Strongly typed.
  5. Interpreted — There is no executable file for java. Java consists both compiler and interpreter.
  6. Dynamic
  7. Average Multithreaded — Belongs to OS.
  8. Object Oriented
  9. High Performance
  10. Distributed.

Java Operators

Operators are used to perform operations on variables and values. Java divides the operators into the following groups:

  • Arithmetic operators
  • Assignment operators
  • Comparison operators
  • Logical operators
  • Bitwise operators

Arithmetic operators:

Assignment Operators:

Comparison Operators:

Logical Operators:

Bitwise Operators:

Java Strings

Strings are used for storing text. A string variable contains a collection of characters surrounded by double quotes:

Create a variable of type String and assign it a value:

String greeting = "Hello";

String Length

A String in Java is actually an object, which contain methods that can perform certain operations on strings. For example, the length of a string can be found with the length() method:

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());

String Methods

There are many string methods available, for example toUpperCase() and toLowerCase():

String txt = "Hello World";
System.out.println(txt.toUpperCase()); // Outputs "HELLO WORLD"
System.out.println(txt.toLowerCase()); // Outputs "hello world"

Finding a Character in a String

The indexOf() method returns the index (the position) of the first occurrence of a specified text in a string (including whitespace):

String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7

Java counts positions from zero.
0 is the first position in a string, 1 is the second, 2 is the third …

String Concatenation

The + operator can be used between strings to combine them. This is called concatenation:

String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);

Note that we have added an empty text (“ “) to create a space between firstName and lastName on print. You can also use the concat() method to concatenate two strings:

String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));

Special Characters

Because strings must be written within quotes, Java will misunderstand this string, and generate an error:

String txt = "We are the so-called "Vikings" from the north.";

The solution to avoid this problem, is to use the backslash escape character.

The backslash (\) escape character turns special characters into string characters:

The sequence \" inserts a double quote in a string:

String txt = "We are the so-called \"Vikings\" from the north.";

The sequence \' inserts a single quote in a string:

String txt = "It\'s alright.";

The sequence \\ inserts a single backslash in a string:

String txt = "The character \\ is called backslash.";

Adding Numbers and Strings

WARNING!

Java uses the + operator for both addition and concatenation.

Numbers are added. Strings are concatenated.

If you add two numbers, the result will be a number:

int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)

If you add two strings, the result will be a string concatenation:

String x = "10";
String y = "20";
String z = x + y; // z will be 1020 (a String)

If you add a number and a string, the result will be a string concatenation:

String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)

--

--