Java Programming Language Notes Set 1
Java Programming Language Notes Set 1
Course Description/Outline
In-depth study of Java. Development of large efficient and reusable systems: encapsulation,
templates, references, constructors and distructors, operator overloading, memory management,
exception handling , std templates, library, programming by contracts, configuration management,
documentation and testing.
What is Java?
Java is a popular programming language, created in 1995.
It is used for:
example
1
public class Main {
System.out.println("Hello World");
System.out.println()
Inside the main() method, we can use the println() method to print a line of text
to the screen:
• System.out.println("Hello World");
Java Variables
Variables are containers for storing data values.
• 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:
• String name = "John";
• System.out.println(name);
3
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):
nt myNum = 5;
Display Variables
The println() method is often used to display variables.
Java Identifiers
All Java variables must be identified with unique names.
4
Identifiers can be short names (like x and y) or more descriptive names (age,
sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
5
Numbers
Primitive number types are divided into two groups:
Floating point types represents numbers with a fractional part, containing one
or more decimals. There are two types: float and double.
Int
The int data type can store whole numbers from -2147483648 to
2147483647. In general, and in our tutorial, the int data type is the preferred
data type when we create variables with a numeric value.
Long
The long data type can store whole numbers from -9223372036854775808 to
9223372036854775807. This is used when int is not large enough to store the
value. Note that you should end the value with an "L":
Float
The float data type can store fractional numbers from 3.4e−038 to 3.4e+038.
Note that you should end the value with an "f":
System.out.println(myNum);
6
Booleans
A boolean data type is declared with the boolean keyword and can only take the
values true or 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':
System.out.println(myGrade);
Strings
The String data type is used to store a sequence of characters (text). String
values must be surrounded by double quotes:
System.out.println(greeting);
The main difference between primitive and non-primitive data types are:
7
• Non-primitive types can be used to call methods to perform certain
operations, while primitive types cannot.
• A primitive type has always a value, while non-primitive types can
be null.
• A primitive type starts with a lowercase letter, while non-primitive types
starts with an uppercase letter.
• The size of a primitive type depends on the data type, while non-primitive
types have all the same size.
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Double
The double data type can store fractional numbers from 1.7e−308 to 1.7e+308.
Note that you should end the value with a "d":
System.out.println(myNum);
8
9
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:
10
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):
System.out.println(txt.indexOf("locate")); // Outputs 7
String Concatenation
The + operator can be used between strings to combine them. This is
called concatenation:
You can also use the concat() method to concatenate two strings:
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:
11
Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x
Math.abs(x)
The Math.abs(x) method returns the absolute (positive) value of
12
Boolean Expression
A Boolean expression is a Java expression that returns a Boolean
value: true or false.
You can use a comparison operator, such as the greater than (>) operator to
find out if an expression (or a variable) is true:
Syntax
if (condition) {
Syntax
if (condition) {
} else {
Syntax
if (condition1) {
} else if (condition2) {
} else {
13
Short Hand If...Else (Ternary Operator)
There is also a short-hand if else, which is known as the ternary
operator because it consists of three operands. It can be used to replace
multiple lines of code with a single line. It is often used to replace simple if else
statements
Syntax
variable = (condition) ? expressionTrue : expressionFalse;
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
This will stop the execution of more code and case testing inside the block.
14
When a match is found, and the job is done, it's time for a break. There is no
need for more testing.
Syntax
while (condition) {
Syntax
do {
while (condition);
Syntax
for (statement 1; statement 2; statement 3) {
15
}
System.out.println(i);
For-Each Loop
There is also a "for-each" loop, which is used exclusively to loop through
elements in an array:
Syntax
for (type variableName : arrayName) {
System.out.println(i);
Java Arrays
Arrays are used to store multiple values in a single variable, instead of declaring
separate variables for each value.
String[] cars;
16
Example
cars[0] = "Opel";
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
Array Length
To find out how many elements an array has, use the length property:
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
// Outputs 4
Example
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[i]);
17
Multidimensional Arrays
A multidimensional array is an array of arrays.
To create a two-dimensional array, add each array within its own set of curly
braces:
Example
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
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
int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };
int x = myNumbers[1][2];
System.out.println(x); // Outputs 7
Java Methods
• 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.
18
methods, such as System.out.println(), but you can also create your
own methods to perform certain actions:
// code to be executed
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:
19
public class Main {
myMethod("Liam");
// Liam Kamau
Multiple Parameters
You can have as many parameters as you like:
myMethod("John", 4);
myMethod("Jenny", 8);
myMethod("Auma", 21);
20
}
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:
return 5.14 + x;
System.out.println(myMethod(5.22));
21
System.out.println("Access denied - You are not old enough!");
} else {
Method Overloading
With method overloading, multiple methods can have the same name with
different parameters:
int myMethod(int x)
float myMethod(float x)
Instead of defining two methods that should do the same thing, it is better to
overload one.
return x + y;
Java Scope
In Java, variables are only accessible inside the region they are created. This is
called scope.
Method Scope
Variables declared directly inside a method are available anywhere in the
method following the line of code in which they were declared:
23
int x = 100;
System.out.println(x);
Block Scope
A block of code refers to all of the code between curly braces {}. Variables
declared inside blocks of code are only accessible by the code between the curly
braces, which follows the line in which the variable was declared:
{ // This is a block
int x = 100;
System.out.println(x);
24
// Code here CANNOT use x
Java Recursion
Recursion is the technique of making a function call itself. This technique
provides a way to break complicated problems down into simple problems which
are easier to solve.
Recursion may be a bit difficult to understand. The best way to figure out how it
works is to experiment with it.
Recursion Example
Adding two numbers together is easy to do, but adding a range of numbers is
more complicated. In the following example, recursion is used to add a range of
numbers together by breaking it down into the simple task of adding two
numbers:
System.out.println(result);
if (k > 0) {
25
} else {
return 0;
Example Explained
When the sum() function is called, it adds parameter k to the sum of all numbers
smaller than k and returns the result. When k becomes 0, the function just
returns 0. When running, the program follows these steps:
10 + sum(9)
10 + ( 9 + sum(8) )
10 + ( 9 + ( 8 + sum(7) ) )
...
10 + 9 + 8 + 7 + 6 + 5 + 4 + 3 + 2 + 1 + sum(0)
10 +9+8+7+6+5+4+3+2+1+0
Since the function does not call itself when k is 0, the program stops there and
returns the result.
Halting Condition
Just as loops can run into the problem of infinite looping, recursive functions
can run into the problem of infinite recursion. Infinite recursion is when the
function never stops calling itself. Every recursive function should have a halting
condition, which is the condition where the function stops calling itself. In the
previous example, the halting condition is when the parameter k becomes 0.
26
int result = sum(5, 10);
System.out.println(result);
} else {
return end;
Tip: The "Don't Repeat Yourself" (DRY) principle is about reducing the repetition
of code. You should extract out the codes that are common for the application,
and place them at a single place and reuse them instead of repeating it.
27
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:
class
Fruit
objects
Apple
Banana
Mango
int x = 5;
28
In Java, an object is created from a class. We have already created the class
named Main, so now we can use this to create objects.
To create an object of Main, specify the class name, followed by the object
name, and use the keyword new:
int x = 5;
System.out.println(myObj.x);
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory/folder:
• Main.java
• Second.java
Main.java
public class Main {
int x = 5;
29
Second.java
class Second {
System.out.println(myObj.x);
Accessing Attributes
You can access attributes by creating an object of the class, and by using the
dot syntax (.):
The following example will create an object of the Main class, with the
name myObj. We use the x attribute on the object to print its value:
int x = 5;
System.out.println(myObj.x);
30
public class Main {
int x = 10;
System.out.println(myObj.x);
Multiple Objects
If you create multiple objects of one class, you can change the attribute values
in one object, without affecting the attribute values in the other:
int x = 5;
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
31
Multiple Attributes
You can specify as many attributes as you want:
myMethod();
32
}
In the example above, we created a static method, which means that it can be
accessed without creating an object of the class, unlike public, which can only
be accessed by objects:
// Static method
// Public method
// Main method
33
// myPublicMethod(); This would compile an error
Example
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:
34
myCar.fullThrottle(); // Call the fullThrottle() method
Example explained
1) We created a custom Main class with the class keyword.
3) The fullThrottle() method and the speed() method will print out some text,
when they are called.
4) The speed() method accepts an int parameter called maxSpeed - we will use this
in 8).
5) In order to use the Main class and its methods, we need to create
an object of the Main Class.
6) Then, go to the main() method, which you know by now is a built-in Java
method that runs your program (any code inside main is executed).
7) By using the new keyword we created an object with the name myCar.
8) Then, we call the fullThrottle() and speed() methods on the myCar object, and
run the program using the name of the object (myCar), followed by a dot (.),
followed by the name of the method (fullThrottle(); and speed(200);). Notice
that we add an int parameter of 260 inside the speed() method.
35
Using Multiple Classes
Like we specified in the Classes chapter, it is a good practice to create an object
of a class and access it in another class.
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:
• Main.java
• Second.java
Main.java
public class Main {
Second.java
class Second {
36
Java Constructors
A constructor in Java is a special method that is used to initialize objects. The
constructor is called when an object of a class is created.
ote that the constructor name must match the class name, and it cannot have
a return type (like void).
Also note that the constructor is called when the object is created.
All classes have constructors by default: if you do not create a class constructor
yourself, Java creates one for you. However, then you are not able to set initial
values for object attributes.
int modelYear;
String modelName;
modelYear = year;
modelName = name;
37
// Outputs 1969 Mustang
attributes, methods and constructors, you can use the one of the following
modifiers:
Non-Access Modifiers
For classes, you can use either final or abstract:
38
final The class cannot be inherited by other classes
For attributes and methods, you can use the one of the following:
static Attributes and methods belongs to the class, rather than an object
abstract Can only be used in an abstract class, and can only be used on
methods.
The method does not have a body, for example abstract void run();.
transient Attributes and methods are skipped when serializing the object
containing them
39
• If you don't want the ability to override existing attribute values, declare
attributes as final
System.out.println(myObj.x);
A static method means that it can be accessed without creating an object of the
class, unlike public:
// Static method
// Public method
40
System.out.println("Public methods must be called by creating
objects");
// Main method
Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:
// abstract class
abstract class Main {
41
public int graduationYear = 2018;
class Second {
42