JAVA(DS & AI)
JAVA(DS & AI)
What is Java?
Java is a popular programming language, created in 1995.
It is used for:
Java Quickstart
In Java, every application begins with a Class Name, and that class must match the
Filename. A class should always start with an uppercase first letter.
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
Main.java
public class Main {
System.out.println("Hello World");
we created a Java file called Main.java, and we used the following code to print
"Hello World" to the screen.
Any code inside the main() method will be executed. just remember that every Java
program has a class name which must match the filename, and that every
program must contain the main() method.
System.out.println()
Inside the main() method, we can use the println() method to print a line of text
to the screen:
System.out.println("Hello World");
Note: The curly braces {} marks the beginning and the end of a block of code.
System is a built-in Java class that contains useful members, such as out, which is
short for "output". The println() method, short for "print line", is used to print a
value to the screen (or a file).
We should also note that each code statement must end with a semicolon (;).
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 single line comment
System.out.println("Hello World");
Example
/* The code below will print the words Hello World
System.out.println("Hello World");
Java Variables
Variables are containers for storing data values.
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
Syntax
type variableName = value;
Where type is one of Data types (such as int or String), and variableName is the
name of the variable (such as x or name). The equal sign is used to assign values
to the variable.
To create a variable that should store text, look at the following example:
Example
Create a variable called name of type String and assign it the value
“john”:
System.out.println(name);
To create a variable that should store a number, We can also declare a variable
without assigning the value, and assign the value later. look at the following
example:
System.out.println(myNum);
int myNum; //without assigning the value
myNum = 15;
System.out.println(myNum);
Note that if we assign a new value to an existing variable, it will overwrite the previous
value:
Example
Change the value of myNum from 15 to 20:
System.out.println(myNum);
Final Variables
If we don't want others to overwrite existing values, use the final keyword (this
will declare the variable as "final" or "constant", which means unchangeable and
read-only):
Other Types
A demonstration of how to declare variables of other types:
Example
int myNum = 5;
float myFloatNum = 5.99f;
Example
Java Operators
Operators are used to perform operations on variables and values. In the example
below, we use the + operator to add two values:
Example
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:
Example
Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.
In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:
Example
int x = 10;
= 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
The return value of a comparison is either true or false. These values are known
as Boolean values
In the following example, we use the greater than operator (>) to find out if 5 is greater
than 3:
Example
int x = 5;
int y = 3;
== Equal to x == y
!= Not equal x != y
&& Logical and Returns true if both statements are true x < 5 && x < 10
! Logical not Reverse the result, returns false if the result is !(x < 5 && x < 10)
true
Java Conditional Statement :
Java has the following conditional statements:
The if Statement
Use the if statement to specify a block of Java code to be executed if a condition
is true.
Syntax
if (condition) {
In the example below, we test two values to find out if 20 is greater than 18. If the
condition is true, print some text:
Example
Example
int x = 20;
int y = 18;
if (x > y) {
Example explained
In the example above we use two variables, x and y, to test whether x is greater
than y (using the > operator). As x is 20, and y is 18, and we know that 20 is greater
than 18, we print to the screen that "x is greater than y".
Syntax
if (condition) {
} else {
Example
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
Example explained
In the example above, time (20) is greater than 18, so the condition is false.
Because of this, we move on to the else condition and print to the screen "Good
evening". If the time was less than 18, the program would print "Good day".
Syntax
if (condition1) {
} else if (condition2) {
} else {
Example
System.out.println("Good morning.");
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
In the example above, time (22) is greater than 10, so the first condition is false.
The next condition, in the else if statement, is also false, so we move on to
the else condition since condition1 and condition2 is both false - and print to
the screen "Good evening".
However, if the time was 14, our program would print "Good day."
Ternary Operator :
There is also a short-hand if else, which is known as the ternary operator because
it consists of three operands.
It can be used to replace multiple lines of code with a single line, and is most often
used to replace simple if else statements:
Syntax
Instead of writing:
Example
System.out.println("Good day.");
} else {
System.out.println("Good evening.");
}
Example
System.out.println(result);
Syntax
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
This is how it works:
The switch expression is evaluated once.
The value of the expression is compared with the values of each case.
If there is a match, the associated block of code is executed.
The break and default keywords are optional, and will be described later
in this chapter
The example below uses the weekday number to calculate the weekday name:
Example
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;
A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.
Example
int day = 4;
switch (day) {
case 6:
System.out.println("Today is Saturday");
break;
case 7:
System.out.println("Today is Sunday");
break;
default:
Note that if the default statement is used as the last statement in a switch block, it
does not need a break.
Java 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.
While Loop
The while loop loops through a block of code as long as a specified condition
is true:
Syntax
while (condition) {
In the example below, the code in the loop will run, over and over again, as long as
a variable (i) is less than 5:
Example
int i = 0;
while (i < 5) {
System.out.println(i);
i++;
Note: Do not forget to increase the variable used in the condition, otherwise the
loop will never end!
Syntax
do {
while (condition);
The example below uses a do/while loop. The loop will always be executed at least
once, even if the condition is false, because the code block is executed before the
condition is tested:
Example
int i = 0;
do {
System.out.println(i);
i++;
Do not forget to increase the variable used in the condition, otherwise the loop will
never end!
For Loop
When we know exactly how many times we want to loop through a block of code,
use the for loop instead of a while loop:
Syntax
Statement 1 is executed (one time) before the execution of the code block.
Statement 2 defines the condition for executing the code block.
Statement 3 is executed (every time) after the code block has been
executed. The example below will print the numbers 0 to 4:
Example
System.out.println(i);
}
Example explained
Another Example
This example will only print even values between 0 and 10:
Example
System.out.println(i);
Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
// Outer loop
// Inner loop
Example
// code to be executed
Example Explained
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:
Example
myMethod();
Example
myMethod();
myMethod();
myMethod();
Example
myMethod("Liam");
myMethod("Jenny");
myMethod("Anja");
OUTPUT
// Liam Refsnes
// Jenny Refsnes
// Anja Refsnes
When a parameter is passed to the method, it is called an argument. So, from the
example above: fname is a parameter, while Liam, Jenny and Anja are
arguments.
Multiple Parameters
We can have as many parameters as we like:
Example
myMethod("Liam", 5);
myMethod("Jenny", 8);
myMethod("Anja", 31);
OUTPUT
// Liam is 5
// Jenny is 8
// Anja is 31
Note that when we are working with multiple parameters, the method call must have
the same number of arguments as there are parameters, and the arguments must be
passed in the same order.
Return Values
The void keyword, used in the examples above, indicates that the method should
not return a value. If we want the method to return a value, we can use a primitive
data type (such as int, char, etc.) instead of void, and use the return keyword
inside the method:
Example
return 5 + x;
System.out.println(myMethod(3));
// Outputs 8 (5 + 3)
Example
return x + y;
System.out.println(myMethod(5, 3));
// Outputs 8 (5 + 3)
We can also store the result in a variable (recommended, as it is easier to read and
maintain):
Example
return x + y;
System.out.println(z);
// Outputs 8 (5 + 3)
Example
} else {
}
public static void main(String[] args) {
Method Overloading
With method overloading, multiple methods can have the same name with different
parameters:
Example
int myMethod(int x)
float myMethod(float x)
Consider the following example, which has two methods that add numbers of
different type:
Example
return x + y;
return x + y;
} // Note – Multiple methods can have the same names as long as the number and / or
type of parameters are different.
Java Arrays
Definition - List of Elements of the same type (Ex - 1 to 9, fruits etc), placed in a
contiguous memory location.
Arrays are used to store multiple values in a single variable, instead of declaring separate
variables for each value. To declare an array, define the variable type with square
brackets:
String[] cars;
We have now declared a variable that holds an array of strings. To insert values to it, you
can place the values in a comma-separated list, inside curly braces:
Example
System.out.println(cars[0]);
// Outputs Volvo
Note: Array indexes start with 0: [0] is the first element. [1] is the second element, etc.
Array Length
To find out how many elements an array has, use the length property:
Example
System.out.println(cars.length);
// Outputs 4
Example
System.out.println(marks[i]);
There are various sorting algorithms that can be used to complete this operation. And,
we can use any algorithm based on the requirement.
2. Starting from the first index, compare the first and the second elements.
3. If the first element is greater than the second element, they are swapped.
4. Now, compare the second and the third elements. Swap them if they are not in
order.
5. The above process goes on until the last element.
2. Remaining Iteration
After each iteration, the largest element among the unsorted elements is placed at the
end.
In each iteration, the comparison takes place up to the last unsorted element.
The array is sorted when all the unsorted elements are placed at their correct positions.
a[i] = a[j];
a[j] = temp;
System.out.println(a[i]);
sorting(a);