SlideShare a Scribd company logo
1 of 155
Download to read offline
JAVA
SIMPLIFIED
Understanding Programming
Fundamentals
01
02
Abstract
Introduction
03
04
05
06
Java Basics
Conditional branching
Loops and Nested Loops
Array and multidimensional arrays
Table of
Contents
07 Strings
ABSTRACT
This project introduces an educational
eBook aimed at simplifying Java
programming for beginner students. It
tackles the common challenge of
complex programming concepts by
offering clear explanations and visual
aids. The eBook integrates interactive
examples, quizzes, and step-by-step
guidance to promote active learning.
The project includes content creation,
interactive design, user feedback
iteration, and publication, with
expected outcomes of enhanced
accessibility to Java programming,
increased engagement, improved self-
learning skills, and empowered
students. This resource targets 1st
and 2nd-year university students,
providing a promising foundation for
coding proficiency and expanding career
opportunities.
INTRODUCTION
What is Java?
Java is a versatile programming language with a "write
once, run anywhere" capability, allowing programs to
work on different computers without adjustments.
Its simplicity and user-friendly syntax make it an ideal
choice for beginners and experienced developers.
Java prioritizes safety with built-in features like
sandboxing and automatic memory management, making
it a top choice for secure applications.
Its vibrant developer community provides resources,
tutorials, and support to help users tackle everyday
challenges.
Java is more than just a programming language; it's a
dynamic and flexible platform that has shaped
numerous software applications.
The language began in the early '90s with ambitious
intentions to be a groundbreaking technology for the
digital cable television industry.
The Green Team, a group of brilliant engineers at Sun
Microsystems, was formed to create a programming
language suitable for digital devices like set-top boxes
and televisions.
James Gosling, often celebrated as the father of Java,
was at the heart of Java's development, setting the
stage for one of the most influential programming
languages.
Java's original name was "Oak," inspired by the robust
and enduring qualities of an oak tree.
Over the years, it has evolved to be used in a wide array
of applications, from Windows and web applications to
enterprise and mobile applications.
In 1995, Time magazine recognized Java as one of the Ten
Best Products of the year, a testament to its growing
influence
History of Java...
The name "Java" was chosen during a coffee-infused
discussion, as Java is an island in Indonesia known for
producing the first coffee (Java coffee)Java's journey
continued with its release by James Gosling at Sun
Microsystems in 1995..
Why Java Programming named "Java"?
Features of Java
simple
Its syntax is based on C++, making it a familiar and
reassuring transition for those familiar with C++
. Java also removes complexities like explicit pointers
and operator overloading, streamlining code and
reducing errors. This makes it more welcoming for
beginners and those starting their coding journey.
Portable
Java is portable because it facilitates you to carry
the Java bytecode to any platform. It doesn't
require any implementation.
Java is an object-oriented programming language.
Everything in Java is an object.
Object-oriented programming (OOPs) is a
methodology that simplifies software development
and maintenance by providing some rules.
Object
Class
Inheritance
Polymorphism
Basic concepts of OOPs are:
1.
2.
3.
4.
Object - Oriented
High Performance
Java is faster than other traditional interpreted
programming languages because Java bytecode is
"close" to native code.
It is still a little bit slower than a compiled language
(e.g., C++).
Java is an interpreted language that is why it is
slower than compiled languages, e.g., C, C++, etc.
The English meaning of Robust is strong.
Java is robust because:
It uses strong memory management.
There is a lack of pointers that avoids security
problems.
Java provides automatic garbage collection which
runs on the Java Virtual Machine to get rid of objects
which are not beingused by a Java application
anymore
There are exception handling and the type checking
mechanism in Java.
.
Robust
A thread is like a separate program, executing
concurrently.
We can write Java programs that deal with many
tasks at once by defining multiple threads.
The main advantage of multi-threading is that it
doesn't occupy memory for each thread.
Multi - threaded
JAVA BASICS
class Simple
{
public static void main(String args[])
{
System.out.println("HELLO WORLD");
}
}
Simple Java program:
The output will be: HELLO WORLD
Explanation :
public: Indicates that the main method can be called by any
object or class
static: Specifies that a method doesn't return anything
void: The return type of the main() method
main is the entry point for the program and indicates
where it should start executing..
Strings args[] : It is used for command line argument
(passed at the time of running the java program).
System.out.println() will print the output.
How to print in java :
class Simple
{
public static void main(String args[])
{
System.out.println("WELCOME");
System.out.println("TO");
System.out.println("OUR BOOK");
}
}
The output will be: WELCOME
TO
OUR BOOK
EXAMPLE 1:
class Simple
{
public static void main(String args[])
{
System.out.print("WELCOME");
System.out.print("TO");
System.out.print("OUR BOOK");
}
}
The output will be: WELCOMETOOUR BOOK
EXAMPLE 2:
class Simple
{
public static void main(String args[])
{
System.out.print("WELCOME "+”TO”+” OUR
BOOK”);
}
}
The output will be: WELCOME TO OUR BOOK
EXAMPLE 3:
class Simple
{
public static void main(String args[])
{
System.out.print("WELCOMEnTOnOUR BOOK”);
}
}
The output will be:
EXAMPLE 4:
WELCOME
TO
OUR BOOK
class Simple
{
public static void main(String args[])
{
System.out.print("WELCOMEtTOtOURtBOOK”);
}
}
The output will be:
EXAMPLE 5:
WELCOME TO OUR BOOK
Variables
A variable is fundamental to programming because they
allow developers to store and manipulate data within their
programs.
In Java there are certain rules that we must follow when
naming variables. They are:
Must begin with a letter, dollar sign ($), or underscore
(_): After the first character, you can use letters,
numbers, underscores, and dollar signs.
Cannot be a Java keyword: You cannot use reserved
words like int, double, class, etc., as variable names.
Case-sensitive: Java is case-sensitive, so myVariable
and myvariable would be treated as different variables.
No spaces or special characters (except underscore and
dollar sign): Variable names cannot contain spaces or
most special characters.
CamelCase convention: It's a common convention in Java
to use CamelCase for variable names, especially for
variables representing objects or instances.
Note: Variables of a datatype can only contain data of that
data type
Valid and Invalid Variable Names:
int count; : Valid
double _price; : Valid
String $name; : Valid
int int = 5; : Invalid
int my Variable; : Invalid
Data Types
In programming, a data type is a classification that
specifies which type of value a variable can hold. There
are many data types in Java but we will discuss the
ones we use the most in our book
int
int is the basic 32-bit signed integer datatype.
Eg (1,-23,4,-20 etc)
Declaration:
int num = 10;
1.
double
Declaration:
double n = 3.14159
double is a 64-bit double precision floating point used
to represent values of great precision
2.
float
Declaration:
float n = 23.4
float is similar to double, but is 32-bit, single precision
floating point
3.
boolean
Declaration:
boolean isThisReal = true
boolean represents either true or false, which is used in
logical operations and conditions
4.
long
Declaration:
long num = 12343953083587630
long represents a 64-bit signed integer and is used for
large numbers
5.
char
Declaration:
char grade = ‘A’
char stands for character. It represents a single 16-bit
unicode character
6.
String
Declaration:
String new = “Hello World”
Although String isn’t technically a primitive data type,
we do use it a lot. String is a class (You will learn
about them later) which are used to represent
sequences of characters
7.
Operator in java :
Operators in Java are the symbols used for
performing certain operations in Java.
Types of Operators in Java:
Arithmetic Operators
Unary Operators
Relational Operators
Assignment Operator
Logical Operators
Ternary Operator
Bitwise Operators
Shift Operators
Instance of operator
1.
2.
3.
4.
5.
6.
7.
8.
9.
Arithmetic Operator
1.
They are used to perform simple arithmetic operations on
primitive data types.
* : Multiplication
/ : Division
% : Modulo
+ : Addition
– : Subtraction
Types :
a + b = 13
a - b = 7
a * b = 30
a / b = 3
a % b = 1
For example:
Let a=6
b=7
2. Unary Operators
Unary operators need only one operand. They are used to
increment, decrement, or negate a value.
Types :
Increment operator
++ : Increment operator, used for incrementing the
value by 1. There are two varieties of increment
operators.
eg: a++; or ++a; //output will be a=a+1
(a) Post-Increment:
Example:-
int a = 6; Output
System.out.print(a++); 6
System.out.print(a); 7
Value is first used for computing the result and
then incremented.
(b) Pre-Increment:
Example:-
int a = 6; Output
System.out.print(++a); 7
System.out.print(a); 7
Value is first incremented the used for computing
result
– – : Decrement operator, used for decrementing the value
by 1. There are two varieties of decrement operators.
eg: a--; or --a; //output will be a=a-1
(a) Post-decrement:
Example:-
int a = 6; Output
System.out.print(a--); 6
System.out.print(a); 5
Value is first used for computing the result and then
decremented.
Decrement operator
(b) Pre-Decrement:
Example:-
int a = 6; Output
System.out.print(--a); 5
System.out.print(a); 5
The value is decremented first, and then the result is
computed.
3. Relational operator
There are two types relational operators equality and
comparison operators
Equality operators
!= (not equal to)
== (equal to)
Comparison operators
> (greater than)
< (lesser than)
>= (greater than or equal to)
<= (lesser than or equal to)
These operator return a true or false values
System.out.println(a==b); //print False
System.out.println(a>=b); //print True
Example :-
a=6 b=5
4. Assignment Operator
‘=’ Assignment operator is used to assign a value
to any variable.
variable = value;
General format for assignment operator is:
Example:
int a=6;
System.out.println( “Previous value of a is :” + a);
a=10;
System.out.println( “Current value of a is :” + a);
output:
Previous value of a is 6
Current value of a is 10
In many cases, the assignment operator can be
combined with other operators to build a shorter
version of the statement called a Compound Statement.
For example,
Instead of a = a+5, we can write a += 5
&=
^=
|=
<<=
>>=
>>>=
=
+=
-=
*=
/=
%=
Instead of a = a*5, we can write a *= 5
Possible Compound statements:
5. Logical Operator
These operators are used to perform “logical AND” and
“logical OR” operations, i.e., a function similar to AND gate
and OR gate in digital electronics.
&&, Logical AND: returns true when both conditions are
true.
||, Logical OR: returns true if at least one condition is
true.
!, Logical NOT: returns true when a condition is false and
vice-versa
Conditional operators are:
boolean x = true;
boolean y = false;
System.out.println("x && y: " + (x && y));
System.out.println("x || y: " + (x || y));
System.out.println("!x: " + (!x));
Example:
output:
x && y: false
x || y: true
!x: false
How to read user input in java??
Scanner class
In Java, Scanner is a class in java.util package used for
obtaining the input of the primitive types like int, double,
etc. and strings. Using the Scanner class in Java is the
easiest way to read input in a Java program.
Value of i Output
nextBoolean()
Used for reading Boolean
value
nextDouble()
Used for reading Double
value
nextFloat()
Used for reading Float
value
nextInt() Used for reading Int value
nextLine() Used for reading Int value
nextLong() Used for reading Long value
nextShort()
Used for reading Short
value
As the name of the command these things read the
next occurrence of the data type in the terminal
Write a program to accept the details of college student.
import java.util.Scanner;
public class ScannerDemo1 {
public static void main(String[] args)
{
// Declare the object and initialize with
// predefined standard input object
Scanner sc = new Scanner(System.in);
// String input
String name = sc.nextLine();
// Character input
char gender = sc.next().charAt(0);
// Numerical data input
// byte, short and float can be read
// using similar-named functions.
int age = sc.nextInt();
long mobileNo = sc.nextLong();
double cgpa = sc.nextDouble();
// Print the values to check if the input was
// correctly obtained.
System.out.println("Name: " + name);
System.out.println("Gender: " + gender);
System.out.println("Age: " + age);
System.out.println("Mobile : " + mobileNo);
System.out.println("CGPA: " + cgpa);
}
}
Code:-
Gowri manoj
F
20
1234567
9.17
Sample input :- Sample output :-
Name: Gowri manoj
Gender: F
Age: 20
Mobile: 1234567
CGPA: 9.17
Conditional Branching
Conditional branching is a fundamental programming
concept used to make decisions, it allows you to
execute different blocks of code depending on
whether a specified condition is true or false.
if-else statement:
1.
The if-else statement allows you to specify one block of
code to execute if a condition is true and another block
to execute if the condition is false.
if (condition) {
// Code to be executed if the condition is true
} else {
// Code to be executed if the condition is false
}
Implementation:
Objective-To find the greatest of 2 number
int number = 3;
if (number > 5) {
System.out.println("The number is greater than 5.");
} else {
System.out.println("The number is not greater than 5.");
}
Code-
Explanation-
This Java code initializes a variable number with the
value 3.
It then checks whether the value of number is greater
than 5.
If the condition is true, it prints "The number is greater
than 5." to the console.
If the condition is false, it prints "The number is not
greater than 5." instead.
In this case, since the value of number is 3, the else
block will be executed, and "The number is not greater
than 5." will be printed.
1.
2.
Objective-To check whether the person is eligible to vote or
note
public class EligibilityCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Check eligibility
if (age >= 18) {
System.out.println("You are eligible to vote!");
} else {
System.out.println("You are not eligible to vote yet."); }
// Close the scanner
scanner.close();
}
Explanation-
Code-
It starts by creating a Scanner object to read user
input.
The program prompts the user to enter their age,
reads the input, and then checks if the entered age is
18 or older.
1.
Objective- To check whether a year is leap or not.
public class LeapYearCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the year
System.out.print("Enter a year: ");
int year = scanner.nextInt();
// Check if it's a leap year
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) {
System.out.println(year + " is a leap year.");
} else {
System.out.println(year + " is not a leap year."); }
// Close the scanner
scanner.close();
}
Code-
If the age is 18 or above, it prints "You are eligible
to vote!" to the console;
2. otherwise, it prints "You are not eligible to vote
yet." The program then closes the Scanner to release
system resources.
Explanation-
It starts by creating a Scanner object to read
user input.
The program prompts the user to enter a year,
reads the input, and then checks
if the entered year satisfies the leap year
conditions.
A year is a leap year if it is divisible by 4 but not
divisible by 100, or it is divisible by 400.
If the conditions are met, it prints "is a leap year"
to the console“;
otherwise, it prints "is not a leap year."
Finally, the program closes the Scanner to release
system resources.
1.
2.
2. if-elif-else Statement:
The if-else if-else statement allows you to test multiple
conditions in a cascading manner and execute different code
blocks based on the first true condition encountered.
Implementation:
if (condition1) {
// Code to be executed if condition1 is true
} else if (condition2) {
// Code to be executed if condition2 is true
} else {
// Code to be executed if no previous condition is true
}
Objective- To find the greatest of 3 numbers.
public class GreatestOfThreeNumbers {
public static void main(String[] args) {
int num1 = 10;
int num2 = 20;
int num3 = 15;
if (num1 > num2 && num1 > num3) {
System.out.println("The greatest number is num1: " + num1);
} else if (num2 > num1 && num2 > num3) {
System.out.println("The greatest number is num2: " + num2);
} else {
System.out.println("The greatest number is num3: " + num3);
}
}
}
Explanation-
This program determines the greatest among three
numbers: num1, num2, and num3.
It initializes these numbers with values 10, 20, and 15,
respectively. The program uses a series of if-else
statements to compare the numbers and identify the
greatest one.
If num1 is greater than both num2 and num3, it prints a
message stating that num1 is the greatest.
If num2 is greater than both num1 and num3, it prints a
message stating that num2 is the greatest.
1.
2.
Code-
public class PositiveNegativeZeroCheck {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the number
System.out.print("Enter a number: ");
int number = scanner.nextInt();
// Check positivity, negativity, or zero
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."); }
// Close the scanner
scanner.close();
}
Objective-To Check whether the entered number is positive
or negative or zero.
Code-
This program checks whether a user-inputted number
is positive, negative, or zero.
It begins by creating a Scanner object to read user
input.
The program prompts the user to enter a number,
reads the input, and then uses a series of if-else
statements to determine whether the number is
positive, negative, or zero.
If the number is greater than 0, it prints "The number
is positive."
If the number is less than 0, it prints "The number is
negative."
If neither condition is met, it concludes that the
number is zero and prints "The number is zero."
Finally, the program closes the Scanner to release
system resources
1.
2.
3.
Explanation-
public class SalaryClassification {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the salary
System.out.print("Enter your salary: ");
double salary = scanner.nextDouble();
// Classify the salary
if (salary < 0) {
System.out.println("Invalid salary. Please
enter a non-negative value.");
} else if (salary < 20000) {
System.out.println("Low income bracket.");
} else if (salary < 50000) {
System.out.println("Moderate income bracket.");
} else if (salary < 100000) {
System.out.println("High income bracket.");
} else {
System.out.println("Very high income bracket."); }
// Close the scanner
scanner.close();
}
Objective -Write a program to classify a person's salary
into different income
Code-
Explanation-
This program takes input for a person's salary,
classifies it into different income brackets, and prints a
corresponding message based on the entered salary.
It starts by creating a Scanner object to read user
input. The program prompts the user to enter their
salary, reads the input, and then uses if-else if-else
statements to classify the salary into various income
brackets.
If the entered salary is negative, it prints an error
message.
If the salary is less than 20,000, it prints "Low income
bracket."
If it's between 20,000 and 50,000, it prints "Moderate
income bracket."
If it's between 50,000 and 100,000, it prints "High income
bracket."
If the salary is 100,000 or more, it prints "Very high
income bracket."
Finally, the program closes the Scanner to release
system resources.
1.
2.
3.
4.
5.
3. Nested if-else statement-
We can use nested if-else statements to create a
structure where one set of if-else conditions is contained
within another. This allows for more complex decision-
making based on multiple criteria .
Implementation-
Define your conditions: Identify the conditions you
want to check.
Write the outer if-else statement: This serves as the
primary condition.
Write the inner if-else statement: This is nested
within the true block of the outer if statement.
Provide the actions or statements to execute: Specify
what should happen based on the combined conditions.
1.
2.
3.
4.
if(condition){
//code to be executed
if(condition){
//code to be executed
}
}
public class MilitarySelection {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input age
System.out.print("Enter your age: ");
int age = scanner.nextInt();
// Input physical fitness score (out of 100)
System.out.print("Enter your physical fitness score (out of 100): ");
int fitnessScore = scanner.nextInt();
// Nested if-else loop to determine military selection eligibility
if (age >= 18) {
System.out.println("You meet the minimum age requirement.")
if (fitnessScore >= 70) {
System.out.println("Congratulations! You are eligible for military
selection.")}
else {
System.out.println("Your physical fitness score is below the required
threshold.");
System.out.println("Consider improving your fitness to meet the
eligibility criteria."); }
} else {
Code-
Objective- Write a program to determine the military
selection eligibility based on age and physical fitness
Explanation
System.out.println("You must be at least 18 years old to
be eligible for military selection."); }
// Close the scanner
scanner.close();
}
This program, determines eligibility for military
selection based on user input for age and physical
fitness score. It uses a nested if-else loop to make
decisions based on multiple criteria.
The program prompts the user to input their age and
physical fitness score.
The outer if-else statement checks if the age is 18 or
older. If true, it proceeds to the inner if-else
statement.
The inner if-else statement checks if the physical
fitness score is 70 or higher. If true, it prints a
message congratulating the user on being eligible for
military selection.
If the age condition in the outer if-else is not met, it
prints a message about the minimum age requirement.
If the fitness score condition in the inner if-else is not
met, it prints a message indicating that the fitness
score is below the required threshold and suggests
improving fitness.
1.
2.
3.
This nested structure allows the program to provide
detailed feedback based on both age and physical fitness.
Objective-Write a program for college scholarship eligibility
using a nested if-else loop
if (income < 50000) {
System.out.println("You qualify for a full scholarship.");
} else if (income >= 50000 && income < 75000) {
System.out.println("You qualify for a partial scholarship.");
} else {
System.out.println("Your income is above
the scholarship threshold."); }
public class CollegeScholarship {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
// Input the GPA
System.out.print("Enter your GPA: ");
double gpa = scanner.nextDouble();
// Input the family income
System.out.print("Enter your family's annual income: ");
double income = scanner.nextDouble();
// Nested if-else loop to determine scholarship eligibility
if (gpa >= 3.5) {
System.out.println("Congratulations! You are eligible for a
scholarship.");
Code-
Practice question
Conditional statement hackerrank contest:
https://www.hackerrank.com/conditi
onal-statement-contest
It allows users to repeat a block of code multiple
times.They enable you to automate repetitive tasks and
process large amounts of data efficiently.
Loops are one of the most essential constructs required
to learn programming.
for
while
do while
In Java, there are three types of loops:
1.
2.
3.
For Loop
This loop is used when you have a pre existing idea for the
number of iterations
Syntax:
for (initialisation, condition; update){
Code Block
}
initialisation: Executed once in the start. Usually a loop
control variable
condition: As long as this condition is met, the loop will
continue
update: Executed per each iteration. Usually used to modify
the loop control variable
LOOPS
Let’s say you didnlt provide a condition statement... the
loop will continue on forever (until your system can handle
it)
Same thing will happen if you don’t provide a update
statement but the result will be different
class HelloWorld {
public static void main(String[] args) {
int i =0;
for(i=0;i<=10;){
System.out.print(i+" ");
}
}
}
Output : 0 0 0 0 0 . . . . . ∞
class HelloWorld {
public static void main(String[] args) {
int i =0;
for(i=0; ;i++){
System.out.print(i+" ");
}
}
}
Output : 1 2 3 4 5 . . . . . . ∞
However, if there is a problem with the initialisation part
of the loop, the code will not be recognised
Examples:
import java.util.Scanner;
public class printnnum{
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
//Scanner class is used to take input from user
int n = sc.nextInt();
//Taking input from user
for(int i=1 ; i<=n ; i++){
//for loop iterates from 1 to n
System.out.println(i);
//printing each i value of loop
}
}
}
Intuition : We have start with number 1 and print all
numbers upto number n one after another
1. Write a program which prints n numbers
Code-
Value of i Output
1
1
2
1
2
3
1
2
3
.
.
.
.
.
.
Explanation:
First we accept the number until which we want to
print to and store it in a variable n
We start the loop at i = 1 and set it to iterate until
the condition “i<=n” is met
Then we print ‘i’
2.Write a program to print even numbers
Intuition : We have start with number 0 and print all even
numbers upto number n one after another
Code -
import java.util.Scanner;
public class printevennums {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
// Taking upto which number we have to print
for(int i=0 ; i<=n ; i+=2){
// for loop iterates from 0 to n with increment of 2
System.out.println(i);
// printing each i value of loop
}
}
}
Value of i Output
0 0
2
0
2
4
0
2
4
6
0
2
4
6
.
.
.
.
.
.
First we accept the number until which we want to
print to and store it in a variable n
We start the loop at i = 1 and set it to iterate until
the condition “i<=n” is met, but this time instead of
iterating i by 1, we iterate it by 2 so that we will print
even numbers
Then we print ‘i’
Explanation:
3. Write a program to find the sum of the first n numbers
Intuition : We have start with number 1 and add all
numbers upto number n one after another
Code -
import java.util.Scanner;
public class printsumofn {
public static void main(String[] main){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
// Taking upto which number we have to get sum
int sum = 0;
// variable to store sum
for(int i=1 ; i<=n ; i++){
// for loop iterates from 1 to n
sum += i;
// adding each i value of loop to sum
}
System.out.println(sum);
// printing sum
}
}
Explanation:
First we accept the number until which we want to find
the sum till and store it in a variable n
We initialise a variable sum to 0 (we will be using this
to update the sum later)
We start the loop at i = 1 and set it to iterate until
the condition “i<=n” is met
We add i to sum and assign it to sum itself, basically
updating sum with i
After the loop is finished we print the sum variable
Value of i Value of sum
initialisation 0
1 1
2 3
3 6
.
.
.
.
.
.
4. Write a program to find if the given number is prime or not
Intuition : We have to check whether the number is
divisible by any number other than 1 and itself. If it is
divisible then it is not prime else it is prime
Code-
import java.util.Scanner;
public class primenumber{
public static void main (String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Whether the number is prime or not
boolean isPrime = true;
//variable to store whether the number is prime or
not
for(int i=2 ; i<n ; i++){
// for loop iterates from 2 to n
if(n%i==0){
// if n is divisible by i
isPrime = false;
// then n is not prime
break;
// break the loop
}
}
First we accept the number we want to verify being
prime or not and store it in n
We initialise a boolean ‘isPrime’ to True. This will store
whether the number is prime or not
We start the loop at i = 2 and set it to iterate until
the condition “i<n” is met
We check if the modulus of the number with i is 0 or
not (divisible)
If divisible, then we change isPrime to false ad break
the loop as there is a factor for the number
If not we proceed to an if block which checks the
condition of our boolean variable, according to which
we can determine if the number is prime or not
if(isPrime){// if isPrime is true
System.out.println("Prime");// then n is prime
}
else{// else
System.out.println("Not Prime");// then n is not prime
}
}
}
Explanation:
Value of i Modulus Value isPrime Value
2 1 True
3 0 False
Let’s take 9 as an example
Here 9 is divisible by 3 hence making it a non prime number
5. Write a program to find if the given number is perfect or
not
Intuition : We have to find all the factors of number and add
them to get sum then check whether the sum is equal to
number or not
Code -
Note: A perfect number is a number who’s factors (other than
itself), added up, equal to itself. Eg. 28 (1+2+4+7+14)
import java.util.Scanner;
public class perfeectnum {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Taking number which is to be checked
int sum = 0;
// variable to store sum
for(int i=1 ; i<n ; i++){
// for loop iterates from 1 to n
if(n%i==0){
// if n is divisible by i
sum += i;
// adding each i value of loop to sum
}
}
if(sum==n){// if sum is equal to n
System.out.println("Perfect Number");
// then n is perfect number
}
else{// else
System.out.println("Not Perfect Number");
// then n is not perfect number
}
}
}
Explanation:
First we accept the number we want to verify being
perfect or not and store it in n
We initialise a variable sum to 0
We start the loop at i = 1 and set it to iterate until
the condition “i<n” is met
We check (using the modulus function) if n is divisible
by i
If it is we add it to sum and assign it to sum like we
did in example 3
Then we are out of the loop and we check if the sum is
equal to the number
If it is then we print “Perfect Number”, else we print
“Not a Perfect Number”
Value of i Value of modulus Value of sum
1 0 1
2 0 3
3 1 3
4 0 7
.
.
7 0 14
.
.
14 0 28
.
.
27 1 28
Let’s take 28
Here sum value is equal to the number which we gave,
making 28 a perfect number
6. Write a program to find the fibonacci numbers till n
Intuition : We have start with number 0 and 1 and print all
fibonacci numbers upto number n one after another
Code-
import java.util.Scanner;
public class fibnacci {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
// Taking upto which number we have to print
int a=0,b=1,c=0;
// initializing a=0,b=1,c=0
System.out.print(a+" "+b+" ");
// printing 0 and 1
for(int i=2 ; i<=n ; i++){
// for loop iterates from 2 to n
c=a+b;// adding a and b and storing it in c
System.out.print(c+" ");// printing c
a=b;// assigning b to a
b=c;// assigning c to b
}
}
}
First, we accept the number n up to which we want to
print the Fibonacci series.
We initialize three variables a, b, and c to 0, 1, and 0,
respectively. These variables will be used to generate
the Fibonacci series.
We print the initial values of a and b (0 and 1) as the
starting points of the Fibonacci series.
We start a loop at i = 2 since the first two Fibonacci
numbers (0 and 1) are already printed. The loop iterates
until the condition i <= n is met.
Inside the loop, we calculate the next Fibonacci number
(c) by adding the previous two numbers (a and b).
We print the calculated Fibonacci number (c).
We update the values of a and b for the next iteration.
a is assigned the value of b, and b is assigned the value
of c.
The loop continues to iterate, generating and printing
Fibonacci numbers until it reaches the specified limit n.
The program concludes, having printed the Fibonacci
series up to the specified number n.
Explanation:
Value of a Value of b Value of c Output
0 1 0 0 1
0 1 1 0 1 1
1 1 2 0 1 1 2
1 2 3 0 1 1 2 3
2 3 5 0 1 1 2 3 5
... ... ... ...
While Loops
The while loop is used when we dont know how many
times a block of code is to be repeated
Syntax:
while (condition){
Code Block
}
The loop continues as long as the condition is true.
If we don’t make the condition false, the loop will carry out
infinitely
class HelloWorld {
public static void main(String[] args) {
int i=0;
while (true) {
i++;
System.out.print(i + " ");
}
}
}
i.e. :
Output: 0 1 2 3 4 . . . .
Examples:
import java.util.Scanner;
public class sumofnnat {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Taking upto which number we have to get sum
int sum = 0; // variable to store sum
int i = 1; // variable to iterate loop
while(i<=n){
// while loop iterates from 1 to n
sum += i;// adding each i value of loop to sum
i++;// incrementing i value
}
System.out.println(sum);// printing sum
}
}
Write a program to find the sum of the first n numbers
Intuition : We have start with number 1 and add all numbers
upto number n one after another
Code-
1.
1.
Explanation:
First we accept the number until which we want to find
the sum to and store it in a variable n
We initialise a variable sum to 0
We initialise i to 1 to start the loop
We give the condition “i<=n” so as long as that is true,
the loop will iterate
We add i to sum and assign it to sum itself, basically
updating sum with i
After the loop is finished we print the sum variable
Value of i Value of sum
initialisation 0
1 1
2 3
3 6
.
.
.
.
.
.
Write a program to find the factorial of n
Intuition : We have start with number 1 and multiply all
numbers upto number n one after another
Code-
2.
import java.util.Scanner;
public class factorial {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
// Taking number whose factorial we have to find
int fact = 1;
// initializing fact to 1
while(n>0){
// while loop iterates from 1 to n
fact = fact * n;
// multiplying each i value of loop to fact
n--;
// decrementing n value
}
System.out.println(fact);// printing fact
}
}
Explanation:
First we accept the number until which we want to find
the factorial and store it in a variable n
We initialise a variable fact to 1
We give the condition “n>0” so as long as that is true, the
loop will iterate
We then multiply fact with n and store the result in fact
itself
We decrement n
When the loop is finished we print out the fact
Value of n Value of fact
4 4
3 12
2 24
1 24
Write a program to find if a number is an armstrong number
or not (cube of the digits of the number is the number itself)
Intuition : We have to get each digit of number and cube it
and add it to sum then check whether the sum is equal to
number or not
Code-
3.
import java.util.Scanner;
public class armstrong {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Taking number which is to be checked
int temp = n;
// storing n in temp variable
int sum = 0;
// variable to store sum
while(temp>0){
// while loop iterates until temp is greater than 0
int rem = temp%10;
// storing remainder of temp divided by 10
sum += rem*rem*rem;
// adding cube of remainder to sum
temp /= 10;
// dividing temp by 10
}
if(sum==n){
// if sum is equal to n
System.out.println("Armstrong Number");
// then n is armstrong number
}
else{// else
System.out.println("Not Armstrong Number");
// then n is not armstrong number
}
}
}
Explanation:
Take number to be checked and store it in the variable n
We store the number in a temporary variable so that
the original number can be used later
Initialise a variable “sum” to 0
We will iterate the while loop till the condition ‘temp >
0’ is not satisfied
We find out the least significant bit (number in unit’s
place) by mod 10 and store it to ‘rem’. This is how we
can find the individual cubes of each digit
Then we cube ‘rem’ and add it with the sum and store it
to the sum variable
We change the temp number by dividing it by 10 and
storing it to temp so that the previous LSB is gone
This process is carried out until the loop is finished
Then we check if sum is equal to n. If it is we print
“Armstrong Number”, if it’s not, we print “Not an
Armstrong Number”
Write a program to find the Compound Interest after a set
amount of years
Intuition : We have to add the interest for each year to the
already existing interest
Code-
4.
import java.util.Scanner;
public class compoundintrest {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
float p = sc.nextInt();
// Taking principal amount
float r = sc.nextInt();
// Taking rate of intrest in percentage
int t = sc.nextInt();
// Taking number of years
while(t>0){
// while loop iterates from t to 1
p = p + (p*r)/100;
// adding each i value of loop to sum
t--;
// decrementing t value
}
System.out.println(p);// printing sum
}
}
Explanation:
Take Principal amount, Rate of Interest, and Time in
variables, p, r, t, respectively
We put the condition “t>0” i.e. the loop will repeat until
t is lesser than or equal to 0
Inside the loop block, we multiply p with r and divide it by
100 (we took r in percentage)
Then we add p to it and store it back in p as the new
principal amount
This happens till the loop is finished
Finally we print out the final amount after t years of r
rate of interest on the amount p
Value of t Value of p
3 10000
2 10500
1 10125.25
0 10125.25
p= 10000, r = 5%, t = 3 years
Nested Loops
Nested loops are basically loops within a loop. The outer
loop will iterate every time the inner loop finishes it’s
entire sequence of iterations. This type of nested looping
should be handled carefully as the time complexity can
quickly get out of hand
Examples:
Write a program to find the prime numbers within 0-n
Intuition : We have to check whether the number is divisible
by any number other than 1 and itself. If it is divisible then it
is not prime else it is prime. We have to check this for all
numbers from 2 to n. If we find any number which is not
prime then we have to break the loop and check for next
number. If we don't find any number which is not prime then
we have to print that number. We have to do this for all
numbers from 2 to n
1.
import java.util.Scanner;
public class allprimeswithinn {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
// Taking upto which number we have to print
for(int i=2 ; i<=n ; i++){ // for loop iterates from 2 to n
boolean isPrime = true;
//boolean variable to check whether i is prime or not
for(int j=2 ; j<i ; j++){
// for loop iterates from 2 to i
if(i%j==0){
// if i is divisible by j
isPrime = false;
break;
// break the loop
}
}
if(isPrime){// if i is prime
System.out.println(i);// print i
}
}
}
}
Code-
Explanation:
We read the number till which we need to print prime
numbers till and store it in n
The outer loop (for (int i = 2; i <= n; i++)) iterates
through numbers from 2 to n.
Inside the outer loop, there's an inner loop (for (int j =
2; j < i; j++)) that checks whether the current number i
is prime or not.
If i is divisible by any number j in the range from 2 to
i-1, isPrime is set to false, and the inner loop breaks.
After the inner loop, if isPrime is still true, it means
that i is a prime number, and it is printed.
Write a program to print an nxn grid of ‘*’
2.
Intuition : We have to print a pattern of n*n stars
import java.util.Scanner;
public class pattern1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Taking the size of pattern
Code-
for(int i=1 ; i<=n ; i++){
// for loop iterates from 1 to n
for(int j=1;j<=n;j++){
// for loop iterates from 1 to n
System.out.print("*");// printing *
}
System.out.println();// going to next line
}
}
}
Explanation:
We read the number which represents the pattern size
The outer loop (for (int i = 1; i <= n; i++)) iterates from
1 to n and represents the rows of the square pattern.
Inside the outer loop, there's an inner loop (for (int j =
1; j <= n; j++)) that iterates from 1 to n and represents
the columns of each row.
In the inner loop, the program prints an asterisk (*)
for each column.
After printing all the asterisks in a row (inner loop), the
program uses System.out.println() to move to the next
line, creating a new row in the square pattern.
This pattern consists of n rows and n columns, and
each element in the pattern is an asterisk (*).
Value of i Value of j Output screen
0 0
1 *
2 (inner loop
terminates)
**
1 0 **
1
**
*
2 (inner loop
terminates)
**
**
2 (outer loop
terminates)
**
**
Write a program to print the following pattern
2.
Intuition : We have to print a pattern of increasing number of
+ from 1 to n. We have to print n-i spaces and i + one after
another
+
++
+++
++++
Code-
import java.util.Scanner;
public class pattern1 {
public static void main(String[] args){
Scanner sc = new Scanner(System.in)
// Scanner object to read inputs
int n = sc.nextInt();
//Taking the size of pattern
for(int i=1 ; i<=n ; i++){
// for loop iterates from 1 to n
for(int j=1 ; j<=n-i ; j++){
// for loop iterates from 1 to n-i
System.out.print(" ");
// printing space
}
for(int j=1 ; j<=i ; j++){
// for loop iterates from 1 to i
System.out.print("+");
// printing +
}
System.out.println();// printing new line
}
}
}
Explanation:
We read the number which represents the pattern size
and store it in n
The outer loop (for (int i = 1; i <= n; i++)) iterates from
1 to n and represents the rows of the pattern.
Inside the outer loop, there's an inner loop 1 (for (int j
= 1; j <= n - i; j++)) that iterates from 1 to (n - i) and
represents the spaces at the beginning of each row.
Following inner loop 1, there's another inner loop 2 (for
(int j = 1; j <= i; j++)) that iterates from 1 to i and
represents the plus signs (+) in each row.
After printing all the spaces and plus signs in a row,
the program uses System.out.println() to move to the
next line, creating a new row in the pattern.
The result is a pattern where each row starts with
spaces, and the number of plus signs increases with
the row number.
Value of i
Value of j
(space)
Value of j
(“+”)
Output
screen
1 2 1 +
2 1 1
+
+
2
+
++
3 0 1
+
++
+
2
+
++
++
3
+
++
+++
Write a program to print a pascal’s triangle
3.
Intuition : We have to print a pattern of pascal triangle of
size n. We have to print n-i spaces and i+1 numbers according
to row number. We have to calculate number for next
iteration using formula number = number * (i-j)/(j+1). We have
to print number and space one after another. We have to go
to next line after each row. We have to print 1 in first row. We
have to print 1 1 in second row
Code-
import java.util.Scanner;
public class pascaltriangle {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
// Scanner object to read inputs
int n = sc.nextInt();
//Taking the size of pattern
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
Example-
for(int i=0 ; i<n ; i++){
// for loop iterates from 0 to n
int number = 1;
// initializing number to 1
for(int space=0 ; space<n-i ; space++){
// for loop iterates from 0 to n-i
System.out.print(" ");
// printing space
}
for(int j=0 ; j<=i ; j++){
// for loop iterates from 0 to i
System.out.print(number+" ");
// printing number
number = number * (i-j)/(j+1);
// calculating number for next iteration
}
System.out.println();// going to next line
}
}
}
Explanation:
We read the number which represents the pattern size
and store it in n
The outer loop (for (int i = 0; i < numRows; i++))
iterates through each row.
Before printing each row, spaces are added to align the
triangle.
The inner loop (for (int j = 0; j <= i; j++)) calculates and
prints the numbers in each row of Pascal's Triangle.
The value of each number is calculated using the
formula number = number * (i - j) / (j + 1).
After printing each row, the program uses
System.out.println() to move to the next line.
When you run this program and input the number of
rows, it will display Pascal's Triangle with the specified
number of rows.
Value of i
Value of j
(space)
Value of j
(“+”)
Output
screen
1 2 1 1
2 1 1
1
1
2
1
1 1
3 0 1
1
1 1
1
2
1
1 1
1 2
3
1
1 1
1 2 1
Loops hackerrank contest:
https://www.hackerrank.com/string-
contest-1700333838
Practice question
ARRAY IN JAVA
Syntax to Declare an Array in Java:
Java array is an object which contains elements of a
similar data type.
The elements of an array are stored in a contiguous
memory location.
Array in Java is index-based, the first element of the
array is stored at the 0th index, 2nd element is stored on
1st index and so on.
dataType[] arr=new datatype[size];
Eg:
int[] arr=new int[3];
arr[0]=1;
arr[1]=2;
arr[2]=3;
Now array becomes:[1,2,3]
int[] arr=new float[3];
arr[0]=9.2;
arr[1]=6.9;
arr[2]=3.2;
Now array becomes:[9.2,6.9,3.2]
1 2 3 4 5
0 1 2 3 4
array length - 5
- indices
arr[2]
returns 3
Note:
In Java, arrays are mutable. This means that you can
change the values of individual elements in an array after it
has been initialized.
Eg: int[] arr={1,2,3,4,5};
arr[1]=6;//Element at index one have been changed to 6
Now array becomes:[1,6,3,4,5]
INSERTION AND PRINTING AN ARRAY OF SIZE N:
Objective : -
To accept n integer array and display the array.
Intuition :-
We need to create a integer array capable of storing n
integers. Then print each element of the array in order.
import java.util.Scanner;
public class Sample
{
public static void main(String[] args)
{
//Scanner class for getting input from user
Scanner sc=new Scanner(System.in);
int n;
// Getting value for array size
n=sc.nextInt();
int myArr=new int[n];//Declaring array of size n
Code-:
//Inputting elements to array
for(int i=0;i<n;i++)
{
myArr[i]=sc.nextInt();
}
System.out.println(“Array is:”);
//printing elements of array
for(int i=0;i<n;i++)
{
System.out.print(myArr[i]+” , “);
}
}
}
Firstly declare an integer n.
Now get input from user and store it to variable n
using scanner class.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at its
corresponding index.
Now we will print each elements in array using for loop
which iterates from 0 to n-1 (index of elements) .
Explanation :
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
Declare empty array of size 5
Step by step output:
Let us assume our n is 5 and user inputs are {1,2,3,4,5}.
When i=0
When i=1
When i=2
When i=3
When i=4
0 1 2 3 4 =>Index
0 1 2 3 4
Index=>
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
i
i
i
i
i
1 2 3 4 5
OUTPUT:
{ 1 }
{ 1 , 2 }
{ 1 , 2 , 3 }
{ 1 , 2 , 3 , 4}
{ 1 , 2 , 3 , 4 ,5 }
Largest and smallest element in an array:
Objective : -
To find and display the largest and smallest element in an
array.
Intuition :-
Accept n sized array and find largest and smallest element
in the array and display it.
Code:-
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner sc = new Scanner(System.in);
// Prompt the user to enter the size of the array
System.out.print("Enter the size of the array: ");
int n = sc.nextInt();
// Create an array to store integers
int[] myArr = new int[n];
// Input values into the array
System.out.println("Enter values for the array:");
for (int i = 0; i < n; i++) {
System.out.print("Enter value for myArr[" + i + "]: ");
myArr[i] = sc.nextInt();
}
// Initialize variables to store the maximum and minimum
values
int max = myArr[0];
int min = myArr[0];
// Find the maximum and minimum values in the array
for (int i = 0; i < n; i++) {
if (max < myArr[i]) {
max = myArr[i];
}
if (min > myArr[i]) {
min = myArr[i];
}
}
// Display the maximum and minimum values
System.out.println("Max element is: " + max);
System.out.println("Min element is: " + min);
}
}
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at
its corresponding index.
Now we declare two variable to store maximum and
minimum element i.e, max and min. And we initialize
these variable with 0th index element of that array.
Now we iterate through array and check each element
that is it greater than max then substitute that
element to max variable. Similarly for minimum we
check whether every element is less than current
minimum element if so, we assign that element to min
variable.
After the for loop we display the largest element as
max and smallest element as min.
Explanation :
Output:
Let our array size be 5 with element {3,4,5,2,1}.We will find
the largest and the shortest element.
Initially the Min and Max variable is assigned with the
initial element in array arr[0] that is 3
0 1 2 3 4
Index=>
3 4 5 2 1
3 4 5 2 1
3 4 5 2 1
3 4 5 2 1
i
i
i
i
i
3 4 5 2 1
MIN/MAX VALUE
Min=3 Max=3
Min=3 Max=4
Min=3 Max=5
Min=2 Max=5
Min=1 Max=5
The output will be:
Max element is 5 and Min element is: 1
Second largest element in an array
Objective : -
To find and display the second largest element in an array.
Intuition :-
We have to find second largest element in array. So, we have
to compare each element of array with max and secondmax.
Code-:
import java.util.Scanner;
public class secondlargest
{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);// Scanner object to
read inputs
int n = sc.nextInt();// Taking number of elements in array
int[] arr = new int[n];// Declaring array of size n
for(int i=0;i<n;i++){// for loop to take array elements as
input
arr[i] = sc.nextInt();// taking array elements as input
}
int max = arr[0];// initializing max to first element of
array
int secondmax = arr[0];// initializing secondmax to first
element of array
for(int i=0;i<n;i++){// for loop to iterate through array
if(arr[i]>max){// if current element is greater than max
secondmax = max;// then secondmax will be max
max = arr[i];// and max will be current element
}
else if(arr[i]>secondmax){// if current element is greater
than secondmax
secondmax = arr[i];// then secondmax will be current
element
}
}
System.out.println(secondmax);// printing secondmax
}
}
Explanation :
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at its
corresponding index.
Now we declare two varible to store maximum and second
maximum element i.e, max and secondmax. And we initialize
these variable with 0th index element of that array.
Now we iterate through array and check each element that
is it greater than max then subtitute that element to max
variable and the old value of max will be given to
secondmax variable.
Output:
After the for loop we display the second largest
element as secondmax.
Let our array size be 5 with element {3,4,5,2,1}.We will find
the second largest element.
0 1 2 3 4
Index=>
3 4 5 2 1
3 4 5 2 1
3 4 5 2 1
3 4 5 2 1
i
i
i
i
i
3 4 5 2 1
MAX/SECONDMAX VALUE
SecondMax=3
Max=3
The output will be:
Second largest element is: 4
SecondMax=3
Max=4
SecondMax=4
Max=5
SecondMax=4
Max=5
SecondMax=4
Max=5
Reverse an array:
Objective : -
To reverse an array and display it.
Intuition :-
Accept n sized array and reverse the array and display
it.
Code-:
import java.util.Scanner;
public class Sample
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n;
n=sc.nextInt();
// Declaring array of size n
int myArr=new int[n];
//Getting array elements from user
for(int i=0;i<n;i++)
{
myArr[i]=sc.nextInt();
}
int start = 0; //Initializing start with index 0
int end = arr.length - 1; //Initializing end with index n-1
//Reversing the array
while (start < end)
{
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++ ;
end-- ;
}
System.out.print(“Reversed array is: ”);
//Printing the reversed array
for(int i=0;i<n;i++)
{
System.out.print(myArr[i]);
}
sc.close();//Closing the scanner
}
}
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at its
corresponding index.
Now we declare variables start initialized with 0 and end
variable with size-1.
Now we iterate while loop till start < end.
After the execution of for loop the array will be
reversed and we will print it.
> At each iteration of the loop we swap the
start
element and end element
> And after swapping the first elements with
last
elements we increment start variable and
decrement
the end variable.
Explanation :
Output:
Let us assume our n is 5 and user inputs are
{1,2,3,4,5}.And we reverse the array and display the
reversed array.
0 1 2 3 4
Index=>
1 2 3 4 5
start
output: :
swap(arr[start,],arr[end])
Swap(1,5)
end
5 2 3 4 1
start end
5 4 3 2 1
start
end
Swap(3,3)
Swap(2,4)
5 4 3 2 1
Searching in array :
There are two popular ways to search an array in Java:
Linear search:
This is the simplest search algorithm. It works by
comparing the target element to each element in the array
until it is found. The time complexity of linear search is
O(n), where n is the size of the array.
Binary search:
This is a more efficient search algorithm. It works by
repeatedly dividing the array in half and searching the half
that contains the target element. The time complexity of
binary search is O(log n), where n is the size of the array.
Linear search :
Objective : -
To search a given element in array using linear search
algorithm.
Intuition :-
Search elements from start to end linearly to find the
target element
import java.util.Scanner;
public class Sample {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
// Entering the size of the array
System.out.print("Enter the size of the array: ");
int n = sc.nextInt();
// Create an array to store integers
int[] myArr = new int[n];
// Input values into the array
System.out.println("Enter values for the array:");
for (int i = 0; i < n; i++) {
System.out.print("Enter value for myArr[" + i + "]: ");
myArr[i] = sc.nextInt();
}
// Prompt the user to enter the key to search
System.out.print("Enter the key to search: ");
int key = sc.nextInt();
// Search for the key in the array
for (int i = 0; i < n; i++) {
if (myArr[i] == key) {
// If key is found, print a message and exit the loop
System.out.println("Element found");
break;
}
}
}
}
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Code-
Explanation :
Output-
0 1 2 3 4
Index=>
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
1 2 3 4 5
i
i
i
i
OUTPUT:
Arr[j]=> 1 != 4=>search
element
Let our array size be 5 with element {1,2,3,4,5}.And the
element to search be 4.
Arr[j]=> 2 != 4=>search
element
Arr[j]=> 3 != 4=>search
element
Arr[j]=> 4 = 4=>search
element
Out put will be: Element found
Then we accept input from user using a for loop
which iterates from 0 to n-1 and stores the input
value at its corresponding index.
Now we declare variables start initialized with 0 and
end variable with size-1.
Now we iterate using for loop and check every
element in each index of array .If we find the element
in array it will print the message “Element found”.
Binary search :
Objective : -
To search a given element in array using binary search
algorithm.
Intuition :-
Search element using binary search algorithm
import java.util.Scanner;
public class binarysearch {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);// Scanner object to
read inputs
int n = sc.nextInt();// Taking number of elements in array
int[] arr = new int[n];// Declaring array of size n
for(int i=0;i<n;i++){// for loop to take array elements as
input
arr[i] = sc.nextInt();// taking array elements as input
}
int x = sc.nextInt();// Taking element to be searched
int index = -1;// initializing index to -1
int low = 0;// initializing low to 0
int high = n-1;// initializing high to n-1
while(low<=high){// while loop to iterate through array
int mid = (low+high)/2;// calculating mid
if(arr[mid]==x){// if current element is equal to x
index = mid;// then index will be mid
break;// break the loop
}
Code-
else if(arr[mid]>x){// if current element is greater than x
high = mid-1;// then high will be mid-1
}
else{// if current element is less than x
low = mid+1; // then low will be mid+1
}
}
System.out.println("Elment found at index "+index);// printing
index
}
}
Explanation :
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at
its corresponding index.
We are given a sorted array. We have to find element x
in array. So, we check the middle element of array.
If middle element is equal to x then we return index of
middle element.
If middle element is greater than x then we search in
left half of array.
If middle element is less than x then we search in right
half of array.
We repeat above steps until we find x or low becomes
greater than high.
If we don't find x then we return -1.
Output
Let our array size be 5 with element {1,2,3,4,5}.And the
element to search be 4.
SORTING ARRAY USING BUBBLE SORT :
Objective : -
Sort a given array using buuble sort and print it.
Intuition :-
Given an array, sort it using bubble sort which compare
each element and swaps accordingly.
import java.util.Scanner;
public class bubblesort {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);// Scanner object to read
inputs
int n = sc.nextInt();// Taking number of elements in array
int[] arr = new int[n];// Declaring array of size n
for(int i=0;i<n;i++){// for loop to take array elements as input
arr[i] = sc.nextInt();// taking array elements as input
}
for(int i=0;i<n-1;i++){// for loop to iterate through array
for(int j=0;j<n-i-1;j++){// for loop to iterate through array
if(arr[j]>arr[j+1]){// if current element is greater than nex
element
int temp = arr[j];// then swap current element with
next element
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
CODE-:
Firstly declare an integer n.
Now we accept the size of the array and store it in a
variable n.
Then we accept input from user using a for loop which
iterates from 0 to n-1 and stores the input value at
its corresponding index.
Inside for loop start with the first element and
compare the current element with the next element.
If the current element is greater than the next
element, then swap both the elements. If not, move to
the next element.
Repeat steps 1 – 3 until we get the sorted list.
And after the sorting print the array.
Explanation :
Let our array size be 5 with element {3,4,5,2,1}.Then the
output will be {3,4,5,6,8}.
Output:
for(int i=0;i<n;i++){// for loop to iterate through array
System.out.print(arr[i]+" ");// printing array elements
}
}
}
1 2 3 4 5
Index=>
5 3 8 4 6
MIN/MAX VALUE
Initial unsorted array
3 5 8 4 6
3 5 8 4 6
3 5 4 8 6
Compare first and second
element
(swap)
Compare second and third
element
(not swap)
Compare third and fourth
element
(swap)
3 5 4 6 8
Compare fourth and fifth
element
(swap)
When i=0
j
j j+1
j j+1
j j+1
j j+1
When i=1
3 4 5 6 8
Compare second and third
element
(swap)
3 4 5 6 8 Compare first and second
element
(not swap)
j j+1
The ouput will be: 3 4 5 6 8
Similarly repeat these steps until no more swaps required.
That is until i<n-1 .
j j+1
3 4 5 6 8
Compare third and fourth
element
(not swap)
j j+1
Rotation of array by d number of
rotation :
Objective : -
Rotate an array k times
Intuition :- We take a temporary array and add last k
elements to the beginning of array and rest to end
Code-
import java.util.Scanner;
public class RotatingArray {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);// Scanner object to read
inputs
int n = sc.nextInt();// Taking number of elements in array
int[] arr = new int[n];// Declaring array of size n
for(int i=0;i<n;i++){// for loop to take array elements as input
arr[i] = sc.nextInt();// taking array elements as input
}
int[] arr2= new int[n];// Declaring array of size n
//first half
for(int i=0;i<d;i++){// for loop to iterate through array
arr2[i] = arr[n-d+i];// storing last d elements in arr2
}
int d = sc.nextInt();// Taking number of rotations
d=d%n;// if d>n then d=d%n
//second half
for(int i=d;i<n;i++){// for loop to iterate through array
arr2[i] = arr[i-d];// storing first n-d elements in arr2
}
arr=arr2;// copying arr2 to arr
for(int i=0;i<n;i++){// for loop to iterate through array
System.out.print(arr[i]+" ");// printing array elements
}
}
}
Explanation :
5 3 8 4 6 k=8
k-rotations
Since the size of array is less than rotations we make k
k=k%(sizeofarray)
We declare new array similar to given array to store
rotated array
k=8%5=3
Accept the array and number of rotations from the
user
5 3 8 4 6
After k rotations first half of the rotated array
would start from n-k th position so we use a for
loop to add these elements to result array
5 3 8 4 6 8 4 6
After k rotations second half of the rotated array
would start from 0 th position to n-k th position
so we use a for loop to add these elements to
result array
5 3 8 4 6 8 4 6 5 3
data_type[ ][ ] array_name = new data_type[x][y];
1 2 3
4 5 6
7 8 9
Multidimensional Arrays can be defined in simple words
as array of arrays. Data in multidimensional arrays
are stored in tabular form
MULTIDIMENSIONAL ARRAY IN JAVA :
Syntax to Declare an Array in Java:
For example:
int[][] matrix=new int[3][3];
matrix={{1,2,3},{4,5,6},{7,8,9}};
The matrix will be:
0 1 2
Index
0
1
2
Indexing in a 3 X 3 matrix
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)
0 1 2
Index
0
1
2
Let the input values be:
(0,0)=>1
(0,1)=>2
(2,2)=>9
(2,1)=>8
(0,2)=>3
(1,0)=>4
(1,1)=>5
(1,2)=>6
(2,0)=>7
Now the matrix will be:
1 2 3
4 5 6
7 8 9
0 1 2
Index
0
1
2
import java.util.Scanner;
public class MatrixInsertion {
public static void main(String[] args) {
int rows = 3;
int cols = 3;
int[][] matrix = new int[rows][cols];
Scanner scanner = new Scanner(System.in);
System.out.print("Enter value for matrix”);
// Insert values into the matrix
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = scanner.nextInt();
}
}
2D array insertion and printing:
Objective : -
Create a matrix using given number of rows and columns
and display it.
Intuition :-
Given number of rows and columns , we have to create a
matrix and input values to corresponding cell from user
and display it.
Code-
// Display the matrix
System.out.println("nMatrix:");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
scanner.close();
}
}
Explanation :
First we get input from user for number of rows and
columns.
Then we accept value for matrix using nested for loop
and store it to corresponding cell.
And we display the matrix using nested for loop.
Let number of rows be 3 and number of column be 3.Let
the input be {{1,6,9},{8,7,0},{4,5,3}}
Output:
1 6 9
8 7 0
4 5 3
The matrix will be:
0 1 2
Index
0
1
2
The output is:
4 5 3
8 7 0
1 6 9
import java.util.Scanner;
public class MatrixSearch {
public static void main(String[] args) {
int rows = 3;
int cols = 3;
int[][] matrix = new int[rows][cols];
Scanner scanner = new Scanner(System.in);
// Entering value for matrix
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = scanner.nextInt();
}
}
System.out.println("nMatrix:");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.print(matrix[i][j] + " ");
}
System.out.println();
}
Searching an element in 2D array :
Objective : -
Search a given element in 2D array and print if element
found or not.
Intuition :-
Given matrix we have to search a value in that matrix and
display whether the element is present or not.
CODE-:
Explanation :
First we get input from user for number of rows and
columns.
Then we accept value for matrix using nested for loop
and store it to corresponding cell.
The boolean variable found is assigned with false.
Then we check each index and check whether the
searchvalue is present or not.
If element present then we assign the value of found
as true.
Then if found=true we will display that element is
present.
System.out.print("nEnter value to search: ");
int searchValue = scanner.nextInt();
boolean found = false;//Setting falg to false
//Checking each cell for given searchvalue
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
if (matrix[i][j] == searchValue) {
found = true;
break;
}
}
}
if (found) {
System.out.println("Value " + searchValue + " found in the matrix.");
}
// Close the Scanner
scanner.close();
}
}
1 6 9
8 7 0
4 5 3
0 1 2
Index
0
1
2
The output is:
Value of
i
Value of
j
Value of
found
0 0 false
1 false
2 false
1 0 true
Value 8 found in the matrix
Let number of rows be 3 and number of column be 3.Let
the input be {{1,6,9},{8,7,0},{4,5,3}} and let the given
searchvalue be 8.
Output:
The matrix will be:
Addition of 2D array :
Objective : -
Add two matrix and display the result in a third matrix.
Intuition :-
Given two matrix perform addition of both matrix and
store it to a third matrix and display it.
Code-
import java.util.Scanner;
public class MatrixAddition {
public static void main(String[] args) {
int rows = 3;
int cols = 3;
int[][] matrix1 = new int[rows][cols];
int[][] matrix2 = new int[rows][cols];
int[][] resultMatrix = new int[rows][cols];
Scanner scanner = new Scanner(System.in);
// Insert values into the first matrix
System.out.println("Enter values for the first matrix:");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.print("Enter value for matrix1[" + i + "][" + j +
"]: ");
matrix1[i][j] = scanner.nextInt();
}
}
// Insert values into the second matrix
System.out.println("Enter values for the second matrix:");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.print("Enter value for matrix2[" + i + "][" + j +
"]: ");
matrix2[i][j] = scanner.nextInt();
}
}
// Perform matrix addition and store the result in the third
matrix
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j];
}
}
// Display the result matrix
System.out.println("nResult Matrix (Matrix1 + Matrix2):");
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
System.out.print(resultMatrix[i][j] + " ");
}
System.out.println();
}
// Close the Scanner
scanner.close();
}
Explanation :
First we get input from user for number of rows and
columns.
Then we accept value for first and second matrix using
nested for loop and store it two different matrix
named matrix 1 and matrix2.
Now we perform addition operation for matrix 1 and
matrix 2 and store it to resultmatrix using nested for
loop.
Then we display the resultmatrix using nested for loop.
Let number of rows be 3 and number of column be 3.Let
the matrix 1 be {{1,6,9},{8,7,0},{4,5,3}} and matrix 2 be
{{1,2,3},{4,5,6},{7,8,9}}
Output:
1 6 9
8 7 0
4 5 3
+ =
1 2 3
4 5 6
7 8 9
5
2 8 12
12 12 6
11 13 12
Matrix 1 Matrix 2 resultmatrix
Matrix muliplication :
Objective : - Mulitiply two given matrixes A and B
Intuition :- Given Two matrix apply the multiplication
algorithm and return the resultant matrix
Code-
import java.util.Scanner;
public class matrixmultiplication {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);//create scanner object
int m = sc.nextInt();//read number of rows of first matrix
int n = sc.nextInt();//read number of columns of first matrix
int[][] mat1 = new int[m][n];//create first matrix
for(int i=0;i<m;i++){//loop through the first matrix
for(int j=0;j<n;j++){
mat1[i][j] = sc.nextInt();//read elements of first matrix
}
}
int p = sc.nextInt();//read number of rows of second matrix
int q = sc.nextInt();//read number of columns of second matrix
int[][] mat2 = new int[p][q];//create second matrix
for(int i=0;i<p;i++){//loop through the second matrix
for(int j=0;j<q;j++){
mat2[i][j] = sc.nextInt();//read elements of second matrix
}
}
if(n==p){
int[][] mat3 = new int[m][q];//create result matrix
for(int i=0;i<m;i++){//loop through the result matrix
for(int j=0;j<q;j++){
mat3[i][j] = 0;
//initialize elements of result matrix to 0
for(int k=0;k<n;k++){//loop through the first matrix
mat3[i][j] += mat1[i][k]*mat2[k][j];
//multiply the matrices
}
}
}
for(int i=0;i<m;i++){//loop through the result matrix
for(int j=0;j<q;j++){
System.out.print(mat3[i][j]+" ");
//print elements of result matrix
}
System.out.println();//go to next line
}
}
else{
System.out.println("The matrices cannot be multiplied");
//print if the matrices cannot be multiplied
}
}
}
Explanation :
First we get input from user for number of rows and
columns.
Then we accept value for first and second matrix using
nested for loop and store it two different matrix
named matrix 1 and matrix2.
1 6 9
8 7 0
4 5 3
1 1 9
1 2 0
6 5 3
0
mat 1 mat 2 mat 3
We initialize mat3[i][j] = mat3[0][0] value to 0
We use a for loop to iterate through elements of the i
i th row of mat 1 and j th column of mat 2 and do the
following operations
we add mat1[0][0]*mat2[0][0] to mat3[0][0]
mat3[0][0] = 0 + 1 * 1 = 1
we add mat1[0][1]*mat2[1][0] to mat3[0][0]
mat3[0][0] = 1 + 6 * 1 = 7
we add mat1[0][2]*mat2[2][0] to mat3[0][0]
mat3[0][0] = 7 + 9 * 6 = 61
We multiply every ith row element of mat1 with every
jth column element of mat2 and get sum of it which the
mat[i][j] elements
1 6 9
8 7 0
4 5 3
1 1 9
1 2 0
6 5 3
61
mat 1 mat 2 mat 3
Similary we do the other columns and rows
1 6 9
8 7 0
4 5 3
1 1 9
1 2 0
6 5 3
61 58 36
15 22 72
27 29 45
mat 1 mat 2 mat 3
Array and 2D array hackerrank contest:
https://www.hackerrank.com/string-
contest-1700333838
Practice question
STRINGS IN JAVA
In Java, a string is an object that represents a
sequence of characters.
Strings in Java are immutable, meaning their values
cannot be changed once they are created. Instead,
when you perform operations that seem to modify
a string, a new string is usually created.
HOW TO CREATE STRINGS
1) String Literal:
The most common way to create a string is by using a
string literal, which is a sequence of characters enclosed
in double quotation marks.
EX:
String str1 = "Hello, World!";
2)Using the new Keyword:
You can also create a string using the new keyword and
the String constructor. However, using string literals is
generally preferred for simplicity.
EX:
String str2 = new String("Hello, World!");
EXAMPLE OF STRINGS
public class StringExample{
public static void main(String args[]){
String s1="java";//creating string by Java string literal
char ch[]={'s','t','r','i','n','g','s'};
String s2=new String(ch);//converting char array to string
String s3=new String("example");//creating Java string by new keyword
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
output::
java
strings
example
Java String class methods
The java.lang.String class provides many useful methods
to perform operations on sequence of char values.
1)char charAt(int index)
It returns char value for the particular index
EXAMPLE:
public class CharAtExample{
public static void main(String args[]){
String name="javatpoint";
char ch=name.charAt(4);//returns the char value at the 4th index
System.out.println(ch);
}}
2)compareTo()
The Java String class compareTo() method compares
the given string with the current string
lexicographically. It returns a positive number,
negative number, or 0.
It compares strings on the basis of the Unicode value
of each character in the strings.
EXAMPLE:
System.out.println(s1.compareTo(s2));//0 because both are
equal
System.out.println(s1.compareTo(s3));//-5 because "h" is 5
times lower than "m"
System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times
lower than "m"
System.out.println(s1.compareTo(s5));//2 because "h" is 2
times greater than "f"
}}
public class CompareToExample{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
String s5="flag";
1.
2.
3.
4.
5.
Output: 0
-5
-1
2
If the first string is lexicographically greater than the
second string, it returns a positive number (difference of
character value). If the first string is less than the second
string lexicographically, it returns a negative number, and if
the first string is lexicographically equal to the second
string, it returns 0.
if s1 > s2, it returns positive number
if s1 < s2, it returns negative number
if s1 == s2, it returns 0
3)concat()
The Java String class concat() method combines specified
string at the end of this string. It returns a combined
string. It is like appending another string
public class ConcatExample{
public static void main(String args[]){
String s1="java string";
// The string s1 does not get changed, even though it is invoking
method
// concat(), as it is immutable. Therefore, the explicit assignment is
required here.
s1.concat("is immutable");
System.out.println(s1);
s1=s1.concat(" is immutable so assign it explicitly");
System.out.println(s1);
}}
example:
java string
java string is immutable so assign it explicitly
output:
explanation:
String s1 = "java string";: Initializes a string s1 with the
value "java string".
s1.concat("is immutable");: This line invokes the concat()
method on s1, attempting to concatenate the string "is
immutable" to s1
Prints the original value of s1.. Thus, it prints "java
string".
s1 = s1.concat(" is immutable so assign it explicitly");: This
line concatenates " is immutable so assign it explicitly" to
the string referenced by s1 and assigns the concatenated
string back to s1.
4)contains()
The Java String class contains() method searches the
sequence of characters in this string. It returns true if
the sequence of char values is found in this string
otherwise returns false.
class ContainsExample{
public static void main(String args[]){
String name="what do you know about me";
System.out.println(name.contains("do you know"));
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}}
example:
output:
true
true
false
explanation:
String name = "what do you know about me";: Initializes
a string variable name with the value "what do you
know about me".
System.out.println(name.contains("do you know"));:
Invokes the contains() method on the name string to
check if the substring "do you know" is present within
it. The method returns true if the specified substring is
found, otherwise false. In this case, it prints true
because "do you know" is a part of the name string.
5) endsWith()
The Java String class endsWith() method checks if this
string ends with a given suffix. It returns true if this
string ends with the given suffix; else returns false.
example:
public class EndsWithExample{
public static void main(String args[]){
String s1="java by javatpoint";
System.out.println(s1.endsWith("t"));
System.out.println(s1.endsWith("point")); }}
System.out.println(name.contains("about"));: Similarly, this
line checks if the substring "about" exists within the
name string. It prints true because "about" is present in
the name string.
System.out.println(name.contains("hello"));: Checks if the
substring "hello" is present in the name string. Since
"hello" is not part of name, it prints false.
output:
true
true
explanation:
String s1 = "java by javatpoint";: Initializes a string
variable s1 with the value "java by javatpoint".
System.out.println(s1.endsWith("t"));: The endsWith()
method checks if the string s1 ends with the character
"t". It returns true if s1 ends with the specified
character, otherwise false. In this case, it prints true
because the last character of s1 is indeed "t".
System.out.println(s1.endsWith("point"));: Similarly, this
line checks if s1 ends with the string "point". It prints
true because the string s1 ends with "point".
6)EQUALS()
The Java String class equals() method compares the two
given strings based on the content of the string. If any
character is not matched, it returns false. If all characters
are matched, it returns true.
EXAMPLE:
public class EqualsExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="javatpoint";
String s3="JAVATPOINT";
System.out.println(s1.equals(s2));: Compares s1 and s2.
Since both strings have the same content
("javatpoint"), it returns true.
System.out.println(s1.equals(s3));: Compares s1 and s3.
It returns false because equals() method is case-
sensitive, and s1 ("javatpoint") is not equal to s3
("JAVATPOINT") due to the difference in case.
System.out.println(s1.equals(s4));: Compares s1 and s4.
It returns false because the contents of s1
("javatpoint") and s4 ("python") are different.
String s4="python";
System.out.println(s1.equals(s2));//true because content and case is
same
System.out.println(s1.equals(s3));//false because case is not same
System.out.println(s1.equals(s4));//false because content is not same
}}
OUTPUT:
true
false
false
Explanation:
It returns the index position for the given char value
1)int indexOf(int ch)
There are four overloaded indexOf() method in Java. The
signature of indexOf() methods are given below:
The Java String class indexOf() method returns the position
of the first occurrence of the specified character or string
in a specified string.
7)INDEXOF():
2)int indexOf(int ch, int fromIndex)
It returns the index position for the given char value and
from index
3)int indexOf(String substring)
It returns the index position for the given substring
4)int indexOf(String substring, int fromIndex)
It returns the index position for the given substring
and from index
public class IndexOfExample{
public static void main(String args[]){
String s1="this is index of example";
//passing substring
int index1=s1.indexOf("is");//returns the index of is substring
int index2=s1.indexOf("index");//returns the index of index substring
System.out.println(index1+" "+index2);//2 8
//passing substring with from index
int index3=s1.indexOf("is",4);//returns the index of is substring after
4th index
System.out.println(index3);//5 i.e. the index of another is
//passing char value
int index4=s1.indexOf('s');//returns the index of s char value
System.out.println(index4);//3
}}
EXAMPLE:
OUTPUT:
2 8
5
3
The Java String class isEmpty() method checks if the
input string is empty or not. Note that here empty
means the number of characters contained in a string
is zero.
8)isEmpty()
EXAMPLE:
public class IsEmptyExample{
public static void main(String args[]){
String s1="";
String s2="javatpoint";
System.out.println(s1.isEmpty());
System.out.println(s2.isEmpty());
}}
OUTPUT:
true
false
EXPLANATION:
System.out.println(s1.isEmpty());: Checks if s1 is empty. It
returns true because s1 has no characters, indicating an
empty string.
System.out.println(s2.isEmpty());: Checks if s2 is empty.
It returns false because s2 contains characters, hence
it's not empty.
9)length()
The Java String class length() method finds the length
of a string. The length of the Java string is the same
as the Unicode code units of the string.
EXAMPLE:
public class LengthExample{
public static void main(String args[]){
String s1="javatpoint";
String s2="python";
System.out.println("string length is: "+s1.length());//10 is the
length of javatpoint string
System.out.println("string length is: "+s2.length());//6 is the
length of python string
}}
OUTPUT:
string length is: 10
string length is: 6
EXPLANATION:
System.out.println("string length is: " + s1.length());:
Calculates and prints the length of s1 using the length()
method. It returns 10 because the length of the string
"javatpoint" is 10 characters.
System.out.println("string length is: " + s2.length());:
Computes and displays the length of s2. It returns 6
because the length of the string "python" is 6
characters.
The java string valueOf() method converts different types
of values into string. By the help of string valueOf()
method, you can convert int to string, long to string,
boolean to string, character to string, float to string,
double to string, object to string and char array to string.
EXAMPLE:
public class StringValueOfExample2 {
public static void main(String[] args) {
// Boolean to String
boolean bol = true;
boolean bol2 = false;
String s1 = String.valueOf(bol);
String s2 = String.valueOf(bol2);
System.out.println(s1);
System.out.println(s2);
}
}
OUTPUT:
true
false
EXPLANATION:
boolean bol = true;: Initializes a boolean variable bol
with the value true.
boolean bol2 = false;: Initializes another boolean
variable bol2 with the value false.
1.
2.
10)valueOf()
String s1 = String.valueOf(bol);: Converts the boolean
value bol to a string representation using
String.valueOf(). It converts true to the string "true".
String s2 = String.valueOf(bol2);: Converts the boolean
value bol2 to a string. It converts false to the string
"false".
The System.out.println() statements print the converted
strings s1 and s2.
11) toLowerCase()
The java string toLowerCase() method returns the
string in lowercase letter. In other words, it converts
all characters of the string into lower case letter.
EXAMPLE:
public class StringLowerExample{
public static void main(String args[]){
String s1="JAVATPOINT HELLO stRIng";
String s1lower=s1.toLowerCase();
System.out.println(s1lower);
}}
OUTPUT:
javatpoint hello string
explantion:
String s1 = "JAVATPOINT HELLO stRIng";: Initializes a
string variable s1 with the value "JAVATPOINT HELLO
stRIng".
String s1lower = s1.toLowerCase();: Applies the
toLowerCase() method to the string s1. This method
transforms all the characters in s1 to lowercase and
stores the result in a new string variable s1lower.
System.out.println(s1lower);: Prints the string stored in
s1lower, which contains the lowercase version of the
original string s1.
1.
2.
3.
12)split()
The java string split() method splits this string against
given regular expression and returns a char array.
EXAMPLE:
public class SplitExample{
public static void main(String args[]){
String s1="java string split method";
String[] words=s1.split("s");//splits the string based on whitespace
//using java foreach loop to print elements of string array
for(String w:words){
System.out.println(w);
}
}}
java
string
split
method
OUTPUT:
EXPLANATION:
String s1 = "java string split method by javatpoint";:
Initializes a string variable s1 with the value "java
string split method by javatpoint".
String[] words = s1.split("s");: Splits the string s1 into
substrings using the split() method. In this case, it
splits the string whenever it encounters whitespace ("
") due to the regular expression s. The split() method
returns an array of strings (String[]), and these
substrings are stored in the words array.
for(String w : words) { System.out.println(w); }:
Iterates through the words array using a foreach
loop (for(String w : words)), printing each substring (w)
that resulted from splitting s1 based on whitespace.
The SplitExample Java class demonstrates the usage of
the split() method to split a string based on whitespace.
Here's a simple explanation:
Some of the other comonly used strings in java are:
1)equalsIgnoreCase()
2)format()
3) getBytes()
4)intern()
5)join()
6)replace()
8)replaceAll()
9)startsWith()
Conacatenate two strings
Objective :- Two string will be inputted by the user, these
string must be concatendated and print as a single string
Intuition :- The input strings should be added and stored to
an another variable the displayed
CODE:-
import java.util.Scanner;
public class concat2strings {
public static void mian(String[] args){
Scanner sc =new Scanner(System.in); //create scanner object
String str1 = sc.nextLine(); //read first string
String str2 = sc.nextLine(); //read second string
String str3 = str1 + str2;//concatenate two strings
System.out.println("The concatenated string is "+str3);
}
}
str1 = “Hello”
str2 = “World”
str 3 = str1 + str2
= “Hello” + “World”
str3 = “HelloWorld”
Output :-
The concatenated string is HelloWorld
Explanation :-
Remove vowels from a string
Objective :- Remove the vowels present in the given string
and return it
Intuition :- We go through each letter of the given string
and move only the vowels into a new string and print it.
CODE:-
import java.util.Scanner;
public class removevowels {
public static void main(String[] args){
Scanner sc = new Scanner(System.in); //create scanner object
String str = sc.nextLine(); //read string
String str1 = ""; // result string
for(int i=0;i<str.length();i++){// to iterate through each index
if(str.charAt(i)!='a' && str.charAt(i)!='e' && str.charAt(i)!='i' &&
str.charAt(i)!='o' && str.charAt(i)!='u'){
str1 = str1 + str.charAt(i);// adds the consonants
}
}
System.out.println("The string after removing vowels is "+str1);
}
}
str = “congratulation”
str1 = “”
for loop iterates from i=0 to i= str.length()-1=13
Explanation :-
Value of variable
i
Condition check
Value of
variable str1
0
str[0]=”c”
str[i] not in
“aeiou”
str1=”c”
1
str[1]=”o”
str[i] not in
“aeiou”
str1=”c”
2
str[2]=”n”
str[i] not in
“aeiou”
str1=”cn”
3
str[3]=”g”
str[i] not in
“aeiou”
str1=”cng”
4
str[4]=”r”
str[i] not in
“aeiou”
str1=”cngr”
.
.
.
.
.
.
13
str[13]=”c”
str[i] not in
“aeiou”
str1=”cngrtltn”
14
loop terminates
i < str.size() =
14<14
str1=”cngrtltn”
Display the result string
Reverse a string
Objective:- Print the reverse version for the input string
Intuition :- We go through each letter of the given string
from the end and add it to result string.
CODE:-
import java.util.Scanner;
public class reversestring {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);//create scanner object
String str = sc.nextLine();//read string
String str1 = "";//create empty string to store the reversed string
for(int i=str.length()-1;i>=0;i--){//loop through the string from the
last index
str1 = str1 + str.charAt(i);//add the character to the string
}
System.out.println("The reversed string is "+str1);//print the
reversed string
}
}
Explanation
Str=”excited”
Str1=””
for loop iterates from i=Str.size()-1 to i=0 the i
value decrements after each loop
Value of variable
i
Function
Value of
variable str1
6 str1=str1+”d” str1=”d”
5 str1=str1+”e” str1=”de”
4 str1=str1+”t” str1=”det”
3 str1=str1+”i” str1=”deti”
.
.
.
.
.
.
0 str1=str1+”e” str1=”deticxe”
-1
loop terminates
i >=0 == -1>=0
str1=”deticxe”
Displays the reversed string
Find a word in a given string
Objective:- Given two string A and B check whether B is
present in A
Intuition :- Use two pointers and find a subsequence in
string A that matches String B
CODE:-
import java.util.Scanner;
public class searchword {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);//create scanner object
String str = sc.nextLine();//read string
String str1 = sc.nextLine();//read word to be searched
int flag = 0;//create flag variable
for(int i=0;i<str.length()-str1.length()+1;i++){//loop through the
string
if(str.charAt(i)==str1.charAt(0)){//check if the first character
of the word to be searched is found
int j = 0;
for(j=0;j<str1.length();j++){//loop through the word to be
searched
if(str.charAt(i+j)!=str1.charAt(j)){//check if the characters
of the word to be searched are found
break;
}
}
if(j==str1.length()){//check if the word to be searched is found
flag = 1;
break;
}
}
}
if(flag==1){//check if the word to be searched is found
System.out.println("The word "+str1+" is found in the string
"+str);
}
else{
System.out.println("The word "+str1+" is not found in the string
"+str);
}
}
} Explanation
A = ”excellent”
B = ”lent”
We assign a variable flag to check whether B is present
in A
We use a for loop to iterate through each letter of the
string A
if the letter the at any index of A is similar to the
first letter of B we compare the all the upcoming
letters
If the sequence dont match we break the
statement
Else we make flag True
We repeat above step till we reach end of the string A
A B BOOL I J
EXCELLENT LENT
A[0]!=B[0]
e!=l
0 0
EXCELLENT LENT
A[1]!=B[0]
x!=e
1 0
EXCELLENT LENT
A[2]!=B[0]
c!=n
2 0
EXCELLENT LENT
.
.
.
.
.
.
EXCELLENT LENT
A[5]==B[0]
l==l
5 0
EXCELLENT LENT
A[5+1]!=b[1]
l != e
5 1
EXCELLENT LENT
A[6]==B[0]
l==l
6 0
EXCELLENT LENT
A[6+1]==B[1]
6 1
EXCELLENT LENT A[6+2]==B[2] 6 2
EXCELLENT LENT A[6+3]==B[3] 6 3
EXCELLENT LENT flag=1 6
loop
terminates
EXCELLENT LENT
loop
terminates
if flag is true we say B has been found in A else vice versa
Longest word in a string
Objective:- Find length of the longest word in a given string
Intuition :- We find the length of each word in the string and
store only the max value and return it
CODE:-
import java.util.Scanner;
public class longestwordinsentence {
public static void main(String[] args){
Scanner sc = new Scanner(System.in);//create scanner object
String str = sc.nextLine();//read string
int max=0;//create variable to store the length of the longest
word
int count=0;//create variable to store the length of the current
word
int index=0;//create variable to store the index of the longest
word
while(index<str.length()){//loop through the string
if(str.charAt(index)!=' '){//check if the character is not a space
count++;//increment the count variable
}
else{
if(count>max){//check if the length of the current word is
greater than the length of the longest word
max = count;//assign the length of the current word to the
length of the longest word
}
Explanation
A = ”I am getting better at coding”
We assign variable max=0 to store max length
We assign a variable count=0 to store length of the
current word
We iterate through each letter in the string
if we encounter a space we change the value of max
to maximum of max and count
Then we make count=0 to check the size of the next
word
We repeat the above steps till we reach end of the
string
We again make max maximum of max count to check
whether last word is the largest
We print the length of the longest word
count = 0;//reset the count variable
}
index++;//increment the index variable
}
max = Math.max(max,count);//check if the length of the current
word is greater than the length of the longest word
System.out.println("The length of the longest word in the string
"+str+" is "+max);
}
}
Add binary
Objective:- Given two string A and B which are binary numbers
find the added values
Intuition :- Use the binary addition alogrithm to get the
result string and display it
CODE:-
import java.util.Scanner;
public class BinaryAddition {
public static void main(String[] args) {
// Create a Scanner object for user input
Scanner sc = new Scanner(System.in);
// Prompt the user to enter two binary numbers
System.out.print("Enter the first binary number: ");
String binary1 = sc.nextLine();
System.out.print("Enter the second binary number: ");
String binary2 = sc.nextLine();
// Initialize variables for result and carry
String result = "";
int carry = 0;
// Initialize indices for traversing the binary numbers
int i = binary1.length() - 1;
int j = binary2.length() - 1;
// Perform binary addition
while (i >= 0 && j >= 0) {
int sum = (binary1.charAt(i) - '0') + (binary2.charAt(j) - '0') + carry;
result = (sum % 2) + result;
carry = sum / 2;
i--;
j--;
}
// Handle remaining digits in the first binary number
while (i >= 0) {
int sum = (binary1.charAt(i) - '0') + carry;
result = (sum % 2) + result;
carry = sum / 2;
i--;
}
// Handle remaining digits in the second binary number
while (j >= 0) {
int sum = (binary2.charAt(j) - '0') + carry;
result = (sum % 2) + result;
carry = sum / 2;
j--;
}
// If there is a carry after all additions, add it to the result
if (carry != 0) {
result = carry + result;
}
// Display the result of binary addition
System.out.println("Binary Sum: " + result);
}
}
Explanation
A = “1011”
B = “101”
We assign C = “” to store result
we iterate from the back of bpth strings till we
finish reading either of the bb
i j A[i] B[J]
SUM+
CARRY
CARRY RESULT
3 2 1 1 1+1+0=0 1 “0”
2 1 1 0 1+0+1=0 1 “00”
1 0 0 1 0+1+1=0 1 “000"
LOOP
ENDS
Carry=0
We check if we forgot to add any values from A or B
In this case we have a carry and A has one more
bit
i A[i]
SUM+
CARRY
CARRY RESULT
0 1 1+1=0 1 “0000"
Carry=1
If we have a left over carry we add it to the result
=
result=”10000"
Practice question
String hackerrank contest:
https://www.hackerrank.com/string-
contest-1700333838
Practice question
Loops hackerrank contest:
Array and 2D array hackerrank contest:
String hackerrank contest:
https://www.hackerrank.com/string-
contest-1700333838
https://www.hackerrank.com/string-
contest-1700333838
https://www.hackerrank.com/string-
contest-1700333838
Conditional statement hackerrank contest:
https://www.hackerrank.com/conditi
onal-statement-contest

More Related Content

What's hot

1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology dM Technologies
 
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...Prasant Kumar
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core javaAisha Siddiqui
 
pn junction diodes
pn junction diodespn junction diodes
pn junction diodesvishal gupta
 
ITFT- C,c++,java and world wide web
ITFT- C,c++,java and world wide webITFT- C,c++,java and world wide web
ITFT- C,c++,java and world wide webAtul Sehdev
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of JavaFu Cheng
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in JavaJin Castor
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1RubaNagarajan
 
Applications of op amps
Applications of op ampsApplications of op amps
Applications of op ampsSARITHA REDDY
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)Sujit Majety
 
Java vs JavaScript | Edureka
Java vs JavaScript | EdurekaJava vs JavaScript | Edureka
Java vs JavaScript | EdurekaEdureka!
 

What's hot (20)

Java Tokens
Java  TokensJava  Tokens
Java Tokens
 
1 Introduction To Java Technology
1 Introduction To Java Technology 1 Introduction To Java Technology
1 Introduction To Java Technology
 
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...
PN JUNCTION DIODE IN हिंदी|FORWARD AND REVERSE BIASED OF DIODE|BASIC ELECTRON...
 
A seminar report on core java
A  seminar report on core javaA  seminar report on core java
A seminar report on core java
 
pn junction diodes
pn junction diodespn junction diodes
pn junction diodes
 
ITFT- C,c++,java and world wide web
ITFT- C,c++,java and world wide webITFT- C,c++,java and world wide web
ITFT- C,c++,java and world wide web
 
The Evolution of Java
The Evolution of JavaThe Evolution of Java
The Evolution of Java
 
java ppt.pdf
java ppt.pdfjava ppt.pdf
java ppt.pdf
 
Looping statements in Java
Looping statements in JavaLooping statements in Java
Looping statements in Java
 
Verilog hdl
Verilog hdlVerilog hdl
Verilog hdl
 
Introduction to Java -unit-1
Introduction to Java -unit-1Introduction to Java -unit-1
Introduction to Java -unit-1
 
digital Counter
digital Counterdigital Counter
digital Counter
 
NLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State AutomataNLP_KASHK:Finite-State Automata
NLP_KASHK:Finite-State Automata
 
Applications of op amps
Applications of op ampsApplications of op amps
Applications of op amps
 
Clipper and clampers
Clipper and clampersClipper and clampers
Clipper and clampers
 
JK flip flops
JK flip flopsJK flip flops
JK flip flops
 
Introduction to java (revised)
Introduction to java (revised)Introduction to java (revised)
Introduction to java (revised)
 
Core java
Core java Core java
Core java
 
Varactor diode
Varactor diodeVaractor diode
Varactor diode
 
Java vs JavaScript | Edureka
Java vs JavaScript | EdurekaJava vs JavaScript | Edureka
Java vs JavaScript | Edureka
 

Similar to Java Simplified: Understanding Programming Basics

Similar to Java Simplified: Understanding Programming Basics (20)

Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1Object-Oriented Programming with Java UNIT 1
Object-Oriented Programming with Java UNIT 1
 
Unit1 introduction to Java
Unit1 introduction to JavaUnit1 introduction to Java
Unit1 introduction to Java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java basic
Java basicJava basic
Java basic
 
Core Java
Core JavaCore Java
Core Java
 
Java programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, MysuruJava programming material for beginners by Nithin, VVCE, Mysuru
Java programming material for beginners by Nithin, VVCE, Mysuru
 
Top 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdfTop 10 Important Core Java Interview questions and answers.pdf
Top 10 Important Core Java Interview questions and answers.pdf
 
Java basic concept
Java basic conceptJava basic concept
Java basic concept
 
Java notes | All Basics |
Java notes | All Basics |Java notes | All Basics |
Java notes | All Basics |
 
Introduction to java
Introduction to java Introduction to java
Introduction to java
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENTJava 3 rd sem. 2012 aug.ASSIGNMENT
Java 3 rd sem. 2012 aug.ASSIGNMENT
 
JAVA introduction and basic understanding.pptx
JAVA  introduction and basic understanding.pptxJAVA  introduction and basic understanding.pptx
JAVA introduction and basic understanding.pptx
 
Hello java
Hello java   Hello java
Hello java
 
Hello Java-First Level
Hello Java-First LevelHello Java-First Level
Hello Java-First Level
 
Hello java
Hello java  Hello java
Hello java
 
01slide
01slide01slide
01slide
 
01slide
01slide01slide
01slide
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java programming language
Java programming languageJava programming language
Java programming language
 

Recently uploaded

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxOH TEIK BIN
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application ) Sakshi Ghasle
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxRoyAbrique
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docxPoojaSen20
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionSafetyChain Software
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 

Recently uploaded (20)

ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
 
Solving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptxSolving Puzzles Benefits Everyone (English).pptx
Solving Puzzles Benefits Everyone (English).pptx
 
Hybridoma Technology ( Production , Purification , and Application )
Hybridoma Technology  ( Production , Purification , and Application  ) Hybridoma Technology  ( Production , Purification , and Application  )
Hybridoma Technology ( Production , Purification , and Application )
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptxContemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
Contemporary philippine arts from the regions_PPT_Module_12 [Autosaved] (1).pptx
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 
mini mental status format.docx
mini    mental       status     format.docxmini    mental       status     format.docx
mini mental status format.docx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Mastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory InspectionMastering the Unannounced Regulatory Inspection
Mastering the Unannounced Regulatory Inspection
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 

Java Simplified: Understanding Programming Basics

  • 2. 01 02 Abstract Introduction 03 04 05 06 Java Basics Conditional branching Loops and Nested Loops Array and multidimensional arrays Table of Contents 07 Strings
  • 3. ABSTRACT This project introduces an educational eBook aimed at simplifying Java programming for beginner students. It tackles the common challenge of complex programming concepts by offering clear explanations and visual aids. The eBook integrates interactive examples, quizzes, and step-by-step guidance to promote active learning. The project includes content creation, interactive design, user feedback iteration, and publication, with expected outcomes of enhanced accessibility to Java programming, increased engagement, improved self- learning skills, and empowered students. This resource targets 1st and 2nd-year university students, providing a promising foundation for coding proficiency and expanding career opportunities.
  • 4. INTRODUCTION What is Java? Java is a versatile programming language with a "write once, run anywhere" capability, allowing programs to work on different computers without adjustments. Its simplicity and user-friendly syntax make it an ideal choice for beginners and experienced developers. Java prioritizes safety with built-in features like sandboxing and automatic memory management, making it a top choice for secure applications. Its vibrant developer community provides resources, tutorials, and support to help users tackle everyday challenges. Java is more than just a programming language; it's a dynamic and flexible platform that has shaped numerous software applications.
  • 5. The language began in the early '90s with ambitious intentions to be a groundbreaking technology for the digital cable television industry. The Green Team, a group of brilliant engineers at Sun Microsystems, was formed to create a programming language suitable for digital devices like set-top boxes and televisions. James Gosling, often celebrated as the father of Java, was at the heart of Java's development, setting the stage for one of the most influential programming languages. Java's original name was "Oak," inspired by the robust and enduring qualities of an oak tree. Over the years, it has evolved to be used in a wide array of applications, from Windows and web applications to enterprise and mobile applications. In 1995, Time magazine recognized Java as one of the Ten Best Products of the year, a testament to its growing influence History of Java...
  • 6. The name "Java" was chosen during a coffee-infused discussion, as Java is an island in Indonesia known for producing the first coffee (Java coffee)Java's journey continued with its release by James Gosling at Sun Microsystems in 1995.. Why Java Programming named "Java"? Features of Java simple Its syntax is based on C++, making it a familiar and reassuring transition for those familiar with C++ . Java also removes complexities like explicit pointers and operator overloading, streamlining code and reducing errors. This makes it more welcoming for beginners and those starting their coding journey. Portable Java is portable because it facilitates you to carry the Java bytecode to any platform. It doesn't require any implementation.
  • 7. Java is an object-oriented programming language. Everything in Java is an object. Object-oriented programming (OOPs) is a methodology that simplifies software development and maintenance by providing some rules. Object Class Inheritance Polymorphism Basic concepts of OOPs are: 1. 2. 3. 4. Object - Oriented High Performance Java is faster than other traditional interpreted programming languages because Java bytecode is "close" to native code. It is still a little bit slower than a compiled language (e.g., C++). Java is an interpreted language that is why it is slower than compiled languages, e.g., C, C++, etc.
  • 8. The English meaning of Robust is strong. Java is robust because: It uses strong memory management. There is a lack of pointers that avoids security problems. Java provides automatic garbage collection which runs on the Java Virtual Machine to get rid of objects which are not beingused by a Java application anymore There are exception handling and the type checking mechanism in Java. . Robust A thread is like a separate program, executing concurrently. We can write Java programs that deal with many tasks at once by defining multiple threads. The main advantage of multi-threading is that it doesn't occupy memory for each thread. Multi - threaded
  • 9. JAVA BASICS class Simple { public static void main(String args[]) { System.out.println("HELLO WORLD"); } } Simple Java program: The output will be: HELLO WORLD Explanation : public: Indicates that the main method can be called by any object or class static: Specifies that a method doesn't return anything void: The return type of the main() method main is the entry point for the program and indicates where it should start executing.. Strings args[] : It is used for command line argument (passed at the time of running the java program). System.out.println() will print the output.
  • 10. How to print in java : class Simple { public static void main(String args[]) { System.out.println("WELCOME"); System.out.println("TO"); System.out.println("OUR BOOK"); } } The output will be: WELCOME TO OUR BOOK EXAMPLE 1: class Simple { public static void main(String args[]) { System.out.print("WELCOME"); System.out.print("TO"); System.out.print("OUR BOOK"); } } The output will be: WELCOMETOOUR BOOK EXAMPLE 2:
  • 11. class Simple { public static void main(String args[]) { System.out.print("WELCOME "+”TO”+” OUR BOOK”); } } The output will be: WELCOME TO OUR BOOK EXAMPLE 3: class Simple { public static void main(String args[]) { System.out.print("WELCOMEnTOnOUR BOOK”); } } The output will be: EXAMPLE 4: WELCOME TO OUR BOOK
  • 12. class Simple { public static void main(String args[]) { System.out.print("WELCOMEtTOtOURtBOOK”); } } The output will be: EXAMPLE 5: WELCOME TO OUR BOOK
  • 13. Variables A variable is fundamental to programming because they allow developers to store and manipulate data within their programs. In Java there are certain rules that we must follow when naming variables. They are: Must begin with a letter, dollar sign ($), or underscore (_): After the first character, you can use letters, numbers, underscores, and dollar signs. Cannot be a Java keyword: You cannot use reserved words like int, double, class, etc., as variable names. Case-sensitive: Java is case-sensitive, so myVariable and myvariable would be treated as different variables. No spaces or special characters (except underscore and dollar sign): Variable names cannot contain spaces or most special characters. CamelCase convention: It's a common convention in Java to use CamelCase for variable names, especially for variables representing objects or instances.
  • 14. Note: Variables of a datatype can only contain data of that data type Valid and Invalid Variable Names: int count; : Valid double _price; : Valid String $name; : Valid int int = 5; : Invalid int my Variable; : Invalid Data Types In programming, a data type is a classification that specifies which type of value a variable can hold. There are many data types in Java but we will discuss the ones we use the most in our book int int is the basic 32-bit signed integer datatype. Eg (1,-23,4,-20 etc) Declaration: int num = 10; 1.
  • 15. double Declaration: double n = 3.14159 double is a 64-bit double precision floating point used to represent values of great precision 2. float Declaration: float n = 23.4 float is similar to double, but is 32-bit, single precision floating point 3. boolean Declaration: boolean isThisReal = true boolean represents either true or false, which is used in logical operations and conditions 4. long Declaration: long num = 12343953083587630 long represents a 64-bit signed integer and is used for large numbers 5.
  • 16. char Declaration: char grade = ‘A’ char stands for character. It represents a single 16-bit unicode character 6. String Declaration: String new = “Hello World” Although String isn’t technically a primitive data type, we do use it a lot. String is a class (You will learn about them later) which are used to represent sequences of characters 7. Operator in java : Operators in Java are the symbols used for performing certain operations in Java. Types of Operators in Java: Arithmetic Operators Unary Operators Relational Operators Assignment Operator Logical Operators Ternary Operator Bitwise Operators Shift Operators Instance of operator 1. 2. 3. 4. 5. 6. 7. 8. 9.
  • 17. Arithmetic Operator 1. They are used to perform simple arithmetic operations on primitive data types. * : Multiplication / : Division % : Modulo + : Addition – : Subtraction Types : a + b = 13 a - b = 7 a * b = 30 a / b = 3 a % b = 1 For example: Let a=6 b=7
  • 18. 2. Unary Operators Unary operators need only one operand. They are used to increment, decrement, or negate a value. Types : Increment operator ++ : Increment operator, used for incrementing the value by 1. There are two varieties of increment operators. eg: a++; or ++a; //output will be a=a+1 (a) Post-Increment: Example:- int a = 6; Output System.out.print(a++); 6 System.out.print(a); 7 Value is first used for computing the result and then incremented. (b) Pre-Increment: Example:- int a = 6; Output System.out.print(++a); 7 System.out.print(a); 7 Value is first incremented the used for computing result
  • 19. – – : Decrement operator, used for decrementing the value by 1. There are two varieties of decrement operators. eg: a--; or --a; //output will be a=a-1 (a) Post-decrement: Example:- int a = 6; Output System.out.print(a--); 6 System.out.print(a); 5 Value is first used for computing the result and then decremented. Decrement operator (b) Pre-Decrement: Example:- int a = 6; Output System.out.print(--a); 5 System.out.print(a); 5 The value is decremented first, and then the result is computed.
  • 20. 3. Relational operator There are two types relational operators equality and comparison operators Equality operators != (not equal to) == (equal to) Comparison operators > (greater than) < (lesser than) >= (greater than or equal to) <= (lesser than or equal to) These operator return a true or false values System.out.println(a==b); //print False System.out.println(a>=b); //print True Example :- a=6 b=5 4. Assignment Operator ‘=’ Assignment operator is used to assign a value to any variable. variable = value; General format for assignment operator is:
  • 21. Example: int a=6; System.out.println( “Previous value of a is :” + a); a=10; System.out.println( “Current value of a is :” + a); output: Previous value of a is 6 Current value of a is 10 In many cases, the assignment operator can be combined with other operators to build a shorter version of the statement called a Compound Statement. For example, Instead of a = a+5, we can write a += 5 &= ^= |= <<= >>= >>>= = += -= *= /= %= Instead of a = a*5, we can write a *= 5 Possible Compound statements:
  • 22. 5. Logical Operator These operators are used to perform “logical AND” and “logical OR” operations, i.e., a function similar to AND gate and OR gate in digital electronics. &&, Logical AND: returns true when both conditions are true. ||, Logical OR: returns true if at least one condition is true. !, Logical NOT: returns true when a condition is false and vice-versa Conditional operators are:
  • 23. boolean x = true; boolean y = false; System.out.println("x && y: " + (x && y)); System.out.println("x || y: " + (x || y)); System.out.println("!x: " + (!x)); Example: output: x && y: false x || y: true !x: false
  • 24. How to read user input in java?? Scanner class In Java, Scanner is a class in java.util package used for obtaining the input of the primitive types like int, double, etc. and strings. Using the Scanner class in Java is the easiest way to read input in a Java program. Value of i Output nextBoolean() Used for reading Boolean value nextDouble() Used for reading Double value nextFloat() Used for reading Float value nextInt() Used for reading Int value nextLine() Used for reading Int value nextLong() Used for reading Long value nextShort() Used for reading Short value As the name of the command these things read the next occurrence of the data type in the terminal
  • 25. Write a program to accept the details of college student. import java.util.Scanner; public class ScannerDemo1 { public static void main(String[] args) { // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // String input String name = sc.nextLine(); // Character input char gender = sc.next().charAt(0); // Numerical data input // byte, short and float can be read // using similar-named functions. int age = sc.nextInt(); long mobileNo = sc.nextLong(); double cgpa = sc.nextDouble(); // Print the values to check if the input was // correctly obtained. System.out.println("Name: " + name); System.out.println("Gender: " + gender); System.out.println("Age: " + age); System.out.println("Mobile : " + mobileNo); System.out.println("CGPA: " + cgpa); } } Code:-
  • 26. Gowri manoj F 20 1234567 9.17 Sample input :- Sample output :- Name: Gowri manoj Gender: F Age: 20 Mobile: 1234567 CGPA: 9.17
  • 27. Conditional Branching Conditional branching is a fundamental programming concept used to make decisions, it allows you to execute different blocks of code depending on whether a specified condition is true or false. if-else statement: 1. The if-else statement allows you to specify one block of code to execute if a condition is true and another block to execute if the condition is false. if (condition) { // Code to be executed if the condition is true } else { // Code to be executed if the condition is false } Implementation:
  • 28. Objective-To find the greatest of 2 number int number = 3; if (number > 5) { System.out.println("The number is greater than 5."); } else { System.out.println("The number is not greater than 5."); } Code- Explanation- This Java code initializes a variable number with the value 3. It then checks whether the value of number is greater than 5. If the condition is true, it prints "The number is greater than 5." to the console. If the condition is false, it prints "The number is not greater than 5." instead. In this case, since the value of number is 3, the else block will be executed, and "The number is not greater than 5." will be printed. 1. 2.
  • 29. Objective-To check whether the person is eligible to vote or note public class EligibilityCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the age System.out.print("Enter your age: "); int age = scanner.nextInt(); // Check eligibility if (age >= 18) { System.out.println("You are eligible to vote!"); } else { System.out.println("You are not eligible to vote yet."); } // Close the scanner scanner.close(); } Explanation- Code- It starts by creating a Scanner object to read user input. The program prompts the user to enter their age, reads the input, and then checks if the entered age is 18 or older. 1.
  • 30. Objective- To check whether a year is leap or not. public class LeapYearCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the year System.out.print("Enter a year: "); int year = scanner.nextInt(); // Check if it's a leap year if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)) { System.out.println(year + " is a leap year."); } else { System.out.println(year + " is not a leap year."); } // Close the scanner scanner.close(); } Code- If the age is 18 or above, it prints "You are eligible to vote!" to the console; 2. otherwise, it prints "You are not eligible to vote yet." The program then closes the Scanner to release system resources.
  • 31. Explanation- It starts by creating a Scanner object to read user input. The program prompts the user to enter a year, reads the input, and then checks if the entered year satisfies the leap year conditions. A year is a leap year if it is divisible by 4 but not divisible by 100, or it is divisible by 400. If the conditions are met, it prints "is a leap year" to the console“; otherwise, it prints "is not a leap year." Finally, the program closes the Scanner to release system resources. 1. 2. 2. if-elif-else Statement: The if-else if-else statement allows you to test multiple conditions in a cascading manner and execute different code blocks based on the first true condition encountered. Implementation: if (condition1) { // Code to be executed if condition1 is true } else if (condition2) { // Code to be executed if condition2 is true } else { // Code to be executed if no previous condition is true }
  • 32. Objective- To find the greatest of 3 numbers. public class GreatestOfThreeNumbers { public static void main(String[] args) { int num1 = 10; int num2 = 20; int num3 = 15; if (num1 > num2 && num1 > num3) { System.out.println("The greatest number is num1: " + num1); } else if (num2 > num1 && num2 > num3) { System.out.println("The greatest number is num2: " + num2); } else { System.out.println("The greatest number is num3: " + num3); } } } Explanation- This program determines the greatest among three numbers: num1, num2, and num3. It initializes these numbers with values 10, 20, and 15, respectively. The program uses a series of if-else statements to compare the numbers and identify the greatest one. If num1 is greater than both num2 and num3, it prints a message stating that num1 is the greatest. If num2 is greater than both num1 and num3, it prints a message stating that num2 is the greatest. 1. 2. Code-
  • 33. public class PositiveNegativeZeroCheck { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the number System.out.print("Enter a number: "); int number = scanner.nextInt(); // Check positivity, negativity, or zero 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."); } // Close the scanner scanner.close(); } Objective-To Check whether the entered number is positive or negative or zero. Code-
  • 34. This program checks whether a user-inputted number is positive, negative, or zero. It begins by creating a Scanner object to read user input. The program prompts the user to enter a number, reads the input, and then uses a series of if-else statements to determine whether the number is positive, negative, or zero. If the number is greater than 0, it prints "The number is positive." If the number is less than 0, it prints "The number is negative." If neither condition is met, it concludes that the number is zero and prints "The number is zero." Finally, the program closes the Scanner to release system resources 1. 2. 3. Explanation-
  • 35. public class SalaryClassification { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the salary System.out.print("Enter your salary: "); double salary = scanner.nextDouble(); // Classify the salary if (salary < 0) { System.out.println("Invalid salary. Please enter a non-negative value."); } else if (salary < 20000) { System.out.println("Low income bracket."); } else if (salary < 50000) { System.out.println("Moderate income bracket."); } else if (salary < 100000) { System.out.println("High income bracket."); } else { System.out.println("Very high income bracket."); } // Close the scanner scanner.close(); } Objective -Write a program to classify a person's salary into different income Code-
  • 36. Explanation- This program takes input for a person's salary, classifies it into different income brackets, and prints a corresponding message based on the entered salary. It starts by creating a Scanner object to read user input. The program prompts the user to enter their salary, reads the input, and then uses if-else if-else statements to classify the salary into various income brackets. If the entered salary is negative, it prints an error message. If the salary is less than 20,000, it prints "Low income bracket." If it's between 20,000 and 50,000, it prints "Moderate income bracket." If it's between 50,000 and 100,000, it prints "High income bracket." If the salary is 100,000 or more, it prints "Very high income bracket." Finally, the program closes the Scanner to release system resources. 1. 2. 3. 4. 5.
  • 37. 3. Nested if-else statement- We can use nested if-else statements to create a structure where one set of if-else conditions is contained within another. This allows for more complex decision- making based on multiple criteria . Implementation- Define your conditions: Identify the conditions you want to check. Write the outer if-else statement: This serves as the primary condition. Write the inner if-else statement: This is nested within the true block of the outer if statement. Provide the actions or statements to execute: Specify what should happen based on the combined conditions. 1. 2. 3. 4. if(condition){ //code to be executed if(condition){ //code to be executed } }
  • 38. public class MilitarySelection { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input age System.out.print("Enter your age: "); int age = scanner.nextInt(); // Input physical fitness score (out of 100) System.out.print("Enter your physical fitness score (out of 100): "); int fitnessScore = scanner.nextInt(); // Nested if-else loop to determine military selection eligibility if (age >= 18) { System.out.println("You meet the minimum age requirement.") if (fitnessScore >= 70) { System.out.println("Congratulations! You are eligible for military selection.")} else { System.out.println("Your physical fitness score is below the required threshold."); System.out.println("Consider improving your fitness to meet the eligibility criteria."); } } else { Code- Objective- Write a program to determine the military selection eligibility based on age and physical fitness
  • 39. Explanation System.out.println("You must be at least 18 years old to be eligible for military selection."); } // Close the scanner scanner.close(); } This program, determines eligibility for military selection based on user input for age and physical fitness score. It uses a nested if-else loop to make decisions based on multiple criteria. The program prompts the user to input their age and physical fitness score. The outer if-else statement checks if the age is 18 or older. If true, it proceeds to the inner if-else statement. The inner if-else statement checks if the physical fitness score is 70 or higher. If true, it prints a message congratulating the user on being eligible for military selection. If the age condition in the outer if-else is not met, it prints a message about the minimum age requirement. If the fitness score condition in the inner if-else is not met, it prints a message indicating that the fitness score is below the required threshold and suggests improving fitness. 1. 2. 3.
  • 40. This nested structure allows the program to provide detailed feedback based on both age and physical fitness. Objective-Write a program for college scholarship eligibility using a nested if-else loop if (income < 50000) { System.out.println("You qualify for a full scholarship."); } else if (income >= 50000 && income < 75000) { System.out.println("You qualify for a partial scholarship."); } else { System.out.println("Your income is above the scholarship threshold."); } public class CollegeScholarship { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); // Input the GPA System.out.print("Enter your GPA: "); double gpa = scanner.nextDouble(); // Input the family income System.out.print("Enter your family's annual income: "); double income = scanner.nextDouble(); // Nested if-else loop to determine scholarship eligibility if (gpa >= 3.5) { System.out.println("Congratulations! You are eligible for a scholarship."); Code-
  • 41. Practice question Conditional statement hackerrank contest: https://www.hackerrank.com/conditi onal-statement-contest
  • 42. It allows users to repeat a block of code multiple times.They enable you to automate repetitive tasks and process large amounts of data efficiently. Loops are one of the most essential constructs required to learn programming. for while do while In Java, there are three types of loops: 1. 2. 3. For Loop This loop is used when you have a pre existing idea for the number of iterations Syntax: for (initialisation, condition; update){ Code Block } initialisation: Executed once in the start. Usually a loop control variable condition: As long as this condition is met, the loop will continue update: Executed per each iteration. Usually used to modify the loop control variable LOOPS
  • 43. Let’s say you didnlt provide a condition statement... the loop will continue on forever (until your system can handle it) Same thing will happen if you don’t provide a update statement but the result will be different class HelloWorld { public static void main(String[] args) { int i =0; for(i=0;i<=10;){ System.out.print(i+" "); } } } Output : 0 0 0 0 0 . . . . . ∞ class HelloWorld { public static void main(String[] args) { int i =0; for(i=0; ;i++){ System.out.print(i+" "); } } } Output : 1 2 3 4 5 . . . . . . ∞
  • 44. However, if there is a problem with the initialisation part of the loop, the code will not be recognised Examples: import java.util.Scanner; public class printnnum{ public static void main(String[] args) { Scanner sc = new Scanner(System.in); //Scanner class is used to take input from user int n = sc.nextInt(); //Taking input from user for(int i=1 ; i<=n ; i++){ //for loop iterates from 1 to n System.out.println(i); //printing each i value of loop } } } Intuition : We have start with number 1 and print all numbers upto number n one after another 1. Write a program which prints n numbers Code-
  • 45. Value of i Output 1 1 2 1 2 3 1 2 3 . . . . . . Explanation: First we accept the number until which we want to print to and store it in a variable n We start the loop at i = 1 and set it to iterate until the condition “i<=n” is met Then we print ‘i’
  • 46. 2.Write a program to print even numbers Intuition : We have start with number 0 and print all even numbers upto number n one after another Code - import java.util.Scanner; public class printevennums { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); // Taking upto which number we have to print for(int i=0 ; i<=n ; i+=2){ // for loop iterates from 0 to n with increment of 2 System.out.println(i); // printing each i value of loop } } }
  • 47. Value of i Output 0 0 2 0 2 4 0 2 4 6 0 2 4 6 . . . . . . First we accept the number until which we want to print to and store it in a variable n We start the loop at i = 1 and set it to iterate until the condition “i<=n” is met, but this time instead of iterating i by 1, we iterate it by 2 so that we will print even numbers Then we print ‘i’ Explanation:
  • 48. 3. Write a program to find the sum of the first n numbers Intuition : We have start with number 1 and add all numbers upto number n one after another Code - import java.util.Scanner; public class printsumofn { public static void main(String[] main){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); // Taking upto which number we have to get sum int sum = 0; // variable to store sum for(int i=1 ; i<=n ; i++){ // for loop iterates from 1 to n sum += i; // adding each i value of loop to sum } System.out.println(sum); // printing sum } }
  • 49. Explanation: First we accept the number until which we want to find the sum till and store it in a variable n We initialise a variable sum to 0 (we will be using this to update the sum later) We start the loop at i = 1 and set it to iterate until the condition “i<=n” is met We add i to sum and assign it to sum itself, basically updating sum with i After the loop is finished we print the sum variable Value of i Value of sum initialisation 0 1 1 2 3 3 6 . . . . . .
  • 50. 4. Write a program to find if the given number is prime or not Intuition : We have to check whether the number is divisible by any number other than 1 and itself. If it is divisible then it is not prime else it is prime Code- import java.util.Scanner; public class primenumber{ public static void main (String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Whether the number is prime or not boolean isPrime = true; //variable to store whether the number is prime or not for(int i=2 ; i<n ; i++){ // for loop iterates from 2 to n if(n%i==0){ // if n is divisible by i isPrime = false; // then n is not prime break; // break the loop } }
  • 51. First we accept the number we want to verify being prime or not and store it in n We initialise a boolean ‘isPrime’ to True. This will store whether the number is prime or not We start the loop at i = 2 and set it to iterate until the condition “i<n” is met We check if the modulus of the number with i is 0 or not (divisible) If divisible, then we change isPrime to false ad break the loop as there is a factor for the number If not we proceed to an if block which checks the condition of our boolean variable, according to which we can determine if the number is prime or not if(isPrime){// if isPrime is true System.out.println("Prime");// then n is prime } else{// else System.out.println("Not Prime");// then n is not prime } } } Explanation:
  • 52. Value of i Modulus Value isPrime Value 2 1 True 3 0 False Let’s take 9 as an example Here 9 is divisible by 3 hence making it a non prime number
  • 53. 5. Write a program to find if the given number is perfect or not Intuition : We have to find all the factors of number and add them to get sum then check whether the sum is equal to number or not Code - Note: A perfect number is a number who’s factors (other than itself), added up, equal to itself. Eg. 28 (1+2+4+7+14) import java.util.Scanner; public class perfeectnum { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Taking number which is to be checked int sum = 0; // variable to store sum for(int i=1 ; i<n ; i++){ // for loop iterates from 1 to n if(n%i==0){ // if n is divisible by i sum += i; // adding each i value of loop to sum } }
  • 54. if(sum==n){// if sum is equal to n System.out.println("Perfect Number"); // then n is perfect number } else{// else System.out.println("Not Perfect Number"); // then n is not perfect number } } } Explanation: First we accept the number we want to verify being perfect or not and store it in n We initialise a variable sum to 0 We start the loop at i = 1 and set it to iterate until the condition “i<n” is met We check (using the modulus function) if n is divisible by i If it is we add it to sum and assign it to sum like we did in example 3 Then we are out of the loop and we check if the sum is equal to the number If it is then we print “Perfect Number”, else we print “Not a Perfect Number”
  • 55. Value of i Value of modulus Value of sum 1 0 1 2 0 3 3 1 3 4 0 7 . . 7 0 14 . . 14 0 28 . . 27 1 28 Let’s take 28 Here sum value is equal to the number which we gave, making 28 a perfect number
  • 56. 6. Write a program to find the fibonacci numbers till n Intuition : We have start with number 0 and 1 and print all fibonacci numbers upto number n one after another Code- import java.util.Scanner; public class fibnacci { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); // Taking upto which number we have to print int a=0,b=1,c=0; // initializing a=0,b=1,c=0 System.out.print(a+" "+b+" "); // printing 0 and 1 for(int i=2 ; i<=n ; i++){ // for loop iterates from 2 to n c=a+b;// adding a and b and storing it in c System.out.print(c+" ");// printing c a=b;// assigning b to a b=c;// assigning c to b } } }
  • 57. First, we accept the number n up to which we want to print the Fibonacci series. We initialize three variables a, b, and c to 0, 1, and 0, respectively. These variables will be used to generate the Fibonacci series. We print the initial values of a and b (0 and 1) as the starting points of the Fibonacci series. We start a loop at i = 2 since the first two Fibonacci numbers (0 and 1) are already printed. The loop iterates until the condition i <= n is met. Inside the loop, we calculate the next Fibonacci number (c) by adding the previous two numbers (a and b). We print the calculated Fibonacci number (c). We update the values of a and b for the next iteration. a is assigned the value of b, and b is assigned the value of c. The loop continues to iterate, generating and printing Fibonacci numbers until it reaches the specified limit n. The program concludes, having printed the Fibonacci series up to the specified number n. Explanation:
  • 58. Value of a Value of b Value of c Output 0 1 0 0 1 0 1 1 0 1 1 1 1 2 0 1 1 2 1 2 3 0 1 1 2 3 2 3 5 0 1 1 2 3 5 ... ... ... ...
  • 59. While Loops The while loop is used when we dont know how many times a block of code is to be repeated Syntax: while (condition){ Code Block } The loop continues as long as the condition is true. If we don’t make the condition false, the loop will carry out infinitely class HelloWorld { public static void main(String[] args) { int i=0; while (true) { i++; System.out.print(i + " "); } } } i.e. : Output: 0 1 2 3 4 . . . .
  • 60. Examples: import java.util.Scanner; public class sumofnnat { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Taking upto which number we have to get sum int sum = 0; // variable to store sum int i = 1; // variable to iterate loop while(i<=n){ // while loop iterates from 1 to n sum += i;// adding each i value of loop to sum i++;// incrementing i value } System.out.println(sum);// printing sum } } Write a program to find the sum of the first n numbers Intuition : We have start with number 1 and add all numbers upto number n one after another Code- 1. 1.
  • 61. Explanation: First we accept the number until which we want to find the sum to and store it in a variable n We initialise a variable sum to 0 We initialise i to 1 to start the loop We give the condition “i<=n” so as long as that is true, the loop will iterate We add i to sum and assign it to sum itself, basically updating sum with i After the loop is finished we print the sum variable Value of i Value of sum initialisation 0 1 1 2 3 3 6 . . . . . .
  • 62. Write a program to find the factorial of n Intuition : We have start with number 1 and multiply all numbers upto number n one after another Code- 2. import java.util.Scanner; public class factorial { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); // Taking number whose factorial we have to find int fact = 1; // initializing fact to 1 while(n>0){ // while loop iterates from 1 to n fact = fact * n; // multiplying each i value of loop to fact n--; // decrementing n value } System.out.println(fact);// printing fact } }
  • 63. Explanation: First we accept the number until which we want to find the factorial and store it in a variable n We initialise a variable fact to 1 We give the condition “n>0” so as long as that is true, the loop will iterate We then multiply fact with n and store the result in fact itself We decrement n When the loop is finished we print out the fact Value of n Value of fact 4 4 3 12 2 24 1 24
  • 64. Write a program to find if a number is an armstrong number or not (cube of the digits of the number is the number itself) Intuition : We have to get each digit of number and cube it and add it to sum then check whether the sum is equal to number or not Code- 3. import java.util.Scanner; public class armstrong { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Taking number which is to be checked int temp = n; // storing n in temp variable int sum = 0; // variable to store sum while(temp>0){ // while loop iterates until temp is greater than 0 int rem = temp%10; // storing remainder of temp divided by 10 sum += rem*rem*rem; // adding cube of remainder to sum temp /= 10;
  • 65. // dividing temp by 10 } if(sum==n){ // if sum is equal to n System.out.println("Armstrong Number"); // then n is armstrong number } else{// else System.out.println("Not Armstrong Number"); // then n is not armstrong number } } } Explanation: Take number to be checked and store it in the variable n We store the number in a temporary variable so that the original number can be used later Initialise a variable “sum” to 0 We will iterate the while loop till the condition ‘temp > 0’ is not satisfied We find out the least significant bit (number in unit’s place) by mod 10 and store it to ‘rem’. This is how we can find the individual cubes of each digit Then we cube ‘rem’ and add it with the sum and store it to the sum variable
  • 66. We change the temp number by dividing it by 10 and storing it to temp so that the previous LSB is gone This process is carried out until the loop is finished Then we check if sum is equal to n. If it is we print “Armstrong Number”, if it’s not, we print “Not an Armstrong Number” Write a program to find the Compound Interest after a set amount of years Intuition : We have to add the interest for each year to the already existing interest Code- 4. import java.util.Scanner; public class compoundintrest { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs float p = sc.nextInt(); // Taking principal amount float r = sc.nextInt(); // Taking rate of intrest in percentage int t = sc.nextInt(); // Taking number of years
  • 67. while(t>0){ // while loop iterates from t to 1 p = p + (p*r)/100; // adding each i value of loop to sum t--; // decrementing t value } System.out.println(p);// printing sum } } Explanation: Take Principal amount, Rate of Interest, and Time in variables, p, r, t, respectively We put the condition “t>0” i.e. the loop will repeat until t is lesser than or equal to 0 Inside the loop block, we multiply p with r and divide it by 100 (we took r in percentage) Then we add p to it and store it back in p as the new principal amount This happens till the loop is finished Finally we print out the final amount after t years of r rate of interest on the amount p
  • 68. Value of t Value of p 3 10000 2 10500 1 10125.25 0 10125.25 p= 10000, r = 5%, t = 3 years
  • 69. Nested Loops Nested loops are basically loops within a loop. The outer loop will iterate every time the inner loop finishes it’s entire sequence of iterations. This type of nested looping should be handled carefully as the time complexity can quickly get out of hand Examples: Write a program to find the prime numbers within 0-n Intuition : We have to check whether the number is divisible by any number other than 1 and itself. If it is divisible then it is not prime else it is prime. We have to check this for all numbers from 2 to n. If we find any number which is not prime then we have to break the loop and check for next number. If we don't find any number which is not prime then we have to print that number. We have to do this for all numbers from 2 to n 1.
  • 70. import java.util.Scanner; public class allprimeswithinn { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); // Taking upto which number we have to print for(int i=2 ; i<=n ; i++){ // for loop iterates from 2 to n boolean isPrime = true; //boolean variable to check whether i is prime or not for(int j=2 ; j<i ; j++){ // for loop iterates from 2 to i if(i%j==0){ // if i is divisible by j isPrime = false; break; // break the loop } } if(isPrime){// if i is prime System.out.println(i);// print i } } } } Code-
  • 71. Explanation: We read the number till which we need to print prime numbers till and store it in n The outer loop (for (int i = 2; i <= n; i++)) iterates through numbers from 2 to n. Inside the outer loop, there's an inner loop (for (int j = 2; j < i; j++)) that checks whether the current number i is prime or not. If i is divisible by any number j in the range from 2 to i-1, isPrime is set to false, and the inner loop breaks. After the inner loop, if isPrime is still true, it means that i is a prime number, and it is printed. Write a program to print an nxn grid of ‘*’ 2. Intuition : We have to print a pattern of n*n stars import java.util.Scanner; public class pattern1 { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Taking the size of pattern Code-
  • 72. for(int i=1 ; i<=n ; i++){ // for loop iterates from 1 to n for(int j=1;j<=n;j++){ // for loop iterates from 1 to n System.out.print("*");// printing * } System.out.println();// going to next line } } } Explanation: We read the number which represents the pattern size The outer loop (for (int i = 1; i <= n; i++)) iterates from 1 to n and represents the rows of the square pattern. Inside the outer loop, there's an inner loop (for (int j = 1; j <= n; j++)) that iterates from 1 to n and represents the columns of each row. In the inner loop, the program prints an asterisk (*) for each column. After printing all the asterisks in a row (inner loop), the program uses System.out.println() to move to the next line, creating a new row in the square pattern. This pattern consists of n rows and n columns, and each element in the pattern is an asterisk (*).
  • 73. Value of i Value of j Output screen 0 0 1 * 2 (inner loop terminates) ** 1 0 ** 1 ** * 2 (inner loop terminates) ** ** 2 (outer loop terminates) ** ** Write a program to print the following pattern 2. Intuition : We have to print a pattern of increasing number of + from 1 to n. We have to print n-i spaces and i + one after another + ++ +++ ++++
  • 74. Code- import java.util.Scanner; public class pattern1 { public static void main(String[] args){ Scanner sc = new Scanner(System.in) // Scanner object to read inputs int n = sc.nextInt(); //Taking the size of pattern for(int i=1 ; i<=n ; i++){ // for loop iterates from 1 to n for(int j=1 ; j<=n-i ; j++){ // for loop iterates from 1 to n-i System.out.print(" "); // printing space } for(int j=1 ; j<=i ; j++){ // for loop iterates from 1 to i System.out.print("+"); // printing + } System.out.println();// printing new line } } }
  • 75. Explanation: We read the number which represents the pattern size and store it in n The outer loop (for (int i = 1; i <= n; i++)) iterates from 1 to n and represents the rows of the pattern. Inside the outer loop, there's an inner loop 1 (for (int j = 1; j <= n - i; j++)) that iterates from 1 to (n - i) and represents the spaces at the beginning of each row. Following inner loop 1, there's another inner loop 2 (for (int j = 1; j <= i; j++)) that iterates from 1 to i and represents the plus signs (+) in each row. After printing all the spaces and plus signs in a row, the program uses System.out.println() to move to the next line, creating a new row in the pattern. The result is a pattern where each row starts with spaces, and the number of plus signs increases with the row number. Value of i Value of j (space) Value of j (“+”) Output screen 1 2 1 + 2 1 1 + + 2 + ++
  • 76. 3 0 1 + ++ + 2 + ++ ++ 3 + ++ +++ Write a program to print a pascal’s triangle 3. Intuition : We have to print a pattern of pascal triangle of size n. We have to print n-i spaces and i+1 numbers according to row number. We have to calculate number for next iteration using formula number = number * (i-j)/(j+1). We have to print number and space one after another. We have to go to next line after each row. We have to print 1 in first row. We have to print 1 1 in second row Code- import java.util.Scanner; public class pascaltriangle { public static void main(String[] args){ Scanner sc = new Scanner(System.in); // Scanner object to read inputs int n = sc.nextInt(); //Taking the size of pattern 1 1 1 1 2 1 1 3 3 1 1 4 6 4 1 Example-
  • 77. for(int i=0 ; i<n ; i++){ // for loop iterates from 0 to n int number = 1; // initializing number to 1 for(int space=0 ; space<n-i ; space++){ // for loop iterates from 0 to n-i System.out.print(" "); // printing space } for(int j=0 ; j<=i ; j++){ // for loop iterates from 0 to i System.out.print(number+" "); // printing number number = number * (i-j)/(j+1); // calculating number for next iteration } System.out.println();// going to next line } } }
  • 78. Explanation: We read the number which represents the pattern size and store it in n The outer loop (for (int i = 0; i < numRows; i++)) iterates through each row. Before printing each row, spaces are added to align the triangle. The inner loop (for (int j = 0; j <= i; j++)) calculates and prints the numbers in each row of Pascal's Triangle. The value of each number is calculated using the formula number = number * (i - j) / (j + 1). After printing each row, the program uses System.out.println() to move to the next line. When you run this program and input the number of rows, it will display Pascal's Triangle with the specified number of rows. Value of i Value of j (space) Value of j (“+”) Output screen 1 2 1 1 2 1 1 1 1 2 1 1 1
  • 79. 3 0 1 1 1 1 1 2 1 1 1 1 2 3 1 1 1 1 2 1
  • 81. ARRAY IN JAVA Syntax to Declare an Array in Java: Java array is an object which contains elements of a similar data type. The elements of an array are stored in a contiguous memory location. Array in Java is index-based, the first element of the array is stored at the 0th index, 2nd element is stored on 1st index and so on. dataType[] arr=new datatype[size]; Eg: int[] arr=new int[3]; arr[0]=1; arr[1]=2; arr[2]=3; Now array becomes:[1,2,3] int[] arr=new float[3]; arr[0]=9.2; arr[1]=6.9; arr[2]=3.2; Now array becomes:[9.2,6.9,3.2] 1 2 3 4 5 0 1 2 3 4 array length - 5 - indices arr[2] returns 3
  • 82. Note: In Java, arrays are mutable. This means that you can change the values of individual elements in an array after it has been initialized. Eg: int[] arr={1,2,3,4,5}; arr[1]=6;//Element at index one have been changed to 6 Now array becomes:[1,6,3,4,5] INSERTION AND PRINTING AN ARRAY OF SIZE N: Objective : - To accept n integer array and display the array. Intuition :- We need to create a integer array capable of storing n integers. Then print each element of the array in order. import java.util.Scanner; public class Sample { public static void main(String[] args) { //Scanner class for getting input from user Scanner sc=new Scanner(System.in); int n; // Getting value for array size n=sc.nextInt(); int myArr=new int[n];//Declaring array of size n Code-:
  • 83. //Inputting elements to array for(int i=0;i<n;i++) { myArr[i]=sc.nextInt(); } System.out.println(“Array is:”); //printing elements of array for(int i=0;i<n;i++) { System.out.print(myArr[i]+” , “); } } } Firstly declare an integer n. Now get input from user and store it to variable n using scanner class. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Now we will print each elements in array using for loop which iterates from 0 to n-1 (index of elements) . Explanation :
  • 84. 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 Declare empty array of size 5 Step by step output: Let us assume our n is 5 and user inputs are {1,2,3,4,5}. When i=0 When i=1 When i=2 When i=3 When i=4 0 1 2 3 4 =>Index
  • 85. 0 1 2 3 4 Index=> 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 i i i i i 1 2 3 4 5 OUTPUT: { 1 } { 1 , 2 } { 1 , 2 , 3 } { 1 , 2 , 3 , 4} { 1 , 2 , 3 , 4 ,5 } Largest and smallest element in an array: Objective : - To find and display the largest and smallest element in an array. Intuition :- Accept n sized array and find largest and smallest element in the array and display it.
  • 86. Code:- import java.util.Scanner; public class Sample { public static void main(String[] args) { // Create a Scanner object for user input Scanner sc = new Scanner(System.in); // Prompt the user to enter the size of the array System.out.print("Enter the size of the array: "); int n = sc.nextInt(); // Create an array to store integers int[] myArr = new int[n]; // Input values into the array System.out.println("Enter values for the array:"); for (int i = 0; i < n; i++) { System.out.print("Enter value for myArr[" + i + "]: "); myArr[i] = sc.nextInt(); } // Initialize variables to store the maximum and minimum values int max = myArr[0]; int min = myArr[0]; // Find the maximum and minimum values in the array for (int i = 0; i < n; i++) { if (max < myArr[i]) { max = myArr[i]; } if (min > myArr[i]) { min = myArr[i]; } } // Display the maximum and minimum values System.out.println("Max element is: " + max); System.out.println("Min element is: " + min); } }
  • 87. Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Now we declare two variable to store maximum and minimum element i.e, max and min. And we initialize these variable with 0th index element of that array. Now we iterate through array and check each element that is it greater than max then substitute that element to max variable. Similarly for minimum we check whether every element is less than current minimum element if so, we assign that element to min variable. After the for loop we display the largest element as max and smallest element as min. Explanation : Output: Let our array size be 5 with element {3,4,5,2,1}.We will find the largest and the shortest element. Initially the Min and Max variable is assigned with the initial element in array arr[0] that is 3
  • 88. 0 1 2 3 4 Index=> 3 4 5 2 1 3 4 5 2 1 3 4 5 2 1 3 4 5 2 1 i i i i i 3 4 5 2 1 MIN/MAX VALUE Min=3 Max=3 Min=3 Max=4 Min=3 Max=5 Min=2 Max=5 Min=1 Max=5 The output will be: Max element is 5 and Min element is: 1
  • 89. Second largest element in an array Objective : - To find and display the second largest element in an array. Intuition :- We have to find second largest element in array. So, we have to compare each element of array with max and secondmax. Code-: import java.util.Scanner; public class secondlargest { public static void main(String[] args){ Scanner sc = new Scanner(System.in);// Scanner object to read inputs int n = sc.nextInt();// Taking number of elements in array int[] arr = new int[n];// Declaring array of size n for(int i=0;i<n;i++){// for loop to take array elements as input arr[i] = sc.nextInt();// taking array elements as input } int max = arr[0];// initializing max to first element of array int secondmax = arr[0];// initializing secondmax to first element of array
  • 90. for(int i=0;i<n;i++){// for loop to iterate through array if(arr[i]>max){// if current element is greater than max secondmax = max;// then secondmax will be max max = arr[i];// and max will be current element } else if(arr[i]>secondmax){// if current element is greater than secondmax secondmax = arr[i];// then secondmax will be current element } } System.out.println(secondmax);// printing secondmax } } Explanation : Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Now we declare two varible to store maximum and second maximum element i.e, max and secondmax. And we initialize these variable with 0th index element of that array. Now we iterate through array and check each element that is it greater than max then subtitute that element to max variable and the old value of max will be given to secondmax variable.
  • 91. Output: After the for loop we display the second largest element as secondmax. Let our array size be 5 with element {3,4,5,2,1}.We will find the second largest element. 0 1 2 3 4 Index=> 3 4 5 2 1 3 4 5 2 1 3 4 5 2 1 3 4 5 2 1 i i i i i 3 4 5 2 1 MAX/SECONDMAX VALUE SecondMax=3 Max=3 The output will be: Second largest element is: 4 SecondMax=3 Max=4 SecondMax=4 Max=5 SecondMax=4 Max=5 SecondMax=4 Max=5
  • 92. Reverse an array: Objective : - To reverse an array and display it. Intuition :- Accept n sized array and reverse the array and display it. Code-: import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner sc=new Scanner(System.in); int n; n=sc.nextInt(); // Declaring array of size n int myArr=new int[n]; //Getting array elements from user for(int i=0;i<n;i++) { myArr[i]=sc.nextInt(); } int start = 0; //Initializing start with index 0 int end = arr.length - 1; //Initializing end with index n-1
  • 93. //Reversing the array while (start < end) { int temp = arr[start]; arr[start] = arr[end]; arr[end] = temp; start++ ; end-- ; } System.out.print(“Reversed array is: ”); //Printing the reversed array for(int i=0;i<n;i++) { System.out.print(myArr[i]); } sc.close();//Closing the scanner } }
  • 94. Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Now we declare variables start initialized with 0 and end variable with size-1. Now we iterate while loop till start < end. After the execution of for loop the array will be reversed and we will print it. > At each iteration of the loop we swap the start element and end element > And after swapping the first elements with last elements we increment start variable and decrement the end variable. Explanation : Output: Let us assume our n is 5 and user inputs are {1,2,3,4,5}.And we reverse the array and display the reversed array.
  • 95. 0 1 2 3 4 Index=> 1 2 3 4 5 start output: : swap(arr[start,],arr[end]) Swap(1,5) end 5 2 3 4 1 start end 5 4 3 2 1 start end Swap(3,3) Swap(2,4) 5 4 3 2 1
  • 96. Searching in array : There are two popular ways to search an array in Java: Linear search: This is the simplest search algorithm. It works by comparing the target element to each element in the array until it is found. The time complexity of linear search is O(n), where n is the size of the array. Binary search: This is a more efficient search algorithm. It works by repeatedly dividing the array in half and searching the half that contains the target element. The time complexity of binary search is O(log n), where n is the size of the array. Linear search : Objective : - To search a given element in array using linear search algorithm. Intuition :- Search elements from start to end linearly to find the target element
  • 97. import java.util.Scanner; public class Sample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // Entering the size of the array System.out.print("Enter the size of the array: "); int n = sc.nextInt(); // Create an array to store integers int[] myArr = new int[n]; // Input values into the array System.out.println("Enter values for the array:"); for (int i = 0; i < n; i++) { System.out.print("Enter value for myArr[" + i + "]: "); myArr[i] = sc.nextInt(); } // Prompt the user to enter the key to search System.out.print("Enter the key to search: "); int key = sc.nextInt(); // Search for the key in the array for (int i = 0; i < n; i++) { if (myArr[i] == key) { // If key is found, print a message and exit the loop System.out.println("Element found"); break; } } } } Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Code- Explanation :
  • 98. Output- 0 1 2 3 4 Index=> 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4 5 i i i i OUTPUT: Arr[j]=> 1 != 4=>search element Let our array size be 5 with element {1,2,3,4,5}.And the element to search be 4. Arr[j]=> 2 != 4=>search element Arr[j]=> 3 != 4=>search element Arr[j]=> 4 = 4=>search element Out put will be: Element found Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Now we declare variables start initialized with 0 and end variable with size-1. Now we iterate using for loop and check every element in each index of array .If we find the element in array it will print the message “Element found”.
  • 99. Binary search : Objective : - To search a given element in array using binary search algorithm. Intuition :- Search element using binary search algorithm import java.util.Scanner; public class binarysearch { public static void main(String[] args){ Scanner sc = new Scanner(System.in);// Scanner object to read inputs int n = sc.nextInt();// Taking number of elements in array int[] arr = new int[n];// Declaring array of size n for(int i=0;i<n;i++){// for loop to take array elements as input arr[i] = sc.nextInt();// taking array elements as input } int x = sc.nextInt();// Taking element to be searched int index = -1;// initializing index to -1 int low = 0;// initializing low to 0 int high = n-1;// initializing high to n-1 while(low<=high){// while loop to iterate through array int mid = (low+high)/2;// calculating mid if(arr[mid]==x){// if current element is equal to x index = mid;// then index will be mid break;// break the loop } Code-
  • 100. else if(arr[mid]>x){// if current element is greater than x high = mid-1;// then high will be mid-1 } else{// if current element is less than x low = mid+1; // then low will be mid+1 } } System.out.println("Elment found at index "+index);// printing index } } Explanation : Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. We are given a sorted array. We have to find element x in array. So, we check the middle element of array. If middle element is equal to x then we return index of middle element. If middle element is greater than x then we search in left half of array. If middle element is less than x then we search in right half of array.
  • 101. We repeat above steps until we find x or low becomes greater than high. If we don't find x then we return -1. Output Let our array size be 5 with element {1,2,3,4,5}.And the element to search be 4.
  • 102. SORTING ARRAY USING BUBBLE SORT : Objective : - Sort a given array using buuble sort and print it. Intuition :- Given an array, sort it using bubble sort which compare each element and swaps accordingly. import java.util.Scanner; public class bubblesort { public static void main(String[] args){ Scanner sc = new Scanner(System.in);// Scanner object to read inputs int n = sc.nextInt();// Taking number of elements in array int[] arr = new int[n];// Declaring array of size n for(int i=0;i<n;i++){// for loop to take array elements as input arr[i] = sc.nextInt();// taking array elements as input } for(int i=0;i<n-1;i++){// for loop to iterate through array for(int j=0;j<n-i-1;j++){// for loop to iterate through array if(arr[j]>arr[j+1]){// if current element is greater than nex element int temp = arr[j];// then swap current element with next element arr[j] = arr[j+1]; arr[j+1] = temp; } } } CODE-:
  • 103. Firstly declare an integer n. Now we accept the size of the array and store it in a variable n. Then we accept input from user using a for loop which iterates from 0 to n-1 and stores the input value at its corresponding index. Inside for loop start with the first element and compare the current element with the next element. If the current element is greater than the next element, then swap both the elements. If not, move to the next element. Repeat steps 1 – 3 until we get the sorted list. And after the sorting print the array. Explanation : Let our array size be 5 with element {3,4,5,2,1}.Then the output will be {3,4,5,6,8}. Output: for(int i=0;i<n;i++){// for loop to iterate through array System.out.print(arr[i]+" ");// printing array elements } } }
  • 104. 1 2 3 4 5 Index=> 5 3 8 4 6 MIN/MAX VALUE Initial unsorted array 3 5 8 4 6 3 5 8 4 6 3 5 4 8 6 Compare first and second element (swap) Compare second and third element (not swap) Compare third and fourth element (swap) 3 5 4 6 8 Compare fourth and fifth element (swap) When i=0 j j j+1 j j+1 j j+1 j j+1 When i=1 3 4 5 6 8 Compare second and third element (swap) 3 4 5 6 8 Compare first and second element (not swap) j j+1
  • 105. The ouput will be: 3 4 5 6 8 Similarly repeat these steps until no more swaps required. That is until i<n-1 . j j+1 3 4 5 6 8 Compare third and fourth element (not swap) j j+1 Rotation of array by d number of rotation : Objective : - Rotate an array k times Intuition :- We take a temporary array and add last k elements to the beginning of array and rest to end Code- import java.util.Scanner; public class RotatingArray { public static void main(String[] args){ Scanner sc = new Scanner(System.in);// Scanner object to read inputs int n = sc.nextInt();// Taking number of elements in array int[] arr = new int[n];// Declaring array of size n for(int i=0;i<n;i++){// for loop to take array elements as input arr[i] = sc.nextInt();// taking array elements as input }
  • 106. int[] arr2= new int[n];// Declaring array of size n //first half for(int i=0;i<d;i++){// for loop to iterate through array arr2[i] = arr[n-d+i];// storing last d elements in arr2 } int d = sc.nextInt();// Taking number of rotations d=d%n;// if d>n then d=d%n //second half for(int i=d;i<n;i++){// for loop to iterate through array arr2[i] = arr[i-d];// storing first n-d elements in arr2 } arr=arr2;// copying arr2 to arr for(int i=0;i<n;i++){// for loop to iterate through array System.out.print(arr[i]+" ");// printing array elements } } } Explanation : 5 3 8 4 6 k=8 k-rotations Since the size of array is less than rotations we make k k=k%(sizeofarray) We declare new array similar to given array to store rotated array k=8%5=3 Accept the array and number of rotations from the user
  • 107. 5 3 8 4 6 After k rotations first half of the rotated array would start from n-k th position so we use a for loop to add these elements to result array 5 3 8 4 6 8 4 6 After k rotations second half of the rotated array would start from 0 th position to n-k th position so we use a for loop to add these elements to result array 5 3 8 4 6 8 4 6 5 3
  • 108. data_type[ ][ ] array_name = new data_type[x][y]; 1 2 3 4 5 6 7 8 9 Multidimensional Arrays can be defined in simple words as array of arrays. Data in multidimensional arrays are stored in tabular form MULTIDIMENSIONAL ARRAY IN JAVA : Syntax to Declare an Array in Java: For example: int[][] matrix=new int[3][3]; matrix={{1,2,3},{4,5,6},{7,8,9}}; The matrix will be: 0 1 2 Index 0 1 2
  • 109. Indexing in a 3 X 3 matrix (0,0) (0,1) (0,2) (1,0) (1,1) (1,2) (2,0) (2,1) (2,2) 0 1 2 Index 0 1 2 Let the input values be: (0,0)=>1 (0,1)=>2 (2,2)=>9 (2,1)=>8 (0,2)=>3 (1,0)=>4 (1,1)=>5 (1,2)=>6 (2,0)=>7 Now the matrix will be: 1 2 3 4 5 6 7 8 9 0 1 2 Index 0 1 2
  • 110. import java.util.Scanner; public class MatrixInsertion { public static void main(String[] args) { int rows = 3; int cols = 3; int[][] matrix = new int[rows][cols]; Scanner scanner = new Scanner(System.in); System.out.print("Enter value for matrix”); // Insert values into the matrix for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i][j] = scanner.nextInt(); } } 2D array insertion and printing: Objective : - Create a matrix using given number of rows and columns and display it. Intuition :- Given number of rows and columns , we have to create a matrix and input values to corresponding cell from user and display it. Code-
  • 111. // Display the matrix System.out.println("nMatrix:"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { System.out.print(matrix[i][j] + " "); } System.out.println(); } scanner.close(); } } Explanation : First we get input from user for number of rows and columns. Then we accept value for matrix using nested for loop and store it to corresponding cell. And we display the matrix using nested for loop.
  • 112. Let number of rows be 3 and number of column be 3.Let the input be {{1,6,9},{8,7,0},{4,5,3}} Output: 1 6 9 8 7 0 4 5 3 The matrix will be: 0 1 2 Index 0 1 2 The output is: 4 5 3 8 7 0 1 6 9
  • 113. import java.util.Scanner; public class MatrixSearch { public static void main(String[] args) { int rows = 3; int cols = 3; int[][] matrix = new int[rows][cols]; Scanner scanner = new Scanner(System.in); // Entering value for matrix for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { matrix[i][j] = scanner.nextInt(); } } System.out.println("nMatrix:"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { System.out.print(matrix[i][j] + " "); } System.out.println(); } Searching an element in 2D array : Objective : - Search a given element in 2D array and print if element found or not. Intuition :- Given matrix we have to search a value in that matrix and display whether the element is present or not. CODE-:
  • 114. Explanation : First we get input from user for number of rows and columns. Then we accept value for matrix using nested for loop and store it to corresponding cell. The boolean variable found is assigned with false. Then we check each index and check whether the searchvalue is present or not. If element present then we assign the value of found as true. Then if found=true we will display that element is present. System.out.print("nEnter value to search: "); int searchValue = scanner.nextInt(); boolean found = false;//Setting falg to false //Checking each cell for given searchvalue for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { if (matrix[i][j] == searchValue) { found = true; break; } } } if (found) { System.out.println("Value " + searchValue + " found in the matrix."); } // Close the Scanner scanner.close(); } }
  • 115. 1 6 9 8 7 0 4 5 3 0 1 2 Index 0 1 2 The output is: Value of i Value of j Value of found 0 0 false 1 false 2 false 1 0 true Value 8 found in the matrix Let number of rows be 3 and number of column be 3.Let the input be {{1,6,9},{8,7,0},{4,5,3}} and let the given searchvalue be 8. Output: The matrix will be:
  • 116. Addition of 2D array : Objective : - Add two matrix and display the result in a third matrix. Intuition :- Given two matrix perform addition of both matrix and store it to a third matrix and display it. Code- import java.util.Scanner; public class MatrixAddition { public static void main(String[] args) { int rows = 3; int cols = 3; int[][] matrix1 = new int[rows][cols]; int[][] matrix2 = new int[rows][cols]; int[][] resultMatrix = new int[rows][cols]; Scanner scanner = new Scanner(System.in); // Insert values into the first matrix System.out.println("Enter values for the first matrix:"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { System.out.print("Enter value for matrix1[" + i + "][" + j + "]: "); matrix1[i][j] = scanner.nextInt(); } }
  • 117. // Insert values into the second matrix System.out.println("Enter values for the second matrix:"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { System.out.print("Enter value for matrix2[" + i + "][" + j + "]: "); matrix2[i][j] = scanner.nextInt(); } } // Perform matrix addition and store the result in the third matrix for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { resultMatrix[i][j] = matrix1[i][j] + matrix2[i][j]; } } // Display the result matrix System.out.println("nResult Matrix (Matrix1 + Matrix2):"); for (int i = 0; i < rows; ++i) { for (int j = 0; j < cols; ++j) { System.out.print(resultMatrix[i][j] + " "); } System.out.println(); } // Close the Scanner scanner.close(); }
  • 118. Explanation : First we get input from user for number of rows and columns. Then we accept value for first and second matrix using nested for loop and store it two different matrix named matrix 1 and matrix2. Now we perform addition operation for matrix 1 and matrix 2 and store it to resultmatrix using nested for loop. Then we display the resultmatrix using nested for loop. Let number of rows be 3 and number of column be 3.Let the matrix 1 be {{1,6,9},{8,7,0},{4,5,3}} and matrix 2 be {{1,2,3},{4,5,6},{7,8,9}} Output: 1 6 9 8 7 0 4 5 3 + = 1 2 3 4 5 6 7 8 9 5 2 8 12 12 12 6 11 13 12 Matrix 1 Matrix 2 resultmatrix
  • 119. Matrix muliplication : Objective : - Mulitiply two given matrixes A and B Intuition :- Given Two matrix apply the multiplication algorithm and return the resultant matrix Code- import java.util.Scanner; public class matrixmultiplication { public static void main(String[] args){ Scanner sc = new Scanner(System.in);//create scanner object int m = sc.nextInt();//read number of rows of first matrix int n = sc.nextInt();//read number of columns of first matrix int[][] mat1 = new int[m][n];//create first matrix for(int i=0;i<m;i++){//loop through the first matrix for(int j=0;j<n;j++){ mat1[i][j] = sc.nextInt();//read elements of first matrix } } int p = sc.nextInt();//read number of rows of second matrix int q = sc.nextInt();//read number of columns of second matrix int[][] mat2 = new int[p][q];//create second matrix for(int i=0;i<p;i++){//loop through the second matrix for(int j=0;j<q;j++){ mat2[i][j] = sc.nextInt();//read elements of second matrix } }
  • 120. if(n==p){ int[][] mat3 = new int[m][q];//create result matrix for(int i=0;i<m;i++){//loop through the result matrix for(int j=0;j<q;j++){ mat3[i][j] = 0; //initialize elements of result matrix to 0 for(int k=0;k<n;k++){//loop through the first matrix mat3[i][j] += mat1[i][k]*mat2[k][j]; //multiply the matrices } } } for(int i=0;i<m;i++){//loop through the result matrix for(int j=0;j<q;j++){ System.out.print(mat3[i][j]+" "); //print elements of result matrix } System.out.println();//go to next line } } else{ System.out.println("The matrices cannot be multiplied"); //print if the matrices cannot be multiplied } } }
  • 121. Explanation : First we get input from user for number of rows and columns. Then we accept value for first and second matrix using nested for loop and store it two different matrix named matrix 1 and matrix2. 1 6 9 8 7 0 4 5 3 1 1 9 1 2 0 6 5 3 0 mat 1 mat 2 mat 3 We initialize mat3[i][j] = mat3[0][0] value to 0 We use a for loop to iterate through elements of the i i th row of mat 1 and j th column of mat 2 and do the following operations we add mat1[0][0]*mat2[0][0] to mat3[0][0] mat3[0][0] = 0 + 1 * 1 = 1 we add mat1[0][1]*mat2[1][0] to mat3[0][0] mat3[0][0] = 1 + 6 * 1 = 7 we add mat1[0][2]*mat2[2][0] to mat3[0][0] mat3[0][0] = 7 + 9 * 6 = 61 We multiply every ith row element of mat1 with every jth column element of mat2 and get sum of it which the mat[i][j] elements
  • 122. 1 6 9 8 7 0 4 5 3 1 1 9 1 2 0 6 5 3 61 mat 1 mat 2 mat 3 Similary we do the other columns and rows 1 6 9 8 7 0 4 5 3 1 1 9 1 2 0 6 5 3 61 58 36 15 22 72 27 29 45 mat 1 mat 2 mat 3
  • 123. Array and 2D array hackerrank contest: https://www.hackerrank.com/string- contest-1700333838 Practice question
  • 124. STRINGS IN JAVA In Java, a string is an object that represents a sequence of characters. Strings in Java are immutable, meaning their values cannot be changed once they are created. Instead, when you perform operations that seem to modify a string, a new string is usually created. HOW TO CREATE STRINGS 1) String Literal: The most common way to create a string is by using a string literal, which is a sequence of characters enclosed in double quotation marks. EX: String str1 = "Hello, World!"; 2)Using the new Keyword: You can also create a string using the new keyword and the String constructor. However, using string literals is generally preferred for simplicity. EX: String str2 = new String("Hello, World!"); EXAMPLE OF STRINGS public class StringExample{ public static void main(String args[]){ String s1="java";//creating string by Java string literal
  • 125. char ch[]={'s','t','r','i','n','g','s'}; String s2=new String(ch);//converting char array to string String s3=new String("example");//creating Java string by new keyword System.out.println(s1); System.out.println(s2); System.out.println(s3); }} output:: java strings example Java String class methods The java.lang.String class provides many useful methods to perform operations on sequence of char values. 1)char charAt(int index) It returns char value for the particular index EXAMPLE: public class CharAtExample{ public static void main(String args[]){ String name="javatpoint"; char ch=name.charAt(4);//returns the char value at the 4th index System.out.println(ch); }}
  • 126. 2)compareTo() The Java String class compareTo() method compares the given string with the current string lexicographically. It returns a positive number, negative number, or 0. It compares strings on the basis of the Unicode value of each character in the strings. EXAMPLE: System.out.println(s1.compareTo(s2));//0 because both are equal System.out.println(s1.compareTo(s3));//-5 because "h" is 5 times lower than "m" System.out.println(s1.compareTo(s4));//-1 because "l" is 1 times lower than "m" System.out.println(s1.compareTo(s5));//2 because "h" is 2 times greater than "f" }} public class CompareToExample{ public static void main(String args[]){ String s1="hello"; String s2="hello"; String s3="meklo"; String s4="hemlo"; String s5="flag"; 1. 2. 3. 4. 5. Output: 0 -5 -1 2
  • 127. If the first string is lexicographically greater than the second string, it returns a positive number (difference of character value). If the first string is less than the second string lexicographically, it returns a negative number, and if the first string is lexicographically equal to the second string, it returns 0. if s1 > s2, it returns positive number if s1 < s2, it returns negative number if s1 == s2, it returns 0 3)concat() The Java String class concat() method combines specified string at the end of this string. It returns a combined string. It is like appending another string public class ConcatExample{ public static void main(String args[]){ String s1="java string"; // The string s1 does not get changed, even though it is invoking method // concat(), as it is immutable. Therefore, the explicit assignment is required here. s1.concat("is immutable"); System.out.println(s1); s1=s1.concat(" is immutable so assign it explicitly"); System.out.println(s1); }} example:
  • 128. java string java string is immutable so assign it explicitly output: explanation: String s1 = "java string";: Initializes a string s1 with the value "java string". s1.concat("is immutable");: This line invokes the concat() method on s1, attempting to concatenate the string "is immutable" to s1 Prints the original value of s1.. Thus, it prints "java string". s1 = s1.concat(" is immutable so assign it explicitly");: This line concatenates " is immutable so assign it explicitly" to the string referenced by s1 and assigns the concatenated string back to s1. 4)contains() The Java String class contains() method searches the sequence of characters in this string. It returns true if the sequence of char values is found in this string otherwise returns false.
  • 129. class ContainsExample{ public static void main(String args[]){ String name="what do you know about me"; System.out.println(name.contains("do you know")); System.out.println(name.contains("about")); System.out.println(name.contains("hello")); }} example: output: true true false explanation: String name = "what do you know about me";: Initializes a string variable name with the value "what do you know about me". System.out.println(name.contains("do you know"));: Invokes the contains() method on the name string to check if the substring "do you know" is present within it. The method returns true if the specified substring is found, otherwise false. In this case, it prints true because "do you know" is a part of the name string.
  • 130. 5) endsWith() The Java String class endsWith() method checks if this string ends with a given suffix. It returns true if this string ends with the given suffix; else returns false. example: public class EndsWithExample{ public static void main(String args[]){ String s1="java by javatpoint"; System.out.println(s1.endsWith("t")); System.out.println(s1.endsWith("point")); }} System.out.println(name.contains("about"));: Similarly, this line checks if the substring "about" exists within the name string. It prints true because "about" is present in the name string. System.out.println(name.contains("hello"));: Checks if the substring "hello" is present in the name string. Since "hello" is not part of name, it prints false. output: true true
  • 131. explanation: String s1 = "java by javatpoint";: Initializes a string variable s1 with the value "java by javatpoint". System.out.println(s1.endsWith("t"));: The endsWith() method checks if the string s1 ends with the character "t". It returns true if s1 ends with the specified character, otherwise false. In this case, it prints true because the last character of s1 is indeed "t". System.out.println(s1.endsWith("point"));: Similarly, this line checks if s1 ends with the string "point". It prints true because the string s1 ends with "point". 6)EQUALS() The Java String class equals() method compares the two given strings based on the content of the string. If any character is not matched, it returns false. If all characters are matched, it returns true. EXAMPLE: public class EqualsExample{ public static void main(String args[]){ String s1="javatpoint"; String s2="javatpoint"; String s3="JAVATPOINT";
  • 132. System.out.println(s1.equals(s2));: Compares s1 and s2. Since both strings have the same content ("javatpoint"), it returns true. System.out.println(s1.equals(s3));: Compares s1 and s3. It returns false because equals() method is case- sensitive, and s1 ("javatpoint") is not equal to s3 ("JAVATPOINT") due to the difference in case. System.out.println(s1.equals(s4));: Compares s1 and s4. It returns false because the contents of s1 ("javatpoint") and s4 ("python") are different. String s4="python"; System.out.println(s1.equals(s2));//true because content and case is same System.out.println(s1.equals(s3));//false because case is not same System.out.println(s1.equals(s4));//false because content is not same }} OUTPUT: true false false Explanation:
  • 133. It returns the index position for the given char value 1)int indexOf(int ch) There are four overloaded indexOf() method in Java. The signature of indexOf() methods are given below: The Java String class indexOf() method returns the position of the first occurrence of the specified character or string in a specified string. 7)INDEXOF(): 2)int indexOf(int ch, int fromIndex) It returns the index position for the given char value and from index 3)int indexOf(String substring) It returns the index position for the given substring 4)int indexOf(String substring, int fromIndex) It returns the index position for the given substring and from index
  • 134. public class IndexOfExample{ public static void main(String args[]){ String s1="this is index of example"; //passing substring int index1=s1.indexOf("is");//returns the index of is substring int index2=s1.indexOf("index");//returns the index of index substring System.out.println(index1+" "+index2);//2 8 //passing substring with from index int index3=s1.indexOf("is",4);//returns the index of is substring after 4th index System.out.println(index3);//5 i.e. the index of another is //passing char value int index4=s1.indexOf('s');//returns the index of s char value System.out.println(index4);//3 }} EXAMPLE: OUTPUT: 2 8 5 3 The Java String class isEmpty() method checks if the input string is empty or not. Note that here empty means the number of characters contained in a string is zero. 8)isEmpty()
  • 135. EXAMPLE: public class IsEmptyExample{ public static void main(String args[]){ String s1=""; String s2="javatpoint"; System.out.println(s1.isEmpty()); System.out.println(s2.isEmpty()); }} OUTPUT: true false EXPLANATION: System.out.println(s1.isEmpty());: Checks if s1 is empty. It returns true because s1 has no characters, indicating an empty string. System.out.println(s2.isEmpty());: Checks if s2 is empty. It returns false because s2 contains characters, hence it's not empty. 9)length() The Java String class length() method finds the length of a string. The length of the Java string is the same as the Unicode code units of the string.
  • 136. EXAMPLE: public class LengthExample{ public static void main(String args[]){ String s1="javatpoint"; String s2="python"; System.out.println("string length is: "+s1.length());//10 is the length of javatpoint string System.out.println("string length is: "+s2.length());//6 is the length of python string }} OUTPUT: string length is: 10 string length is: 6 EXPLANATION: System.out.println("string length is: " + s1.length());: Calculates and prints the length of s1 using the length() method. It returns 10 because the length of the string "javatpoint" is 10 characters. System.out.println("string length is: " + s2.length());: Computes and displays the length of s2. It returns 6 because the length of the string "python" is 6 characters.
  • 137. The java string valueOf() method converts different types of values into string. By the help of string valueOf() method, you can convert int to string, long to string, boolean to string, character to string, float to string, double to string, object to string and char array to string. EXAMPLE: public class StringValueOfExample2 { public static void main(String[] args) { // Boolean to String boolean bol = true; boolean bol2 = false; String s1 = String.valueOf(bol); String s2 = String.valueOf(bol2); System.out.println(s1); System.out.println(s2); } } OUTPUT: true false EXPLANATION: boolean bol = true;: Initializes a boolean variable bol with the value true. boolean bol2 = false;: Initializes another boolean variable bol2 with the value false. 1. 2. 10)valueOf()
  • 138. String s1 = String.valueOf(bol);: Converts the boolean value bol to a string representation using String.valueOf(). It converts true to the string "true". String s2 = String.valueOf(bol2);: Converts the boolean value bol2 to a string. It converts false to the string "false". The System.out.println() statements print the converted strings s1 and s2. 11) toLowerCase() The java string toLowerCase() method returns the string in lowercase letter. In other words, it converts all characters of the string into lower case letter. EXAMPLE: public class StringLowerExample{ public static void main(String args[]){ String s1="JAVATPOINT HELLO stRIng"; String s1lower=s1.toLowerCase(); System.out.println(s1lower); }} OUTPUT: javatpoint hello string
  • 139. explantion: String s1 = "JAVATPOINT HELLO stRIng";: Initializes a string variable s1 with the value "JAVATPOINT HELLO stRIng". String s1lower = s1.toLowerCase();: Applies the toLowerCase() method to the string s1. This method transforms all the characters in s1 to lowercase and stores the result in a new string variable s1lower. System.out.println(s1lower);: Prints the string stored in s1lower, which contains the lowercase version of the original string s1. 1. 2. 3. 12)split() The java string split() method splits this string against given regular expression and returns a char array. EXAMPLE: public class SplitExample{ public static void main(String args[]){ String s1="java string split method"; String[] words=s1.split("s");//splits the string based on whitespace //using java foreach loop to print elements of string array for(String w:words){ System.out.println(w); } }} java string split method OUTPUT:
  • 140. EXPLANATION: String s1 = "java string split method by javatpoint";: Initializes a string variable s1 with the value "java string split method by javatpoint". String[] words = s1.split("s");: Splits the string s1 into substrings using the split() method. In this case, it splits the string whenever it encounters whitespace (" ") due to the regular expression s. The split() method returns an array of strings (String[]), and these substrings are stored in the words array. for(String w : words) { System.out.println(w); }: Iterates through the words array using a foreach loop (for(String w : words)), printing each substring (w) that resulted from splitting s1 based on whitespace. The SplitExample Java class demonstrates the usage of the split() method to split a string based on whitespace. Here's a simple explanation: Some of the other comonly used strings in java are: 1)equalsIgnoreCase() 2)format() 3) getBytes() 4)intern() 5)join() 6)replace() 8)replaceAll() 9)startsWith()
  • 141. Conacatenate two strings Objective :- Two string will be inputted by the user, these string must be concatendated and print as a single string Intuition :- The input strings should be added and stored to an another variable the displayed CODE:- import java.util.Scanner; public class concat2strings { public static void mian(String[] args){ Scanner sc =new Scanner(System.in); //create scanner object String str1 = sc.nextLine(); //read first string String str2 = sc.nextLine(); //read second string String str3 = str1 + str2;//concatenate two strings System.out.println("The concatenated string is "+str3); } } str1 = “Hello” str2 = “World” str 3 = str1 + str2 = “Hello” + “World” str3 = “HelloWorld” Output :- The concatenated string is HelloWorld Explanation :-
  • 142. Remove vowels from a string Objective :- Remove the vowels present in the given string and return it Intuition :- We go through each letter of the given string and move only the vowels into a new string and print it. CODE:- import java.util.Scanner; public class removevowels { public static void main(String[] args){ Scanner sc = new Scanner(System.in); //create scanner object String str = sc.nextLine(); //read string String str1 = ""; // result string for(int i=0;i<str.length();i++){// to iterate through each index if(str.charAt(i)!='a' && str.charAt(i)!='e' && str.charAt(i)!='i' && str.charAt(i)!='o' && str.charAt(i)!='u'){ str1 = str1 + str.charAt(i);// adds the consonants } } System.out.println("The string after removing vowels is "+str1); } } str = “congratulation” str1 = “” for loop iterates from i=0 to i= str.length()-1=13 Explanation :-
  • 143. Value of variable i Condition check Value of variable str1 0 str[0]=”c” str[i] not in “aeiou” str1=”c” 1 str[1]=”o” str[i] not in “aeiou” str1=”c” 2 str[2]=”n” str[i] not in “aeiou” str1=”cn” 3 str[3]=”g” str[i] not in “aeiou” str1=”cng” 4 str[4]=”r” str[i] not in “aeiou” str1=”cngr” . . . . . . 13 str[13]=”c” str[i] not in “aeiou” str1=”cngrtltn” 14 loop terminates i < str.size() = 14<14 str1=”cngrtltn” Display the result string
  • 144. Reverse a string Objective:- Print the reverse version for the input string Intuition :- We go through each letter of the given string from the end and add it to result string. CODE:- import java.util.Scanner; public class reversestring { public static void main(String[] args){ Scanner sc = new Scanner(System.in);//create scanner object String str = sc.nextLine();//read string String str1 = "";//create empty string to store the reversed string for(int i=str.length()-1;i>=0;i--){//loop through the string from the last index str1 = str1 + str.charAt(i);//add the character to the string } System.out.println("The reversed string is "+str1);//print the reversed string } }
  • 145. Explanation Str=”excited” Str1=”” for loop iterates from i=Str.size()-1 to i=0 the i value decrements after each loop Value of variable i Function Value of variable str1 6 str1=str1+”d” str1=”d” 5 str1=str1+”e” str1=”de” 4 str1=str1+”t” str1=”det” 3 str1=str1+”i” str1=”deti” . . . . . . 0 str1=str1+”e” str1=”deticxe” -1 loop terminates i >=0 == -1>=0 str1=”deticxe” Displays the reversed string
  • 146. Find a word in a given string Objective:- Given two string A and B check whether B is present in A Intuition :- Use two pointers and find a subsequence in string A that matches String B CODE:- import java.util.Scanner; public class searchword { public static void main(String[] args){ Scanner sc = new Scanner(System.in);//create scanner object String str = sc.nextLine();//read string String str1 = sc.nextLine();//read word to be searched int flag = 0;//create flag variable for(int i=0;i<str.length()-str1.length()+1;i++){//loop through the string if(str.charAt(i)==str1.charAt(0)){//check if the first character of the word to be searched is found int j = 0; for(j=0;j<str1.length();j++){//loop through the word to be searched if(str.charAt(i+j)!=str1.charAt(j)){//check if the characters of the word to be searched are found break; } }
  • 147. if(j==str1.length()){//check if the word to be searched is found flag = 1; break; } } } if(flag==1){//check if the word to be searched is found System.out.println("The word "+str1+" is found in the string "+str); } else{ System.out.println("The word "+str1+" is not found in the string "+str); } } } Explanation A = ”excellent” B = ”lent” We assign a variable flag to check whether B is present in A We use a for loop to iterate through each letter of the string A if the letter the at any index of A is similar to the first letter of B we compare the all the upcoming letters If the sequence dont match we break the statement Else we make flag True We repeat above step till we reach end of the string A
  • 148. A B BOOL I J EXCELLENT LENT A[0]!=B[0] e!=l 0 0 EXCELLENT LENT A[1]!=B[0] x!=e 1 0 EXCELLENT LENT A[2]!=B[0] c!=n 2 0 EXCELLENT LENT . . . . . . EXCELLENT LENT A[5]==B[0] l==l 5 0 EXCELLENT LENT A[5+1]!=b[1] l != e 5 1 EXCELLENT LENT A[6]==B[0] l==l 6 0 EXCELLENT LENT A[6+1]==B[1] 6 1 EXCELLENT LENT A[6+2]==B[2] 6 2 EXCELLENT LENT A[6+3]==B[3] 6 3 EXCELLENT LENT flag=1 6 loop terminates EXCELLENT LENT loop terminates if flag is true we say B has been found in A else vice versa
  • 149. Longest word in a string Objective:- Find length of the longest word in a given string Intuition :- We find the length of each word in the string and store only the max value and return it CODE:- import java.util.Scanner; public class longestwordinsentence { public static void main(String[] args){ Scanner sc = new Scanner(System.in);//create scanner object String str = sc.nextLine();//read string int max=0;//create variable to store the length of the longest word int count=0;//create variable to store the length of the current word int index=0;//create variable to store the index of the longest word while(index<str.length()){//loop through the string if(str.charAt(index)!=' '){//check if the character is not a space count++;//increment the count variable } else{ if(count>max){//check if the length of the current word is greater than the length of the longest word max = count;//assign the length of the current word to the length of the longest word }
  • 150. Explanation A = ”I am getting better at coding” We assign variable max=0 to store max length We assign a variable count=0 to store length of the current word We iterate through each letter in the string if we encounter a space we change the value of max to maximum of max and count Then we make count=0 to check the size of the next word We repeat the above steps till we reach end of the string We again make max maximum of max count to check whether last word is the largest We print the length of the longest word count = 0;//reset the count variable } index++;//increment the index variable } max = Math.max(max,count);//check if the length of the current word is greater than the length of the longest word System.out.println("The length of the longest word in the string "+str+" is "+max); } }
  • 151. Add binary Objective:- Given two string A and B which are binary numbers find the added values Intuition :- Use the binary addition alogrithm to get the result string and display it CODE:- import java.util.Scanner; public class BinaryAddition { public static void main(String[] args) { // Create a Scanner object for user input Scanner sc = new Scanner(System.in); // Prompt the user to enter two binary numbers System.out.print("Enter the first binary number: "); String binary1 = sc.nextLine(); System.out.print("Enter the second binary number: "); String binary2 = sc.nextLine(); // Initialize variables for result and carry String result = ""; int carry = 0; // Initialize indices for traversing the binary numbers int i = binary1.length() - 1; int j = binary2.length() - 1; // Perform binary addition while (i >= 0 && j >= 0) { int sum = (binary1.charAt(i) - '0') + (binary2.charAt(j) - '0') + carry; result = (sum % 2) + result; carry = sum / 2; i--; j--; }
  • 152. // Handle remaining digits in the first binary number while (i >= 0) { int sum = (binary1.charAt(i) - '0') + carry; result = (sum % 2) + result; carry = sum / 2; i--; } // Handle remaining digits in the second binary number while (j >= 0) { int sum = (binary2.charAt(j) - '0') + carry; result = (sum % 2) + result; carry = sum / 2; j--; } // If there is a carry after all additions, add it to the result if (carry != 0) { result = carry + result; } // Display the result of binary addition System.out.println("Binary Sum: " + result); } } Explanation A = “1011” B = “101” We assign C = “” to store result we iterate from the back of bpth strings till we finish reading either of the bb
  • 153. i j A[i] B[J] SUM+ CARRY CARRY RESULT 3 2 1 1 1+1+0=0 1 “0” 2 1 1 0 1+0+1=0 1 “00” 1 0 0 1 0+1+1=0 1 “000" LOOP ENDS Carry=0 We check if we forgot to add any values from A or B In this case we have a carry and A has one more bit i A[i] SUM+ CARRY CARRY RESULT 0 1 1+1=0 1 “0000" Carry=1 If we have a left over carry we add it to the result = result=”10000"
  • 154. Practice question String hackerrank contest: https://www.hackerrank.com/string- contest-1700333838
  • 155. Practice question Loops hackerrank contest: Array and 2D array hackerrank contest: String hackerrank contest: https://www.hackerrank.com/string- contest-1700333838 https://www.hackerrank.com/string- contest-1700333838 https://www.hackerrank.com/string- contest-1700333838 Conditional statement hackerrank contest: https://www.hackerrank.com/conditi onal-statement-contest