Showing posts with label Java Interview Programs. Show all posts
Showing posts with label Java Interview Programs. Show all posts

Wednesday, 14 September 2016

Java Program to find Unique elements From Array?

public class DistinctElementsFromArray {

public static void getElements(int[] arr){
System.out.println("UNIQUE ELEMENTS FROM ARRAY : ");
for(int i=0;i<arr.length;i++){
boolean unique = false;
for(int j=0;j<i;j++){
if(arr[i] == arr[j]){
unique = true;
}
}
if(!unique){
System.out.print(arr[i]+",");
}
}
}
public static void main(String[] args) {
int[] arr = {5,2,5,3,2,8,7};
DistinctElementsFromArray.getElements(arr);
}

}

Program Output :-

UNIQUE ELEMENTS FROM ARRAY : 
5,2,3,8,7,




Tuesday, 13 September 2016

Java program to Convert Binary To Decimal?

The decimal number is equal to the sum of powers of 2 of the binary number's '1' digits place . Here we add only those powers whose binary is one. For Example :-
Binary Number
1
1
1
0
0
0
0
Power of 2
26
25
24
23
22
21
20
Value
64
32
16
8
4
2
 1

                       64  +   32   +   16   +    0   +   0   +   0   +   0   = 112


public class BinaryToDecimal {

public static void getDecimal(int num){
int binary = num;
int i = 0;
int decimal = 0;
while(num > 0){
int temp = num % 10;
decimal+=Math.pow(2, i++)*temp; 
num = num / 10;
}
System.out.println("DECIMAL OF "+binary+" : "+decimal);
}
public static void main(String[] args) {
BinaryToDecimal.getDecimal(11);
BinaryToDecimal.getDecimal(1110000);
}

}

Program Output :-

DECIMAL OF 11 : 3
DECIMAL OF 1110000 : 112


Java Program to Convert Decimal to Binary?

Below example shows how to convert Decimal number into binary ,as we Know that for converting decimal to binary we divide the number by 2 untill the quotient become zero or one ,and then we reverse the remainder .

public class DecimalToBinary {

public static void getBinary(int num){
int local = num;
int[] arr = new int[num];
int place=0;

while(num > 0){
int temp = num % 2;
arr[place++] = temp;
num = num / 2;
}
System.out.print("BINARY OF "+local+" : ");
for(int j = place-1 ;j >= 0 ;j--){
System.out.print(arr[j]);
}

}
public static void main(String[] args) {
DecimalToBinary.getBinary(112);
}

}

Program Output :-

BINARY OF 112 : 1110000



Java Program for Bubble Sort?

Bubble sort algorithm is the simplest sorting algorithm. In bubble sort algorithm, array is traversed from first element to last element.  Here, first element is compared with the next element. If first element is greater than the next element,then it is swapped.

import java.util.Arrays;

public class BubbleSort {

public static void method_1(int[] arr){
System.out.println("ELEMENTS BEFORE SORTING : ");
for (int i : arr) {
System.out.print(i+",");
}

for(int i=0 ; i < arr.length ; i++){
for(int j=0 ; j < arr.length-1 ;j++){
if(arr[j] > arr[j+1]){
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}

System.out.println("\n\nELEMENTS AFTER SORTING : ");
for (int i : arr) {
System.out.print(i+",");
}
}
public static void method_2(int[] arr){
System.out.println("\n\nSORTING USING PREDEFINED METHOD : ");
Arrays.sort(arr);
for(int i : arr){
System.out.print(i+",");
}
}
public static void main(String[] args) {
int[] arr = {5,6,3,1,2};
BubbleSort.method_1(arr);
BubbleSort.method_2(arr);
}

}

Program Output :-

ELEMENTS BEFORE SORTING : 
5,6,3,1,2,

ELEMENTS AFTER SORTING : 
1,2,3,5,6,

SORTING USING PREDEFINED METHOD : 

1,2,3,5,6,


Friday, 9 September 2016

Java Program to find Prime Numbers From 1 to N?

Below Example shows how to find all Prime Numbers from 1 to N.

public class PrimeNumbersFromOneToN {

public void allPrimeNumbers(int num){
System.out.println("Prime Numbers From 1 to "+num);
for(int i=1;i<num;i++){
boolean isPrime = true;
for(int j=2;j<i;j++){
if(i % j == 0){
isPrime = false;
break;
}
}
if(isPrime){
System.out.print(i+",");
}

}
}
public static void main(String[] args) {
PrimeNumbersFromOneToN p = new PrimeNumbersFromOneToN();
p.allPrimeNumbers(100);
}

}

Program Output :-

Prime Numbers From 1 to 100
1,2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,



Java Program to check Number is Prime or Not?

A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself. A natural number greater than 1 that is not a prime number is called a composite number.


public class NumberIsPrimeOrNot {

public static boolean isPrime(int num){
for(int i=2;i<=num/2;i++){
if(num % i == 0){
return false;
}
}
return true;
}
public static void main(String[] args) {
System.out.println("IS 17 PRIME NUMBER : "+NumberIsPrimeOrNot.isPrime(17));
System.out.println("IS 5 PRIME NUMBER : "+NumberIsPrimeOrNot.isPrime(5));
}

}

Program Output :-

IS 17 PRIME NUMBER : true
IS 5 PRIME NUMBER : true



Thursday, 8 September 2016

Java Program to Sum each Digit of Given Number?

Below Example shows how to Sum each Digit of Number. The Logic behind the sum of each digits is that divide the number by 10 and add Reminder to separate variable, Repeat this process until number become 0.


public class SumEachDigitOfNumber {
public static int getSum(int num){
int sum = 0;
if(num == 0){
return num;
}
else{
while(num > 0){
int temp = num%10;
sum+=temp;
num = num/10;
}
}
return sum;
}
public static void main(String[] args) {
System.out.println("SUM OF DIGITS : "+SumEachDigitOfNumber.getSum(222));
}


}

Program Output :-

SUM OF DIGITS : 6







Java Program to Swap Two Variables Without Using Third Variable?

Below Example shows how to swap two variables without using third variable. The Simple logic behind swapping is to add and subtract both values in given variables.

public class SwapTwoNumbersWithoutThirdVariable {

public static void main(String[] args) {
int a = 12;
int b = 6;

System.out.println("BEFORE SWAP : A = "+a+" ,B = "+b);
a = a+b;
b = a-b;
a = a-b;
System.out.println("AFTER  SWAP : A = "+a+" ,B = "+b);
}

}

Program Output :-

BEFORE SWAP : A = 12 ,B = 6

AFTER  SWAP : A = 6 ,B = 12



Tuesday, 6 September 2016

Java Program to find Common Elements from two Arrays ?

Below Example shows how to find common elements from two input arrays.

public class CommonElementsFromTwoArray {

public static void main(String[] args) {
int[] input1 = {4,5,9,8,2,6,3};
int[] input2 = {4,2,6,0,1};

System.out.println("Common Elements In Both Arrays :-");
for(int i=0; i<input1.length; i++){
for(int j=0; j<input2.length; j++){
if(input1[i] == input2[j]){
System.out.println(input1[i]);
}
}
}
}
}

Program Output :-

Common Elements In Both Arrays :-
4
2
6



Java Program to check Number is Perfect or Not ?

A perfect number is a positive integer that is equal to the sum of its positive divisors, that is, the sum of its positive divisors excluding the number itself.
For Example The first perfect number is 6, because 1, 2, and 3 are its positive divisors, and sum of  1 + 2 + 3 = 6. Other Perfect Numbers are 28 ,496 and so on.


public class PerfectNumber {

public static boolean isNumPerfect(int num){
boolean status = false;
int temp = 0;
for(int i=1;i<=num/2;i++){
if(num%i == 0){
temp+= i;
}
}
if(temp == num){
status = true;
} else{
status = false;
}
return status;
}
public static void main(String[] args) {
System.out.println("Is 6 Perfect Number : "+PerfectNumber.isNumPerfect(6));
System.out.println("Is 28 Perfect Number : "+PerfectNumber.isNumPerfect(28));
System.out.println("Is 30 Perfect Number : "+PerfectNumber.isNumPerfect(30));
}
}

Program Output :-

Is 6 Perfect Number : true
Is 28 Perfect Number : true

Is 30 Perfect Number : false



Saturday, 3 September 2016

Java Program to find First And Second Maximum Number From int type Array ?

Below example show how to find first and second largest Number From int type Array.

public class TwoMaximumNumberFromList {

public static void method(int[] num){
int firstMax = 0;
int secondMax = 0;
for(int n : num){
if(n > firstMax){
secondMax = firstMax;
firstMax = n;
}
else if(secondMax < n){
secondMax = n;
}
}
System.out.println("FIRST MAXIMUM NUMBER : "+firstMax);
System.out.println("SECOND MAXIMUM NUMBER : "+secondMax);
}
public static void main(String[] args) {
int[] num={5,6,9,3};
TwoMaximumNumberFromList.method(num);
}

}

Program Output :-
FIRST MAXIMUM NUMBER : 9

SECOND MAXIMUM NUMBER : 6




Java Program to find Duplicate Character In String ?

Below example show how to count repeated characters from String.

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

public class DuplicateCharacterFromString {

public static void method(String str){
Map<Character, Integer> map = new HashMap<>();
for(int i=0;i<str.length();i++){
if(map.containsKey(str.charAt(i))){
map.put(str.charAt(i), map.get(str.charAt(i))+1);
}
else{
map.put(str.charAt(i), 1);
}
}
Set<Character> set = map.keySet();
for(Character c : set){
if(map.get(c) > 1){
System.out.println(c+":"+map.get(c));
}
}
}
public static void main(String[] args) {
DuplicateCharacterFromString.method("abca");
}


}
Program Output :-

a:2




Java Programs to Reverse a Numbers ?

Below example shows how to reverse a number using numeric operations. 

public class ReverseNumbers {

public static void reverse(int num){
int reverse = 0;
while(num != 0){
reverse = (reverse*10)+(num%10);
num = num/10;
}
System.out.println("REVERSE : "+reverse);
}
public static void main(String[] args) {
ReverseNumbers.reverse(123);
ReverseNumbers.reverse(1425);
}

}
Program Output :-
REVERSE : 321
REVERSE : 5241


Friday, 2 September 2016

Different Ways to Print Exception Message in Java.

There are 3 Ways to print Exception Message :-
1 > Using Object of java.lang.Exception. This Only Prints the Exception Name.

2 > Using printStackTrace() Method. This is the method which is defined in java.lang.Throwable class and it is inherited from java.lang.Error class and java.lang.Exception class.This method display the name of the Exception and Line where the Exception has Occurred in the Program.

3 > Using getMessage() Method. This method only display the Exception Message.

public class WaysToPrintExceptionMsg {

public static void method_1(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
System.out.println(e);

}
}
public static void method_2(){
String s1=null;
try {
s1.length();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void method_3(){
try {
int x=1/0;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public static void main(String[] args) {
System.out.println("METHOD 1 OUTPUT :- ");
WaysToPrintExceptionMsg.method_1();
System.out.println("\n\nMETHOD 2 OUTPUT :- ");
WaysToPrintExceptionMsg.method_2();
System.out.println("\n\nMETHOD 3 OUTPUT :- ");
WaysToPrintExceptionMsg.method_3();
}

}
Program Output :-
METHOD 1 OUTPUT :- 
java.lang.NullPointerException


METHOD 2 OUTPUT :- 
java.lang.NullPointerException
at exceptions.programs.WaysToPrintExceptionMsg.method_2(WaysToPrintExceptionMsg.java:23)
at exceptions.programs.WaysToPrintExceptionMsg.main(WaysToPrintExceptionMsg.java:39)


METHOD 3 OUTPUT :- 
/ by zero




Saturday, 27 August 2016

Java Program Showing Serializable Interface Example ?

Serialization in java is a mechanism of writing the state of an object into a byte stream. 
Serializable is a marker interface (has no body). It is just used to "mark" java classes which support a certain capability. 
It must be implemented by the class whose object you want to persist. 
The reverse operation of serialization is called deserialization. 
The String class and all the wrapper classes implements java.io.Serializable interface by default.

Let's see the example given below :-

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class Employee implements Serializable{
private static final long serialVersionUID = -7343212483392987741L;
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
public class SerialiazableExample {
static void storeObject(Employee emp,String filePath) throws IOException { //Java Serialization Method
FileOutputStream os = new FileOutputStream(filePath);
ObjectOutputStream ob = new ObjectOutputStream(os);
ob.writeObject(emp);
ob.flush();
ob.close();
System.out.println("Object Written In File Successfully.."+filePath);
}
static void displayObject(String filePath) throws IOException, ClassNotFoundException{ // Java Deserialization Method
System.out.println("READING DATA FROM FILE:::");
FileInputStream is = new FileInputStream(filePath);
ObjectInputStream ob = new ObjectInputStream(is);
Employee emp = (Employee)ob.readObject();
System.out.println("NAME\tID");
System.out.println("----\t--");
System.out.println(emp.getId()+"\t"+emp.getName());
ob.close();
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
String filePath = "D:/serializable_file.txt";
Employee e = new Employee();
e.setName("Pushkar Khosla");
e.setId(101);
storeObject(e,filePath);
displayObject(filePath);
}
}
Programs Output:-
Object Written In File Successfully..D:/serializable_file.txt
READING DATA FROM FILE:::
NAME ID
---- --
101 Pushkar Khosla