Object Oriented Programming - Java[2
Object Oriented Programming - Java[2
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 languages in the world
It has a large demand in the current job market
It is easy to learn and simple to use
It is open-source and free
It is secure, fast and powerful
It has 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.
Syntax
System.out.println("Hello World");
}
Example explained
Every line of code that runs in Java must be inside a class. And the class name should always start with
an uppercase first letter. In our example, we named the class Main.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.
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");
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is short for "output".
The println() method, short for "print line", is used to print a value to the screen (or a file).
Don't worry too much about how System, out and println() works. Just know that you need them
together to print stuff to the screen.
You should also note that each code statement must end with a semicolon (;).
Example:
System.out.println("Hello World!");
System.out.println("It is awesome!");
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
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare
the variable as "final" or "constant", which means unchangeable and read-only):
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:
// Good
int m = 60;
// Student data
// Print variables
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:
int x = 100 + 50;
int x = 5;
int y = 3;
Java Strings
Strings are used for storing text.
A String variable contains a collection of characters surrounded by double quotes:
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(txt.indexOf("locate")); // Outputs 7
String Concatenation
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:
System.out.println(firstName.concat(lastName));
Java Math
Math.max(x,y)
The Math.max(x,y) method can be used to find the highest value of x and y:
Math.max(5, 10);
Math.min(5, 10);
Math.sqrt(64);
if (doorCode == 1337) {
} else {
This example shows how you can use if..else to find out if a number is positive or negative:
if (myNum > 0) {
} else {
} else {
int myNum = 5;
if (myNum % 2 == 0) {
System.out.println(myNum + " is even");
} else {
Java Switch
Instead of writing many if..else statements, you can use the switch statement.
The switch statement selects one of many code blocks to be executed:
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:
int day = 4;
switch (day) {
case 1:
System.out.println("Monday");
break;
case 2:
System.out.println("Tuesday");
break;
case 3:
System.out.println("Wednesday");
break;
case 4:
System.out.println("Thursday");
break;
case 5:
System.out.println("Friday");
break;
case 6:
System.out.println("Saturday");
break;
case 7:
System.out.println("Sunday");
break;
default:
Week 2
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.
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
int i = 0;
do {
System.out.println(i);
i++;
Real-Life Examples
To demonstrate a practical example of the while loop, we have created a simple "countdown" program:
int countdown = 3;
System.out.println(countdown);
countdown--;
}
System.out.println("Happy New Year!!");
System.out.println(i);
This example will only print even values between 0 and 10:
System.out.println(i);
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
// Outer loop
// Inner loop
Real-Life Examples
int number = 2;
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:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you can place the
values in a comma-separated list, inside curly braces:
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
To create an array of integers, you could write:
int[] myNum = {10, 20, 30, 40};
Access the Elements of an Array
You can access an array element by referring to the index number.
This statement accesses the value of the first element in cars:
// Outputs Volvo
System.out.println(cars[i]);
Multidimensional Arrays
A multidimensional array is an array of arrays.
Multidimensional arrays are useful when you want to store data as a tabular form, like a table with rows
and columns.
To create a two-dimensional array, add each array within its own set of curly braces:
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:
System.out.println(myNumbers[1][2]); // Outputs 7
myNumbers[1][2] = 9;
System.out.println(myNumbers[i][j]);
}
}
Or you could just use a for-each loop, which is considered easier to read and write:
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:
// code to be executed
}
• 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:
Inside main, call the myMethod() method:
myMethod();
myMethod();
myMethod();
myMethod();
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
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:
public class Main {
static void myMethod(String fname, int age) {
System.out.println(fname + " is " + age);
}
public static void main(String[] args) {
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
}
}
// Liam is 5
// Jenny is 8
// Anja is 31
Java Return
we used the void keyword in all examples, which 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 + x;
}
public static void main(String[] args) {
System.out.println(myMethod(3));
// Outputs 8 (5 + 3)
return x + y;
System.out.println(myMethod(5, 3));
// Outputs 8 (5 + 3)
You can also store the result in a variable (recommended, as it is easier to read and maintain):
return x + y;
System.out.println(z);
// Outputs 8 (5 + 3)
int myMethod(int x)
float myMethod(float x)
Consider the following example, which has two methods that add numbers of different type:
return x + y;
}
static double plusMethodDouble(double x, double y) {
return x + y;
Instead of defining two methods that should do the same thing, it is better to overload one.
In the example below, we overload the plusMethod method to work for both int and double:
return x + y;
return x + y;
}
Week 3
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:
int x = 100;
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);
}
Java 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
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.
Java Classes/Objects
Java is an object-oriented programming language.
Everything in Java is associated with classes and objects, along with its attributes and methods. For
example: in real life, a car is an object. The car has attributes, such as weight and color, and methods,
such as drive and brake.
A Class is like an object constructor, or a "blueprint" for creating objects.
Create a Class
To create a class, use the keyword class:
public class Main {
int x = 5;
Remember that a class should always start with an uppercase first letter, and that the name of the java
file should match the class name.
Create an Object
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:
Example
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:
System.out.println(myObj1.x);
System.out.println(myObj2.x);
int x = 5;
Second.java
class Second {
public static void main(String[] args) {
System.out.println(myObj.x);
int x = 5;
int y = 3;
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:
Example:
Create an object called "myObj" and print the value of x:
int x = 5;
System.out.println(myObj.x);
Modify Attributes
You can also modify attribute values:
Example
Set the value of x to 40:
int x;
myObj.x = 40;
System.out.println(myObj.x);
If you don't want the ability to override existing values, declare the attribute as final:
System.out.println(myObj.x);
The final keyword is useful when you want a variable to always store the same value, like PI
(3.14159...).
The final keyword is called a "modifier".
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:
Example
Change the value of x to 25 in myObj2, and leave x in myObj1 unchanged:
int x = 5;
myObj2.x = 25;
System.out.println(myObj1.x); // Outputs 5
System.out.println(myObj2.x); // Outputs 25
Multiple Attributes
You can specify as many attributes as you want:
Example