Skip to main content

Posts

Showing posts from December, 2017

Even Or Odd Number!!

Such programs are too simple and requires the fundamental logic for checking whether a number is odd or ever. Any number which is divisible by 2 is even else odd. In the below code snippet, you will find two operators % and /.  x=4 y=2 x%y will computes to 0 which is the remainder!! x/y will compute to 2 which is the quotient. # Below is the code: class EvenOrOdd { public String compute(int x) { if (x % 2 == 0) { return x + " is even"; } else return x + " is odd"; } } public class TestEvenOrOdd { public static void main(String[] args) { EvenOrOdd ref = new EvenOrOdd(); System.out.println(ref.compute(5)); System.out.println(ref.compute(10)); } } #Output:

Reversing of a string[Customized Logic]

# String in java is a class!! String objects are immutable which means once created cannot be destroyed. There are various way of instantiating or creating objects of string. 1. String s1="ABC"; 2. String s2=new String("ABC"); 3. char [] abc={'A','B','C'};     String s3=new String(abc); So the problem statement is to reverse a string. Input="ABCFAD" Outpt=DAFCBA. Below is the code snippet to achieve the above problem statement. class StringReversing { public void computeStringReversal(String string){ // convert the string into character of array char [] characterArray=string.toCharArray(); int lowerIndex=0; int higherIndex=string.length()-1; char temp; while(higherIndex>lowerIndex) { temp=characterArray[lowerIndex]; characterArray[lowerIndex]=characterArray[higherIndex]; characterArray[higherIndex]=temp; higherIndex--; lowerIndex++; } System.out.prin...

Sorting an Array[Customized Logic ]

Sorting of array can be done through various logic's!! Either through using Arrays.sort() method or through customize logic. Here we are going to discuss the customized logic.  Below is the logic snippet for sorting the elements of an integer array Logic for custom sort: for(int i=0;i<size-1;i++) { for(int j=0;j<size-1;j++) { if(arr[j]>arr[j+1]) { temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } use of sort method: Arrays.sort(arr); Complete Code: class SortingArray { public void customSort(int [] arr) { int size=arr.length; int temp=0; // outer loop for(int i=0;i<size-1;i++) { // inner loop for(int j=0;j<size-1;j++) { if(arr[j]>arr[j+1]) { /* * Swapping logic */ temp=arr[j]; arr[j]=arr[j+1]; arr[j+1]=temp; } } } // displaying the elements of the array for...