Вы находитесь на странице: 1из 58

1.

Program to capitalize a string


import java.util.*;
public class Main
{
public static void main(String[] args) {
String s1="hello";
StringBuffer s=new StringBuffer();
System.out.println(s.append(Character.toUpperCase(s1.charAt(0))));
s.append(s1.substring(1));
System.out.println(s.toString());

}
}

2. Program to reverse a string

import java.lang.*;
import java.io.*;
import java.util.*;

// Class of ReverseString
class ReverseString
{
public static void main(String[] args)
{
String input = "Geeks for Geeks";

StringBuilder input1 = new StringBuilder();

// append a string into StringBuilder input1


input1.append(input);

// reverse StringBuilder input1


input1 = input1.reverse();

// print reversed String


System.out.println(input1);
}
}
3. To convert decimal to binary

class GFG
{

static void decToBinary(int n)


{

int[] binaryNum = new int[1000];

int i = 0;
while (n > 0)
{

binaryNum[i] = n % 2;
n = n / 2;
i++;
}

for (int j = i - 1; j >= 0; j--)


System.out.print(binaryNum[j]);
}

public static void main (String[] args)


{
int n = 17;
decToBinary(n);
}
}

4. Power of a number

public class Power {

public static void main(String[] args) {

int base = 3, exponent = -4;


double result = Math.pow(base, exponent);

System.out.println("Answer = " + result);


}
}

5. Program to compare two strings

public class EqualCheck {


public static void main(String args[]){
String a = "AVATAR";
String b = "avatar";

if(a.equals(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}

if(a.equalsIgnoreCase(b)){
System.out.println("Both strings are equal.");
} else {
System.out.println("Both strings are not equal.");
}
}
}

6. import java.util.Date;

public class DisplayDate {


public static void main(String args[]) {
// Instantiate a objects
Date date1 = new Date();
Date date2 = new Date();

if(date1.compareTo(date2)>0){
System.out.println("Date1 is after Date2");
}else if(date1.compareTo(date2)<0){
System.out.println("Date1 is before Date2");
}else{
System.out.println("Date1 is equal to Date2");
}

}
}
7. To count number of words in a sentence
import java.util.*;
public class Main
{
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String s=sc.nextLine();
String[] a=s.split("\\s+");
int l=a.length;
System.out.println(l);
}
}

8. Java program to print gcd of two number


public calass Gcd{
public static void main(String a[]){
int n1=81,n2=153,gcd=1;
for(int i=1;i<=n1&&i<=n2;i++){
if(n1%i==0 &&n2%i==0)
gcd=I;
}
System.out.printf(gcd);
}

9. Java program to print lcm of two numbers

public calass Lcd{


public static void main(String a[]){
int n1=81,n2=153,gcd=1,lcm;
for(int i=1;i<=n1&&i<=n2;i++){
if(n1%i==0 &&n2%i==0)
gcd=I;
}
lcm=(n1*n2)/gcd;
System.out.printf(lcm);
}
10. Transpose of a matrix.

Import java.util.scanner.*;
Public class Transpose
{
Public static void main(String args[])
{
Int I,j;
System.out.println(“Enter rows and columns”);
Scanner s = new Scanner(System.in);
int row = s.nextInt();
int column = s.nextInt();
int array[][] = new int[row][column];
System.out.println("Enter matrix:");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
array[i][j] = s.nextInt();
System.out.print(" ");
}
}
System.out.println("The above matrix before Transpose is ");
for(i = 0; i < row; i++)
{
for(j = 0; j < column; j++)
{
System.out.print(array[i][j]+" ");
}
System.out.println(" ");
}
System.out.println("The above matrix after Transpose is ");
for(i = 0; i < column; i++)
{
for(j = 0; j < row; j++)
{
System.out.print(array[j][i]+" ");
}
System.out.println(" ");
}
}
}

11. Find first and second largest number in an array

public class FindTopTwo {

public static void main(String[] args) {


int numArr[] = {2, 5, 14, 1, 26, 65, 123, 6};
int firstNum = 0;
int secondNum = 0;
for(int i = 0; i < numArr.length; i++){
if(firstNum < numArr[i]){
secondNum = firstNum;
firstNum = numArr[i];
}else if(secondNum < numArr[i]){
secondNum = numArr[i];
}
}
System.out.println("Top two numbers : First - "
+ firstNum + " Second " + secondNum);
}

12. Perfect Number


import java.util.Scanner;
public class Perfect
{
public static void main(String[] args)
{
int n, sum = 0;
Scanner s = new Scanner(System.in);
System.out.print("Enter any integer you want to check:");
n = s.nextInt();
for(int i = 1; i < n; i++)
{
if(n % i == 0)
{
sum = sum + i;
}
}
if(sum == n)
{
System.out.println("Given number is Perfect");
}
else
{
System.out.println("Given number is not Perfect");
}
}

13. Java program for Strong Number


import java.util.Scanner;

public class StrongNumber1 {


private static Scanner sc;
public static void main(String[] args)
{
int Number, Temp, Reminder, Sum = 0, i, Factorial;
sc = new Scanner(System.in);

System.out.print(" Please Enter any Number : ");


Number = sc.nextInt();

Temp = Number;
while( Temp > 0)
{
Factorial = 1;
i = 1;
Reminder = Temp % 10;
while (i <= Reminder)
{
Factorial = Factorial * i;
i++;
}
System.out.println(" The Factorial of " + Reminder + " = " + Factorial);
Sum = Sum + Factorial;
Temp = Temp /10;
}

System.out.println(" The Sum of the Factorials of a Given Number " +


Number + " = " + Sum);

if ( Number == Sum )
{
System.out.println("\n " + Number + " is a Strong Number");
}
else
{
System.out.println("\n " + Number + " is Not a Strong Number");
}
}
}

14. Factorial
class FactorialExample{
public static void main(String args[]){
int i,fact=1;
int number=5;//It is the number to calculate factorial
for(i=1;i<=number;i++){
fact=fact*i;
}
System.out.println("Factorial of "+number+" is: "+fact);
}
}

15. Java program for implementation of Bubble Sort


class BubbleSort
{
void bubbleSort(int arr[])
{
int n = arr.length;
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}

/* Prints the array */


void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i] + " ");
System.out.println();
}

public static void main(String args[])


{
BubbleSort ob = new BubbleSort();
int arr[] = {64, 34, 25, 12, 22, 11, 90};
ob.bubbleSort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

16. write a program to reverse a arraylist in java


import java.util.*;
public class ReverseArrayList
{
public static void main(String[] args)
{
ArrayList<String> arrlist = new ArrayList<String>();
arrlist.add("Apple");
arrlist.add("Amazon");
arrlist.add("Facebook");
arrlist.add("Google");
arrlist.add("IBM");
arrlist.add("Tesla");
System.out.println("Before Reverse ArrayList:");
System.out.println(arrlist);
Collections.reverse(arrlist);
System.out.println("After Reverse ArrayList:");
System.out.println(arrlist);
}
}

17. write a program to compare two strings


public class Comparision{
public static void main(String args[]){
String s1="hello";
String s2="hello";
String s3="hemlo";
String s4="flag";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
}
}

18. Write a program on conversion of decimal to hexa


import java.util.Scanner;
class DecimalToHexa
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =sc.nextInt();
// calling method toHexString()
String str = Integer.toHexString(num);
System.out.println(" Decimal to hexadecimal: "+str);
}
}
(or)
import java.util.Scanner;
class DecimalToHexa
{
public static void main(String args[])
{
Scanner sc = new Scanner( System.in );
System.out.print("Enter a decimal number : ");
int num =sc.nextInt();
// For storing remainder
int rem;
// For storing result
String result="";
// Digits in hexadecimal number system
char hex[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
while(num>0)
{
rem=num%16;
result=hex[rem]+result;
num=num/16;
}
System.out.println("Decimal to hexadecimal: "+result);
}
}

19. Read two String user input and check if first contains second in a java

import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First String:");
String s1 = scanner.nextLine();
System.out.println("Enter Second String:");
String s2 = scanner.nextLine();
scanner.close();
boolean result = stringContainsSubstring(s1, s2);
System.out.println(s1+" contains "+s2+" = "+result);
}
private static boolean stringContainsSubstring(String string, String substring) {
boolean result = false;
result = string.contains(substring);
return result;
}
}

20. write a simple program on threads


class MyThread extends Thread{
public void run(){
System.out.println("My thread is in running state.");
}
}
class ThreadSleepDemo{
public static void main(String args[]){
MyThread obj=new MyThread();
obj.start();
while(obj.isAlive())
{
try
{
obj.sleep(10);
}
catch(InterruptedException e)
{
System.out.println(“Sleeping thread interrupted”);
}
System.out.println(“Thread-Sleep Demo Complete”);
}
}
}

21. write a program to print the odd and even places numbers in an array
import java.util.*;
public class Main
{
public static void main(String[] args)
{
int n;
Scanner s = new Scanner(System.in);
System.out.print("Enter no. of elements you want in array:");
n = s.nextInt();
int a[] = new int[n];
System.out.println("Enter all the elements:");
for (int i = 0; i < n; i++)
{
a[i] = s.nextInt();
}
System.out.print("Odd numbers:");
for(int i = 0 ; i < n ; i++)
{
if(a[i] % 2 != 0)
{
System.out.print(a[i]+" ");
}
}
System.out.println("");
System.out.print("Even numbers:");
for(int i = 0 ; i < n ; i++)
{
if(a[i] % 2 == 0)
{
System.out.print(a[i]+" ");
}
}
}
}

22. Program to count the number of digits


import java.util.*;
class Main {
public static void main(String[] args) {
int count = 0;
Scanner sc = new Scanner(System.in);
int num = sc.nextInt();
while(num != 0)
{
num = num/10;
++count;
}
System.out.println("Number of digits: " + count);
}
}

23. Write a program for the panagram


panagram: It means each and every alphabet should be in the string which we are taking

public class Main {


public static void main(String[] args) {
String str = "The quick brown fox jumps over the lazy dog";
boolean[] alphaList = new boolean[26];
int index = 0;
int flag = 1;
for (int i = 0; i < str.length(); i++) {
if ( str.charAt(i) >= 'A' && str.charAt(i) <= 'Z') {
index = str.charAt(i) - 'A';
}else if( str.charAt(i) >= 'a' && str.charAt(i) <= 'z') {
index = str.charAt(i) - 'a';
}
alphaList[index] = true;
}
for (int i = 0; i <= 25; i++) {
if (alphaList[i] == false)
flag = 0;
}
System.out.print("String: " + str);
if (flag == 1)
System.out.print("\nThe above string is a pangram.");
else
System.out.print("\nThe above string is not a pangram.");
}
}
24. write a program to find the length of the string
import java.util.Scanner;
public class Stringpro
{
public static void main(String args[])
{
String str;
int len;
Scanner sc = new Scanner(System.in);
System.out.print("Enter Your Name : ");
str = sc.nextLine();
len = str.length();
System.out.print("Length of Entered String is " + len);
}
}

25. Write a program for the spy number


spy: It means the sum of a given number and product of the given number should be same

import java.util.*;
class Main
{
static boolean checkSpy(int input)
{
int digit, sum = 0, product = 1;
while (input > 0)
{
digit = input % 10;
sum = sum + digit;
product = product * digit;
input = input / 10;
}
if (sum == product)
return true;
else
return false;
}
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();
if (checkSpy(input))
System.out.println("The number is "+ "a Spy number");
else
System.out.println("The number is "+ "NOT a Spy number");
}
}

26. Write a program for the selection sort


import java.util.*;
public class Main {
public static void selectionSort(int[] arr){
for (int i = 0; i < arr.length - 1; i++)
{
int index = i;
for (int j = i + 1; j < arr.length; j++){
if (arr[j] < arr[index]){
index = j;//searching for lowest index
}
}
int smallerNumber = arr[index];
arr[index] = arr[i];
arr[i] = smallerNumber;
}
}
public static void main(String a[]){
Scanner sc = new Scanner(System.in);
System.out.println("enter n value");
int n = sc.nextInt();
int arr1[] = new int[n]; // fixing the array with particular no of integers
System.out.println("Enter " + n + " integers");
for (int i = 0; i < n; i++)
arr1[i] = sc.nextInt();
System.out.println("Before Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
System.out.println();
selectionSort(arr1);//sorting array using selection sort
System.out.println("After Selection Sort");
for(int i:arr1){
System.out.print(i+" ");
}
}
}

27. write a program on array index out of bound exception


class Exception
{
public static void main(String args[])
{
try{
String str="beginnersbook";
System.out.println(str.length());;
char c = str.charAt(0);
c = str.charAt(40);
System.out.println(c);
}catch(StringIndexOutOfBoundsException e){
System.out.println("StringIndexOutOfBoundsException!!");
}
}
}

29. Palindrome

int n=454;
while(n>0)
{
r=n%10;
rev=(rev*10)+r;
n=n/10;
}
if(temp==rev)
System.out.println("palindrome number ");
else
System.out.println("not palindrome");

30. String palindrome

Method 1:

int length = str.length();

for ( int i = length - 1; i >= 0; i-- )


rev = rev + str.charAt(i);
if (str.equals(rev))
System.out.println(str+" is a palindrome");
else
System.out.println(str+" is not a palindrome");

Method 2:

// reverse the given String


String reverse = new StringBuffer(s).reverse().toString();

// check whether the string is palindrome or not


if (s.equals(reverse))
System.out.println("Yes");

else
System.out.println("No");

31.Prime number

int num=29;

boolean flag=false;

for( int i=2; i<num/2; ++i)

if( num%i == 0)

flag=true;

break;

}
}

if( !flag )

System.out.println(“prime number”);

else

System.out.println(“not a prime number”);

32. Char is vowel or consonant

if(ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' )

System.out.println(ch + " is vowel");

else

System.out.println(ch + " is consonant");

33. Prime numbers between two intervels

for(i = s1; i <= s2; i++)

for( j = 2; j < i; j++)

if(i % j == 0)

{
flag = 0;

break;

Else

flag = 1;

if(flag == 1)

System.out.println(i);

34. Factors of a number

For loop

int number = 60;

System.out.print("Factors of " + number + " are: ");

for(int i = 1; i <= number; ++i) {

if (number % i == 0) {

System.out.print(i + " ");

While loop:
i = 1;

while(i <= Number) {

if(Number % i == 0) {

System.out.format(" %d ", i);

i++;

35. How To Remove White Spaces From String In Java Using Built-In Methods?

public class RemoveWhiteSpaces


{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter input string to be cleaned from white spaces...!");

String inputString = sc.nextLine();

String stringWithoutSpaces = inputString.replaceAll("\s+", "");

System.out.println("Input String : "+inputString);

System.out.println("Input String Without Spaces : "+stringWithoutSpaces);

}
}

36. Find All Pairs Of Elements In An Array Whose Sum Is Equal To A Given Number

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


{
for (int j = i+1; j < inputArray.length; j++)
{
if(inputArray[i]+inputArray[j] == inputNumber)
{
System.out.println(inputArray[i]+" + "+inputArray[j]+" = "+inputNumber);
}
}
}

37. find the duplicate characters in a string.

String str = "programming";


int cnt = 0;
char[] inp = str.toCharArray();
System.out.println("Duplicate Characters are:");
for (int i = 0; i < str.length(); i++) {
for (int j = i + 1; j < str.length(); j++) {
if (inp[i] == inp[j]) {
System.out.println(inp[j]);
cnt++;
break;
}
}
}

38. Square root of a number


double sqrt(int number) {
double t;

double squareRoot = number / 2;

do
{
t = squareRoot;
squareRoot = (t + (number / t)) / 2;
} while ((t - squareRoot) != 0);

return squareRoot;
}

39. Binary Search

int c, first, last, middle, n, search, array[];

first = 0;
last = n - 1;
middle = (first + last)/2;

while( first <= last )


{
if ( array[middle] < search )
first = middle + 1;
else if ( array[middle] == search )
{
System.out.println(search + " found at location " + (middle + 1) + ".");
break;
}
else
last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
System.out.println(search + " isn't present in the list.\n");

40. Count no of words in given String

int count=0;

char ch[]= new char[string.length()];


for(int i=0;i<string.length();i++)
{
ch[i]= string.charAt(i);
if( ((i>0)&&(ch[i]!=' ')&&(ch[i-1]==' ')) || ((ch[0]!=' ')&&(i==0)) )
count++;
}

41. Check two arrays are equal or not

boolean equalOrNot = true;

if(arrayOne.length == arrayTwo.length)
{
for (int i = 0; i < arrayOne.length; i++)
{
if(arrayOne[i] != arrayTwo[i])

equalOrNot = false;

}
}
else
equalOrNot = false;

if (equalOrNot)

System.out.println("Two Arrays Are Equal");

else

System.out.println("Two Arrays Are Not equal");

42. Remove An Element At Specific Index From An Array?

String[] arrayBeforeRemoval = new String[] {"Zero", "One", "Two", "Three", "Four",


"Five", "Six"};

//Removing an element at index 2

String[] arrayAfterRemoval = ArrayUtils.remove(arrayBeforeRemoval, 2);

System.out.println("Array After Removal");


System.out.println(Arrays.toString(arrayAfterRemoval));

43. Write a program to swap two numbers without using third variable?
import java.util.*;
class SwapTwoNumbers{
public static void main(int args[]){
int a1,a2;
Scanner sc=new Scanner(System.in);
System.out.println(“ enter two numbers”);
a1=sc.nextInt();
a2=sc.nextInt();
System.out.println(“ before swapping values of a1 and a2 is:”+a1” ”+a2);
a1=a1+a2;
a2=a1-a2;
a1=a1-a2;
System.out.println(“ after swapping values of a1 and a2”+a1+” ”+a2);
}
}
44.Write a program to remove a specified character from a string?
Import java.util.ArrayList;
Import java.util.List;
class RemoveCharFromString{
public static void main(String args[]){

Scanner sc=new Scanner(System.in);


String word=sc.nextLine();
Char ch=sc.next().charAt(0);
StringBuilder sb=new StringBuilder();
Char[] letters=word.toCharArray();
For(char c:letters){
If(c!=ch){
Sb.append(c);
}
}
}
System.out.println(“after removing specified character”+sb.toString());
}
}
Another approach:
Public static String removeRecursive(String word, char ch){
int index = word.indexOf(ch);
if(index == -1){
return word;
}
return removeRecursive(word.substring(0, index) + word.substring(index +1,
word.length()), ch);
}
45.Write a program to find occurrence of a character in a string?
Import java.util.*;
Class MaxandMinsum{
Public static void main(String args[]){
Scanner sc=new Scanner(System.in);
System.out.println(“ enter size of array”);
int max=0,min=0,sum=0;
int n=sc.nextInt();
int a[]=new int(n);
System.out.println(“ enter elements”);
for(i=0;i<n;i++){
a[i]=sc.nextInt();
}
For(i=0;i<n;i++)
{
If(a[i]>min){
Min=a[i];
}
Else
Max=a[i];
}
Sum=max+min;
System.out.println(“ sum of max and min elements in array is”+sum);
}
}
46.Write a program to check two strings anagrams or not?
import java.io.*;
import java.util.Arrays;
import java.util.Collections;

class Anagrams {

static boolean areAnagram(char[] str1, char[] str2)


{
int n1 = str1.length;
int n2 = str2.length;

if (n1 != n2)
return false;
else{
Arrays.sort(str1);
Arrays.sort(str2);
for (int i = 0; i < n1; i++)
if (str1[i] != str2[i])
return false;
else
return true;
}
}

public static void main(String args[])


{
char str1[] = { 'a', 'b', 'd', 'c' };
char str2[] = { 'd', 'a', 'b', 'c' };
if (areAnagram(str1, str2))
System.out.println("The two strings are"
+ " anagram of each other");
else
System.out.println("The two strings are not"
+ " anagram of each other");
}
}
47.Write a program to convert a binary number into decimal number?
import java.util.Scanner;

public class BinaryToDecimal {

public static void main(String[] args) {


Scanner ip=new Scanner(System.in);
System.out.println("enter string :");
String i=ip.nextLine();
StringBuilder sp=new StringBuilder(i.length());
for (int j = 0; j < i.length(); j++) {
char c=i.charAt(j);
if(c>47&&c<50) {
sp.append(c);
}
else {
System.out.println("invalid binary number");
System.exit(0);
}
}
int decimal=Integer.parseInt(sp.toString(),2);
System.out.println(decimal);

}
48.Write a program for reverse of a string without using predefined functions?

import java.util.*;
class Reverse{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
String s,rev=” ”;
s=sc.nextLine();
int n=s.length();
for(i=n;i>0;i--){
rev=rev+s.charAt(i);
}
System.out.println(“reverse of ”+s+” is”+rev);
}
}

49.Write a program to find ASCII value of a character?


Import java.util.*;
class Asciivalue{
public static void main(String args[]){
Scanner sc=new Scanner(System.in);
char ch=sc.next().charAt(0);
int ascii=ch;
int castAscsii=(int)ch;
System.out.println(“ the ascii value of ”+ch+” is”+ascii);
System.out.println(“ the ascii value of ”+ch+” is”+castAscii);
}
}
50.Write a program to find roots of quadratic equation?
Import java.util.*;
class Quadratic{
public static void main(string[] args){
int a,b,c;
double r1,r2;

Scanner sc =new Scanner(System.in);


System.out.println(“ enter a,b,c values”);
a=sc.nextInt();
b=sc.nextInt();
c=sc.nextInt();
double d=b*b-4*a*c;
if(d>0){
r1=(-b+Math.sqrt(d))/(2*a);
r2=(-b-Math.sqrt(d))/(2*a);
System.out.println(“ roots of quadratic equation are”+r1+” “+r2);
}
else if(d==0){
r1=r2=-b/(2*a);
System.out.println(“ roots of quadratic equation are”+r1+” “+r2);
}
else{
double realpart=-b/(2*a);
double imginarypart=Math.sqrt(-d)/(2*a);
System.out.format(“ roots of quadratic equation are r1=%.2f+%.2fi and r2=%.2f+%.2fi” ,
realpart,imaginarypart,realpart,imaginarypart);
}
}
}
51.Write a program for Arithmetic Exception?
class ArithmeticException_Demo
{
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b;
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
52.Write a program for number format exception?
class NumberFormat_Demo
{
public static void main(String args[])
{
try {

int num = Integer.parseInt ("akki") ;


System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
53.Program to concatenate two arrays without using arraycopy

public class Concat {

public static void main(String[] args) {


int[] array1 = {1, 2, 3};
int[] array2 = {4, 5, 6};

int length = array1.length + array2.length;

int[] result = new int[length];


int pos = 0;
for (int element : array1) {
result[pos] = element;
pos++;
}

for (int element : array2) {


result[pos] = element;
pos++;
}

System.out.println(Arrays.toString(result));
}
}

54.Program to perform binary search using recursion

class BinarySearchExample1{
public static int binarySearch(int arr[], int first, int last, int key){
if (last>=first){
int mid = first + (last - first)/2;
if (arr[mid] == key){
return mid;
}
if (arr[mid] > key){
return binarySearch(arr, first, mid-1, key);//search in left subarray
}else{
return binarySearch(arr, mid+1, last, key);//search in right subarray
}
}
return -1;
}
public static void main(String args[]){
int arr[] = {10,20,30,40,50};
int key = 30;
int last=arr.length-1;
int result = binarySearch(arr,0,last,key);
if (result == -1)
System.out.println("Element is not found!");
else
System.out.println("Element is found at index: "+result);
}
}
55. Program to perform operations on a tree set

Public class TreeSetExample{


Public static void main(String[] args){

TreeSet<String> TreeSet = new TreeSet<>();

TreeSet.add("A");
TreeSet.add("B");
TreeSet.add("C");
TreeSet.add("D");
TreeSet.add("E");

System.out.println(TreeSet);

boolean found = TreeSet.contains("A”);


System.out.println(found);

TreeSet.remove("D");

Iterator<String> itr = TreeSet.iterator();

while(itr.hasNext())
{
String value = itr.next();

System.out.println("Value: " + value);


}
}
}
56 .How to check an element is present in a list or not?
import java.util.ArrayList;

class ExistorNot {
public static void main(String[] args)
{

ArrayList<Integer> arr = new ArrayList<Integer>(4);


arr.add(1);
arr.add(2);
arr.add(3);
arr.add(4);

boolean ans = arr.contains(2);

if (ans)
System.out.println("The list contains 2");
else
System.out.println("The list does not contains 2");

}
}

57.Program to convert map into set?


import java.util.Map;

class MaptoSet {
public static void main(String[] args)
{

Map<Integer, String> sourceMap = new HashMap<>();


sourceMap.put(1,”abc”);
sourceMap.put(2,”xyz”);
sourceMap.put(3,”lmn”);
Set<String> targetSet = new HashSet<>(sourceMap.values());
System.out.println(targetSet);
}
}

58. Java program to find largest of three numbers using ternary operator?
Code:-
public class LargestNumber
{
public static void main(String[] args)
{
int num1, num2, num3, result, temp;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter First Number:");
num1 = scanner.nextInt();
System.out.println("Enter Second Number:");
num2 = scanner.nextInt();
System.out.println("Enter Third Number:");
num3 = scanner.nextInt();
scanner.close();
temp = num1>num2 ? num1:num2;
result = num3>temp ? num3:temp;
System.out.println("Largest Number is:"+result);
}
}
59. Java program to check if given number is perfect square or not?
Code:-
import java.util.Scanner;
class PerfectSquare {

static boolean checkPerfectSquare(double x)


{
double sq = Math.sqrt(x);
return ((sq - Math.floor(sq)) == 0);
}
public static void main(String[] args)
{
System.out.print("Enter any number:");
Scanner scanner = new Scanner(System.in);
double num = scanner.nextDouble();
scanner.close();
if (checkPerfectSquare(num))
System.out.print(num+ " is a perfect square number");
else
System.out.print(num+ " is not a perfect square number");
}
}
60. Java program to break integer into digits?
Code:-
import java.util.Scanner;
public class IntToDigit
{
public static void main(String args[])
{
int num, temp, digit, count = 0;
Scanner scanner = new Scanner(System.in);
System.out.print("Enter any number:");
num = scanner.nextInt();
scanner.close();
temp = num;
while(num > 0)
{
num = num / 10;
count++;
}
while(temp > 0)
{
digit = temp % 10;
System.out.println("Digit at place "+count+" is: "+digit);
temp = temp / 10;
count--;
}
}
}
61. Java program to check given year is leap year or not?
Code:-
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
int year;
Scanner scan = new Scanner(System.in);
System.out.println("Enter any Year:");
year = scan.nextInt();
scan.close();
boolean isLeap = false;
if(year % 4 == 0)
{
if( year % 100 == 0)
{
if ( year % 400 == 0)
isLeap = true;
else
isLeap = false;
}
else
isLeap = true;
}
else
{
isLeap = false;
}
if(isLeap)
System.out.println(year + " is a Leap Year.");
else
System.out.println(year + " is not a Leap Year.");
}
}
62. Java program to generate random number?
Code:-
import java.util.*;
class GenerateRandomNumber {
public static void main(String[] args) {
int counter;
Random rnum = new Random();
System.out.println("Random Numbers:");
for (i = 1; i <= 5; i++) {
System.out.println(rnum.nextInt(200));
}
}
}
63. Java program to print alternative prime number?
Code:-
class AlternativePrime
{
static int checkPrime(int num)
{
int i, flag = 0;
for(i = 2; i<= num / 2; i++)
{
if(num % i == 0)
{
flag = 1;
break;
}
}
if(flag == 0)
return 1;
else
return 0;
}
static void printAltPrime(int n)
{
int temp = 2;
for(int num = 2; num <= n-1; num++)
{
if (checkPrime(num) == 1)
{
if (temp % 2 == 0)
System.out.print(num + " ");
temp ++;
}
}
}
public static void main(String[] args)
{
int num = 20;
System.out.print("Alternate prime numbers upto " + num+" are: ");
printAltPrime(num);
}
}
64. Java program to encode and decode URL?
Code:-
import java.util.Base64;
public class Base64BasicEncryption {
public static void main(String[] args) {
Base64.Encoder encoder = Base64.getUrlEncoder();
String eStr =
encoder.encodeToString("http://www.google.com/javaclasses/".getBytes());
System.out.println("Encoded URL: "+eStr);
Base64.Decoder decoder = Base64.getUrlDecoder();
String dStr = new String(decoder.decode(eStr));
System.out.println("Decoded URL: "+dStr);
}
}
65. Java program to reverse a string without using string inbuilt function reverse()?
Code:-
public class StringReverse {
public static void main(String[] args) {
String str = "Saket Saurav";
char chars[] = str.toCharArray(); // converted to character array and printed in
reverse order
for(int i= chars.length-1; i>=0; i--) {
System.out.print(chars[i]);
}
}
}

66. Java program to create singleton design pattern?


Code:-
public class JavaHungrySingleton
{
private static JavaHungrySingleton uniqueInstance;
private JavaHungrySingleton(){}
public static synchronized JavaHungrySingleton getInstance()
{
if (uniqueInstance ==null )
{
uniqueInstance=new JavaHungrySingleton();
}
return uniqueInstance ;
}
//logic implementation or our code
}
67. Java program to find largest number less than given number and without a given
digit?
Code:-
public class LargestNumber
{
static int getLLessThanN(int number, int digit)
{
//Converting digit to char
char c = Integer.toString(digit).charAt(0);
for (int i = number; i > 0; --i)
{
if(Integer.toString(i).indexOf(c) == -1)
{
//If 'i' doesn't contain 'c'

return i;
}
}
return -1;
}
public static void main(String[] args)
{
Int digit,number;
Scanner sc=new Scanner(System.in);
number=sc.nextInt();
digit=sc.nextInt();
System.out.println(getLLessThanN(number, digit));
}
}
68. Java program to check given number is niven/harshad number?
Code:-
public class NivenNumber {
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
int num = sc.nextInt();
int x = num, y, sum = 0;
while(x>0)
{
y = x%10;
sum = sum + y;
x = x/10;
}
if(num%sum == 0)
System.out.println(num+" is a Harshad Number.");
else
System.out.println(num+" is not a Harshad Number.");
}
}//353 is Harshad Number

69. How to avoid dead lock in java?

public class DeadLockFixed {


/** * Both method are now requesting lock in same order, first Integer and then String. * You
could have also done reverse e.g. first String and then Integer,

* both will solve the problem, as long as both method are requesting lock

* in consistent order. */

public void method1() {

synchronized (Integer.class) {

System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {

System.out.println("Aquired lock on String.class object");

public void method2() {

synchronized (Integer.class) {

System.out.println("Aquired lock on Integer.class object");

synchronized (String.class) {

System.out.println("Aquired lock on String.class object");

70. Sort the array by using merge sort?

#include<stdio.h>

void mergeSort(int[],int,int);

void merge(int[],int,int,int);

void main ()

{
int a[10]= {10, 9, 7, 101, 23, 44, 12, 78, 34, 23};

int i;

mergeSort(a,0,9);

printf("printing the sorted elements");

for(i=0;i<10;i++)

printf("\n%d\n",a[i]);

void mergeSort(int a[], int beg, int end)

int mid;

if(beg<end)

mid = (beg+end)/2;

mergeSort(a,beg,mid);

mergeSort(a,mid+1,end);

merge(a,beg,mid,end);

void merge(int a[], int beg, int mid, int end)

int i=beg,j=mid+1,k,index = beg;

int temp[10];

while(i<=mid && j<=end)

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

temp[index] = a[i];

i = i+1;

else

temp[index] = a[j];

j = j+1;

index++;

if(i>mid)

while(j<=end)

temp[index] = a[j];

index++;

j++;

else

while(i<=mid)

temp[index] = a[i];

index++;
i++;

k = beg;

while(k<index)

a[k]=temp[k];

k++;

3.java program to print all permutations of a string?

public static void permutation(String input){

permutation("", input);

/*

* Recursive method which actually prints all permutations

* of given String, but since we are passing an empty String

* as current permutation to start with,

* I have made this method private and didn't exposed it to client.

*/

private static void permutation(String perm, String word) {

if (word.isEmpty()) {

System.err.println(perm + word);

} else {

for (int i = 0; i &lt; word.length(); i++) {


permutation(perm + word.charAt(i), word.substring(0, i)

+ word.substring(i + 1, word.length()));

Output:

123

132

213

231

312

321.

71. Verify if a String is a digit number or not using regular expression

import java.util.regex.Pattern;

/**

* Java program to demonstrate use of Regular Expression to check

* if a String is a 6 digit number or not.

*/

public class RegularExpressionExample {

public static void main(String args[]) {

// Regular expression in Java to check if String is number or not

Pattern pattern = Pattern.compile(".*[^0-9].*");


//Pattern pattern = Pattern.compile(".*\\D.*");

String [] inputs = {"123", "-123" , "123.12", "abcd123"};

for(String input: inputs){

System.out.println( "does " + input + " is number : "

+ !pattern.matcher(input).matches());

// Regular expression in java to check if String is 6 digit number or not

String [] numbers = {"123", "1234" , "123.12", "abcd123", "123456"};

Pattern digitPattern = Pattern.compile("\\d{6}");

//Pattern digitPattern = Pattern.compile("\\d\\d\\d\\d\\d\\d");

for(String number: numbers){

System.out.println( "does " + number + " is 6 digit number : "

+ digitPattern.matcher(number).matches());

Output:

does 123 is number : true

does -123 is number : false

does 123.12 is number : false

does abcd123 is number : false


does 123 is 6 digit number : false

does 1234 is 6 digit number : false

does 123.12 is 6 digit number : false

does abcd123 is 6 digit number : false

does 123456 is 6 digit number : true

5.Program to count leaf nodes in a binary tree?

// Java implementation to find leaf count of a given Binary tree

/* Class containing left and right child of current

node and key value*/

class Node

int data;

Node left, right;

public Node(int item)

data = item;

left = right = null;

public class BinaryTree

//Root of the Binary Tree

Node root;
/* Function to get the count of leaf nodes in a binary tree*/

int getLeafCount()

return getLeafCount(root);

int getLeafCount(Node node)

if (node == null)

return 0;

if (node.left == null && node.right == null)

return 1;

else

return getLeafCount(node.left) + getLeafCount(node.right);

/* Driver program to test above functions */

public static void main(String args[])

/* create a tree */

BinaryTree tree = new BinaryTree();

tree.root = new Node(1);

tree.root.left = new Node(2);

tree.root.right = new Node(3);

tree.root.left.left = new Node(4);

tree.root.left.right = new Node(5);


/* get leaf count of the abve tree */

System.out.println("The leaf count of binary tree is : "+ tree.getLeafCount());

71. Java Program to calculate an average of all numbers in an array.

import java.util.Scanner;

/*

* Java Program to calculate average of numbers in array

* input : [1, 2, 3, 4, 5]

* output: 3.0

*/

public class ArrayAverageProblem {

public static void main(String[] args) {

System.out

.println("Welcome to Java Prorgram to calculate average of numbers");

System.out.println("Please enter length of the array?");

Scanner scnr = new Scanner(System.in);

int length = scnr.nextInt();

int[] input = new int[length];

System.out.println("Please enter numbers ");


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

input[i] = scnr.nextInt();

float average = average(input);

System.out.println("Average of all numbers in array is " + average);

scnr.close();

/**

* Java method to calculate average of all numbers of array

* @param input

* @return average of all numbers in array

*/

public static float average(int[] input) {

float sum = 0f;

for (int number : input) {

sum = sum + number;

return sum / input.length;

}
Output

Welcome to Java Program to calculate average of numbers

Please enter the length of the array?

Please enter numbers

Average of all numbers in array is 3.0

72. Write a program to find largest between three numbers using ternary operator?

import java.util.Scanner;
public class Largest_Ternary
{
public static void main(String[] args)
{
int a, b, c, d;
Scanner s = new Scanner(System.in);
System.out.println("Enter all three numbers:");
a = s.nextInt();
b = s.nextInt();
c = s.nextInt();
d = c > (a > b ? a : b) ? c : ((a > b) ? a : b);
System.out.println("Largest Number:"+d);
}
}

73. Write a java program to print the following pattern

1
24
369
4 8 12 16
5 10 15 20 25
6 12 18 24 30 36
7 14 21 28 35 42 49
8 16 24 32 40 48 56 64
9 18 27 36 45 54 63 72 81
10 20 30 40 50 60 70 80 90 100

public class pattern{


public static void main(String[] args){
int lines=10;
int i=1;
int j;
for(i=1;i<=lines;i++){// this loop is used to print the lines
for(j=1;j<=i;j++){// this loop is used to print lines
System.out.print(i*j+" ");
}
System.out.println("");
}
}
}

74. Write a java program to print the following pattern

*****
****
***
**
*

import java.util.Scanner;
public class Edureka
{
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);

System.out.println("Enter the number of rows: "); //takes input from user

int rows = sc.nextInt();

for (int i= rows-1; i>=0 ; i--)


{
for (int j=0; j<=i; j++)
{
System.out.print("*" + " ");
}
System.out.println();
}
sc.close();
}
}
555.

5555

Вам также может понравиться