Java Basics


1. What are the basic data types in Java?

8 basic data types in Java are

1) byte: The byte data type is an 8-bit signed two's complement integer.
2)short: The short data type is a 16-bit signed two's complement integer.
3)int: By default, the int data type is a 32-bit signed two's complement integer, which has a minimum value of -2^31 and a maximum value of 2^31 -1.
4) long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -2^63 and a maximum value of 2^63 -1
5) float: The float data type is a single-precision 32-bit floating point.
6) double: The double data type is a double-precision 64-bit IEEE 754 floating point.
7)boolean: The boolean data type has only two possible values: true and false.
8)char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).



2. What is auto boxing and unboxing?

Autoboxing is the automatic conversion that the Java compiler performs between the primitive types and their corresponding object wrapper classes.

For example, converting an int to an Integer, a double to a Double, and so on. The conversion of wrapper class objects to primitive types is called unboxing.

Here is the simplest example of autoboxing:

Character ch = 'a';

Here primitive value a char is converted to an object of Character class.


3. Write a program to read two numbers and print their sum.

import java.util.Scanner;
public class ReadNumber {	
	public static void main(String args[]) {
		int num;
		Scanner sc = new Scanner(System.in);
		num = sc.nextInt();
		int num2 = sc.nextInt();
		System.out.println("The sum is "+(num+num2)); 
	}
}
Scanner is a class which allows us to read data from a stream. The other method is to use BufferedReader.

Scanner sc = new Scanner(System.in)

is for reading from console.

Another program but using BufferedReader is
;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;


public class ReadNumber {

public static void main(String args[]) {
int num;
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String str;
try {
str = reader.readLine();
num = Integer.parseInt(str);
str = reader.readLine();
int num2 = Integer.parseInt(str);
System.out.println("The sum is "+(num+num2));
} catch (IOException e) {

e.printStackTrace();
}

}

}


4. Write a Java program where a class has a method called print which is overloaded for integer and float parameters.

public class OverloadedPrint{
     void print(int num)
     {
        System.out.println("intger number is "+num);
     }
     void print(float num)
     {
        System.out.println("float number is "+num);
     }
     public static void main(String a[])
    {
        OverloadedPrint obj = new OverloadedPrint();
        obj.print(10);  
        obj.print(1.2f);
    }
}

Note that the second call to print method in main() has 1.2f as parameter. If instead we call the method as
obj.print(1.2);
we will get a compilation error.

Because 1.2 is a double literal, not a float literal. A float literal must have a suffix of f or F.


5. Write a Java program to read 10 numbers, store them in an array and find their sum and product.

import java.util.Scanner;
public class ArraySum
{
    public static void main(String args[])
   {
     int arr[] = new int[10];
     Scanner sc = new Scanner(System.in);
     for(int i=0;i<10;i++)
       arr[i]=sc.nextInt();

     int s = 0;
     int p = 1;
     for(int i=0;i<10;i++)
     {
       s+=arr[i];
       p*=arr[i];
     }
     System.out.println("The sum of array is "+s);
     System.out.println("The product of array is "+p);
    }
}

6. Write a Java program to find the largest element in 3X3 matrix.

import java.util.Scanner;
public class MatrixSum
{
  int mat[][]=new int[3][3];
  public static void main(String args[])
  {
     MatrixSum obj = new MatrixSum();
     Scanner sc = new Scanner(System.in);
     for(int i=0;i<3;i++)

       for(int j=0;j<3;j++)
          obj.mat[i][j]= sc.nextInt();
 
      int max = obj.mat[0][0];
      for(int i=0;i<3;i++)
        for(int j=0;j<3;j++)
          {
              if (obj.mat[i][j]>max)
                max = obj.mat[i][j];
         }
     System.out.println("The largest element is "+max);
   }
}

7. A magic square of order n is an arrangement of n × n numbers in a square, such that the n numbers in all rows, all columns, and both diagonals add to the same constant. Write a program to read nXn numbers and find if these numbers form a magic square.


import java.util.Scanner;
class maginsquare{
    public static void main(String args[]){
        int n;
        System.out.println("n=");
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        int matrix[][] = new int[n][n];
        for(int i=0;i<n;i++){
            System.out.println("Enter the elements of row"+i);
            for(int j=0;j<n;j++)
            {
                matrix[i][j]=scanner.nextInt();
            }
        }
        if(isMagicSquare(matrix,n))
            System.out.println("It is a magic square");
        else
            System.out.println("It is not a magic square");
    }

    static boolean isMagicSquare(int mat[][],int n){
        int rowsum,prevrowsum=0;
        for(int i=0;i<n;i++){
            rowsum= 0;
            for(int j=0;j<n;j++)
                rowsum+=mat[i][j];
            if(prevrowsum==0)
                prevrowsum=rowsum;
            if( rowsum!=prevrowsum)
                return false;
        }
        int prevcolsum=0,colsum=0;
        for(int col=0;col<n;col++){
            colsum=0;
            for(int row=0;row<n;row++)
                colsum=colsum+mat[row][col];
            if(prevcolsum==0)
                prevcolsum=colsum;
            if(prevcolsum!=colsum)
                return false;
        }
        if(prevcolsum!=prevrowsum)
            return false;
        int diasum=0;
        for(int i=0;i<n;i++)
            diasum+=mat[i][i];
        if(diasum!=prevrowsum)
            return false;
        return true;
    }
}
We have defined a two dimensional array matrix and read its elements. We have used a function called isMagicSquare which returns false whenever any of the conditions is false - if rowsums are not equal, if column sums are not equal or if diagonal sums are not equal.

The program is a good example for the use of 2d arrays and functions with 2d array parameters.

8. What is the output of this code?

class evaluate {
   public static void main(String args[]) {
        int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
        int n = 6;
        n = arr[arr[n] / 2];
        System.out.println(arr[n] / 2);
   } 
}

Output is 1


9. What are the differences between String and StringBuffer classes

length: The length of the String object is fixed. The length of the StringBuffer can be increased.

Modification: String object is immutable. StringBuffer object is mutable.

Performance: String is slower during concatenation. StringBuffer is faster during concatenation.

Memory: String Consumes more memory. StringBuffer Consumes less memory.

Storage: String uses string constant pool. String buffere uses heap Memory.


10. What are the rules for variable names in Java?

1) Begin with alphabet or underscore
2) can contain only alphabets, digits and _
3) can not be a keyword

Also note that variable names are case sensitive. And Java names follow camel case - capitalizing first letter of each word.

1) class Names begin with upper case letter
2) method names and field names begin with lower case.


11. Write a Java program to display first n Fibonacci numbers.

import java.util.Scanner;
class Demo{
    public static void main(String args[]){
       Demo obj = new Demo();
       int n;
       System.out.println("n=");
       Scanner scanner  = new Scanner(System.in);
       n = scanner.nextInt(); 
       obj.printFib(n);	
    }
    void printFib(int n){
        int fn1 = 0;
        int fn2 = 1;
        int fn;
        for(int i=0;i<n;i++)
        {
            if(i==0)
               System.out.println(" "+fn1);
            else if(i==1)
               System.out.println(" "+fn2);
            else
             {
                fn = fn1+fn2;
                fn2 = fn1;
                fn1 = fn;
                System.out.println(" "+fn);
             }
         }
     }
   }
A Fibonacci number fn is equal to fn-1 + fn-2. The first two fibonacci numbers are are 0 and 1.


12. How is a package created in Java program?

To create a package, you choose a name for the package and put a package statement with that name at the top of every source file that contains the types (classes, interfaces, enumerations, and annotation types)

e.g.
package calc;
public class ABC{
....
}



If you do not use a package statement, your type ends up in an unnamed package.

The standard practice is to use inverted company name in the begining of package.

e.g.
package com.google.somepackage;


13. Write a Java program to find the median of an array.

import java.util.Arrays;
import java.util.Scanner;

public class ArrayMedian {
    public static void main(String args[]){
        int n ;
        System.out.println("Size of array=");
        Scanner scanner = new Scanner(System.in);
        n = scanner.nextInt();
        int arr[] = new int[n];
        System.out.println("Enter array elements:");
        for(int i=0;i<n;i++)
            arr[i] = scanner.nextInt();

        Arrays.sort(arr);
        double median;
        if(n%2==0){
            median =( arr[n/2]+arr[n/2-1])/2.0;
        }else{
            median = arr[n/2];
        }
        System.out.println("Median of the array="+median);
    }
}

A median is an element of an array which as equal number of values which are greater and smaller than itself.

For a sorted array median is just the middle element. But if the array has even number of elements the median is half of sum of two middle elements.


14. What are the differences between break and continue statements?

break and continue are two statements used within loops.

break will stop the loop and exit it. But continue will skip the current iteration of the loop and go to next iteration.

for(int i=0;i<10;i++){
if(i==2)
continue;
if(i==5)
break;
System.out.println(i);
}

The code will print 0 1 3 4. continue will skip the i value of 2. And break will terminate the loop when i is 5.


break is also used to exit a case in switch statement.

e.g.
switch(m){
case 1: System.out.println("one");
break;
case 2: System.out.println("two");
break;
}

If we omit break, then for m = 1, the output will be both one and two.


15. With an example, explain static block.

A static block or static initializer block is executed only once when the class is loaded. It is a block of code used to initialize static variables.

A static block is written in a class with the keyword static.

e.g.
class A{
static int m;
static {
m = 100;
}
int getM(){
return m;
}
}
class Demo{
public static void main(String args[]){
A obj = new A();
System.out.println(obj.getM());
}
}

In the above class, static block is used to initialize static variable m.

Also note that you can also have instance block in a class. It is written similar to static block, but without static keyword. And an instance block is added by the compiler to all the constructors of the class.


16. What are wrapper classes?

Wrappers are classes which enclose primitive data types into objects.

These are Integer, Float, Double etc. They can be typecast to their primitive counterparts.

e.g.
Integer m = 1;

Here m is not a primitive variable but an object of Integer class.

Many classes - e.g. collection frame work, do not work with primitive data types. In such cases, we can use wrapper classes which are compatible with primitive types.


17. Write a program to read a line and find out how many vowels and consonants are present in the line.

import java.util.Scanner;

public class StringTest {
    void printVowelConsonants(String str){
        char arr[] = str.toCharArray();
        int vowCount=0,consCount=0;
        for(char ch:arr){
            if(Character.isAlphabetic(ch)){
                ch = Character.toLowerCase(ch);
                if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||ch=='u'){
                    vowCount++;
                }else{
                    consCount++;
                }
            }
        }
        System.out.println("The String has "+vowCount+" vowels and "+consCount+" consonants");
    }   

  public static void main(String args[]){
        System.out.println("Enter a string:");
        Scanner scanner = new Scanner(System.in);
        String str = scanner.nextLine();
        StringTest obj = new StringTest();
        obj.printVowelConsonants(str);
    }
}

18. When can a Java program use a return statement with no values? What is the use of such a statement?

A return statement without values cab be used within void functions.

Such a statement is used for exiting the function.

e.g.
void printSquareRoot(int num){
if(num<0)
return;
....
}


19. The following code does not compile. Why?

public class StringyThing {
   public static void main(String[] args) {
      String s = new String("Hello world");
      System.out.println(s);
   }
}
 
class String {
    private final java.lang.String s; 
    public String(java.lang.String s) {
         this.s = s;
    }
    public java.lang.String toString() {
        return s;
    }
 }

main() method which is the starting point of execution of Java program requires an array of String objects. But as the String class is redefined, the program tries to use main function with this new String class. That is the reason the program does not compile.


20. What is a recursion? What is tail call recursion?

Recursion is the process in which a function calls itself.

A typical example of recursion in Mathemetics is factorial function.

n! = n * n-1!

A recursive method has a statement which calls itself.

Infinite loop : If there is no base condition where there is no recursive call in a recursive method, then the execution never ends. At some point, there will be a crash because of stack overflow.

Every recursive method must have a base condition which if true, there is no recursive call.

e.g.
int factorial(){
if(n==0)//base condition
return 1;
else
return n* factorial(n-1);
}

Tail call recursion is a method where recursive call is the last statement in the method.


21. Write a program to add two binary numbers in Java.

public class OnlyDigits {
    public static void main(String args[]) {
       int m = 0b110011;
       int n = 0b101100;
       int ans = m+n;
       System.out.println("The sum of two numbers is "+Integer.toBinaryString(ans));

    }
}

In Java 7, a binary number is written by prefixing it with 0b. We have defined two binary numbers m and n. Then we add these using simple integer addition. Next the answer is printed using toBinaryString() method of integer class. 

22. Write a recursive function to find the factorial of a number.

 int factorial(int n){
        if(n==0)
            return 1;
        return n*factorial(n-1);
    }

According to definition, a factorial of a number 

n! = n* (n-1)!

and 0! = 1

So if n is greater than 1, we are recursively calling factorial function with n-1. The base condition is n=0. If n=0, we are returning 1. 

23. Does Java send arguments to functions using call by value method or call by reference method?

Arguments are sent to functions using call by value method.

Which means that if the parameters are modified in the function, the arguments in caller will not be modified.

e.g.
class Demo{
static void changeNumber(int n){
n = n+100;
System.out.println(n);
}
public static void main(String args[]){
int a= 10;
changeNumber(a);
System.out.println(a);
}
}

The output is 110 10

As a is passed using call by value, a is not changed in main function and remains 10 only.


24. Write a program to find LCM of two numbers.

import java.util.Scanner;
class Demo{
  int gcd(int n1,int n2){
   if(n1%n2==0)
      return n2;
   return gcd(n2,n1%n2);   
  }
  public static void main(String args[]){
   int num1,num2;
   Demo obj = new Demo();
   Scanner scanner = new Scanner(System.in);
   num1 = scanner.nextInt();
   num2 = scanner.nextInt();
   if(num1<num2){
    int t = num1;
    num1 = num2;
    num2 = t;
   }
   int gcd = obj.gcd(num1,num2);
   int lcm = (num1*num2)/gcd; 
   System.out.println("LCM of "+num1+" and "+num2+"is "+lcm);
   
  }
 }


LCM is least common multiple of two numbers. You can find LCM by finding the GCD (greatest common divisor - the largest number which divides both given numbers) and then dividing the product by this GCD. 

Because n1 * n2 = LCM *GCD

GCD can be found using recursive algorithm

gcd of n1, n2 = n2 if n1 is divisible by n2
                     = gcd of n2, n1%n2 if not divisible


25. Write a program to find all the prime factors of a given number.

import java.util.Scanner;
import java.lang.Math;
class PrimeFactors{
     void printFactors(int num){
          if(num%2==0){
            System.out.println("2 ");
            while (num%2==0)
             num = num/2;
          }
          int s = (int)Math.sqrt(num);
          for(int i=3;i<=num;i+=2){
               if(num%i==0){
                    System.out.println(i);
                  while(num%i==0)
                     num = num/i;
               } 
          }

     }

     public static void main(String args[]){
         PrimeFactors pf = new PrimeFactors();
         int n;
         Scanner scanner = new Scanner(System.in);
         n  = scanner.nextInt();
         pf.printFactors(n);
     }
}
           

26. Write a program to find the maximum of the given n command line arguments.

class Demo{
     public static void main(String args[]){
         int l = args.length;
         int max = Integer.valueOf(args[0]);
         for(int i=1;i<l;i++){
              int n = Integer.valueOf(args[i]);
              if(n>max)
                  max = n;
         }
         System.out.println("the largest numeber is "+max);
         
    }
}
 

27. Write a program to read a number and print whether the number is prime or not.

import java.util.Scanner;
class prime{
   boolean isPrime(int n){
     if(n%2==0)
       return false;
     int sqn = (int)Math.sqrt(n);
     for(int i=3;i<sqn;i+=2)
        if(n%i==0)
           return false;

     return true;
   }
   public static void main(String args[]){
       Scanner scanner = new Scanner(System.in);
       System.out.println("n=");
       int num = scanner.nextInt();
       prime p1 = new prime();
       if(p1.isPrime(num))
          System.out.println("The number is prime");
       else
          System.out.println("The number is not prime");
   }
}

28. Can we declare main() method as private?

No.

main() method is the starting point of execution of java program. So JVM needs to have access to the main method. If it is private, outside programs can not access the method. That is the reason, main() method should be public.

If we make the method as private, there won't be any compile timer error - there will be a run time error.


29. Is String a primitive data type in Java?

No.

String is not a primitive data type. But it is a library class java.lang.String.

Java has char as primitive data type, which stores one character. You can use an array of chars to store a string.


30. Why Strings in Java are called immutable?

Because once defined, a String object can not be changed. If the String variable is changed, a new object is created.


31. Explain break statement in Java program.


break is used after each case in a switch so that code breaks after the matching case and doesn't continue the execution of subsequent cases as well.

e.g.
switch(option){
case 1: ans = num1+num2;
break;
case 2: ans = num1 - num2;
break;
}

break in a loop: In for loop, while loop or do-while loop, break statement will terminate the loop. It is used for stopping the loop execution in the middle when certain condition is met.

for(int i=0;i<10;i++){
int n = scanner.nextInt();
if(n==-1)
break;
sum+=n;
}