JAVA
Full Java Tutorial
Java is an open-source, class-based, high-level, object-oriented programming language. Java is platform independent as the Java programs are compiled into byte code that are platform independent.
History:
Java programming language was created by James Gosling in 1995. The original idea was to design a language for the television industry. Gosling worked along with his team also called the Green Team and the project they worked on was called Greentalk. This project was later named as OAK. The name OAK has its roots to the oak tree that stood outside Gosling's office. This name had to be drooped later as it was already a trademark by Oak Technologies.
So how was the name Java suggested?
Since the language could no longer be named OAK, Gosling and his team had to come up with new name. The team considered various names like DNA, RUBY, JAVA, JOLT DYNAMIC, REVOLUTIONARY, SILK. But the name had to unique and quite easy to say. The name Java occurred in gosling's mind while having a cup of coffee at his office.
Types of Java Applications:
1.> Web Application:
Web Application are the applications that run on web browser using servlet, JSP, struts technologies. These technologies create Java web applications and deploy them on server. create Java web applications and deploy them on server.
2.> Mobile Application:
These are mobile applications created using Java.
3.> Standalone Application:
Standalone applications are executed by themselves without the need of other programs and files. Example of such an application is antivirus.
4.> Enterprise Application:
Some applications are designed for corporate organizations with the intent to control major process in real time. Such application are called enterprise application.
Features of Java:
1. Object Oriented
2. Simple
3. Robust
4. Multithread
5. Platform Independent
6. Secure
7. Portable
8. High Performance
9. Distributed
10. Dynamic
11. Architecture
Object Oriented: In object oriented programming everything is an object rather that function and logic.
Simple: Java is simple to understand, easy to learn and implement.
Secured: It is possible to design secured software systems using Java.
Platform Independent: Java is write once and run anywhere language, meaning once the code is written, it can be executed on any software and hardware systems.
Portable: Java is not necessarily fixated to a single hardware machine. Once created, java code can be used on any platform.
Architecture Neutral: Java is architecture neutral meaning the size of primitive type is fixed and does not vary depending upon the type of architecture.
Robust: Java emphasizes a lot on error handling, type checking, memory management, etc. This makes it a robust language.
Interpreted: Java converts high-level program statement into Assembly Level Language, thus making it interpreted.
Distributed: Java lets us create distributed applications that can run on multiple computers simultaneously.
Dynamic: Java is designed to adapt to ever evolving systems thus making it dynamic.
Multi-thread: multi-threading is an important feature provided by java for creating web applications.
High-performance: Java uses Just-In-Time compiler thus giving us a high performance.
** What is JVM:-
JVM stands for Java Virtual Machine. It is a virtual machine that provides a runtime environment to execute java bytecode. . The Java program is converted into java bytecode which can be than understood by the CPU to get the output.
** What is JRE:-
JRE stands for Java Runtime Environment. It's provides java libraries, the JVM and other files and documents that are needed to run java application.
** What is JDK:-
JDK stands for Java Development Kit. It is a superset of JRE and is used to create java applications. There are three JDK provided by Oracle, Java Enterprise Edition, Java Standard Edition and Mobaile Edition.
Basic Java Syntax:-
package syntax1;
public class DEtails {
public static void main(String[] args) {
System.out.println("HELLO REHAN");
}
}
OUTPUT:- HELLO REHAN
Java Comments:-
Comments in any programming language are ignored by the compiler or the interpreter. A comment is a part of the coding file that the programmer does not want to execute, rather the programmer uses it to either explain a block of code or to avoid the execution of a specific part of code while testing.
There are two types of comments:
1. Single-line comment (//)
2. Multi-line comment (/* .......*/)
There are two forms of datatypes in Java:
Data Type
Size
Range
bool
1 bit
true, false
char
2 byte
a….z, A….Z
byte
1 byte
-27 to 27-1
-128 to 128
short
2 byte
-215 to 215-1
-32768 to 32767
int
4 byte
-231 to 231-1
-2,147,483,648 to 2,147,483,647
long
8 byte
-263 to 263-1
-9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
float
4 byte
6.022f
double
8 byte
3.142
Java Variables:-
Variables are containers that store information that can be manipulated and referenced later by the programmer within the code. Java variables have a data type associated with them which can tell us about the size and layout of the variable's memory.
datatype variable = value
There are three types of variables
A. Local Variable
B. Instance Variable
C. Class/Static Variable
A. Local Variables:
A variable that is declared inside the body of the method or constructor is called a local variable. It is called so because the extent of a local variable lies only within the method or constructor within which it is created and other methods in the class cannot access it.
Inside the method body, local variable is declared using the static keyword.
Example:
public class variableType {
public void localVariable() {
String name = "Ben";
int marks = 95;
System.out.println(name + " Scored " + marks + "%.");
}
public static void main(String[] args) {
variableType vt = new variableType();
vt.localVariable();
}
}
Copy
Output:
Ben Scored 95%.
Copy
If it is accessed outside the method or constructor within which it is creaed, then it give an error.
Example:
public class variableType {
public void localVariable() {
String name = "Ben";
int marks = 95;
}
public void notLocalVariable() {
System.out.println(name + " Scored " + marks + "%.");
}
public static void main(String[] args) {
variableType vt = new variableType();
vt.notLocalVariable();
}
}
Copy
Output:
name cannot be resolved to a variable
marks cannot be resolved to a variable
Copy
B. Instance Variables:
An instance variable is declared inside the class but outside a method or a constructor. It is similar to a static variable except that it is declared without using the keyword static. These variables are accessible by all methods or constructors that are inside the class.
Example:
public class variableType {
public String name = "Ben";
public int marks = 95;
public void instanceVariable() {
System.out.println(name + " Scored " + marks + "%.");
}
public static void main(String[] args) {
variableType vt = new variableType();
vt.instanceVariable();
}
}
Copy
Output:
Ben Scored 95%.
Copy
C. Class/Static Variables:
An static variable is declared inside the class but outside a method or a constructor. It is similar to a instance variable except that it is declared using the keyword static. These variables are accessible by all methods or constructors that are inside the class.
Example:
public class variableType {
public static String name;
public static int marks;
public static void main(String[] args) {
name = "Ben";
marks = 95;
System.out.println(name + " Scored " + marks + "%.");
}
}
Copy
Output:
Ben Scored 95%.
Copy
If variable is not declared static the it gives an error.
Example:
public class variableType {
public String name;
public int marks;
public static void main(String[] args) {
name = "Ben";
marks = 95;
System.out.println(name + " Scored " + marks + "%.");
}
}
Copy
Output:
Cannot make a static refrence to a non-static field
Java has different types of operators for different operations. They are as follows:
Arithmetic operators:
Arithmetic operators are used to perform arithmetic/mathematical operations.
Name
Operator
Example
Addition
+
a+b
Subtraction
-
a-b
Multiplication
*
a*b
Division
/
a/b
Modulus
%
a%b
Increment
++
a++ or b++
Decrement
--
a-- or b--
Assignment operators:
These operators are used to assign values to variables.
Name
Operator
Evaluated As
Assignment
=
a=b
Addition assignment
+=
a+=b or a=a+b
Subtraction assignment
-=
a-=b or a=a-b
Multiplication assignment
*=
a*=b or a=a*b
Division assignment
/=
a//=b or a=a//b
Modulus assignment
%=
a%=b or a=a%b
Bitwise AND assignment
&=
a&=b or a=a&b
Bitwise inclusive OR assignment
|=
a|=b or a=a|b
Bitwise exclusive OR assignment
^=
a^=b or a=a^b
Right Shift assignment
>>=
a>>=b or a=a>>b
Left Shift assignment
<<=
a<<=b or a=a<<b
Bitwise operators:
Bitwise operators are used to deal with binary operations.
Name
Operator
Example
Bitwise AND
&
a & b
Bitwise OR
|
a | b
Bitwise NOT
~
~a
Bitwise XOR
^
a ^ b
Bitwise right shift
>>
a>>
Bitwise left shift
<<
b<<
Unsigned right shift
>>>
a>>>
Comparison operators:
These operators are used to compare values.
Name
Operator
Example
Equal
==
a==b
Not Equal
!=
a!=b
Less Than
<
a>b
Greater Than
>
a<b
Less Than or Equal to
<=
a>=b
Greater Than or Equal to
>=
a<=b
Logical operators:
These operators are used to deal with logical operations.
Name
Operator
Example
AND
&&
a && b
OR
||
a || b
NOT
!
! (a=2 or b=3)
Other operators:
A. Instanceof operator:
This operator checks if an object is an instance of class.
Example:
class Main {
public static void main(String[] args) {
Integer number = 5;
boolean res;
if (res = number instanceof Integer){
System.out.println("number is an object of Integer. Hence: " + res);
} else {
System.out.println("number is not an object of Integer.Hence: " + res);
}
}
}
Copy
Output:
number is an object of Integer. Hence: true
Copy
B. Conditional operator:
It is used in a single line if-else statement.
Example:
class Main {
public static void main(String[] args) {
Integer number = 3;
String res;
res = (number > 5) ? "number greater than five" : "number lesser than five";
System.out.println(res);
}
}
Copy
Output:
number lesser than five
User Input/Output
Taking Input:
To use the Scanner class, we need to import the java.util.Scanner package.
import java.util.Scanner;
Copy
Now the Scanner class has been imported. We create an object of the Scanner class to use the methods within it.
Scanner sc = new Scanner(System.in)
Copy
The System.in is passed as a parameter and is used to take input.
Note: Your object can be named anything, there is no specific convention to follow. But we normally name our object sc for easy use and implementation.
There are four ways to create an object of the scanner class. Let us see how we can create Scanner objects:
A. Reading keyboard input:
Scanner sc = new Scanner(System.in)
Copy
B. Reading String input:
Scanner sc = new Scanner(String str)
Copy
C. Reading input stream:
Scanner sc = new Scanner(InputStream input)
Copy
D. Reading File input:
Scanner sc = new Scanner(File file)
Copy
So how does a Scanner class work?
The scanner object reads the entered inputs and divides the string into tokens. The tokens are usually divided based upon whitespaces and newline.
Example:
Susan
19
78.95
O
Copy
The above input will be divided as “Susan”, “19”, “78.95” and “O”. Then the Scanner object will iterate over each token and then it will read each token depending upon the type of Scanner object created.
Now, we have seen how Scanner object is created, different ways to create it, how it reads input, and how it works. Let us see different methods to take inputs.
Below are the methods that belong to the scanner class:
Method
Description
nextLine()
Accepts string value
next()
Accept string till whitespace
nextInt()
Accepts int value
nextFloat()
Accepts float value
nextDouble()
Accepts double value
nextLong()
Accepts long value
nextShort()
Accepts short value
nextBoolean()
Accepts Boolean value
nextByte()
Accepts Byte value
Example:
import java.util.Scanner;
public class ScannerExample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Name, RollNo, Marks, Grade");
String name = sc.nextLine(); //used to read line
int RollNo = sc.nextInt(); //used to read int
double Marks = sc.nextDouble(); //used to read double
char Grade = sc.next().charAt(0); //used to read till space
System.out.println("Name: "+name);
System.out.println("Gender: "+RollNo);
System.out.println("Marks: "+Marks);
System.out.println("Grade: "+Grade);
sc.close();
}
}
Copy
Output:
Enter Name, RollNo, Marks, Grade
Rehan
19
87.25
A
Name: Rehan
Gender: 19
Marks: 87.25
Grade: A
Copy
Entering the wrong type of input, or just messing up with the order of inputs in the above example will give an error.
For same example when we change the order of inputs it gives the following output:
Enter Name, RollNo, Marks, Grade
Rajesh
Joshi
Exception in thread "main" java.util.InputMismatchException
at java.base/java.util.Scanner.throwFor(Scanner.java:939)
at java.base/java.util.Scanner.next(Scanner.java:1594)
at java.base/java.util.Scanner.nextInt(Scanner.java:2258)
at java.base/java.util.Scanner.nextInt(Scanner.java:2212)
at javaFiles/FileHandling.ScannerExample.main(ScannerExample.java:14
if Statement
Decision-making involves evaluating a condition to a Boolean value and making a decision based on it. The basic idea revolves around executing the block of code whose condition evaluates to true. Below are the types of decision-making statements:
if statement:
In a simple if statement, a block of code inside the if statement is only executed if the condition evaluates to true.
Syntax:
if (condition) {
//block of code
}
e.g.1
public class JavaIf {
public static void main(String[] args) {
String name = "Rehan ";
int Roll = 25;
if (name == "Rehan" && Roll == 25) {
System.out.println("Details of Rehan.");
}
}
}
Copy
Output:
Details of Rehan.
Copy
if…..else Statement
Recommended by LinkedIn
In an if…..else statement we have two blocks of code, wherein the former block of code (code inside if statement) is executed if condition evaluates to true and the later block of code (code inside else statement) is executed if the condition is false.
Syntax:
if (condition) {
//block of code
} else {
//block of code
}
Copy
Example:
public class JavaIf {
public static void main(String[] args) {
String name = "Rehan";
int Roll = 25;
if (name == "Rehan" && Roll == 26) {
System.out.println("Details of Rehan.");
} else {
System.out.println("Invalid details.");
}
}
}
Copy
Output:
Invalid details.
if…..else if Statement
But what if we have more than two blocks of code? And what if we need to check which block of code evaluates to true? Well here we use an if…..else if statement.
if……else if statements allows us to check multiple expressions and enter the block of code where the condition evaluates to true.
Syntax:
if (condition 1) {
//block of code
} else if (condition 2) {
//block of code
} else if (condition 3) {
//block of code
} else if (condition 4) {
//block of code
} else {
//if no condition matches
//block of code
}
Copy
Example:
public class JavaIf {
public static void main(String[] args) {
String name[] = {"Mohan", "Rohan", "Soham"};
int Roll[] = {25, 36, 71};
if (name[0] == "Mohan" && Roll[1] == 25) {
System.out.println("Details of Mohan.");
} else if (name[2] == "Rohan" && Roll[1] == 36) {
System.out.println("Details of Rohan.");
} else if (name[2] == "Soham" && Roll[2] == 71) {
System.out.println("Details of Soham.");
} else {
System.out.println("Invalid details.");
}
}
}
Copy
Output:
Details of Soham.
Nested if Statements
if statements inside other if statements are called nested if statements.
Example:
public class Nested {
public static void main(String[] args) {
String name = "Mohan";
int Roll = 25;
int marks = 85;
if (name == "Mohan" && Roll == 25) {
if (marks > 35) {
System.out.println("Mohan has been promoted to next class.");
} else {
System.out.println("Mohan needs to give re-exam.");
}
}
}
}
Copy
Output:
Mohan has been promoted to next class.
switch case Statements
In a switch statement, a block of code is executed from many based on switch case.
Syntax:
switch (expression) {
case value1:
// code
break;
case value2:
// code
break;
...
...
default:
// default statements
}
Copy
Example:
public class JavaSwitch {
public static void main(String[] args) {
String day = "Wednesday";
switch (day) {
case "Sunday":
System.out.println("Today is Sunday");
break;
case "Monday":
System.out.println("Today is Monday");
break;
case "Tuesday":
System.out.println("Today is Tuesday");
break;
case "Wednesday":
System.out.println("Today is Wednesday");
break;
case "Thursday":
System.out.println("Today is Thursday");
break;
case "Friday":
System.out.println("Today is Friday");
break;
case "Saturday":
System.out.println("Today is Saturday");
break;
}
}
}
Copy
Output:
Today is Wednesday
for Loop
Loops in any programming language are used to execute a block of code again and again until a base condition is achieved. As soon as a base condition is satisfied the loop is terminated and the control is returned to the main body of the program.
There are three types of loops in java:
for loop:
Whenever a loop needs to be run a specific number of times, we use a for loop.
Syntax:
for (initializeVariable, testCondition, increment/decrement){
//block of code
}
Copy
Example:
public class ForLoop1 {
public static void main(String[] args) {
for(int i=1; i<=10; i++) {
System.out.println("2 * "+ i+ " = "+ 2*i);
}
}
}
Copy
Output:
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
2 * 5 = 10
2 * 6 = 12
2 * 7 = 14
2 * 8 = 16
2 * 9 = 18
2 * 10 = 20
Copy
We also have a special syntax for iterating through arrays and other collection objects, also called as a for-each loop.
Syntax:
for (type variable : collectionObject){
//block of code
}
Copy
Example:
public class ForEach1 {
public static void main(String[] args) {
int[] prime = {1,3,5,7,11,13,17,19};
System.out.println("Prime numbers are:");
for(int i : prime) {
System.out.println(i);
}
}
}
Copy
Output:
Prime numbers are:
1
3
5
7
11
13
17
19
Copy
And lastly we have an infinite for loop, wherein the expression always evaluates to true, hence running indefinitely.
Example:
public class ForLoop1 {
public static void main(String[] args) {
for(int i=1; i<=10; i--) {
System.out.println(i);
}
}
}
Copy
Output:
-3832975
-3832976
-3832977
-3832978
-3832979
-3832980
-3832981
-3832982
-3832983
-3832984
-3832985
.
.
.
.
Copy
The loop will keep on running until you halt the program.
while Loop
Whenever we are not sure about the number of times the loop needs to be run, we use a while loop. A while loop keeps on running till the condition is true, as soon as the condition is false, control is returned to the main body of the program.
Syntax:
while (baseBooleanCondition) {
//block of code
}
Copy
baseBooleanCondition: it checks if the condition is true or false after each iteration. If true, run block of code. If false, terminate the loop.
Example:
public class WhileLoop {
public static void main(String[] args) {
int i = 10;
while (i>0) {
System.out.println(i);
i--;
}
}
}
Copy
Output:
10
9
8
7
6
5
4
3
2
1
do-while Loop
A do…..while loop is a special kind of loop that runs the loop at least once even if the base condition is false. This is because the base condition in this loop is checked after executing the block of code. As such, even if the condition is false, the loop is bound to run atleast once. Hence, do…..while loop is also called as an Exit Control Loop.
Syntax:
do {
//block of code
} while (baseBooleanCondition);
Copy
Example 1:
public class WhileLoop {
public static void main(String[] args) {
int i = 10;
do {
System.out.println(i);
i--;
} while (i>0);
}
}
Copy
Output:
10
9
8
7
6
5
4
3
2
1
Copy
Example 2:
public class WhileLoop {
public static void main(String[] args) {
int i = 10;
do {
System.out.println(i);
i--;
} while (i>10);
}
}
Copy
Output:
10
Copy
As we can see, even if condition is false, the loop runs at least once.
Nested Loops
Loops inside other loops are called nested loops.
Example:
public class Nested {
public static void main(String[] args) {
for (int i=1; i<5; i++) {
for (int j=1; j<5; j++) {
System.out.println(i+" * "+j+" = "+i*j);
}
System.out.println();
}
}
}
Copy
Output:
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
1 * 4 = 4
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
2 * 4 = 8
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
3 * 4 = 12
4 * 1 = 4
4 * 2 = 8
4 * 3 = 12
4 * 4 = 16
break/continue Statement
break statement
In java, break statement is used when working with any kind of a loop or a switch statement. It breaks out of the loop or a switch statement and returns the control to the main body of the program. In the case of nested loops, it breaks the inner loop and control is returned to the outer loop.
Example:
public class JavaBreak {
public static void main(String[] args) {
for(int n=1; n<=20; n++) {
if(n%2 == 0) {
System.out.println(n);
if (n == 12) {
break;
}
}
}
}
}
Copy
Output:
2
4
6
8
10
12
Copy
continue statement
The continue statement breaks the current iteration in the loop, if a specified condition occurs, moves to the end of the loop, and continues with the next iteration in the loop.
Example:
public class JavaContinue {
public static void main(String[] args) {
for(int n=1; n<=20; n++) {
if(n%2 == 0) {
if (n == 12) {
continue;
}
System.out.println(n);
}
}
}
}
Copy
Output:
2
4
6
8
10
14
16
18
20
String Basics
Strings in java is a sequence of characters that Is enclosed in double quotes. Whenever java comes across a String literal in the code, it creates a string literal with the value of string.
Example:
public class string {
public static void main(String[] args) {
String name;
name = "Diablo";
System.out.println("My name is " + name);
}
}
Copy
Output:
My name is Diablo
Copy
The same can be done using an array of characters.
Example:
public class string {
public static void main(String[] args) {
char[] name = {'D', 'i', 'a', 'b', 'l', 'o'};
String welcomeMsg = new String(name);
System.out.println("Welcome " + welcomeMsg);
}
}
Copy
Output:
Welcome Diablo
Copy
Concatenate Strings:
Concatenation between two strings in java is done using the + operator.
Example:
public class string {
public static void main(String[] args) {
String fname, lname;
fname = "Diablo";
lname = "Ramirez";
System.out.println(fname + " " + lname);
}
}
Copy
Output:
Diablo Ramirez
Copy
Alternatively, we can use the concat() method to concatenate two strings.
Example:
public class string {
public static void main(String[] args) {
String fname, lname;
fname = "Diablo";
lname = " Ramirez";
System.out.println(fname.concat(lname));
}
}
Copy
Output:
Diablo Ramirez
Copy
What if we concatenate string with an integer?
Well concatenating a string and an integer will give us a string.
Example:
public class string {
public static void main(String[] args) {
String name;
int quantity;
quantity = 12;
name = " Apples";
System.out.println(quantity + name);
}
}
Copy
Output:
12 Apples
Escape Characters
Try running the code given below in your java compiler.
public class string {
public static void main(String[] args) {
System.out.println("He said, "I believe that the Earth is Flat".");
}
}
Copy
As we can see that the code gives an error. This is because the compiler assumes that the string ends after the 2nd quotation mark.
This can be solved by using ‘\’ (backslash). Backslash acts as an escape character allowing us to use quotation marks in strings.
Example:
public class string {
public static void main(String[] args) {
System.out.println("He said, \"I believe that the Earth is Flat\".");
System.out.println("she said, \'But the Earth is spherical\'.");
}
}
Copy
Output:
He said, "I believe that the Earth is Flat".
she said, 'But the Earth is spherical'.
Copy
Similarly to use a backslash in the string we must escape it with another backslash.
Example:
public class string {
public static void main(String[] args) {
System.out.println("The path is D:\\Docs\\Java\\Strings");
}
}
Copy
Output:
The path is D:\Docs\Java\Strings
Copy
We also have an escape character for printing on a new line(\n), inserting a tab(\t), backspacing(\b), etc.
Example:
public class string {
public static void main(String[] args) {
System.out.println("My name is Anthony. \nI'm an Artist.");
System.out.println();
System.out.println("Age:\t18");
System.out.println("Addresss\b: Washington DC");
}
}
Copy
Output:
My name is Anthony.
I'm an Artist.
Age: 18
Address: Washington DC
String Methods
Here we will see some of the popular methods we can use with strings.
length(): This method is used to find the length of a string.
Example:
public class string {
public static void main(String[] args) {
String quote = "To be or not to be";
System.out.println(quote.length());
}
}
Copy
Output:
18
Copy
indexOf(): This method returns the first occurrence of a specified character or text in a string.
Example:
public class string {
public static void main(String[] args) {
String quote = "To be or not to be";
System.out.println(quote.indexOf("be")); //index of text
System.out.println(quote.indexOf("r")); //index of character
}
}
Copy
Output:
3
7
Copy
toLowerCase(): Converts string to lower case characters.
Example:
public class string {
public static void main(String[] args) {
String quote = "THOR: Love and Thunder";
System.out.println(quote.toLowerCase());
}
}
Copy
Output:
thor: love and thunder
Copy
toUpperCase(): Converts string to upper case characters.
Example:
public class string {
public static void main(String[] args) {
String quote = "THOR: Love and Thunder"
System.out.println(quote.toUpperCase());
}
}
Copy
Output:
THOR: LOVE AND THUNDER
Array Basics
An array is a container object that holds a fixed number of values of a single type. We do not need to create different variables to store many values, instead we store them in different indices of the same objects and refer them by these indices whenever we need to call them.
Syntax:
Datatype[] arrayName = {val1, val2, val3,……. valN}
Copy
Note: array indexing in java starts from [0].
There are two types of array in java:
We will see how to perform different operations on both the type of arrays,
A. Length of an array:
Finding out the length of an array is very crucial when performing major operations. This is done using the .length property:
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Chennai"};
int[] numbers = {25,93,48,95,74,63,87,11,36};
System.out.println("Number of Cities: " + cities.length);
System.out.println("Length of Num List: " + numbers.length);
}
}
Copy
Output:
Number of Cities: 5
Length of Num List: 9
Copy
B. Accessing array elements:
Array elements can be accessed using indexing. In java, indexing starts from 0 rather than 1.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Chennai"};
int[] numbers = {25,93,48,95,74,63,87,11,36};
//accessing array elements using indexing
System.out.println(cities[3]);
System.out.println(numbers[2]);
}
}
Copy
Output:
Pune
48
Copy
C. Change array elements:
The value of any element within the array can be changed by referring to its index number.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] cities = {"Delhi", "Mumbai", "Lucknow", "Pune", "Chennai"};
cities[2] = "Bangalore";
System.out.println(cities[2]);
}
}
Copy
Output:
Bangalore
Multidimensional Arrays
We can even create multidimensional arrays i.e. arrays within arrays. We access values by providing an index for the array and another one for the value inside it.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[][] objects = {{"Spoon", "Fork", "Bowl"}, {"Salt", "Pepper"}};
//accessing array elements using indexing
System.out.println(objects[0][2]);
System.out.println(objects[1][1]);
}
}
Copy
Output:
Bowl
Pepper
Copy
We can also print the multi-dimensional array.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
int[][] objects = {{1,2,3}, {4,5,6}};
for (int i = 0; i < objects.length; i++) {
for (int j = 0; j < objects[i].length; j++) {
System.out.print(objects[i][j] + "\t");
}
System.out.println();
}
}
}
Copy
Output:
1 2 3
4 5 6
Copy
Use loops with arrays:
The simplest way of looping through an array is to use a simple for-each loop.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] objects = {"Spoon", "Fork", "Bowl", "Salt", "Pepper"};
for (String i : objects) {
System.out.println(i);
}
}
}
Copy
Output:
Spoon
Fork
Bowl
Salt
Pepper
Copy
Alternatively, you can also use a simple for loop to do the same.
Example:
public class ArrayExample {
public static void main(String[] args) {
//creating array objects
String[] objects = {"Spoon", "Fork", "Bowl", "Salt", "Pepper"};
for (int i = 0; i < objects.length; i++) {
System.out.println(objects[i]);
}
}
}
Copy
Output:
Spoon
Fork
Bowl
Salt
Pepper
Java Methods
Methods or Functions are a block of code that accept certain parameters and perform actions whenever they are called. Methods are always written inside a java class and can be called by simply referring to the method name.
Passing Parameters:
Parameters are nothing but the variables that are passed inside the parenthesis of a method. We can pass a single or more than one parameter of different datatypes inside our method.
Example 1: Passing single parameter
public class MethodExample {
static void Details(String name) {
System.out.println("Welcome " + name);
}
public static void main(String[] args) {
Details("Rehan");
}
}
Copy
Output:
Welcome Rehan
Copy
Example 2: Passing multiple parameters
public class MethodExample {
static void Details(String name, int roll) {
System.out.println("Welcome " + name);
System.out.println("Your roll number is "+ roll);
}
public static void main(String[] args) {
Details"Rehan", 37);
}
}
Copy
Output:
Welcome Rehan
Your roll number is 37
Copy
Example 3: Method with loop
public class MethodIf {
static int Details(int num) {
int fact = 1;
for (int i=2; i<=num; i++) {
fact = fact * i;
}
return fact;
}
public static void main(String[] args) {
System.out.println(Details(3));
System.out.println(Details(4));
System.out.println(Details(5));
}
}
Copy
Output:
6
24
120
Copy
Example 4: Method with control statements
public class Methodloop {
static void Details(int marks) {
if (marks < 35) {
System.out.println("Fail");
} else if (marks >= 35 && marks < 65) {
System.out.println("B grade");
} else if (marks >= 65 && marks < 75) {
System.out.println("A grade");
} else if (marks >= 75 && marks < 100) {
System.out.println("O grade");
} else {
System.out.println("Invalid marks entered");
}
}
public static void main(String[] args) {
Details(25);
Details(90);
Details(60);
}
}
Copy
Output:
Fail
O grade
B grade
Copy
So what can we make out from e.g.3 and e.g.4? In e.g.3, we have created a method without using the void keyword, this lets us return the value inside the method. Whereas in e.g.4, we have created a method using void keyword, this means that our method wont return a value.