Java Home
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}}
Java Syntax
public class Main {
public static void main(String[] args) {
System.out.println("Hello World");
}}
Java Output
( Print Text )
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("It is awesome!");
( Print Numbers )
System.out.println(3);
System.out.println(358);
System.out.println(50000);
Java Comment
// This is a comment
Java Variables
In Java, there are different types of variables.
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
Display Variables
The println() method is often used to display variables. To combine both text and a
variable, use the + character:
Example
String name = "John";
System.out.println("Hello " + name);
You can also use the + character to add a variable to another variable: Example
Example
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
For numeric values, the + character works as a mathematical operator (notice that
we use int (integer) variables here):
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
From the example above, you can expect:
x stores the value 5
y stores the value 6
Then we use the println() method to display the value of x + y,
which is 11
To declare more than one variable of the same type, You can use
a comma-separated list.
Example
Instead of writing:
int x = 5;int y = 6;int z = 50;System.out.println(x + y + z);
You can simply write:
int x = 5, y = 6, z = 50;System.out.println(x + y + z);
You can also assign the same value to multiple variables in one line:
Example
int x, y, z;
x = y = z = 50;System.out.println(x + y + z);
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). Note: It is recommended to use descriptive names in
order to create understandable and maintainable code:
Example
// Goodint minutesPerHour = 60;
// OK, but not so easy to understand what m actually is
int m = 60;
The general rules for naming variables 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 DataTypes
As explained in the previous chapter, a variable in Java must be a specified data
types.
int myNum = 5; // Integer (whole number)
float myFloatNum = 5.99f; // Floating point number
char myLetter = 'D'; // Character
boolean myBool = true; // BooleanString myText = "Hello" //
String
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no
additional methods. There are eight primitive data types in Java.
Data Type Size Description
Byte 1 byte Stores whole numbers from
-128 to 127
Short 2 bytes
Stores whole numbers from
-32,768 to 32,767
Int 4 bytes Stores whole numbers from
2,147,483,648 to
2,147,
483,64
7
Long 8 bytes Stores whole numbers from
-9,223,372,036,854,775,808
to
9,223,372,036,854,775,807
Float 4 bytes
Stores fractional numbers.
Sufficient for
storing 6 to 7 decimal digits
Double 8 bytes Stores fractional numbers.
Sufficient for storing 15
decimal digits
Boolean 1 bit Stores true or false values
Char 2 bytes Stores a single
character/letter or ASCII
values
Byte
byte myNum = 100;
System.out.println(myNum);
Short
short myNum = 5000;
System.out.println(myNum);
Int
int myNum = 100000;
System.out.println(myNum);
Long
long myNum = 15000000000L;
System.out.println(myNum);
Float
float myNum = 5.75f;
System.out.println(myNum);
Double
double myNum = 19.99d;
System.out.println(myNum);
Boolean Types
Very often in programming, you will need a data type that can only have one of two
values, like:
YES / NO ON / OFF TRUE / FALSE
For this, Java has a boolean data type, which can only take the values true or false:
boolean isJavaFun = true;
boolean isFishTasty = false;
System.out.println(isJavaFun); // Outputs
trueSystem.out.println(isFishTasty); // Outputs false
Characters
The char data type is used to store a single character. The character must be
surrounded by single quotes, like 'A' or 'c':
Example
char myGrade = 'B';
System.out.println(myGrade);
Example
char myVar1 = 65, myVar2 = 66, myVar3 =
67;System.out.println(myVar1);System.out.println(myVar2);System.o
ut.println(myVar3);
Strings
The String data type is used to store a sequence of characters (text). String values
must be surrounded by double quotes:
Example
String greeting = "Hello World";
System.out.println(greeting);
Java Type Casting
Type casting is when you assign a value of one primitive data type to another type.
In Java, there are two types of casting:
Widening Casting (automatically) - converting a smaller type to a
larger type size
byte -> short -> char -> int -> long -> float -> double
Narrowing Casting (manually) - converting a larger type to a
smaller size type
double -> float -> long -> int -> char -> short -> byte
Widening Casting
Widening casting is done automatically when passing a smaller size
type to a larger size type:
public class Main {
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
}}
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in
front of the value:
public class Main {
public static void main(String[] args) {
double myDouble = 9.78d;
int myInt = (int) myDouble; // Manual casting: double to int
System.out.println(myDouble); // Outputs 9.78
System.out.println(myInt); // Outputs 9
}}
Java Operators
Operators are used to perform operations on variables and values. In the example
below, we use the + operator to add together two values:
Example
int x = 100 + 50;
Although the + operator is often used to add together two values, like in the example
above, it can also be used to add together a variable and a value, or a variable and
another variable:
Example
int sum1 = 100 + 50; // 150 (100 + 50)
int sum2 = sum1 + 250; // 400 (150 + 250)
int sum3 = sum2 + sum2; // 800 (400 + 400)
Java divides the operators into the following groups:
Arithmetic operators
Assignment operators
Comparison operators
Logical operators
Bitwise operators
Operator Name Description Example
+ Addition Adds together two X+Y
values
Subtraction Subtracts one value X-Y
- from another
* Multiplication Multiplies two X*Y
values
/ Division Divides one value by X/Y
another
% Modulus Returns the division X%Y
remainder
++ Increment Increases the value ++X
of a variable by 1
-- Decrement Decreases the value --X
of a variable by 1
Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
Example
Get your own Java Server 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());
More 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):
Example
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatenation
The + operator can be used between strings to combine them. This is called
concatenation:
Example
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
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:
Example
int x = 10;
int y = 20;
int z = x + y; // z will be 30 (an integer/number)
If you add a number and a string, the result will be a string
concatenation:
Example
String x = "10";
int y = 20;
String z = x + y; // z will be 1020 (a String)