Java Interview Questions

Java Interview Questions


1. Explain Some Assembly Controls?

BRA Branch; Motorola 680x0, Motorola 68300; short (16 bit) unconditional branch relative to the current program counter

JMP Jump; Motorola 680x0, Motorola 68300; unconditional jump (any valid effective addressing mode other than data register)

JMP Jump; Intel 80x86; unconditional jump (near [relative displacement from PC] or far; direct or indirect [based on contents of general purpose register, memory location, or indexed])

JMP Jump; MIX; unconditional jump to location M; J-register loaded with the address of the instruction which would have been next if the jump had not been taken

JSJ Jump, Save J-register; MIX; unconditional jump to location M; J-register unchanged

Jcc Jump Conditionally; Intel 80x86; conditional jump (near [relative displacement from PC] or far; direct or indirect [based on contents of general purpose register, memory location, or indexed]) based on a tested condition: JA/JNBE, JAE/JNB, JB/JNAE, JBE/JNA, JC, JE/JZ, JNC, JNE/JNZ, JNP/JPO, JP/JPE, JG/JNLE, JGE/JNL, JL/JNGE, JLE/JNG, JNO, JNS, JO, JS

Bcc Branch Conditionally; Motorola 680x0, Motorola 68300; short (16 bit) conditional branch relative to the current program counter based on a tested condition: BCC, BCS, BEQ, BGE, BGT, BHI, BLE, BLS, BLT, BMI, BNE, BPL, BVC, BVS

JOV Jump on Overflow; MIX; conditional jump to location M if overflow toggle is on; if jump occurs, J-register loaded with the address of the instruction which would have been next if the jump had not been taken

2. What Is Assembly Condition Codes?

Condition codes are the list of possible conditions that can be tested during conditional instructions. Typical conditional instructions include: conditional branches, conditional jumps, and conditional subroutine calls. Some processors have a few additional data related conditional instructions, and some processors make every instruction

conditional. Not all condition codes available for a processor will be implemented for every conditional instruction.

3. What Is Data Movement?

Data movement instructions move data from one location to another. The source and destination locations are determined by the addressing modes, and can be registers or memory. Some processors have different instructions for loading registers and storing to memory, while other processors have a single instruction with flexible addressing modes.

4. What Are Kinds Of Processors?

Processors can broadly be divided into the categories of: CISC, RISC, hybrid, and special purpose.

5. What Are Assembly Attributes?

Attributes are declarative tags in code that insert additional metadata into an assembly.

6. What Are The Types Of Assemblies?

Assemblies are of two types:

Private Assemblies

Shared Assemblies

7. Explain An Intermediate Language?

Assemblies are made up of IL code modules and the metadata that describes them. Although programs may be compiled via an IDE or the command line, in fact, they are simply translated into IL, not machine code. The actual machine code is not generated until the function that requires it is called.

8. What Is Assembly Language?

Each personal computer has a microprocessor that manages the computer's arithmetical, logical, and control activities.

Each family of processors has its own set of instructions for handling various operations such as getting input from keyboard, displaying information on screen and performing various other jobs. These set of instructions are called 'machine language instructions'.

A processor understands only machine language instructions, which are strings of 1's and 0's. However, machine language is too obscure and complex for using in software development. So, the low-level assembly language is designed for a specific family of processors that represents various instructions in symbolic code and a more understandable form.

9. What Are The Advantages Of Assembly Language?

Having an understanding of assembly language makes one aware of:

How programs interface with OS, processor, and BIOS;

How data is represented in memory and other external devices;

How the processor accesses and executes instruction;

How instructions access and process data;

How a program accesses external devices.

Other advantages of using assembly language are:

It requires less memory and execution time;

It allows hardware-specific complex jobs in an easier way;

It is suitable for time-critical jobs;

It is most suitable for writing interrupt service routines and other memory resident programs.

10. What Are The Basic Features Of Pc Hardware?

The main internal hardware of a PC consists of processor, memory, and registers. Registers are processor components that hold data and address. To execute a program, the system copies it from the external device into the internal memory. The processor executes the program instructions.

The fundamental unit of computer storage is a bit; it could be ON (1) or OFF (0). A group of nine related bits makes a byte, out of which eight bits are used for data and the

last one is used for parity. According to the rule of parity, the number of bits that are ON (1) in each byte should always be odd.

So, the parity bit is used to make the number of bits in a byte odd. If the parity is even, the system assumes that there had been a parity error (though rare), which might have been caused due to hardware fault or electrical disturbance.

The processor supports the following data sizes −

Word: a 2-byte data item

Doubleword: a 4-byte (32 bit) data item

Quadword: an 8-byte (64 bit) data item

Paragraph: a 16-byte (128 bit) area

Kilobyte: 1024 bytes

Megabyte: 1,048,576 bytes

11. What Is Binary Number System?

Every number system uses positional notation, i.e., each position in which a digit is written has a different positional value. Each position is power of the base, which is 2 for binary number system, and these powers begin at 0 and increase by 1.

The value of a binary number is based on the presence of 1 bits and their positional value. So, the value of a given binary number is:

1 + 2 + 4 + 8 +16 + 32 + 64 + 128 = 255

which is same as 28 - 1.

12. What Is Hexadecimal Number System?

Hexadecimal number system uses base 16. The digits in this system range from 0 to 15. By convention, the letters A through F is used to represent the hexadecimal digits corresponding to decimal values 10 through 15.

Hexadecimal numbers in computing is used for abbreviating lengthy binary representations. Basically, hexadecimal number system represents a binary data by dividing each byte in half and expressing the value of each half-byte.

13. What Is Local Environment Setup?

Assembly language is dependent upon the instruction set and the architecture of the processor. In this tutorial, we focus on Intel-32 processors like Pentium. To follow this tutorial, you will need :

An IBM PC or any equivalent compatible computer

A copy of Linux operating system

A copy of NASM assembler program

There are many good assembler programs, such as :

Microsoft Assembler (MASM)

Borland Turbo Assembler (TASM)

The GNU assembler (GAS)

We will use the NASM assembler, as it is :

Free. You can download it from various web sources.

Well documented and you will get lots of information on net.

Could be used on both Linux and Windows.

14. How To Installing Nasm?

If you select "Development Tools" while installing Linux, you may get NASM installed along with the Linux operating system and you do not need to download and install it separately. For checking whether you already have NASM installed, take the following steps −

Open a Linux terminal.

Type whereis nasm and press ENTER.

If it is already installed, then a line like, nasm: /usr/bin/nasm appears. Otherwise, you will see just nasm:, then you need to install NASM.

To install NASM, take the following steps :

Check The netwide assembler (NASM) website for the latest version.

Download the Linux source archive nasm-X.XX.ta.gz, where X.XX is the NASM version number in the archive.

Unpack the archive into a directory which creates a subdirectory nasm-X. XX.

cd to nasm-X.XX and type ./configure. This shell script will find the best C compiler to use and set up Makefiles accordingly.

Type make to build the nasm and ndisasm binaries.

Type make install to install nasm and ndisasm in /usr/local/bin and to install the man pages.

This should install NASM on your system. Alternatively, you can use an RPM distribution for the Fedora Linux. This version is simpler to install, just double-click the RPM file.

15. What Are The Assembly Program Sections?

An assembly program can be divided into three sections −

The data section,

The bss section, and

The text section.

16. What Is The Data Section?

The data section is used for declaring initialized data or constants. This data does not change at runtime. You can declare various constant values, file names, or buffer size, etc., in this section.

The syntax for declaring data section is:

section.data

17. What Is The Bss Section?

The bss section is used for declaring variables. The syntax for declaring bss section is :

section.bss

18. What Is The Text Section?

The text section is used for keeping the actual code. This section must begin with the declaration global _start, which tells the kernel where the program execution begins.

The syntax for declaring text section is:

section.text

   global _start

_start:

19. What Are The Assembly Language Statements?

Assembly language programs consist of three types of statements −

Executable instructions or instructions,

Assembler directives or pseudo-ops, and

Macros.

The executable instructions or simply instructions tell the processor what to do. Each instruction consists of an operation code (opcode). Each executable instruction generates one machine language instruction.

The assembler directives or pseudo-ops tell the assembler about the various aspects of the assembly process. These are non-executable and do not generate machine language instructions.

Macros are basically a text substitution mechanism.

20. What Is The Syntax Of Assembly Language Statements?

Assembly language statements are entered one statement per line. Each statement follows the following format −

[label]   mnemonic   [operands]   [;comment]

The fields in the square brackets are optional. A basic instruction has two parts, the first one is the name of the instruction (or the mnemonic), which is to be executed, and the second are the operands or the parameters of the command.

21. What Are Memory Segments?

A segmented memory model divides the system memory into groups of independent segments referenced by pointers located in the segment registers. Each segment is used to contain a specific type of data. One segment is used to contain instruction codes, another segment stores the data elements, and a third segment keeps the program stack.

In the light of the above discussion, we can specify various memory segments as −

Data segment − It is represented by .data section and the .bss. The .data section is used to declare the memory region, where data elements are stored for the program. This section cannot be expanded after the data elements are declared, and it remains static throughout the program.

The .bss section is also a static memory section that contains buffers for data to be declared later in the program. This buffer memory is zero-filled.

Code segment − It is represented by .text section. This defines an area in memory that stores the instruction codes. This is also a fixed area.

Stack − This segment contains data values passed to functions and procedures within the program.

22. What Are The Processor Registers?

There are ten 32-bit and six 16-bit processor registers in IA-32 architecture. The registers are grouped into three categories −

General registers,

Control registers, and

Segment registers.

The general registers are further divided into the following groups −

Data registers,

Pointer registers, and

Index registers.

23. What Linux System Calls?

You can make use of Linux system calls in your assembly programs. You need to take the following steps for using Linux system calls in your program −

Put the system call number in the EAX register.

Store the arguments to the system call in the registers EBX, ECX, etc.

Call the relevant interrupt (80h).

The result is usually returned in the EAX register.

There are six registers that store the arguments of the system call used. These are the EBX, ECX, EDX, ESI, EDI, and EBP. These registers take the consecutive arguments, starting with the EBX register. If there are more than six arguments, then the memory location of the first argument is stored in the EBX register.

Most assembly language instructions require operands to be processed. An operand address provides the location, where the data to be processed is stored. Some instructions do not require an operand, whereas some other instructions may require one, two, or three operands.

When an instruction requires two operands, the first operand is generally the destination, which contains data in a register or memory location and the second operand is the source. Source contains either the data to be delivered (immediate addressing) or the address (in register or memory) of the data. Generally, the source data remains unaltered after the operation.

24. What Are The Basic Modes Of Addressing ?

The three basic modes of addressing are −

Register addressing

Immediate addressing

Memory addressing

Register Addressing

In this addressing mode, a register contains the operand. Depending upon the instruction, the register may be the first operand, the second operand or both.

For example,

MOV DX, TAX_RATE ; Register in first operand

MOV COUNT, CX  ; Register in second operand

MOV EAX, EBX  ; Both the operands are in registers

As processing data between registers does not involve memory, it provides fastest processing of data.

Immediate Addressing

An immediate operand has a constant value or an expression. When an instruction with two operands uses immediate addressing, the first operand may be a register or memory location, and the second operand is an immediate constant. The first operand defines the length of the data.

For example,

BYTE_VALUE  DB  150 ; A byte value is defined

WORD_VALUE  DW  300 ; A word value is defined

ADD  BYTE_VALUE, 65 ; An immediate operand 65 is added

MOV AX, 45H; Immediate constant 45H is transferred to AX

Direct Memory Addressing

When operands are specified in memory addressing mode, direct access to main memory, usually to the data segment, is required. This way of addressing results in slower processing of data. To locate the exact location of data in memory, we need the segment start address, which is typically found in the DS register and an offset value. This offset value is also called effective address.

In direct addressing mode, the offset value is specified directly as part of the instruction, usually indicated by the variable name. The assembler calculates the offset value and maintains a symbol table, which stores the offset values of all the variables used in the program.

In direct memory addressing, one of the operands refers to a memory location and the other operand references a register.

25. What Is The Equ Directive?

The EQU directive is used for defining constants. The syntax of the EQU directive is as follows −

CONSTANT_NAME EQU expression

For example: TOTAL_STUDENTS equ 50

You can then use this constant value in your code, like −

mov  ecx,  TOTAL_STUDENTS

cmp  eax,  TOTAL_STUDENTS

The operand of an EQU statement can be an expression −

LENGTH equ 20

WIDTH  equ 10

AREA   equ length * width

Above code segment would define AREA as 200.

26. How Do You Check Your Java Process Is Running On Linux?

You can check by using "ps" command and "grep" command e.g. ps -ef | grep "myprocess". The keyword which you use with grep for search can be anything unique to your process, something which appears in its command line e.g. name of the class which implements the main method. You can also do "ps -ef | grep java" to list all Java process.

27. How Do You Check How Much Memory And Cpu Your Java Process Is Consuming?

First, you need to find the PID of your process, which you can find by using the "ps" command as shown in the previous . Once you find the PID you can use the "top" command to find the CPU and memory usage. Alternatively, you can also use the prstat command as shown here.

28. What Does -xmx And -xms Parameters Mean?

These are parameters to specify heap size in Java. The -Xms defines the size of the heap when JVM starts up and -Xmx is used to specify the maximum heap size for Java application i.e. your heap cannot grow beyond that and JVM will die by throwing OutOfMemoryError if your heap doesn't have enough space to create new objects. See here to learn more about heap memory in Java.

29. What Is The Difference Between Jvm And Jre?

The JRE stands for Java Runtime Environment and JVM stands for Java Virtual Machine. You install JRE to run Java application e.g. Applet or Core Java application or Web server like Tomcat. The JVM is part of JRE. See here to learn more differences between JVM and JRE.

30. What Is The Difference Between Jvm And Jit?

The JVM stands for Java Virtual machine while JIT stands for Just in time Compiler. The JIT is part of JVM and used to convert the Java bytecode into native machine code which runs faster. There is some threshold set if a code runs more than the threshold it becomes the candidate of just in time compilation by JIT.

31. How Do You Take The Heap Dump Of A Java Process?

There are many ways to take the heap dump of a Java process e.g. Tomcat, but most common is by using tools available in JDK e.g. jVisualVM, jCmd, and jmap. Here is the command you can use to take the heap dump of Java process:

$ jmap -dump:live, file=/location/of/heap_dump.hprof  PID

The heap dump will contain all live objects and they are stored in heap_dump.hprof file. Remember, you also need PID of Java process which you can find by using "ps" and "grep" command as discussed in the first . You can see Java Performance Companion by Charlie Hunt to learn more about taking and analyzing heap dump in Java to find memory leak and other memory related errors.

32. How Do You Take A Thread Dump Of A Java Process?

Taking thread dump is easier than taking heap dump because you don't need to remember tool. In Linux, you can just use the kill command to take the thread dump e.g.

$ kill -3 PID

will print the thread dump in the log file or where System.out is redirected. Similarly, in Windows, you can use Ctrl + Break from the command prompt. Alternatively, you can also use jConsole and VisualVM to take the thread dump of Java application in both Windows and Linux. You can also read Java Performance The Definitive Guide By Scott Oaks to learn more about thread dump and heap dump.

33. What Is Outofmemoryerror In Java? How Do You Deal With That?

The Java virtual machine throws java.lang.OutOfMemoryError when there is not enough memory to run the application e.g. no more memory to create new objects, no more memory to create new threads etc. The most common OutOfMemoryError is the java.lang.OutOfMemoryError: java heap space, which comes when there is no more memory left to create a new object.

34. What Is The Difference Between 32-bit And 64-bit Jvm?

The main differences between 32-bit and 64-bit JVM are that later is designed for 64-bit operating system e.g. Windows 8 or later versions of Linux. From Java developer's perspective, the main difference between them comes from heap size. A 64-bit JVM virtually has unlimited heap memory as compared to 4GB of the theoretical limit of 32-bit JVM. If your program needs more memory, better run it on 64-bit JVM with large heap space. See here to learn more about 32-bit and 64-bit JVM.

35. What Is Garbage Collector?

The garbage collector is a component of Java virtual machine which is responsible for reclaiming memory from dead objects. It's one of the key components and allows an application developer to focus on application development rather than doing memory management. Some of the popular garbage collectors are a Concurrent Mark-Sweep garbage collector and G1 garbage collector in recent times.

36. How Do You Analyze A Heap Dump?

There are many tools to analyze heap dump in Java e.g. you can use the jhat tool which comes along with JDK. You can also use Eclipse Memory Analyzer to analyze heap dump to find out any memory leak in Java while dealing with OutOfMemoryError in Java. See Java Performance The Definitive Guide By Scott Oaks to learn more about analyzing Java Heap dump.

37. What Is The Difference Between Web Server And Application Server?

The main difference between Web and Application Server comes from the fact that you cannot run EJB on the Web server like Tomcat or Jetty. The application server like WebLogic and WebSphere provides the runtime environment for EJB and other advanced services required by Java EE or J2EE specification.

38. What Is The Difference Between Apache Httpd And Tomcat?

Though both httpd and Tomcat are products of Apache software foundation, the httpd is more popular and used across the web and not just in Java world. The httpd is a web server which can serve static HTML files and dynamic content using PHP, Perl or Python, while Tomcat is a Servlet container which provides the runtime environment for Servlet and JSP. You can also use both Apache httpd and Tomcat together in Java world.

39. Can You Use Apache And Tomcat Together?

Yes, you can use Apache and Tomcat together. There are many Java web application which is fronted by Apache web server to deliver static resources e.g. HTML files, images, configuration files etc. You can then configure Apache to forward the request to Tomcat.

40. How Do You Start And Stop Tomcat In Linux?

When you install Tomcat in Linux by unzipping the downloaded package, you can see that there is a startup.sh and shutdown.sh file in the tomcat/bin directory. These scripts are used to start and stop Tomcat in Linux. These scripts internally call Catalina.sh, the main script to start Tomcat engine.

41. How Do You Start And Stop Apache On Linux?

The Apache server runs as httpd daemon in Linux and you can either use kill command after finding the PID of httpd process as shown here or you can use the apachectl script as shown below to start and stop Apache web server in Linux

Starting Apache web server in Linux

$ apachectl start

Stopping Apache web server in Linux

$ apachectl stop

Restarting Apache web server in Linux

$ apachectl restart

or:

/sbin/service httpd restart

You might need root access to do if Apache web server is not running on your application account.

42. What Is The Difference Between Jdbc And Jndi?

As I said in the previous answer, the JDBC stands for Java Database Connectivity and provides APIs and guidelines to connect a database from Java, while JNDI stands for Java Naming and Directory Interface and provides a logical structure for retrieving resources e.g. database, messaging queues, enterprise Java beans without knowing their physical place e.g. host or port. You can register a resource with JNDI and then rest of your application component can access them using JNDI name. The database connection pool is the most common resource accessed via JNDI in web servers like Tomcat or WebLogic.

43. What Is Database Connection Pool?

As it name suggests, it just a pool of database connections. Since creating a new database connection in real-time is an expensive process and can potentially slow down the response time, many application maintains a pool of active database connection. When a request comes in they retrieve a connection from the pool, get the data from the database and then return the connection back to pool so that it can be reused. This way, response time is improved in most of the Java web application. See here to setup a database connection pool in Tomcat using Spring framework.

44. Your Java Application Is Connected To A Database Via A Connection Pool. Suddenly Your Database Goes Down? Is That An Issue With Your Java Application? Do You Need To Restart Your Java Application?

hint: Since your Java application is using a connection pool, it has active connections to database which will get disconnected once DB goes down. If you try to execute a query, you will receive Socket errors.

45. How Do You Send Web Service Request From Linux?

There are some commands available in Linux e.g. curl and wget which allows you to send HTTP commands, which you can use to call and test your web services from Linux. Particular, Curl is used extensively to test RESTful Web Services because it can send POST request, GET request, request with headers and also authenticate using both basic and digest authentication.

If you are working with REST API, I suggest learning curl, it's very convenient to check if your API is working properly using curl from the command line. You can even write a script to automate those stuff.

46. What Is The Difference Between Http And Https?

This is one of the common and easy s. Of course, you know the difference between HTTP and HTTPS right? well, HTTP is insecure but HTTPS is secure, the extra "s" is for security, which means it not only encode and encrypt the message before sending but also verify the identity of the server by using  SSL certificates provided by global certificate authorities e.g. GoDaddy, Thawte, VeriSign, Digicert, GeoTrust, and Comodo.  See here to learn more how SSL and Certifications work in Java web application.

47. What Is The Difference Between The Get And Post Method?

Another simple but frequently asked  on Java support interviews. The main difference between the GET and POST is that GET is both idempotent and safe but POST is not. You can fire GET request multiple time and it will give the same result but multiple POST submission should always be avoided. GET is also used to read data from server and POST is used to send data to the server.

48. What Is The Difference Between Servlet And Jsp?

This is another interesting Java JEE support Interview . Even though both Servlet and JSP is used to create dynamic HTML the key difference between them is their purpose. Servlet is meant for Java developers and you write more Java than HTML and that's why it serves as Controller in many popular MVC framework e.g. DispatcherServlet in Spring MVC.

On the other hand, JSP is designed for HTML developers and it's more HTML than Java and that's why it is used as "view" in MVC frameworks like Spring and Struts. See the link in the answer for more detailed comparison.

49. What Is The Difference Between Struts And Spring Mvc?

This is again a popular and frequently asked  on Java JEE Interviews. Even though both are popular web MVC framework for Java applications, the key difference is that Spring brings dependency injection first and Struts brings it later using Struts 2.0.

Spring is also a suite of libraries e.g. you get Spring Security to implement security in your application, then there is Spring Boot, Spring Data, Spring Cloud and many more useful libraries under Spring umbrella.

50. What Is The Difference Between Jdbc And Hibernate?

There are many differences between JDBC and Hibernate but the most important one is that JDBC provides an API to connect to the database and execute the query but Hibernate is an ORM (Object Relational modeling) framework, which means it allows you to work with objects while it takes care of saving and retrieving object from database.

In short, in JDBC you need to write SQL queries to get and store data from database but in Hibernate you just deal with objects, Hibernate takes care of issuing SQL queries to the database.

51. What Is The Difference Between Stack Memory And Heap? Which One Is Faster?

These are just two different memory areas used to store different kinds of variables. The stack is local to every thread while heap memory is shared among all threads. Since Stack is closer to thread and usually implemented using CPU registers they are faster than heap memory. The stack is used to store local variables as well method call frames while heap is used to store objects and class metadata. See the detailed answer for more points.

52. Your Java Application Is Connecting To Another Java Application (server) Running On The Remote Host And Listening On Port 17865. Now, You Don't Have Access To That Remote Host To Go And See If The Process Is Running. How Do Find If The Server Is Up And Running?

you can use the telnet command.

53. You Are Supporting A Java Web Application Which Connects To Many Core Java Process And Gets Data From Them To The Distribution To Clients? One Client Complains That The Request For Data Is Taking Too Long And It's Almost Like Hung? How Do You Troubleshoot This Problem?

check the log, check database, check the file system

54. The Java Application You Support Connects To A Database Via A Dns, Which Automatically Switches To The Secondary Database Server When The Primary Goes Down. You Find That In The Event Of A Failover, Your Java Application Is Not Connecting To Secondary Db Server? How Do You Troubleshoot This Problem?

check which version your Java application is running. Some JRE caches the DNS e.g. JRE 1.6

55. What Is A Deadlock? How Do You Find If Your Java Program Has A Deadlock?

The deadlock is a condition which can occur between two or multiple threads. In this case, each of the thread waits for each other and cannot progress. In Java, this usually happens when thread 1 holds the lock required by thread 2 and thread 2 holds the lock required by thread 1. If your Java program is hung then it could be a deadlock. You can take a thread dump and find out if any thread is waiting for the lock hold by other and vice-versa. You can also use jConsole tool to find deadlock.

56. What Is The Race Condition?

The race condition is another multithreading and concurrency bug which happens due to racing between two threads, for example, if one thread is updating a variable and second thread tries to read the value before it finished. You can avoid race conditions by properly synchronizing your code.

57. What Is The Difference Between Path And Classpath?

Both are key environment variable used by Java platform, but the key difference between them is that PATH points to the JDK binaries or native libraries e.g. java.exe, while CLASSPATH points to Java binaries e.g. JAR files, which contains bytecode. PATH is also system level concept independent of Java but CLASSPATH is purely Java concept and used by JVM to load classes required by Java application you are running.

58. How Do You Find The Java Version Used By Your Application?

You can run the java -version command in the command prompt to find out the version of Java used by your application. If you have multiple JDK or JRE installed then make sure you use the one which is used by your application.

59. What Is The Main Difference Between Java Platform And Other Platforms?

The Java platform differs from most other platforms in the sense that it’s a software-based platform that runs on top of other hardware-based platforms.It has two components:

Runtime Environment

API(Application Programming Interface)

60. When Abstract Methods Are Used?

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

61. What Are Wrapper Classes?

These are classes that allow primitive types to be accessed as objects. Example: Integer, Character, Double, Boolean etc.

62. What Do You Mean By Platform Independence?

Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

63. What Is A Pointer And Does Java Support Pointers?

Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn’t support the usage of pointers.

64. What Is The Difference Between Creating String As New() And Literal?

When we create string with new() Operator, it’s created in heap and not added into string pool while String created using literal are created in String pool itself which exists in PermGen area of heap.

String s = new String(“Test”);

does not  put the object in String pool , we need to call String.intern() method which is used to put  them into String pool explicitly. its only when you create String object as String literal e.g. String s = “Test” Java automatically put that into String pool. (  Deloitte JAVA interview s )

65. What Is The Use Of The Finally Block? Is Finally Block In Java Guaranteed To Be Called? When Finally Block Is Not Called?

Finally is the block of code that executes always. The code in finally block will execute even if an exception is occurred. Finally block is NOT called in following conditions

If the JVM exits while the try or catch code is being executed, then the finally block may not execute. This may happen due to System.exit() call.

if the thread executing the try or catch code is interrupted or killed, the finally block may not execute even though the application as a whole continues.

If a exception is thrown in finally block and not handled then remaining code in finally block may not be executed.

66. What’s The Difference Between The Methods Sleep() And Wait()?

The code sleep(2000); puts thread aside for exactly two seconds. The code wait(2000), causes a wait of up to two second. A thread could stop waiting earlier if it receives the notify() or notifyAll() call. The method wait() is defined in the class Object and the method sleep() is defined in the class Thread.

67. What Is The Difference Between An Interface And An Abstract Class ?

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.

68. Difference Between Final, Finally And Finalize ?

Final is used to apply restrictions on class, method and variable. Final class can’t be inherited, final method can’t be overridden and final variable value can’t be changed.

Finally is used to place important code, it will be executed whether exception is handled or not.

Finalize is used to perform clean up processing just before object is garbage collected.

Core Java Tutorial

 Java Programmer Jobs

 All Interview s

69. For Every Interface Written In A Java File, .class File Will Be Generated After Compilation? True Or False?

True. For every interface written in a java file, .class file will be generated after compilation.

70. Can You Identify The Error In The Below Code? Interface A { Private Int I; }

Illegal modifier for field i. Only public, static and final are allowed.

71. What Will Be The Output Of The Following Program?

Interface A

{

Void Mymethod();

}

Class B

{

Public Void My Method()

{

System.out.println("my Method");

}

}

Class C Extends B Implements A

{

}

Class Main Class

{

Public Static Void Main(string[] Args)

{

A A = New C();

A.mymethod();

}

}

My Method

72. Can A Class Implement More Than One Interfaces?

Yes, a class can implement more than one interfaces.

73. Why The Below Code Is Showing Compile Time Error?

Interface X

{

Void Method X();

}

Class Y Implements X

{

Void Methodx()

{

System.out.println("method X");

}>br> }

Interface methods must be implemented as public. Because, interface methods are public by default and you should not reduce the visibility of any methods while overriding.

74. Does Below Code Compile Successfully? If Not, Why?

Interface A

{

Int I = 111;

}

Class B Implements A

{

Void Methodb()

{

I = 222;

}

}

No, because interface fields are static and final by default and you can’t change their value once they are initialized. In the above code, methodB() is changing value of interface field A.i. It shows compile time error.

75. Is The Following Code Written Correctly?

Class A

{

//class A

}

Interface B Extends A

{

//interface B Extending Class A

}

No. An interface can extend another interface not the class.

76. What Will Be The Output Of The Following Program?

Interface P

{

String P = "pppp";

String Methodp();

}

Interface Q Extends P

{

String Q = "qqqq";

String Methodq();

}

Class R Implements P, Q

{

Public String Methodp()

{

Return Q+p;

}

Public String Methodq()

{

Return P+q;

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

R R = New R();

System.out.println(r.methodp());

System.out.println(r.methodq());

}

}

QQQQPPPP

PPPPQQQQ

77. Can Interfaces Have Constructor?

No. Interfaces can’t have constructors.

78. Is The Below Program Written Correctly? If Yes, What Will Be The Output?

Class A Implements B

{

Public Int Methodb(int I)

{

Return I =+ I * I;

}

}

Interface B

{

Int Methodb(int I);

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

B B = New A();

System.out.println(b.methodb(2));

}

}

Yes, program is written correctly. Output will be,

4

79. Can You Find Out The Errors In The Following Code?

Interface A

{

{

System.out.println("interface A");

}

Static

{

System.out.println("interface A");

}

}

Interfaces can’t have initializers.

80. How Do You Access Interface Field ‘i’ In The Below Code?

Class P

{

Interface Q

{

Int I = 111;

}

}

P.Q.i

81. Like Classes In Java, Interfaces Also Extend Java.lang.object Class By Default. True Or False?

False. Interfaces don’t extend Object class.

82. Does Below Program Compile Successfully?

Interface Abc

{

Public Void Methodone();

Public Void Methodtwo();

}

Interface Pqr Extends Abc

{

Public Void Methodone();

Public Void Methodtwo();

}

Yes, program compiles successfully.

83. Can Interfaces Have Static Methods?

Yes, from Java 8, interfaces can have static methods

84. Is The Following Program Written Correctly? If Yes, What Will Be The Output?

Interface Abc

{

Void Methodone();

}

Interface Pqr Extends Abc

{

Void Methodtwo();

}

Abstract Class Xyz Implements Pqr

{

Public Void Methodone()

{

Methodtwo();

}

}

Class Mno Extends Xyz

{

Public Void Methodtwo()

{

Methodone();

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

Abc Abc = New Mno();

Abc.methodone();

}

}

Yes, program is written is correctly. But, it will throw StackOverflowError at run time. Because, methodOne() and methodTwo() are cyclicly called.

85. What Will Be The Output Of The Following Program?

Interface X

{

Char C = 'a';

Char Methodx();

}

Class Y Implements X

{

{

System.out.println(c);

}

Public Char Methodx()

{

Char C = This.c;

Return ++c;

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

Y Y = New Y();

System.out.println(y.methodx());

System.out.println(y.c);

System.out.println(x.c);

}

}

A

B

A

A

86. Can You Identify The Error In The Below Code?

Interface A

{

Void Methoda();

}

Class B Implements A

{

Public Void Methoda()

{

Interface C

{

Int I = 123;

}

}

}

Interfaces can’t be local members of a method.

87. Can We Declare An Interface As ‘abstract’?

Yes, interfaces can be declared as ‘abstract’. But, there is no need to declare like that because interfaces are ‘abstract’ by default.

88. What Will Be The Output Of The Following Program?

Interface One

{

String S = "final";

String Methodone();

}

Interface Two

{

String Methodone();

}

Abstract Class Three

{

String S = "not Final";

Public Abstract String Methodone();

}

Class Four Extends Three Implements One, Two

{

Public String Methodone()

{

String S = Super.s + One.s;

Return S;

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

Four Four = New Four();

System.out.println(four.methodone());

One One = Four;

System.out.println(one.s);

}

}

NOT FINALFINAL

FINAL

89. What Will Be The Output Of The Below Program?

Interface X

{

Void Method();

}

Class Y

{

Public Void Method()

{

System.out.println("class Y");

}

}

Class Z Extends Y Implements X

{

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

X X = New Z();

X.method();

}

}

CLASS Y

90. Can Interfaces Have Methods Other Than Abstract?

Yes, from Java 8, interfaces can have static methods and default methods other than abstract methods.

91. What Will Be The Output Of The Following Program?

Interface A

{

Int Methoda();

}

Interface B

{

Int Methodb();

}

Interface C

{

Int Methodc();

}

Class D Implements A, B, C

{

Int I = 999+111;

Public Int Methoda()

{

I =+ I / I;

Return I;

}

Public Int Methodb()

{

I =- I * I;

Return I;

}

Public Int Methodc()

{

I = ++i - --i;

Return I;

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

D D = New D();

System.out.println(d.i);

System.out.println(d.methoda());

System.out.println(d.methodb());

System.out.println(d.methodc());

}

}

1110

1

-1

1

92. How Do You Print The Value Of Field ‘i’ Of Interface ‘onetwothree’ In The Below Example And What Will Be The It’s Value?

Interface One

{

Int I = 222;

Interface Onetwo

{

Int I = One.i+one.i;

Interface Onetwothree

{

Int I = Onetwo.i + Onetwo.i;

}

}

}

Printing ‘i’ value —> System.out.println(One.OneTwo.OneTwoThree.i)

Value of One.OneTwo.OneTwoThree.i will be 888.

93. All Members Of Interface Are Public By Default. True Or False?

True.

94. What Will Be The Output Of The Following Program?

Interface A

{

String A = "aaa";

String Methoda();

}

Interface B

{

String B = "bbb";

String Methodb();

}

Class C Implements A, B

{

Public String Methoda()

{

Return A+b;

}

Public String Methodb()

{ Return B+a;

}

}

Class D Extends C Implements A, B

{ String D = "ddd";

Public String Methoda()

{ Return D+methodb();

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

C C = New C();

System.out.println(c.methoda());

System.out.println(c.methodb());

C = New D();

System.out.println(c.methoda());

System.out.println(c.methodb());

}

}

AAABBB

BBBAAA

DDDBBBAAA

BBBAAA

95. Is The Below Program Written Correctly? If Yes, What Will Be The Output?

Interface X

{

Void Methodx();

Interface Y

{

Void Method();

}

}

Class Z Implements X, X.y

{

{

Method();

System.out.println(1);

}

Public Void Methodx()

{

Methody();

System.out.println(2);

}

Public Void Methody()

{

System.out.println(3);

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

Z Z = New Z();

Z.methodx();

Z.methody();

X X = Z;

X.methodx();

}

}

Yes, program is correct. Output will be,

3

2

1

3

2

3

3

96. Can You Identify The Error In The Below Code?

Class A Implements A.b

{

Static Interface B

{

Void Methodb();

}

}

Cycle detected. Any class cannot extend itself or it’s member types.

97. Interfaces Are Abstract And Public By Default. True Or False?

False. Interfaces are abstract by default but not public.

98. Can You Identify The Error In The Below Code?

Interface X

{

Void Methodx();

}

Interface Y Extends X

{

Void Methody();

}

Class Z Implements Y

{

Public Void Methody()

{

System.out.println("method Y");

}

}

Class Z must implement methodX() also.

99. Can We Define Interface As Generic?

Yes, we can define generic interface

100. What Will Be The Output Of The Following Program?

Abstract Class A

{

Abstract Void Mymethod(number N);

}

Interface B

{

Abstract Void Mymethod(object O);

}

Class C Extends A Implements B

{

Void Mymethod(number N)

{

System.out.println("number");

}

Public Void Mymethod(object O)

{

System.out.println("object");

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

A A = New C();

A.mymethod(new Integer(121));

B B = New C();

B.mymethod(new Integer(121));

C C = New C();

C.mymethod(new Integer(121));

}

}

Number

Object

Number

101. Is The Below Program Written Correctly? If Yes, What Will Be The Output?

Interface I {

Class C

{

Int I;

Public C(int I)

{

This.i = ++i;

}

Int Methodc()

{

Return ++i;

}

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

I.c C = New I.c(000);

System.out.println(c.method());

}

}

Yes, program is written correctly. Output will be,

2

102. What Will Be The Output Of The Following Program?

Class A { }

Class B Extends A { }

Class C Extends B { }

Interface Abc

{

Void Method(a A);

}

Interface Pqr

{

Void Method(b B);

}

Class M Implements Abc, Pqr

{

Public Void Method(a A)

{

System.out.println(2);

}

Public Void Method(b B)

{

System.out.println(3);

}

}

Public Class Mainclass

{

Public Static Void Main(string[] Args)

{

M M = New M();

M.method(new A());

M.method(new B());

M.method(new C());

}

}

 

2

3

3

103. Can You Identify The Errors In The Below Code?

Interface I

{

Class C Implements I

{

Public Void Method(int I)

{

System.out.println(i);

}

}

Void Method(int I);

}

No errors.

104. What Is The Most Important Feature Of Java?

Java is a platform independent language.

105. What Do You Mean By Platform Independence?

Platform independence means that we can write and compile the java code in one platform (eg Windows) and can execute the class in any other supported platform eg (Linux,Solaris,etc).

106. Are Jvm's Platform Independent?

JVM's are not platform independent. JVM's are platform specific run time implementation provided by the vendor.

107. What Is A Jvm?

JVM is Java Virtual Machine which is a run time environment for the compiled java class files.

108. What Is The Difference Between A Jdk And A Jvm?

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.

109. What Is A Pointer And Does Java Support Pointers?

Pointer is a reference handle to a memory location. Improper handling of pointers leads to memory leaks and reliability issues hence Java doesn't support the usage of pointers.

110. What Is The Base Class Of All Classes?

java.lang.Object

111. Does Java Support Multiple Inheritance?

Java doesn't support multiple inheritance.

112. Is Java A Pure Object Oriented Language?

Java uses primitive data types and hence is not a pure object oriented language.

113. Are Arrays Primitive Data Types?

In Java, Arrays are objects.

114. What Is Difference Between Path And Classpath?

Path and Classpath are operating system level environment variales. Path is used define where the system can find the executables(.exe) files and classpath is used to specify the location .class files.

115. What Are Local Variables?

Local varaiables are those which are declared within a block of code like methods. Local variables should be initialised before accessing them.

116. What Are Instance Variables?

Instance variables are those which are defined at the class level. Instance variables need not be initialized before using them as they are automatically initialized to their default values.

117. How To Define A Constant Variable In Java?

The variable should be declared as static and final. So only one copy of the variable exists for all instances of the class and the value can't be changed also. static final int PI = 2.14; is an example for constant.

118. Should A Main Method Be Compulsorily Declared In All Java Classes?

No not required. main method should be defined only if the source class is a java application.

119. What Is The Return Type Of The Main Method?

Main method doesn't return anything hence declared void.

120. Why Is The Main Method Declared Static?

main method is called by the JVM even before the instantiation of the class hence it is declared as static.

121. What Is The Arguement Of Main Method?

main method accepts an array of String object as arguement.

122. Can A Main Method Be Overloaded?

Yes. You can have any number of main methods with different method signature and implementation in the class.

123. Can A Main Method Be Declared Final?

Yes. Any inheriting class will not be able to have it's own default main method.

124. Does The Order Of Public And Static Declaration Matter In Main Method?

No it doesn't matter but void should always come before main().

125. Can A Source File Contain More Than One Class Declaration?

Yes a single source file can contain any number of Class declarations but only one of the class can be declared as public.

126. What Is A Package?

Package is a collection of related classes and interfaces. package declaration should be first statement in a java class.

127. Which Package Is Imported By Default?

java.lang package is imported by default even without a package declaration.

128. Can A Class Declared As Private Be Accessed Outside It's Package?

Not possible.

129. Can A Class Be Declared As Protected?

A class can't be declared as protected. only methods can be declared as protected.

130. What Is The Access Scope Of A Protected Method?

A protected method can be accessed by the classes within the same package or by the subclasses of the class in any package.

131. What Is The Purpose Of Declaring A Variable As Final?

A final variable's value can't be changed. final variables should be initialized before using them.

132. What Is The Impact Of Declaring A Method As Final?

A method declared as final can't be overridden. A sub-class can't have the same method signature with a different implementation.

134. I Don't Want My Class To Be Inherited By Any Other Class. What Should I Do?

You should declared your class as final. But you can't define your class as final, if it is an abstract class. A class declared as final can't be extended by any other class.

135. Can You Give Few Examples Of Final Classes Defined In Java Api?

java.lang.String,java.lang.Math are final classes.

136. How Is Final Different From Finally And Finalize?

final is a modifier which can be applied to a class or a method or a variable. final class can't be inherited, final method can't be overridden and final variable can't be changed.

finally is an exception handling code section which gets executed whether an exception is raised or not by the try block code segment.

finalize() is a method of Object class which will be executed by the JVM just before garbage collecting object to give a final chance for resource releasing activity.

137. Can A Class Be Declared As Static?

No a class cannot be defined as static. Only a method,a variable or a block of code can be declared as static.

138. When Will You Define A Method As Static?

When a method needs to be accessed even before the creation of the object of the class then we should declare the method as static.

139. What Are The Restriction Imposed On A Static Method Or A Static Block Of Code?

A static method should not refer to instance variables without creating an instance and cannot use "this" operator to refer the instance.

140. I Want To Print "hello" Even Before Main Is Executed. How Will You Acheive That?

Print the statement inside a static block of code. Static blocks get executed when the class gets loaded into the memory and even before the creation of an object. Hence it will be executed before the main method. And it will be executed only once.

141. What Is The Importance Of Static Variable?

static variables are class level variables where all objects of the class refer to the same variable. If one object changes the value then the change gets reflected in all the objects.

142. Can We Declare A Static Variable Inside A Method?

Static variables are class level variables and they can't be declared inside a method. If declared, the class will not compile.

143. What Is An Abstract Class And What Is It's Purpose?

A Class which doesn't provide complete implementation is defined as an abstract class. Abstract classes enforce abstraction.

144. Can A Abstract Class Be Declared Final?

Not possible. An abstract class without being inherited is of no use and hence will result in compile time error.

145. What Is Use Of A Abstract Variable?

Variables can't be declared as abstract. only classes and methods can be declared as abstract.

146. Can You Create An Object Of An Abstract Class?

Not possible. Abstract classes can't be instantiated.

147. Can A Abstract Class Be Defined Without Any Abstract Methods?

Yes it's possible. This is basically to avoid instance creation of the class.

148. Class C Implements Interface I Containing Method M1 And M2 Declarations. Class C Has Provided Implementation For Method M2. Can I Create An Object Of Class C?

No not possible. Class C should provide implementation for all the methods in the Interface I. Since Class C didn't provide implementation for m1 method, it has to be declared as abstract. Abstract classes can't be instantiated.

149. Can A Method Inside A Interface Be Declared As Final?

No not possible. Doing so will result in compilation error. public and abstract are the only applicable modifiers for method declaration in an interface.

150. Can An Interface Implement Another Interface?

Intefaces doesn't provide implementation hence a interface cannot implement another interface.

151. Can An Interface Extend Another Interface?

Yes an Interface can inherit another Interface, for that matter an Interface can extend more than one Interface.

152. Can A Class Extend More Than One Class?

Not possible. A Class can extend only one class but can implement any number of Interfaces.

153. Why Is An Interface Be Able To Extend More Than One Interface But A Class Can't Extend More Than One Class?

Basically Java doesn't allow multiple inheritance, so a Class is restricted to extend only one Class. But an Interface is a pure abstraction model and doesn't have inheritance hierarchy like classes(do remember that the base class of all classes is Object). So an Interface is allowed to extend more than one Interface.

154. Can An Interface Be Final?

Not possible. Doing it will result in compilation error.

155. Can A Class Be Defined Inside An Interface?

Yes it's possible.

156. Can An Interface Be Defined Inside A Class?

Yes it's possible.

157. What Is A Marker Interface?

An Interface which doesn't have any declaration inside but still enforces a mechanism.

158. Which Oo Concept Is Achieved By Using Overloading And Overriding?

Polymorphism.

159. If I Only Change The Return Type, Does The Method Become Overloaded?

No it doesn't. There should be a change in method arguements for a method to be overloaded.

160. Why Does Java Not Support Operator Overloading?

Operator overloading makes the code very difficult to read and maintain. To maintain code simplicity, Java doesn't support operator overloading.

161. Can We Define Private And Protected Modifiers For Variables In Interfaces?

No

162. What Is Externalizable?

Externalizable is an Interface that extends Serializable Interface. And sends data into Streams in Compressed Format. It has two methods, writeExternal(ObjectOuput out) and readExternal(ObjectInput in)

163. What Modifiers Are Allowed For Methods In An Interface?

Only public and abstract modifiers are allowed for methods in interfaces.

164. What Is A Local, Member And A Class Variable?

Variables declared within a method are "local" variables. Variables declared within the class i.e not within any methods are "member" variables (global variables). Variables declared within the class i.e not within any methods and are defined as "static" are class variables.

165. What Is An Abstract Method?

An abstract method is a method whose implementation is deferred to a subclass.

166. What Value Does Read() Return When It Has Reached The End Of A File?

The read() method returns -1 when it has reached the end of a file.

167. Can A Byte Object Be Cast To A Double Value?

No, an object cannot be cast to a primitive value.

168. What Is The Difference Between A Static And A Non-static Inner Class?

A non-static inner class may have object instances that are associated with instances of the class's outer class. A static inner class does not have any object instances.

169. What Is An Object's Lock And Which Object's Have Locks?

An object's lock is a mechanism that is used by multiple threads to obtain synchronized access to the object. A thread may execute a synchronized method of an object only after it has acquired the object's lock. All objects and classes have locks. A class's lock is acquired on the class's Class object.

170. What Is The % Operator?

It is referred to as the modulo or remainder operator. It returns the remainder of dividing the first operand by the second operand.

171. When Can An Object Reference Be Cast To An Interface Reference?

An object reference be cast to an interface reference when the object implements the referenced interface.

172. Which Class Is Extended By All Other Classes?

The Object class is extended by all other classes.

173. Which Non-unicode Letter Characters May Be Used As The First Character Of An Identifier?

The non-Unicode letter characters $ and _ may appear as the first character of an identifier.

174. What Restrictions Are Placed On Method Overloading?

Two methods may not have the same name and argument list but different return types.

175. What Is Transient Variable?

Transient variable can't be serialize. For example if a variable is declared as transient in a Serializable class and the class is written to an ObjectStream, the value of the variable can't be written to the stream instead when the class is retrieved from the ObjectStream the value of the variable becomes null.

176. What Is Collection Api?

The Collection API is a set of classes and interfaces that support operation on collections of objects. These classes and interfaces are more flexible, more powerful, and more regular than the vectors, arrays, and hashtables if effectively replaces.

Example of classes: HashSet, HashMap, ArrayList, LinkedList, TreeSet and TreeMap.

Example of interfaces: Collection, Set, List and Map.

177. What Is Casting?

There are two types of casting, casting between primitive numeric types and casting between object references. Casting between numeric types is used to convert larger values, such as double values, to smaller values, such as byte values. Casting between object references is used to refer to an object by a compatible class, interface, or array type reference.

178. What Is The Return Type Of A Program's Main() Method?

void.

179. If A Variable Is Declared As Private, Where May The Variable Be Accessed?

A private variable may only be accessed within the class in which it is declared.

180. What Do You Understand By Private, Protected And Public?

These are accessibility modifiers. Private is the most restrictive, while public is the least restrictive. There is no real difference between protected and the default type (also known as package protected) within the context of the same package, however the protected keyword allows visibility to a derived class in a different package.

181. What Is Downcasting ?

Downcasting is the casting from a general to a more specific type, i.e. casting down the hierarchy.

182. What Modifiers May Be Used With An Inner Class That Is A Member Of An Outer Class?

A (non-local) inner class may be declared as public, protected, private, static, final, or abstract.

183. How Many Bits Are Used To Represent Unicode, Ascii, Utf-16, And Utf-8 Characters?

Unicode requires 16 bits and ASCII require 7 bits. Although the ASCII character set uses only 7 bits, it is usually represented as 8 bits. UTF-8 represents characters using 8, 16, and 18 bit patterns. UTF-16 uses 16-bit and larger bit patterns.

184. What Restrictions Are Placed On The Location Of A Package Statement Within A Source Code File?

A package statement must appear as the first line in a source code file (excluding blank lines and comments).