Top 30 Java Basic Interview Questions for Freshers

Java Basic Interview Questions for Freshers

Q 1: What is the most Important feature of java?
Ans: Java is platform independent language.

Q 2: What do you mean by Platform Independence?
Ans: Platform Independence  you can run and compile program in one platform and can execute in any other platform.

Q 3: What is JVM?
Ans: The Java interpreter along with the runtime environment required to run the Java application in called as Java virtual machine(JVM)

Q 4: What is the difference between a JDK and a JVM?
Ans: JDK is Java Development Kit which is for development purpose and it includes execution environment also. But JVM is purely a run time environment and hence you will not be able to compile your source files using a JVM.

Q 5: What is the base class of all classes?
Ans: java.lang.Object

Q 6: What is JIT Compiler?
Ans: Just-In-Time(JIT) compiler is  used to improve the performance. JIT compiles parts of the byte code that have similar functionality at the same time,

Q 7: Are JVM's Platform Independent?
 Ans: JVM'S are not platform Independent. JVM'S are platform Specific.

Q 8: What is are packages?
Ans: A package is a collection of related classes and interfaces providing access protection and namespace management.

Q 9: What if main method declare as private?
Ans: No,It will compile fine but in run time it will error like main method should be in public.cannot find main method.

Q 10: What is platform?
Ans: A platform is basically the hardware or software environment in which a program runs.There are two types of platforms software and hardware.Java provides software-based platform.

Q 11: What is meant by Inheritance and what are its advantages?
 Ans: Inheritance is the process of inheriting all the features from a class. The advantages of inheritance are reusability of code and accessibility of variables and methods of the super class by subclasses.

Q 12: What is the difference between superclass and subclass?
Ans: A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Q 13: What all memory areas are allocated by JVM?
Ans: Heap, Stack, Program Counter Register and Native Method Stack

Q 14: What is javac ?
Ans: It produces the java byte code from *.java file.It is the intermediate representation of your source code that contains instructions.

Q 15: Can we mark constructors final?
Ans: No, Constructor cannot be declared final.

Q 16: What are two different ways to call garbage collector?
Ans: System.gc() OR Runtime.getRuntime().gc().

Q 17: What is the difference between superclass and subclass?
 Ans: A super class is a class that is inherited whereas sub class is a class that does the inheriting.

Q 18: What is an abstract class?
Ans: An abstract class is a class designed with implementation gaps for subclasses to fill in and is deliberately incomplete.

Q 19: What are the states associated in the thread?
Ans: Thread contains ready, running, waiting and dead states.

Q 20: What is the difference between a constructor and a method?
Ans: A constructor is a member function of a class that is used to create objects of that class. It has the same name as the class itself, has no return type, and is invoked using the new operator.
A method is an ordinary member function of a class. It has its own name, a return type (which may be void), and is invoked using the dot operator.

Q 21: What is the difference between an Interface and an Abstract class?
Ans: An abstract class can have instance methods that implement a default behavior. An Interface can only declare constants and instance methods, but cannot implement default behavior and all methods are implicitly abstract.
An interface has all public members and no implementation. An abstract class is a class which may have the usual flavors of class members (private, protected, etc.), but has some abstract methods.

Q 22: Can we override a static method?
Ans: No, we cannot override a static method. Static means class level.

Q 23: What is synchronization?
Ans: Synchronization is the mechanism that ensures that only one thread is accessed the resources at a time.

Q 24: What is deadlock?
Ans: When two threads are waiting each other and can’t precede the program is said to be deadlock.

Q 25: Use of finalize() method in java?
 Ans: finalize() method is used to free the allocated resource.

Q 26: Is it possible to overload main() method of a class?
Ans: Yes, we can overload main() method as well. But every time public static main(String[] args) will be called automatically by JVM.Other methods need to call explicitly.

Q 27: What is static in java?
Ans: Static means one per class, not one for each object no matter how many instance of a class might exist. This means that you can use them without creating an instance of a class.Static methods are implicitly final, because overriding is done based on the type of the object, and static methods are attached to a class, not an object.
A static method in a superclass can be shadowed by another static method in a subclass, as long as the original method was not declared final. However, you can't override a static method with a nonstatic method. In other words, you can't change a static method into an instance method in a subclass.

Q 28: Can I declare a data type inside loop in java?
Ans: Any Data type declaration should not be inside the loop. Its possible but not recommended.

Q 29: What is final class?
Ans: A final class can't be extended ie., final class may not be subclassed. A final method can't be overridden when its class is inherited. You can't change value of a final variable (is a constant).

Q 30: Can we inherit the constructors?

Ans: No, we cannot inherit constructors. We can call super class constructors from subclass constructor by using super() call.


~~~~~~ Best Of Luck ~~~~~


Most Important Topics for Java Interviews

Most Important Topics for Java Interviews

Before preparing for java interview you want to know which topics are most important. To give you an idea, this list of Java interview questions includes following topics and it will help you most.

  •     Multi threading, concurrency and thread basics
  •     Date type conversion and fundamentals
  •     Array
  •     String
  •     Garbage Collection
  •     Java Collections Framework
  •     Java IO and NIO
  •     Common Networking protocols
  •     JVM internals
  •     Java Best Practices
  •     JUnit
  •     JDBC
  •     Date, Time, and Calendar
  •     GOF Design Patterns
  •     SOLID design principles
  •     Abstract class and interface
  •     Java basics e.g. equals() and hashcode
  •     Generics and Enum
  •     Data structure and algorithm in Java
  •     Regular expressions
  •     XML Processing in Java
  •     Programming
  •  


Friends you are also lucky that nowadays there are some good books available to prepare for Java interviews, one of them   which I find useful and interesting to read is Java Programming Interview Exposed by Markham. It will give you to some of the most important topics for Java and JEE interviews.



Best Of Luck


How to install Java in Linux Step by Step

Java Installation

Java is a collection of software better known for its cross platform availability was developed by Sun Microsystems in 1995. Java platform is used by millions of applications and websites (specially used in banking sites) due to its fast, secure and reliable nature.
Today, Java is everywhere, from desktops to data-centers, game consoles to scientific computers, mobile phones.
There are more than one version of Java can be installed and running on same computer and also it’s possible to have different version of JDK and JRE simultaneously on a machine, actually there are abundant of applications that requires Java-jre (Java Runtime Environment) and those who are developer required Java-sdk (Software Development Kit).
There are lots of Linux distribution comes with other version of Java called OpenJDK. OpenJDK is an open source implementation of Java application.

Follow these steps to download and install 32/64 - bit Java for Linux.
  • Download
  • Install

Download

Go to http://java.com and click on the Download button
Now download the Java (JDK) 8u45 source tarball files for your system architecture as following Screenshot.

Java Installation

There are two types of installation packages.
  • Java on Linux Platforms

 This installs the Java Runtime Environment (JRE) for 32-bit Linux, using an archive binary file (.tar.gz).
  •  Java on RPM-based Linux Platforms

  1. This installs the Java Runtime Environment (JRE) for 32-bit RPM-based Linux platforms, such as SuSE  and Red Hat , using an RPM.
  2. Download the package that best pack your needs. You can download the file to any of the directories on your system.
  3. Before the file can be downloaded, you must accept the license agreement.
  4. Download and check the download file size to ensure that you have downloaded the full.

Install Java 8 in Linux.

Note : To install Java in a system-wide location such as /usr/local, you must login as the root user to gain the necessary permissions. If you do not have root access, install the Java in your home directory or a sub directory for which you have write permissions

Before installing Java, make sure that have you installed java or  verify the version of installed Java.


[root@linuxelearn ~]# # java -version
java version "1.7.0_75"
OpenJDK Runtime Environment (IcedTea 2.5.4) (7u75-2.5.4-2)
OpenJDK 64-Bit Server VM (build 24.75-b04, mixed mode)
[root@linuxelearn ~]#


If Java is already installed, we will get the current version.

Make a directory where you want to install Java. For global access (for all users) install it preferably in the directory /opt/java.

# mkdir /opt/java && cd /opt/java


[root@linuxelearn ~]# mkdir /opt/java
[root@linuxelearn ~]#


Change to the directory in /opt/java.

Syntax : # cd directory_path_name
For example, to install the software in the /opt/java/ directory type following command .
#cd /opt/java/


[root@linuxelearn ~]# cd /opt/java
[root@linuxelearn java]#


Move the downloaded .tar.gz archive binary to the current directory.

Unpack the tarball and install Java using following command.

# tar zxvf jre-8u121-linux-i586.tar.gz


[root@linuxelearn java]# tar zxvf jre-8u121-linux-i586

  • The Java files are installed in a directory called jre1.8.0_73 in the current directory.
  • Into this example, we have installed into /opt/java/jre1.8.0_73 directory.
  • Delete the .tar.gz file if you want other wise you can keep as it is.

Java on RPM based Linux
  1. First you have to Become root by running su and entering the super-user password.
  2. If you installed any previous Java packages in linux uninstall that packages using the following command.

# rpm -e package_name


[root@linuxelearn java]# rpm -e jre-8u121-linux-i586


       3. Then Change to the directory in which you want to install java packages using
Syntax: cd directory_pat
For example, to install the software in the /opt/java/ directory.

#cd /opt/java


[root@linuxelearn ~]# cd /opt/java
[root@linuxelearn java]#



       4. Install the java package using following command.

#rpm -ivh jre-8u73-linux-i586.rpm


[root@linuxelearn java]# rpm -ivh jre-8u121-linux-i586.rpm
Preparing...                ########################################### [100%]
   1:jre1.8.0_121           ########################################### [100%]
Unpacking JAR files...
            plugin.jar...
/var/tmp/rpm-tmp.h1cXub: /usr/java/jre1.8.0_121/bin/unpack200: /lib/ld-linux.so.


Use following command To upgrade a package,

#rpm -Uvh jre-8u73-linux-i586.rpm


[root@linuxelearn java]# rpm -Uvh jre-8u121-linux-i586.rpm
Preparing...                ########################################### [100%]
            package jre1.8.0_121-1.8.0_121-fcs.i586 is already installed
[root@linuxelearn java]#

  • Exit from the root shell there is no need to reboot system.

Now set the Java Environment Variables.

[root@linuxelearn java]# export JAVA_HOME=/opt/java/jdk1.8.0_45/
[root@linuxelearn java]# export JRE_HOME=/opt/java/jdk1.8.0._45/jre
[root@linuxelearn java]# export PATH=$PATH:/opt/java/jdk1.8.0_45/bin:/opt/java/jdk1.8.0_45/jre/bin


# export JAVA_HOME=/opt/java/jdk1.8.0_45/    
# export JRE_HOME=/opt/java/jdk1.8.0._45/jre
# export PATH=$PATH:/opt/java/jdk1.8.0_45/bin:/opt/java/jdk1.8.0_45/jre/bin

Now You can verify the Java version again, to confirm.

# java -version


[root@linuxelearn java]# java -version
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)
[root@linuxelearn java]#


How to enable Java Support in Firefox

You have to run following commands to enable Java module for Firefox.

[root@linuxelearn java]# alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so libjavaplugin.so /opt/java/jdk1.8.0_45/jre/lib/i386/libnpjp2.so 20000


--------------- For 32-bit Systems ---------------
# alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so libjavaplugin.so /opt/java/jdk1.8.0_45/jre/lib/i386/libnpjp2.so 20000
--------------- For 64-bit Systems ---------------
# alternatives --install /usr/lib/mozilla/plugins/libjavaplugin.so libjavaplugin.so /opt/java/jdk1.8.0_45/jre/lib/amd64/libnpjp2.so 20000

Now check the Java support by restarting Firefox and enter about:plugins on the address bar. You will get following screen output.
Java Installation

........................................................

I hope You enjoyed reading this article.


How to restrict a user to run only two commands in sudoers

Restrict a user “pooja” to run only two root commands.

This task is very simple, just modify the previous permissions assign to pooja.
Let’s give pooja to run only #fdisk and #parted command access.
First check the complete path of those command by using following command
    
    # which fdisk
    # which parted


[pooja@linuxelearn ~]$ which fdisk
/sbin/fdisk
[pooja@linuxelearn ~]$ which parted
/sbin/parted
[pooja@linuxelearn ~]$


Lets assign both above paths in sudoers file.

# visudo

##      user    MACHINE=COMMANDS
##
## The COMMANDS section may have other options added to it.
##
## Allow root to run any commands anywhere
root    ALL=(ALL)       ALL
pooja   ALL=(ALL)       /sbin/fdisk,/sbin/parted

## Allows members of the 'sys' group to run networking, software,
## service management apps and more.

  • Login as a pooja and try assigned commands and other commands as well

[root@linuxelearn ~]# su pooja
[pooja@linuxelearn root]$ sudo fdisk -l
[sudo] password for pooja:

Disk /dev/sda: 17.2 GB, 17179869184 bytes
255 heads, 63 sectors/track, 2088 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000efa3d

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              26        1301    10240000   83  Linux
/dev/sda3            1301        1562     2097152   82  Linux swap / Solaris
/dev/sda4            1562        2088     4228884    5  Extended
/dev/sda5            1562        1626      517837+  82  Linux swap / Solaris
/dev/sda6            1627        1691      522081   8e  Linux LVM
/dev/sda7            1692        1756      522081   8e  Linux LVM
/dev/sda8            1757        1821      522081   82  Linux swap / Solaris
[pooja@linuxelearn root]$

[pooja@linuxelearn ~]$ sudo useradd jon
Sorry, user pooja is not allowed to execute '/usr/sbin/useradd jon' as root on linuxelearn.rj.com.
[pooja@linuxelearn ~]$


Note : Try the same commands for group also. It is exactly same.

How to allow any group or user to run only network related commands as sudo user in Linux.

To allow a group run only network commands, first uncomment the following line.


## Networking
# Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconfig, /sbin/mii-tool

## Networking
Cmnd_Alias NETWORKING = /sbin/route, /sbin/ifconfig, /bin/ping, /sbin/dhclient, /usr/bin/net, /sbin/iptables, /usr/bin/rfcomm, /usr/bin/wvdial, /sbin/iwconfig, /sbin/mii-tool


Observe that you have just remove # before the line to make the line readable and also observe that it contains all networking commands.
  • Just replace “ALL” with “NETWORKING” from the last field of group line.


## Allows people in group wheel to run all commands
# %wheel        ALL=(ALL)       ALL
 
%rpgroup      ALL=(ALL)       NETWORKING



Note: NETWORKING is the name of the command alias where uncommented the line.
  • Now login as one of the member of rp group and try some commands assigned it.


[pooja@linuxelearn ~]$ sudo ifconfig
eth0      Link encap:Ethernet  HWaddr 08:00:27:0A:86:5B 
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 b)  TX bytes:0 (0.0 b)

lo        Link encap:Local Loopback 
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:396 errors:0 dropped:0 overruns:0 frame:0
          TX packets:396 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:47248 (46.1 KiB)  TX bytes:47248 (46.1 KiB)

[pooja@linuxelearn ~]$ sudo userdel raj
Sorry, user pooja is not allowed to execute '/usr/sbin/userdel raj' as root on linuxelearn.rj.com.
[pooja@linuxelearn ~]$






How to give any group all privileges like root in sudoers file.

Allow a group all root privileges in sudo file.

Let’s first check the members of group using following command and then apply root privileges.
  • #tail /etc/gshadow


[root@linuxelearn ~]# tail /etc/gshadow
nagios:!::
nagcmd:!::apache
rahul:!::
ram:!::pooja
rpgroup:!:nagios:rahulp,pooja
ktg:!::
admin:!::
pooja:!::
linuxelearn1:!::
rjgroup:!::nagios
[root@linuxelearn ~]#


To give root privileges to group add a line by using sudoers file as shown below.
  • Type Command VISUDO to open sudoers file.
  • #visudo (save the sudoers file as we save a vim file using “wq!”)


## Allows people in group wheel to run all commands
# %wheel        ALL=(ALL)       ALL
%rpgroup      ALL=(ALL)       ALL
 
## Same thing without a password
# %wheel        ALL=(ALL)       NOPASSWD: ALL

  • Now, login as one of the user of rpgroup try root commands


[root@linuxelearn ~]# su pooja
[pooja@linuxelearn root]$ cd

[pooja@linuxelearn ~]$ sudo fdisk -l

We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:

    #1) Respect the privacy of others.
    #2) Think before you type.
    #3) With great power comes great responsibility.

[sudo] password for pooja:

Disk /dev/sda: 17.2 GB, 17179869184 bytes
255 heads, 63 sectors/track, 2088 cylinders
Units = cylinders of 16065 * 512 = 8225280 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x000efa3d

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *           1          26      204800   83  Linux
Partition 1 does not end on cylinder boundary.
/dev/sda2              26        1301    10240000   83  Linux
/dev/sda3            1301        1562     2097152   82  Linux swap / Solaris
/dev/sda4            1562        2088     4228884    5  Extended
/dev/sda5            1562        1626      517837+  82  Linux swap / Solaris
/dev/sda6            1627        1691      522081   8e  Linux LVM
/dev/sda7            1692        1756      522081   8e  Linux LVM
/dev/sda8            1757        1821      522081   82  Linux swap / Solaris
[pooja@linuxelearn ~]$


This is all about group root privileges.


I hope you like this article…