JAVA DATA TYPES MOST FREQUENTLY ASKED INTERVIEW QUESTIONS AND ANSWERS

The eight primitive data types in Java are byte, short , int , long , float , double , char and boolean.

data_type variable_name = initial_value;

The purpose of initializing a variable in Java is to assign it an initial value so that it can be safely used in program . By initializing a variable, it prevents runtime exceptions , avoid compilation errors and enhance safety & security.

data_type variable_name;

data_type variable_name;

In Java primitive data type store the actual value directly , while reference data type store a memory address that points to where the actual data is located .The size of the primitive variable is fixed whereas the size of reference variable is dynamic

Variables in Java are used to allocate specific amount of memory for the data and to inform the compiler about the type of data that will be stored.

The two main categories of data types in java are primitive data type and reference data type.

‘int’ is used for storing integer values. float is a single -precision floating -point data type, and double is a double-precision floating-point data type .The size of the ‘int’ data type is 4 bytes(32-bit), the size of the ‘double’ data type is 8 bytes( 64 -bit) and the size of the ‘float’ data type is 4 bytes(32-bit).

The default value of boolean variable in Java is ‘false’.

Data type in java defines the type and size of data a variable can store.

Given number is z , determine whether this number is Armstrong Number or not. A positive integer number of n digits is called an Armstrong Number of order n if

abcd…=pow(a,n) + pow(b, n) +pow(c,n)+pow(d,n)+………, where a, b, c, d are digits of input number abcd….., n is the number of digits present in the number.

Approach

  1. First count the number of digits present in the given number z. Let the number of digits be n.
  2. For every digits present in the number z ,let digits are d1 , d2 , d3,…..;compute d1^n , d2^n , d3^n……..
  3. If the sum of all computed digits are equal to z i.e. d1^n+d2^n+d3^n+……..=z; it is an armstrong number, then print that this number is an armstrong number, else print this number is not an armstrong number.

Example:

153 is an armstrong number because

1^3+5^3+3^3=153

1634 is a 4 digit armstrong number because

1^4+6^4+3^4+4^4=1634

Java Program to check a number is Armstrong Number Or Not

public class ArmstrongNumber {

public static void main (String args[]) {

// code to enter a number you want to check armstrong number or not

Scanner sc = new Scanner(System.in);

System.out.println(“Enter the number you want to check whether armstrong number or not”);

int n = sc.nextInt();

int temp=n,digits=0,rev,sum=0;

//To find the number of digits:

while(temp>0) {

temp=temp/10;

digits++;

}

temp=n;

while (temp > 0) {

//To find the last digit

rem=temp%10;

//Sum up of the each digit to the power total number of digits present in the number

sum + = Math.pow(rem,digits);

//To remove the last digit

temp=temp/10;

}

if (sum==n) {

System.out.println(“The given number is an armstrong number”);

}

else

System.out.println(“The given number is not an armstrong number”);

}

}

}

If you don’t understand how to find the number of digits java program and how to sum up each digits of a number,

Check the following :

Java Program to count the number of digits in a given number

Let, Given number be n , count the number of digits present in this number

Example :

Input n= 9876

Output: 4

There are 4 digits in 9876 , which are 9 , 8 , 7 & 6.

Approach :

In this approach count the digits by removing the digits from the given number starting from right to left till the number is reduced to 0 . Here remove digits from right because rightmost digit can be removed by performing integer division by 10 . For eg : n=9876, then 9876/10 = 987.6=987(Integer Division ) .

import java.util.*;

public class CountDigits {

public static void main (String args[] ) {

Scanner sc = new Scanner ( System.in) ;

System.out.println(“Enter the number to count the digits in it”);

int num=sc.nextInt();

int temp=num,count=0;

// if the number is exactly 0 , it has 1 digit

if(temp==0) {

count=1 ;

} else {

//Loop runs until the number become 0

while (temp >0 ) {

temp=temp/10; //Removes the last digit

count++;

}

}

System.out.println(“Number of digits : ” + count);

}

}

In Java, String Interning is a memory optimization technique which ensures all distinct string values share a single copy in a specific memory region called the String Constant Pool. The intern() method is used for interning in Java.

When str.intern() method is called , the JVM performs the following tasks :

  1. It checks if an identical string already exists in the String Constant Pool.
  2. If the String is already exists in the String Constant Pool , it returns the reference to that existing String pool
  3. If the String is not present in the String Constant pool, it adds the String to the String Constant Pool and returns its reference.

Example :

String s1=”Gift”;

String s2=”Gift”;

String s3=new String(“Gift”);

String s4=s3.intern();

System.out.println(s1==s2);//true

System.out.println(s1==s3); //false

System.out.println(s1==s4); //true as both point to the same pool address

Yes, In Java String is Thread-Safe. The main reason for thread-safety of String is immutability of String . Once String object is created , its character sequence and internal state cannot be modified or altered . Threads can only read from a String object but never write to it , so there is no risk of race conditions , data corruption . Multiple threads can safely share the exact same string instance simultaneously without explicit synchronization . Hence Java String are thread-safe.

In Java == is a relational operator , whereas equals() is a method of String class. The == operator compares object references , whereas the .equals() method compares the actual text content present inside the string objects. The == operator can be used to compare primitive values like int or char, whereas equals() method cannot be used on primitives. The == operator is safe to use with null values without throwing errors , whereas if you use null values in equals() method , it will throw NullPointerException .

String object of string class are stored in Heap memory, not in stack area. Let’s go deep into this topic. String object can be created in two ways i.e. 1. By using string literal 2. By using the ‘new’ keyword

String literal is created by using a double quote. While creating a string using string literal , the JVM checks the String in String Constant Pool. If the string doesnot exist then a new string instance is created and placed in the String constant pool. But if the same string is exist in the String Constant Pool , then it will not create a new String object , rather it will return the reference to the same instance . So Java compiler doesn’t allocate new memory for string literal if the same string is already present in the String Constant Pool, due to which creating string object using string literal is memory efficient. Earlier upto JDK 6 , String constant pool was located inside PermGen. But from JDK7 , String constant pool moved to Heap Area.

But if we create String object using a new keyword , then it creates a new reference of the object and store in Heap Area and Thus creating string object using new keyword is not memory efficient.

String is immutable means that once a String object is created , its value cannot be changed.

There are many advantages of Strings being immutable:

  1. Security: Immutabity of String prevents sensitive data such as passwords , file paths and URLs from being modified after creation.
  2. Thread Safety: As string is immutable, Multiple Threads can access the same string object without synchronization issuues.
  3. String Pool Optimization : As String is immutable, it allows multiple references to safely share the same string object , which save memory.
  4. HashCode Caching: Due to immutable property of String , the hashcode remains constant , which improves the performance of collections like HashMap.
  5. Better Memory Management : As String is immutable , strings can be reused , which reduce the unnecessary object creation.

A String can be created in two ways in Java:

  1. Through String Literal : Using String literal, one can create a string which is memory efficient because no new object is created if that string is already existed in the string constant pool.

Example:

String str=”Giftisincredible”;

2. Using new Keyword : A String can also be created using new keyword. While a String is created using new keyword, it creates a new object in heap memory , even if the same string already exists in the String constant pool.

While creating a String object using new keyword, one object is created in the heap memory, the string literal is stored in the string pool if the string is not already present in the string pool and the reference variable of that string object points to the heap object, not the string constant pool .

Example:

String str=new String(“Giftisincredible”);

Java String Pool is a special memory area inside the heap memory that stores unique string objects . Whenever JVM finds a String literal , it first checks whether an identical string already exists in the String constant pool . If the string is already present in the String Constant Pool, then JVM reuses the existing String object reference . If the string is not present in the String constant pool , it creates a new string object in the String Constant Pool .

The main advantages of String Constant Pool is that it reduces the memory consumption by reusing immutable string objects .

String is not a primitive data type . String is a derived data type which is also called reference type because they refer to an object . String class is present in Java.lang package . There are many functions that need to be called upon when processing a string ,such functions are indexOf() , equals() , substring() , toUppercase() etc. Primitive data types don’t have these functions .

Answer:

Yes , String can be used in the switch case in Java.

Example:

public class StringSwitchCase{

public static void main(String args[] ) {

String gift =”Apple Watch”;

switch(gift ) {

case “IPhone” :

System.out.println(“gift is Iphone”);

break;

case “Car” :

System.out.println(“Gift is car”);

break;

case “AppleWatch” :

System.out.println(“Gift is apple watch”);

break;

default :

System.out.println(“You are winning some gifts”);

}

}

OUTPUT:

Gift is apple watch

Answer:

Yes, it is possible to compare two strings using == operator . If you compare two strings using == operator , it compares the reference or adress value, but don’t compare the actual content . If you use equals() method to compare two strings , then it will compare the actual content of two strings .

Example:

public class StringComparision {

public static void main (String args[] ) {

String str1= “Beautiful” ;

String str2 =”Beautiful” ;

String str3 =new String (“Beautiful” ) ;

System.out.println(str1==str2);

//true because both points to same memory allocation

System.out.println(str1==str3));

// false because str3 refers to the instance created in the heap memory .

System.out.println(str1.equals(str3));

// true because both have the same content even though both are different string objects .

}

}

Answer :

The basic difference between StringBuffer and StringBuilder is Thread safety and Synchronization .

StringBuffer is Synchronized and thread-safe due to which multiple threads can safely use it . While StringBuilder is not Synchronized and so not thread-safe .

StringBuffer is slower due to synchronization overhead. Whereas StringBuilder is fast as it avoids locking mechanisms .

Answer:

A String object is immutable means its value cannot be changed after creation , whereas StringBuffer object is mutable , which means it’s characters or length can be changed directly without creating new memory objects .

String uses the String Constant Pool for memory allocation , whereas StringBuffer directly use Heap Memory for memory allocation .

String is Thread-safe due to immutability , whereas StringBuffer is Thread-safe due to synchronized methods .

In String class, equals() method is overriden to compare values, whereas in StringBuffer, equals() method is not overriden

You should avoid using the + operator for string concatenation inside loops because it triggers excessive memory consumption and quadratic O(n^2) time complexity. As Strings are immutable , they cannot be modified in place . Every single + operation copies the entire existing string into a brand-new memory location .

Instead of using + in a loop , StringBuilder offers a more efficient way to build strings . It doesn’t create a new object for each concatenation , which helps in reducing memory allocations and improve overall performance.

Yes, Strings can be garbage collected in Java. The eligibility for garbage collection of Strings in Java completely depends on how they were created.

If Strings are created dynamically at runtime such as using the new keyword , concatenating non-constant strings or reading data from a file , those strings occupy memory in heap memory .As soon as these types of strings become unreachable i.e. no active thread or variable holds a reference to them , they become eligible for garbage collection .

Secondly if the Strings are created as hardcoded literals (e.g. String s=”Gift” ) or dynamically added using the intern() method are placed inside the String Constant Pool . Now let’s check how the strings present in String Constant Pool are garbage collected.

If you add manually a dynamic string to the pool using String.intern() , it can be garbage collected as soon as it becomes unreachable by your application i.e. when no active references remain.

A hardcoded string literal can only be garbage collected if the defining class that contains the literal is unloaded by its ClassLoader .

A String is a non-primitive data type which represent the sequence of characters enclosed in double quotes . String can conrain letters , numbers , spaces , symbols and punctuation .

Key characteristics of Java String are Immutability , Memory Optimization and constant pool. String is immutable because once a string object is created , its value cannot be changed . Java uses special memory location called String Constant Pool inside the heap memory .If you create multiple strings with same text literal , Java points to the same memory slot inside the Constant Pool to save space.