0% found this document useful (0 votes)
92 views

Learn Java From Basics - Bikram

The document provides an introduction to Java programming. It discusses what Java is, why it should be used, how it differs from other languages, and how to install and run a basic "Hello World" Java program. It demonstrates creating a Java file with a main class, compiling the file with javac, and running the program with java. Key aspects of Java code like comments and variables are also introduced.

Uploaded by

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

Learn Java From Basics - Bikram

The document provides an introduction to Java programming. It discusses what Java is, why it should be used, how it differs from other languages, and how to install and run a basic "Hello World" Java program. It demonstrates creating a Java file with a main class, compiling the file with javac, and running the program with java. Key aspects of Java code like comments and variables are also introduced.

Uploaded by

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

@BikramMaharjan

LEARN JAVA FROM


BASICS
By Bikram Maharjan
Msc.CSIT
@BikramMaharjan
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 (especially Android apps)
• Desktop applications
• Web applications
• Web servers and application servers
• Games
• Database connection
• And much, much more!
@BikramMaharjan
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
@BikramMaharjan
Why Java is different from other
languages
High Level
M Language(Java)
A C
C .CLASS O
Java Compiler
M
1. Checks the Grammar of
O P
Syntax.
S I Converts
JIT 2. After the successful
L byte
compilation JLT convert into
E code to
the byte code
R binary
WINDOWS
MAC
JIT Compiler
(.EXE O/S)
@BikramMaharjan
Java Install
Some PCs might have Java already installed.
To check if you have Java installed on a Windows PC, search in the start bar for Java or type the
following in Command Prompt (cmd.exe):
C:\Users\Your Name>java –version
If Java is installed, you will see something like this (depending on version):
java version "11.0.1" 2018-10-16 LTS
Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
@BikramMaharjan
Setup for Windows
1.Go to "System Properties" (Can be found on Control Panel > System and Security > System >
Advanced System Settings)
2.Click on the "Environment variables" button under the "Advanced" tab
3.Then, select the "Path" variable in System variables and click on the "Edit" button
4.Click on the "New" button and add the path where Java is installed, followed by \bin. By
default, Java is installed in C:\Program Files\Java\jdk-11.0.1 (If nothing else was specified when
you installed it). In that case, You will have to add a new path with: C:\Program
Files\Java\jdk-11.0.1\bin
Then, click "OK", and save the settings
5.At last, open Command Prompt (cmd.exe) and type java -version to see if Java is running on
your machine
@BikramMaharjan
Show how to install Java step by step
Step 1
@BikramMaharjan
Show how to install Java step by step
Step 2
@BikramMaharjan
Show how to install Java step by step
Step 3
@BikramMaharjan
Show how to install Java step by step
Step 4
@BikramMaharjan
Show how to install Java step by step
Step 5
• Write the following in the command line (cmd.exe):
C:\Users\Your Name>java –version

• If Java was successfully installed, you will see something like this (depending on version):

java version "11.0.1" 2018-10-16 LTS


Java(TM) SE Runtime Environment 18.9 (build 11.0.1+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.1+13-LTS, mixed mode)
@BikramMaharjan
Java QuickStart
• In Java, every application begins with a class name, and that class must match the filename.
• Let's create our first Java file, called Main.java, which can be done in any text editor (like
Notepad).
• The file should contain a "Hello World" message, which is written with the following code:
Java Syntax
public class Main {
public static void main(String[] args) {
System.out.println("Hello ritu");
}
}
@BikramMaharjan
Steps to Run Java File
Save the code in Notepad as "Main.java".
Open Command Prompt (cmd.exe), navigate to the directory where you saved your file, and type
"javac Main.java":
C:\Users\Your Name>javac Main.java
This will compile your code. If there are no errors in the code, the command prompt will take you
to the next line. Now, type "java Main" to run the file:
C:\Users\Your Name>java Main
The output should read:
Hello World
@BikramMaharjan
Example explained
We created a java file called main.java, and we used the following code to print “Hello world” to the
screen:

Every line of code that runs in Java must be inside a class. In our example, we
named the class Main. A class should always start with an uppercase first letter.
Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

The name of the java file must match the class name. When saving the file, save it
using the class name and add ".java" to the end of the filename. To run the example
above on your computer, make sure that Java is properly installed:
@BikramMaharjan
public class FirstJavaProgram {
This is the first line of our java program. Every java
application must have at least one class definition
that consists of class keyword followed by class
name. When I say keyword, it means that it should
not be changed, we should use it as it is. However
the class name can be anything.
@BikramMaharjan
public static void main(String[] args)
{
This is our next line in the program, lets break it down to understand it:
public: This makes the main method public that means that we can call the method from outside the
class.

static: We do not need to create object for static methods to run. They can run itself.

void: It does not return anything.

main: It is the method name. This is the entry point method from which the JVM can run your program.

(String[] args): Used for command line arguments that are passed as strings. We will cover that in a
separate post.
@BikramMaharjan
System.out.println("This is my first program in java");

This method prints the contents inside the double quotes


into the console and inserts a newline after.

Note: The curly braces {} marks the beginning and the end
of a block of code.

Note: Each code statement must end with a semicolon.


@BikramMaharjan
Test Yourself With Exercises
Insert the missing part of the code below to output "Hello World".

public class MyClass {


public static void main(String[] args) {
_______._____.______("Hello World");
}
}
@BikramMaharjan
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
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:


Example
// This is a comment
System.out.println("Hello World");
@BikramMaharjan
Comments

Single Line Comment


System.out.println("Hello World"); /* The code below will print the words Hello
World
// This is a comment
to the screen, and it is amazing */
System.out.println("Hello World");

Multiple Line Comment


@BikramMaharjan
Exercise:
This is a single-line comment

This is a multi-line comment

Activity Time
@BikramMaharjan
Variables in Java
Variables are containers for storing data values.
In Java, there are different types of variables, for example:

Data Type Description

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


@BikramMaharjan
How to Declare a variable in Java
To declare a variable follow this syntax:

data_type variable_name = value;


here value is optional because in java, you can declare the variable first and then later assign the value to it.
Example :-
Create a variable called name of type String and assign it the value "John":

String name = "John";


System.out.println(name);
@BikramMaharjan
Program Example of Data types
(String)
public class Main {
public static void main(String[] args) {
String name = "John";
System.out.println(name);
}
}

Output :
John
@BikramMaharjan
Program Example of Data types (int)
To create a variable that should store a number, look at the following example:

public class Main {


public static void main(String[] args) {
int myNum = 15;
System.out.println(myNum);
}
}
Output :
15
@BikramMaharjan
Declare a variable without assigning the value

You can also declare a variable without assigning the value, and assign the value later:
public class Main {
public static void main(String[] args) {
int myNum;
myNum = 15;
System.out.println(myNum);
}
}
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
@BikramMaharjan
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):public
class Main {
public static void main(String[] args) {
final int myNum = 15;
myNum = 20; // will generate an error
System.out.println(myNum);
}
}
Output :
Main.java:4: error: cannot assign a value to final variable myNum
myNum = 20;
^
1 error
@BikramMaharjan
Other Data Types

int myNum = 5;
float myFloatNum = 5.99f;
char myLetter = 'D';
boolean myBool = true;
String myText = "Hello";
@BikramMaharjan
Variables naming convention in java
• 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
@BikramMaharjan
Display Variables
The println() method is often used to display variables.

To combine both text and a variable, use the + character:


public class Main {
public static void main(String[] args) {
String name = "John";
System.out.println("Hello " + name);
}
}
Output :
Hello John
@BikramMaharjan
Example
public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
String fullName = firstName + lastName;
System.out.println(fullName);
}
}
Output :
John Doe
@BikramMaharjan
Example
public class Main {
public static void main(String[] args) {
int x = 5;
int y = 6;
System.out.println(x + y); // Print the value of x + y
}
}

Output :
11
@BikramMaharjan
Declare Many Variables
To declare more than one variable of the same type, use a comma-separated list:

public class Main {


public static void main(String[] args) {
int x = 5, y = 6, z = 50;
System.out.println(x + y + z);
}
}
Output :
61
@BikramMaharjan
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:
@BikramMaharjan
Example
public class Main {
public static void main(String[] args) {
// Good
int minutesPerHour = 60;

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


int m = 60;

System.out.println(minutesPerHour);
System.out.println(m);
}
}
Output :
60
60
@BikramMaharjan
Activity
Create a variable named carName and assign the value Volvo to it.

=
@BikramMaharjan
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

Data types are divided into two groups:


• Primitive data types - includes byte, short, int, long, float, double, boolean and char
• Non-primitive data types - such as String, Arrays and Classes (you will learn more about these in a
later chapter)
@BikramMaharjan
Primitive Data Types
A primitive data type specifies the size and type of variable values, and it has no additional
methods.
There
DATAare eight primitive
TYPE SIZE data types in Java: 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,647
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
@BikramMaharjan
Non Primitive Data Types
on-primitive data types are called reference types because they refer to objects.

The main difference between primitive and non-primitive data types are:
• Primitive types are predefined (already defined) in Java. Non-primitive types are created by the
programmer and is not defined by Java (except for String).
• 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.
• Examples of non-primitive types are Strings, Arrays, Classes, Interface, etc.
@BikramMaharjan
Activity
Add the correct data type for the following variables:

myNum = 9;
myFloatNum = 8.99f;
myLetter = 'A’;
myBool = false;
myText = "Hello World";
@BikramMaharjan
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:

1. Widening Casting (automatically) - converting a smaller type to a larger type size


byte -> short -> char -> int -> long -> float -> double

2. Narrowing Casting (manually) - converting a larger type to a smaller size type


double -> float -> long -> int -> char -> short -> byte
@BikramMaharjan
Widening Casting
Widening casting is done automatically when passing a smaller size type to a larger size type:
Example:
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
}
}
@BikramMaharjan
Narrowing Casting
Narrowing casting must be done manually by placing the type in parentheses in front of the value:
Example:
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
}
}
@BikramMaharjan
Java Operators
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
public class Main {
public static void main(String[] args) {
int x = 100 + 50;
System.out.println(x);
}
}
@BikramMaharjan
Java Operators
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:
public class Main {
public static void main(String[] args) {
int sum1 = 100 + 50;
int sum2 = sum1 + 250;
int sum3 = sum2 + sum2;
System.out.println(sum1);
System.out.println(sum2);
System.out.println(sum3);
}
}
@BikramMaharjan
Java Operators
• Java divides the operators into the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators

@BikramMaharjan
Arithmetic Operators
Operator Name Description Example

+ Addition Adds together two values x+y

- Subtraction Subtracts one value from another x-y

* Multiplication Multiplies two values x*y

/ Division Divides one value by another x/y

% Modulus Returns the division remainder x%y

++ Increment Increases the value of a variable by 1 ++x

-- Decrement Decreases the value of a variable by 1 --x


@BikramMaharjan
Increment Operator (++)
public class Main {
public static void main(String[] args) {
int x = 5;
++x;
System.out.println(x);
}
}
@BikramMaharjan
Decrement Operator (--)
public class Main {
public static void main(String[] args) {
int x = 5;
--x;
System.out.println(x);
}
}
@BikramMaharjan
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:

public class Main {


public static void main(String[] args) {
int x = 10;
System.out.println(x);
}
}
@BikramMaharjan
A list of all assignment
operators:
Operator Example Same As
= x=5 x= 5
+= x += 3 x= x+3
-= x -= 3 x= x-3
*= x *= 3 x= x*3
/= x /= 3 x= x/3
%= x %= 3 x= x%3
&= x &= 3 x= x&3
|= x |= 3 x= x|3
^= x ^= 3 x= x^3
>>= x >>= 3 x= x >> 3
<<= x <<= 3 x= x << 3
@BikramMaharjan
Java Comparison Operators
Operator Name Example

== Equal to x == y

!= Not equal x != y

> Greater than x>y

< Less than x<y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y


@BikramMaharjan
Java Logical Operators
Operator Name Description Example
&& Logical and Returns true if both statements x < 5 && x < 10
are true
|| Logical or Returns true if one of the x < 5 || x < 4
statements is true

! Logical not Reverse the result, returns !(x < 5 && x < 10)
false if the result is true
@BikramMaharjan
Example(Logical &&)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 && x < 10); // returns true because 5
is greater than 3 AND 5 is less than 10
}
}
@BikramMaharjan
Example(Logical ||)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(x > 3 || x < 4); // returns true because one of the conditions are true
(5 is greater than 3, but 5 is not less than 4)
}
}
@BikramMaharjan
Example(Logical !)
public class Main {
public static void main(String[] args) {
int x = 5;
System.out.println(!(x > 3 && x < 10)); // returns false because ! (not) is used to reverse
the result
}
}
@BikramMaharjan
Activity
System.out.println(10 5);
@BikramMaharjan
Java Strings
Strings are used for storing text.

A String variable contains a collection of characters surrounded by double quotes:


public class Main {
public static void main(String[] args) {
String greeting = "Hello";
System.out.println(greeting);
}
}
@BikramMaharjan
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:
public class Main {
public static void main(String[] args) {
String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
System.out.println("The length of the txt string is: " + txt.length());
}
}
@BikramMaharjan
String Uppercase and lowercase
Method
public class Main {
public static void main(String[] args) {
String txt = "Hello World";
System.out.println(txt.toUpperCase());
System.out.println(txt.toLowerCase());
}
}
@BikramMaharjan
Finding a Character in a String
public class Main {
public static void main(String[] args) {
String txt = "Please locate where 'locate' occurs!";
System.out.println(txt.indexOf("locate"));
}
}
@BikramMaharjan
String Concatenation
public class Main {
public static void main(String args[]) {
String firstName = "John";
String lastName = "Doe";
System.out.println(firstName + " " + lastName);
}
}
@BikramMaharjan
String (Concat() method)
public class Main {
public static void main(String[] args) {
String firstName = "John ";
String lastName = "Doe";
System.out.println(firstName.concat(lastName));
}
}
@BikramMaharjan
Activity
Fill in the missing part to create a greeting variable of
type String and assign it the value Hello.

greeting = ;
@BikramMaharjan
Java Math (Math.max(x,y))
The Math.max(x,y) method can be used to find the highest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.max(5, 10));
}
}
@BikramMaharjan
Math.min(x,y)
The Math.min(x,y) method can be used to find the lowest value of x and y:
public class Main {
public static void main(String[] args) {
System.out.println(Math.min(5, 10));
}
}
@BikramMaharjan
Math.sqrt(x)
The Math.sqrt(x) method returns the square root of x:

public class Main {


public static void main(String[] args) {
System.out.println(Math.sqrt(64));
}
}
@BikramMaharjan
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
@BikramMaharjan
Java Conditions and If Statements
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
@BikramMaharjan
The if Statement
public class Main {
public static void main(String[] args) {
int x = 20;
int y = 18;
if (x > y) {
System.out.println("x is greater than y");
}
}
}
@BikramMaharjan
The else Statement
public class Main {
public static void main(String[] args) {
int time = 20;
if (time < 18) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
@BikramMaharjan
The else if Statement
public class Main {
public static void main(String[] args) {
int time = 22;
if (time < 10) {
System.out.println("Good morning.");
} else if (time < 20) {
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
}
}
@BikramMaharjan
Java Switch Statements
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
@BikramMaharjan
Switch Case Example
public class Main { case 4:
public static void main(String[] args) { System.out.println("Thursday");
break;
int day = 4;
case 5:
switch (day) {
System.out.println("Friday");
case 1:
break;
System.out.println("Monday"); case 6:
break; System.out.println("Saturday");
case 2: break;
System.out.println("Tuesday"); case 7:
break; System.out.println("Sunday");
break;
case 3:
}
System.out.println("Wednesday");
}
break;
}
@BikramMaharjan
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.
1. While loop
2. Do while loop
3. For loop
@BikramMaharjan
Java While Loop
The while loop loops through a block of code as long as a specified condition is true:
while (condition) {
// code block to be executed
}
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
}
}
}
@BikramMaharjan
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 (statement 1; statement 2; statement 3) {
// code block to be executed
}
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
System.out.println(i);
}
}
}
@BikramMaharjan
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.

do {
// code block to be executed
}
while (condition);
@BikramMaharjan
EXAMPLE
public class Main {
public static void main(String[] args) {
int i = 0;
do {
System.out.println(i);
i++;
}
while (i < 5);
}
}
@BikramMaharjan
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;
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};

To create an array of integers, you could write:


int[] myNum = {10, 20, 30, 40};
@BikramMaharjan
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:


public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars[0]);
}
}
@BikramMaharjan
Change an Array Element
To change the value of a specific element, refer to the index number:

public class Main {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
cars[0] = "Opel";
System.out.println(cars[0]);
}
}
@BikramMaharjan
Array Length
To find out how many elements an array has, use the length property:

public class Main {


public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
System.out.println(cars.length);
}
}
@BikramMaharjan
ACTIVITY
Create an array of type String called cars.

= {"Volvo", "BMW", "Ford"};


@BikramMaharjan
Java Arrays Loop

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:


@BikramMaharjan
Loop Through an Array
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
System.out.println(cars[i]);
}
}
}
@BikramMaharjan
Loop Through an Array with For-Each
There is also a "for-each" loop, which is used exclusively to loop through elements in
arrays:

Syntax:
for (type variable : arrayname) {
...
}
@BikramMaharjan
For each loop example
public class Main {
public static void main(String[] args) {
String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
System.out.println(i);
}
}
}
@BikramMaharjan
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.
@BikramMaharjan
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
}
}
@BikramMaharjan
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
@BikramMaharjan
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:
@BikramMaharjan
Example (calling a method)
public class Main {
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {


myMethod();
}
}
@BikramMaharjan
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();
}
}
@BikramMaharjan
Activity
Insert the missing part to call myMethod from main.
static void myMethod() {
System.out.println("I just got executed!");
}

public static void main(String[] args) {

;
}
@BikramMaharjan
Java Method Parameters
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.
@BikramMaharjan
Java Method Parameters
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 + " Verma");
}

public static void main(String[] args) {


myMethod(“Anjali");
myMethod(“Sumit");
myMethod(“Kavita");
}
}
@BikramMaharjan
Java - 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
@BikramMaharjan
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:
Class Object
Fruit Apple, Mango, Grapes

Car Volvo, Audi, Toyota


@BikramMaharjan
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.
@BikramMaharjan
Java Class
Create a Class
To create a class, use the keyword class:Main.java
Create a class named "Main" with a variable x:

public class Main {


int x = 5;
}
@BikramMaharjan
Java Object
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:
@BikramMaharjan
Object Example
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}
@BikramMaharjan
Multiple Objects Example
public class Main {
int x = 5;

public static void main(String[] args) {


Main myObj1 = new Main();
Main myObj2 = new Main();
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}
@BikramMaharjan
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
@BikramMaharjan
Using Multiple Classes
Main.java

public class Main {

int x = 5;

Main.java Second.java
Second.java
}

class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
@BikramMaharjan
Continue…
When both files have been compiled:
C:\Users\Your Name>javac Main.java
C:\Users\Your Name>javac Second.java

Run the Second.java file:


C:\Users\Your Name>java Second

And the output will be:


5
@BikramMaharjan
Activity
Create an object of MyClass called myObj.

= new ();
@BikramMaharjan
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. It can be used to set initial values for object attributes:

Note 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.
@BikramMaharjan
Constructure Example
// Create a Main class
public class Main {
int x;

// Create a class constructor for the Main class


public Main() {
x = 5;
}

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}
@BikramMaharjan
Java Modifiers
By now, you are quite familiar with the public keyword that appears in almost all of our examples:

public class Main

The public keyword is an access modifier, meaning that it is used to set the access level for classes,
attributes, methods and constructors.

We divide modifiers into two groups:

• Access Modifiers - controls the access level


• Non-Access Modifiers - do not control access level, but provides other functionality
@BikramMaharjan
Access Modifiers
->For classes, you can use either public or default:
public The class is accessible by any other class
default The class is only accessible by classes in the same
package.
->For attributes, methods and constructors, you can use the one of the following:
public The code is accessible for all classes
private The code is only accessible within the declared class
Default The code is only accessible in the same package. This is used when
you don't specify a modifier.
protected The code is accessible in the same package and subclasses.
@BikramMaharjan
Non-Access Modifiers
For classes, you can use either final or abstract:

Modifier Description
final The class cannot be inherited by other classes
abstract The class cannot be used to create objects

For attributes and methods, you can use the one of the
following:
@BikramMaharjan
Non-Access Modifiers
For attributes and methods, you can use the one of the following:

Modifier Description
final Attributes and methods cannot be overridden/modified
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();. The body is
provided by the subclass (inherited from).
transient Attributes and methods are skipped when serializing the object containing
them
synchronized Methods can only be accessed by one thread at a time
volatile The value of an attribute is not cached thread-locally, and is always read from
the "main memory"
@BikramMaharjan
Final Example
If you don't want the ability to override existing attribute values, declare attributes as final:
public class Main {
final int x = 10;
final double PI = 3.14;

public static void main(String[] args) {


Main myObj = new Main();
myObj.x = 50; // will generate an error
myObj.PI = 25; // will generate an error
System.out.println(myObj.x);
}
}
@BikramMaharjan
Static Example
A static method means that it can be accessed without creating an object of the class, unlike public:
public class Main {
// Static method
static void myStaticMethod() {
System.out.println("Static methods can be called without creating objects");
}

// Public method
public void myPublicMethod() {
System.out.println("Public methods must be called by creating objects");
}

// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method

Main myObj = new Main(); // Create an object of MyClass


myObj.myPublicMethod(); // Call the public method
}
}
@BikramMaharjan
Abstract Example
// Code from filename: Main.java // End code from filename: Main.java
// abstract class
abstract class Main { // Code from filename: Second.java
public String fname = "John"; class Second {
public int age = 24; public static void main(String[] args) {
public abstract void study(); // abstract // create an object of the Student class
method (which inherits attributes and methods from
Main)
}
Student myObj = new Student();

// Subclass (inherit from Main)


System.out.println("Name: " + myObj.fname);
class Student extends Main {
System.out.println("Age: " + myObj.age);
public int graduationYear = 2018;
System.out.println("Graduation Year: " +
public void study() { // the body of the abstract myObj.graduationYear);
method is provided here
myObj.study(); // call abstract method
System.out.println("Studying all day long");
}
}
}
}
@BikramMaharjan
Java Encapsulation
The meaning of Encapsulation, is to make sure that "sensitive" data is hidden from users.
To achieve this, you must:

declare class variables/attributes as private


provide public get and set methods to access and update the value of a private
variable
@BikramMaharjan
Get and Set
You learned from the previous chapter that private variables can only be accessed
within the same class (an outside class has no access to it). However, it is possible to
access them if we provide public get and set methods.

The get method returns the variable value, and the set method sets the value.

Syntax for both is that they start with either get or set, followed by the name of the
variable, with the first letter in upper case:
@BikramMaharjan
Example
public class Person {
private String name; // private = restricted access

// Getter
public String getName() {
return name;
}

// Setter
public void setName(String newName) {
this.name = newName;
}
}
@BikramMaharjan
Example Explained
The get method returns the value of the variable name.

The set method takes a parameter (newName) and assigns it to the name variable. The
this keyword is used to refer to the current object.

However, as the name variable is declared as private, we cannot access it from outside
this class:
@BikramMaharjan
Java Packages & API
A package in Java is used to group related classes. Think of it as a folder in a file directory. We
use packages to avoid name conflicts, and to write a better maintainable code. Packages are
divided into two categories:

Built-in Packages (packages from the Java API)


User-defined Packages (create your own packages)
@BikramMaharjan
Built-in Packages
The Java API is a library of prewritten classes, that are free to use, included in the Java
Development Environment.
The library contains components for managing input, database programming, and much
much more. The complete list can be found at Oracles website:
https://docs.oracle.com/javase/8/docs/api/.
The library is divided into packages and classes. Meaning you can either import a single class
(along with its methods and attributes), or a whole package that contain all the classes that
belong to the specified package.
To use a class or a package from the library, you need to use the import keyword:
import package.name.Class; // Import a single class
import package.name.*; // Import the whole package
@BikramMaharjan
Import a Class
If you find a class you want to use, for example, the Scanner class, which is used to get user
input, write the following code:

Example:-
import java.util.Scanner;
In the example above, java.util is a package, while Scanner is a class of the java.util package.

To use the Scanner class, create an object of the class and use any of the available methods
found in the Scanner class documentation. In our example, we will use the nextLine() method,
which is used to read a complete line:
@BikramMaharjan
Scanner Example
import java.util.Scanner; // import the Scanner class

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
@BikramMaharjan
Import a Package
There are many packages to choose from. In the previous example, we used the Scanner class
from the java.util package. This package also contains date and time facilities, random-number
generator and other utility classes.

To import a whole package, end the sentence with an asterisk sign (*). The following example
will import ALL the classes in the java.util package:
@BikramMaharjan
Example of import the java package
import java.util.*; // import the java.util package

class Main {
public static void main(String[] args) {
Scanner myObj = new Scanner(System.in);
String userName;

// Enter username and press Enter


System.out.println("Enter username");
userName = myObj.nextLine();

System.out.println("Username is: " + userName);


}
}
@BikramMaharjan
User-defined Packages
To create your own package, you need to understand that Java uses a file system directory to
store them. Just like folders on your computer:

To create a package, use the package keyword:

package mypack;

class MyPackageClass {
public static void main(String[] args) {
System.out.println("This is my package!");
}
}
Save the file as MyClass.java, and compile it:

You might also like