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

JAVA(DS & AI)

Java is a widely-used programming language created in 1995, owned by Oracle, and utilized for various applications including mobile, desktop, and web. It is platform-independent, easy to learn, and has a strong community support, making it highly demanded in the job market. The document covers Java basics such as syntax, variables, data types, operators, and control statements, providing essential information for beginners to get started with Java programming.

Uploaded by

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

JAVA(DS & AI)

Java is a widely-used programming language created in 1995, owned by Oracle, and utilized for various applications including mobile, desktop, and web. It is platform-independent, easy to learn, and has a strong community support, making it highly demanded in the job market. The document covers Java basics such as syntax, variables, data types, operators, and control statements, providing essential information for beginners to get started with Java programming.

Uploaded by

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

JAVA (DSA)

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 language 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 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

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.

Note: Java is case-sensitive: "MyClass" and "myclass" has different meaning.

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 {

public static void main(String[] args) {

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.

The main Method


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

public static void main(String[] args)

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

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:

Example
/* 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

Declaring (Creating) Variables


To create a variable, we must specify the type and assign it a value:

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

String name = "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:

int myNum = 15;

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:

int myNum = 15;

myNum = 20; // myNum is now 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):

final int myNum = 15;

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


variale

Other Types
A demonstration of how to declare variables of other types:

Example

int myNum = 5;
float myFloatNum = 5.99f;

char myLetter = 'D';

boolean myBool = true;

String myText = "Hello";

The General Rules for Naming Variables are:


 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 _.
 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

Java Data Types


As we read in the above, a variable in Java must be a specified data type:

Example

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 – String, int, float, boolean and char
 Non-primitive data types - such as Arrays and Classes

Primitive Data Types


A primitive data type specifies the size and type of variable values, and it has no
additional methods.

There are eight primitive data types in Java:

Data Type Size Description

byte 1 byte Stores whole numbers from -128 to 127

short 2 Stores whole numbers from -32,768 to 32,767


bytes

int 4 Stores whole numbers from -2,147,483,648 to 2,147,483,647


bytes

long 8 Stores whole numbers from -9,223,372,036,854,775,808 to


bytes 9,223,372,036,854,775,807

float 4 Stores fractional numbers. Sufficient for storing 6 to 7 decimal digits


bytes

double 8 Stores fractional numbers. Sufficient for storing 15 decimal digits


bytes

boolean 1 bit Stores true or false values


char 2 Stores a single character/letter or ASCII values
bytes

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

int x = 100 + 50;

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

int sum1 = 100 + 50; // 150 (100 + 50)

int sum2 = sum1 + 250; // 400 (150 + 250)

int sum3 = sum2 + sum2; // 800 (400 + 400)

Java divides the operators into the following groups:


 Arithmetic operators
 Assignment operators
 Relational operators
 Logical operators
 Bitwise operators

Arithmetic Operators
Arithmetic operators are used to perform common mathematical operations.

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

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:

Example

int x = 10;

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

Java Relational Operators


Relational operators are used to compare two values (or variables). This is important in
programming, because it helps us to find answers and make decisions.

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;

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

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

Java Logical Operators


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

Operator Name Description Example

&& Logical and Returns true if both statements are true x < 5 && x < 10

|| Logical or Returns true if one of the statements is true x < 5 || x < 4

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

 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

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

// block of code to be executed if the condition is true


}

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

if (20 > 18) {

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

We can also test variables:

Example

int x = 20;

int y = 18;

if (x > y) {

System.out.println("x is greater than 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".

The else Statement


Use the else statement to specify a block of code to be executed if the condition
is false.

Syntax

if (condition) {

// block of code to be executed if the condition is true

} else {

// block of code to be executed if the condition is false

Example

int time = 20;

if (time < 18) {

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

} else {

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

// Outputs "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".

The else if Statement


Use the else if statement to specify a new condition if the first condition is false.

Syntax

if (condition1) {

// block of code to be executed if condition1 is true

} else if (condition2) {

// block of code to be executed if the condition1 is false and


condition2 is true

} else {

// block of code to be executed if the condition1 is false and


condition2 is false

Example

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

// Outputs "Good evening."


Example explained

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

variable = (condition) ? expressionTrue : expressionFalse;

Instead of writing:

Example

int time = 20;

if (time < 18) {

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

} else {

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

we can simply write:

Example

int time = 20;

String result = (time < 18) ? "Good day." : "Good evening.";

System.out.println(result);

Java Switch Statements


Instead of writing many if..else statements, we can use the switch statement.
The switch statement selects one of many code blocks to be executed:

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;

// Outputs "Thursday" (day 4)

The break Keyword


 When Java reaches a break keyword, it breaks out of the switch block.
 This will stop the execution of more code and case testing inside the block.
 When a match is found, and the job is done, it's time for a break. There is no
need for more testing.

A break can save a lot of execution time because it "ignores" the execution of all
the rest of the code in the switch block.

The default Keyword


The default keyword specifies some code to run if there is no case match:

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:

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

// Outputs "Looking forward to the Weekend"

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

// code block to be executed

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!

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.

Syntax

do {

// code block to be executed

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

while (i < 5);

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

for (statement 1; statement 2; statement 3) {

// code block to be executed

 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

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

System.out.println(i);

}
Example explained

 Statement 1 sets a variable before the loop starts (int i = 0).


 Statement 2 defines the condition for the loop to run (i must be less than 5).
If the condition is true, the loop will start over again, if it is false, the loop will
end.
 Statement 3 increases a value (i++) each time the code block in the loop has
been executed.

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

Example

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

System.out.println(i);

Nested Loops
It is also possible to place a loop inside another loop. This is called a nested loop.
The "inner loop" will be executed one time for each iteration of the "outer loop":

Example

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

Java Function / Methods

 A method is a block of code which only runs when it is called.


 We 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 Functions / 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 we can also create wer own methods to perform
certain actions:

Example

Create a method inside Main:

public class Main {

static void myMethod() {

// code to be executed

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.
 void means that this method does not have a return value.

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

Inside main, call the myMethod() method:

public class Main {

static void myMethod() {

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

public static void main(String[] args) {

myMethod();

} // Outputs "I just got executed!"

A method can also be called multiple times:

Example

public class Main {

static void myMethod() {

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

public static void main(String[] args) {

myMethod();

myMethod();

myMethod();

// I just got executed!


// I just got executed!

// I just got executed!

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. We can add
as many parameters as we want, just separate them with a comma.
 The following example has a method that takes a String called fname as
parameter. When the method is called, we pass along a first name, which is used
inside the method to print the full name:

Example

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

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

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

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

public class Main {

static int myMethod(int x) {

return 5 + x;

public static void main(String[] args) {

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

// Outputs 8 (5 + 3)

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

Example

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

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

// Outputs 8 (5 + 3)

We can also store the result in a variable (recommended, as it is easier to read and
maintain):
Example

public class Main {

static int myMethod(int x, int y) {

return x + y;

public static void main(String[] args) {

int z = myMethod(5, 3);

System.out.println(z);

// Outputs 8 (5 + 3)

A Method with If...Else


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

Example

public class Main {

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

public static void checkAge(int age) {

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

if (age < 18) {

System.out.println("Access denied - We are not old enough!");

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

} else {

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

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

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

} // Outputs "Access granted - We are old enough!"

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

Example
int myMethod(int x)

float myMethod(float x)

double myMethod(double x, double y)

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

Example

public static int plusMethodInt(int x, int y) {

return x + y;

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

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

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

To create an array of integers, you could write:

int marks[] = new int[5];

int[] myNum = {10, 20, 30, 40};

Access the Elements of an Array


You can access an array element by referring to the index number. This statement accesses
the value of the first element in cars:

Example

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

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

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

System.out.println(cars.length);

// Outputs 4

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 marks array:

Example

int[] marks = {95, 60, 50, 95, 80};

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

System.out.println(marks[i]);

Q1) Trapping Rainwater


Given n non – negative integers representing an elevation map where
the width of each bar is 1, compute how much water it can trap after
raining.
7
6
5
Height = { 4, 2, 0, 6, 3, 2, 5};
4
3
2
1
0
1 1 1 1 1 1 1
Sorting Algorithm
A sorting algorithm is used to arrange elements of an array/list in a specific order. For
example,

Here, we are sorting the array in ascending order.

There are various sorting algorithms that can be used to complete this operation. And,
we can use any algorithm based on the requirement.

Different Sorting Algorithms


 Bubble Sort
 Selection Sort
 Insertion Sort
 Merge Sort
 Quicksort
Bubble Sort
Bubble sort is a sorting algorithm that compares two adjacent elements and swaps
them until they are in the Ascending/Descending order.

Working of Bubble Sort


Suppose we are trying to sort the elements in ascending order.

1. First Iteration (Compare and Swap)

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

The same process goes on for the remaining iterations.

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.

public class BubbleSort {

public static void sorting(int a[]) {

System.out.println("\nSorted Array: ");

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

for(int j = i+1; j < a.length; j++){

if (a[i] > a[j]) {

int temp = a[i];

a[i] = a[j];

a[j] = temp;

System.out.println(a[i]);

public static void main(String[] args) {

System.out.println("UnSorted Array: ");

int a[] = {5,8,2,3,1};

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


System.out.println(a[i]);

sorting(a);

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy