Core Java

1. Wap to print Fibonnaci series eg 1 1 2 3 5 8 …. up to a given number

class Fibonacci{
public static void main(String args[])
{
 int n1=0,n2=1,n3,i,count=10;
 System.out.print(n1+" "+n2);//printing 0 and 1
 for(i=2;i<count;++i)//loop starts from 2 because 0 and 1 are already printed
 {
  n3=n1+n2;
  System.out.print(" "+n3);
  n1=n2;
  n2=n3;
 }
}
}
Output: 0 1 1 2 3 5 8 13 21 34

2. Wap to check if given number is prime number or not.

public class Prime{
 public static void main(String args[]){
  int i,m=0,flag=0;
  int n=3;//it is the number to be checked
  m=n/2;
  if(n==0||n==1){
   System.out.println(n+" is not prime number");
  }else{
   for(i=2;i<=m;i++){
    if(n%i==0){
     System.out.println(n+" is not prime number");
     flag=1;
     break;
    }
   }
   if(flag==0)  { System.out.println(n+" is prime number"); }
  }//end of else
}
}
Output:
3 is prime number

3. Wap to check if given string is palindrome or not.

public class Palindrome
{
    public static void main(String args[])
    {
        String a, b = "";
        Scanner s = new Scanner(System.in);
        System.out.print("Enter the string you want to check:");
        a = s.nextLine();
        int n = a.length();
        for(int i = n - 1; i >= 0; i--)
        {
            b = b + a.charAt(i);
        }
        if(a.equalsIgnoreCase(b))
        {
            System.out.println("The string is palindrome.");
        }
        else
        {
            System.out.println("The string is not palindrome.");
        }
    }
}
Output:
Enter the string you want to check: abba
The string is palindrome.

4. Wap to check if given integer is palindrome or not.

class Palindrome{
 public static void main(String args[]){
  int r,sum=0,temp;
  int n=313;//It is the number variable to be checked for palindrome
  temp=n;
  while(n>0){
   r=n%10;  //getting remainder
   sum=(sum*10)+r;
   n=n/10;
  }
  if(temp==sum)
   System.out.println("Palindrome Number ");
  else
   System.out.println("not palindrome");
}
}
Output:
Palindrome Number

5. Wap to check if given number is armstrong or not.

class Armstrong{
  public static void main(String[] args)  {
    int c=0,a,temp;
    int n=371;//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");
   }
}
Output:
Armstrong Number

6. Wap for Factorial.

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

7. WAP to Reverse the String.

1) By StringBuilder / StringBuffer
public class StringFormatter {
public static String reverseString(String str){
    StringBuilder sb=new StringBuilder(str);
    sb.reverse();
    return sb.toString();
}
}
public class TestStringFormatter {
public static void main(String[] args) {
    System.out.println(StringFormatter.reverseString("India"));
    System.out.println(StringFormatter.reverseString("Hindustan"));
    }
}
Output:
aidnI
natsudniH
2) By Reverse Iteration
public class StringFormatter {
public static String reverseString(String str){
    char ch[]=str.toCharArray();
    String rev="";
    for(int i=ch.length-1;i>=0;i--){
        rev+=ch[i];
    }
    return rev;
}
}
public class TestStringFormatter {
public static void main(String[] args) {
    System.out.println(StringFormatter.reverseString("India"));
    System.out.println(StringFormatter.reverseString("Hindustan"));
    }
}
Output:
aidnI
natsudniH

8. Wap to remove duplicates from array.

public class RemoveDuplicate{
public static int removeDuplicate(int arr[], int n){
        if (n==0 || n==1){
            return n;
        }
        int[] temp = new int[n];
        int j = 0;
        for (int i=0; i<n-1; i++){
            if (arr[i] != arr[i+1]){
                temp[j++] = arr[i];
            }
         }
        temp[j++] = arr[n-1];
        // Changing original array
        for (int i=0; i<j; i++){
            arr[i] = temp[i];
        }
        return j;
    }
    public static void main (String[] args) {
        int arr[] = {5,10,20,20,30,5,30,40,50,50};
        int length = arr.length;
        length = removeDuplicate(arr, length);
        //printing array elements
        for (int i=0; i<length; i++)
           System.out.print(arr[i]+" ");
    }
}
Output:
5 10 20 30 40 50 

9. Wap to calculate square root of number.

public class Squareroot {
	private static Scanner c;
	public static void main(String[] args)
	{
		double number, squareRoot;
		c = new Scanner(System.in);
		System.out.print(" Please Enter any Number : ");
		number = c.nextDouble();
		squareRoot = Math.sqrt(number);
		System.out.println("n The Square of a Given Number  " + number + "  =  " + squareRoot);
	}
}
Output:
Please enter any number : 144
The Square of a Given Number 144 is 12.0

10. Wap to reverse the word in a string.

import java.io.*;
import java.util.*;
class Reverse {
// reverses individual words of a string
static void reverseWords(String str)
{
    Stack<Character> st=new Stack<Character>();
    // Traverse given string
    for (int i = 0; i < str.length(); ++i) {
        if (str.charAt(i) != ' ')
            st.push(str.charAt(i));
        else {
            while (st.empty() == false) {
                System.out.print(st.pop());
            }
            System.out.print(" ");
        }
    }
    while (st.empty() == false) {
        System.out.print(st.pop());
    }
}
public static void main(String[] args)
{
   String str = "Hello World";
    reverseWords(str);
  }
}
Output:
dlroW olleH

11. Wap to check if given two string is Anagram or not.

public class Anagram {
    static void isAnagram(String str1, String str2) {
        String s1 = str1.replaceAll("\s", "");
        String s2 = str2.replaceAll("\s", "");
        boolean status = true;
        if (s1.length() != s2.length()) {
            status = false;
        } else {
            char[] ArrayS1 = s1.toLowerCase().toCharArray();
            char[] ArrayS2 = s2.toLowerCase().toCharArray();
            Arrays.sort(ArrayS1);
            Arrays.sort(ArrayS2);
            status = Arrays.equals(ArrayS1, ArrayS2);
        }
        if (status) {
            System.out.println(s1 + " and " + s2 + " are anagrams");
        } else {
            System.out.println(s1 + " and " + s2 + " are not anagrams");
        }
    }
    public static void main(String[] args) {
        isAnagram("Road", "Roar");
        isAnagram("Website", "Android");
    }
}
Output:
Road and Roar are anagrams
Website and Android are anagrams

12. Wap to determine if given year is leap year or not.

public class LeapYear {
public static void main(String[] args) {
//year we want to check int year = 2004;
//if year is divisible by 4, it is a leap year
if(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0)) System.out.println("Year " + year + " is a leap year");
else
System.out.println("Year " + year + " is not a leap year");
}
}
Output :
Year 2004 is a leap year

13. Wap to print number 1 to 1000.

public class PrintNumbers
{
    public static void main(String[] args)
    {
        for(int i=1; i<=1000; i++)
        {
            System.out.println(i);
        }
    }
}

14. Wap to calculate sum of first 20 natural number.

public class SumNumbers
{
    public static void main(String[] args)
    {
        int sum = 0;
        for(int i=1; i<=20; i++)
        {
            sum += i;
        }
        System.out.println("Sum: " + sum);
    }
}

15. Wap to Decimal to Binary.

import java.util.Scanner;
public class DecimalToBinary
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Decimal Number : ");
        int inputNumber = scanner.nextInt();
        int copyOfInputNumber = inputNumber;
        String binary = "";
        int rem = 0;
        while (inputNumber > 0)
        {
            rem = inputNumber % 2;
            binary =  rem + binary;
            inputNumber = inputNumber/2;
        }
        System.out.println("Binary of "+copyOfInputNumber+" is "+binary);
    }
}
Output :
Enter Decimal Number :
30
Binary of 30 is 11110

16. Wap to convert Decimal to Octal.

import java.util.Scanner;
public class DecimalToOctal
{
    public static void main(String[] args)
    {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter Decimal Number : ");
        int inputNumber = scanner.nextInt();
        int copyOfInputNumber = inputNumber;
        String octal = "";
        int rem = 0;
        while (inputNumber > 0)
        {
            rem = inputNumber%8;
            octal =  rem + octal;
            inputNumber = inputNumber/8;
        }
        System.out.println("Octal of "+copyOfInputNumber+" is "+octal);
    }
}
Output :
Enter Decimal Number :
250
Octal of 250 is 372

17. Wap to convert Decimal to HexaDecimal.

import java.util.Scanner;
public class DecimalToHexaDecimal
{
    public static void main(String[] args)
    {
        Scanner scanner= new Scanner(System.in);
        System.out.println("Enter Decimal Number : ");
        int inputNumber = scanner.nextInt();
        int copyOfInputNumber = inputNumber;
        String hexa = "";
        char hexaDecimals[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        int rem = 0;
        while (inputNumber > 0)
        {
            rem = inputNumber%16;
            hexa =  hexaDecimals[rem] + hexa;
            inputNumber = inputNumber/16;
        }
        System.out.println("HexaDecimal of "+copyOfInputNumber+" is "+hexa);
    }
}
Output :
Enter Decimal Number :
1500
HexaDecimal of 1500 is 5DC

18. Wap that reads a set of integers, then print the sum of even and odd integers.

import java.util.Scanner;
public class ReadIntegers
{
    public static void main(String[] args)
    {
        Scanner console = new Scanner(System.in);
        int number;
        char choice;
        int evenSum = 0;
        int oddSum = 0;
        do
        {
            System.out.print("Enter the number ");
            number = console.nextInt();
            if( number % 2 == 0)
            {
                evenSum += number;
            }
            else
            {
                oddSum += number;
            }
            System.out.print("Do you want to continue y/n? ");
            choice = console.next().charAt(0);
        }while(choice=='y' || choice == 'Y');
        System.out.println("Sum of even numbers: " + evenSum);
        System.out.println("Sum of odd numbers: " + oddSum);
    }
}

19. Wap to convert Arraylist to array.

public class MainClass
{
    public static void main(String[] args)
    {
        ArrayList<String> list = new ArrayList<String>();
        list.add("PHP");
        list.add("Python");
        list.add("C");
        list.add("SERVLETS");
        list.add("J2EE");
        System.out.println(list);
        Object[] array = list.toArray();
        for (Object object : array)
        {
            System.out.println(object);
        }
    }
}
Output:
PHP
Python
C
Servlet
J2EE

20. Wap to insert an element at particular position in an arraylist.

public class MainClass
{
    public static void main(String[] args)
    {
        ArrayList<String> al = new ArrayList<String>();
        al.add("First");
        al.add("Second");
        al.add("Third");
        al.add("Fourth");
        System.out.println(list);
        //Inserting "A" at index 1
        al.add(1, "A");
        //Inserting "B" at index 3
        al.add(3, "B");
        System.out.println(al);
    }
}
Output:
[First, A, Second, B, Third, Fourth]

21. Wap to remove an element at the particular positon of an arraylist.

public class MainClass
{
    public static void main(String[] args)
    {
        ArrayList<String> al = new ArrayList<String>();
        al.add("A");
        al.add("B");
        al.add("C");
        al.add("D");
        System.out.println(al);
        //Removing an element from position 2
        al.remove(2);
        System.out.println(al);
        //Removing an element from position 3
        al.remove(3);
        System.out.println(al);
    }
}
Output:
[A,B,C,D]
[A,B,D]
[A,B]

22. Wap to retrieve a portion of an arraylist.

public class MainClass
{
    public static void main(String[] args)
    {
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(4);
        al.add(5);
        al.add(6);
        System.out.println(al);
        //Retrieving a SubList
        List<Integer> subList = al.subList(1, 4);
        System.out.println(subList);    //Output : [2, 3, 4]
        //Modifying the list
        al.set(2, 0);
        //Changes will be reflected in subList
        System.out.println(subList);    //Output : [2, 0, 4]
        //Modifying the subList
        subList.set(2, 0);
        //Changes will be reflected in list
        System.out.println(al);    //Output : [1, 2, 0, 0, 5, 6]
    }
}
Output:
[1 2 3 4 5 6]
[2 3 4]
[2 0 4]
[1 2 0 0 5 6]

23. Wap to insert more than one element at a particular position in arraylist.

public class MainClass
{
    public static void main(String[] args)
    {
        ArrayList<Integer> al = new ArrayList<Integer>();
        al.add(1);
        al.add(2);
        al.add(3);
        al.add(4);
        System.out.println(al);     //Output : [1, 2, 3, 4]
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(5);
        list.add(6);
        list.add(7);
        list.add(8);
        System.out.println(list);    //Output : [5, 6, 7, 8]
        //Inserting all elements of list at index 2 of al
        list1.addAll(2, list);
        System.out.println(al);    //Output : [1, 2, 5, 6, 7, 8, 3, 4]
    }
}

24. Wap to sort an array and search an element inside it.

import java.util.Arrays;
public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 4, 2, -7 , 9, -25, 19, 14, -35 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 4);
      System.out.println("Found 4 @ " + index);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if(i != 0) {
            System.out.print(", ");
         }
         System.out.print(array[i]);
      }
      System.out.println();
   }
}
Output :-
Sorted array: [length: 8]
-35 -25 -7 2 4 9 14 19
Found 4 @ 4

25. Wap to sort an array and insert an element inside it.

import java.util.Arrays;
public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 4, 2, -7 , 9, -25, 19, 14, -35 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 1);
      System.out.println("Didn't find 1 @ " + index);
      int newIndex = -index - 1;
      array = insertElement(array, 1, newIndex);
      printArray("With 1 added", array);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if (i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);
      }
      System.out.println();
   }
   private static int[] insertElement(int original[], int element, int index) {
      int length = original.length;
      int destination[] = new int[length + 1];
      System.arraycopy(original, 0, destination, 0, index);
      destination[index] = element;
      System.arraycopy(original, index, destination, index + 1, length - index);
      return destination;
   }
}
Output:
Sorted array: [length: 8]
-35 -25 -7 2 4 9 14 19
Didn't find 1 @ 5
With 1 added: [length: 9]
-35 -25 -7 2 4 1 9 14 19

26. Wap to merge two array.

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
   public static void main(String args[]) {
      String a[] = { "K", "O", "D" };
      String b[] = { "N", "E", "S", "T" };
      List list = new ArrayList(Arrays.asList(a));
      list.addAll(Arrays.asList(b));
      Object[] c = list.toArray();
      System.out.println(Arrays.toString(c));
   }
}
Output:
[K, O, D, N, E, S, T]

27. Wap to sort an array and search an element inside it.

import java.util.Arrays;
public class MainClass {
   public static void main(String args[]) throws Exception {
      int array[] = { 4, 2, -7 , 9, -25, 19, 14, -35 };
      Arrays.sort(array);
      printArray("Sorted array", array);
      int index = Arrays.binarySearch(array, 4);
      System.out.println("Found 4 @ " + index);
   }
   private static void printArray(String message, int array[]) {
      System.out.println(message + ": [length: " + array.length + "]");
      for (int i = 0; i < array.length; i++) {
         if(i != 0){
            System.out.print(", ");
         }
         System.out.print(array[i]);
      }
      System.out.println();
   }
}
Output:
Sorted array: [length: 10]
-35 -25 -7 2 4 9 14 19
Found 4 @ 4

28. Wap to check if two arrays are equal or not.

import java.util.Arrays;
public class Main {
   public static void main(String[] args) throws Exception {
      int[] arry = {2,3,5,7,9,10};
      int[] arry1 = {2,3,5,7,9,10};
      int[] arry2 = {1,2,3,4};
      System.out.println("Is array 1 equal to array 2? " +Arrays.equals(arry, arry1));
      System.out.println("Is array 1 equal to array 3? " +Arrays.equals(arry, arry2));
   }
}
Output:
Is array 1 equal to array 2? true
Is array 1 equal to array 3? false

29. Wap to iterate array-list using for-loop, while loop and advance for loop.

import java.util.*;
public class arrayList {
	public static void main(String[] args) {
		ArrayList al = new ArrayList();
		al.add("5");
		al.add("10");
		al.add("15");
		System.out.println(al.size());
		System.out.println("While Loop:");
		Iterator itr = al.iterator();
		while(itr.hasNext()) {
			System.out.println(itr.next());
		}
		System.out.println("Advanced For Loop:");
		for(Object obj : al) {
			System.out.println(obj);
	}
		System.out.println("For Loop:");
		for(int i=0; i<list.size(); i++) {
			System.out.println(al.get(i));
		}
}
}
Output:
3
While Loop:
5
10
15
Advanced For Loop:
5
10
15
For Loop:
5
10
15

30. Wap to find second largest number in an integer in array.

public class MainClass
{
    static int secondLargest(int[] input)
    {
        int firstLargest, secondLargest;
        //Checking elements of input array
        if(input[0] > input[1])
        {
            //If first element is greater than second element
            firstLargest = input[0];
            secondLargest = input[1];
        }
        else
        {
            //If second element is greater than first element
            firstLargest = input[1];
            secondLargest = input[0];
        }
        //Checking remaining elements of input array
        for (int i = 2; i < input.length; i++)
        {
            if(input[i] > firstLargest)
            {
                secondLargest = firstLargest;
                firstLargest = input[i];
            }
            else if (input[i] < firstLargest && input[i] > secondLargest)
            {
                secondLargest = input[i];
            }
        }
        return secondLargest;
    }
    public static void main(String[] args)
    {
        System.out.println(secondLargest(new int[] {25, 12, 10, 33, 4, 90}));
        System.out.println(secondLargest(new int[] {122, 150, 108, 298, 399}));
        System.out.println(secondLargest(new int[] {1202, 1543, 1011, 2584, 5894}));
    }
}
Output :
10
122
1202

31. Wap to find missing number in an array.

public class MissingNumber
{
    static int sumOfNnumbers(int n)
    {
        int sum = (n * (n+1))/ 2;
        return sum;
    }
    static int sumOfElements(int[] array)
    {
        int sum = 0;
        for (int i = 0; i < array.length; i++)
        {
            sum = sum + array[i];
        }
        return sum;
    }
    public static void main(String[] args)
    {
        int n = 8;
        int[] a = {1, 5, 2, 3, 7, 6, 8};
        int sumOfNnumbers = sumOfNnumbers(n);
        int sumOfElements = sumOfElements(a);
        int missingNumber = sumOfNnumbers - sumOfElements;
        System.out.println("Missing Number is = "+missingNumber);
    }
}

32. Wap to get roman value of a decimal number.

KodNest 9047698
import java.util.Scanner;
public class MainClass
{
    public static void main(String[] args)
    {
        String[] romanSymbols = {"I", "IV", "V", "IX", "X", "XL", "L", "XC", "X", "CD", "D", "CM", "M"};
        int[] decimals = {1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000};
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter The Decimal Number Between 1 and 2999");
        int inputNumber = scanner.nextInt();
        int copyOfInputNumber = inputNumber;
        String roman = "";
        if (inputNumber >= 1 && inputNumber <= 2999)
        {
            for (int i = 0; i < 13; i++)
            {
                while(inputNumber >= decimals[i])
                {
                    inputNumber = inputNumber - decimals[i];
                    roman = roman + romanSymbols[i];
                }
            }
            System.out.println("Roman Value Of "+copyOfInputNumber+" is : "+roman);
        }
        else
        {
            System.out.println("Not a valid number");
        }
    }
}
Output :
Enter The Decimal Number Between 1 and 2999
1269
Roman Value Of 1269 is : MCCLXIX

33. Wap to move zero to an end of an array.

public class SeparateZeros
{
    static void moveZerosToEnd(int inputArray[])
    {
        int counter = 0;
        for (int i = 0; i < inputArray.length; i++)
        {
            if(inputArray[i] != 0)
            {
                inputArray[counter] = inputArray[i];
                //Incrementing the counter by 1
                counter++;
            }
        }
        //Assigning zero to remaining elements
        while (counter < inputArray.length)
        {
            inputArray[counter] = 0;
            counter++;
        }
        System.out.println(Arrays.toString(inputArray));
    }
    public static void main(String[] args)
    {
        moveZerosToEnd(new int[] {4, 10, 20, 0, 30, 0, 8});
        moveZerosToEnd(new int[] {-9, 0, 12, 24, 0, 15, 0, 22});
    }
}
Output :
[4, 10, 20, 30, 8, 0, 0]
[-9, 12, 24, 15, 22, 0, 0]

34. Wap to bring zero to front of an array.

public class SeparateZeros
{
    static void moveZerosToFront(int inputArray[])
    {
        int counter = inputArray.length-1;
        for (int i = inputArray.length-1; i >= 0; i--)
        {
            if(inputArray[i] != 0)
            {
                inputArray[counter] = inputArray[i];
                counter--;
            }
        }
        while (counter >= 0)
        {
            inputArray[counter] = 0;
            counter--;
        }
        System.out.println(Arrays.toString(inputArray));
    }
    public static void main(String[] args)
    {
        moveZerosToFront(new int[] {4, 10, 20, 0, 30, 0, 8});
        moveZerosToFront(new int[] {-9, 0, 12, 24, 0, 15, 0, 22});
    }
}
Output:
[0, 0, 4, 10, 20, 30, 8]
[0, 0, -9, 12, 24, 15, 22]

35. Wap to count occurances of character in string.

class CharCountInString
{
    static void characterCount(String inputString)
    {
        HashMap<Character, Integer> charCountMap = new HashMap<Character, Integer>();
        //Converting given string to char array
        char[] strArray = inputString.toCharArray();
        for (char c : strArray)
        {
            if(charCountMap.containsKey(c))
            {
                charCountMap.put(c, charCountMap.get(c)+1);
            }
            else
            {
                charCountMap.put(c, 1);
            }
        }
        System.out.println(charCountMap);
    }
    public static void main(String[] args)
    {
       characterCount("Internationalization");
    }
}
Output :
{I=1, n=4, t=2, e=1, r=1, a=3, i=3, z=1, o=2}

36. How to find all permutation of a given string

public class StringPermutations {
    public static void main(String args[]) {
        permutation("123");
    }
   public static void permutation(String input){
          permutation("", input);
   }
  private static void permutation(String perm, String word) {
        if (word.isEmpty()) {
            System.err.println(perm + word);
        } else {
            for (int i = 0; i < 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

37. Wap to remove all white space from a string.

1) Using replaceAll() Method.

In the first method, we use replaceAll() method of String class to remove all white spaces (including tab also) from a string. This is the one of the easiest method to remove all white spaces from a string. This method takes two parameters. One is the string to be replaced and another one is the string to be replaced with. We pass the string “s” to be replaced with an empty string “”.

2) Without Using replaceAll() Method.

In the second method, we remove all white spaces (including tab also) from a string without using replaceAll() method. First we convert the given string to char array and then we traverse this array to find white spaces. We append the characters which are not the white spaces to StringBuffer object.

class RemoveWhiteSpaces
{
    public static void main(String[] args)
    {
        String str = " Core Java jsp servlet  jdbc struts hibernate spring ";
        //1. Using replaceAll() Method
        String strWithoutSpace = str.replaceAll("\s", "");
        System.out.println(strWithoutSpace);
Output : CoreJavajspservletsjdbcstrutshibernatespring
        //2. Without Using replaceAll() Method
        char[] strArray = str.toCharArray();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < strArray.length; i++)
        {
            if( (strArray[i] != ' ') && (strArray[i] != 't') )
            {
                sb.append(strArray[i]);
            }
        }
        System.out.println(sb);
    }
}
//Output : CoreJavajspservletsjdbcstrutshibernatespring

38. Wap to convert String To Integer in Java.

There are two methods available in java to convert string to integer. One is Integer.parseInt() method and another one is Integer.valueOf() method. Both these methods are static methods of java.lang.Integer class. Both these methods throw NumberFormatException if input string is not a valid integer. The main difference between Integer.parseInt() and Integer.valueOf() method is that parseInt() method returns primitive int where as valueOf() method returns java.lang.Integer object.

public class Demo1
{
    public static void main(String[] args)
    {
        String s = "2015";
        int i = Integer.parseInt(s);
        System.out.println(i);
    }
}
//Output : 2015
Example2:
public class Demo2
{
    public static void main(String[] args)
    {
        String s = "2015";
        int i = Integer.valueOf(s);
        System.out.println(i);
    }
}
//Output : 2015

39. Wap to convert Integer to String in Java.

You are also often need to do the reverse conversion i.e converting from integer to string. Java provides couple of methods to do that also. one is Integer.toString() method and another one is String.valueOf() method. Both these methods return string representation of the given integer.

public class Demo1
{
    public static void main(String[] args)
    {
        int i = 2015;
        String s = Integer.toString(i);
        System.out.println(s);
    }
}
//Output : 2015
Example2:
public class Demo2
{
    public static void main(String[] args)
    {
        int i = 2015;
        String s = String.valueOf(i);
        System.out.println(s);
    }
}
//Output : 2015

40. Wap to reverse a given string with preserving the position of spaces

KodNest reverse
public class MainClass1
{
    static void reverseString(String inputString)
    {
        //Converting inputString to char array 'inputStringArray'
        char[] inputStringArray = inputString.toCharArray();
        //Defining a new char array 'resultArray' with same size as inputStringArray
        char[] resultArray = new char[inputStringArray.length];
        //First for loop :
        //For every space in the 'inputStringArray',
        //we insert spaces in the 'resultArray' at the corresponding positions
        for (int i = 0; i < inputStringArray.length; i++)
        {
            if (inputStringArray[i] == ' ')
            {
                resultArray[i] = ' ';
            }
        }
        //Initializing 'j' with length of resultArray
        int j = resultArray.length-1;
        //Second for loop :
        //we copy every non-space character of inputStringArray
        //from first to last at 'j' position of resultArray
        for (int i = 0; i < inputStringArray.length; i++)
        {
            if (inputStringArray[i] != ' ')
            {
                //If resultArray already has space at index j then decrementing 'j'
                if(resultArray[j] == ' ')
                {
                    j--;
                }
                resultArray[j] = inputStringArray[i];
                j--;
            }
        }
        System.out.println(inputString+" ---> "+String.valueOf(resultArray));
    }
    public static void main(String[] args)
    {
        reverseString("I Am Not String");
        reverseString("JAVA JSP ANDROID");
      }
}
Output:
I Am Not String —> g ni rtS toNmAI
JAVA JSP ANDROID —> DIOR DNA PSJAVAJ

41. Wap to swap first and last character of words in a sentence.

Input : kodnest for freshers

Output :todnesk  rof sresherf

Approach:As mentioned in the example we have to replace first and last character of word and keep rest of the alphabets as it is.

First we will create an Char array of given String by using toCharArray() method.

Now we iterate the char array by using for loop.

In for loop, we declare a variable whose value is dependent on i.

Whenever we found an alphabet we increase the value of i and whenever we reach at space, we are going to perform swapping between first and last character of the word which is previous of space.

class Demo
{
    static String count(String str)
    {
        // Create an equivalent char array
        // of given string
        char[] ch = str.toCharArray();
        for (int i = 0; i < ch.length; i++) {
            // k stores index of first character
            // and i is going to store index of last
            // character.
            int k = i;
            while (i < ch.length && ch[i] != ' ')
                i++;
            // Swapping
            char temp = ch[k];
            ch[k] = ch[i - 1];
            ch[i - 1] = temp;
            // We assume that there is only one space
            // between two words.
        }
        return new String(ch);
    }
    public static void main(String[] args)
    {
        String str = "kodnest for freshers";
        System.out.println(count(str));
    }
}

42. Wap to replace character in string.

public class StringReplace {
    public static void main(String args[]) {
     String word = "World";
     //replacing character in this String
     String replaced = word.replace("W", "K");
     System.out.println("Replacing character in String");
     System.out.println("Original String before replace : " + word);
     System.out.println("Replaced String : " + replaced);
     //replacing substring on String in Java
     String str = "PHP is good programming language";
     replaced = str.replaceAll("PHP", "Java");
     System.out.println("String before replace : " + str);
     System.out.println("String after replace : " + replaced);
     //replacing all space in String with # using regular expression
     replaced = str.replaceFirst("\s", "#");
     System.out.println("Replacing first match of regex using replaceFirst()");
     System.out.println("Original String before replacement : " + str);
     System.out.println("Final String : " + replaced);
     System.out.println("Replacing all occurrence of substring which match regex");
     replaced = str.replaceAll("\s", "#");
     System.out.println("ReplaceAll Example : " + replaced);
    }
}
Output:
Replacing character in String
Original String before replace : World
Replaced String : Korld
String before replace : PHP is good programming language
String after replace : Java is good programming language
Replacing first match of regex using replaceFirst()
Original String before replacement : PHP is good programming language
Final String : PHP#is good programming language
Replacing all occurrence of substring which match regex
ReplaceAll Example : PHP#is#good#programming#language

43. Wap to count number of words in string.

public class WordCount {
      static int wordcount(String 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++;
            }
            return count;
        }
      public static void main(String[] args) {
          String string ="Java is a best programming language";
         System.out.println(wordcount(string) + " words.");
    }
}
Output:
6 words.

44. Wap to swap two number without using third variable.

import java.util.Scanner;
class SwapTwoNumberWithoutThirdVariable
{
   public static void main(String args[])
   {
      int x, y;
      System.out.println("Enter the number for x and y ");
      Scanner in = new Scanner(System.in);
      x = in.nextInt();
      y = in.nextInt();
      System.out.println("Before Swappingnx = "+x+"ny = "+y);
      x = x + y
      y = x - y;
      x = x - y;
      System.out.println("After Swapping without third variablenx = "+x+"ny = "+y);
   }
}
Output:
Enter the number for x and y
25
49
Before Swapping
x = 25
y = 49
After Swapping without a third variable
x = 49
y = 25

45. Wap to implement Encapsulation in Java.

class Loan
{
private int duration; //private variables examples of encapsulation
private String loan;
private String borrower;
private String salary;
//public constructor can break encapsulation instead use factory method
private Loan(int duration, String loan, String borrower, String salary)
{
this.duration = duration;
this.loan = loan;
this.borrower = borrower;
this.salary = salary;
}
// create loan can encapsulate loan creation logic
public Loan createLoan(String loanType)
{
return loan;
}
}

46. Wap to achieve encapsulation.

To achieve encapsulation in Java:

• Declare the variables of a class as ‘private’.

• Provide public setter and getter methods to modify and view the variable’s values

public class EncapTest
{
private String name;
private String idNum;
private int age;
public int getAge()
{
return age;
}
public String getName()
{
return name;
}
public String getIdNum()
{
return idNum;
}
public void setAge( int newAge)
{
age = newAge;
}
public void setName(String newName)
{
name = newName;
}
public void setIdNum( String newId)
{
idNum = newId;
}
}

47. Wap to print half pyramid using $.

$
$ $
$ $ $
$ $ $ $
$ $ $ $ $

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        for(int i = 1; i <= rows; ++i) {
            for(int j = 1; j <= i; ++j) {
                System.out.print("$ ");
            }
            System.out.println();
        }
    }
}

48. Wap to print half triangle using numbers.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        for(int i = 1; i <= rows; ++i) {
            for(int j = 1; j <= i; ++j) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

49. Wap to print half triangle using alphabet.

A
B B
C C C
D D D D
E E E E E

public class Pattern {
    public static void main(String[] args) {
        char last = 'E', alphabet = 'A';
        for(int i = 1; i <= (last-'A'+1); ++i) {
            for(int j = 1; j <= i; ++j) {
                System.out.print(alphabet + " ");
            }
            ++alphabet;
            System.out.println();
        }
    }
}

50. Wap to print inverted half triangle using $

$ $ $ $ $
$ $ $ $
$ $ $
$ $
$

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        for(int i = rows; i >= 1; --i) {
            for(int j = 1; j <= i; ++j) {
                System.out.print("$ ");
            }
            System.out.println();
        }
    }
}

51. Wap to print inverted half triangle using numbers.

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        for(int i = rows; i >= 1; --i) {
            for(int j = 1; j <= i; ++j) {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

52. Wap to print full triangle using $.

$
$ $ $
$ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $ $ $ $ $

public class Pattern {
    public static void main(String[] args) {
        int rows = 5, k = 0;
        for(int i = 1; i <= rows; ++i, k = 0) {
            for(int space = 1; space <= rows - i; ++space) {
                System.out.print("  ");
            }
            while(k != 2 * i - 1) {
                System.out.print("$ ");
                ++k;
            }
            System.out.println();
        }
    }
}

53. Wap to print full pyramid using number

1
2 3 2
3 4 5 4 3
4 5 6 7 6 5 4
5 6 7 8 9 8 7 6 5

public class Pattern {
    public static void main(String[] args) {
        int rows = 5, k = 0, count = 0, count1 = 0;
        for(int i = 1; i <= rows; ++i) {
            for(int space = 1; space <= rows - i; ++space) {
                System.out.print("  ");
                ++count;
            }
            while(k != 2 * i - 1) {
                if (count <= rows - 1) {
                    System.out.print((i + k) + " ");
                    ++count;
                }
                else {
                    ++count1;
                    System.out.print((i + k - 2 * count1) + " ");
                }
                ++k;
            }
            count1 = count = k = 0;
            System.out.println();
        }
    }
}

54. Wap to print inverted full pyramid using $.

$ $ $ $ $ $ $ $ $
$ $ $ $ $ $ $
$ $ $ $ $
$ $ $
$

public class Pattern {
    public static void main(String[] args) {
        int rows = 5;
        for(int i = rows; i >= 1; --i) {
            for(int space = 1; space <= rows - i; ++space) {
                System.out.print("  ");
            }
            for(int j=i; j <= 2 * i - 1; ++j) {
                System.out.print("$ ");
            }
            for(int j = 0; j < i - 1; ++j) {
                System.out.print("$ ");
            }
            System.out.println();
        }
    }
}

55. Wap to print Pascal’s Triangle.

1
1 1
1 2 1
1 3 3 1

public class Pattern {
    public static void main(String[] args) {
        int rows = 4, cof = 1;
        for(int i = 0; i < rows; i++) {
            for(int space = 1; space < rows - i; ++space) {
                System.out.print("  ");
            }
            for(int j = 0; j <= i; j++) {
                if (j == 0 || i == 0)
                    cof = 1;
                else
                    cof = cof * (i - j + 1) / j;
                System.out.printf("%4d", cof);
            }
            System.out.println();
        }
    }
}

56. Wap to print Flyod triangle.

1
2 3
4 5 6

public class Pattern {
    public static void main(String[] args) {
        int rows = 3, number = 1;
        for(int i = 1; i <= rows; i++) {
            for(int j = 1; j <= i; j++) {
                System.out.print(number + " ");
                ++number;
            }
            System.out.println();
        }
    }
}

57. Wap to print the following pattern.

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows ");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}

58. Wap to print following pattern.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows  ");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
        for (int i = rows; i >= 1; i--)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

59. Wap to print the following pattern.

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1
1
1 2
1 2 3
1 2 3 4
1 2 3 4 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows ");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

60. Wap to print following pattern.

5 4 3 2 1
4 3 2 1
3 2 1
2 1
1
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows ");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = i; j >= 1; j--)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
        for (int i = 1; i <= rows; i++)
        {
            for (int j = i; j >= 1; j--)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

61. Wap to print following pattern.

5 4 3 2 1
5 4 3 2
5 4 3
5 4
5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows  ");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = rows; j >= i; j--)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

62. Wap to print following pattern.

5
5 4
5 4 3
5 4 3 2
5 4 3 2 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = rows; j >= i; j--)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

63. Wap to print following pattern.

1
2 1
3 2 1
4 3 2 1
5 4 3 2 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = i; j >= 1; j--)
            {
                System.out.print(j + " ");
            }
            System.out.println();
        }
    }
}

64. Wap to print following pattern.

1
2 7
3 8 13
4 9 14 19
5 10 15 20 25

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            int temp = i;
            for (int j = i; j >= 1; j--)
            {
                System.out.print(temp + " ");
                temp = temp + rows;
            }
            System.out.println();
        }
    }
}

65. Wap to print following pattern.

1
1 2 1
1 2 3 2 1
1 2 3 4 3 2 1
1 2 3 4 5 4 3 2 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j + " ");
            }
            for (int k = i - 1; k >= 1; k--)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

66. Wap to print following pattern.

1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= rows - i + 1; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

67. Wap to print following pattern.

1
1 2
1 2 3
1 2 3 4
1 2 3 4 5
1 2 3 4
1 2 3
1 2
1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = rows; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= rows - i; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

68. Wap to print following pattern.

12345
2345
345
45
5
5
45
345
2345
12345

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = i; k <= rows; k++)
            {
                System.out.print(k);
            }
            System.out.println();
        }
        for (int i = rows; i >= 1; i--)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = i; k <= rows; k++)
            {
                System.out.print(k);
            }
            System.out.println();
        }
    }
}

69. Wap to print following pattern.

1 2 3 4 5
2 3 4 5
3 4 5
4 5
5
5
4 5
3 4 5
2 3 4 5
1 2 3 4 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = i; k <= rows; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
        for (int i = rows; i >= 1; i--)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = i; k <= rows; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

70. Wap to print following pattern.

5
4 5
3 4 5
2 3 4 5
1 2 3 4 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print(" ");
            }
            for (int k = i; k <= rows; k++)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

71. Wap to print following pattern.

1
1 0
1 0 1
1 0 1 0
1 0 1 0 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j % 2 + " ");
            }
            System.out.println();
        }
    }
}

72. Wap to print following pattern.

1 0 0 0 0
0 2 0 0 0
0 0 3 0 0
0 0 0 4 0
0 0 0 0 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j < i; j++)
            {
                System.out.print("0 ");
            }
            System.out.print(i + " ");
            for (int k = i; k < rows; k++)
            {
                System.out.print("0 ");
            }
            System.out.println();
        }
    }
}

73. Wap to print following pattern.

1 1 1 1 1
1 1 1 2 2
1 1 3 3 3
1 4 4 4 4
5 5 5 5 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = rows; j > i; j--)
            {
                System.out.print(1 + " ");
            }
            for (int k = 1; k <= i; k++)
            {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}

74. Wap to print following pattern.

1 2 3 4 5 4 3 2 1
2 3 4 5 4 3 2
3 4 5 4 3
4 5 4
5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = i; j <= rows; j++)
            {
                System.out.print(j + " ");
            }
            for (int k = rows - 1; k >= i; k--)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

75. Wap to print following pattern.

1
2 2
3 3 3
4 4 4 4
5 5 5 5 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = rows; j > i; j--)
            {
                System.out.print(" ");
            }
            for (int k = 1; k <= i; k++)
            {
                System.out.print(i + " ");
            }
            System.out.println();
        }
    }
}

76. Wap to print following pattern.

5 5 5 5 5
4 5 5 5 5
3 4 5 5 5
2 3 4 5 5
1 2 3 4 5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = i; j < rows; j++)
            {
                System.out.print(j + " ");
            }
            for (int k = rows - i; k < rows; k++)
            {
                System.out.print(5 + " ");
            }
            System.out.println();
        }
    }
}

77. Wap to print following pattern.

1
2 6
3 7 10
4 8 11 13
5 9 12 14 15

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        int k = 1;
        for (int i = 1; i <= rows; i++)
        {
            k=i;
            for (int j = 1; j <= i; j++)
            {
                System.out.print(k + " ");
                k = k + rows - j;
            }
            System.out.println();
        }
    }
}

78. Wap to print following pattern.

1
2 4
3 6 9
4 8 12 16
5 10 15
6 12
7

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        int temp = 1;
        for(int i=1; i<=rows/2+1; i++)
        {
            for(int j=1;j<=i;j++)
            {
                System.out.print(temp*j+" ");
            }
            System.out.println();
            temp++;
        }
        for(int i=1; i<=rows/2; i++)
        {
            for(int j=1;j<=rows/2+1-i;j++)
            {
                System.out.print(temp*j+" ");
            }
            System.out.println();
            temp++;
        }
    }
}

79. Wap to print following pattern.

1
2 9
3 8 10
4 7 11 14
5 6 12 13 15

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j <= i; j++)
            {
                if (j % 2 == 0)
                {
                    System.out.print(1 + j * rows - (j - 1) * j / 2 + i - j + " ");
                } else
                {
                    System.out.print(1 + j * rows - (j - 1) * j / 2 + rows - 1 - i + " ");
                }
            }
         System.out.println();
        }
    }
}

80. Wap to print following pattern.

1 10 11 20 21
2 9 12 19 22
3 8 13 18 23
4 7 14 17 24
5 6 15 16 25

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 0; i < rows; i++)
        {
            for (int j = 0; j < rows; j++)
            {
                if (j % 2 == 0)
                    System.out.print((rows * (j)) + i + 1 + " ");
                else
                    System.out.print((rows * (j + 1)) - i + " ");
            }
            System.out.print("n");
        }
    }
}

81. Wap to print following pattern.

5 5 5 5 5
5 4 4 4 4
5 4 3 3 3
5 4 3 2 2
5 4 3 2 1

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        int temp = 0;
        for (int i = rows; i >= 1; i--)
        {
            for (int j = rows ; j >= i; j--)
            {
                System.out.print(j + " ");
                temp =j;
            }
            for (int k = rows - i+1; k < rows; k++)
            {
                System.out.print(temp + " ");
            }
            System.out.println();
        }
    }
}

82. Wap to print following pattern.

5
4 5 4
3 4 5 4 3
2 3 4 5 4 3 2
1 2 3 4 5 4 3 2 1
2 3 4 5 4 3 2
3 4 5 4 3
4 5 4
5

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = rows; i >= 1; i--)
        {
            for (int j = i; j <= rows; j++)
            {
                System.out.print(j + " ");
            }
            for (int k = rows-1; k >= i; k--)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
        for (int i = 2; i <= rows; i++)
        {
            for (int j = i; j <= rows; j++)
            {
                System.out.print(j + " ");
            }
            for (int k = rows-1; k >= i; k--)
            {
                System.out.print(k + " ");
            }
            System.out.println();
        }
    }
}

83. Wap to print following pattern.

1 2 3 4 5
2 3 4 5 1
3 4 5 1 2
4 5 1 2 3
5 1 2 3 4

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            int j = i;
            for (int k = 1; k <= rows; k++)
            {
                System.out.print(j + " ");
                j++;
                if (j > rows)
                    j = 1;
            }
            System.out.println();
        }
        sc.close();
    }
}

84. Wap to print following pattern.

1 3 5 7 9
3 5 7 9 1
5 7 9 1 3
7 9 1 3 5
9 1 3 5 7

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            int j = (i * 2) - 1;
            for (int k = 1; k <= rows; k++)
            {
                System.out.print(j + " ");
                j += 2;
                if (j > (rows * 2) - 1)
                    j = 1;
            }
            System.out.println();
        }
        sc.close();
    }
}

85. Wap to print following pattern.

1 1
12 21
123 321
1234 4321
1234554321

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i = 1; i <= rows; i++)
        {
            for (int j = 1; j <= i; j++)
            {
                System.out.print(j);
            }
            for (int j= i*2 ; j < rows*2; j++)
            {
                System.out.print(" ");
            }
            for (int l = i; l >= 1; l--)
            {
                System.out.print(l);
            }
            System.out.println();
        }
        sc.close();
    }
}

86. Wap to print following pattern.

1
2 3
6 5 4
7 8 9 10
15 14 13 12 11

import java.util.Scanner;
public class Pattern
{
    public static void main(String[] args)
    {
        int curRow = 1;
        int counter = 1;
        // Create a new Scanner object
        Scanner sc = new Scanner(System.in);
        // Get the number of rows from the user
        System.out.println("Enter the number of rows");
        int rows = sc.nextInt();
        for (int i=1; i<= rows; i++)
        {
            if (i % 2 == 0)
            {
                for (int j = 1; j<=i; j++)
                {
                    System.out.print(counter  +" ");
                    counter++;
                }
            }
            else
            {
                int reverse = curRow + counter - 1;
                for (int j = 0; j<i; j++)
                {
                    System.out.print(reverse--  +" ");
                    counter++;
                }
            }
            System.out.println();
            curRow++;
        }
    }
}
KodNest Learn java kodnest Free

Java

10% Complete Last activity on Sep 21, 2019 See More learn-html-kodnest Free

HTML (Hyper Text Markup Langage)

63% Complete Last activity on Sep 07, 2019 See More learn-css-kodnest Free

CSS (Cascading Style Sheet)

11% Complete Last activity on Sep 12, 2019 See More learn-javascript-kodnest Free

JavaScript

13% Complete Last activity on Sep 14, 2019 See More learn-algorithm-kodnest Free

Algorithm

18% Complete Last activity on Sep 09, 2019 See More KodNest KODNEST8 Free

DataStructure

50% Complete Last activity on Sep 17, 2019 See More

Related Articles

Core Java

1. What are primitive types in Java ? byte, short, int, long, float, double, char, boolean… 2. What are tokens? Name the 5 types of tokens available in Java with an example…

C Programming

1. Wap to check if the given number is armstrong number or not. #include<stdio.h> #include<conio.h> void main(){ int a,t,l,sum=0; printf(“\nPlease enter your number\n”); scanf(“%d”,&a); t=a;…

Hackerearth-Java

     1. Challenge : Welcome to Java! Welcome to the world of Java! In this challenge, we practice printing to stdout. The code stubs…

Responses

Your email address will not be published. Required fields are marked *

KodNest Training New Batch is starting on 5th October 2020. Attend one week free demo classes.Register Now

New Report

Close