SlideShare uma empresa Scribd logo
1 de 17
Baixar para ler offline
20 Most Important Java Programming Interview Questions 
Powered by –
1. What's the difference between an interface and an abstract class?  An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.  An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.  Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.  Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.  When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.  A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.  A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility. 2. When to use abstract class or interface?  Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.  If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
 Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that on mind before choosing.  Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.  Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts. 3. What does the Serializable interface do?  The Serializable interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string. For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system cannot be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.  Serializing objects that don't implement the Serializable interface will result in a NotSerializableException being thrown. 4. How you can force the garbage collection?  Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.  Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.  Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to
explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 5. What is Synchronization in Java?  Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time.  In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. 6. What is memory leak?  A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn‘t get garbage collected. 7. What is difference between stringbuffer and stringbuilder?  The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.  Criteria to choose among StringBuffer and StringBuilder  If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.  If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous. 8. What is the difference between checked and unchecked exceptions?  In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
 Furthermore, checked exceptions represent invalid conditions in areas outside the immediate control of the program. 9. How does Java allocate stack and heap memory?  Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class).  In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.  In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.  The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code. 10. What is Java Reflection?  Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. 11. What is JVM? Why Java is called the ‘Platform Independent Programming Language’? JVM, or the Java Virtual Machine, is an interpreter which accepts ‗Bytecode‘ and executes it. Java has been termed as a ‗Platform Independent Language‘ as it primarily works on the notion of ‗compile once, run everywhere‘. Here‘s a sequential step establishing the Platform independence feature in Java:  The Java Compiler outputs Non-Executable Codes called ‗Bytecode‘.  Bytecode is a highly optimized set of computer instruction which could be executed by the Java Virtual Machine (JVM).  The translation into Bytecode makes a program easier to be executed across a wide range of platforms, since all we need is a JVM designed for that particular platform.
 JVMs for various platforms might vary in configuration, those they would all understand the same set of Bytecode, thereby making the Java Program ‗Platform Independent‘. 12. What is the Difference between JDK and JRE? When asked typical Java Interview Questions most startup Java developers get confused with JDK and JRE. And eventually, they settle for ‗anything would do man, as long as my program runs!!‘ Not quite right if you aspire to make a living and career out of Programming. The ―JDK‖ is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The ―JRE‖ is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE‘s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc. 13. What does the ‘static’ keyword mean? We are sure you must be well-acquainted with the Java Basics. Now that we are settled with the initial concepts, let‘s look into the Language specific offerings. Static variable is associated with a class and not objects of that class. For example: public class ExplainStatic { public static String name = "Look I am a static variable"; }
We have another class where-in we intend to access this static variable just defined. public class Application { public static void main(String[] args) { System.out.println(ExplainStatic.name) } } We don‘t create object of the class ExplainStatic to access the static variable. We directly use the class name itself: ExplainStatic.name 14. What are the Data Types supported by Java? What is Autoboxing and Unboxing? This is one of the most common and fundamental Java interview questions. This is something you should have right at your finger-tips when asked. The eight Primitive Data types supported by Java are:  Byte : 8-bit signed two‘s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)  Short: 16-bit signed two‘s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).  Int: 32-bit signed two‘s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)  Long: 64-bit signed two‘s complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)  Float  Double
Autoboxing: The Java compiler brings about an automatic transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float, Double,etc) for the ease of compilation. Unboxing: The automatic transformation of wrapper types into their primitive equivalent is known as Unboxing. 15. What is the difference between STRINGBUFFER and STRING? String object is immutable. i.e, the value stored in the String object cannot be changed. Consider the following code snippet: String myString = ―Hello‖; myString = myString + ‖ Guest‖; When you print the contents of myString the output will be ―Hello Guest‖. Although we made use of the same object (myString), internally a new object was created in the process. That‘s a performance issue. StringBuffer/StringBuilder objects are mutable: StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
String str = ―Be Happy With Your Salary.'' str += ―Because Increments are a myth"; StringBuffer strbuf = new StringBuffer(); strbuf.append(str); System.out.println(strbuf); The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth. 16. What is Function Over-Riding and Over-Loading in Java? This is a very important concept in OOP (Object Oriented Programming) and is a must-know for every Java Programmer. Over-Riding: An override is a type of function which occurs in a class which inherits from another class. An override function ―replaces‖ a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. That probably was a little over the top. The code snippet below should explain things better. public class Car { public static void main (String [] args) { Car a = new Car(); Car b = new Ferrari(); //Car ref, but a Ferrari object
a.start(); // Runs the Car version of start() b.start(); // Runs the Ferrari version of start() } } class Car { public void start() { System.out.println("This is a Generic start to any Car"); } }class Ferrari extends Car { public void start() { System.out.println("Let‘s start the Ferrari and go out for a cool Party.");} } Over-Loading: Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism. Functions in Java could be overloaded by two mechanisms ideally:  Varying the number of arguments.  Varying the Data Type. class CalculateArea{ void Area(int length){System.out.println(length*2);}
void Area(int length , int width){System.out.println(length*width);} public static void main(String args[]){ CalculateArea obj=new CalculateArea(); obj.Area(10); // Area of a Square obj.Area(20,20); // Area of a Rectangle } } 17. What is Constructors, Constructor Overloading in Java and Copy- Constructor? Constructors form the basics of OOPs, for starters. Constructor: The sole purpose of having Constructors is to create an instance of a class. They are invoked while creating an object of a class. Here are a few salient features of Java Constructors:  Constructors can be public, private, or protected.  If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor – you have to write one.  They are called only once when the class is being instantiated.  They must have the same name as the class itself.  They do not return a value and you do not have to specify the keyword void.  If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor.
public class Boss{ String name; Boss(String input) { //This is the constructor name = "Our Boss is also known as : " + input; } public static void main(String args[]) { Boss p1 = new Boss("Super-Man"); } } Constructor overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows: public class Boss{ String name; Boss(String input) { //This is the constructor name = "Our Boss is also known as : " + input; } Boss() { name = "Our Boss is a nice man. We don‘t call him names.‖;
} public static void main(String args[]) { Boss p1 = new Boss("Super-Man"); Boss p2 = new Boss(); } } Copy Constructor: A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter. 
18. What is Java Exception Handling? What is the difference between Errors, Unchecked Exception and Checked Exception? Anything that‘s not Normal is an exception. Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred. In Java, exceptions are objects. When you throw an exception, you throw an object. You can‘t throw just any object as an exception, however — only those object whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. Here‘s a hierarchical Exception class structure:  An Unchecked Exception inherits from RuntimeException (which extends from Exception). The JVM treats RuntimeException differently as there is no requirement for the application-code to deal with them explicitly.  A Checked Exception inherits from the Exception-class. The client code has to handle the checked exceptions either in a try-catch
clause or has to be thrown for the Super class to catch the same. A Checked Exception thrown by a lower class (sub-class) enforces a contract on the invoking class (super-class) to catch or throw it.  Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError (OOM), that may not be so easy to handle. Exception handling needs special attention while designing large applications. So we would suggest you to spend some time brushing up your Java skills. 19. What is the difference between Throw and Throws in Java Exception Handling? Throws: A throws clause lists the types of exceptions that a method might throw, thereby warning the invoking method – ‗Dude. You need to handle this list of exceptions I might throw.‘ Except those of type Error or RuntimeException, all other Exceptions or any of their subclasses, must be declared in the throws clause, if the method in question doesn‘t implement a try…catch block. It is therefore the onus of the next-on-top method to take care of the mess. public void myMethod() throws PRException {..} This means the super function calling the function should be equipped to handle this exception. public void Callee() { try{ myMethod();
}catch(PRException ex) { ...handle Exception....} } Using the Throw: If the user wants to throw an explicit Exception, often customized, we use the Throw. The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. try{ if(age>100){throw new AgeBarException(); //Customized ExceptioN }else{ ....} } }catch(AgeBarException ex){ ...handle Exception..... } 20. What is the Difference between Byte stream and Character streams? Every Java Programmer deals with File Operations. To generate User reports, send attachments through mails and spill out data files from Java programs. And a sound knowledge on File Operation becomes even more important while dealing with Java questions.
Byte stream: For reading and writing binary data, byte stream is incorporated. Programs use byte streams to perform byte input and output.  Performing InputStream operations or OutputStream operations means generally having a loop that reads the input stream and writes the output stream one byte at a time.  You can use buffered I/O streams for an overhead reduction (overhead generated by each such request often triggers disk access, network activity, or some other operation that is relatively expensive). Character streams: Character streams work with the characters rather than the byte. In Java, characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage, characters become the platform independent, program independent, language independent.
Study on the go; get high quality complete preparation courses now on your mobile!

Mais conteúdo relacionado

Mais procurados

Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Languagejaimefrozr
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletFahmi Jafar
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Javaparag
 
Java Presentation
Java PresentationJava Presentation
Java PresentationAmr Salah
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaEdureka!
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring FrameworkHùng Nguyễn Huy
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVAAnkita Totala
 
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMJava Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMshamnasain
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.pptVMahesh5
 

Mais procurados (20)

Introduction to Java Programming Language
Introduction to Java Programming LanguageIntroduction to Java Programming Language
Introduction to Java Programming Language
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
JDK,JRE,JVM
JDK,JRE,JVMJDK,JRE,JVM
JDK,JRE,JVM
 
Java architecture
Java architectureJava architecture
Java architecture
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Knowledge Sharing : Java Servlet
Knowledge Sharing : Java ServletKnowledge Sharing : Java Servlet
Knowledge Sharing : Java Servlet
 
Exception Handling In Java
Exception Handling In JavaException Handling In Java
Exception Handling In Java
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
JVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdfJVM Under The Hood WDI.pdf
JVM Under The Hood WDI.pdf
 
Java Presentation
Java PresentationJava Presentation
Java Presentation
 
Spring Boot Interview Questions | Edureka
Spring Boot Interview Questions | EdurekaSpring Boot Interview Questions | Edureka
Spring Boot Interview Questions | Edureka
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Data Types & Variables in JAVA
Data Types & Variables in JAVAData Types & Variables in JAVA
Data Types & Variables in JAVA
 
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVMJava Virtual Machine (JVM), Difference JDK, JRE & JVM
Java Virtual Machine (JVM), Difference JDK, JRE & JVM
 
Exception Handling in Java
Exception Handling in JavaException Handling in Java
Exception Handling in Java
 
Introduction to Java
Introduction to JavaIntroduction to Java
Introduction to Java
 
Core java
Core javaCore java
Core java
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Servlet.ppt
Servlet.pptServlet.ppt
Servlet.ppt
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 

Destaque

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)Alok Kumar
 
Open Source - Bзгляд из вражeскoгo лагeря
Open Source - Bзгляд из вражeскoгo лагeряOpen Source - Bзгляд из вражeскoгo лагeря
Open Source - Bзгляд из вражeскoгo лагeряAndrew Zaikin
 
Java. Lecture 01. Introducing Java
Java. Lecture 01. Introducing JavaJava. Lecture 01. Introducing Java
Java. Lecture 01. Introducing Javacolriot
 
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...CocoaHeads
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overridingPinky Anaya
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Ryan Cuprak
 
Date & Time in Java SE 8
Date & Time in Java SE 8Date & Time in Java SE 8
Date & Time in Java SE 8Ilya Lapitan
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questionsGradeup
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)sunilbhaisora1
 
Մաթեմատիկա
ՄաթեմատիկաՄաթեմատիկա
ՄաթեմատիկաG-College
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questionsDhivyashree Selvarajtnkpm
 
դաս մաթեմատիկա Հասմիկ Ավետիքյան
դաս մաթեմատիկա Հասմիկ Ավետիքյանդաս մաթեմատիկա Հասմիկ Ավետիքյան
դաս մաթեմատիկա Հասմիկ Ավետիքյանwww.mskh.am
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Nishan Barot
 
մաթեմատիկա 4 րդ դասարան
մաթեմատիկա 4 րդ դասարանմաթեմատիկա 4 րդ դասարան
մաթեմատիկա 4 րդ դասարանnordprocmskh
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Ryan Cuprak
 

Destaque (20)

Important java programs(collection+file)
Important java programs(collection+file)Important java programs(collection+file)
Important java programs(collection+file)
 
Open Source - Bзгляд из вражeскoгo лагeря
Open Source - Bзгляд из вражeскoгo лагeряOpen Source - Bзгляд из вражeскoгo лагeря
Open Source - Bзгляд из вражeскoгo лагeря
 
Java. Lecture 01. Introducing Java
Java. Lecture 01. Introducing JavaJava. Lecture 01. Introducing Java
Java. Lecture 01. Introducing Java
 
Java 8. Lambdas
Java 8. LambdasJava 8. Lambdas
Java 8. Lambdas
 
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
Встреча №9. Алгоритмы и коллекции стандартных библиотек C++, C#, Java, Object...
 
Differences between method overloading and method overriding
Differences between method overloading and method overridingDifferences between method overloading and method overriding
Differences between method overloading and method overriding
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
Date & Time in Java SE 8
Date & Time in Java SE 8Date & Time in Java SE 8
Date & Time in Java SE 8
 
մեթոդ և հնար
մեթոդ և հնարմեթոդ և հնար
մեթոդ և հնար
 
Classical programming interview questions
Classical programming interview questionsClassical programming interview questions
Classical programming interview questions
 
Interview questions(programming)
Interview questions(programming)Interview questions(programming)
Interview questions(programming)
 
Մաթեմատիկա
ՄաթեմատիկաՄաթեմատիկա
Մաթեմատիկա
 
Java classes and objects interview questions
Java classes and objects interview questionsJava classes and objects interview questions
Java classes and objects interview questions
 
դաս մաթեմատիկա Հասմիկ Ավետիքյան
դաս մաթեմատիկա Հասմիկ Ավետիքյանդաս մաթեմատիկա Հասմիկ Ավետիքյան
դաս մաթեմատիկա Հասմիկ Ավետիքյան
 
Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.Final JAVA Practical of BCA SEM-5.
Final JAVA Practical of BCA SEM-5.
 
մաթեմատիկա 4 րդ դասարան
մաթեմատիկա 4 րդ դասարանմաթեմատիկա 4 րդ դասարան
մաթեմատիկա 4 րդ դասարան
 
ուսուցման մեթոդներ
ուսուցման մեթոդներուսուցման մեթոդներ
ուսուցման մեթոդներ
 
Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]Top 50 java ee 7 best practices [con5669]
Top 50 java ee 7 best practices [con5669]
 
դասվար թեմատիկ պլան
դասվար թեմատիկ պլանդասվար թեմատիկ պլան
դասվար թեմատիկ պլան
 
Բաց դաս
Բաց դասԲաց դաս
Բաց դաս
 

Semelhante a 20 most important java programming interview questions

Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview QuestionsKuntal Bhowmick
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfnofakeNews
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PunePankaj kshirsagar
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedGaurav Maheshwari
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.netJanbask ItTraining
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedyearninginjava
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questionssatish reddy
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questionssatish reddy
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2Techglyphs
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questionsRohit Singh
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1javatrainingonline
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdfvenud11
 

Semelhante a 20 most important java programming interview questions (20)

Java Interview Questions
Java Interview QuestionsJava Interview Questions
Java Interview Questions
 
1
11
1
 
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdfJAVA VIVA QUESTIONS_CODERS LODGE.pdf
JAVA VIVA QUESTIONS_CODERS LODGE.pdf
 
Core java questions
Core java questionsCore java questions
Core java questions
 
Core_Java_Interview.pdf
Core_Java_Interview.pdfCore_Java_Interview.pdf
Core_Java_Interview.pdf
 
Java interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council PuneJava interview questions and answers for cognizant By Data Council Pune
Java interview questions and answers for cognizant By Data Council Pune
 
Top 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experiencedTop 371 java fa qs useful for freshers and experienced
Top 371 java fa qs useful for freshers and experienced
 
Java questions and answers jan bask.net
Java questions and answers jan bask.netJava questions and answers jan bask.net
Java questions and answers jan bask.net
 
Java Faqs useful for freshers and experienced
Java Faqs useful for freshers and experiencedJava Faqs useful for freshers and experienced
Java Faqs useful for freshers and experienced
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
 
Android interview questions
Android interview questionsAndroid interview questions
Android interview questions
 
Java interview questions
Java interview questionsJava interview questions
Java interview questions
 
Bt0074 oops with java2
Bt0074 oops with java2Bt0074 oops with java2
Bt0074 oops with java2
 
Pocket java
Pocket javaPocket java
Pocket java
 
Core java interview questions
Core java interview questionsCore java interview questions
Core java interview questions
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1Java J2EE Interview Questions Part-1
Java J2EE Interview Questions Part-1
 
Viva file
Viva fileViva file
Viva file
 
1669617800196.pdf
1669617800196.pdf1669617800196.pdf
1669617800196.pdf
 
java basic .pdf
java basic .pdfjava basic .pdf
java basic .pdf
 

Último

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppCeline George
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxmanuelaromero2013
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxheathfieldcps1
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...RKavithamani
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingTechSoup
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactdawncurless
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfciinovamais
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...Marc Dusseiller Dusjagr
 

Último (20)

Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
URLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website AppURLs and Routing in the Odoo 17 Website App
URLs and Routing in the Odoo 17 Website App
 
How to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptxHow to Make a Pirate ship Primary Education.pptx
How to Make a Pirate ship Primary Education.pptx
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
The basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptxThe basics of sentences session 2pptx copy.pptx
The basics of sentences session 2pptx copy.pptx
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
Privatization and Disinvestment - Meaning, Objectives, Advantages and Disadva...
 
Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
 
Staff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSDStaff of Color (SOC) Retention Efforts DDSD
Staff of Color (SOC) Retention Efforts DDSD
 
Grant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy ConsultingGrant Readiness 101 TechSoup and Remy Consulting
Grant Readiness 101 TechSoup and Remy Consulting
 
Accessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impactAccessible design: Minimum effort, maximum impact
Accessible design: Minimum effort, maximum impact
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
“Oh GOSH! Reflecting on Hackteria's Collaborative Practices in a Global Do-It...
 

20 most important java programming interview questions

  • 1. 20 Most Important Java Programming Interview Questions Powered by –
  • 2. 1. What's the difference between an interface and an abstract class?  An abstract class is a class that is only partially implemented by the programmer. It may contain one or more abstract methods. An abstract method is simply a function definition that serves to tell the programmer that the method must be implemented in a child class.  An interface is similar to an abstract class; indeed interfaces occupy the same namespace as classes and abstract classes. For that reason, you cannot define an interface with the same name as a class. An interface is a fully abstract class; none of its methods are implemented and instead of a class sub-classing from it, it is said to implement that interface.  Abstract classes can have constants, members, method stubs and defined methods, whereas interfaces can only have constants and methods stubs.  Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public.  When inheriting an abstract class, the child class must define the abstract methods, whereas an interface can extend another interface and methods don't have to be defined.  A child class can only extend a single abstract (or any other) class, whereas an interface can extend or a class can implement multiple other interfaces.  A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility. 2. When to use abstract class or interface?  Interface is used when you only want to declare which methods and members a class MUST have. Anyone implementing the interface will have to declare and implement the methods listed by the interface.  If you also want to have a default implementation, use abstract class. Any class extending the abstract class will have to implement only its abstract methods and members, and will have some default implementation of the other methods of the abstract class, which you may override or not.
  • 3.  Finally, you can implement as many interfaces as you want, but only extend one class (being it abstract or not). Keep that on mind before choosing.  Abstract class is an incomplete implementation of some concept. This incomplete implementation may be different in different context. Derived class implements the abstract class in its context.  Interface defines contract or standard. Implementation of the interface has to follow the contract or standard. Interfaces are more used to set these types of standards or contracts. 3. What does the Serializable interface do?  The Serializable interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string. For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system cannot be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.  Serializing objects that don't implement the Serializable interface will result in a NotSerializableException being thrown. 4. How you can force the garbage collection?  Garbage collection automatic process and can't be forced. You could request it by calling System.gc(). JVM does not guarantee that GC will be started immediately.  Garbage collection is one of the most important feature of Java, Garbage collection is also called automatic memory management as JVM automatically removes the unused variables/objects (value is null) from the memory. User program can't directly free the object from memory, instead it is the job of the garbage collector to automatically free the objects that are no longer referenced by a program.  Every class inherits finalize() method from java.lang.Object, the finalize() method is called by garbage collector when it determines no more references to the object exists. In Java, it is good idea to
  • 4. explicitly assign null into a variable when no more in use. I Java on calling System.gc() and Runtime.gc(), JVM tries to recycle the unused objects, but there is no guarantee when all the objects will garbage collected. 5. What is Synchronization in Java?  Synchronization is a process of controlling the access of shared resources by the multiple threads in such a manner that only one thread can access one resource at a time.  In non synchronized multithreaded application, it is possible for one thread to modify a shared object while another thread is in the process of using or updating the object's value. 6. What is memory leak?  A memory leak is where an unreferenced object that will never be used again still hangs around in memory and doesn‘t get garbage collected. 7. What is difference between stringbuffer and stringbuilder?  The only difference between StringBuffer and StringBuilder is that StringBuilder is unsynchronized whereas StringBuffer is synchronized. So when the application needs to be run only in a single thread then it is better to use StringBuilder. StringBuilder is more efficient than StringBuffer.  Criteria to choose among StringBuffer and StringBuilder  If your text can change and will only be accessed from a single thread, use a StringBuilder because StringBuilder is unsynchronized.  If your text can changes, and will be accessed from multiple threads, use a StringBuffer because StringBuffer is synchronous. 8. What is the difference between checked and unchecked exceptions?  In general, unchecked exceptions represent defects in the program (bugs), which are normally Runtime exceptions.
  • 5.  Furthermore, checked exceptions represent invalid conditions in areas outside the immediate control of the program. 9. How does Java allocate stack and heap memory?  Each time an object is created in Java it goes into the area of memory known as heap. The primitive variables like int and double are allocated in the stack, if they are local method variables and in the heap if they are member variables (i.e. fields of a class).  In Java methods local variables are pushed into stack when a method is invoked and stack pointer is decremented when a method call is completed.  In a multi-threaded application each thread will have its own stack but will share the same heap. This is why care should be taken in your code to avoid any concurrent access issues in the heap space.  The stack is threadsafe (each thread will have its own stack) but the heap is not threadsafe unless guarded with synchronisation through your code. 10. What is Java Reflection?  Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. 11. What is JVM? Why Java is called the ‘Platform Independent Programming Language’? JVM, or the Java Virtual Machine, is an interpreter which accepts ‗Bytecode‘ and executes it. Java has been termed as a ‗Platform Independent Language‘ as it primarily works on the notion of ‗compile once, run everywhere‘. Here‘s a sequential step establishing the Platform independence feature in Java:  The Java Compiler outputs Non-Executable Codes called ‗Bytecode‘.  Bytecode is a highly optimized set of computer instruction which could be executed by the Java Virtual Machine (JVM).  The translation into Bytecode makes a program easier to be executed across a wide range of platforms, since all we need is a JVM designed for that particular platform.
  • 6.  JVMs for various platforms might vary in configuration, those they would all understand the same set of Bytecode, thereby making the Java Program ‗Platform Independent‘. 12. What is the Difference between JDK and JRE? When asked typical Java Interview Questions most startup Java developers get confused with JDK and JRE. And eventually, they settle for ‗anything would do man, as long as my program runs!!‘ Not quite right if you aspire to make a living and career out of Programming. The ―JDK‖ is the Java Development Kit. I.e., the JDK is bundle of software that you can use to develop Java based software. The ―JRE‖ is the Java Runtime Environment. I.e., the JRE is an implementation of the Java Virtual Machine which actually executes Java programs. Typically, each JDK contains one (or more) JRE‘s along with the various development tools like the Java source compilers, bundling and deployment tools, debuggers, development libraries, etc. 13. What does the ‘static’ keyword mean? We are sure you must be well-acquainted with the Java Basics. Now that we are settled with the initial concepts, let‘s look into the Language specific offerings. Static variable is associated with a class and not objects of that class. For example: public class ExplainStatic { public static String name = "Look I am a static variable"; }
  • 7. We have another class where-in we intend to access this static variable just defined. public class Application { public static void main(String[] args) { System.out.println(ExplainStatic.name) } } We don‘t create object of the class ExplainStatic to access the static variable. We directly use the class name itself: ExplainStatic.name 14. What are the Data Types supported by Java? What is Autoboxing and Unboxing? This is one of the most common and fundamental Java interview questions. This is something you should have right at your finger-tips when asked. The eight Primitive Data types supported by Java are:  Byte : 8-bit signed two‘s complement integer. It has a minimum value of -128 and a maximum value of 127 (inclusive)  Short: 16-bit signed two‘s complement integer. It has a minimum value of -32,768 and a maximum value of 32,767 (inclusive).  Int: 32-bit signed two‘s complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive)  Long: 64-bit signed two‘s complement integer. It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive)  Float  Double
  • 8. Autoboxing: The Java compiler brings about an automatic transformation of primitive type (int, float, double etc.) into their object equivalents or wrapper type (Integer, Float, Double,etc) for the ease of compilation. Unboxing: The automatic transformation of wrapper types into their primitive equivalent is known as Unboxing. 15. What is the difference between STRINGBUFFER and STRING? String object is immutable. i.e, the value stored in the String object cannot be changed. Consider the following code snippet: String myString = ―Hello‖; myString = myString + ‖ Guest‖; When you print the contents of myString the output will be ―Hello Guest‖. Although we made use of the same object (myString), internally a new object was created in the process. That‘s a performance issue. StringBuffer/StringBuilder objects are mutable: StringBuffer/StringBuilder objects are mutable; we can make changes to the value stored in the object. What this effectively means is that string operations such as append would be more efficient if performed using StringBuffer/StringBuilder objects than String objects.
  • 9. String str = ―Be Happy With Your Salary.'' str += ―Because Increments are a myth"; StringBuffer strbuf = new StringBuffer(); strbuf.append(str); System.out.println(strbuf); The Output of the code snippet would be: Be Happy With Your Salary. Because Increments are a myth. 16. What is Function Over-Riding and Over-Loading in Java? This is a very important concept in OOP (Object Oriented Programming) and is a must-know for every Java Programmer. Over-Riding: An override is a type of function which occurs in a class which inherits from another class. An override function ―replaces‖ a function inherited from the base class, but does so in such a way that it is called even when an instance of its class is pretending to be a different type through polymorphism. That probably was a little over the top. The code snippet below should explain things better. public class Car { public static void main (String [] args) { Car a = new Car(); Car b = new Ferrari(); //Car ref, but a Ferrari object
  • 10. a.start(); // Runs the Car version of start() b.start(); // Runs the Ferrari version of start() } } class Car { public void start() { System.out.println("This is a Generic start to any Car"); } }class Ferrari extends Car { public void start() { System.out.println("Let‘s start the Ferrari and go out for a cool Party.");} } Over-Loading: Overloading is the action of defining multiple methods with the same name, but with different parameters. It is unrelated to either overriding or polymorphism. Functions in Java could be overloaded by two mechanisms ideally:  Varying the number of arguments.  Varying the Data Type. class CalculateArea{ void Area(int length){System.out.println(length*2);}
  • 11. void Area(int length , int width){System.out.println(length*width);} public static void main(String args[]){ CalculateArea obj=new CalculateArea(); obj.Area(10); // Area of a Square obj.Area(20,20); // Area of a Rectangle } } 17. What is Constructors, Constructor Overloading in Java and Copy- Constructor? Constructors form the basics of OOPs, for starters. Constructor: The sole purpose of having Constructors is to create an instance of a class. They are invoked while creating an object of a class. Here are a few salient features of Java Constructors:  Constructors can be public, private, or protected.  If a constructor with arguments has been defined in a class, you can no longer use a default no-argument constructor – you have to write one.  They are called only once when the class is being instantiated.  They must have the same name as the class itself.  They do not return a value and you do not have to specify the keyword void.  If you do not create a constructor for the class, Java helps you by using a so called default no-argument constructor.
  • 12. public class Boss{ String name; Boss(String input) { //This is the constructor name = "Our Boss is also known as : " + input; } public static void main(String args[]) { Boss p1 = new Boss("Super-Man"); } } Constructor overloading: passing different number and type of variables as arguments all of which are private variables of the class. Example snippet could be as follows: public class Boss{ String name; Boss(String input) { //This is the constructor name = "Our Boss is also known as : " + input; } Boss() { name = "Our Boss is a nice man. We don‘t call him names.‖;
  • 13. } public static void main(String args[]) { Boss p1 = new Boss("Super-Man"); Boss p2 = new Boss(); } } Copy Constructor: A copy constructor is a type of constructor which constructs the object of the class from another object of the same class. The copy constructor accepts a reference to its own class as a parameter. 18. What is Java Exception Handling? What is the difference between Errors, Unchecked Exception and Checked Exception? Anything that‘s not Normal is an exception. Exceptions are the customary way in Java to indicate to a calling method that an abnormal condition has occurred. In Java, exceptions are objects. When you throw an exception, you throw an object. You can‘t throw just any object as an exception, however — only those object whose classes descend from Throwable. Throwable serves as the base class for an entire family of classes, declared in java.lang, that your program can instantiate and throw. Here‘s a hierarchical Exception class structure:  An Unchecked Exception inherits from RuntimeException (which extends from Exception). The JVM treats RuntimeException differently as there is no requirement for the application-code to deal with them explicitly.  A Checked Exception inherits from the Exception-class. The client code has to handle the checked exceptions either in a try-catch
  • 14. clause or has to be thrown for the Super class to catch the same. A Checked Exception thrown by a lower class (sub-class) enforces a contract on the invoking class (super-class) to catch or throw it.  Errors (members of the Error family) are usually thrown for more serious problems, such as OutOfMemoryError (OOM), that may not be so easy to handle. Exception handling needs special attention while designing large applications. So we would suggest you to spend some time brushing up your Java skills. 19. What is the difference between Throw and Throws in Java Exception Handling? Throws: A throws clause lists the types of exceptions that a method might throw, thereby warning the invoking method – ‗Dude. You need to handle this list of exceptions I might throw.‘ Except those of type Error or RuntimeException, all other Exceptions or any of their subclasses, must be declared in the throws clause, if the method in question doesn‘t implement a try…catch block. It is therefore the onus of the next-on-top method to take care of the mess. public void myMethod() throws PRException {..} This means the super function calling the function should be equipped to handle this exception. public void Callee() { try{ myMethod();
  • 15. }catch(PRException ex) { ...handle Exception....} } Using the Throw: If the user wants to throw an explicit Exception, often customized, we use the Throw. The Throw clause can be used in any part of code where you feel a specific exception needs to be thrown to the calling method. try{ if(age>100){throw new AgeBarException(); //Customized ExceptioN }else{ ....} } }catch(AgeBarException ex){ ...handle Exception..... } 20. What is the Difference between Byte stream and Character streams? Every Java Programmer deals with File Operations. To generate User reports, send attachments through mails and spill out data files from Java programs. And a sound knowledge on File Operation becomes even more important while dealing with Java questions.
  • 16. Byte stream: For reading and writing binary data, byte stream is incorporated. Programs use byte streams to perform byte input and output.  Performing InputStream operations or OutputStream operations means generally having a loop that reads the input stream and writes the output stream one byte at a time.  You can use buffered I/O streams for an overhead reduction (overhead generated by each such request often triggers disk access, network activity, or some other operation that is relatively expensive). Character streams: Character streams work with the characters rather than the byte. In Java, characters are stored by following the Unicode (allows a unique number for every character) conventions. In such kind of storage, characters become the platform independent, program independent, language independent.
  • 17. Study on the go; get high quality complete preparation courses now on your mobile!