0% found this document useful (0 votes)
2 views59 pages

Java Language notes and programs to practise

The document provides a comprehensive overview of Java programming concepts, including data types, operators, control structures, and built-in functions. It contains example code snippets for various operations such as volume calculations, leap year checks, and prime number identification, along with explanations of array handling and string manipulation. Additionally, it includes multiple programming exercises categorized by difficulty levels, from basic to advanced topics.

Uploaded by

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

Java Language notes and programs to practise

The document provides a comprehensive overview of Java programming concepts, including data types, operators, control structures, and built-in functions. It contains example code snippets for various operations such as volume calculations, leap year checks, and prime number identification, along with explanations of array handling and string manipulation. Additionally, it includes multiple programming exercises categorized by difficulty levels, from basic to advanced topics.

Uploaded by

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

JAVA

JAVA
LEVEL - 1

FORMAT

import java.util.Scanner; //for getting user input

class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String a=obj.nextLine();
char b=obj.next().charAt(0); //charAt(zero)
System.out.println("String is "+a);
System.out.println("Character is "+b);
}
}

To convert any datatype to int: (int)no

Math.PI is used for value 3.14

Unary Operator ( ~ and ! )

int a=10;
int b=-10;
boolean c=true;
boolean d=false;
System.out.println(~a); //-11 (minus of total positive value which starts from 0)
System.out.println(~b); //9 (positive of total minus, positive starts from 0)
System.out.println(!c); //false (opposite of boolean value)
System.out.println(!d); ///true

Right Shift Operator

System.out.println(10>>2); // 10/2^2=10/4=2
System.out.println(20>>2);// 20/2^2=20/4=5
System.out.println(20>>3);// 20/2^3=20/8=2

Left Shift Operator

System.out.println(10<<2);
//10*2^2=10*4=40
System.out.println(10<<3);
//10*2^3=10*8=80
System.out.println(20<<2);
//20*2^2=20*4=80
System.out.println(15<<4);
//15*2^4=15*16=240

Logical && and Bitwise &

The logical && operator doesn't check the second condition if the first condition is false. It
checks the second condition only if the first one is true.

The bitwise & operator always checks both conditions whether first condition is true or false

int a=10;
int b=5;
int c=20;
System.out.println(a<b && a++<c);//false && true = false
System.out.println(a);//10 because second condition is not checked
System.out.println(a<b & a++<c);//false & true = false
System.out.println(a);//11 because second condition is checked
Logical || and Bitwise |

The logical || operator doesn't check the second condition if the first condition is true. It checks
the second condition only if the first one is false.

The bitwise | operator always checks both conditions whether first condition is true or false

System.out.println(a>b||a++<c); //true || true = true


System.out.println(a);//10 because second condition is not checked
System.out.println(a>b|a++<c);//true | true = true
System.out.println(a);//11 because second condition is checked

Ternary Operator

int a=2;
int b=5;
int min=(a<b)?a:b;
System.out.println(min); //2

Input : 54.36666
Output : 54.36

double number = 54.36666;


double truncatedNumber = Math.floor(number * 100) / 100;

Input : 54.36666
Output : 54.37

double number = 54.36666;


String roundedNumber = String.format("%.2f", number);
System.out.println(roundedNumber); //System.out.println(String.format("%.2f",number));
System.out.format("%.2f",number);
System.out.printf("%.2f%n",number);

To round off
double a=133.78966; // Input
double b=Math.round(a);
System.out.println((int)b);
// Output : 134

Build in Functions // import java.lang.Math;

Math.sqrt()
Math.cbrt()
Math.pow()

Formulas

Km to m
M=km*1000

M to km
Km=M/100

Area

Circle : pi*r*r
Square : s*s
Rectangle : l*b
Triangle : (1/2)*b*h

Volume

Circle : (4/3)*pi*r*r*r (or) pi*r*r*h


Square : s*s*s
Rectangle : l*w*h
Triangle : b*h

Swapping without another variable

int a = 5;
int b = 10;
a = a ^ b; // a now holds the XOR of a and b
b = a ^ b; // b is now equal to the original value of a
a = a ^ b; // a is now equal to the original value of b

System.out.println("a: " + a); // a will be 10


System.out.println("b: " + b); // b will be 5

int a = 5;
int b = 10;

a = a + b; // a now holds the sum of a and b


b = a - b; // b is now equal to the original value of a
a = a - b; // a is now equal to the original value of b

System.out.println("a: " + a); // a will be 10


System.out.println("b: " + b); // b will be 5

PROGRAMS

1.​Volume Calculation

import java.util.Scanner;
import java.lang.Math;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int c=myobj.nextInt();
if(c==1)
{
float r=myobj.nextFloat();
float h=myobj.nextFloat();
double v=(1.0/3)*Math.PI*r*r*h;
double vo=Math.round(v);
System.out.println((int)vo);
}
else if(c==2)
{
float r=myobj.nextFloat();
float h=myobj.nextFloat();
double v=Math.PI*r*r*h;
double vo=Math.round(v);
System.out.println((int)vo);
}
else if(c==3)
{
float r=myobj.nextFloat();
double v=4.0/3*Math.PI*r*r*r;
double vo=Math.round(v);
System.out.println((int)vo);
}
else
{
System.out.println("Invalid");
}
}
}

2.​Leap year

import java.util.Scanner;
import java.lang.Math;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int y=myobj.nextInt();
if(y%4==0)
{
if(y%100==0)
{
if(y%400==0)
{
System.out.println("LEAP");
}
else
{
System.out.println("NOT LEAP");
}
}
else
{
System.out.println("LEAP");
}
}
else
{
System.out.println("NOT LEAP");
}
}
}

3.​Input : 16
Output : 4 //(2^4)

int a=myobj.nextInt();
double b=Math.sqrt(a);
System.out.println((int)b);

4.​Difference in 2 Time intervals

Input : 5 40
6 20
Output : 0 hours 40 minutes

import java.util.Scanner;
import java.lang.Math;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int h1=myobj.nextInt();
int m1=myobj.nextInt();
int h2=myobj.nextInt();
int m2=myobj.nextInt();
int tm1=h1*60+m1;
int tm2=h2*60+m2;
int difm=Math.abs(tm1-tm2);
int hours=difm/60;
int minu=difm%60;
System.out.println(hours+" Hours "+minu+" Minutes");

}
}

5.​To find powers of given inputs

import java.util.Scanner;
import java.lang.Math;
class Main
{
public static void main(String[] args)
{
// Scanner myobj=new Scanner(System.in);
int a=2;
int b=3;
System.out.println((int)Math.pow(a,b));

}
}
LEVEL - 2
1.​Prime or Composite

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int n=myobj.nextInt();
if(n<=1)
{
System.out.println("COMPOSITE");
return ;
}
int f=1;
for(int i=2;i<=Math.sqrt(n);i++)
{
if(n%i==0)
{
f=0;
break;
}
}
if(f==1)
{
System.out.println("PRIME");
}
else
{
System.out.println("COMPOSITE");
}
}
}

2.​Armstrong Number or Narcissistic Number

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int n=myobj.nextInt();
int rem1,rem2;
int c=0;
int org=n,temp=n;
int sum=0;
while(n!=0)
{
rem1=n%10;
c++;
n/=10;
}
while(temp!=0)
{
rem2=temp%10;
sum+=Math.pow(rem2,c);
temp/=10;
}
if(sum==org)
{
System.out.println("ARMSTRONG");
}
else
{
System.out.println("NOT");
}
}
}

3.​Abundant Number

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int n=myobj.nextInt();
int sum=0;
for(int i=1;i<=n/2;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(sum>n)
{
System.out.println("ABUNDANT");
}
else
{
System.out.println("NOT");
}
}
}

4.​Replace all 0 with 1 using arithmetic operators

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int n=myobj.nextInt();
int rem=0,rev=0;
int rem2=0,rev2=0;
int temp=n;
while(n!=0)
{
rem=n%10;
if(rem==0)
{
rem+=1;
}
rev=rev*10+rem;
n/=10;
}
while(rev!=0)
{
rem2=rev%10;
rev2=rev2*10+rem2;
rev/=10;
}
System.out.println(rev2);
}
}

5.​Fibonacci​ series

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner myobj=new Scanner(System.in);
int n=myobj.nextInt();
int n1=0;
int n2=1;
int no;
for (int i=0;i<n;i++)
{
System.out.print(n1+"," );
no=n1+n2;
n1=n2;
n2=no;
}
}
}

6.​Printing next five prime numbers

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
n=n+1;
int c=0,f=1;
while(c<5)
{
f=1;
for(int i=2;i<=Math.sqrt(n);i++)
{
if(n%i==0)
{
f=0;
break;
}
}
// n=n+1;
if(f==1)
{
System.out.println(n);
c+=1;
//n+=1;
}
n=n+1;
}
}
}

7.​ Geometric Series Sum Calculator (1​+ ½ + ¼ + ⅛ +...1/N )

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
float sum=1;
int j=1;
for(int i=1;i<n;i++)
{
sum+=1.0/(j*2);
j*=2;
}
System.out.format("%.2f",sum);
}
}

8.​Sum of Squares of N Natural Numbers


(Input:5 Output:55 [1*1+2*2+3*3+4*4+5*5]

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
int sum=0;
for(int i=1;i<=n;i++)
{
sum+=i*i;
}
System.out.println(sum);
}
}

9.​Digit Count

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int c=0,len;
String n=obj.nextLine();
len=n.length();
for(int i=0;i<len;i++)
{
char ch=n.charAt(i);
if(ch>=48 && ch<=57)
{
c+=1;
}
}
System.out.println(c);
}
}
LEVEL - 3
Topics : Arrays , 2d array , Strings

ARRAYS

1.​Declaring Arrays

int arr[]=new int[100];

2.​To find length of the array

arr.length

3.​To print

for(int i:arr)
System.out.println(i);

Build-In Function in Arrays

1.​ int[] arr = {5, 3, 8, 1};


Arrays.sort(arr);
// Output: arr = [1, 3, 5, 8]

2.​ int[] arr = {1, 3, 5, 8};


int index = Arrays.binarySearch(arr, 5);
// Output: index = 2

3.​ int[] arr = {1, 2, 3};


int[] newArr = Arrays.copyOf(arr, 5);
// Output: newArr = [1, 2, 3, 0, 0]

4.​ int[] arr1 = {1, 2, 3};


int[] arr2 = {1, 2, 3};
boolean isEqual = Arrays.equals(arr1, arr2);
// Output: isEqual = true

5.​ int[] arr = new int[5];


Arrays.fill(arr, 7);
// Output: arr = [7, 7, 7, 7, 7]

6.​ int[] arr = {1, 2, 3, 4, 5};


int[] newArr = Arrays.copyOfRange(arr, 1, 4);
// Output: newArr = [2, 3, 4]

7.​ int[] arr1 = {1, 2, 3, 4};


int[] arr2 = {1, 2, 0, 4};
int mismatchIndex = Arrays.mismatch(arr1, arr2);
System.out.println(mismatchIndex);
// Outputs: 2 (the first mismatch is at index 2)

PROGRAMS :

1.​To get input for array and printing it

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[100];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}

2.​Another method for printing arrays ( But if you use this


method for printing, while declaring array you should specify
correct size not random or it will print zero for the extra
size)

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
System.out.println("Another Method");
for(int i:arr)
{
System.out.println(i);
}
}
}

3.​To find smallest element

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
int min=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i]<min)
{
min=arr[i];
}
}
System.out.println(min);
}
}

4.​To sort using built in function

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
Arrays.sort(arr);
for(int i=0;i<n;i++)
{
System.out.println(arr[i]);
}
}
}

5.​To check if two arrays are same

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
int n1=obj.nextInt();
int arr1[]=new int[n1];
for(int i=0;i<n1;i++)
{
arr1[i]=obj.nextInt();
}
if(Arrays.equals(arr,arr1))
{
System.out.println("TRUE");
}
else
{
System.out.println("NOT TRUE");
}

}
}

6.​Using Intstream

import java.util.Scanner;
import java.util.Arrays;
import java.util.stream.IntStream;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n;
n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
IntStream stream = Arrays.stream(arr);
stream.forEach(i-> System.out.print(i+" ")); // Output: 1 2 3
//stream.forEach(i -> System.out.print(i + " "));

}
}

7.​The output array should hold the same first value and
remaining value should be difference of iterative values (PS)

Input : 5 (size)
2 6 8 4 9
Output : 2 4 2 -4 5
// At the end of the output it has extra space.

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
int arr[]=new int[100];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
int ans[]=new int[100];
int x=0;
ans[x]=arr[x];
x++;
for(int i=1;i<n;i++)
{
ans[x]=arr[i]-arr[i-1];
x++;
}
for(int i=0;i<n;i++)
{
System.out.print(ans[i]+" ");
}

}
}
8.​To reverse the array in grouping method (PS)

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
//obj.nextLine();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
int k=obj.nextInt();
int c=0,x=0,y=k;
int z=n/k ;
int m=1;
for(int i=1;i<=z;i++)
{
int newarr[]=Arrays.copyOfRange(arr,c,y);
int len=newarr.length;
for(int j=len-1;j>=0;j--)
{
System.out.print(newarr[j]+" ");
c++;
}
m++;
y=k*m;
}
if(n>c)
{
// int rem=n-c;
int newarr1[]=Arrays.copyOfRange(arr,c,n);
int len1=newarr1.length;
for(int i=0;i<len1;i++)
{
if(i==len1-1)
{
System.out.print(newarr1[i]);
}
else
{
System.out.print(newarr1[i]+" ");
}
}
}

}
}

Input : 5
1
2
3
4
5
3
Output:
ANSWER
3 2 1 4 5

(OR) To avoid space in printing the last element

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}
int k=obj.nextInt();
int c=0,x=0,y=k;
System.out.println("ANSWER");
int z=n/k ;
int m=1;
int ans[]=new int[n];
for(int i=1;i<=z;i++)
{
int newarr[]=Arrays.copyOfRange(arr,c,y);
int len=newarr.length;
for(int j=len-1;j>=0;j--)
{
ans[c]=newarr[j];
c++;
}
m++;
y=k*m;
}

if(n>c)
{
int newarr1[]=Arrays.copyOfRange(arr,c,n);
int len1=newarr1.length;
for(int i=0;i<len1;i++)
{
ans[c]=newarr1[i];
c++;
}
}
for(int i=0;i<n;i++)
{
if(i!=n-1)
{
System.out.print(ans[i]+" ");
}
else
{
System.out.print(ans[i]);
}
}
}
}

9.​To sum all the elements in an array except the maximum and
minimum element (PS)

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++)
{
arr[i]=obj.nextInt();
}

/* To find minimum and maximum element using builtin method

int min=Arrays.stream(arr).min().getAsInt();
int max=Arrays.stream(arr).max().getAsInt(); */

int min=arr[0];
int max=arr[0];
for(int i=0;i<n;i++)
{
if(arr[i]>max)
{
max=arr[i];
}
}
for(int i=0;i<n;i++)
{
if(arr[i]<min)
{
min=arr[i];
}
}
int sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i];
}
System.out.println(sum-min-max);
}
}

10.​ Rank program in ascending order

import java.util.Scanner;

class Main {
public static void main(String[] args) {
Scanner obj = new Scanner(System.in);
int size = obj.nextInt();
int[] arr = new int[size];
int[] ranks = new int[size];
for (int i = 0; i < size; i++)
{
arr[i] = obj.nextInt();
}
for (int i=0; i<size;i++)
{
ranks[i]=size;
for (int j=0;j<size;j++)
{
if (arr[j]>arr[i])
{
ranks[i]--;
}
}
}
for (int i=0;i<size;i++)
{
System.out.print(ranks[i]);
if (i<size-1)
{
System.out.print(",");
}
}
}
}
STRINGS
Build-in Function

1.​ split()
Split the words in a sentence //Requires delimiter like split(“ “) or split(“/”)

2.​ charAt(int index)


char ch = str.charAt(0); // Returns 'H' in Hello

3.​ substring(int beginIndex, int endIndex)


String sub = str.substring(0, 5); // Returns "Hello" in HelloWorld

4.​ substring(int beginIndex)


String sub = str.substring(7); // Returns "rld!" in HelloWorld

5.​ equals(Object obj)


String s1 = "Java";
String s2 = "Java";
boolean isEqual = s1.equals(s2); // Returns true

6.​ equalsIgnoreCase(String anotherString)


String s1 = "Java";
String s2 = "java";
boolean isEqual = s1.equalsIgnoreCase(s2); // Returns true

7.​ toLowerCase()
String lower = str.toLowerCase(); // Returns "hello, world!"

8.​ toUpperCase()
String upper = str.toUpperCase(); // Returns "HELLO, WORLD!"

9.​ trim()
String str = " Hello World! ";
String trimmed = str.trim(); // Returns "Hello World!"
10.​ replace()
String replaced = str.replace('l', 'p'); // Returns "Heppo, Worpd!"

11.​ contains(CharSequence s)
boolean contains = str.contains("World"); // Returns true

12.​ startsWith(String prefix)


boolean starts = str.startsWith("Hello"); // Returns true

13.​ endsWith(String suffix)


boolean ends = str.endsWith("!"); // Returns true

14.​ indexOf(String str)


int index = str.indexOf("World"); // Returns 7 in Hello World

15.​ lastIndexOf(String str)


int lastIndex = str.lastIndexOf("l"); // Returns 10 in Hello World

16.​ split(String regex)


String[] words = str.split(" "); // Splits into ["Hello" , "World!"]

17.​ compareTo(String anotherString)


int comparison = str.compareTo("Hello"); // Returns 0 if equal

18.​ join(CharSequence delimiter, CharSequence... elements)


String joined = String.join("@", "Java", "Python", "C++"); // Returns
"Java@Python@C++"

String ans=str.join("@",str.split(" "));


Input : hey hi hello
Output : hey@hi@hello

19.​ matches(String regex)


boolean isMatch = str.matches("\\w+"); // Checks if str contains only word
characters
20.​ toCharArray()
char[] arr = str.toCharArray(); // Converts to ['H', 'e', 'l', 'l', 'o'] for input Hello

21.​ concat(String str)


String s1 = "Hello";
String s2 = s1.concat("World!"); // Returns "HelloWorld!"

22.​ replaceAll(String regex, String replacement)


String str = "Java is awesome!";
String replaced = str.replaceAll("\\s", "-"); // Returns "Java-is-awesome!"

23.​ replaceFirst(String regex, String replacement)


String str = "Java is awesome!";
String replaced = str.replaceFirst("\\s", "-"); // Returns "Java-is awesome!"

24.​ valueOf(Object obj)


int num = 10;
String str = String.valueOf(num); // Returns "10"

25.​ matches(String regex)


String str = "12345";
boolean isMatch = str.matches("\\d+"); // Returns true (if the string contains only
digits)

26.​ regionMatches(int toffset, String other, int ooffset, int len)


String str1 = "Hello";
String str2 = "ell";
boolean match = str1.regionMatches(1, str2, 0, 3); // Returns true

27.​ To convert a single character to upper or lower case ;


Use Character.toUpperCase(str);

●​ For Arrays : use arr.length to find length of the arrays


●​ For Strings : use str.length() to find string length
●​ Even if you use a string inside an array use arr.length to find the length of
it.
PROGRAMS :

1.​To find total number of words in a sentence

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str=obj.nextLine();
int c=0;
String ans[]=str.split("\\s+"); // “\\s+” is for spliting only space or tab space
or newline
c=ans.length; // only length not length() because it is an array that contains
string
System.out.println(c);

}
}

2.​To check if a character is in a sentence or word

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str=obj.nextLine();
int n=str.length();
int flag=0;
for(int i=0;i<n;i++)
{
if(str.charAt(i)=='z')
{
flag=1;
break;
}
}
if(flag==1)
{
System.out.println("FOUND");
}
else
{
System.out.println("NOT FOUND");
}

}
}

3.​To use join function

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String one="@";
String two="Hey hii hello";
String arr[]=two.split(" ");
System.out.println(String.join(one,arr));
}
}

4.​Input : 4
Arjun
Santhiya
ravi
kavi
Output : A.S.r.k. (PS)

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
int n=obj.nextInt();
obj.nextLine();
String str[]=new String[n];
for(int i=0;i<n;i++)
{
str[i]=obj.nextLine();
}
// String word="";
char ch;
String ans="";
for(int i=0;i<n;i++)
{
//word=str[i];
ch=str[i].charAt(0);
ans+=ch;
ans+=".";
}
System.out.println(ans);
}
}

5.​Input : abcdeafgabcrf
abc
Output : 0,8, (PS)

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str,sub;
str=obj.nextLine();
sub=obj.nextLine();
int index=str.indexOf(sub);
while((index=str.indexOf(sub,index))!=-1)
{
System.out.print(index+",");
index+=sub.length();
}
}
}

(OR) To avoid comma at last

Input : abcdeafgabchij
abc
Output : 0,8 (PS)
import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str,sub;
str=obj.nextLine();
sub=obj.nextLine();
int index=str.indexOf(sub);
int x=0;
int arr[]=new int[100];
while((index=str.indexOf(sub,index))!=-1)
{
arr[x]=index;
x++;
index+=sub.length();
}
for(int i=0;i<x;i++)
{
if(i==x-1)
{
System.out.print(arr[i]);
}
else
{
System.out.print(arr[i]+",");
}
}
}
}

6.​Input : 3
"he
is"
good
Output : "He is" good.

Input : 4
the
world
is
good
Output : The world is good. (PS)

import java.util.Scanner;

class Main
{
public static void main(String[] args)
{
Scanner obj = new Scanner(System.in);
int n = obj.nextInt();
obj.nextLine();
String str = "";
String s = "";
for (int i = 0; i < n; i++)
{
s=obj.nextLine();
if (i==n-1)
{
str+=s +".";
}
else
{
str+=s+" ";
}
}
StringBuilder ans = new StringBuilder();
int z=0;
int y=0;
for(int i=0;i<str.length();i++)
{
if ((str.charAt(i)>=65 && str.charAt(i)<=90) || (str.charAt(i)>=97 &&
str.charAt(i)<=122) && z==0)
{
ans.append(Character.toUpperCase(str.charAt(i)));
z++;
}
else
{
ans.append(str.charAt(i));
}
}
System.out.println(ans.toString());
}
}

7.​Input : hey
gud to see you
isn’t it?
Output : [hey, gud to see you, isnt it?, null, null] //Because the
size declared here is 5 but only 3 inputs so..

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str[]=new String[5];
for(int i=0;i<3;i++)
{
str[i]=obj.nextLine();
}
System.out.println(Arrays.toString(str));
}
}

8.​To get the first letter of each word in a sentence and print it
with dot. (PS)

Input : Arjun Das murali krishnan


Output : A.D.m.k.

import java.util.Scanner;
import java.util.Arrays;
class Main
{
public static void main(String args[])
{
Scanner scan=new Scanner(System.in);
String str=scan.nextLine();
int l=str.length();
String arr[]=new String[l];
char ch=str.charAt(0);
System.out.print(ch+".");
for(int i=1;i<l;i++)
{
char st=str.charAt(i);
if(st==' ')
{
char str1=str.charAt(i+1);
System.out.print(str1+".");

}
}
}
}

9.​To find frequency of every letter

Input : aaabbccccdbbb
Output : a3b2c4d1b3

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str=obj.nextLine();
StringBuilder ans=new StringBuilder();
int c=1;
for (int i=1;i<str.length();i++)
{
if (str.charAt(i)==str.charAt(i-1))
{
c++;
}
else
{
ans.append(str.charAt(i-1));
ans.append(c);
c=1;
}
}
if (str.length()>0)
{
ans.append(str.charAt(str.length()-1));
ans.append(c);
}
System.out.println(ans.toString());
}
}

10.​ Reverse even index word

import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Scanner obj=new Scanner(System.in);
String str=obj.nextLine();
String arr[]=str.split(" ");
int len=arr.length;
String a="";
for(int i=0;i<len;i+=2)
{
a=arr[i];
int l=a.length();
for(int j=l-1;j>=0;j--)
{
char ch=a.charAt(j);
System.out.print(ch);
}
System.out.print("\n");
}
}
}

11.​ LEETCODE 1394


https://leetcode.com/problems/find-lucky-integer-in-an-array/descrip
tion/?envType=daily-question&envId=2025-07-05
import java.util.Scanner;
import java.util.Arrays;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int ex=sc.nextInt();
boolean ans[]=new boolean[n];
int t,x=0,c=0;
for(int i=0;i<n;i++){
c=0;
t=arr[i]+ex;
for(int j=0;j<n;j++){
if(t>=arr[j]){
c++;
}
}
if(c==arr.length){
ans[x]=true;
x++;
}
else{
ans[x]=false;
x++;
}
}
System.out.println(Arrays.toString(ans));
}
}

12.​ LEETCODE 1431


https://leetcode.com/problems/kids-with-the-greatest-number-of-
candies/description/

import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int c=0;
ArrayList<Integer> ans = new ArrayList<>();
for(int i=0;i<n;i++){
c=0;
for(int j=0;j<n;j++){
if(arr[i]==arr[j]){
c++;
}
}
if(c==arr[i]){
ans.add(c);
}
}

int len=ans.size();
if(len==1){
System.out.println(ans.get(0));
}
else if(len>1){
System.out.println(Collections.max(ans));
}
if(len==0){
System.out.println("-1");
}

}
}

13.​ LEETCODE 34
https://leetcode.com/problems/find-first-and-last-position-of-elemen
t-in-sorted-array/description/

import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int f=-1,l=-1,c=0;
int tar=sc.nextInt();
for(int i=0;i<n;i++){
if(arr[i]==tar){
f=i;
break;
}
}
for(int i=n-1;i>f;i--){
if(arr[i]==tar){
l=i;
}
}
if(f==-1 || l==-1){
System.out.println(f+" "+l);
}
else{
System.out.println(f+" "+l);
}
}
}

14.​ LEETCODE 75
https://leetcode.com/problems/sort-colors/description/

import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int z=0,o=0,t=0,x=0;
for(int i=0;i<n;i++){
if(arr[i]==0){
z++;
}
else if(arr[i]==1){
o++;
}
else{
t++;
}
}
int ans[]=new int[n];
for(int i=0;i<z;i++){
ans[x]=0;
x++;
}
for(int i=0;i<o;i++){
ans[x++]=1;
}
for(int i=0;i<t;i++){
ans[x++]=2;
}
for(int i=0;i<n;i++){
System.out.println(ans[i]+" ");
}
}
}

15.​ LEETCODE 905


https://leetcode.com/problems/sort-array-by-parity/description/

import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
for(int i=0;i<n;i++){
arr[i]=sc.nextInt();
}
int ans[]=new int[n];
int x=0;
for(int i=0;i<n;i++){
if(arr[i]%2==0){
ans[x++]=arr[i];
}
}
for(int i=0;i<n;i++){
if(arr[i]%2!=0){
ans[x++]=arr[i];
}
}
for(int i=0;i<n;i++){
System.out.print(ans[i]+" ");
}
}
}

16.​ LEETCODE 682


https://leetcode.com/problems/baseball-game/description/

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
sc.nextLine();
String[] arr = sc.nextLine().split(" ");
ArrayList<Integer> ans=new ArrayList<>();
int x=-1;
for(int i=0;i<n;i++){
if(!arr[i].equals("C")&&!arr[i].equals("D")&&!arr[i].equals("+")){
int val=Integer.parseInt(String.valueOf(arr[i]));
ans.add(val);
x++;
}
else if(arr[i].equals("D")){
int no1=(int)ans.get(x);
ans.add(no1*2);
x++;
}
else if (arr[i].equals("C")) {
ans.remove(x);
x--;
}
else if(arr[i].equals("+")){
int no2=(int)ans.get(x);
int no3=(int)ans.get(x-1);
ans.add(no2+no3);
x++;
}
}
int sum=0;
for(int i:ans){
sum+=i;
}
System.out.println(sum);
// System.out.println(ans);
}
}
17.​ LEETCODE 345
https://leetcode.com/problems/reverse-vowels-of-a-string/descriptio
n/

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String str=sc.nextLine();
int n=str.length();
int x=0;
ArrayList<Character> arr = new ArrayList<>();
for(int i=0;i<n;i++){
char ch=str.charAt(i);
char c=Character.toLowerCase(ch);
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u'){
arr.add(ch);
x++;
}
}
char s[]=new char[x];
int z=0,m=0;
for(int i=x-1;i>=0;i--){
s[z]=arr.get(i);
z++;
}
char ans[]=new char[n];
for(int i=0;i<n;i++){
char ch=str.charAt(i);
char c=Character.toLowerCase(ch);
if(c=='a' || c=='e' || c=='i' || c=='o' || c=='u'){
ans[i]=s[m];
m++;
}
else{
ans[i]=ch;
}
}
System.out.println(new String(ans));
}
}

18.​ LEETCODE 412


https://leetcode.com/problems/fizz-buzz/description/

import java.util.Scanner;
import java.util.Arrays;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
String str[]=new String[n];
int x=0;
for(int i=1;i<=n;i++){
if(i%3==0 && i%5!=0){
str[x++]="Fizz";
}
else if(i%5==0 && i%3!=0){
str[x++]="Buzz";
}
else if(i%3==0 && i%5==0){
str[x++]="FizzBuzz";
}
else{
str[x++] = String.valueOf(i);
}
}
for(int i=0;i<n;i++){
System.out.println(str[i]);
}
}
}

19.​ LEETCODE 520


https://leetcode.com/problems/fizz-buzz/description/

import java.util.Scanner;
import java.util.Arrays;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
int l=s.length();
int c=0,z=0;
for(int i=0;i<l;i++){
char ch=s.charAt(i);
if((int)ch>=65 && (int)ch<=90){
c++;
if(c==1){
z=i;
}
}
}
if(c==0 || c==l || (c==1 && z==0)){
System.out.println("true");
}
else{
System.out.println("false");
}

}
}
New method in program
1.​ To print a char array as string :

System.out.println(new String(ans)); // ans is a char array

2.​ How to get a single character from a string and convert it into
lowercase

char ch=str.charAt(i);
char c=Character.toLowerCase(ch); // str is a string, used loop so i

3.​ To create ArrayList

ArrayList<Integer> ans=new ArrayList<>(); // used when size is not known, for


this u have to import [ import java.util.ArrayList; ]

4.​ To convert a string to integer

int val=Integer.parseInt(String.valueOf(arr[i])); // arr is a string array, used


loop so i

5.​ To find max in arrayList

System.out.println(Collections.max(ans)); // ans is a ArrayList, for this u

have to import [ import java.util.Collections; ]

6.​ How to insert a int value in string array

str[x++] = String.valueOf(i); // str in string array and i is int value


High end training JAVA
HIGH END TRAINING

JAVA

ARRAYS

●​ One dimensional array


●​ Two dimensional arrays
●​ Multi dimensional arrays - changing size

int arr[]=new int[100];

Static [Fixed size] - Array


Dynamic [Changing size] - Linked lists, array lists

For Loop - Use for loop if end point is known else use while loop.

●​ Simple for loop


●​ Nested loop
●​ For Enhancing loop or for each loop - can’t skip an iteration, condition
need not be specified.
int[] arr = {1, 2, 3, 4, 5};
for(int i : arr)
{
System.out.println(i);
}
public static void main(String[] args)
args - Variable name, Changeable

Traversal

●​ Boundary Traversal
●​ Snake or ZigZag Traversal
●​ Spiral Traversal

Array : 1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Boundary Traversal - 1 2 3 4 8 12 16 15 14 13 9 5
Snake or Zigzag traversal - 1 2 3 4 8 7 6 5 9 10 11 12 16 15 14 13
Spiral Traversal - 1 2 3 4 8 12 16 15 14 13 9 5 6 7 11 10

You might also like