Programs on array and string
1)
public class MaxElemntInArray {
public static void main(String[] args) {
int[] a = {70,20,79,70,555};
System.out.println("====================");
System.out.println(a.length);
System.out.println("========================");
int max = a[0];
for(int i=1 ; i<a.length ; i++)
{
if(max < a[i])
{
max = a[i];
}
}
System.out.println(max);
}
}
Output:
====================
5
========================
555
2)
public class MinElementInArray {
public static void main(String[] args) {
int[] a = {70,20,79,70,555};
System.out.println("====================");
System.out.println(a.length);
System.out.println("========================");
int min = a[0];
for(int i=1 ; i<a.length ; i++)
{
if(min > a[i])
{
min = a[i];
}
}
System.out.println(min);
}
}
Output:
====================
5
========================
20
3)
public class ReplaceWithZero {
public static void main(String[] args) {
int[] a = {60,10,20,68,10,48};
int num=10;
for(int i=0 ; i<a.length ; i++)
{
if(a[i]==num)
{
a[i]=0;
}
}
for(int i=0 ; i<a.length ; i++)
{
System.out.print(a[i]+" ");
}
}
}
Output:
60 0 20 68 0 48
4)
public class ReverseString {
public static void main(String[] args) {
String name = "roja";
int length = name.length();
String reverse ="";
for(int i=length-1 ; i>=0 ; i--)
{
reverse = reverse+name.charAt(i);
}
System.out.println(reverse);
System.out.println("=================");
if(reverse.equals(name))
{
System.out.println("palindrome");
}
else {
System.out.println("not palindrome");
}
}
}
Output:
ajor
=================
not palindrome
5)
public class SearchElementInArray {
public static void main(String[] args) {
int[] a = {900,67,19,80,99};
int ele =90;
int flag = 0;
for(int i=0 ; i<a.length ; i++)
{
if(a[i]==ele)
{
flag=1;
System.out.println("element found");
break;
}
}
if(flag == 0)
{
System.out.println("element not found");
}
}
}
Output:
element not found
6) public class BubbleSort {
public static void main(String[] args) {
int[] a = {50,10,100,80};
int temp;
for(int i=0 ; i<a.length-1 ;i++)
{
int flag=0;
for(int j =0 ; j<a.length-1 ;j++)
{
//if(a[j] < a[j+1])-->descending order
if(a[j] > a[j+1])//-->ascending order
{
temp = a[j];
a[j]=a[j+1];
a[j+1]=temp;
flag=1;
}
}
if(flag==0)
{
break;
}
}
for(int i=0 ; i<a.length ; i++)
{
System.out.print(a[i]+" ");
}
}
}
Output:
10 50 80 100
7)
public class ToUpperCase {
public static void main(String[] args) {
String s1 = "ABCD";
char[] a1 = s1.toCharArray();
for(int i=0 ; i<a1.length ; i++)
{
// if(a1[i]>='a' && a1[i]<='z')
if(a1[i]>='A' && a1[i]<='Z')
{
// a1[i]= (char) (a1[i]-32);
a1[i]= (char) (a1[i]+32);
}
}
String str = new String(a1);
System.out.println(str);
}
}
Output:
abcd
8)
public class CountPrimeNumber {
public static void main(String[] args) {
int[] a = {2,3,6,7};
int noOfPrimeNum=0;
for(int i=0 ; i<a.length ; i++)
{
int count=0;
for(int j=1 ; j<=a[i] ; j++)
{
int num = a[i];
if(num%j==0)
{
count++;
}
}
if(count==2)
{
noOfPrimeNum++;
}
}
System.out.println(noOfPrimeNum);
}
}
Output:
3