Wednesday, January 22, 2020

Basic Java Programs for Beginners

1. Java Program to find weather a given number is prime or not

Code:

import java.util.Scanner;
public class prime {
public static void main(String args[])
{
int i,count=0;
@SuppressWarnings("resource")
Scanner sc = new Scanner(System.in);
System.out.println("Enter a Number");
int num = sc.nextInt();
        System.out.println(num);
if(num == 1)
{
System.out.print(num+" is Not Prime");
return;
}
else
{
for(i=2;i<num;i++)
{
if(num%2==0)
{
count++;
}
}
if(count>1)
{
System.out.print(num+" is Not Prime");
}
else
{
System.out.print(num+" prime number");
}
}
}

}

2. Binary Search

Code:

import java.util.Scanner;

public class binarySearch 
{
  @SuppressWarnings("resource")
  public static void main(String args[]) 
  {
Scanner sc = new Scanner(System.in);
int num,size,mid;
System.out.println("Enter Array size ");
size=sc.nextInt();
int arr[]=new int[size];
System.out.println("Enter Array elements in ascending order ");
for (int i = 0; i < size; i++) 
{
          arr[i]=sc.nextInt();
}
System.out.println("Enter Search key ");
mid=size/2;
num = sc.nextInt();
for (int i = 0; i < size; i++) 
{
  for (int j = size-1; j >=mid+1; j--) 
  {
   if (num == arr[mid]) 
   {
    mid=arr[mid];
   }
   else
   {
//you try this☺
   }
}
     }
    System.out.println("Element "+num+" found in index "+mid);
  }
}

3. Java Program to Reverse a given String

Code:

import java.util.Scanner;
@SuppressWarnings("resource")
public class reverseString 
{
  public static void  main(String args[]) {
     Scanner sc = new Scanner(System.in);
  System.out.println("Enter a String");
  String str = sc.next();
  String rev = " ";
  for (int i = str.length()-1; i>=0; i--) 
  {
rev = rev+str.charAt(i);
  }
  System.out.println("Original String "+str+" Reversed String is "+rev);
  if(str.equalsIgnoreCase(rev))
  {
System.out.println("Palindrome ");
  }
  else
  {
   System.out.println("Not Palindrome");
  }
 }
}

4. Java Program to find Largest in an Array

Code:

public class largeInArray 
{
 public static void main(String args[]) 
 {
int arr[]= {1,5,0,-1,10,15,7};
int large=0;
for(int i=0;i<arr.length;i++)
{
if(arr[i] > large)
{
large = arr[i];
}
}
System.out.println(large);
  }
}

5. Armstrong Number

Code:

public class armstrongNum 
{
 public static void main(String[] args)  
 {  
    int c=0,a,temp;  
    int n=153;//It is the number to check Armstrong  
    temp=n;  
    while(n>0)  
    {  
    a=n%10;  
    n=n/10;  
    c=c+(a*a*a);  
    }  
    if(temp==c)  
    System.out.println("armstrong number");   
    else  
        System.out.println("Not armstrong number");   
   }  
}

6. Program on static operations

class A
{
static int x;
int y;
A(int a,int b)
{
x=a+b;
y=x+b;
}
}
public class StaticOperations 
{
@SuppressWarnings("static-access")
public static void main(String args[]) 
{
A a=new A(2,3);
A a1=new A(5,10);
System.out.println(a.x+" "+a.y);
}

}



No comments:

Post a Comment