0% found this document useful (0 votes)
3 views11 pages

Java Tricky Question

These are the tricky questions about java which asked in the placement interviews...

Uploaded by

aggarwalishu263
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
0% found this document useful (0 votes)
3 views11 pages

Java Tricky Question

These are the tricky questions about java which asked in the placement interviews...

Uploaded by

aggarwalishu263
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF or read online on Scribd
mee ava Thi 8 } 1 | i @ © iu ‘essential tals end lbraries the pplication needs But, there's coo! fol called Tlnk in newer Tova versions from Java 9 that lets us bundle our Sava eppliation with its Kite version of the JRE, and alse with Graal me can build @ native Image thot doesn't need @ JRE to run Is it possible to have the JDK installed without having the JRE? No, the JDK contains the JRE. 11's impossible to have @ JDK without ¢ JRE, os it contains essential components for runing Tave aplication, which the JDK also uses for development. Can you tell me what algorithm JVM uses for garbage collection? VW uses multiple garbage collection algerthms such as Mark-Sweep, Mark-Compoct, ard Generational Copying, depending on the colector chosen How can memory leaks occur in Java even if we have automatic garbage collection? Memory leaks in Jove occur when objects are no longer needed but still referenced from other reachable objects, ond hence preventing the garbage colector from reclaiming their memery. Is java a 100% object-oriented programming language? No, Teva isnot considered 100% object-oriented because it uses primitive types (lke int, char, te.) that are not objects. In a fully object-oriented language, everything Is treated es an object. What are the advantages of Java being partially object-oriented? 1) Using simple, non-object types lke integers and boolens helps Tava run faster and use less memory 2) The mix of features ellos eve to work well wth ether technologies and systems, which might rot be fully object-oriented What is the use of object-oriented programming languages in the enterprise projects? (Object-oriented pragramming (OOP) is used in big projects to make ceding easier to handle. helps organize code better, mkes it ecsier to update and scale, ond lets programmers reuse Explain public static void main(string args[])? In Jove, publc stati veid main(String ergs) is the entry point of any standalone Tava pplication public makes this method accessible from onywhere, static meons X don't need ‘tp ereate an object to call this method, void means it doesn't return ony vale, and main is the ame of this method. ‘The String] args pert isan array that holds any command-line arguments passed to the program. ‘$0, when I run a Jeva program, this is the first methed that gets called What will happen if we don't declare the main as static? TT dent declare the main method es static in @ Jove program, the JVM won't be able to launch ‘our pplication Can we override the main method? No, we camot override the main methed of Jave becouse a stetic methad comot be overidéen “The static method in Java Is associated with a clos wheres the ran-statie method is aseciated with an abject. Static belongs te the class area, state metheds don't need on abject tobe elle Can we overload the main method? Yes, We can overload the main method in Java by Just changing its argument. But JVM only calls the orignal main method, it will never cell cur overcaded main methed, Can primitive data types be NULL ? No, primitive data types in Tova cannot be null. They have default velues (¢.9., 0 forint, flse for boolean, 0.0 fer double) ond must cvays have ¢ value. Can we declare pointer in java ? No, Jom eoestprofde the sport of Pome, As Jove needed to be more sere because of hich the feature ofthe printer i not provided in ave Why we use wrapper class in collections ecause ArrayList, HashMap, and ethers inthe Java Collections Framework, can only held objects ‘and not primitive types. Wrapper classes allow primitive vales to be treated es cbjects, encling ‘them fo be stored end managed within these colections. ‘Examples of wrapper classes are Integer, Boolean, Double ete ‘Astobexing automatically converts primitive type (Ike Int) to Its corresponding wrapper class (integer). Unboxing does the reverse, converting an Integer back t0 on it ‘When comparing two Integer instances using ==, autobexng might lead to false results becouse it compores object references, not valies. ‘A NulbointerException can occur if you unbox a ull object; fer example, assigning rll to an “Integer and then using it in a context where an int ie expected, Tt will not be beneficial when there is many unique strings because it will be complex situate to check each string. ‘A scenario where StringBuffer is more epproprate than String is in ¢ multi-threeded server plication where multiple threads modify a shared string, such as constructing a complex log ‘entry concurrently from different thread. “They help in organizing code Packages prevent naming conflicts by providing @ unique namespace Packages support modulrity by ellowing developers to seperate the program ‘Organizing classes into packages mekes it easier to locate related class pene Using getters and setters instead of public variables allows us to control how values ere set ond ‘accessed, add validation, and keep the obility to change how data is stored without affecting i i i i [No, a top-level class cannot be private or protected becouse it restricts access, making it ‘unusable from any other classes, contrary to the purpose of a top-level class. Yes, a class in Jove can be declared without any methods or fields, Such cess can sil be used to create objects, clthough these objects would have ro specific behavior or state Ln order to make @ singleton class, first we hove at make a constructor as private, next we have to create a private static Instone of the cless and finally we have to provide e sttie ‘method instance so that's haw we con erecte the singleton clase ‘Singleton classes are not threed-safe by defoult. If multiple threads try to create an instance at ‘the sane tine, it cold result in multiple istonces, To prevent this, we con synchronize the ‘method that cretes the nstence or use a static iii Yes, we con use private constructors in Java, They are mostly used in lasses that provide sete methods or contain ony sete fields, A commen se isn the Singleton design pattern, where the goa sf int the class ro ey one abject. Yes, yu can have multiple constractrs ina Tae cess, each wth « fferet set of parameters “his lets you reste objects in various ways depending on whet inforetion yeu hve et the tine. ‘These re useful in concurrent programming because they can be shared between threads without needing syncronization How can we create immutable class? Declare the class as final so it cant be extended ‘Moke all of the fields final and private so that direct access is not allowed, Don't provide setter methods for variables Initialize all fields using 0 constructor method Can a class extends on its own? No, a class in Java cannot extend itself. If it tries, it will couse on error Why multiple inheritance is not possible in java? SS TT porent cee have methods thet cone, How does method overloading relate to polymorphism? Method overloading ie using the some methid rome with cifferent inputs in the came clase, 11's a simple wey 1 use pelymerphisn when you'r writing your code What is dynamic method dispatch in Java? Dynamic method dispatch is @ way Jove decides which method Yo se at runtime when metheds ere coveridden in sbclazces It ensures the correct method Ie used bated on the type ef abject. Can constructors be polymorphic? No, conatructors cant be pelorphic. We can have many constructors in class with efferent Inputs, but they don't behave differently based onthe object tpe like methods do, Can you provide examples of where abstraction is effectively used in Java libraries? Tova es ston We Siti tle Po engl When YN WEG Lt YY dW lew hot tres dete, whether a on Aro ore Une What happens if a class includes an abstract method? ‘A clase with on ebstract method must itself be abstract. We cant eeate ebjects directly from on ebstract class it's meant to be © bluprint for other cores How does abstraction help in achieving loose coupling in software ‘Abstraction lets us hide complex details and only show whet's neceatery. This kes it easier to chang ports of your program without affecting others, Keeping diferent parts independent and ester to manoge. Use on interface when we want fo lst the methads a class shad have, without dealing how they work. Use class extension when we want new cats fo inherit features and behaviors from on sits clone ard oon ity tha rectly, but we con use interfaces for @ In Sova, we con't inherit features from multiple classes simian effect A class con fellow the guidelines ef many interfaces et once, which lets it combine ‘many sts of copies. | Yes, interfaces in Java con have static methods, which you con use without creating an instance ofthe class. Encapedation keeps important data hidden and safe. Tt only lets certain port of ur program use ‘this dote, which helps prevent mistakes ond keeps the data secure from unwanted changes When we call an overleded method, the Jave compiler looks et the umber end type of arguments 3 i i } i i z i g In Jove, we comot overiead methods st by changing thet retum ‘ype, The methods must afer by the perameters for overleadng tobe valid ‘The poremeters must difer In how many there re, what type they are or the erder they are in {In Jove, method overriding occurs when o subclass has a method with the same name, retirn ‘the perent class when called ? i 4 | i a i superclass. 11's useful becuse it helps find mistokes if the method doesnot actully override en existing methed from the parent cas. 1 cifferen subcleses override the same method from a superciss, each subclass wil hove it i a f { i i : i i i i i i z i i i compton error occurs. The "super" keyword isenly applicable within subelases to refer to members of the i No, the this ond super keyword comot be uted in sate methede. Static methods belang to the loss, not intences, and super refers to the sipercass's object context, which does net exist in 4 static contest 1 Jove, the super keyword lets a subclass use methods from its paren class, helping it behave in ferent weys end thet i nething but a polmerphie behevor Yes, static black can throw an exception, but if it does, the exception must be handled within ‘the block itself or declared using a throws clause in the class. Ne, stare methods camot be overridden in Jove because method overriding Is besed on dynamic boning at runtine end state methods are bound et comple te. Prior to Tova 8, yes, we can print something without main methed buts its rot pesible from Jove i Common ute cases for using finel variables in Teva pregronming incide defining constants, perameters passed to methods, ond local variables in lanbdes or anonymous ier clases. “The “final keyword contributes te immutability and thread safety in Java by enring that the value of @ verisble carnet be changed once assigned, preverting unintended medifications and potentil concurrency issues, [No, as functional interface lows to have only single abstrect method, However functional Interface can inherit another iterface If it contains only static and default methods in it ‘Arrays sort) ses a Bul-Pivot Cuicksort algorithm for primitive types end TimSort for object erreys. Collections. sort) uses TinSert, @ hybrid sorting egcithen combining merge sect and i A TreeSet ie more appropriate than @ HashSet when you ned to maintain the elements in @ “orted onder, For example, if we are managing alist of customer names thet must be depleyed ranting liked lst oro elanced tree depend upon the Java version in each bucket {Hf two keys have the same hash cede, they end wp in the some bucket inthe HashMap, The keys re then linked together in lit inside thot bucket to manage them Before Jove 8, HashMap declt with colisions by using ¢ simple linked lst. Strtng from Jove 8, when too may tema end pn the same bucat, the et tot inte bulanced fre, which helps sped up searching. Cencrentosiay boosts pertomorce in muli-tireoded zeta by letting tterer tress, cess ond notify diferent ports of the map sraitereusy, recy wating tes ord ingrovig ley i A il li : ij i H i | ‘The Singleton pattern is commenly used to manage detabase conection, ensuring a single shored canmction atone ie reuted efficiently. Use syhronized blecks er methods to ensure thet ely one thread can eecess the date structure te time, preventing concurrent mdificton issues. No, a thread in Jove cant be started more then one. Attempting fo resart a tread that hot _deeady run wil row an TlegelThveadStateEacetin. Yes, you con create © server in « Jeve oplctin using ony Tove SE APES, such os by utizing Logo ke Teno bara me beli hui herckehic bahar USipe mai Krishna avn ty meni Radha Rani lagi Kash 020 Kahani puri hot Ain yon woh hei Hain! -2 to tu adhuni nahi puri meri hot Kahani paoni Hat ,-to usme mai Shiv aun 0 pave a ad at parece aus 88 Giles,

You might also like