0% found this document useful (0 votes)
5 views101 pages

Introduction to Java Till Method Overloading

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is versatile, supporting mobile, desktop, and web applications, and is known for its platform independence, ease of learning, and strong community support. The document covers Java installation, basic syntax, data types, variables, operators, and includes examples for beginners to understand Java programming.

Uploaded by

Haneen Yousuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views101 pages

Introduction to Java Till Method Overloading

Java is a widely-used programming language created in 1995, owned by Oracle, and runs on over 3 billion devices. It is versatile, supporting mobile, desktop, and web applications, and is known for its platform independence, ease of learning, and strong community support. The document covers Java installation, basic syntax, data types, variables, operators, and includes examples for beginners to understand Java programming.

Uploaded by

Haneen Yousuf
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 101

INTRODUCTION TO JAVA

What is Java?
Java is a popular programming language, created in 1995.

It is owned by Oracle, and more than 3 billion devices run Java.

It is used for:

 Mobile applications (specially Android apps)


 Desktop applications
 Web applications
 Web servers and application servers
 Games
 Database connection
 And much, much more!

Why Use Java?


 Java works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc.)
 It is one of the most popular programming 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

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 "22.0.0" 2024-08-21 LTS
Java(TM) SE Runtime Environment 22.9 (build 22.0.0+13-LTS)
Java HotSpot(TM) 64-Bit Server VM 22.9 (build 22.0.0+13-LTS, mixed mode)

If you do not have Java installed on your computer, you can download it for free at oracle.com.

STARTING JAVA

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:

First.java

public class First {


public static void main(String[] args) {
System.out.println("Hello World");
}
}
To compile and Run Program :

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

Note: Java is case-sensitive: "First" and "first" 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.

The main Method


The main() method is required and you will see it in every Java program:

Purpose: This defines a public class called First. In Java, every program must have at least one class, and
this is where the program starts.

public static void main(String[] args) {

 Purpose: This is the main method where the execution of the program begins. It's a
standard method signature in Java.
o public: Accessible to other classes.
o static: Can be run without creating an instance of the class.
o void: Does not return any value.
o String[] args: Allows command-line arguments to be passed to the program
(not used in this example).
System.out.println("Hello World");

Purpose: Prints the message "Hello World" to the console, prompting the user to
input the first number.

Print Text
You learned from the previous chapter that you can use the println() method to
output values or print text in Java:

public class Example {


public static void main(String[] args) {
System.out.println("Hello World!");
System.out.println("I am learning Java.");
System.out.println("My name is Ziauddin Siddiqui!!");
}
}

Java Output Numbers


Print Numbers
You can also use the println() method to print numbers.

However, unlike text, we don't put numbers inside double quotes:


public class Main {
public static void main(String[] args) {
System.out.println(3);
System.out.println(358);
System.out.println(50000);
}
}

Mathematical Calculations:
You can also perform mathematical calculations inside the println() method:

public class Main {


public static void main(String[] args) {
System.out.println(6 + 6);
}
}

public class Main {


public static void main(String[] args) {
System.out.println(2 * 5);
}
}
Java Comments
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:

public class Main {


public static void main(String[] args) {
// This is a comment
System.out.println("Hello World");
}
}
This example uses a single-line comment at the end of a line of code:

public class Main {


public static void main(String[] args) {
System.out.println("Hello World"); // This is a comment
}
}

Java Multi-line Comments


Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by Java.

This example uses a multi-line comment (a comment block) to explain the


code:

public class Main {


public static void main(String[] args) {
/* The code below will print the words Hello World
to the screen, and it is amazing */
System.out.println("Hello World");
}
}
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

How to Initialize Variables in Java?


 It can be perceived with the help of 3 components that are as follows:
 datatype: Type of data that can be stored in this variable.
 variable_name: Name given to the variable.
 value: It is the initial value stored in the variable.
public class Main {

public static void main(String[] args) {

String name = "John";

System.out.println(name);

}
// Java Program to implement
// Local Variables
import java.io.*;

class Main {
public static void main(String[] args)
{
// Declared a Local Variable
int var = 10;

// This variable is local to this main method only


System.out.println("Local Variable: " + var);
}
}

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

Or

public class Main {

public static void main(String[] args) {


int myNum;

myNum = 15;

System.out.println(myNum);

Change the value of variable

public class Main {

public static void main(String[] args) {

int myNum = 25;

myNum = 30; // myNum is now 30

System.out.println(myNum);

}
Error in assigning value :

public class Main {

public static void main(String[] args) {

final int myNum = 15;

myNum = 20; // will generate an error

System.out.println(myNum);

Declare variables of other types:

int myNum = 5;

float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

Display Variables
public class Main {

public static void main(String[] args) {

String name = "John";

System.out.println("Hello " + name);

You can also use the + character to add a variable to another variable:

public class Main {

public static void main(String[] args) {

String firstName = "John ";

String lastName = "Doe";

String fullName = firstName + lastName;

System.out.println(fullName);

}
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

Declare Many Variables

public class Main {

public static void main(String[] args) {

int x = 5, y = 6, z = 50;

System.out.println(x + y + z);

OR

int x = 5;
int y = 6;

int z = 50;

System.out.println(x + y + z);

Example
public class Main {

public static void main(String[] args) {

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

Arithmatic operators

// Java Program to implement


// Arithmetic Operators
import java.io.*;

// Drive Class
class GFG {
// Main Function
public static void main (String[] args) {

// Arithmetic operators on integers


int a = 10;
int b = 3;

// Arithmetic operators on Strings


String num1 = "15";
String num2 = "25";

// Convert Strings to integers


int a1 = Integer.parseInt(num1);
int b1 = Integer.parseInt(num2);

System.out.println("a + b = " + (a + b));


System.out.println("a - b = " + (a - b));
System.out.println("a * b = " + (a * b));
System.out.println("a / b = " + (a / b));
System.out.println("a % b = " + (a % b));
System.out.println("a1 + b1 = " + (a1 + b1));

}
}

Calculate the Area of a Rectangle

public class Main {

public static void main(String[] args) {

// Create integer variables

int length = 4;

int width = 6;

int area;

// Calculate the area of a rectangle

area = length * width;

// Print variables

System.out.println("Length is: " + length);


System.out.println("Width is: " + width);

System.out.println("Area of the rectangle is: " + area);

Java Data Types


public class Main {

public static void main(String[] args) {

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

System.out.println(myNum);

System.out.println(myFloatNum);

System.out.println(myLetter);

System.out.println(myBool);

System.out.println(myText);

}
}

EXAMPLE

public class Samplemain {

public static void main(String[] args) {

// Create variables of different data types

int items = 50;

float costPerItem = 9.99f;

float totalCost = items * costPerItem;

char currency = '$';

// Print variables

System.out.println("Number of items: " + items);

System.out.println("Cost per item: " + currency + costPerItem );

System.out.println("Total cost = " + currency + totalCost );

}
Java Type Casting

Calculate the Area of a Rectangle

public class Main {

public static void main(String[] args) {

int myInt = 9;

double myDouble = myInt; // Automatic casting: int to double

System.out.println(myInt);

System.out.println(myDouble);

public class Main {


public static void main(String[] args) {

// Set the maximum possible score in the game to 500

int maxScore = 500;

// The actual score of the user

int userScore = 423;

/* Calculate the percentage of the user's score in relation to the maximum


available score.

Convert userScore to float to make sure that the division is accurate */

float percentage = (float) userScore / maxScore * 100.0f;

// Print the result

System.out.println("User's percentage is " + percentage);

}
Java Operators
public class Main {

public static void main(String[] args) {

int x = 100 + 50;

System.out.println(x);

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

}
public class Main {

public static void main(String[] args) {

int x = 5;

int y = 3;

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

Boolean Values
A boolean type is declared with the boolean keyword and can only take the
values true or false:

public class Main {

public static void main(String[] args) {

boolean isJavaFun = true;

boolean isFishTasty = false;

System.out.println(isJavaFun);

System.out.println(isFishTasty);

}
public class Main {

public static void main(String[] args) {

int x = 10;

int y = 9;

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

public class Main {

public static void main(String[] args) {

int x = 10;

System.out.println(x == 10); // returns true, because the value of x is


equal to 10

}
public class Main {

public static void main(String[] args) {

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

public class Main {

public static void main(String[] args) {

int myAge = 25;

int votingAge = 18;


System.out.println(myAge >= votingAge); // returns true (25 year olds
are allowed to vote!)

AND OPERATOR

// Java code to illustrate

// logical AND operator

import java.io.*;

class Logical {

public static void main(String[] args)

// initializing variables

int a = 10, b = 20, c = 20, d = 0;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

System.out.println("Var3 = " + c);


// using logical AND to verify

// two constraints

if ((a < b) && (b == c)) {

d = a + b + c;

System.out.println("The sum is: " + d);

else

System.out.println("False conditions");

import java.io.*;

class shortCircuiting {

public static void main(String[] args)

// initializing variables

int a = 10, b = 20, c = 15;

// displaying b
System.out.println("Value of b : " + b);

// Using logical AND

// Short-Circuiting effect as the first condition is

// false so the second condition is never reached

// and so ++b(pre increment) doesn't take place and

// value of b remains unchanged

if ((a > c) && (++b > c)) {

System.out.println("Inside if block");

// displaying b

System.out.println("Value of b : " + b);

OR OPERATOR

// Java code to illustrate

// logical OR operator

import java.io.*;
class Logical {

public static void main(String[] args)

// initializing variables

int a = 10, b = 1, c = 10, d = 30;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

System.out.println("Var3 = " + c);

System.out.println("Var4 = " + d);

// using logical OR to verify

// two constraints

if (a > b || c == d)

System.out.println(

"One or both + the conditions are true");

else

System.out.println(

"Both the + conditions are false");

}
import java.io.*;

class ShortCircuitingInOR {

public static void main (String[] args) {

// initializing variables

int a = 10, b = 20, c = 15;

// displaying b

System.out.println("Value of b: " +b);

// Using logical OR

// Short-circuiting effect as the first condition is true

// so the second condition is never reached

// and so ++b (pre-increment) doesn't take place and

// value of b remains unchanged

if((a < c) || (++b < c))

System.out.println("Inside if");

// displaying b

System.out.println("Value of b: " +b);


}

NOT OPERATOR

// Java code to illustrate

// logical NOT operator

import java.io.*;

class Logical {

public static void main(String[] args)

// initializing variables

int a = 10, b = 1;

// Displaying a, b, c

System.out.println("Var1 = " + a);

System.out.println("Var2 = " + b);

// Using logical NOT operator

System.out.println("!(a < b) = " + !(a < b));

System.out.println("!(a > b) = " + !(a > b));


}

public class LogicalOperators {

public static void main(String[] args) {

boolean a = true;

boolean b = false;

System.out.println("a: " + a);

System.out.println("b: " + b);

System.out.println("a && b: " + (a && b));

System.out.println("a || b: " + (a || b));

System.out.println("!a: " + !a);

System.out.println("!b: " + !b);

Java Strings
public class Main {

public static void main(String[] args) {

String greeting = "Hello";

System.out.println(greeting);

public class Main {

public static void main(String[] args) {

String txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

System.out.println("The length of the txt string is: " + txt.length());

}
public class Main {

public static void main(String[] args) {

String txt = "Hello World";

System.out.println(txt.toUpperCase());

System.out.println(txt.toLowerCase());

public class Main {

public static void main(String[] args) {

String txt = "Please locate where 'locate' occurs!";

System.out.println(txt.indexOf("locate"));

String Concatenation

public class Main {


public static void main(String args[]) {

String firstName = "John";

String lastName = "Doe";

System.out.println(firstName + " " + lastName);

public class ConcatenationExample1 {

public static void main(String[] args) {

String part1 = "Java";

String part2 = "is";

String part3 = "awesome!";

// Concatenate multiple strings

String sentence = part1 + " " + part2 + " " + part3;

// Output the concatenated string

System.out.println(sentence);

}
Java Math

public class Main {

public static void main(String[] args) {

System.out.println(Math.max(5, 10));

public class Main {

public static void main(String[] args) {

System.out.println(Math.sqrt(64));

public class Main {

public static void main(String[] args) {

System.out.println(Math.abs(-4.7));

}
public class Main {

public static void main(String[] args) {

System.out.println(Math.random());

public class Main {

public static void main(String[] args) {

int randomNum = (int)(Math.random() * 101); // 0 to 100

System.out.println(randomNum);

public class Main {

public static void main(String[] args) {

boolean isJavaFun = true;


boolean isFishTasty = false;

System.out.println(isJavaFun);

System.out.println(isFishTasty);

public class Main {

public static void main(String[] args) {

int x = 10;

int y = 9;

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

public class Main {

public static void main(String[] args) {

int myAge = 25;

int votingAge = 18;

System.out.println(myAge >= votingAge); // returns true (25 year olds


are allowed to vote!)

}
}

Java If ... Else (Selection


Statement)
public class Main {

public static void main(String[] args) {

if (20 > 18) {

System.out.println("20 is greater than 18"); // obviously

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

}
}

Java Else
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.");

SHORT HAND

public class Main {

public static void main(String[] args) {

int time = 22;

if (time < 10) {


System.out.println("Good morning.");

} else if (time < 18) {

System.out.println("Good day.");

} else {

System.out.println("Good evening.");

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

}
public class Main {

public static void main(String[] args) {

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

public class Main {

public static void main(String[] args) {

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

public class IfElseExample2 {

public static void main(String[] args) {

int number = 0;

// if-else if-else statement

if (number > 0) {

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

} else if (number < 0) {

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

} else {
System.out.println("The number is zero.");

public class IfElseExample5 {

public static void main(String[] args) {

int temperature = 25;

boolean isRaining = false;

// Multiple conditions

if (temperature > 30 && !isRaining) {

System.out.println("It's hot and sunny outside.");

} else if (temperature > 30 && isRaining) {

System.out.println("It's hot and rainy outside.");

} else if (temperature <= 30 && isRaining) {

System.out.println("It's cool and rainy outside.");

} else {

System.out.println("It's cool and sunny outside.");

}
SWITCH statement

public class Main {

public static void main(String[] args) {

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;

public class Main {

public static void main(String[] args) {

int day = 4;

switch (day) {

case 6:

System.out.println("Today is Saturday");

break;

case 7:

System.out.println("Today is Sunday");

break;
default:

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

Java While Loop


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

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

Java While Loop


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

public class Main {

public static void main(String[] args) {

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.

public class Main {

public static void main(String[] args) {

int i = 0;

do {

System.out.println(i);

i++;

}
while (i < 5);

public class Main {

public static void main(String[] args) {

int dice = 1;

while (dice <= 6) {

if (dice < 6) {

System.out.println("No Good");

} else {

System.out.println("Good!");

dice = dice + 1;

FOR LOOP
public class Main {

public static void main(String[] args) {

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

System.out.println(i);

public class Main {

public static void main(String[] args) {

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

System.out.println(i);

}
Java Nested Loops
public class Main {

public static void main(String[] args) {

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

public class Main {

public static void main(String[] args) {

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

for (String i : cars) {


System.out.println(i);

public class Main {

public static void main(String[] args) {

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

System.out.println(i);

public class Main {

public static void main(String[] args) {

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

System.out.println(i);

}
2 times Table

public class Main {

public static void main(String[] args) {

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 Break and Continue


public class Main {

public static void main(String[] args) {

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

if (i == 4) {

break;
}

System.out.println(i);

public class Main {

public static void main(String[] args) {

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

if (i == 4) {

continue;

System.out.println(i);

}
}

public class Main {

public static void main(String[] args) {

int i = 0;

while (i < 10) {

System.out.println(i);

i++;

if (i == 4) {

break;

public class Main {

public static void main(String[] args) {

int i = 0;

while (i < 10) {


if (i == 4) {

i++;

continue;

System.out.println(i);

i++;

Java Arrays
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:

public class Main {

public static void main(String[] args) {

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

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

}
Change an Array Element

public class Main {

public static void main(String[] args) {

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

cars[0] = "Opel";

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

Array Length

public class Main {

public static void main(String[] args) {

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

System.out.println(cars.length);

}
}

Java Arrays Loop

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

public class Main {

public static void main(String[] args) {

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

for (String i : cars) {

System.out.println(i);
}

public class Main {

public static void main(String[] args) {

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

// Get the length of the array

int length = ages.length;

// Loop through the elements of the array

for (int age : ages) {

sum += age;

// Calculate the average by dividing the sum by the length

avg = sum / length;


// Print the average

System.out.println("The average age is: " + avg);

public class Main {

public static void main(String[] args) {

// An array storing different ages

int ages[] = {20, 22, 18, 35, 48, 26, 87, 70};

float avg, sum = 0;

// Get the length of the array

int length = ages.length;

// Create a 'lowest age' variable and assign the first array element of ages
to it

int lowestAge = ages[0];

// Loop through the elements of the ages array to find the lowest age
for (int age : ages) {

// Check if the current age is smaller than the current 'lowest age'

if (lowestAge > age) {

// If the smaller age is found, update 'lowest age' with that element

lowestAge = age;

// Output the value of the lowest age

System.out.println("The lowest age in the array is: " + lowestAge);

Multidimensional Array

public class Main {

public static void main(String[] args) {

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

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

}
Change Element Values

public class Main {

public static void main(String[] args) {

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

myNumbers[1][2] = 9;

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

public class Main {

public static void main(String[] args) {

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

}
}

public class Main {

public static void main(String[] args) {

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

for (int[] row : myNumbers) {

for (int i : row) {

System.out.println(i);

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() {

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

public static void main(String[] args) {

myMethod();

public class Main {

static void myMethod() {

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

public static void main(String[] args) {

myMethod();
myMethod();

myMethod();

Java Method Parameters


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.

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

}
}

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

A Method with If...Else


public class Main {

// Create a checkAge() method with an integer parameter 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

}
Java Return

public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

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

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

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

}
Java Method Overloading

public class Main {

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

}
public class Main {

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

Method Scope
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 {}.

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 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.
public class Main {

public static void main(String[] args) {

int result = sum(10);

System.out.println(result);

public static int sum(int k) {

if (k > 0) {

return k + sum(k - 1);

} else {

return 0;

public class Main {

public static void main(String[] args) {

int result = sum(5, 10);

System.out.println(result);

}
public static int sum(int start, int end) {

if (end > start) {

return end + sum(start, end - 1);

} else {

return end;

Java User Input (Scanner)

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


}
}

import java.util.Scanner;

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

System.out.println("Enter name, age and salary:");

// String input
String name = myObj.nextLine();

// Numerical input
int age = myObj.nextInt();
double salary = myObj.nextDouble();

// Output input by user


System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Salary: " + salary);
}
}
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

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;

public static void main(String[] args) {

Main myObj = new Main();

System.out.println(myObj.x);

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

}
Java Class Attributes
In the previous chapter, 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:

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:

public class Main {

int x;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 40;

System.out.println(myObj.x);

public class Main {

int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // x is now 25

System.out.println(myObj.x);

}
}

public class Main {

final int x = 10;

public static void main(String[] args) {

Main myObj = new Main();

myObj.x = 25; // will generate an error

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:

public class Main {

int x = 5;

public static void main(String[] args) {

Main myObj1 = new Main();

Main myObj2 = new Main();

myObj2.x = 25;

System.out.println(myObj1.x);

System.out.println(myObj2.x);

}
Multiple Attributes
You can specify as many attributes as you want:

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

}
Java Class Methods
You learned from the Java Methods chapter that methods are declared within a
class, and that they are used to perform certain actions:

public class Main {

static void myMethod() {

System.out.println("Hello World!");

public static void main(String[] args) {

myMethod();

}
Static vs. Public
You will often see Java programs that have either static or public attributes and
methods.

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:

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

Access Methods With an Object

// Create a Main class

public class Main {

// Create a fullThrottle() method

public void fullThrottle() {

System.out.println("The car is going as fast as it can!");

// Create a speed() method and add a parameter

public void speed(int maxSpeed) {

System.out.println("Max speed is: " + maxSpeed);

// Inside main, call the methods on the myCar object


public static void main(String[] args) {

Main myCar = new Main(); // Create a myCar object

myCar.fullThrottle(); // Call the fullThrottle() method

myCar.speed(200); // Call the speed() method

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:

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

Constructor Parameters
Constructors can also take parameters, which is used to initialize attributes.

The following example adds an int y parameter to the constructor. Inside the
constructor we set x to y (x=y). When we call the constructor, we pass a
parameter to the constructor (5), which will set the value of x to 5:

public class Main {

int x;

public Main(int y) {

x = y;

public static void main(String[] args) {

Main myObj = new Main(5);

System.out.println(myObj.x);

}
}

//filename: Main.java

public class Main {

int modelYear;

String modelName;

public Main(int year, String name) {

modelYear = year;

modelName = name;

public static void main(String[] args) {

Main myCar = new Main(1969, "Mustang");

System.out.println(myCar.modelYear + " " + myCar.modelName);

}
Modifiers
By now, you are quite familiar with the public keyword that appears in almost all
of our examples:

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

MAIN CLASS

public class Main {

public String fname = "John";

public String lname = "Doe";

public String email = "[email protected]";

public int age = 24;

Second class

class Second {

public static void main(String[] args) {

Main myObj = new Main();

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

System.out.println("Email: " + myObj.email);


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

Abstract
An abstract method belongs to an abstract class, and it does not have a body.
The body is provided by the subclass:

MAIN CLASS

class Second {

public static void main(String[] args) {

Main myObj = new Main();

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

System.out.println("Email: " + myObj.email);

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

Second Class

class Second {

public static void main(String[] args) {


// create an object of the Student class (which inherits attributes and
methods from Main)

Student myObj = new Student();

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

System.out.println("Email: " + myObj.email);

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

System.out.println("Graduation Year: " + myObj.graduationYear);

myObj.study(); // call abstract method

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

}
}

Static
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

Java Encapsulation

You might also like