Let's learn java programming language with easy steps

Thursday, 21 September 2017

How to Convert Decimal to Binary in Java


Decimal to Binary Conversion in Java

Java Decimal to Binary Conversion

Here we will learn, How to convert decimal to binary in java with easy examples. Java decimal to binary conversion is the most important core java interview question.

There are many number conversion interview questions which is asked in java interviews like java program to convert decimal to hexadecimal, java program to convert decimal to octal, java program to convert binary to decimal, etc. But here we learn only decimal to binary conversion program in java. Let's start...

First, Let us understand what is decimal and binary number.

Decimal Numbers - Decimal number is the real number using the base 10. There are only 10 digits which represents numbers and starting from 0 to 9.

Binary Numbers - Binary number is number which contains only two digits 0 and 1 which know as bits.

Binary numbers in computer language i. e 0 and 1 represents true/false or on/off.

There are 3 ways, we can convert decimal to binary in java programs.

  • First is, Using toBinaryString() method of Integer class.
  • Second is, Using you own logic without any predefined method.
  • Third is, Using Stack. 

1) Decimal to Binary Example Using toBinaryString() method

class DecimalBinary
{
public static void main(String args[])
{
System.out.println("Binary representation of 1: ");
System.out.println(Integer.toBinaryString(1));
System.out.println("Binary representation of 6: ");
System.out.println(Integer.toBinaryString(6));
System.out.println("Binary representation of 12: ");
System.out.println(Integer.toBinaryString(12));
System.out.println("Binary representation of 45: ");
System.out.println(Integer.toBinaryString(45));
}
}

Output: Binary representation of 1:
              1
             Binary representation of 6:
             110
             Binary representation of 12:
             1100
             Binary representation of 45:
             101101


2) Decimal to Binary Example and count the number of 1s in binary numbers

In this program, we will take the input from user and convert it decimal to binary number and count 1s.

import java.util.Scanner;
class Counts
{
public static void main(String args[])
{
int n, a, count = 0;
String s = "";
Scanner sc = new Scanner(System.in);
System.out.println("Enter decimal number ");
n = sc.nextInt();
while(n>0)
{
a = n%2;
if(a == 1)
{
count++;
}
s = s+" "+a;
n = n/2;
}
System.out.println("Binary number: "+s);
System.out.println("No. of 1s: "+count);
}
}

Output: Enter decimal number
             45
             Binary number: 101101
             No of 1s: 4


3) Write a java program to convert decimal to binary without using predefined method

class Test
{
public void binaryConvert(int num)
{
int bin[] = new int[45];
int index = 0;
while(num > 0)
{
bin[index++] = num%2;
num = num/2;
}
for(int i = index-1; i >= 0; i--)
{
System.out.print(bin[i]);
}
}
public static void main(String args[])
{
Test t = new Test();
System.out.println("Binary representation of 123: ");
t.binaryConvert(123);
}
}

Output: Binary representation of 123:
             1111011


4) Another Example of java decimal to binary conversion

In this program, we create stack object and take input from the user for converting decimal to binary.

import java.util.*;
class Demo
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
//creating Stack object
Stack<Integer> stack = new Stack<Integer>();
System.out.println("Enter the decimal number: ");
int num = sc.nextInt();
while(num != 0)
{
int b = num % 2;
stack.push(b);
num /= 2;
}
System.out.print("\n Binary is: ");
while(!(stack.isEmpty()))
{
System.out.print(stack.pop());
}
System.out.println();
}
}

Output: Enter the decimal number: 
             65
             Binary is: 1000001


Above all the examples of decimal to binary conversion programs in java are mostly asked in java interviews.

Share:

Wednesday, 20 September 2017

Interview Questions and Answers on Inheritance in Java


Java Inheritance Interview Questions

Java Inheritance Interview Questions and Answers

Now, Here we are going see some most important interview questions and answers on inheritance in java. This is the most important topic from the core java interview point of view.

There are many oops concepts interview questions are asked in core java interviews and Java inheritance concept is one of them.


(1) What is inheritance in java?

Inheritance is the oops concept and in java inheritance means re-usability. By using this inheritance concept a child class can inherit its parent class so that the child class can reuse all the field and methods of its parent class.


(2) What are the types of inheritance?

There are 5 types of inheritance. Suppose there is a class A, B, C, and D.

1) Single level inheritance.

B extends A

2) Multilevel inheritance.

C extends B and B extends A

3) Multiple inheritance.

C extends B and A

4) Hierarchical inheritance.

C  and B extends A  

5) Hybrid inheritance.

D extends C and B and C and B extends A


(3) Use of inheritance in java?

There are many reasons for using inheritance in java and these are given below.
  1. To achieve dynamic binding or method overriding.
  2. For code re-usability.
  3. To save time.

(4) Does java support multiple inheritance?

No, Java doesn't support multiple inheritance because of complexity and ambiguity in a program. Java does not support multiple inheritance through the class but it is possible through the interface.

(5) What is the syntax of inheritance?

There is the syntax of inheritance.

//Single levele inheritance
class A
{
//data member;
//member function
}
class B extends A
{
//data member;
//member function
}
}


(6) What is IS-A relationship in inheritance?

Java inheritance represents is-a relationship and parent-child relationship is also know as is-a relationship.


(7) What is aggregation in java?

If a class have an entity reference, it is known as aggregation and aggregation represents Has-a relationship.

For example 

class Student
{
String name;
Address  address;//Adderess is a class
}

Here Address is a class which may contain other information like city, country, etc.


(8) By default, all the classes extend which class in java?

In java, All the classes extend Object class by default because Object class is the super class in java.


(9) How inheritance can be implemented in java?

By two ways we can implement inheritance.

  • Using extends keyword.
  • Using implements keyword.

(10) How do you implement multiple inheritance in java?

We can implement multiple inheritance in java by using interface concept. A class can implement multiple interface at the same time but a class can't extend more than one class at a time.

For example:

interface My
{
//method
}
interface My1
{
//method
}
class Test implements My,My1
{}


(11) Can a class extend itself?

No, A class can't extend itself.


(12) Are interfaces extend Object class by default?

As we know that all the classes extend Object class by default but the interface does not extend Object class by default.


(13) Can you inherit a final class in java?

No, We can't extend the final class.


(14) Can you inherit final method of super class into a sub-class?

Yes, we can inherit final method of a super class into a sub-class.


(13) Can you inherit private members of super class into a sub-class?

No, we cannot inherit private member of a super class into a sub-class.


(14) Can we inherit constructor in sub-class?

No, we cannot inherit constructor in sub-class.


(15) What happens if super class and sub class having same field name?

Super class field will be hidden in the sub class but you can access hidden field of a super class by using 'super' keyword in the sub-class.


(16) Can you inherit static member into a sub-class.

Yes, we can.


Above all the java inheritance questions and answers are quite useful for java interviews.




Share:

Monday, 18 September 2017

Java Array Programming Interview Questions and Answers


Array Programming Interview Questions in Java

Array Coding Interview Questions in Java

This is the most important article for core java interview. Here we are going to discuss some java array programming interview questions and answers one-by-one in detail.

In the last post, you have learned String programming interview questions but here we will see array coding interview questions in java.

Let's start programming questions on array.


(1) What is the output of following program?

class Demo1
{
public static void main(String args[])
{
int i[] = new int[0];
System.out.println(i[0]);
}
}

Output: java.lang.ArrayIndexOutOfBoundsException...run-time error


(2) Can we pass the negative number in array size declaration?

class Demo2
{
public static void main(String args[])
{
int i[] = new int[-3];
------
------
}
}

Output: java.lang.NegativeArraySizeException...run-time exception


(3) Write a java program to find intersection between two arrays?

In this example,we will find the common elements between 2 arrays.

class Demo3
{
public static void main(String args[])
{
String s1[] = {"red", "pink", "orange", "black"};
String s2[] = {"pink", "brown", "red", "white"};
//using HashSet class
HashSet<String> hs = new HashSet<String>();
for(int i = 0; i<s1.length; i++)
{
for(int j = 0; j<s2.length; j++)
{
if(s1[i].equals(s2[j]))
{
hs.add(s1[i]);
}
}
}
System.out.println(hs);
}
}

Output: [red, pink]


(4) Write a java program to sort an array elements?

By the help of Arrays.sort() method we can easily sort the array elements in ascending order and this sort() method internally uses quick sort algorithm to sort the elements of an array.

class Demo4
{
public static void main(String args[])
{
int[] i = {4, 1, 99, 3, 7};
Arrays.sort(i);
System.out.println(Arrays.toString(i));
}
}

Output: [1, 3, 4, 7, 99]


(5) Write a java program to reverse an array?

This is the simple java programs on array where we reverse the elements of an array in java.

class Demo5
{
public static void main(String args[])
{
int n[] = {1,2,3,4,5,6,7,8,9,10};
System.out.println("Array elements before reverse");

for(int i = 0; i<n.length; i++)
{
System.out.print(n[i]+" ");
}
for(int i = 0; i<n.length/2; i++)
{
int temp = n[i];
n[i] = n[n.length-1-i];
n[n.length-1-i] = temp;
}
System.out.println("\n Array elements after reverse");
for(int i = 0; i<n.length; i++)
{
System.out.print(n[i]+" ");
}
}
}

Output: Array elements before reverse
             1 2 3 4 5 6 7 8 9 10
             Array elements after reverse
             10 9 8 7 6 5 4 3 2 1


(6) Write a java program to find duplicate elements in array?

class Demo6
{
public static void main(String args[])
{
String[] s = {"apple", "orange", "apple", "banana"};
HashSet<String> hs = new HashSet<String>();
for(String duplicate : s)
{
if(!hs.add(duplicate))
{
System.out.println(duplicate);
}
}
}
}

Output: apple


(7) Write a java program to find minimum and maximum value in an array?

class Demo7
{
public static void main(String args[])
{
int []a = {1,5,8,9,50,100,200};
//assign first element of an array to largest and smallest
int smallest = a[0];
int largest = a[0];
for(int i = 1; i<a.length; i++)
{
if(a[i]>largest)
largest = a[i];
else if(a[i]<smallest)
smallest = a[i];
}
System.out.println("Largest number is "+ largest);
System.out.println("Smallest number is "+ smallest);
}
}

Output: Largest number is 200
             Smallest number is 1


(8) How to compare two arrays in java?

If two array are of the same size and data types then we can use Arrays.equals() method for comparison.

import java.util.*;
class Demo8
{
public static void main(String args[])
{
int a[] = {1, 2, 3, 4};
int b[] = {9, 8, 7, 6};
int c[] = {1, 2, 3, 4};
System.out.println(Arrays.equals(a, b));
System.out.println(Arrays.equals(b, c));
}
}

Output: false
              true

Above all the programming questions on array in java are quite useful for any core java programming interview questions.



Share:

Sunday, 17 September 2017

Difference Between class and interface in java


Class vs Interface in Java

class vs interface in java

In the last post we have already discussed what is the difference between abstract class and interface in java but here we will learn what is the difference between class and interface in java in detail.

Let's start what is the differences between class and interface in java with examples.


Java Class

  • In java 'class' keyword is used to create a class.
  • We can create object or instance of class easily in java.
  • We cannot achieve multiple inheritance through class.
  • The data members of a class are not public, static, and final by default.
  • The methods of class are not public and abstract by default.
  • We can declare default and parameterized constructor in a class.
  • A class can implement interface.
  • In a class method can be final and static.
  • Here 'extends' keyword is used for inheritance in class.
  • In a class, we can use public, private and protected access specifiers with method.
  • We can declare main() method in class.
  • There only concrete methods are allowed i.e with method{} body.
  • A class can extend only one class but implement any number of interfaces.

Simple Java Class Example

class Students
{
String name;
int rollno;
Students(String name, int rollno)
{
this.name = name;
this.rollno = rollno;
System.out.println(name+" "+rollno);
}
static void run()
{
System.out.println("Students participates in race program");
}
public static void main(String... s)
{
Students ss = new Students("sachin", 12);
Students.run();
}
}

Output: sachin 12
             Students participates in race program


Java Interface

  • In java 'interface' keyword is used to create interface in java.
  • We can't create object of an interface.
  • We can achieve multiple inheritance through interface in java.
  • The data members of an interface are public, static, and final by default.
  • The methods of an interface are public and abstract by default.
  • We cannot declare any kind of java constructor in an interface.
  • A class can implement an interface but an interface cannot extend a class or implement a class.
  • In an interface, methods cannot be static or final.
  • Here 'implements' keyword is used for inheritance in an interface.
  • In an interface, there only public specifier is allowed.
  • We can't declare main() method in an interface.
  • There only abstract method(without body) is allowed in an interface but now in java 8 version we can keep non-abstract method(with body).
  • An interface can extend multiple interfaces but cannot implement any interface.



Simple Example of Java Interface

This is the simple interface program in java with output.

interface My
{
void show();
}
interface My2
{
void display();
}
class Test implements My,My2
{
public void show()
{
System.out.println("Interface My");

}
public void display()
{
System.out.println("Interface My2");
}
public static void main(String args[])
{
Test t =
new Test();

t.show();
t.display();
}
}

Output: Interface My
             Interface My2


Use of Interface in Java

  • So that we can achieve fully abstraction in java.
  • So that we can achieve multiple inheritance in java.

In this article, you have learned what is the difference between class and interface in java.

I hope, this interface vs class article will be useful to you.



Share:

Wednesday, 13 September 2017

String Programming Interview Questions in Java


String Programming Interview Questions

Java String Programming Interview Questions and Answers

Here we are gonna to discuss some string programming interview questions in java. String handling is the most important topic in core java.

In this article you will see most frequently asked java string programming interview questions and answers.

Let's start java string programs asked in interview one-by-one.

(1) What is the output of following program?

class Test1
{
public static void main(String args[])
{
String a = "javatutorial95"+100+200;
System.out.println(a);
}
}

Output: javatutorial95100200


(2) What is the output of following program?

class Test2
{
public static void main(String args[])
{
String a = 10+20+"javatutorial95"+20+30;
System.out.println(a);
}
}

Output: 30javatutorial952030


(3) Write a program to reverse a String in java without using String API?

class Test3
{
public static void main(String args[])
{
String s = "Best Country";
String reverse = "";
for(int i = s.length()-1; i>=0; --i)
{
reverse +=s.charAt(i);
}
System.out.println(reverse);
}
}

Output: yrtnuoC tseB


(4) Write a java program to check String is palindrome or not?

class Test4
{
public static void main(String args[])
{
String name = "MADAM";//String to be checked for palindrom
String reverse = "";
for(int i = name.length()-1; i>=0; --i)
{
reverse += name.charAt(i);
}
System.out.println(reverse);

if(reverse.equalsIgnoreCase(name))
{
System.out.println("String is palindrome");
}
else
{
System.out.println("String is not palindrome");
}
}
}

Output: MADAM
             String is plindrome


(5) Write a java program to find the duplicate words and their number of occurrences in a string?

import java.util.*;
class Test5
{
static void duplicateWords(String string1)
{
//splitting string1 into words
String[] words = string1.split(" ");

//creating HashMap with word as key and count as value
HashMap<String, Integer> wordcount = new HashMap<String, Integer>();

//checking each words
for(String word : words)
{
if(wordcount.containsKey(word.toLowerCase()))
{
wordcount.put(word.toLowerCase(), wordcount.get(word.toLowerCase())+1);
}
else
{
wordcount.put(word.toLowerCase(), 1);
}
}
Set<String> wordsstring = wordcount.keySet();
for(String word : wordsstring)
{
if(wordcount.get(word)>1)
{
System.out.println(word+"  :  "+wordcount.get(word));
}
}
}

public static void main(String args[])
{
duplicateWords(dog is Dog not cat);
duplicateWords(cat is Dog not cat and cat);
}
}

Output: dog : 2
              cat : 3


(6) Write a java program to count the number of words in a string?

import java.util.*;
class Test6
{
public static void main(String args[])
{
System.out.println("Enter your string");
//using Scanner class
Scanner s = new Scanner(System.in);
String s1 = s.nextLine();
String[] words = s1.trim().split(" ");
System.out.println("Number of word in a string "+words.length);
}
}


(7) Write a java program to count the number of occurrences of each characters in string?

Occurrence of characters in string e.g "javatutorial" j = 1, a = 3, v = 1..

import java.util.*;
class Test7
{
static void characterCount(String string1)
{
HashMap<Character, Integer> hm = new HashMap<Character, Integer>();
//converting given string to char array
char[] ch = string1.toCharArray();
//checking eahc char of ch
for(char c : ch)
{
if(hm.containsKey(c))
{
hm.put(c, hm.get(c)+1);
}
else
{
hm.put(c, 1);
}
}
System.out.println(hm);
}
public static void main(String args[])
{
characterCount("India is a good country");
}
}


(8) How to check total number of vowels in a java string?

There are 5 vowels in a to z alphabet e.g 'a', 'e', 'i', 'o', 'u'.

import java.util.*;
class Test8
{
public static void main(String args[])
{
System.out.println("Enter some string");
Scanner sc = new Scanner(System.in);
String str = sc.nextLine();
char chars[] = str.toCharArray();
int count = 0;
for(char c : chars)
{
switch(c)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
count++;
break;
}
}
System.out.println("Number of vowels in string "+count);
}
}

Output: Enter some string
              i love you
              Number of vowels in string 5


(9) How to sort the string without using string API in java?

class Test9
{
public static void main(String args[])
{
String original = "zfabcd";
int j = 0;
char temp = 0;
char chars[] = original.toCharArray();
for(int i = 0; i<chars.length; i++)
{
for(j = 0; j<chars.length; j++)
{
if (chars[j]>chars[i])
{
temp = chars[i];
chars[i]=chars[j];
chars[j]=temp;
}
}
}
for(int k = 0; k<chars.length; k++)
{
System.out.println(chars[k]);
}
}
}

Output: a
             b
             c
             d
             f
             z

Above all the java string programs examples are quite useful in any core java interview. 



Share:

Facebook Page Likes

Follow javatutorial95 on Google+

Follow javatutorial95 on twitter

Popular Posts

Translate