Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Java Basics

Java is a popular programming language created in 1995. It is used to build mobile apps, desktop apps, web apps, games and more. Java code can run on many platforms due to its write once, run anywhere ability. It has a large community and is useful for both simple and complex applications.

Uploaded by

Amir Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Java Basics

Java is a popular programming language created in 1995. It is used to build mobile apps, desktop apps, web apps, games and more. Java code can run on many platforms due to its write once, run anywhere ability. It has a large community and is useful for both simple and complex applications.

Uploaded by

Amir Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 25

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.

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!

Why Use Java?


 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi,
etc.)
 It is one of the most popular programming language in the world
 It is easy to learn and simple to use
 It is open-source and free
 It is secure, fast and powerful
 It has a huge community support (tens of millions of developers)
 Java is an object oriented language which gives a clear structure to
programs and allows code to be reused, lowering development costs
 As Java is close to C++ and C#, it makes it easy for programmers to
switch to Java or vice versa.
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:

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:

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:

Syntax
Type variable = 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:

Example
Create a variable called name of type String and assign it the value "John":

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

Example
Create a variable called myNum of type int and assign it the value 15:
Java Data Types
As explained above, a variable in Java must be a specified data type:

Example

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

Java divides the operators into the following groups:

 Arithmetic operators
 Assignment operators
 Comparison operators
 Logical operators
 Bitwise operators
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

Java Assignment Operators


Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example

A list of assignment operators:


Java Comparison Operators
Comparison operators are used to compare two values:

Java Logical Operators


Logical operators are used to determine the logic between variables or values:
Java Conditions and If Statements
Java supports the usual logical conditions from mathematics:

 Less than: a < b


 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b
 Equal to a == b
 Not Equal to: a != b

You can use these conditions to perform different actions for different decisions.

Java has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition is


true
 Use else to specify a block of code to be executed, if the same condition
is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

The if Statement
Use the if statement to specify a block of Java code to be executed if a
condition is true.

Syntax

Note that if is in lowercase letters. Uppercase letters (If or IF) will generate an
error.

In the example below, we test two values to find out if 20 is greater than 18. If
the condition is true, print some text:
Example

We can also test variables:

Example

Example explained

In the example above we use two variables, x and y, to test whether x is


greater than y (using the > operator). As x is 20, and y is 18, and we know that
20 is greater than 18, we print to the screen that "x is greater than y".

The else Statement


Use the else statement to specify a block of code to be executed if the
condition is false.

Syntax
Example

Example explained

In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".

The else if Statement


Use the else if statement to specify a new condition if the first condition
is false.

Syntax

Example
Example explained

In the example above, time (22) is greater than 10, so the first
condition is false. The next condition, in the else if statement, is also false, so
we move on to the else condition since condition1 and condition2 is
both false - and print to the screen "Good evening".

However, if the time was 14, our program would print "Good day."

Java Switch Statements


Use the switch statement to select one of many code blocks to be executed.

Syntax

This is how it works:

 The switch expression is evaluated once.


 The value of the expression is compared with the values of each case.
 If there is a match, the associated block of code is executed.
 The break and default keywords are optional, and will be described later in
this chapter

The example below uses the weekday number to calculate the weekday name:
Example

The break Keyword


When Java reaches a break keyword, it breaks out of the switch block.

This will stop the execution of more code and case testing inside the block.

When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
The default Keyword
The default keyword specifies some code to run if there is no case match:

Loops
Loops can execute a block of code as long as a specified condition is reached.

Loops are handy because they save time, reduce errors, and they make code
more readable.

Java While Loop


The while loop loops through a block of code as long as a specified condition
is true:

Syntax
In the example below, the code in the loop will run, over and over again, as
long as a variable (i) is less than 5:

Example

Note: Do not forget to increase the variable used in the condition, otherwise
the loop will never end!

The Do/While Loop


The do/while loop is a variant of the while loop. This loop will execute the code
block once, before checking if the condition is true, then it will repeat the loop
as long as the condition is true.

Syntax

The example below uses a do/while loop. The loop will always be executed at
least once, even if the condition is false, because the code block is executed
before the condition is tested:

Example
Do not forget to increase the variable used in the condition, otherwise the loop
will never end!

Java For Loop


When you know exactly how many times you want to loop through a block of
code, use the for loop instead of a while loop:

Syntax

Statement 1 is executed (one time) before the execution of the code block.

Statement 2 defines the condition for executing the code block.

Statement 3 is executed (every time) after the code block has been executed.

The example below will print the numbers 0 to 4:

Example

Example explained

Statement 1 sets a variable before the loop starts (int i = 0).

Statement 2 defines the condition for the loop to run (i must be less than 5). If
the condition is true, the loop will start over again, if it is false, the loop will
end.

Statement 3 increases a value (i++) each time the code block in the loop has
been executed.
Java Break
You have already seen the break statement used in an earlier chapter of this
tutorial. It was used to "jump out" of a switch statement.

The break statement can also be used to jump out of a loop.

This example jumps out of the loop when i is equal to 4:

Example

Java Continue
The continue statement breaks one iteration (in the loop), if a specified
condition occurs, and continues with the next iteration in the loop.

This example skips the value of 4:

Example

Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.

To declare an array, define the variable type with square brackets:

We have now declared a variable that holds an array of strings. To insert values
to it, we can use an array literal - place the values in a comma-separated list,
inside curly braces:

To create an array of integers, you could write:

Access the Elements of an Array


You access an array element by referring to the index number.

This statement accesses the value of the first element in cars:

Example

Array Length
To find out how many elements an array has, use the length property:
Example

Loop Through an Array


You can loop through the array elements with the for loop, and use
the length property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

Example

Multidimensional Arrays
A multidimensional array is an array containing one or more arrays.

To create a two-dimensional array, add each array within its own set of curly
braces:

Example

myNumbers is now an array with two arrays as its elements.

To access the elements of the myNumbers array, specify two indexes: one for
the array, and one for the element inside that array. This example accesses the
third element (2) in the second array (1) of myNumbers:
Example

We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):

Example

We can also use a for loop inside another for loop to get the elements of a two-
dimensional array (we still have to point to the two indexes):

Example
What is OOP?
OOP stands for Object-Oriented Programming.

Procedural programming is about writing procedures or methods that perform


operations on the data, while object-oriented programming is about creating
objects that contain both data and methods.

Object-oriented programming has several advantages over procedural


programming:

 OOP is faster and easier to execute


 OOP provides a clear structure for the programs
 OOP helps to keep the Java code DRY "Don't Repeat Yourself", and makes
the code easier to maintain, modify and debug
 OOP makes it possible to create full reusable applications with less code
and shorter development time

Java - What are Classes and Objects?


Classes and objects are the two main aspects of object-oriented programming.

Look at the following illustration to see the difference between class and
objects:
Another example:

So, a class is a template for objects, and an object is an instance of a class.

When the individual objects are created, they inherit all the variables and
methods from the class.

Create a Class
To create a class, use the keyword class:

Create an Object
In Java, an object is created from a class. We have already created the class
named MyClass, so now we can use this to create objects.
To create an object of MyClass, specify the class name, followed by the object
name, and use the keyword new:

Multiple Objects
You can create multiple objects of one class:
Java Methods
A method is a block of code which only runs when it is called.

You can pass data, known as parameters, into a method.

Methods are used to perform certain actions, and they are also known
as functions.

Why use methods? To reuse code: define the code once, and use it many
times.

Create a Method
A method must be declared within a class. It is defined with the name of the
method, followed by parentheses (). Java provides some pre-defined methods,
such as System.out.println(), but you can also create your own methods to
perform certain actions:

Example
Create a method inside Main:

Example Explained

 myMethod() is the name of the method


 static means that the method belongs to the Main class and not an
object of the Main class. You will learn more about objects and how to
access methods through objects later in this tutorial.
 void means that this method does not have a return value. You will learn
more about return values later in this chapter
Call a Method
To call a method in Java, write the method's name followed by two
parentheses () and a semicolon;

In the following example, myMethod() is used to print a text (the action), when it
is called:

Example
Inside main, call the myMethod() method:

A method can also be called multiple times:

Example
Parameters and Arguments
Information can be passed to methods as parameter. Parameters act as
variables inside the method.

Parameters are specified after the method name, inside the parentheses. You
can add as many parameters as you want, just separate them with a comma.

The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is
used inside the method to print the full name:

Example

When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are arguments.

Multiple Parameters
You can have as many parameters as you like:
Note that when you are working with multiple parameters, the method call must
have the same number of arguments as there are parameters, and the
arguments must be passed in the same order.

Return Values
The void keyword, used in the examples above, indicates that the method
should not return a value. If you want the method to return a value, you can
use a primitive data type (such as int, char, etc.) instead of void, and use
the return keyword inside the method:

Example

You can also store the result in a variable (recommended, as it is easier to read
and maintain):

Example

You might also like