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

Object Oriented Programming - Java[2

The document provides an introduction to Java programming, covering its history, usage, and advantages such as platform independence and community support. It explains fundamental concepts including syntax, variables, data types, operators, control structures like loops and conditionals, arrays, and methods. The document also includes practical examples to illustrate these concepts in action.

Uploaded by

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

Object Oriented Programming - Java[2

The document provides an introduction to Java programming, covering its history, usage, and advantages such as platform independence and community support. It explains fundamental concepts including syntax, variables, data types, operators, control structures like loops and conditionals, arrays, and methods. The document also includes practical examples to illustrate these concepts in action.

Uploaded by

baghalialibhai
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Week 1

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

public class Main {

public static void main(String[] args) {

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.

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. Don't worry about the keywords before and after it.
You will get to know them bit by bit while reading this tutorial.
For now, just remember that every Java program has a class name which must match the filename, and
that every program must contain the main() method.

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

public static void main(String[] args) {

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("I am learning Java.");

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

Declaring (Creating) Variables

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):

final int myNum = 15;

myNum = 20; // will generate an error: cannot assign a value to a


final variable

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 minutesPerHour = 60;


// OK, but not so easy to understand what m actually is

int m = 60;

Real Life Example of Variables:

// Student data

String studentName = "John Doe";

int studentID = 15;

int studentAge = 23;

float studentFee = 75.25f;

char studentGrade = 'B';

// Print variables

System.out.println("Student name: " + studentName);

System.out.println("Student id: " + studentID);

System.out.println("Student age: " + studentAge);

System.out.println("Student fee: " + studentFee);

System.out.println("Student grade: " + studentGrade);

Java Data Types

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

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;

Java Comparison Operators

int x = 5;

int y = 3;

System.out.println(x > y); // returns true, because 5 is higher


than 3

Java Logical Operators


You can also test for true or false values with logical operators.
Logical operators are used to determine the logic between variables or values:

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

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):

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

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));
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);

Java If ... Else


This example shows how you can use if..else to "open a door" if the user enters the correct code:

int doorCode = 1337;

if (doorCode == 1337) {

System.out.println("Correct code. The door is now open.");

} else {

System.out.println("Wrong code. The door remains closed.");

This example shows how you can use if..else to find out if a number is positive or negative:

int myNum = 10; // Is this a positive or negative number?

if (myNum > 0) {

System.out.println("The value is a positive number.");


} else if (myNum < 0) {

System.out.println("The value is a negative number.");

} else {

System.out.println("The value is 0.");

Find out if a person is old enough to vote:

int myAge = 25;

int votingAge = 18;

if (myAge >= votingAge) {

System.out.println("Old enough to vote!");

} else {

System.out.println("Not old enough to vote.");

Find out if a number is even or odd:

int myNum = 5;

if (myNum % 2 == 0) {
System.out.println(myNum + " is even");

} else {

System.out.println(myNum + " is odd");

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:

System.out.println("Looking forward to the Weekend");

// Outputs "Thursday" (day 4)


The default keyword specifies some code to run if there is no case match:
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.
A break can save a lot of execution time because it "ignores" the execution of all the rest of the code
in the switch block.

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.

Java While Loop

int i = 0;
while (i < 5) {

System.out.println(i);

i++;

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.
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:

int i = 0;
do {

System.out.println(i);

i++;

while (i < 5);

Real-Life Examples
To demonstrate a practical example of the while loop, we have created a simple "countdown" program:

int countdown = 3;

while (countdown > 0) {

System.out.println(countdown);

countdown--;

}
System.out.println("Happy New Year!!");

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:

for (int i = 0; i < 5; i++) {

System.out.println(i);

This example will only print even values between 0 and 10:

for (int i = 0; i <= 10; i = i + 2) {

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

for (int i = 1; i <= 2; i++) {

System.out.println("Outer: " + i); // Executes 2 times

// Inner loop

for (int j = 1; j <= 3; j++) {


System.out.println(" Inner: " + j); // Executes 6 times (2 * 3)

Real-Life Examples

int number = 2;

// Print the multiplication table for the number 2

for (int i = 1; i <= 10; i++) {

System.out.println(number + " x " + i + " = " + (number * i));

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:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};


System.out.println(cars[0]);

// Outputs Volvo

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:

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

for (int i = 0; i < cars.length; i++) {

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:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

System.out.println(myNumbers[1][2]); // Outputs 7

Change Element Values


You can also change the value of an element:

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

myNumbers[1][2] = 9;

System.out.println(myNumbers[1][2]); // Outputs 9 instead of 7


Loop Through a Multi-Dimensional Array
You 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):

int[][] myNumbers = { {1, 2, 3, 4}, {5, 6, 7} };

for (int i = 0; i < myNumbers.length; ++i) {

for (int j = 0; j < myNumbers[i].length; ++j) {

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:

public class Main {

static void myMethod() {

// 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:

public class Main {

static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

// Outputs "I just got executed!"

A method can also be called multiple times:

public class Main {


static void myMethod() {

System.out.println("I just got executed!");

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!

// I just got executed!

// I just got executed!

Java Method Parameters


Parameters and Arguments
Information can be passed to methods as a 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:
public class Main {

static void myMethod(String fname) {

System.out.println(fname + " Refsnes");

public static void main(String[] args) {

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

A Method with If...Else


It is common to use if...else statements inside methods:

public class Main {

// Create a checkAge() method with an integer variable called age

static void checkAge(int age) {

// If age is less than 18, print "access denied"

if (age < 18) {

System.out.println("Access denied - You are not old


enough!");

// If age is greater than, or equal to, 18, print "access


granted"
} else {

System.out.println("Access granted - You are old enough!");

public static void main(String[] args) {

checkAge(20); // Call the checkAge method and pass along an age


of 20

// Outputs "Access granted - You are old enough!"

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:

public class Main {

static int myMethod(int x) {

return 5 + x;

}
public static void main(String[] args) {

System.out.println(myMethod(3));

// Outputs 8 (5 + 3)

This example returns the sum of a method's two parameters:

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

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):

public class Main {


static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);

System.out.println(z);

// Outputs 8 (5 + 3)

Java Method Overloading


With method overloading, multiple methods can have the same name with different parameters:

int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

Consider the following example, which has two methods that add numbers of different type:

static int plusMethodInt(int x, int y) {

return x + y;

}
static double plusMethodDouble(double x, double y) {

return x + y;

public static void main(String[] args) {

int myNum1 = plusMethodInt(8, 5);

double myNum2 = plusMethodDouble(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

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:

static int plusMethod(int x, int y) {

return x + y;

static double plusMethod(double x, double y) {

return x + y;
}

public static void main(String[] args) {

int myNum1 = plusMethod(8, 5);

double myNum2 = plusMethod(4.3, 6.26);

System.out.println("int: " + myNum1);

System.out.println("double: " + myNum2);

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:

public class Main {

public static void main(String[] args) {

// Code here CANNOT use x

int x = 100;

// Code here can use x


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:

public class Main {

public static void main(String[] args) {

// Code here CANNOT use x

{ // This is a block

// Code here CANNOT use x

int x = 100;

// Code here CAN use x

System.out.println(x);

} // The block ends here

// Code here CANNOT use 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 - 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:

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.

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:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Multiple Objects
You can create multiple objects of one class:
Example
Create two objects of Main:

public class Main {


int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

System.out.println(myObj1.x);

System.out.println(myObj2.x);

Using Multiple Classes


You can also create an object of a class and access it in another class. This is often used for better
organization of classes (one class has all the attributes and methods, while the other class holds
the main() method (code to be executed)).
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;

Second.java

class Second {
public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

What happens if we have two en

try points of our code which one will run?

Java Class Attributes


Previously we used the term "variable" for x in the example (as shown below). It is actually
an attribute of the class. Or you could say that class attributes are variables within a class:
Example
Create a class called "Main" with two attributes: x and y:

public class Main {

int x = 5;

int y = 3;

Another term for class attributes is fields.///As MCQs

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:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

Modify Attributes
You can also modify attribute values:

Example
Set the value of x to 40:

public class Main {

int x;

public static void main(String[] args) {


Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

If you don't want the ability to override existing values, declare the attribute as final:

public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error: cannot assign a value


to a final variable

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:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main(); // Object 1

Main myObj2 = new Main(); // Object 2

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

public class Main {

String fname = "John";

String lname = "Doe";


int age = 24;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println("Name: " + myObj.fname + " " + myObj.lname);

System.out.println("Age: " + myObj.age);

You might also like